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 use rustc_data_structures::indexed_vec::Idx;
15 use hair::cx::to_ref::ToRef;
16 use hair::util::UserAnnotatedTyHelpers;
17 use rustc::hir::def::{Def, CtorKind};
18 use rustc::mir::interpret::GlobalId;
19 use rustc::ty::{self, AdtKind, Ty};
20 use rustc::ty::adjustment::{Adjustment, Adjust, AutoBorrow, AutoBorrowMutability};
21 use rustc::ty::cast::CastKind as TyCastKind;
23 use rustc::hir::def_id::LocalDefId;
24 use rustc::mir::{BorrowKind};
27 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr {
28 type Output = Expr<'tcx>;
30 fn make_mirror<'a, 'gcx>(self, cx: &mut Cx<'a, 'gcx, 'tcx>) -> Expr<'tcx> {
31 let temp_lifetime = cx.region_scope_tree.temporary_scope(self.hir_id.local_id);
32 let expr_scope = region::Scope {
33 id: self.hir_id.local_id,
34 data: region::ScopeData::Node
37 debug!("Expr::make_mirror(): id={}, span={:?}", self.id, self.span);
39 let mut expr = make_mirror_unadjusted(cx, self);
41 // Now apply adjustments, if any.
42 for adjustment in cx.tables().expr_adjustments(self) {
43 debug!("make_mirror: expr={:?} applying adjustment={:?}",
46 expr = apply_adjustment(cx, self, expr, adjustment);
49 // Next, wrap this up in the expr's scope.
54 kind: ExprKind::Scope {
55 region_scope: expr_scope,
57 lint_level: cx.lint_level_of(self.id),
61 // Finally, create a destruction scope, if any.
62 if let Some(region_scope) =
63 cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id) {
68 kind: ExprKind::Scope {
71 lint_level: LintLevel::Inherited,
81 fn apply_adjustment<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
82 hir_expr: &'tcx hir::Expr,
84 adjustment: &Adjustment<'tcx>)
86 let Expr { temp_lifetime, mut span, .. } = expr;
87 let kind = match adjustment.kind {
88 Adjust::ReifyFnPointer => {
89 ExprKind::ReifyFnPointer { source: expr.to_ref() }
91 Adjust::UnsafeFnPointer => {
92 ExprKind::UnsafeFnPointer { source: expr.to_ref() }
94 Adjust::ClosureFnPointer => {
95 ExprKind::ClosureFnPointer { source: expr.to_ref() }
97 Adjust::NeverToAny => {
98 ExprKind::NeverToAny { source: expr.to_ref() }
100 Adjust::MutToConstPointer => {
101 ExprKind::Cast { source: expr.to_ref() }
103 Adjust::Deref(None) => {
104 // Adjust the span from the block, to the last expression of the
105 // block. This is a better span when returning a mutable reference
106 // with too short a lifetime. The error message will use the span
107 // from the assignment to the return place, which should only point
108 // at the returned value, not the entire function body.
110 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
112 // // ^ error message points at this expression.
115 // We don't need to do this adjustment in the next match arm since
116 // deref coercions always start with a built-in deref.
117 if let ExprKind::Block { body } = expr.kind {
118 if let Some(ref last_expr) = body.expr {
119 span = last_expr.span;
123 ExprKind::Deref { arg: expr.to_ref() }
125 Adjust::Deref(Some(deref)) => {
126 let call = deref.method_call(cx.tcx(), expr.ty);
130 ty: cx.tcx.mk_ref(deref.region,
136 kind: ExprKind::Borrow {
137 region: deref.region,
138 borrow_kind: deref.mutbl.to_borrow_kind(),
143 overloaded_place(cx, hir_expr, adjustment.target, Some(call), vec![expr.to_ref()])
145 Adjust::Borrow(AutoBorrow::Ref(r, m)) => {
148 borrow_kind: m.to_borrow_kind(),
152 Adjust::Borrow(AutoBorrow::RawPtr(m)) => {
153 // Convert this to a suitable `&foo` and
154 // then an unsafe coercion. Limit the region to be just this
156 let region = ty::ReScope(region::Scope {
157 id: hir_expr.hir_id.local_id,
158 data: region::ScopeData::Node
160 let region = cx.tcx.mk_region(region);
163 ty: cx.tcx.mk_ref(region,
169 kind: ExprKind::Borrow {
171 borrow_kind: m.to_borrow_kind(),
175 let cast_expr = Expr {
177 ty: adjustment.target,
179 kind: ExprKind::Cast { source: expr.to_ref() }
182 // To ensure that both implicit and explicit coercions are
183 // handled the same way, we insert an extra layer of indirection here.
184 // For explicit casts (e.g. 'foo as *const T'), the source of the 'Use'
185 // will be an ExprKind::Hair with the appropriate cast expression. Here,
186 // we make our Use source the generated Cast from the original coercion.
188 // In both cases, this outer 'Use' ensures that the inner 'Cast' is handled by
189 // as_operand, not by as_rvalue - causing the cast result to be stored in a temporary.
190 // Ordinary, this is identical to using the cast directly as an rvalue. However, if the
191 // source of the cast was previously borrowed as mutable, storing the cast in a
192 // temporary gives the source a chance to expire before the cast is used. For
193 // structs with a self-referential *mut ptr, this allows assignment to work as
196 // For example, consider the type 'struct Foo { field: *mut Foo }',
197 // The method 'fn bar(&mut self) { self.field = self }'
198 // triggers a coercion from '&mut self' to '*mut self'. In order
199 // for the assignment to be valid, the implicit borrow
200 // of 'self' involved in the coercion needs to end before the local
201 // containing the '*mut T' is assigned to 'self.field' - otherwise,
202 // we end up trying to assign to 'self.field' while we have another mutable borrow
205 // We only need to worry about this kind of thing for coercions from refs to ptrs,
206 // since they get rid of a borrow implicitly.
207 ExprKind::Use { source: cast_expr.to_ref() }
210 // See the above comment for Adjust::Deref
211 if let ExprKind::Block { body } = expr.kind {
212 if let Some(ref last_expr) = body.expr {
213 span = last_expr.span;
217 ExprKind::Unsize { source: expr.to_ref() }
223 ty: adjustment.target,
229 fn make_mirror_unadjusted<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
230 expr: &'tcx hir::Expr)
232 let expr_ty = cx.tables().expr_ty(expr);
233 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
235 let kind = match expr.node {
236 // Here comes the interesting stuff:
237 hir::ExprKind::MethodCall(_, method_span, ref args) => {
238 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
239 let expr = method_callee(cx, expr, method_span,None);
240 let args = args.iter()
251 hir::ExprKind::Call(ref fun, ref args) => {
252 if cx.tables().is_method_call(expr) {
253 // The callee is something implementing Fn, FnMut, or FnOnce.
254 // Find the actual method implementation being called and
255 // build the appropriate UFCS call expression with the
256 // callee-object as expr parameter.
258 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
260 let method = method_callee(cx, expr, fun.span,None);
262 let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e));
263 let tupled_args = Expr {
264 ty: cx.tcx.mk_tup(arg_tys),
267 kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
272 fun: method.to_ref(),
273 args: vec![fun.to_ref(), tupled_args.to_ref()],
277 let adt_data = if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) =
280 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
281 expr_ty.ty_adt_def().and_then(|adt_def| {
283 Def::VariantCtor(variant_id, CtorKind::Fn) => {
284 Some((adt_def, adt_def.variant_index_with_id(variant_id)))
286 Def::StructCtor(_, CtorKind::Fn) |
287 Def::SelfCtor(..) => Some((adt_def, 0)),
294 if let Some((adt_def, index)) = adt_data {
295 let substs = cx.tables().node_substs(fun.hir_id);
297 let user_ty = cx.tables().user_substs(fun.hir_id)
298 .map(|user_substs| UserTypeAnnotation::TypeOf(adt_def.did, user_substs));
300 let field_refs = args.iter()
304 name: Field::new(idx),
312 variant_index: index,
319 ty: cx.tables().node_id_to_type(fun.hir_id),
328 hir::ExprKind::AddrOf(mutbl, ref expr) => {
329 let region = match expr_ty.sty {
330 ty::Ref(r, _, _) => r,
331 _ => span_bug!(expr.span, "type of & not region"),
335 borrow_kind: mutbl.to_borrow_kind(),
340 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
342 hir::ExprKind::Assign(ref lhs, ref rhs) => {
349 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
350 if cx.tables().is_method_call(expr) {
351 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
361 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
362 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
366 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
367 if cx.tables().is_method_call(expr) {
368 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
371 match (op.node, cx.constness) {
372 // FIXME(eddyb) use logical ops in constants when
373 // they can handle that kind of control-flow.
374 (hir::BinOpKind::And, hir::Constness::Const) => {
381 (hir::BinOpKind::Or, hir::Constness::Const) => {
389 (hir::BinOpKind::And, hir::Constness::NotConst) => {
390 ExprKind::LogicalOp {
396 (hir::BinOpKind::Or, hir::Constness::NotConst) => {
397 ExprKind::LogicalOp {
405 let op = bin_op(op.node);
416 hir::ExprKind::Index(ref lhs, ref index) => {
417 if cx.tables().is_method_call(expr) {
418 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
422 index: index.to_ref(),
427 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
428 if cx.tables().is_method_call(expr) {
429 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
431 ExprKind::Deref { arg: arg.to_ref() }
435 hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
436 if cx.tables().is_method_call(expr) {
437 overloaded_operator(cx, expr, vec![arg.to_ref()])
446 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
447 if cx.tables().is_method_call(expr) {
448 overloaded_operator(cx, expr, vec![arg.to_ref()])
450 if let hir::ExprKind::Lit(ref lit) = arg.node {
452 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
464 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
466 ty::Adt(adt, substs) => {
467 match adt.adt_kind() {
468 AdtKind::Struct | AdtKind::Union => {
473 user_ty: cx.user_substs_applied_to_adt(expr.hir_id, adt),
474 fields: field_refs(cx, fields),
475 base: base.as_ref().map(|base| {
478 field_types: cx.tables()
479 .fru_field_types()[expr.hir_id]
486 let def = match *qpath {
487 hir::QPath::Resolved(_, ref path) => path.def,
488 hir::QPath::TypeRelative(..) => Def::Err,
491 Def::Variant(variant_id) => {
492 assert!(base.is_none());
494 let index = adt.variant_index_with_id(variant_id);
497 variant_index: index,
499 user_ty: cx.user_substs_applied_to_adt(expr.hir_id, adt),
500 fields: field_refs(cx, fields),
505 span_bug!(expr.span, "unexpected def: {:?}", def);
513 "unexpected type for struct literal: {:?}",
519 hir::ExprKind::Closure(..) => {
520 let closure_ty = cx.tables().expr_ty(expr);
521 let (def_id, substs, movability) = match closure_ty.sty {
522 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
523 ty::Generator(def_id, substs, movability) => {
524 (def_id, UpvarSubsts::Generator(substs), Some(movability))
527 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
530 let upvars = cx.tcx.with_freevars(expr.id, |freevars| {
532 .zip(substs.upvar_tys(def_id, cx.tcx))
533 .map(|(fv, ty)| capture_freevar(cx, expr, fv, ty))
544 hir::ExprKind::Path(ref qpath) => {
545 let def = cx.tables().qpath_def(qpath, expr.hir_id);
546 convert_path_expr(cx, expr, def)
549 hir::ExprKind::InlineAsm(ref asm, ref outputs, ref inputs) => {
550 ExprKind::InlineAsm {
552 outputs: outputs.to_ref(),
553 inputs: inputs.to_ref(),
557 // Now comes the rote stuff:
558 hir::ExprKind::Repeat(ref v, ref count) => {
559 let def_id = cx.tcx.hir.local_def_id(count.id);
560 let substs = Substs::identity_for_item(cx.tcx.global_tcx(), def_id);
561 let instance = ty::Instance::resolve(
567 let global_id = GlobalId {
571 let span = cx.tcx.def_span(def_id);
572 let count = match cx.tcx.at(span).const_eval(cx.param_env.and(global_id)) {
573 Ok(cv) => cv.unwrap_usize(cx.tcx),
575 e.report_as_error(cx.tcx.at(span), "could not evaluate array length");
585 hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
586 hir::ExprKind::Break(dest, ref value) => {
587 match dest.target_id {
588 Ok(target_id) => ExprKind::Break {
589 label: region::Scope {
590 id: cx.tcx.hir.node_to_hir_id(target_id).local_id,
591 data: region::ScopeData::Node
593 value: value.to_ref(),
595 Err(err) => bug!("invalid loop id for break: {}", err)
598 hir::ExprKind::Continue(dest) => {
599 match dest.target_id {
600 Ok(loop_id) => ExprKind::Continue {
601 label: region::Scope {
602 id: cx.tcx.hir.node_to_hir_id(loop_id).local_id,
603 data: region::ScopeData::Node
606 Err(err) => bug!("invalid loop id for continue: {}", err)
609 hir::ExprKind::Match(ref discr, ref arms, _) => {
611 discriminant: discr.to_ref(),
612 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
615 hir::ExprKind::If(ref cond, ref then, ref otherwise) => {
617 condition: cond.to_ref(),
619 otherwise: otherwise.to_ref(),
622 hir::ExprKind::While(ref cond, ref body, _) => {
624 condition: Some(cond.to_ref()),
625 body: block::to_expr_ref(cx, body),
628 hir::ExprKind::Loop(ref body, _, _) => {
631 body: block::to_expr_ref(cx, body),
634 hir::ExprKind::Field(ref source, ..) => {
636 lhs: source.to_ref(),
637 name: Field::new(cx.tcx.field_index(expr.id, cx.tables)),
640 hir::ExprKind::Cast(ref source, ref cast_ty) => {
641 // Check for a user-given type annotation on this `cast`
642 let user_ty = cx.tables.user_provided_tys().get(cast_ty.hir_id)
643 .map(|&t| UserTypeAnnotation::Ty(t));
646 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
652 // Check to see if this cast is a "coercion cast", where the cast is actually done
653 // using a coercion (or is a no-op).
654 let cast = if let Some(&TyCastKind::CoercionCast) =
659 // Convert the lexpr to a vexpr.
660 ExprKind::Use { source: source.to_ref() }
662 // check whether this is casting an enum variant discriminant
663 // to prevent cycles, we refer to the discriminant initializer
664 // which is always an integer and thus doesn't need to know the
665 // enum's layout (or its tag type) to compute it during const eval
669 // B = A as isize + 4,
671 // The correct solution would be to add symbolic computations to miri,
672 // so we wouldn't have to compute and store the actual value
673 let var = if let hir::ExprKind::Path(ref qpath) = source.node {
674 let def = cx.tables().qpath_def(qpath, source.hir_id);
677 .node_id_to_type(source.hir_id)
679 .and_then(|adt_def| {
681 Def::VariantCtor(variant_id, CtorKind::Const) => {
682 let idx = adt_def.variant_index_with_id(variant_id);
683 let (d, o) = adt_def.discriminant_def_for_variant(idx);
684 use rustc::ty::util::IntTypeExt;
685 let ty = adt_def.repr.discr_type();
686 let ty = ty.to_ty(cx.tcx());
696 let source = if let Some((did, offset, var_ty)) = var {
697 let mk_const = |literal| Expr {
701 kind: ExprKind::Literal { literal, user_ty: None },
703 let offset = mk_const(ty::Const::from_bits(
706 cx.param_env.and(var_ty),
710 // in case we are offsetting from a computed discriminant
711 // and not the beginning of discriminants (which is always `0`)
712 let substs = Substs::identity_for_item(cx.tcx(), did);
713 let lhs = mk_const(ty::Const::unevaluated(
719 let bin = ExprKind::Binary {
737 ExprKind::Cast { source }
740 if let Some(user_ty) = user_ty {
741 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
742 // inefficient, revisit this when performance becomes an issue.
743 let cast_expr = Expr {
750 ExprKind::ValueTypeAscription {
751 source: cast_expr.to_ref(),
752 user_ty: Some(user_ty),
758 hir::ExprKind::Type(ref source, ref ty) => {
759 let user_provided_tys = cx.tables.user_provided_tys();
760 let user_ty = user_provided_tys
762 .map(|&c_ty| UserTypeAnnotation::Ty(c_ty));
763 if source.is_place_expr() {
764 ExprKind::PlaceTypeAscription {
765 source: source.to_ref(),
769 ExprKind::ValueTypeAscription {
770 source: source.to_ref(),
775 hir::ExprKind::Box(ref value) => {
777 value: value.to_ref(),
780 hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
781 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
783 hir::ExprKind::Yield(ref v) => ExprKind::Yield { value: v.to_ref() },
794 fn user_substs_applied_to_def(
795 cx: &mut Cx<'a, 'gcx, 'tcx>,
798 ) -> Option<UserTypeAnnotation<'tcx>> {
800 // A reference to something callable -- e.g., a fn, method, or
801 // a tuple-struct or tuple-variant. This has the type of a
802 // `Fn` but with the user-given substitutions.
805 Def::StructCtor(_, CtorKind::Fn) |
806 Def::VariantCtor(_, CtorKind::Fn) |
808 Def::AssociatedConst(_) =>
809 Some(UserTypeAnnotation::TypeOf(def.def_id(), cx.tables().user_substs(hir_id)?)),
811 // A unit struct/variant which is used as a value (e.g.,
812 // `None`). This has the type of the enum/struct that defines
813 // this variant -- but with the substitutions given by the
815 Def::StructCtor(_def_id, CtorKind::Const) |
816 Def::VariantCtor(_def_id, CtorKind::Const) =>
817 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
819 // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
821 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
824 bug!("user_substs_applied_to_def: unexpected def {:?} at {:?}", def, hir_id)
828 fn method_callee<'a, 'gcx, 'tcx>(
829 cx: &mut Cx<'a, 'gcx, 'tcx>,
832 overloaded_callee: Option<(DefId, &'tcx Substs<'tcx>)>,
834 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
835 let (def_id, substs, user_ty) = match overloaded_callee {
836 Some((def_id, substs)) => (def_id, substs, None),
838 let type_dependent_defs = cx.tables().type_dependent_defs();
839 let def = type_dependent_defs
842 span_bug!(expr.span, "no type-dependent def for method callee")
844 let user_ty = user_substs_applied_to_def(cx, expr.hir_id, def);
845 (def.def_id(), cx.tables().node_substs(expr.hir_id), user_ty)
848 let ty = cx.tcx().mk_fn_def(def_id, substs);
853 kind: ExprKind::Literal {
854 literal: ty::Const::zero_sized(cx.tcx(), ty),
860 trait ToBorrowKind { fn to_borrow_kind(&self) -> BorrowKind; }
862 impl ToBorrowKind for AutoBorrowMutability {
863 fn to_borrow_kind(&self) -> BorrowKind {
864 use rustc::ty::adjustment::AllowTwoPhase;
866 AutoBorrowMutability::Mutable { allow_two_phase_borrow } =>
867 BorrowKind::Mut { allow_two_phase_borrow: match allow_two_phase_borrow {
868 AllowTwoPhase::Yes => true,
869 AllowTwoPhase::No => false
871 AutoBorrowMutability::Immutable =>
877 impl ToBorrowKind for hir::Mutability {
878 fn to_borrow_kind(&self) -> BorrowKind {
880 hir::MutMutable => BorrowKind::Mut { allow_two_phase_borrow: false },
881 hir::MutImmutable => BorrowKind::Shared,
886 fn convert_arm<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx> {
888 patterns: arm.pats.iter().map(|p| cx.pattern_from_hir(p)).collect(),
889 guard: match arm.guard {
890 Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
893 body: arm.body.to_ref(),
895 lint_level: LintLevel::Inherited,
899 fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
900 expr: &'tcx hir::Expr,
903 let substs = cx.tables().node_substs(expr.hir_id);
905 // A regular function, constructor function or a constant.
908 Def::StructCtor(_, CtorKind::Fn) |
909 Def::VariantCtor(_, CtorKind::Fn) |
910 Def::SelfCtor(..) => {
911 let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
913 literal: ty::Const::zero_sized(
915 cx.tables().node_id_to_type(expr.hir_id),
922 Def::AssociatedConst(def_id) => {
923 let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
925 literal: ty::Const::unevaluated(
929 cx.tables().node_id_to_type(expr.hir_id),
935 Def::StructCtor(def_id, CtorKind::Const) |
936 Def::VariantCtor(def_id, CtorKind::Const) => {
937 match cx.tables().node_id_to_type(expr.hir_id).sty {
938 // A unit struct/variant which is used as a value.
939 // We return a completely different ExprKind here to account for this special case.
940 ty::Adt(adt_def, substs) => {
943 variant_index: adt_def.variant_index_with_id(def_id),
945 user_ty: cx.user_substs_applied_to_adt(expr.hir_id, adt_def),
950 ref sty => bug!("unexpected sty: {:?}", sty),
954 Def::Static(node_id, _) => ExprKind::StaticRef { id: node_id },
956 Def::Local(..) | Def::Upvar(..) => convert_var(cx, expr, def),
958 _ => span_bug!(expr.span, "def `{:?}` not yet implemented", def),
962 fn convert_var<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
963 expr: &'tcx hir::Expr,
966 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
969 Def::Local(id) => ExprKind::VarRef { id },
971 Def::Upvar(var_id, index, closure_expr_id) => {
972 debug!("convert_var(upvar({:?}, {:?}, {:?}))",
976 let var_hir_id = cx.tcx.hir.node_to_hir_id(var_id);
977 let var_ty = cx.tables().node_id_to_type(var_hir_id);
979 // FIXME free regions in closures are not right
980 let closure_ty = cx.tables()
981 .node_id_to_type(cx.tcx.hir.node_to_hir_id(closure_expr_id));
983 // FIXME we're just hard-coding the idea that the
984 // signature will be &self or &mut self and hence will
985 // have a bound region with number 0
986 let closure_def_id = cx.tcx.hir.local_def_id(closure_expr_id);
987 let region = ty::ReFree(ty::FreeRegion {
988 scope: closure_def_id,
989 bound_region: ty::BoundRegion::BrAnon(0),
991 let region = cx.tcx.mk_region(region);
993 let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.sty {
994 match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() {
995 ty::ClosureKind::Fn => {
996 let ref_closure_ty = cx.tcx.mk_ref(region,
999 mutbl: hir::MutImmutable,
1003 temp_lifetime: temp_lifetime,
1005 kind: ExprKind::Deref {
1010 kind: ExprKind::SelfRef,
1016 ty::ClosureKind::FnMut => {
1017 let ref_closure_ty = cx.tcx.mk_ref(region,
1020 mutbl: hir::MutMutable,
1026 kind: ExprKind::Deref {
1031 kind: ExprKind::SelfRef,
1036 ty::ClosureKind::FnOnce => {
1041 kind: ExprKind::SelfRef,
1050 kind: ExprKind::SelfRef,
1054 // at this point we have `self.n`, which loads up the upvar
1055 let field_kind = ExprKind::Field {
1056 lhs: self_expr.to_ref(),
1057 name: Field::new(index),
1060 // ...but the upvar might be an `&T` or `&mut T` capture, at which
1061 // point we need an implicit deref
1062 let upvar_id = ty::UpvarId {
1064 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
1066 match cx.tables().upvar_capture(upvar_id) {
1067 ty::UpvarCapture::ByValue => field_kind,
1068 ty::UpvarCapture::ByRef(borrow) => {
1072 ty: cx.tcx.mk_ref(borrow.region,
1075 mutbl: borrow.kind.to_mutbl_lossy(),
1085 _ => span_bug!(expr.span, "type of & not region"),
1090 fn bin_op(op: hir::BinOpKind) -> BinOp {
1092 hir::BinOpKind::Add => BinOp::Add,
1093 hir::BinOpKind::Sub => BinOp::Sub,
1094 hir::BinOpKind::Mul => BinOp::Mul,
1095 hir::BinOpKind::Div => BinOp::Div,
1096 hir::BinOpKind::Rem => BinOp::Rem,
1097 hir::BinOpKind::BitXor => BinOp::BitXor,
1098 hir::BinOpKind::BitAnd => BinOp::BitAnd,
1099 hir::BinOpKind::BitOr => BinOp::BitOr,
1100 hir::BinOpKind::Shl => BinOp::Shl,
1101 hir::BinOpKind::Shr => BinOp::Shr,
1102 hir::BinOpKind::Eq => BinOp::Eq,
1103 hir::BinOpKind::Lt => BinOp::Lt,
1104 hir::BinOpKind::Le => BinOp::Le,
1105 hir::BinOpKind::Ne => BinOp::Ne,
1106 hir::BinOpKind::Ge => BinOp::Ge,
1107 hir::BinOpKind::Gt => BinOp::Gt,
1108 _ => bug!("no equivalent for ast binop {:?}", op),
1112 fn overloaded_operator<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1113 expr: &'tcx hir::Expr,
1114 args: Vec<ExprRef<'tcx>>)
1116 let fun = method_callee(cx, expr, expr.span, None);
1121 from_hir_call: false,
1125 fn overloaded_place<'a, 'gcx, 'tcx>(
1126 cx: &mut Cx<'a, 'gcx, 'tcx>,
1127 expr: &'tcx hir::Expr,
1129 overloaded_callee: Option<(DefId, &'tcx Substs<'tcx>)>,
1130 args: Vec<ExprRef<'tcx>>,
1131 ) -> ExprKind<'tcx> {
1132 // For an overloaded *x or x[y] expression of type T, the method
1133 // call returns an &T and we must add the deref so that the types
1134 // line up (this is because `*x` and `x[y]` represent places):
1136 let recv_ty = match args[0] {
1137 ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e),
1138 ExprRef::Mirror(ref e) => e.ty
1141 // Reconstruct the output assuming it's a reference with the
1142 // same region and mutability as the receiver. This holds for
1143 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1144 let (region, mutbl) = match recv_ty.sty {
1145 ty::Ref(region, _, mutbl) => (region, mutbl),
1146 _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
1148 let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut {
1153 // construct the complete expression `foo()` for the overloaded call,
1154 // which will yield the &T type
1155 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1156 let fun = method_callee(cx, expr, expr.span, overloaded_callee);
1157 let ref_expr = Expr {
1161 kind: ExprKind::Call {
1165 from_hir_call: false,
1169 // construct and return a deref wrapper `*foo()`
1170 ExprKind::Deref { arg: ref_expr.to_ref() }
1173 fn capture_freevar<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1174 closure_expr: &'tcx hir::Expr,
1175 freevar: &hir::Freevar,
1176 freevar_ty: Ty<'tcx>)
1178 let var_hir_id = cx.tcx.hir.node_to_hir_id(freevar.var_id());
1179 let upvar_id = ty::UpvarId {
1181 closure_expr_id: cx.tcx.hir.local_def_id(closure_expr.id).to_local(),
1183 let upvar_capture = cx.tables().upvar_capture(upvar_id);
1184 let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1185 let var_ty = cx.tables().node_id_to_type(var_hir_id);
1186 let captured_var = Expr {
1189 span: closure_expr.span,
1190 kind: convert_var(cx, closure_expr, freevar.def),
1192 match upvar_capture {
1193 ty::UpvarCapture::ByValue => captured_var.to_ref(),
1194 ty::UpvarCapture::ByRef(upvar_borrow) => {
1195 let borrow_kind = match upvar_borrow.kind {
1196 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1197 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1198 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }
1203 span: closure_expr.span,
1204 kind: ExprKind::Borrow {
1205 region: upvar_borrow.region,
1207 arg: captured_var.to_ref(),
1214 /// Converts a list of named fields (i.e. for struct-like struct/enum ADTs) into FieldExprRef.
1215 fn field_refs<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1216 fields: &'tcx [hir::Field])
1217 -> Vec<FieldExprRef<'tcx>> {
1221 name: Field::new(cx.tcx.field_index(field.id, cx.tables)),
1222 expr: field.expr.to_ref(),