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_index::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(self, cx: &mut Cx<'_, '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, 'tcx>(
72 cx: &mut Cx<'a, 'tcx>,
73 hir_expr: &'tcx hir::Expr,
75 adjustment: &Adjustment<'tcx>
77 let Expr { temp_lifetime, mut span, .. } = expr;
79 // Adjust the span from the block, to the last expression of the
80 // block. This is a better span when returning a mutable reference
81 // with too short a lifetime. The error message will use the span
82 // from the assignment to the return place, which should only point
83 // at the returned value, not the entire function body.
85 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
87 // // ^ error message points at this expression.
89 let mut adjust_span = |expr: &mut Expr<'tcx>| {
90 if let ExprKind::Block { body } = expr.kind {
91 if let Some(ref last_expr) = body.expr {
92 span = last_expr.span;
98 let kind = match adjustment.kind {
99 Adjust::Pointer(PointerCast::Unsize) => {
100 adjust_span(&mut expr);
101 ExprKind::Pointer { cast: PointerCast::Unsize, source: expr.to_ref() }
103 Adjust::Pointer(cast) => {
104 ExprKind::Pointer { cast, source: expr.to_ref() }
106 Adjust::NeverToAny => {
107 ExprKind::NeverToAny { source: expr.to_ref() }
109 Adjust::Deref(None) => {
110 adjust_span(&mut expr);
111 ExprKind::Deref { arg: expr.to_ref() }
113 Adjust::Deref(Some(deref)) => {
114 // We don't need to do call adjust_span here since
115 // deref coercions always start with a built-in deref.
116 let call = deref.method_call(cx.tcx(), expr.ty);
120 ty: cx.tcx.mk_ref(deref.region,
126 kind: ExprKind::Borrow {
127 borrow_kind: deref.mutbl.to_borrow_kind(),
132 overloaded_place(cx, hir_expr, adjustment.target, Some(call), vec![expr.to_ref()])
134 Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
136 borrow_kind: m.to_borrow_kind(),
140 Adjust::Borrow(AutoBorrow::RawPtr(m)) => {
141 // Convert this to a suitable `&foo` and
142 // then an unsafe coercion.
145 ty: cx.tcx.mk_ref(cx.tcx.lifetimes.re_erased,
151 kind: ExprKind::Borrow {
152 borrow_kind: m.to_borrow_kind(),
156 let cast_expr = Expr {
158 ty: adjustment.target,
160 kind: ExprKind::Cast { source: expr.to_ref() }
163 // To ensure that both implicit and explicit coercions are
164 // handled the same way, we insert an extra layer of indirection here.
165 // For explicit casts (e.g., 'foo as *const T'), the source of the 'Use'
166 // will be an ExprKind::Hair with the appropriate cast expression. Here,
167 // we make our Use source the generated Cast from the original coercion.
169 // In both cases, this outer 'Use' ensures that the inner 'Cast' is handled by
170 // as_operand, not by as_rvalue - causing the cast result to be stored in a temporary.
171 // Ordinary, this is identical to using the cast directly as an rvalue. However, if the
172 // source of the cast was previously borrowed as mutable, storing the cast in a
173 // temporary gives the source a chance to expire before the cast is used. For
174 // structs with a self-referential *mut ptr, this allows assignment to work as
177 // For example, consider the type 'struct Foo { field: *mut Foo }',
178 // The method 'fn bar(&mut self) { self.field = self }'
179 // triggers a coercion from '&mut self' to '*mut self'. In order
180 // for the assignment to be valid, the implicit borrow
181 // of 'self' involved in the coercion needs to end before the local
182 // containing the '*mut T' is assigned to 'self.field' - otherwise,
183 // we end up trying to assign to 'self.field' while we have another mutable borrow
186 // We only need to worry about this kind of thing for coercions from refs to ptrs,
187 // since they get rid of a borrow implicitly.
188 ExprKind::Use { source: cast_expr.to_ref() }
194 ty: adjustment.target,
200 fn make_mirror_unadjusted<'a, 'tcx>(
201 cx: &mut Cx<'a, 'tcx>,
202 expr: &'tcx hir::Expr,
204 let expr_ty = cx.tables().expr_ty(expr);
205 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
207 let kind = match expr.kind {
208 // Here comes the interesting stuff:
209 hir::ExprKind::MethodCall(_, method_span, ref args) => {
210 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
211 let expr = method_callee(cx, expr, method_span,None);
212 let args = args.iter()
223 hir::ExprKind::Call(ref fun, ref args) => {
224 if cx.tables().is_method_call(expr) {
225 // The callee is something implementing Fn, FnMut, or FnOnce.
226 // Find the actual method implementation being called and
227 // build the appropriate UFCS call expression with the
228 // callee-object as expr parameter.
230 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
232 let method = method_callee(cx, expr, fun.span,None);
234 let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e));
235 let tupled_args = Expr {
236 ty: cx.tcx.mk_tup(arg_tys),
239 kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
244 fun: method.to_ref(),
245 args: vec![fun.to_ref(), tupled_args.to_ref()],
249 let adt_data = if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) =
252 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
253 expr_ty.ty_adt_def().and_then(|adt_def| {
255 Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) =>
256 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id))),
257 Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
264 if let Some((adt_def, index)) = adt_data {
265 let substs = cx.tables().node_substs(fun.hir_id);
266 let user_provided_types = cx.tables().user_provided_types();
267 let user_ty = user_provided_types.get(fun.hir_id)
270 if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
275 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
277 let field_refs = args.iter()
281 name: Field::new(idx),
289 variant_index: index,
296 ty: cx.tables().node_type(fun.hir_id),
305 hir::ExprKind::AddrOf(mutbl, ref expr) => {
307 borrow_kind: mutbl.to_borrow_kind(),
312 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
314 hir::ExprKind::Assign(ref lhs, ref rhs) => {
321 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
322 if cx.tables().is_method_call(expr) {
323 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
333 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
334 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
338 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
339 if cx.tables().is_method_call(expr) {
340 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
343 match (op.node, cx.constness) {
344 // FIXME(eddyb) use logical ops in constants when
345 // they can handle that kind of control-flow.
346 (hir::BinOpKind::And, hir::Constness::Const) => {
347 cx.control_flow_destroyed.push((
349 "`&&` operator".into(),
357 (hir::BinOpKind::Or, hir::Constness::Const) => {
358 cx.control_flow_destroyed.push((
360 "`||` operator".into(),
369 (hir::BinOpKind::And, hir::Constness::NotConst) => {
370 ExprKind::LogicalOp {
376 (hir::BinOpKind::Or, hir::Constness::NotConst) => {
377 ExprKind::LogicalOp {
385 let op = bin_op(op.node);
396 hir::ExprKind::Index(ref lhs, ref index) => {
397 if cx.tables().is_method_call(expr) {
398 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
402 index: index.to_ref(),
407 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
408 if cx.tables().is_method_call(expr) {
409 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
411 ExprKind::Deref { arg: arg.to_ref() }
415 hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
416 if cx.tables().is_method_call(expr) {
417 overloaded_operator(cx, expr, vec![arg.to_ref()])
426 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
427 if cx.tables().is_method_call(expr) {
428 overloaded_operator(cx, expr, vec![arg.to_ref()])
430 if let hir::ExprKind::Lit(ref lit) = arg.kind {
432 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
444 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
446 ty::Adt(adt, substs) => {
447 match adt.adt_kind() {
448 AdtKind::Struct | AdtKind::Union => {
449 let user_provided_types = cx.tables().user_provided_types();
450 let user_ty = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
451 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
454 variant_index: VariantIdx::new(0),
457 fields: field_refs(cx, fields),
458 base: base.as_ref().map(|base| {
461 field_types: cx.tables()
462 .fru_field_types()[expr.hir_id]
469 let res = cx.tables().qpath_res(qpath, expr.hir_id);
471 Res::Def(DefKind::Variant, variant_id) => {
472 assert!(base.is_none());
474 let index = adt.variant_index_with_id(variant_id);
475 let user_provided_types = cx.tables().user_provided_types();
476 let user_ty = user_provided_types.get(expr.hir_id)
479 "make_mirror_unadjusted: (variant) user_ty={:?}",
484 variant_index: index,
487 fields: field_refs(cx, fields),
492 span_bug!(expr.span, "unexpected res: {:?}", res);
500 "unexpected type for struct literal: {:?}",
506 hir::ExprKind::Closure(..) => {
507 let closure_ty = cx.tables().expr_ty(expr);
508 let (def_id, substs, movability) = match closure_ty.kind {
509 ty::Closure(def_id, substs) => (def_id,
510 UpvarSubsts::Closure(substs), None),
511 ty::Generator(def_id, substs, movability) => {
512 (def_id, UpvarSubsts::Generator(substs), Some(movability))
515 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
518 let upvars = cx.tcx.upvars(def_id).iter()
519 .flat_map(|upvars| upvars.iter())
520 .zip(substs.upvar_tys(def_id, cx.tcx))
521 .map(|((&var_hir_id, _), ty)| capture_upvar(cx, expr, var_hir_id, ty))
531 hir::ExprKind::Path(ref qpath) => {
532 let res = cx.tables().qpath_res(qpath, expr.hir_id);
533 convert_path_expr(cx, expr, res)
536 hir::ExprKind::InlineAsm(ref asm, ref outputs, ref inputs) => {
537 ExprKind::InlineAsm {
539 outputs: outputs.to_ref(),
540 inputs: inputs.to_ref(),
544 // Now comes the rote stuff:
545 hir::ExprKind::Repeat(ref v, ref count) => {
546 let def_id = cx.tcx.hir().local_def_id(count.hir_id);
547 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
548 let instance = ty::Instance::resolve(
554 let global_id = GlobalId {
558 let span = cx.tcx.def_span(def_id);
559 let count = match cx.tcx.at(span).const_eval(cx.param_env.and(global_id)) {
560 Ok(cv) => cv.eval_usize(cx.tcx, cx.param_env),
561 Err(ErrorHandled::Reported) => 0,
562 Err(ErrorHandled::TooGeneric) => {
563 cx.tcx.sess.span_err(span, "array lengths can't depend on generic parameters");
573 hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
574 hir::ExprKind::Break(dest, ref value) => {
575 match dest.target_id {
576 Ok(target_id) => ExprKind::Break {
577 label: region::Scope {
578 id: target_id.local_id,
579 data: region::ScopeData::Node
581 value: value.to_ref(),
583 Err(err) => bug!("invalid loop id for break: {}", err)
586 hir::ExprKind::Continue(dest) => {
587 match dest.target_id {
588 Ok(loop_id) => ExprKind::Continue {
589 label: region::Scope {
590 id: loop_id.local_id,
591 data: region::ScopeData::Node
594 Err(err) => bug!("invalid loop id for continue: {}", err)
597 hir::ExprKind::Match(ref discr, ref arms, _) => {
599 scrutinee: discr.to_ref(),
600 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
603 hir::ExprKind::Loop(ref body, _, _) => {
605 body: block::to_expr_ref(cx, body),
608 hir::ExprKind::Field(ref source, ..) => {
610 lhs: source.to_ref(),
611 name: Field::new(cx.tcx.field_index(expr.hir_id, cx.tables)),
614 hir::ExprKind::Cast(ref source, ref cast_ty) => {
615 // Check for a user-given type annotation on this `cast`
616 let user_provided_types = cx.tables.user_provided_types();
617 let user_ty = user_provided_types.get(cast_ty.hir_id);
620 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
626 // Check to see if this cast is a "coercion cast", where the cast is actually done
627 // using a coercion (or is a no-op).
628 let cast = if cx.tables().is_coercion_cast(source.hir_id) {
629 // Convert the lexpr to a vexpr.
630 ExprKind::Use { source: source.to_ref() }
632 // check whether this is casting an enum variant discriminant
633 // to prevent cycles, we refer to the discriminant initializer
634 // which is always an integer and thus doesn't need to know the
635 // enum's layout (or its tag type) to compute it during const eval
639 // B = A as isize + 4,
641 // The correct solution would be to add symbolic computations to miri,
642 // so we wouldn't have to compute and store the actual value
643 let var = if let hir::ExprKind::Path(ref qpath) = source.kind {
644 let res = cx.tables().qpath_res(qpath, source.hir_id);
647 .node_type(source.hir_id)
649 .and_then(|adt_def| {
652 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
655 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
656 let (d, o) = adt_def.discriminant_def_for_variant(idx);
657 use rustc::ty::util::IntTypeExt;
658 let ty = adt_def.repr.discr_type();
659 let ty = ty.to_ty(cx.tcx());
669 let source = if let Some((did, offset, var_ty)) = var {
670 let mk_const = |literal| Expr {
674 kind: ExprKind::Literal {
679 let offset = mk_const(ty::Const::from_bits(
682 cx.param_env.and(var_ty),
686 // in case we are offsetting from a computed discriminant
687 // and not the beginning of discriminants (which is always `0`)
688 let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
689 let lhs = mk_const(cx.tcx().mk_const(ty::Const {
690 val: ConstValue::Unevaluated(did, substs),
693 let bin = ExprKind::Binary {
711 ExprKind::Cast { source }
714 if let Some(user_ty) = user_ty {
715 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
716 // inefficient, revisit this when performance becomes an issue.
717 let cast_expr = Expr {
723 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
725 ExprKind::ValueTypeAscription {
726 source: cast_expr.to_ref(),
727 user_ty: Some(*user_ty),
733 hir::ExprKind::Type(ref source, ref ty) => {
734 let user_provided_types = cx.tables.user_provided_types();
735 let user_ty = user_provided_types.get(ty.hir_id).map(|u_ty| *u_ty);
736 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
737 if source.is_place_expr() {
738 ExprKind::PlaceTypeAscription {
739 source: source.to_ref(),
743 ExprKind::ValueTypeAscription {
744 source: source.to_ref(),
749 hir::ExprKind::DropTemps(ref source) => {
750 ExprKind::Use { source: source.to_ref() }
752 hir::ExprKind::Box(ref value) => {
754 value: value.to_ref(),
757 hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
758 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
760 hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: v.to_ref() },
761 hir::ExprKind::Err => unreachable!(),
772 fn user_substs_applied_to_res(
773 cx: &mut Cx<'a, 'tcx>,
776 ) -> Option<ty::CanonicalUserType<'tcx>> {
777 debug!("user_substs_applied_to_res: res={:?}", res);
778 let user_provided_type = match res {
779 // A reference to something callable -- e.g., a fn, method, or
780 // a tuple-struct or tuple-variant. This has the type of a
781 // `Fn` but with the user-given substitutions.
782 Res::Def(DefKind::Fn, _) |
783 Res::Def(DefKind::Method, _) |
784 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) |
785 Res::Def(DefKind::Const, _) |
786 Res::Def(DefKind::AssocConst, _) =>
787 cx.tables().user_provided_types().get(hir_id).map(|u_ty| *u_ty),
789 // A unit struct/variant which is used as a value (e.g.,
790 // `None`). This has the type of the enum/struct that defines
791 // this variant -- but with the substitutions given by the
793 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) =>
794 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
796 // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
798 cx.user_substs_applied_to_ty_of_hir_id(hir_id),
801 bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id)
803 debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
807 fn method_callee<'a, 'tcx>(
808 cx: &mut Cx<'a, 'tcx>,
811 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
813 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
814 let (def_id, substs, user_ty) = match overloaded_callee {
815 Some((def_id, substs)) => (def_id, substs, None),
817 let (kind, def_id) = cx.tables().type_dependent_def(expr.hir_id)
819 span_bug!(expr.span, "no type-dependent def for method callee")
821 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id));
822 debug!("method_callee: user_ty={:?}", user_ty);
823 (def_id, cx.tables().node_substs(expr.hir_id), user_ty)
826 let ty = cx.tcx().mk_fn_def(def_id, substs);
831 kind: ExprKind::Literal {
832 literal: ty::Const::zero_sized(cx.tcx(), ty),
838 trait ToBorrowKind { fn to_borrow_kind(&self) -> BorrowKind; }
840 impl ToBorrowKind for AutoBorrowMutability {
841 fn to_borrow_kind(&self) -> BorrowKind {
842 use rustc::ty::adjustment::AllowTwoPhase;
844 AutoBorrowMutability::Mutable { allow_two_phase_borrow } =>
845 BorrowKind::Mut { allow_two_phase_borrow: match allow_two_phase_borrow {
846 AllowTwoPhase::Yes => true,
847 AllowTwoPhase::No => false
849 AutoBorrowMutability::Immutable =>
855 impl ToBorrowKind for hir::Mutability {
856 fn to_borrow_kind(&self) -> BorrowKind {
858 hir::MutMutable => BorrowKind::Mut { allow_two_phase_borrow: false },
859 hir::MutImmutable => BorrowKind::Shared,
864 fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx> {
866 pattern: cx.pattern_from_hir(&arm.pat),
867 guard: match arm.guard {
868 Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
871 body: arm.body.to_ref(),
872 lint_level: LintLevel::Explicit(arm.hir_id),
873 scope: region::Scope {
874 id: arm.hir_id.local_id,
875 data: region::ScopeData::Node
881 fn convert_path_expr<'a, 'tcx>(
882 cx: &mut Cx<'a, 'tcx>,
883 expr: &'tcx hir::Expr,
885 ) -> ExprKind<'tcx> {
886 let substs = cx.tables().node_substs(expr.hir_id);
888 // A regular function, constructor function or a constant.
889 Res::Def(DefKind::Fn, _) |
890 Res::Def(DefKind::Method, _) |
891 Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) |
892 Res::SelfCtor(..) => {
893 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
894 debug!("convert_path_expr: user_ty={:?}", user_ty);
896 literal: ty::Const::zero_sized(
898 cx.tables().node_type(expr.hir_id),
904 Res::Def(DefKind::ConstParam, def_id) => {
905 let hir_id = cx.tcx.hir().as_local_hir_id(def_id).unwrap();
906 let item_id = cx.tcx.hir().get_parent_node(hir_id);
907 let item_def_id = cx.tcx.hir().local_def_id(item_id);
908 let generics = cx.tcx.generics_of(item_def_id);
909 let local_def_id = cx.tcx.hir().local_def_id(hir_id);
910 let index = generics.param_def_id_to_index[&local_def_id];
911 let name = cx.tcx.hir().name(hir_id);
912 let val = ConstValue::Param(ty::ParamConst::new(index, name));
914 literal: cx.tcx.mk_const(
917 ty: cx.tables().node_type(expr.hir_id),
924 Res::Def(DefKind::Const, def_id) |
925 Res::Def(DefKind::AssocConst, def_id) => {
926 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
927 debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
929 literal: cx.tcx.mk_const(ty::Const {
930 val: ConstValue::Unevaluated(def_id, substs),
931 ty: cx.tables().node_type(expr.hir_id),
937 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
938 let user_provided_types = cx.tables.user_provided_types();
939 let user_provided_type = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
940 debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
941 let ty = cx.tables().node_type(expr.hir_id);
943 // A unit struct/variant which is used as a value.
944 // We return a completely different ExprKind here to account for this special case.
945 ty::Adt(adt_def, substs) => {
948 variant_index: adt_def.variant_index_with_ctor_id(def_id),
950 user_ty: user_provided_type,
955 _ => bug!("unexpected ty: {:?}", ty),
959 Res::Def(DefKind::Static, id) => ExprKind::StaticRef { id },
961 Res::Local(var_hir_id) => convert_var(cx, expr, var_hir_id),
963 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
968 cx: &mut Cx<'_, 'tcx>,
969 expr: &'tcx hir::Expr,
970 var_hir_id: hir::HirId,
971 ) -> ExprKind<'tcx> {
972 let upvar_index = cx.tables().upvar_list.get(&cx.body_owner)
973 .and_then(|upvars| upvars.get_full(&var_hir_id).map(|(i, _, _)| i));
975 debug!("convert_var({:?}): upvar_index={:?}, body_owner={:?}",
976 var_hir_id, upvar_index, cx.body_owner);
978 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
981 None => ExprKind::VarRef { id: var_hir_id },
983 Some(upvar_index) => {
984 let closure_def_id = cx.body_owner;
985 let upvar_id = ty::UpvarId {
986 var_path: ty::UpvarPath {hir_id: var_hir_id},
987 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
989 let var_ty = cx.tables().node_type(var_hir_id);
991 // FIXME free regions in closures are not right
992 let closure_ty = cx.tables().node_type(
993 cx.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id),
996 // FIXME we're just hard-coding the idea that the
997 // signature will be &self or &mut self and hence will
998 // have a bound region with number 0
999 let region = ty::ReFree(ty::FreeRegion {
1000 scope: closure_def_id,
1001 bound_region: ty::BoundRegion::BrAnon(0),
1003 let region = cx.tcx.mk_region(region);
1005 let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.kind {
1006 match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() {
1007 ty::ClosureKind::Fn => {
1008 let ref_closure_ty = cx.tcx.mk_ref(region,
1011 mutbl: hir::MutImmutable,
1017 kind: ExprKind::Deref {
1022 kind: ExprKind::SelfRef,
1028 ty::ClosureKind::FnMut => {
1029 let ref_closure_ty = cx.tcx.mk_ref(region,
1032 mutbl: hir::MutMutable,
1038 kind: ExprKind::Deref {
1043 kind: ExprKind::SelfRef,
1048 ty::ClosureKind::FnOnce => {
1053 kind: ExprKind::SelfRef,
1062 kind: ExprKind::SelfRef,
1066 // at this point we have `self.n`, which loads up the upvar
1067 let field_kind = ExprKind::Field {
1068 lhs: self_expr.to_ref(),
1069 name: Field::new(upvar_index),
1072 // ...but the upvar might be an `&T` or `&mut T` capture, at which
1073 // point we need an implicit deref
1074 match cx.tables().upvar_capture(upvar_id) {
1075 ty::UpvarCapture::ByValue => field_kind,
1076 ty::UpvarCapture::ByRef(borrow) => {
1080 ty: cx.tcx.mk_ref(borrow.region,
1083 mutbl: borrow.kind.to_mutbl_lossy(),
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, 'tcx>(
1119 cx: &mut Cx<'a, 'tcx>,
1120 expr: &'tcx hir::Expr,
1121 args: Vec<ExprRef<'tcx>>
1122 ) -> ExprKind<'tcx> {
1123 let fun = method_callee(cx, expr, expr.span, None);
1128 from_hir_call: false,
1132 fn overloaded_place<'a, 'tcx>(
1133 cx: &mut Cx<'a, 'tcx>,
1134 expr: &'tcx hir::Expr,
1136 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
1137 args: Vec<ExprRef<'tcx>>,
1138 ) -> ExprKind<'tcx> {
1139 // For an overloaded *x or x[y] expression of type T, the method
1140 // call returns an &T and we must add the deref so that the types
1141 // line up (this is because `*x` and `x[y]` represent places):
1143 let recv_ty = match args[0] {
1144 ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e),
1145 ExprRef::Mirror(ref e) => e.ty
1148 // Reconstruct the output assuming it's a reference with the
1149 // same region and mutability as the receiver. This holds for
1150 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1151 let (region, mutbl) = match recv_ty.kind {
1152 ty::Ref(region, _, mutbl) => (region, mutbl),
1153 _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
1155 let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut {
1160 // construct the complete expression `foo()` for the overloaded call,
1161 // which will yield the &T type
1162 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1163 let fun = method_callee(cx, expr, expr.span, overloaded_callee);
1164 let ref_expr = Expr {
1168 kind: ExprKind::Call {
1172 from_hir_call: false,
1176 // construct and return a deref wrapper `*foo()`
1177 ExprKind::Deref { arg: ref_expr.to_ref() }
1180 fn capture_upvar<'tcx>(
1181 cx: &mut Cx<'_, 'tcx>,
1182 closure_expr: &'tcx hir::Expr,
1183 var_hir_id: hir::HirId,
1185 ) -> ExprRef<'tcx> {
1186 let upvar_id = ty::UpvarId {
1187 var_path: ty::UpvarPath { hir_id: var_hir_id },
1188 closure_expr_id: cx.tcx.hir().local_def_id(closure_expr.hir_id).to_local(),
1190 let upvar_capture = cx.tables().upvar_capture(upvar_id);
1191 let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1192 let var_ty = cx.tables().node_type(var_hir_id);
1193 let captured_var = Expr {
1196 span: closure_expr.span,
1197 kind: convert_var(cx, closure_expr, var_hir_id),
1199 match upvar_capture {
1200 ty::UpvarCapture::ByValue => captured_var.to_ref(),
1201 ty::UpvarCapture::ByRef(upvar_borrow) => {
1202 let borrow_kind = match upvar_borrow.kind {
1203 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1204 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1205 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }
1210 span: closure_expr.span,
1211 kind: ExprKind::Borrow {
1213 arg: captured_var.to_ref(),
1220 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1221 fn field_refs<'a, 'tcx>(
1222 cx: &mut Cx<'a, 'tcx>,
1223 fields: &'tcx [hir::Field]
1224 ) -> Vec<FieldExprRef<'tcx>> {
1228 name: Field::new(cx.tcx.field_index(field.hir_id, cx.tables)),
1229 expr: field.expr.to_ref(),