1 use crate::thir::cx::Cx;
2 use crate::thir::util::UserAnnotatedTyHelpers;
3 use rustc_data_structures::stack::ensure_sufficient_stack;
5 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
6 use rustc_index::vec::Idx;
7 use rustc_middle::hir::place::Place as HirPlace;
8 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
9 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::interpret::Scalar;
12 use rustc_middle::mir::{BinOp, BorrowKind, Field, UnOp};
13 use rustc_middle::thir::*;
14 use rustc_middle::ty::adjustment::{
15 Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
17 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
18 use rustc_middle::ty::{self, AdtKind, Ty, UpvarSubsts, UserType};
19 use rustc_span::def_id::DefId;
21 use rustc_target::abi::VariantIdx;
24 crate fn mirror_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) -> ExprId {
25 // `mirror_expr` is recursing very deep. Make sure the stack doesn't overflow.
26 ensure_sufficient_stack(|| self.mirror_expr_inner(expr))
29 crate fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> {
30 exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect()
33 pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId {
34 let temp_lifetime = self.region_scope_tree.temporary_scope(hir_expr.hir_id.local_id);
36 region::Scope { id: hir_expr.hir_id.local_id, data: region::ScopeData::Node };
38 debug!("Expr::make_mirror(): id={}, span={:?}", hir_expr.hir_id, hir_expr.span);
40 let mut expr = self.make_mirror_unadjusted(hir_expr);
42 let adjustment_span = match self.adjustment_span {
43 Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span),
47 // Now apply adjustments, if any.
48 for adjustment in self.typeck_results.expr_adjustments(hir_expr) {
49 debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment);
52 self.apply_adjustment(hir_expr, expr, adjustment, adjustment_span.unwrap_or(span));
55 // Next, wrap this up in the expr's scope.
60 kind: ExprKind::Scope {
61 region_scope: expr_scope,
62 value: self.thir.exprs.push(expr),
63 lint_level: LintLevel::Explicit(hir_expr.hir_id),
67 // Finally, create a destruction scope, if any.
68 if let Some(region_scope) =
69 self.region_scope_tree.opt_destruction_scope(hir_expr.hir_id.local_id)
75 kind: ExprKind::Scope {
77 value: self.thir.exprs.push(expr),
78 lint_level: LintLevel::Inherited,
84 self.thir.exprs.push(expr)
89 hir_expr: &'tcx hir::Expr<'tcx>,
91 adjustment: &Adjustment<'tcx>,
94 let Expr { temp_lifetime, .. } = expr;
96 // Adjust the span from the block, to the last expression of the
97 // block. This is a better span when returning a mutable reference
98 // with too short a lifetime. The error message will use the span
99 // from the assignment to the return place, which should only point
100 // at the returned value, not the entire function body.
102 // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
104 // // ^ error message points at this expression.
106 let mut adjust_span = |expr: &mut Expr<'tcx>| {
107 if let ExprKind::Block { body } = &expr.kind {
108 if let Some(last_expr) = body.expr {
109 span = self.thir[last_expr].span;
115 let kind = match adjustment.kind {
116 Adjust::Pointer(PointerCast::Unsize) => {
117 adjust_span(&mut expr);
118 ExprKind::Pointer { cast: PointerCast::Unsize, source: self.thir.exprs.push(expr) }
120 Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: self.thir.exprs.push(expr) },
121 Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) },
122 Adjust::Deref(None) => {
123 adjust_span(&mut expr);
124 ExprKind::Deref { arg: self.thir.exprs.push(expr) }
126 Adjust::Deref(Some(deref)) => {
127 // We don't need to do call adjust_span here since
128 // deref coercions always start with a built-in deref.
129 let call = deref.method_call(self.tcx(), expr.ty);
135 .mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }),
137 kind: ExprKind::Borrow {
138 borrow_kind: deref.mutbl.to_borrow_kind(),
139 arg: self.thir.exprs.push(expr),
143 let expr = Box::new([self.thir.exprs.push(expr)]);
145 self.overloaded_place(hir_expr, adjustment.target, Some(call), expr, deref.span)
147 Adjust::Borrow(AutoBorrow::Ref(_, m)) => ExprKind::Borrow {
148 borrow_kind: m.to_borrow_kind(),
149 arg: self.thir.exprs.push(expr),
151 Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
152 ExprKind::AddressOf { mutability, arg: self.thir.exprs.push(expr) }
156 Expr { temp_lifetime, ty: adjustment.target, span, kind }
159 fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> {
160 let expr_ty = self.typeck_results().expr_ty(expr);
161 let expr_span = expr.span;
162 let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
164 let kind = match expr.kind {
165 // Here comes the interesting stuff:
166 hir::ExprKind::MethodCall(_, method_span, ref args, fn_span) => {
167 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
168 let expr = self.method_callee(expr, method_span, None);
169 // When we apply adjustments to the receiver, use the span of
170 // the overall method call for better diagnostics. args[0]
171 // is guaranteed to exist, since a method call always has a receiver.
172 let old_adjustment_span = self.adjustment_span.replace((args[0].hir_id, expr_span));
173 tracing::info!("Using method span: {:?}", expr.span);
174 let args = self.mirror_exprs(args);
175 self.adjustment_span = old_adjustment_span;
178 fun: self.thir.exprs.push(expr),
185 hir::ExprKind::Call(ref fun, ref args) => {
186 if self.typeck_results().is_method_call(expr) {
187 // The callee is something implementing Fn, FnMut, or FnOnce.
188 // Find the actual method implementation being called and
189 // build the appropriate UFCS call expression with the
190 // callee-object as expr parameter.
192 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
194 let method = self.method_callee(expr, fun.span, None);
196 let arg_tys = args.iter().map(|e| self.typeck_results().expr_ty_adjusted(e));
197 let tupled_args = Expr {
198 ty: self.tcx.mk_tup(arg_tys),
201 kind: ExprKind::Tuple { fields: self.mirror_exprs(args) },
203 let tupled_args = self.thir.exprs.push(tupled_args);
207 fun: self.thir.exprs.push(method),
208 args: Box::new([self.mirror_expr(fun), tupled_args]),
214 if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
215 // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
216 expr_ty.ty_adt_def().and_then(|adt_def| match path.res {
217 Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
218 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
220 Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
226 if let Some((adt_def, index)) = adt_data {
227 let substs = self.typeck_results().node_substs(fun.hir_id);
228 let user_provided_types = self.typeck_results().user_provided_types();
230 user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
231 if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
236 debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
238 let field_refs = args
241 .map(|(idx, e)| FieldExpr {
242 name: Field::new(idx),
243 expr: self.mirror_expr(e),
246 ExprKind::Adt(Box::new(Adt {
249 variant_index: index,
256 ty: self.typeck_results().node_type(fun.hir_id),
257 fun: self.mirror_expr(fun),
258 args: self.mirror_exprs(args),
266 hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
267 ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: self.mirror_expr(arg) }
270 hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
271 ExprKind::AddressOf { mutability, arg: self.mirror_expr(arg) }
274 hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: self.mirror_block(blk) },
276 hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
277 ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) }
280 hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
281 if self.typeck_results().is_method_call(expr) {
282 let lhs = self.mirror_expr(lhs);
283 let rhs = self.mirror_expr(rhs);
284 self.overloaded_operator(expr, Box::new([lhs, rhs]))
288 lhs: self.mirror_expr(lhs),
289 rhs: self.mirror_expr(rhs),
294 hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
295 literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false),
300 hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
301 if self.typeck_results().is_method_call(expr) {
302 let lhs = self.mirror_expr(lhs);
303 let rhs = self.mirror_expr(rhs);
304 self.overloaded_operator(expr, Box::new([lhs, rhs]))
308 hir::BinOpKind::And => ExprKind::LogicalOp {
310 lhs: self.mirror_expr(lhs),
311 rhs: self.mirror_expr(rhs),
313 hir::BinOpKind::Or => ExprKind::LogicalOp {
315 lhs: self.mirror_expr(lhs),
316 rhs: self.mirror_expr(rhs),
320 let op = bin_op(op.node);
323 lhs: self.mirror_expr(lhs),
324 rhs: self.mirror_expr(rhs),
331 hir::ExprKind::Index(ref lhs, ref index) => {
332 if self.typeck_results().is_method_call(expr) {
333 let lhs = self.mirror_expr(lhs);
334 let index = self.mirror_expr(index);
335 self.overloaded_place(expr, expr_ty, None, Box::new([lhs, index]), expr.span)
337 ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) }
341 hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => {
342 if self.typeck_results().is_method_call(expr) {
343 let arg = self.mirror_expr(arg);
344 self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span)
346 ExprKind::Deref { arg: self.mirror_expr(arg) }
350 hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => {
351 if self.typeck_results().is_method_call(expr) {
352 let arg = self.mirror_expr(arg);
353 self.overloaded_operator(expr, Box::new([arg]))
355 ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) }
359 hir::ExprKind::Unary(hir::UnOp::Neg, ref arg) => {
360 if self.typeck_results().is_method_call(expr) {
361 let arg = self.mirror_expr(arg);
362 self.overloaded_operator(expr, Box::new([arg]))
363 } else if let hir::ExprKind::Lit(ref lit) = arg.kind {
365 literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, true),
370 ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) }
374 hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() {
375 ty::Adt(adt, substs) => match adt.adt_kind() {
376 AdtKind::Struct | AdtKind::Union => {
377 let user_provided_types = self.typeck_results().user_provided_types();
378 let user_ty = user_provided_types.get(expr.hir_id).copied();
379 debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
380 ExprKind::Adt(Box::new(Adt {
382 variant_index: VariantIdx::new(0),
385 fields: self.field_refs(fields),
386 base: base.as_ref().map(|base| FruInfo {
387 base: self.mirror_expr(base),
388 field_types: self.typeck_results().fru_field_types()[expr.hir_id]
396 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
398 Res::Def(DefKind::Variant, variant_id) => {
399 assert!(base.is_none());
401 let index = adt.variant_index_with_id(variant_id);
402 let user_provided_types =
403 self.typeck_results().user_provided_types();
404 let user_ty = user_provided_types.get(expr.hir_id).copied();
405 debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
406 ExprKind::Adt(Box::new(Adt {
408 variant_index: index,
411 fields: self.field_refs(fields),
416 span_bug!(expr.span, "unexpected res: {:?}", res);
422 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
426 hir::ExprKind::Closure(..) => {
427 let closure_ty = self.typeck_results().expr_ty(expr);
428 let (def_id, substs, movability) = match *closure_ty.kind() {
429 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
430 ty::Generator(def_id, substs, movability) => {
431 (def_id, UpvarSubsts::Generator(substs), Some(movability))
434 span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
440 .closure_min_captures_flattened(def_id)
441 .zip(substs.upvar_tys())
442 .map(|(captured_place, ty)| {
443 let upvars = self.capture_upvar(expr, captured_place, ty);
444 self.thir.exprs.push(upvars)
448 // Convert the closure fake reads, if any, from hir `Place` to ExprRef
449 let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) {
450 Some(fake_reads) => fake_reads
452 .map(|(place, cause, hir_id)| {
453 let expr = self.convert_captured_hir_place(expr, place.clone());
454 (self.thir.exprs.push(expr), *cause, *hir_id)
460 ExprKind::Closure { closure_id: def_id, substs, upvars, movability, fake_reads }
463 hir::ExprKind::Path(ref qpath) => {
464 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
465 self.convert_path_expr(expr, res)
468 hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm {
469 template: asm.template,
473 .map(|(op, _op_sp)| {
475 hir::InlineAsmOperand::In { reg, ref expr } => {
476 InlineAsmOperand::In { reg, expr: self.mirror_expr(expr) }
478 hir::InlineAsmOperand::Out { reg, late, ref expr } => {
479 InlineAsmOperand::Out {
482 expr: expr.as_ref().map(|expr| self.mirror_expr(expr)),
485 hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
486 InlineAsmOperand::InOut { reg, late, expr: self.mirror_expr(expr) }
488 hir::InlineAsmOperand::SplitInOut {
493 } => InlineAsmOperand::SplitInOut {
496 in_expr: self.mirror_expr(in_expr),
497 out_expr: out_expr.as_ref().map(|expr| self.mirror_expr(expr)),
499 hir::InlineAsmOperand::Const { ref anon_const } => {
500 let anon_const_def_id =
501 self.tcx.hir().local_def_id(anon_const.hir_id);
502 let value = ty::Const::from_anon_const(self.tcx, anon_const_def_id);
503 let span = self.tcx.hir().span(anon_const.hir_id);
505 InlineAsmOperand::Const { value, span }
507 hir::InlineAsmOperand::Sym { ref expr } => {
508 let qpath = match expr.kind {
509 hir::ExprKind::Path(ref qpath) => qpath,
512 "asm `sym` operand should be a path, found {:?}",
517 self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
518 let res = self.typeck_results().qpath_res(qpath, expr.hir_id);
521 Res::Def(DefKind::Fn, _) | Res::Def(DefKind::AssocFn, _) => {
522 ty = self.typeck_results().node_type(expr.hir_id);
524 self.user_substs_applied_to_res(expr.hir_id, res);
525 InlineAsmOperand::SymFn {
526 expr: self.thir.exprs.push(Expr {
530 kind: ExprKind::Literal {
531 literal: ty::Const::zero_sized(self.tcx, ty),
539 Res::Def(DefKind::Static, def_id) => {
540 InlineAsmOperand::SymStatic { def_id }
544 self.tcx.sess.span_err(
546 "asm `sym` operand must point to a fn or static",
549 // Not a real fn, but we're not reaching codegen anyways...
550 ty = self.tcx.ty_error();
551 InlineAsmOperand::SymFn {
552 expr: self.thir.exprs.push(Expr {
556 kind: ExprKind::Literal {
557 literal: ty::Const::zero_sized(self.tcx, ty),
569 options: asm.options,
570 line_spans: asm.line_spans,
573 hir::ExprKind::LlvmInlineAsm(ref asm) => ExprKind::LlvmInlineAsm {
575 outputs: self.mirror_exprs(asm.outputs_exprs),
576 inputs: self.mirror_exprs(asm.inputs_exprs),
579 hir::ExprKind::ConstBlock(ref anon_const) => {
580 let anon_const_def_id = self.tcx.hir().local_def_id(anon_const.hir_id);
581 let value = ty::Const::from_anon_const(self.tcx, anon_const_def_id);
583 ExprKind::ConstBlock { value }
585 // Now comes the rote stuff:
586 hir::ExprKind::Repeat(ref v, ref count) => {
587 let count_def_id = self.tcx.hir().local_def_id(count.hir_id);
588 let count = ty::Const::from_anon_const(self.tcx, count_def_id);
590 ExprKind::Repeat { value: self.mirror_expr(v), count }
592 hir::ExprKind::Ret(ref v) => {
593 ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) }
595 hir::ExprKind::Break(dest, ref value) => match dest.target_id {
596 Ok(target_id) => ExprKind::Break {
597 label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
598 value: value.as_ref().map(|value| self.mirror_expr(value)),
600 Err(err) => bug!("invalid loop id for break: {}", err),
602 hir::ExprKind::Continue(dest) => match dest.target_id {
603 Ok(loop_id) => ExprKind::Continue {
604 label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node },
606 Err(err) => bug!("invalid loop id for continue: {}", err),
608 hir::ExprKind::Let(ref pat, ref expr, _) => {
609 ExprKind::Let { expr: self.mirror_expr(expr), pat: self.pattern_from_hir(pat) }
611 hir::ExprKind::If(cond, then, else_opt) => ExprKind::If {
612 if_then_scope: region::Scope {
613 id: then.hir_id.local_id,
614 data: region::ScopeData::IfThen,
616 cond: self.mirror_expr(cond),
617 then: self.mirror_expr(then),
618 else_opt: else_opt.map(|el| self.mirror_expr(el)),
620 hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match {
621 scrutinee: self.mirror_expr(discr),
622 arms: arms.iter().map(|a| self.convert_arm(a)).collect(),
624 hir::ExprKind::Loop(ref body, ..) => {
625 let block_ty = self.typeck_results().node_type(body.hir_id);
626 let temp_lifetime = self.region_scope_tree.temporary_scope(body.hir_id.local_id);
627 let block = self.mirror_block(body);
628 let body = self.thir.exprs.push(Expr {
632 kind: ExprKind::Block { body: block },
634 ExprKind::Loop { body }
636 hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
637 lhs: self.mirror_expr(source),
638 name: Field::new(self.tcx.field_index(expr.hir_id, self.typeck_results)),
640 hir::ExprKind::Cast(ref source, ref cast_ty) => {
641 // Check for a user-given type annotation on this `cast`
642 let user_provided_types = self.typeck_results.user_provided_types();
643 let user_ty = user_provided_types.get(cast_ty.hir_id);
646 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
647 expr, cast_ty.hir_id, user_ty,
650 // Check to see if this cast is a "coercion cast", where the cast is actually done
651 // using a coercion (or is a no-op).
652 let cast = if self.typeck_results().is_coercion_cast(source.hir_id) {
653 // Convert the lexpr to a vexpr.
654 ExprKind::Use { source: self.mirror_expr(source) }
655 } else if self.typeck_results().expr_ty(source).is_region_ptr() {
656 // Special cased so that we can type check that the element
657 // type of the source matches the pointed to type of the
660 source: self.mirror_expr(source),
661 cast: PointerCast::ArrayToPointer,
664 // check whether this is casting an enum variant discriminant
665 // to prevent cycles, we refer to the discriminant initializer
666 // which is always an integer and thus doesn't need to know the
667 // enum's layout (or its tag type) to compute it during const eval
671 // B = A as isize + 4,
673 // The correct solution would be to add symbolic computations to miri,
674 // so we wouldn't have to compute and store the actual value
675 let var = if let hir::ExprKind::Path(ref qpath) = source.kind {
676 let res = self.typeck_results().qpath_res(qpath, source.hir_id);
677 self.typeck_results().node_type(source.hir_id).ty_adt_def().and_then(
678 |adt_def| match res {
680 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
683 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
684 let (d, o) = adt_def.discriminant_def_for_variant(idx);
685 use rustc_middle::ty::util::IntTypeExt;
686 let ty = adt_def.repr.discr_type();
687 let ty = ty.to_ty(self.tcx());
697 let source = if let Some((did, offset, var_ty)) = var {
698 let mk_const = |literal| Expr {
702 kind: ExprKind::Literal { literal, user_ty: None, const_id: None },
704 let offset = self.thir.exprs.push(mk_const(ty::Const::from_bits(
707 self.param_env.and(var_ty),
711 // in case we are offsetting from a computed discriminant
712 // and not the beginning of discriminants (which is always `0`)
713 let substs = InternalSubsts::identity_for_item(self.tcx(), did);
714 let lhs = ty::Const {
715 val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(
716 ty::WithOptConstParam::unknown(did),
721 let lhs = self.thir.exprs.push(mk_const(self.tcx().mk_const(lhs)));
723 ExprKind::Binary { op: BinOp::Add, lhs: lhs, rhs: offset };
724 self.thir.exprs.push(Expr {
734 self.mirror_expr(source)
737 ExprKind::Cast { source: 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 = self.thir.exprs.push(Expr {
749 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
751 ExprKind::ValueTypeAscription { source: cast_expr, user_ty: Some(*user_ty) }
756 hir::ExprKind::Type(ref source, ref ty) => {
757 let user_provided_types = self.typeck_results.user_provided_types();
758 let user_ty = user_provided_types.get(ty.hir_id).copied();
759 debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
760 let mirrored = self.mirror_expr(source);
761 if source.is_syntactic_place_expr() {
762 ExprKind::PlaceTypeAscription { source: mirrored, user_ty }
764 ExprKind::ValueTypeAscription { source: mirrored, user_ty }
767 hir::ExprKind::DropTemps(ref source) => {
768 ExprKind::Use { source: self.mirror_expr(source) }
770 hir::ExprKind::Box(ref value) => ExprKind::Box { value: self.mirror_expr(value) },
771 hir::ExprKind::Array(ref fields) => {
772 ExprKind::Array { fields: self.mirror_exprs(fields) }
774 hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: self.mirror_exprs(fields) },
776 hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: self.mirror_expr(v) },
777 hir::ExprKind::Err => unreachable!(),
780 Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind }
783 fn user_substs_applied_to_res(
787 ) -> Option<ty::CanonicalUserType<'tcx>> {
788 debug!("user_substs_applied_to_res: res={:?}", res);
789 let user_provided_type = match res {
790 // A reference to something callable -- e.g., a fn, method, or
791 // a tuple-struct or tuple-variant. This has the type of a
792 // `Fn` but with the user-given substitutions.
793 Res::Def(DefKind::Fn, _)
794 | Res::Def(DefKind::AssocFn, _)
795 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
796 | Res::Def(DefKind::Const, _)
797 | Res::Def(DefKind::AssocConst, _) => {
798 self.typeck_results().user_provided_types().get(hir_id).copied()
801 // A unit struct/variant which is used as a value (e.g.,
802 // `None`). This has the type of the enum/struct that defines
803 // this variant -- but with the substitutions given by the
805 Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
806 self.user_substs_applied_to_ty_of_hir_id(hir_id)
809 // `Self` is used in expression as a tuple struct constructor or a unit struct constructor
810 Res::SelfCtor(_) => self.user_substs_applied_to_ty_of_hir_id(hir_id),
812 _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
814 debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
820 expr: &hir::Expr<'_>,
822 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
824 let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
825 let (def_id, substs, user_ty) = match overloaded_callee {
826 Some((def_id, substs)) => (def_id, substs, None),
829 self.typeck_results().type_dependent_def(expr.hir_id).unwrap_or_else(|| {
830 span_bug!(expr.span, "no type-dependent def for method callee")
832 let user_ty = self.user_substs_applied_to_res(expr.hir_id, Res::Def(kind, def_id));
833 debug!("method_callee: user_ty={:?}", user_ty);
834 (def_id, self.typeck_results().node_substs(expr.hir_id), user_ty)
837 let ty = self.tcx().mk_fn_def(def_id, substs);
842 kind: ExprKind::Literal {
843 literal: ty::Const::zero_sized(self.tcx(), ty),
850 fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId {
852 pattern: self.pattern_from_hir(&arm.pat),
853 guard: arm.guard.as_ref().map(|g| match g {
854 hir::Guard::If(ref e) => Guard::If(self.mirror_expr(e)),
855 hir::Guard::IfLet(ref pat, ref e) => {
856 Guard::IfLet(self.pattern_from_hir(pat), self.mirror_expr(e))
859 body: self.mirror_expr(arm.body),
860 lint_level: LintLevel::Explicit(arm.hir_id),
861 scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node },
864 self.thir.arms.push(arm)
867 fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> {
868 let substs = self.typeck_results().node_substs(expr.hir_id);
870 // A regular function, constructor function or a constant.
871 Res::Def(DefKind::Fn, _)
872 | Res::Def(DefKind::AssocFn, _)
873 | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
874 | Res::SelfCtor(..) => {
875 let user_ty = self.user_substs_applied_to_res(expr.hir_id, res);
876 debug!("convert_path_expr: user_ty={:?}", user_ty);
878 literal: ty::Const::zero_sized(
880 self.typeck_results().node_type(expr.hir_id),
887 Res::Def(DefKind::ConstParam, def_id) => {
888 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
889 let item_id = self.tcx.hir().get_parent_node(hir_id);
890 let item_def_id = self.tcx.hir().local_def_id(item_id);
891 let generics = self.tcx.generics_of(item_def_id);
892 let index = generics.param_def_id_to_index[&def_id];
893 let name = self.tcx.hir().name(hir_id);
894 let val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
896 literal: self.tcx.mk_const(ty::Const {
898 ty: self.typeck_results().node_type(expr.hir_id),
901 const_id: Some(def_id),
905 Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
906 let user_ty = self.user_substs_applied_to_res(expr.hir_id, res);
907 debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
909 literal: self.tcx.mk_const(ty::Const {
910 val: ty::ConstKind::Unevaluated(ty::Unevaluated::new(
911 ty::WithOptConstParam::unknown(def_id),
914 ty: self.typeck_results().node_type(expr.hir_id),
917 const_id: Some(def_id),
921 Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
922 let user_provided_types = self.typeck_results.user_provided_types();
923 let user_provided_type = user_provided_types.get(expr.hir_id).copied();
924 debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
925 let ty = self.typeck_results().node_type(expr.hir_id);
927 // A unit struct/variant which is used as a value.
928 // We return a completely different ExprKind here to account for this special case.
929 ty::Adt(adt_def, substs) => ExprKind::Adt(Box::new(Adt {
931 variant_index: adt_def.variant_index_with_ctor_id(def_id),
933 user_ty: user_provided_type,
934 fields: Box::new([]),
937 _ => bug!("unexpected ty: {:?}", ty),
941 // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is
942 // a constant reference (or constant raw pointer for `static mut`) in MIR
943 Res::Def(DefKind::Static, id) => {
944 let ty = self.tcx.static_ptr_ty(id);
945 let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
946 let kind = if self.tcx.is_thread_local_static(id) {
947 ExprKind::ThreadLocalRef(id)
949 let ptr = self.tcx.create_static_alloc(id);
950 ExprKind::StaticRef {
951 literal: ty::Const::from_scalar(
953 Scalar::from_pointer(ptr.into(), &self.tcx),
960 arg: self.thir.exprs.push(Expr { ty, temp_lifetime, span: expr.span, kind }),
964 Res::Local(var_hir_id) => self.convert_var(var_hir_id),
966 _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
970 fn convert_var(&mut self, var_hir_id: hir::HirId) -> ExprKind<'tcx> {
971 // We want upvars here not captures.
972 // Captures will be handled in MIR.
975 .upvars_mentioned(self.body_owner)
976 .map_or(false, |upvars| upvars.contains_key(&var_hir_id));
979 "convert_var({:?}): is_upvar={}, body_owner={:?}",
980 var_hir_id, is_upvar, self.body_owner
984 ExprKind::UpvarRef { closure_def_id: self.body_owner, var_hir_id }
986 ExprKind::VarRef { id: var_hir_id }
990 fn overloaded_operator(
992 expr: &'tcx hir::Expr<'tcx>,
994 ) -> ExprKind<'tcx> {
995 let fun = self.method_callee(expr, expr.span, None);
996 let fun = self.thir.exprs.push(fun);
998 ty: self.thir[fun].ty,
1001 from_hir_call: false,
1006 fn overloaded_place(
1008 expr: &'tcx hir::Expr<'tcx>,
1010 overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
1011 args: Box<[ExprId]>,
1013 ) -> ExprKind<'tcx> {
1014 // For an overloaded *x or x[y] expression of type T, the method
1015 // call returns an &T and we must add the deref so that the types
1016 // line up (this is because `*x` and `x[y]` represent places):
1018 // Reconstruct the output assuming it's a reference with the
1019 // same region and mutability as the receiver. This holds for
1020 // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1021 let (region, mutbl) = match *self.thir[args[0]].ty.kind() {
1022 ty::Ref(region, _, mutbl) => (region, mutbl),
1023 _ => span_bug!(span, "overloaded_place: receiver is not a reference"),
1025 let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
1027 // construct the complete expression `foo()` for the overloaded call,
1028 // which will yield the &T type
1029 let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1030 let fun = self.method_callee(expr, span, overloaded_callee);
1031 let fun = self.thir.exprs.push(fun);
1032 let fun_ty = self.thir[fun].ty;
1033 let ref_expr = self.thir.exprs.push(Expr {
1037 kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span },
1040 // construct and return a deref wrapper `*foo()`
1041 ExprKind::Deref { arg: ref_expr }
1044 fn convert_captured_hir_place(
1046 closure_expr: &'tcx hir::Expr<'tcx>,
1047 place: HirPlace<'tcx>,
1049 let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1050 let var_ty = place.base_ty;
1052 // The result of capture analysis in `rustc_typeck/check/upvar.rs`represents a captured path
1053 // as it's seen for use within the closure and not at the time of closure creation.
1055 // That is we see expect to see it start from a captured upvar and not something that is local
1056 // to the closure's parent.
1057 let var_hir_id = match place.base {
1058 HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1059 base => bug!("Expected an upvar, found {:?}", base),
1062 let mut captured_place_expr = Expr {
1065 span: closure_expr.span,
1066 kind: self.convert_var(var_hir_id),
1069 for proj in place.projections.iter() {
1070 let kind = match proj.kind {
1071 HirProjectionKind::Deref => {
1072 ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) }
1074 HirProjectionKind::Field(field, ..) => {
1075 // Variant index will always be 0, because for multi-variant
1076 // enums, we capture the enum entirely.
1078 lhs: self.thir.exprs.push(captured_place_expr),
1079 name: Field::new(field as usize),
1082 HirProjectionKind::Index | HirProjectionKind::Subslice => {
1083 // We don't capture these projections, so we can ignore them here
1088 captured_place_expr =
1089 Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind };
1097 closure_expr: &'tcx hir::Expr<'tcx>,
1098 captured_place: &'tcx ty::CapturedPlace<'tcx>,
1101 let upvar_capture = captured_place.info.capture_kind;
1102 let captured_place_expr =
1103 self.convert_captured_hir_place(closure_expr, captured_place.place.clone());
1104 let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1106 match upvar_capture {
1107 ty::UpvarCapture::ByValue(_) => captured_place_expr,
1108 ty::UpvarCapture::ByRef(upvar_borrow) => {
1109 let borrow_kind = match upvar_borrow.kind {
1110 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1111 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1112 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false },
1117 span: closure_expr.span,
1118 kind: ExprKind::Borrow {
1120 arg: self.thir.exprs.push(captured_place_expr),
1127 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExpr.
1128 fn field_refs(&mut self, fields: &'tcx [hir::ExprField<'tcx>]) -> Box<[FieldExpr]> {
1131 .map(|field| FieldExpr {
1132 name: Field::new(self.tcx.field_index(field.hir_id, self.typeck_results)),
1133 expr: self.mirror_expr(field.expr),
1139 trait ToBorrowKind {
1140 fn to_borrow_kind(&self) -> BorrowKind;
1143 impl ToBorrowKind for AutoBorrowMutability {
1144 fn to_borrow_kind(&self) -> BorrowKind {
1145 use rustc_middle::ty::adjustment::AllowTwoPhase;
1147 AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
1148 allow_two_phase_borrow: match allow_two_phase_borrow {
1149 AllowTwoPhase::Yes => true,
1150 AllowTwoPhase::No => false,
1153 AutoBorrowMutability::Not => BorrowKind::Shared,
1158 impl ToBorrowKind for hir::Mutability {
1159 fn to_borrow_kind(&self) -> BorrowKind {
1161 hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
1162 hir::Mutability::Not => BorrowKind::Shared,
1167 fn bin_op(op: hir::BinOpKind) -> BinOp {
1169 hir::BinOpKind::Add => BinOp::Add,
1170 hir::BinOpKind::Sub => BinOp::Sub,
1171 hir::BinOpKind::Mul => BinOp::Mul,
1172 hir::BinOpKind::Div => BinOp::Div,
1173 hir::BinOpKind::Rem => BinOp::Rem,
1174 hir::BinOpKind::BitXor => BinOp::BitXor,
1175 hir::BinOpKind::BitAnd => BinOp::BitAnd,
1176 hir::BinOpKind::BitOr => BinOp::BitOr,
1177 hir::BinOpKind::Shl => BinOp::Shl,
1178 hir::BinOpKind::Shr => BinOp::Shr,
1179 hir::BinOpKind::Eq => BinOp::Eq,
1180 hir::BinOpKind::Lt => BinOp::Lt,
1181 hir::BinOpKind::Le => BinOp::Le,
1182 hir::BinOpKind::Ne => BinOp::Ne,
1183 hir::BinOpKind::Ge => BinOp::Ge,
1184 hir::BinOpKind::Gt => BinOp::Gt,
1185 _ => bug!("no equivalent for ast binop {:?}", op),