1 use crate::thir::cx::block;
2 use crate::thir::cx::to_ref::ToRef;
3 use crate::thir::cx::Cx;
4 use crate::thir::util::UserAnnotatedTyHelpers;
7 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
8 use rustc_index::vec::Idx;
9 use rustc_middle::mir::interpret::Scalar;
10 use rustc_middle::mir::BorrowKind;
11 use rustc_middle::ty::adjustment::{
12 Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
14 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
15 use rustc_middle::ty::{self, AdtKind, Ty};
18 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> {
19 type Output = Expr<'tcx>;
21 fn make_mirror(self, cx: &mut Cx<'_, 'tcx>) -> Expr<'tcx> {
22 let temp_lifetime = cx.region_scope_tree.temporary_scope(self.hir_id.local_id);
23 let expr_scope = region::Scope { id: self.hir_id.local_id, data: region::ScopeData::Node };
25 debug!("Expr::make_mirror(): id={}, span={:?}", self.hir_id, self.span);
27 let mut expr = make_mirror_unadjusted(cx, self);
29 // Now apply adjustments, if any.
30 for adjustment in cx.typeck_results().expr_adjustments(self) {
31 debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment);
32 expr = apply_adjustment(cx, self, expr, adjustment);
35 // Next, wrap this up in the expr's scope.
40 kind: ExprKind::Scope {
41 region_scope: expr_scope,
43 lint_level: LintLevel::Explicit(self.hir_id),
47 // Finally, create a destruction scope, if any.
48 if let Some(region_scope) = cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id)
54 kind: ExprKind::Scope {
57 lint_level: LintLevel::Inherited,
67 fn apply_adjustment<'a, 'tcx>(
68 cx: &mut Cx<'a, 'tcx>,
69 hir_expr: &'tcx hir::Expr<'tcx>,
71 adjustment: &Adjustment<'tcx>,
73 let Expr { temp_lifetime, mut span, .. } = expr;
75 // Adjust the span from the block, to the last expression of the
76 // block. This is a better span when returning a mutable reference
77 // with too short a lifetime. The error message will use the span
78 // from the assignment to the return place, which should only point
79 // at the returned value, not the entire function body.
81 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
83 // // ^ error message points at this expression.
85 let mut adjust_span = |expr: &mut Expr<'tcx>| {
86 if let ExprKind::Block { body } = expr.kind {
87 if let Some(ref last_expr) = body.expr {
88 span = last_expr.span;
94 let kind = match adjustment.kind {
95 Adjust::Pointer(PointerCast::Unsize) => {
96 adjust_span(&mut expr);
97 ExprKind::Pointer { cast: PointerCast::Unsize, source: expr.to_ref() }
99 Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: expr.to_ref() },
100 Adjust::NeverToAny => ExprKind::NeverToAny { source: expr.to_ref() },
101 Adjust::Deref(None) => {
102 adjust_span(&mut expr);
103 ExprKind::Deref { arg: expr.to_ref() }
105 Adjust::Deref(Some(deref)) => {
106 // We don't need to do call adjust_span here since
107 // deref coercions always start with a built-in deref.
108 let call = deref.method_call(cx.tcx(), expr.ty);
112 ty: cx.tcx.mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }),
114 kind: ExprKind::Borrow {
115 borrow_kind: deref.mutbl.to_borrow_kind(),
129 Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
130 ExprKind::Borrow { borrow_kind: m.to_borrow_kind(), arg: expr.to_ref() }
132 Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
133 ExprKind::AddressOf { mutability, arg: expr.to_ref() }
137 Expr { temp_lifetime, ty: adjustment.target, span, kind }
140 fn make_mirror_unadjusted<'a, 'tcx>(
141 cx: &mut Cx<'a, 'tcx>,
142 expr: &'tcx hir::Expr<'tcx>,
144 let expr_ty = cx.typeck_results().expr_ty(expr);
145 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
147 let kind = match expr.kind {
148 // Here comes the interesting stuff:
149 hir::ExprKind::MethodCall(_, method_span, ref args, fn_span) => {
150 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
151 let expr = method_callee(cx, expr, method_span, None);
152 let args = args.iter().map(|e| e.to_ref()).collect();
153 ExprKind::Call { ty: expr.ty, fun: expr.to_ref(), args, from_hir_call: true, fn_span }
156 hir::ExprKind::Call(ref fun, ref args) => {
157 if cx.typeck_results().is_method_call(expr) {
158 // The callee is something implementing Fn, FnMut, or FnOnce.
159 // Find the actual method implementation being called and
160 // build the appropriate UFCS call expression with the
161 // callee-object as expr parameter.
163 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
165 let method = method_callee(cx, expr, fun.span, None);
167 let arg_tys = args.iter().map(|e| cx.typeck_results().expr_ty_adjusted(e));
168 let tupled_args = Expr {
169 ty: cx.tcx.mk_tup(arg_tys),
172 kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
177 fun: method.to_ref(),
178 args: vec![fun.to_ref(), tupled_args.to_ref()],
184 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
185 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
186 expr_ty.ty_adt_def().and_then(|adt_def| match path.res {
187 Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
188 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
190 Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
196 if let Some((adt_def, index)) = adt_data {
197 let substs = cx.typeck_results().node_substs(fun.hir_id);
198 let user_provided_types = cx.typeck_results().user_provided_types();
199 let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
200 if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
205 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
207 let field_refs = args
210 .map(|(idx, e)| FieldExprRef { name: Field::new(idx), expr: e.to_ref() })
215 variant_index: index,
222 ty: cx.typeck_results().node_type(fun.hir_id),
232 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
233 ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: arg.to_ref() }
236 hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
237 ExprKind::AddressOf { mutability, arg: arg.to_ref() }
240 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
242 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
243 ExprKind::Assign { lhs: lhs.to_ref(), rhs: rhs.to_ref() }
246 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
247 if cx.typeck_results().is_method_call(expr) {
248 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
250 ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() }
254 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
255 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
260 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
261 if cx.typeck_results().is_method_call(expr) {
262 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
265 match (op.node, cx.constness) {
266 (hir::BinOpKind::And, _) => ExprKind::LogicalOp {
271 (hir::BinOpKind::Or, _) => ExprKind::LogicalOp {
278 let op = bin_op(op.node);
279 ExprKind::Binary { op, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
285 hir::ExprKind::Index(ref lhs, ref index) => {
286 if cx.typeck_results().is_method_call(expr) {
292 vec![lhs.to_ref(), index.to_ref()],
296 ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() }
300 hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
301 if cx.typeck_results().is_method_call(expr) {
302 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()], expr.span)
304 ExprKind::Deref { arg: arg.to_ref() }
308 hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
309 if cx.typeck_results().is_method_call(expr) {
310 overloaded_operator(cx, expr, vec![arg.to_ref()])
312 ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() }
316 hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
317 if cx.typeck_results().is_method_call(expr) {
318 overloaded_operator(cx, expr, vec![arg.to_ref()])
319 } else if let hir::ExprKind::Lit(ref lit) = arg.kind {
321 literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
326 ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
330 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() {
331 ty::Adt(adt, substs) => match adt.adt_kind() {
332 AdtKind::Struct | AdtKind::Union => {
333 let user_provided_types = cx.typeck_results().user_provided_types();
334 let user_ty = user_provided_types.get(expr.hir_id).copied();
335 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
338 variant_index: VariantIdx::new(0),
341 fields: field_refs(cx, fields),
342 base: base.as_ref().map(|base| FruInfo {
344 field_types: cx.typeck_results().fru_field_types()[expr.hir_id].clone(),
349 let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
351 Res::Def(DefKind::Variant, variant_id) => {
352 assert!(base.is_none());
354 let index = adt.variant_index_with_id(variant_id);
355 let user_provided_types = cx.typeck_results().user_provided_types();
356 let user_ty = user_provided_types.get(expr.hir_id).copied();
357 debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
360 variant_index: index,
363 fields: field_refs(cx, fields),
368 span_bug!(expr.span, "unexpected res: {:?}", res);
374 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
378 hir::ExprKind::Closure(..) => {
379 let closure_ty = cx.typeck_results().expr_ty(expr);
380 let (def_id, substs, movability) = match *closure_ty.kind() {
381 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
382 ty::Generator(def_id, substs, movability) => {
383 (def_id, UpvarSubsts::Generator(substs), Some(movability))
386 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
394 .flat_map(|upvars| upvars.iter())
395 .zip(substs.upvar_tys())
396 .map(|((&var_hir_id, _), ty)| capture_upvar(cx, expr, var_hir_id, ty))
398 ExprKind::Closure { closure_id: def_id, substs, upvars, movability }
401 hir::ExprKind::Path(ref qpath) => {
402 let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
403 convert_path_expr(cx, expr, res)
406 hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm {
407 template: asm.template,
413 hir::InlineAsmOperand::In { reg, ref expr } => {
414 InlineAsmOperand::In { reg, expr: expr.to_ref() }
416 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
417 InlineAsmOperand::Out {
420 expr: expr.as_ref().map(|expr| expr.to_ref()),
423 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
424 InlineAsmOperand::InOut { reg, late, expr: expr.to_ref() }
426 hir::InlineAsmOperand::SplitInOut {
431 } => InlineAsmOperand::SplitInOut {
434 in_expr: in_expr.to_ref(),
435 out_expr: out_expr.as_ref().map(|expr| expr.to_ref()),
437 hir::InlineAsmOperand::Const { ref expr } => {
438 InlineAsmOperand::Const { expr: expr.to_ref() }
440 hir::InlineAsmOperand::Sym { ref expr } => {
441 let qpath = match expr.kind {
442 hir::ExprKind::Path(ref qpath) => qpath,
445 "asm `sym` operand should be a path, found {:?}",
450 cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
451 let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
454 Res::Def(DefKind::Fn, _) | Res::Def(DefKind::AssocFn, _) => {
455 ty = cx.typeck_results().node_type(expr.hir_id);
456 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
457 InlineAsmOperand::SymFn {
462 kind: ExprKind::Literal {
463 literal: ty::Const::zero_sized(cx.tcx, ty),
472 Res::Def(DefKind::Static, def_id) => {
473 InlineAsmOperand::SymStatic { def_id }
477 cx.tcx.sess.span_err(
479 "asm `sym` operand must point to a fn or static",
482 // Not a real fn, but we're not reaching codegen anyways...
483 ty = cx.tcx.ty_error();
484 InlineAsmOperand::SymFn {
489 kind: ExprKind::Literal {
490 literal: ty::Const::zero_sized(cx.tcx, ty),
503 options: asm.options,
504 line_spans: asm.line_spans,
507 hir::ExprKind::LlvmInlineAsm(ref asm) => ExprKind::LlvmInlineAsm {
509 outputs: asm.outputs_exprs.to_ref(),
510 inputs: asm.inputs_exprs.to_ref(),
513 hir::ExprKind::ConstBlock(ref anon_const) => {
514 let anon_const_def_id = cx.tcx.hir().local_def_id(anon_const.hir_id);
515 let value = ty::Const::from_anon_const(cx.tcx, anon_const_def_id);
517 ExprKind::ConstBlock { value }
519 // Now comes the rote stuff:
520 hir::ExprKind::Repeat(ref v, ref count) => {
521 let count_def_id = cx.tcx.hir().local_def_id(count.hir_id);
522 let count = ty::Const::from_anon_const(cx.tcx, count_def_id);
524 ExprKind::Repeat { value: v.to_ref(), count }
526 hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
527 hir::ExprKind::Break(dest, ref value) => match dest.target_id {
528 Ok(target_id) => ExprKind::Break {
529 label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
530 value: value.to_ref(),
532 Err(err) => bug!("invalid loop id for break: {}", err),
534 hir::ExprKind::Continue(dest) => match dest.target_id {
535 Ok(loop_id) => ExprKind::Continue {
536 label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node },
538 Err(err) => bug!("invalid loop id for continue: {}", err),
540 hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match {
541 scrutinee: discr.to_ref(),
542 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
544 hir::ExprKind::Loop(ref body, _, _) => {
545 ExprKind::Loop { body: block::to_expr_ref(cx, body) }
547 hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
548 lhs: source.to_ref(),
549 name: Field::new(cx.tcx.field_index(expr.hir_id, cx.typeck_results)),
551 hir::ExprKind::Cast(ref source, ref cast_ty) => {
552 // Check for a user-given type annotation on this `cast`
553 let user_provided_types = cx.typeck_results.user_provided_types();
554 let user_ty = user_provided_types.get(cast_ty.hir_id);
557 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
558 expr, cast_ty.hir_id, user_ty,
561 // Check to see if this cast is a "coercion cast", where the cast is actually done
562 // using a coercion (or is a no-op).
563 let cast = if cx.typeck_results().is_coercion_cast(source.hir_id) {
564 // Convert the lexpr to a vexpr.
565 ExprKind::Use { source: source.to_ref() }
566 } else if cx.typeck_results().expr_ty(source).is_region_ptr() {
567 // Special cased so that we can type check that the element
568 // type of the source matches the pointed to type of the
570 ExprKind::Pointer { source: source.to_ref(), cast: PointerCast::ArrayToPointer }
572 // check whether this is casting an enum variant discriminant
573 // to prevent cycles, we refer to the discriminant initializer
574 // which is always an integer and thus doesn't need to know the
575 // enum's layout (or its tag type) to compute it during const eval
579 // B = A as isize + 4,
581 // The correct solution would be to add symbolic computations to miri,
582 // so we wouldn't have to compute and store the actual value
583 let var = if let hir::ExprKind::Path(ref qpath) = source.kind {
584 let res = cx.typeck_results().qpath_res(qpath, source.hir_id);
585 cx.typeck_results().node_type(source.hir_id).ty_adt_def().and_then(|adt_def| {
588 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
591 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
592 let (d, o) = adt_def.discriminant_def_for_variant(idx);
593 use rustc_middle::ty::util::IntTypeExt;
594 let ty = adt_def.repr.discr_type();
595 let ty = ty.to_ty(cx.tcx());
605 let source = if let Some((did, offset, var_ty)) = var {
606 let mk_const = |literal| {
611 kind: ExprKind::Literal { literal, user_ty: None, const_id: None },
615 let offset = mk_const(ty::Const::from_bits(
618 cx.param_env.and(var_ty),
622 // in case we are offsetting from a computed discriminant
623 // and not the beginning of discriminants (which is always `0`)
624 let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
625 let lhs = mk_const(cx.tcx().mk_const(ty::Const {
626 val: ty::ConstKind::Unevaluated(
627 ty::WithOptConstParam::unknown(did),
633 let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
634 Expr { temp_lifetime, ty: var_ty, span: expr.span, kind: bin }.to_ref()
642 ExprKind::Cast { source }
645 if let Some(user_ty) = user_ty {
646 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
647 // inefficient, revisit this when performance becomes an issue.
648 let cast_expr = Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind: cast };
649 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
651 ExprKind::ValueTypeAscription {
652 source: cast_expr.to_ref(),
653 user_ty: Some(*user_ty),
659 hir::ExprKind::Type(ref source, ref ty) => {
660 let user_provided_types = cx.typeck_results.user_provided_types();
661 let user_ty = user_provided_types.get(ty.hir_id).copied();
662 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
663 if source.is_syntactic_place_expr() {
664 ExprKind::PlaceTypeAscription { source: source.to_ref(), user_ty }
666 ExprKind::ValueTypeAscription { source: source.to_ref(), user_ty }
669 hir::ExprKind::DropTemps(ref source) => ExprKind::Use { source: source.to_ref() },
670 hir::ExprKind::Box(ref value) => ExprKind::Box { value: value.to_ref() },
671 hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
672 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
674 hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: v.to_ref() },
675 hir::ExprKind::Err => unreachable!(),
678 Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind }
681 fn user_substs_applied_to_res<'tcx>(
682 cx: &mut Cx<'_, 'tcx>,
685 ) -> Option<ty::CanonicalUserType<'tcx>> {
686 debug!("user_substs_applied_to_res: res={:?}", res);
687 let user_provided_type = match res {
688 // A reference to something callable -- e.g., a fn, method, or
689 // a tuple-struct or tuple-variant. This has the type of a
690 // `Fn` but with the user-given substitutions.
691 Res::Def(DefKind::Fn, _)
692 | Res::Def(DefKind::AssocFn, _)
693 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
694 | Res::Def(DefKind::Const, _)
695 | Res::Def(DefKind::AssocConst, _) => {
696 cx.typeck_results().user_provided_types().get(hir_id).copied()
699 // A unit struct/variant which is used as a value (e.g.,
700 // `None`). This has the type of the enum/struct that defines
701 // this variant -- but with the substitutions given by the
703 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
704 cx.user_substs_applied_to_ty_of_hir_id(hir_id)
707 // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
708 Res::SelfCtor(_) => cx.user_substs_applied_to_ty_of_hir_id(hir_id),
710 _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
712 debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
716 fn method_callee<'a, 'tcx>(
717 cx: &mut Cx<'a, 'tcx>,
718 expr: &hir::Expr<'_>,
720 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
722 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
723 let (def_id, substs, user_ty) = match overloaded_callee {
724 Some((def_id, substs)) => (def_id, substs, None),
726 let (kind, def_id) = cx
728 .type_dependent_def(expr.hir_id)
729 .unwrap_or_else(|| span_bug!(expr.span, "no type-dependent def for method callee"));
730 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id));
731 debug!("method_callee: user_ty={:?}", user_ty);
732 (def_id, cx.typeck_results().node_substs(expr.hir_id), user_ty)
735 let ty = cx.tcx().mk_fn_def(def_id, substs);
740 kind: ExprKind::Literal {
741 literal: ty::Const::zero_sized(cx.tcx(), ty),
749 fn to_borrow_kind(&self) -> BorrowKind;
752 impl ToBorrowKind for AutoBorrowMutability {
753 fn to_borrow_kind(&self) -> BorrowKind {
754 use rustc_middle::ty::adjustment::AllowTwoPhase;
756 AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
757 allow_two_phase_borrow: match allow_two_phase_borrow {
758 AllowTwoPhase::Yes => true,
759 AllowTwoPhase::No => false,
762 AutoBorrowMutability::Not => BorrowKind::Shared,
767 impl ToBorrowKind for hir::Mutability {
768 fn to_borrow_kind(&self) -> BorrowKind {
770 hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
771 hir::Mutability::Not => BorrowKind::Shared,
776 fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'tcx> {
778 pattern: cx.pattern_from_hir(&arm.pat),
779 guard: arm.guard.as_ref().map(|g| match g {
780 hir::Guard::If(ref e) => Guard::If(e.to_ref()),
781 hir::Guard::IfLet(ref pat, ref e) => Guard::IfLet(cx.pattern_from_hir(pat), e.to_ref()),
783 body: arm.body.to_ref(),
784 lint_level: LintLevel::Explicit(arm.hir_id),
785 scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node },
790 fn convert_path_expr<'a, 'tcx>(
791 cx: &mut Cx<'a, 'tcx>,
792 expr: &'tcx hir::Expr<'tcx>,
794 ) -> ExprKind<'tcx> {
795 let substs = cx.typeck_results().node_substs(expr.hir_id);
797 // A regular function, constructor function or a constant.
798 Res::Def(DefKind::Fn, _)
799 | Res::Def(DefKind::AssocFn, _)
800 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
801 | Res::SelfCtor(..) => {
802 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
803 debug!("convert_path_expr: user_ty={:?}", user_ty);
805 literal: ty::Const::zero_sized(cx.tcx, cx.typeck_results().node_type(expr.hir_id)),
811 Res::Def(DefKind::ConstParam, def_id) => {
812 let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
813 let item_id = cx.tcx.hir().get_parent_node(hir_id);
814 let item_def_id = cx.tcx.hir().local_def_id(item_id);
815 let generics = cx.tcx.generics_of(item_def_id);
816 let local_def_id = cx.tcx.hir().local_def_id(hir_id);
817 let index = generics.param_def_id_to_index[&local_def_id.to_def_id()];
818 let name = cx.tcx.hir().name(hir_id);
819 let val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
823 .mk_const(ty::Const { val, ty: cx.typeck_results().node_type(expr.hir_id) }),
825 const_id: Some(def_id),
829 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
830 let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
831 debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
833 literal: cx.tcx.mk_const(ty::Const {
834 val: ty::ConstKind::Unevaluated(
835 ty::WithOptConstParam::unknown(def_id),
839 ty: cx.typeck_results().node_type(expr.hir_id),
842 const_id: Some(def_id),
846 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
847 let user_provided_types = cx.typeck_results.user_provided_types();
848 let user_provided_type = user_provided_types.get(expr.hir_id).copied();
849 debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
850 let ty = cx.typeck_results().node_type(expr.hir_id);
852 // A unit struct/variant which is used as a value.
853 // We return a completely different ExprKind here to account for this special case.
854 ty::Adt(adt_def, substs) => ExprKind::Adt {
856 variant_index: adt_def.variant_index_with_ctor_id(def_id),
858 user_ty: user_provided_type,
862 _ => bug!("unexpected ty: {:?}", ty),
866 // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is
867 // a constant reference (or constant raw pointer for `static mut`) in MIR
868 Res::Def(DefKind::Static, id) => {
869 let ty = cx.tcx.static_ptr_ty(id);
870 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
871 let kind = if cx.tcx.is_thread_local_static(id) {
872 ExprKind::ThreadLocalRef(id)
874 let ptr = cx.tcx.create_static_alloc(id);
875 ExprKind::StaticRef {
876 literal: ty::Const::from_scalar(cx.tcx, Scalar::Ptr(ptr.into()), ty),
880 ExprKind::Deref { arg: Expr { ty, temp_lifetime, span: expr.span, kind }.to_ref() }
883 Res::Local(var_hir_id) => convert_var(cx, var_hir_id),
885 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
889 fn convert_var<'tcx>(cx: &mut Cx<'_, 'tcx>, var_hir_id: hir::HirId) -> ExprKind<'tcx> {
890 // We want upvars here not captures.
891 // Captures will be handled in MIR.
894 .upvars_mentioned(cx.body_owner)
895 .map_or(false, |upvars| upvars.contains_key(&var_hir_id));
897 debug!("convert_var({:?}): is_upvar={}, body_owner={:?}", var_hir_id, is_upvar, cx.body_owner);
900 ExprKind::UpvarRef { closure_def_id: cx.body_owner, var_hir_id }
902 ExprKind::VarRef { id: var_hir_id }
906 fn bin_op(op: hir::BinOpKind) -> BinOp {
908 hir::BinOpKind::Add => BinOp::Add,
909 hir::BinOpKind::Sub => BinOp::Sub,
910 hir::BinOpKind::Mul => BinOp::Mul,
911 hir::BinOpKind::Div => BinOp::Div,
912 hir::BinOpKind::Rem => BinOp::Rem,
913 hir::BinOpKind::BitXor => BinOp::BitXor,
914 hir::BinOpKind::BitAnd => BinOp::BitAnd,
915 hir::BinOpKind::BitOr => BinOp::BitOr,
916 hir::BinOpKind::Shl => BinOp::Shl,
917 hir::BinOpKind::Shr => BinOp::Shr,
918 hir::BinOpKind::Eq => BinOp::Eq,
919 hir::BinOpKind::Lt => BinOp::Lt,
920 hir::BinOpKind::Le => BinOp::Le,
921 hir::BinOpKind::Ne => BinOp::Ne,
922 hir::BinOpKind::Ge => BinOp::Ge,
923 hir::BinOpKind::Gt => BinOp::Gt,
924 _ => bug!("no equivalent for ast binop {:?}", op),
928 fn overloaded_operator<'a, 'tcx>(
929 cx: &mut Cx<'a, 'tcx>,
930 expr: &'tcx hir::Expr<'tcx>,
931 args: Vec<ExprRef<'tcx>>,
932 ) -> ExprKind<'tcx> {
933 let fun = method_callee(cx, expr, expr.span, None);
934 ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false, fn_span: expr.span }
937 fn overloaded_place<'a, 'tcx>(
938 cx: &mut Cx<'a, 'tcx>,
939 expr: &'tcx hir::Expr<'tcx>,
941 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
942 args: Vec<ExprRef<'tcx>>,
944 ) -> ExprKind<'tcx> {
945 // For an overloaded *x or x[y] expression of type T, the method
946 // call returns an &T and we must add the deref so that the types
947 // line up (this is because `*x` and `x[y]` represent places):
949 let recv_ty = match args[0] {
950 ExprRef::Thir(e) => cx.typeck_results().expr_ty_adjusted(e),
951 ExprRef::Mirror(ref e) => e.ty,
954 // Reconstruct the output assuming it's a reference with the
955 // same region and mutability as the receiver. This holds for
956 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
957 let (region, mutbl) = match *recv_ty.kind() {
958 ty::Ref(region, _, mutbl) => (region, mutbl),
959 _ => span_bug!(span, "overloaded_place: receiver is not a reference"),
961 let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
963 // construct the complete expression `foo()` for the overloaded call,
964 // which will yield the &T type
965 let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
966 let fun = method_callee(cx, expr, span, overloaded_callee);
967 let ref_expr = Expr {
971 kind: ExprKind::Call {
975 from_hir_call: false,
980 // construct and return a deref wrapper `*foo()`
981 ExprKind::Deref { arg: ref_expr.to_ref() }
984 fn capture_upvar<'tcx>(
985 cx: &mut Cx<'_, 'tcx>,
986 closure_expr: &'tcx hir::Expr<'tcx>,
987 var_hir_id: hir::HirId,
990 let upvar_id = ty::UpvarId {
991 var_path: ty::UpvarPath { hir_id: var_hir_id },
992 closure_expr_id: cx.tcx.hir().local_def_id(closure_expr.hir_id),
994 let upvar_capture = cx.typeck_results().upvar_capture(upvar_id);
995 let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
996 let var_ty = cx.typeck_results().node_type(var_hir_id);
997 let captured_var = Expr {
1000 span: closure_expr.span,
1001 kind: convert_var(cx, var_hir_id),
1003 match upvar_capture {
1004 ty::UpvarCapture::ByValue(_) => captured_var.to_ref(),
1005 ty::UpvarCapture::ByRef(upvar_borrow) => {
1006 let borrow_kind = match upvar_borrow.kind {
1007 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1008 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1009 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false },
1014 span: closure_expr.span,
1015 kind: ExprKind::Borrow { borrow_kind, arg: captured_var.to_ref() },
1022 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1023 fn field_refs<'a, 'tcx>(
1024 cx: &mut Cx<'a, 'tcx>,
1025 fields: &'tcx [hir::Field<'tcx>],
1026 ) -> Vec<FieldExprRef<'tcx>> {
1029 .map(|field| FieldExprRef {
1030 name: Field::new(cx.tcx.field_index(field.hir_id, cx.typeck_results)),
1031 expr: field.expr.to_ref(),