1 use crate::hair::cx::block;
2 use crate::hair::cx::to_ref::ToRef;
3 use crate::hair::cx::Cx;
4 use crate::hair::util::UserAnnotatedTyHelpers;
6 use rustc::mir::interpret::{ErrorHandled, Scalar};
7 use rustc::mir::BorrowKind;
8 use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast};
9 use rustc::ty::subst::{InternalSubsts, SubstsRef};
10 use rustc::ty::{self, AdtKind, Ty};
12 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
13 use rustc_hir::def_id::LocalDefId;
14 use rustc_index::vec::Idx;
17 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> {
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 { id: self.hir_id.local_id, data: region::ScopeData::Node };
24 debug!("Expr::make_mirror(): id={}, span={:?}", self.hir_id, self.span);
26 let mut expr = make_mirror_unadjusted(cx, self);
28 // Now apply adjustments, if any.
29 for adjustment in cx.tables().expr_adjustments(self) {
30 debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment);
31 expr = apply_adjustment(cx, self, expr, adjustment);
34 // Next, wrap this up in the expr's scope.
39 kind: ExprKind::Scope {
40 region_scope: expr_scope,
42 lint_level: LintLevel::Explicit(self.hir_id),
46 // Finally, create a destruction scope, if any.
47 if let Some(region_scope) = cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id)
53 kind: ExprKind::Scope {
56 lint_level: LintLevel::Inherited,
66 fn apply_adjustment<'a, 'tcx>(
67 cx: &mut Cx<'a, 'tcx>,
68 hir_expr: &'tcx hir::Expr<'tcx>,
70 adjustment: &Adjustment<'tcx>,
72 let Expr { temp_lifetime, mut span, .. } = expr;
74 // Adjust the span from the block, to the last expression of the
75 // block. This is a better span when returning a mutable reference
76 // with too short a lifetime. The error message will use the span
77 // from the assignment to the return place, which should only point
78 // at the returned value, not the entire function body.
80 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
82 // // ^ error message points at this expression.
84 let mut adjust_span = |expr: &mut Expr<'tcx>| {
85 if let ExprKind::Block { body } = expr.kind {
86 if let Some(ref last_expr) = body.expr {
87 span = last_expr.span;
93 let kind = match adjustment.kind {
94 Adjust::Pointer(PointerCast::Unsize) => {
95 adjust_span(&mut expr);
96 ExprKind::Pointer { cast: PointerCast::Unsize, source: expr.to_ref() }
98 Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: expr.to_ref() },
99 Adjust::NeverToAny => ExprKind::NeverToAny { source: expr.to_ref() },
100 Adjust::Deref(None) => {
101 adjust_span(&mut expr);
102 ExprKind::Deref { arg: expr.to_ref() }
104 Adjust::Deref(Some(deref)) => {
105 // We don't need to do call adjust_span here since
106 // deref coercions always start with a built-in deref.
107 let call = deref.method_call(cx.tcx(), expr.ty);
111 ty: cx.tcx.mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }),
113 kind: ExprKind::Borrow {
114 borrow_kind: deref.mutbl.to_borrow_kind(),
119 overloaded_place(cx, hir_expr, adjustment.target, Some(call), vec![expr.to_ref()])
121 Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
122 ExprKind::Borrow { borrow_kind: m.to_borrow_kind(), arg: expr.to_ref() }
124 Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
125 ExprKind::AddressOf { mutability, arg: expr.to_ref() }
129 Expr { temp_lifetime, ty: adjustment.target, span, kind }
132 fn make_mirror_unadjusted<'a, 'tcx>(
133 cx: &mut Cx<'a, 'tcx>,
134 expr: &'tcx hir::Expr<'tcx>,
136 let expr_ty = cx.tables().expr_ty(expr);
137 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
139 let kind = match expr.kind {
140 // Here comes the interesting stuff:
141 hir::ExprKind::MethodCall(_, method_span, ref args) => {
142 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
143 let expr = method_callee(cx, expr, method_span, None);
144 let args = args.iter().map(|e| e.to_ref()).collect();
145 ExprKind::Call { ty: expr.ty, fun: expr.to_ref(), args, from_hir_call: true }
148 hir::ExprKind::Call(ref fun, ref args) => {
149 if cx.tables().is_method_call(expr) {
150 // The callee is something implementing Fn, FnMut, or FnOnce.
151 // Find the actual method implementation being called and
152 // build the appropriate UFCS call expression with the
153 // callee-object as expr parameter.
155 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
157 let method = method_callee(cx, expr, fun.span, None);
159 let arg_tys = args.iter().map(|e| cx.tables().expr_ty_adjusted(e));
160 let tupled_args = Expr {
161 ty: cx.tcx.mk_tup(arg_tys),
164 kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
169 fun: method.to_ref(),
170 args: vec![fun.to_ref(), tupled_args.to_ref()],
175 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
176 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
177 expr_ty.ty_adt_def().and_then(|adt_def| match path.res {
178 Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
179 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
181 Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
187 if let Some((adt_def, index)) = adt_data {
188 let substs = cx.tables().node_substs(fun.hir_id);
189 let user_provided_types = cx.tables().user_provided_types();
191 user_provided_types.get(fun.hir_id).map(|u_ty| *u_ty).map(|mut u_ty| {
192 if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
197 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
199 let field_refs = args
202 .map(|(idx, e)| FieldExprRef { name: Field::new(idx), expr: e.to_ref() })
207 variant_index: index,
214 ty: cx.tables().node_type(fun.hir_id),
223 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
224 ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: arg.to_ref() }
227 hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
228 ExprKind::AddressOf { mutability, arg: arg.to_ref() }
231 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
233 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
234 ExprKind::Assign { lhs: lhs.to_ref(), rhs: rhs.to_ref() }
237 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
238 if cx.tables().is_method_call(expr) {
239 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
241 ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() }
245 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
246 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
250 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
251 if cx.tables().is_method_call(expr) {
252 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
255 match (op.node, cx.constness) {
256 // Destroy control flow if `#![feature(const_if_match)]` is not enabled.
257 (hir::BinOpKind::And, hir::Constness::Const)
258 if !cx.tcx.features().const_if_match =>
260 cx.control_flow_destroyed.push((op.span, "`&&` operator".into()));
261 ExprKind::Binary { op: BinOp::BitAnd, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
263 (hir::BinOpKind::Or, hir::Constness::Const)
264 if !cx.tcx.features().const_if_match =>
266 cx.control_flow_destroyed.push((op.span, "`||` operator".into()));
267 ExprKind::Binary { op: BinOp::BitOr, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
270 (hir::BinOpKind::And, _) => ExprKind::LogicalOp {
275 (hir::BinOpKind::Or, _) => ExprKind::LogicalOp {
282 let op = bin_op(op.node);
283 ExprKind::Binary { op, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
289 hir::ExprKind::Index(ref lhs, ref index) => {
290 if cx.tables().is_method_call(expr) {
291 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
293 ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() }
297 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
298 if cx.tables().is_method_call(expr) {
299 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
301 ExprKind::Deref { arg: arg.to_ref() }
305 hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
306 if cx.tables().is_method_call(expr) {
307 overloaded_operator(cx, expr, vec![arg.to_ref()])
309 ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() }
313 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
314 if cx.tables().is_method_call(expr) {
315 overloaded_operator(cx, expr, vec![arg.to_ref()])
317 if let hir::ExprKind::Lit(ref lit) = arg.kind {
319 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
323 ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
328 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind {
329 ty::Adt(adt, substs) => match adt.adt_kind() {
330 AdtKind::Struct | AdtKind::Union => {
331 let user_provided_types = cx.tables().user_provided_types();
332 let user_ty = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
333 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
336 variant_index: VariantIdx::new(0),
339 fields: field_refs(cx, fields),
340 base: base.as_ref().map(|base| FruInfo {
342 field_types: cx.tables().fru_field_types()[expr.hir_id].clone(),
347 let res = cx.tables().qpath_res(qpath, expr.hir_id);
349 Res::Def(DefKind::Variant, variant_id) => {
350 assert!(base.is_none());
352 let index = adt.variant_index_with_id(variant_id);
353 let user_provided_types = cx.tables().user_provided_types();
354 let user_ty = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
355 debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
358 variant_index: index,
361 fields: field_refs(cx, fields),
366 span_bug!(expr.span, "unexpected res: {:?}", res);
372 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
376 hir::ExprKind::Closure(..) => {
377 let closure_ty = cx.tables().expr_ty(expr);
378 let (def_id, substs, movability) = match closure_ty.kind {
379 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
380 ty::Generator(def_id, substs, movability) => {
381 (def_id, UpvarSubsts::Generator(substs), Some(movability))
384 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
391 .flat_map(|upvars| upvars.iter())
392 .zip(substs.upvar_tys(def_id, cx.tcx))
393 .map(|((&var_hir_id, _), ty)| capture_upvar(cx, expr, var_hir_id, ty))
395 ExprKind::Closure { closure_id: def_id, substs, upvars, movability }
398 hir::ExprKind::Path(ref qpath) => {
399 let res = cx.tables().qpath_res(qpath, expr.hir_id);
400 convert_path_expr(cx, expr, res)
403 hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm {
405 outputs: asm.outputs_exprs.to_ref(),
406 inputs: asm.inputs_exprs.to_ref(),
409 // Now comes the rote stuff:
410 hir::ExprKind::Repeat(ref v, ref count) => {
411 let def_id = cx.tcx.hir().local_def_id(count.hir_id);
412 let substs = InternalSubsts::identity_for_item(cx.tcx, def_id);
413 let span = cx.tcx.def_span(def_id);
414 let count = match cx.tcx.const_eval_resolve(
415 ty::ParamEnv::reveal_all(),
422 if let Some(count) = cv.try_to_bits_for_ty(
424 ty::ParamEnv::reveal_all(),
429 bug!("repeat count constant value can't be converted to usize");
432 Err(ErrorHandled::Reported) => 0,
433 Err(ErrorHandled::TooGeneric) => {
434 let span = cx.tcx.def_span(def_id);
435 cx.tcx.sess.span_err(span, "array lengths can't depend on generic parameters");
440 ExprKind::Repeat { value: v.to_ref(), count }
442 hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
443 hir::ExprKind::Break(dest, ref value) => match dest.target_id {
444 Ok(target_id) => ExprKind::Break {
445 label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
446 value: value.to_ref(),
448 Err(err) => bug!("invalid loop id for break: {}", err),
450 hir::ExprKind::Continue(dest) => match dest.target_id {
451 Ok(loop_id) => ExprKind::Continue {
452 label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node },
454 Err(err) => bug!("invalid loop id for continue: {}", err),
456 hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match {
457 scrutinee: discr.to_ref(),
458 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
460 hir::ExprKind::Loop(ref body, _, _) => {
461 ExprKind::Loop { body: block::to_expr_ref(cx, body) }
463 hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
464 lhs: source.to_ref(),
465 name: Field::new(cx.tcx.field_index(expr.hir_id, cx.tables)),
467 hir::ExprKind::Cast(ref source, ref cast_ty) => {
468 // Check for a user-given type annotation on this `cast`
469 let user_provided_types = cx.tables.user_provided_types();
470 let user_ty = user_provided_types.get(cast_ty.hir_id);
473 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
474 expr, cast_ty.hir_id, user_ty,
477 // Check to see if this cast is a "coercion cast", where the cast is actually done
478 // using a coercion (or is a no-op).
479 let cast = if cx.tables().is_coercion_cast(source.hir_id) {
480 // Convert the lexpr to a vexpr.
481 ExprKind::Use { source: source.to_ref() }
482 } else if cx.tables().expr_ty(source).is_region_ptr() {
483 // Special cased so that we can type check that the element
484 // type of the source matches the pointed to type of the
486 ExprKind::Pointer { source: source.to_ref(), cast: PointerCast::ArrayToPointer }
488 // check whether this is casting an enum variant discriminant
489 // to prevent cycles, we refer to the discriminant initializer
490 // which is always an integer and thus doesn't need to know the
491 // enum's layout (or its tag type) to compute it during const eval
495 // B = A as isize + 4,
497 // The correct solution would be to add symbolic computations to miri,
498 // so we wouldn't have to compute and store the actual value
499 let var = if let hir::ExprKind::Path(ref qpath) = source.kind {
500 let res = cx.tables().qpath_res(qpath, source.hir_id);
501 cx.tables().node_type(source.hir_id).ty_adt_def().and_then(
502 |adt_def| match res {
504 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
507 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
508 let (d, o) = adt_def.discriminant_def_for_variant(idx);
509 use rustc::ty::util::IntTypeExt;
510 let ty = adt_def.repr.discr_type();
511 let ty = ty.to_ty(cx.tcx());
521 let source = if let Some((did, offset, var_ty)) = var {
522 let mk_const = |literal| {
527 kind: ExprKind::Literal { literal, user_ty: None },
531 let offset = mk_const(ty::Const::from_bits(
534 cx.param_env.and(var_ty),
538 // in case we are offsetting from a computed discriminant
539 // and not the beginning of discriminants (which is always `0`)
540 let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
541 let lhs = mk_const(cx.tcx().mk_const(ty::Const {
542 val: ty::ConstKind::Unevaluated(did, substs, None),
545 let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
546 Expr { temp_lifetime, ty: var_ty, span: expr.span, kind: bin }.to_ref()
554 ExprKind::Cast { source }
557 if let Some(user_ty) = user_ty {
558 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
559 // inefficient, revisit this when performance becomes an issue.
560 let cast_expr = Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind: cast };
561 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
563 ExprKind::ValueTypeAscription {
564 source: cast_expr.to_ref(),
565 user_ty: Some(*user_ty),
571 hir::ExprKind::Type(ref source, ref ty) => {
572 let user_provided_types = cx.tables.user_provided_types();
573 let user_ty = user_provided_types.get(ty.hir_id).map(|u_ty| *u_ty);
574 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
575 if source.is_syntactic_place_expr() {
576 ExprKind::PlaceTypeAscription { source: source.to_ref(), user_ty }
578 ExprKind::ValueTypeAscription { source: source.to_ref(), user_ty }
581 hir::ExprKind::DropTemps(ref source) => ExprKind::Use { source: source.to_ref() },
582 hir::ExprKind::Box(ref value) => ExprKind::Box { value: value.to_ref() },
583 hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
584 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
586 hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: v.to_ref() },
587 hir::ExprKind::Err => unreachable!(),
590 Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind }
593 fn user_substs_applied_to_res<'tcx>(
594 cx: &mut Cx<'_, 'tcx>,
597 ) -> Option<ty::CanonicalUserType<'tcx>> {
598 debug!("user_substs_applied_to_res: res={:?}", res);
599 let user_provided_type = match res {
600 // A reference to something callable -- e.g., a fn, method, or
601 // a tuple-struct or tuple-variant. This has the type of a
602 // `Fn` but with the user-given substitutions.
603 Res::Def(DefKind::Fn, _)
604 | Res::Def(DefKind::Method, _)
605 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
606 | Res::Def(DefKind::Const, _)
607 | Res::Def(DefKind::AssocConst, _) => {
608 cx.tables().user_provided_types().get(hir_id).map(|u_ty| *u_ty)
611 // A unit struct/variant which is used as a value (e.g.,
612 // `None`). This has the type of the enum/struct that defines
613 // this variant -- but with the substitutions given by the
615 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
616 cx.user_substs_applied_to_ty_of_hir_id(hir_id)
619 // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
620 Res::SelfCtor(_) => cx.user_substs_applied_to_ty_of_hir_id(hir_id),
622 _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
624 debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
628 fn method_callee<'a, 'tcx>(
629 cx: &mut Cx<'a, 'tcx>,
630 expr: &hir::Expr<'_>,
632 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
634 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
635 let (def_id, substs, user_ty) = match overloaded_callee {
636 Some((def_id, substs)) => (def_id, substs, None),
638 let (kind, def_id) = cx
640 .type_dependent_def(expr.hir_id)
641 .unwrap_or_else(|| span_bug!(expr.span, "no type-dependent def for method callee"));
642 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id));
643 debug!("method_callee: user_ty={:?}", user_ty);
644 (def_id, cx.tables().node_substs(expr.hir_id), user_ty)
647 let ty = cx.tcx().mk_fn_def(def_id, substs);
652 kind: ExprKind::Literal { literal: ty::Const::zero_sized(cx.tcx(), ty), user_ty },
657 fn to_borrow_kind(&self) -> BorrowKind;
660 impl ToBorrowKind for AutoBorrowMutability {
661 fn to_borrow_kind(&self) -> BorrowKind {
662 use rustc::ty::adjustment::AllowTwoPhase;
664 AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
665 allow_two_phase_borrow: match allow_two_phase_borrow {
666 AllowTwoPhase::Yes => true,
667 AllowTwoPhase::No => false,
670 AutoBorrowMutability::Not => BorrowKind::Shared,
675 impl ToBorrowKind for hir::Mutability {
676 fn to_borrow_kind(&self) -> BorrowKind {
678 hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
679 hir::Mutability::Not => BorrowKind::Shared,
684 fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'tcx> {
686 pattern: cx.pattern_from_hir(&arm.pat),
687 guard: match arm.guard {
688 Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
691 body: arm.body.to_ref(),
692 lint_level: LintLevel::Explicit(arm.hir_id),
693 scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node },
698 fn convert_path_expr<'a, 'tcx>(
699 cx: &mut Cx<'a, 'tcx>,
700 expr: &'tcx hir::Expr<'tcx>,
702 ) -> ExprKind<'tcx> {
703 let substs = cx.tables().node_substs(expr.hir_id);
705 // A regular function, constructor function or a constant.
706 Res::Def(DefKind::Fn, _)
707 | Res::Def(DefKind::Method, _)
708 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
709 | Res::SelfCtor(..) => {
710 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
711 debug!("convert_path_expr: user_ty={:?}", user_ty);
713 literal: ty::Const::zero_sized(cx.tcx, cx.tables().node_type(expr.hir_id)),
718 Res::Def(DefKind::ConstParam, def_id) => {
719 let hir_id = cx.tcx.hir().as_local_hir_id(def_id).unwrap();
720 let item_id = cx.tcx.hir().get_parent_node(hir_id);
721 let item_def_id = cx.tcx.hir().local_def_id(item_id);
722 let generics = cx.tcx.generics_of(item_def_id);
723 let local_def_id = cx.tcx.hir().local_def_id(hir_id);
724 let index = generics.param_def_id_to_index[&local_def_id];
725 let name = cx.tcx.hir().name(hir_id);
726 let val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
728 literal: cx.tcx.mk_const(ty::Const { val, ty: cx.tables().node_type(expr.hir_id) }),
733 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
734 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
735 debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
737 literal: cx.tcx.mk_const(ty::Const {
738 val: ty::ConstKind::Unevaluated(def_id, substs, None),
739 ty: cx.tables().node_type(expr.hir_id),
745 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
746 let user_provided_types = cx.tables.user_provided_types();
747 let user_provided_type = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
748 debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
749 let ty = cx.tables().node_type(expr.hir_id);
751 // A unit struct/variant which is used as a value.
752 // We return a completely different ExprKind here to account for this special case.
753 ty::Adt(adt_def, substs) => ExprKind::Adt {
755 variant_index: adt_def.variant_index_with_ctor_id(def_id),
757 user_ty: user_provided_type,
761 _ => bug!("unexpected ty: {:?}", ty),
765 // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is
766 // a constant reference (or constant raw pointer for `static mut`) in MIR
767 Res::Def(DefKind::Static, id) => {
768 let ty = cx.tcx.static_ptr_ty(id);
769 let ptr = cx.tcx.alloc_map.lock().create_static_alloc(id);
770 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
776 kind: ExprKind::StaticRef {
777 literal: ty::Const::from_scalar(cx.tcx, Scalar::Ptr(ptr.into()), ty),
785 Res::Local(var_hir_id) => convert_var(cx, expr, var_hir_id),
787 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
791 fn convert_var<'tcx>(
792 cx: &mut Cx<'_, 'tcx>,
793 expr: &'tcx hir::Expr<'tcx>,
794 var_hir_id: hir::HirId,
795 ) -> ExprKind<'tcx> {
800 .and_then(|upvars| upvars.get_full(&var_hir_id).map(|(i, _, _)| i));
803 "convert_var({:?}): upvar_index={:?}, body_owner={:?}",
804 var_hir_id, upvar_index, cx.body_owner
807 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
810 None => ExprKind::VarRef { id: var_hir_id },
812 Some(upvar_index) => {
813 let closure_def_id = cx.body_owner;
814 let upvar_id = ty::UpvarId {
815 var_path: ty::UpvarPath { hir_id: var_hir_id },
816 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
818 let var_ty = cx.tables().node_type(var_hir_id);
820 // FIXME free regions in closures are not right
823 .node_type(cx.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
825 // FIXME we're just hard-coding the idea that the
826 // signature will be &self or &mut self and hence will
827 // have a bound region with number 0
828 let region = ty::ReFree(ty::FreeRegion {
829 scope: closure_def_id,
830 bound_region: ty::BoundRegion::BrAnon(0),
832 let region = cx.tcx.mk_region(region);
834 let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.kind {
835 match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() {
836 ty::ClosureKind::Fn => {
837 let ref_closure_ty = cx.tcx.mk_ref(
839 ty::TypeAndMut { ty: closure_ty, mutbl: hir::Mutability::Not },
845 kind: ExprKind::Deref {
850 kind: ExprKind::SelfRef,
856 ty::ClosureKind::FnMut => {
857 let ref_closure_ty = cx.tcx.mk_ref(
859 ty::TypeAndMut { ty: closure_ty, mutbl: hir::Mutability::Mut },
865 kind: ExprKind::Deref {
870 kind: ExprKind::SelfRef,
876 ty::ClosureKind::FnOnce => Expr {
880 kind: ExprKind::SelfRef,
884 Expr { ty: closure_ty, temp_lifetime, span: expr.span, kind: ExprKind::SelfRef }
887 // at this point we have `self.n`, which loads up the upvar
889 ExprKind::Field { lhs: self_expr.to_ref(), name: Field::new(upvar_index) };
891 // ...but the upvar might be an `&T` or `&mut T` capture, at which
892 // point we need an implicit deref
893 match cx.tables().upvar_capture(upvar_id) {
894 ty::UpvarCapture::ByValue => field_kind,
895 ty::UpvarCapture::ByRef(borrow) => ExprKind::Deref {
900 ty::TypeAndMut { ty: var_ty, mutbl: borrow.kind.to_mutbl_lossy() },
912 fn bin_op(op: hir::BinOpKind) -> BinOp {
914 hir::BinOpKind::Add => BinOp::Add,
915 hir::BinOpKind::Sub => BinOp::Sub,
916 hir::BinOpKind::Mul => BinOp::Mul,
917 hir::BinOpKind::Div => BinOp::Div,
918 hir::BinOpKind::Rem => BinOp::Rem,
919 hir::BinOpKind::BitXor => BinOp::BitXor,
920 hir::BinOpKind::BitAnd => BinOp::BitAnd,
921 hir::BinOpKind::BitOr => BinOp::BitOr,
922 hir::BinOpKind::Shl => BinOp::Shl,
923 hir::BinOpKind::Shr => BinOp::Shr,
924 hir::BinOpKind::Eq => BinOp::Eq,
925 hir::BinOpKind::Lt => BinOp::Lt,
926 hir::BinOpKind::Le => BinOp::Le,
927 hir::BinOpKind::Ne => BinOp::Ne,
928 hir::BinOpKind::Ge => BinOp::Ge,
929 hir::BinOpKind::Gt => BinOp::Gt,
930 _ => bug!("no equivalent for ast binop {:?}", op),
934 fn overloaded_operator<'a, 'tcx>(
935 cx: &mut Cx<'a, 'tcx>,
936 expr: &'tcx hir::Expr<'tcx>,
937 args: Vec<ExprRef<'tcx>>,
938 ) -> ExprKind<'tcx> {
939 let fun = method_callee(cx, expr, expr.span, None);
940 ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false }
943 fn overloaded_place<'a, 'tcx>(
944 cx: &mut Cx<'a, 'tcx>,
945 expr: &'tcx hir::Expr<'tcx>,
947 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
948 args: Vec<ExprRef<'tcx>>,
949 ) -> ExprKind<'tcx> {
950 // For an overloaded *x or x[y] expression of type T, the method
951 // call returns an &T and we must add the deref so that the types
952 // line up (this is because `*x` and `x[y]` represent places):
954 let recv_ty = match args[0] {
955 ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e),
956 ExprRef::Mirror(ref e) => e.ty,
959 // Reconstruct the output assuming it's a reference with the
960 // same region and mutability as the receiver. This holds for
961 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
962 let (region, mutbl) = match recv_ty.kind {
963 ty::Ref(region, _, mutbl) => (region, mutbl),
964 _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
966 let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
968 // construct the complete expression `foo()` for the overloaded call,
969 // which will yield the &T type
970 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
971 let fun = method_callee(cx, expr, expr.span, overloaded_callee);
972 let ref_expr = Expr {
976 kind: ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false },
979 // construct and return a deref wrapper `*foo()`
980 ExprKind::Deref { arg: ref_expr.to_ref() }
983 fn capture_upvar<'tcx>(
984 cx: &mut Cx<'_, 'tcx>,
985 closure_expr: &'tcx hir::Expr<'tcx>,
986 var_hir_id: hir::HirId,
989 let upvar_id = ty::UpvarId {
990 var_path: ty::UpvarPath { hir_id: var_hir_id },
991 closure_expr_id: cx.tcx.hir().local_def_id(closure_expr.hir_id).to_local(),
993 let upvar_capture = cx.tables().upvar_capture(upvar_id);
994 let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
995 let var_ty = cx.tables().node_type(var_hir_id);
996 let captured_var = Expr {
999 span: closure_expr.span,
1000 kind: convert_var(cx, closure_expr, var_hir_id),
1002 match upvar_capture {
1003 ty::UpvarCapture::ByValue => captured_var.to_ref(),
1004 ty::UpvarCapture::ByRef(upvar_borrow) => {
1005 let borrow_kind = match upvar_borrow.kind {
1006 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1007 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1008 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false },
1013 span: closure_expr.span,
1014 kind: ExprKind::Borrow { borrow_kind, arg: captured_var.to_ref() },
1021 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1022 fn field_refs<'a, 'tcx>(
1023 cx: &mut Cx<'a, 'tcx>,
1024 fields: &'tcx [hir::Field<'tcx>],
1025 ) -> Vec<FieldExprRef<'tcx>> {
1028 .map(|field| FieldExprRef {
1029 name: Field::new(cx.tcx.field_index(field.hir_id, cx.tables)),
1030 expr: field.expr.to_ref(),