]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/cx/expr.rs
Auto merge of #79945 - jackh726:existential_trait_ref, r=nikomatsakis
[rust.git] / compiler / rustc_mir_build / src / thir / cx / expr.rs
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;
5 use crate::thir::*;
6 use rustc_hir as hir;
7 use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
8 use rustc_index::vec::Idx;
9 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
10 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
11 use rustc_middle::mir::interpret::Scalar;
12 use rustc_middle::mir::BorrowKind;
13 use rustc_middle::ty::adjustment::{
14     Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
15 };
16 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
17 use rustc_middle::ty::{self, AdtKind, Ty};
18 use rustc_span::Span;
19
20 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> {
21     type Output = Expr<'tcx>;
22
23     fn make_mirror(self, cx: &mut Cx<'_, 'tcx>) -> Expr<'tcx> {
24         let temp_lifetime = cx.region_scope_tree.temporary_scope(self.hir_id.local_id);
25         let expr_scope = region::Scope { id: self.hir_id.local_id, data: region::ScopeData::Node };
26
27         debug!("Expr::make_mirror(): id={}, span={:?}", self.hir_id, self.span);
28
29         let mut expr = make_mirror_unadjusted(cx, self);
30
31         // Now apply adjustments, if any.
32         for adjustment in cx.typeck_results().expr_adjustments(self) {
33             debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment);
34             expr = apply_adjustment(cx, self, expr, adjustment);
35         }
36
37         // Next, wrap this up in the expr's scope.
38         expr = Expr {
39             temp_lifetime,
40             ty: expr.ty,
41             span: self.span,
42             kind: ExprKind::Scope {
43                 region_scope: expr_scope,
44                 value: expr.to_ref(),
45                 lint_level: LintLevel::Explicit(self.hir_id),
46             },
47         };
48
49         // Finally, create a destruction scope, if any.
50         if let Some(region_scope) = cx.region_scope_tree.opt_destruction_scope(self.hir_id.local_id)
51         {
52             expr = Expr {
53                 temp_lifetime,
54                 ty: expr.ty,
55                 span: self.span,
56                 kind: ExprKind::Scope {
57                     region_scope,
58                     value: expr.to_ref(),
59                     lint_level: LintLevel::Inherited,
60                 },
61             };
62         }
63
64         // OK, all done!
65         expr
66     }
67 }
68
69 fn apply_adjustment<'a, 'tcx>(
70     cx: &mut Cx<'a, 'tcx>,
71     hir_expr: &'tcx hir::Expr<'tcx>,
72     mut expr: Expr<'tcx>,
73     adjustment: &Adjustment<'tcx>,
74 ) -> Expr<'tcx> {
75     let Expr { temp_lifetime, mut span, .. } = expr;
76
77     // Adjust the span from the block, to the last expression of the
78     // block. This is a better span when returning a mutable reference
79     // with too short a lifetime. The error message will use the span
80     // from the assignment to the return place, which should only point
81     // at the returned value, not the entire function body.
82     //
83     // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
84     //      x
85     //   // ^ error message points at this expression.
86     // }
87     let mut adjust_span = |expr: &mut Expr<'tcx>| {
88         if let ExprKind::Block { body } = expr.kind {
89             if let Some(ref last_expr) = body.expr {
90                 span = last_expr.span;
91                 expr.span = span;
92             }
93         }
94     };
95
96     let kind = match adjustment.kind {
97         Adjust::Pointer(PointerCast::Unsize) => {
98             adjust_span(&mut expr);
99             ExprKind::Pointer { cast: PointerCast::Unsize, source: expr.to_ref() }
100         }
101         Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: expr.to_ref() },
102         Adjust::NeverToAny => ExprKind::NeverToAny { source: expr.to_ref() },
103         Adjust::Deref(None) => {
104             adjust_span(&mut expr);
105             ExprKind::Deref { arg: expr.to_ref() }
106         }
107         Adjust::Deref(Some(deref)) => {
108             // We don't need to do call adjust_span here since
109             // deref coercions always start with a built-in deref.
110             let call = deref.method_call(cx.tcx(), expr.ty);
111
112             expr = Expr {
113                 temp_lifetime,
114                 ty: cx.tcx.mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }),
115                 span,
116                 kind: ExprKind::Borrow {
117                     borrow_kind: deref.mutbl.to_borrow_kind(),
118                     arg: expr.to_ref(),
119                 },
120             };
121
122             overloaded_place(
123                 cx,
124                 hir_expr,
125                 adjustment.target,
126                 Some(call),
127                 vec![expr.to_ref()],
128                 deref.span,
129             )
130         }
131         Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
132             ExprKind::Borrow { borrow_kind: m.to_borrow_kind(), arg: expr.to_ref() }
133         }
134         Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
135             ExprKind::AddressOf { mutability, arg: expr.to_ref() }
136         }
137     };
138
139     Expr { temp_lifetime, ty: adjustment.target, span, kind }
140 }
141
142 fn make_mirror_unadjusted<'a, 'tcx>(
143     cx: &mut Cx<'a, 'tcx>,
144     expr: &'tcx hir::Expr<'tcx>,
145 ) -> Expr<'tcx> {
146     let expr_ty = cx.typeck_results().expr_ty(expr);
147     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
148
149     let kind = match expr.kind {
150         // Here comes the interesting stuff:
151         hir::ExprKind::MethodCall(_, method_span, ref args, fn_span) => {
152             // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
153             let expr = method_callee(cx, expr, method_span, None);
154             let args = args.iter().map(|e| e.to_ref()).collect();
155             ExprKind::Call { ty: expr.ty, fun: expr.to_ref(), args, from_hir_call: true, fn_span }
156         }
157
158         hir::ExprKind::Call(ref fun, ref args) => {
159             if cx.typeck_results().is_method_call(expr) {
160                 // The callee is something implementing Fn, FnMut, or FnOnce.
161                 // Find the actual method implementation being called and
162                 // build the appropriate UFCS call expression with the
163                 // callee-object as expr parameter.
164
165                 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
166
167                 let method = method_callee(cx, expr, fun.span, None);
168
169                 let arg_tys = args.iter().map(|e| cx.typeck_results().expr_ty_adjusted(e));
170                 let tupled_args = Expr {
171                     ty: cx.tcx.mk_tup(arg_tys),
172                     temp_lifetime,
173                     span: expr.span,
174                     kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
175                 };
176
177                 ExprKind::Call {
178                     ty: method.ty,
179                     fun: method.to_ref(),
180                     args: vec![fun.to_ref(), tupled_args.to_ref()],
181                     from_hir_call: true,
182                     fn_span: expr.span,
183                 }
184             } else {
185                 let adt_data =
186                     if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
187                         // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
188                         expr_ty.ty_adt_def().and_then(|adt_def| match path.res {
189                             Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
190                                 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
191                             }
192                             Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
193                             _ => None,
194                         })
195                     } else {
196                         None
197                     };
198                 if let Some((adt_def, index)) = adt_data {
199                     let substs = cx.typeck_results().node_substs(fun.hir_id);
200                     let user_provided_types = cx.typeck_results().user_provided_types();
201                     let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
202                         if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
203                             *did = adt_def.did;
204                         }
205                         u_ty
206                     });
207                     debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
208
209                     let field_refs = args
210                         .iter()
211                         .enumerate()
212                         .map(|(idx, e)| FieldExprRef { name: Field::new(idx), expr: e.to_ref() })
213                         .collect();
214                     ExprKind::Adt {
215                         adt_def,
216                         substs,
217                         variant_index: index,
218                         fields: field_refs,
219                         user_ty,
220                         base: None,
221                     }
222                 } else {
223                     ExprKind::Call {
224                         ty: cx.typeck_results().node_type(fun.hir_id),
225                         fun: fun.to_ref(),
226                         args: args.to_ref(),
227                         from_hir_call: true,
228                         fn_span: expr.span,
229                     }
230                 }
231             }
232         }
233
234         hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
235             ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: arg.to_ref() }
236         }
237
238         hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
239             ExprKind::AddressOf { mutability, arg: arg.to_ref() }
240         }
241
242         hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
243
244         hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
245             ExprKind::Assign { lhs: lhs.to_ref(), rhs: rhs.to_ref() }
246         }
247
248         hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
249             if cx.typeck_results().is_method_call(expr) {
250                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
251             } else {
252                 ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() }
253             }
254         }
255
256         hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
257             literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
258             user_ty: None,
259             const_id: None,
260         },
261
262         hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
263             if cx.typeck_results().is_method_call(expr) {
264                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
265             } else {
266                 // FIXME overflow
267                 match (op.node, cx.constness) {
268                     (hir::BinOpKind::And, _) => ExprKind::LogicalOp {
269                         op: LogicalOp::And,
270                         lhs: lhs.to_ref(),
271                         rhs: rhs.to_ref(),
272                     },
273                     (hir::BinOpKind::Or, _) => ExprKind::LogicalOp {
274                         op: LogicalOp::Or,
275                         lhs: lhs.to_ref(),
276                         rhs: rhs.to_ref(),
277                     },
278
279                     _ => {
280                         let op = bin_op(op.node);
281                         ExprKind::Binary { op, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
282                     }
283                 }
284             }
285         }
286
287         hir::ExprKind::Index(ref lhs, ref index) => {
288             if cx.typeck_results().is_method_call(expr) {
289                 overloaded_place(
290                     cx,
291                     expr,
292                     expr_ty,
293                     None,
294                     vec![lhs.to_ref(), index.to_ref()],
295                     expr.span,
296                 )
297             } else {
298                 ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() }
299             }
300         }
301
302         hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
303             if cx.typeck_results().is_method_call(expr) {
304                 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()], expr.span)
305             } else {
306                 ExprKind::Deref { arg: arg.to_ref() }
307             }
308         }
309
310         hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
311             if cx.typeck_results().is_method_call(expr) {
312                 overloaded_operator(cx, expr, vec![arg.to_ref()])
313             } else {
314                 ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() }
315             }
316         }
317
318         hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
319             if cx.typeck_results().is_method_call(expr) {
320                 overloaded_operator(cx, expr, vec![arg.to_ref()])
321             } else if let hir::ExprKind::Lit(ref lit) = arg.kind {
322                 ExprKind::Literal {
323                     literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
324                     user_ty: None,
325                     const_id: None,
326                 }
327             } else {
328                 ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
329             }
330         }
331
332         hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() {
333             ty::Adt(adt, substs) => match adt.adt_kind() {
334                 AdtKind::Struct | AdtKind::Union => {
335                     let user_provided_types = cx.typeck_results().user_provided_types();
336                     let user_ty = user_provided_types.get(expr.hir_id).copied();
337                     debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
338                     ExprKind::Adt {
339                         adt_def: adt,
340                         variant_index: VariantIdx::new(0),
341                         substs,
342                         user_ty,
343                         fields: field_refs(cx, fields),
344                         base: base.as_ref().map(|base| FruInfo {
345                             base: base.to_ref(),
346                             field_types: cx.typeck_results().fru_field_types()[expr.hir_id].clone(),
347                         }),
348                     }
349                 }
350                 AdtKind::Enum => {
351                     let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
352                     match res {
353                         Res::Def(DefKind::Variant, variant_id) => {
354                             assert!(base.is_none());
355
356                             let index = adt.variant_index_with_id(variant_id);
357                             let user_provided_types = cx.typeck_results().user_provided_types();
358                             let user_ty = user_provided_types.get(expr.hir_id).copied();
359                             debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
360                             ExprKind::Adt {
361                                 adt_def: adt,
362                                 variant_index: index,
363                                 substs,
364                                 user_ty,
365                                 fields: field_refs(cx, fields),
366                                 base: None,
367                             }
368                         }
369                         _ => {
370                             span_bug!(expr.span, "unexpected res: {:?}", res);
371                         }
372                     }
373                 }
374             },
375             _ => {
376                 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
377             }
378         },
379
380         hir::ExprKind::Closure(..) => {
381             let closure_ty = cx.typeck_results().expr_ty(expr);
382             let (def_id, substs, movability) = match *closure_ty.kind() {
383                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
384                 ty::Generator(def_id, substs, movability) => {
385                     (def_id, UpvarSubsts::Generator(substs), Some(movability))
386                 }
387                 _ => {
388                     span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
389                 }
390             };
391
392             let upvars = cx
393                 .typeck_results()
394                 .closure_min_captures_flattened(def_id)
395                 .zip(substs.upvar_tys())
396                 .map(|(captured_place, ty)| capture_upvar(cx, expr, captured_place, ty))
397                 .collect();
398             ExprKind::Closure { closure_id: def_id, substs, upvars, movability }
399         }
400
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)
404         }
405
406         hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm {
407             template: asm.template,
408             operands: asm
409                 .operands
410                 .iter()
411                 .map(|(op, _op_sp)| {
412                     match *op {
413                         hir::InlineAsmOperand::In { reg, ref expr } => {
414                             InlineAsmOperand::In { reg, expr: expr.to_ref() }
415                         }
416                         hir::InlineAsmOperand::Out { reg, late, ref expr } => {
417                             InlineAsmOperand::Out {
418                                 reg,
419                                 late,
420                                 expr: expr.as_ref().map(|expr| expr.to_ref()),
421                             }
422                         }
423                         hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
424                             InlineAsmOperand::InOut { reg, late, expr: expr.to_ref() }
425                         }
426                         hir::InlineAsmOperand::SplitInOut {
427                             reg,
428                             late,
429                             ref in_expr,
430                             ref out_expr,
431                         } => InlineAsmOperand::SplitInOut {
432                             reg,
433                             late,
434                             in_expr: in_expr.to_ref(),
435                             out_expr: out_expr.as_ref().map(|expr| expr.to_ref()),
436                         },
437                         hir::InlineAsmOperand::Const { ref expr } => {
438                             InlineAsmOperand::Const { expr: expr.to_ref() }
439                         }
440                         hir::InlineAsmOperand::Sym { ref expr } => {
441                             let qpath = match expr.kind {
442                                 hir::ExprKind::Path(ref qpath) => qpath,
443                                 _ => span_bug!(
444                                     expr.span,
445                                     "asm `sym` operand should be a path, found {:?}",
446                                     expr.kind
447                                 ),
448                             };
449                             let temp_lifetime =
450                                 cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
451                             let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
452                             let ty;
453                             match res {
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 {
458                                         expr: Expr {
459                                             ty,
460                                             temp_lifetime,
461                                             span: expr.span,
462                                             kind: ExprKind::Literal {
463                                                 literal: ty::Const::zero_sized(cx.tcx, ty),
464                                                 user_ty,
465                                                 const_id: None,
466                                             },
467                                         }
468                                         .to_ref(),
469                                     }
470                                 }
471
472                                 Res::Def(DefKind::Static, def_id) => {
473                                     InlineAsmOperand::SymStatic { def_id }
474                                 }
475
476                                 _ => {
477                                     cx.tcx.sess.span_err(
478                                         expr.span,
479                                         "asm `sym` operand must point to a fn or static",
480                                     );
481
482                                     // Not a real fn, but we're not reaching codegen anyways...
483                                     ty = cx.tcx.ty_error();
484                                     InlineAsmOperand::SymFn {
485                                         expr: Expr {
486                                             ty,
487                                             temp_lifetime,
488                                             span: expr.span,
489                                             kind: ExprKind::Literal {
490                                                 literal: ty::Const::zero_sized(cx.tcx, ty),
491                                                 user_ty: None,
492                                                 const_id: None,
493                                             },
494                                         }
495                                         .to_ref(),
496                                     }
497                                 }
498                             }
499                         }
500                     }
501                 })
502                 .collect(),
503             options: asm.options,
504             line_spans: asm.line_spans,
505         },
506
507         hir::ExprKind::LlvmInlineAsm(ref asm) => ExprKind::LlvmInlineAsm {
508             asm: &asm.inner,
509             outputs: asm.outputs_exprs.to_ref(),
510             inputs: asm.inputs_exprs.to_ref(),
511         },
512
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);
516
517             ExprKind::ConstBlock { value }
518         }
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);
523
524             ExprKind::Repeat { value: v.to_ref(), count }
525         }
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(),
531             },
532             Err(err) => bug!("invalid loop id for break: {}", err),
533         },
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 },
537             },
538             Err(err) => bug!("invalid loop id for continue: {}", err),
539         },
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(),
543         },
544         hir::ExprKind::Loop(ref body, _, _) => {
545             ExprKind::Loop { body: block::to_expr_ref(cx, body) }
546         }
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)),
550         },
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);
555
556             debug!(
557                 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
558                 expr, cast_ty.hir_id, user_ty,
559             );
560
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
569                 // destination.
570                 ExprKind::Pointer { source: source.to_ref(), cast: PointerCast::ArrayToPointer }
571             } else {
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
576                 // Example:
577                 // enum Foo {
578                 //     A,
579                 //     B = A as isize + 4,
580                 // }
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| {
586                         match res {
587                             Res::Def(
588                                 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
589                                 variant_ctor_id,
590                             ) => {
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());
596                                 Some((d, o, ty))
597                             }
598                             _ => None,
599                         }
600                     })
601                 } else {
602                     None
603                 };
604
605                 let source = if let Some((did, offset, var_ty)) = var {
606                     let mk_const = |literal| {
607                         Expr {
608                             temp_lifetime,
609                             ty: var_ty,
610                             span: expr.span,
611                             kind: ExprKind::Literal { literal, user_ty: None, const_id: None },
612                         }
613                         .to_ref()
614                     };
615                     let offset = mk_const(ty::Const::from_bits(
616                         cx.tcx,
617                         offset as u128,
618                         cx.param_env.and(var_ty),
619                     ));
620                     match did {
621                         Some(did) => {
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),
628                                     substs,
629                                     None,
630                                 ),
631                                 ty: var_ty,
632                             }));
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()
635                         }
636                         None => offset,
637                     }
638                 } else {
639                     source.to_ref()
640                 };
641
642                 ExprKind::Cast { source }
643             };
644
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);
650
651                 ExprKind::ValueTypeAscription {
652                     source: cast_expr.to_ref(),
653                     user_ty: Some(*user_ty),
654                 }
655             } else {
656                 cast
657             }
658         }
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 }
665             } else {
666                 ExprKind::ValueTypeAscription { source: source.to_ref(), user_ty }
667             }
668         }
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() },
673
674         hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: v.to_ref() },
675         hir::ExprKind::Err => unreachable!(),
676     };
677
678     Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind }
679 }
680
681 fn user_substs_applied_to_res<'tcx>(
682     cx: &mut Cx<'_, 'tcx>,
683     hir_id: hir::HirId,
684     res: Res,
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()
697         }
698
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
702         // user.
703         Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
704             cx.user_substs_applied_to_ty_of_hir_id(hir_id)
705         }
706
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),
709
710         _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
711     };
712     debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
713     user_provided_type
714 }
715
716 fn method_callee<'a, 'tcx>(
717     cx: &mut Cx<'a, 'tcx>,
718     expr: &hir::Expr<'_>,
719     span: Span,
720     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
721 ) -> Expr<'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),
725         None => {
726             let (kind, def_id) = cx
727                 .typeck_results()
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)
733         }
734     };
735     let ty = cx.tcx().mk_fn_def(def_id, substs);
736     Expr {
737         temp_lifetime,
738         ty,
739         span,
740         kind: ExprKind::Literal {
741             literal: ty::Const::zero_sized(cx.tcx(), ty),
742             user_ty,
743             const_id: None,
744         },
745     }
746 }
747
748 trait ToBorrowKind {
749     fn to_borrow_kind(&self) -> BorrowKind;
750 }
751
752 impl ToBorrowKind for AutoBorrowMutability {
753     fn to_borrow_kind(&self) -> BorrowKind {
754         use rustc_middle::ty::adjustment::AllowTwoPhase;
755         match *self {
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,
760                 },
761             },
762             AutoBorrowMutability::Not => BorrowKind::Shared,
763         }
764     }
765 }
766
767 impl ToBorrowKind for hir::Mutability {
768     fn to_borrow_kind(&self) -> BorrowKind {
769         match *self {
770             hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
771             hir::Mutability::Not => BorrowKind::Shared,
772         }
773     }
774 }
775
776 fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'tcx> {
777     Arm {
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()),
782         }),
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 },
786         span: arm.span,
787     }
788 }
789
790 fn convert_path_expr<'a, 'tcx>(
791     cx: &mut Cx<'a, 'tcx>,
792     expr: &'tcx hir::Expr<'tcx>,
793     res: Res,
794 ) -> ExprKind<'tcx> {
795     let substs = cx.typeck_results().node_substs(expr.hir_id);
796     match res {
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);
804             ExprKind::Literal {
805                 literal: ty::Const::zero_sized(cx.tcx, cx.typeck_results().node_type(expr.hir_id)),
806                 user_ty,
807                 const_id: None,
808             }
809         }
810
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));
820             ExprKind::Literal {
821                 literal: cx
822                     .tcx
823                     .mk_const(ty::Const { val, ty: cx.typeck_results().node_type(expr.hir_id) }),
824                 user_ty: None,
825                 const_id: Some(def_id),
826             }
827         }
828
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);
832             ExprKind::Literal {
833                 literal: cx.tcx.mk_const(ty::Const {
834                     val: ty::ConstKind::Unevaluated(
835                         ty::WithOptConstParam::unknown(def_id),
836                         substs,
837                         None,
838                     ),
839                     ty: cx.typeck_results().node_type(expr.hir_id),
840                 }),
841                 user_ty,
842                 const_id: Some(def_id),
843             }
844         }
845
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);
851             match ty.kind() {
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 {
855                     adt_def,
856                     variant_index: adt_def.variant_index_with_ctor_id(def_id),
857                     substs,
858                     user_ty: user_provided_type,
859                     fields: vec![],
860                     base: None,
861                 },
862                 _ => bug!("unexpected ty: {:?}", ty),
863             }
864         }
865
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)
873             } else {
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),
877                     def_id: id,
878                 }
879             };
880             ExprKind::Deref { arg: Expr { ty, temp_lifetime, span: expr.span, kind }.to_ref() }
881         }
882
883         Res::Local(var_hir_id) => convert_var(cx, var_hir_id),
884
885         _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
886     }
887 }
888
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.
892     let is_upvar = cx
893         .tcx
894         .upvars_mentioned(cx.body_owner)
895         .map_or(false, |upvars| upvars.contains_key(&var_hir_id));
896
897     debug!("convert_var({:?}): is_upvar={}, body_owner={:?}", var_hir_id, is_upvar, cx.body_owner);
898
899     if is_upvar {
900         ExprKind::UpvarRef { closure_def_id: cx.body_owner, var_hir_id }
901     } else {
902         ExprKind::VarRef { id: var_hir_id }
903     }
904 }
905
906 fn bin_op(op: hir::BinOpKind) -> BinOp {
907     match op {
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),
925     }
926 }
927
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 }
935 }
936
937 fn overloaded_place<'a, 'tcx>(
938     cx: &mut Cx<'a, 'tcx>,
939     expr: &'tcx hir::Expr<'tcx>,
940     place_ty: Ty<'tcx>,
941     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
942     args: Vec<ExprRef<'tcx>>,
943     span: Span,
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):
948
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,
952     };
953
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"),
960     };
961     let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
962
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 {
968         temp_lifetime,
969         ty: ref_ty,
970         span,
971         kind: ExprKind::Call {
972             ty: fun.ty,
973             fun: fun.to_ref(),
974             args,
975             from_hir_call: false,
976             fn_span: span,
977         },
978     };
979
980     // construct and return a deref wrapper `*foo()`
981     ExprKind::Deref { arg: ref_expr.to_ref() }
982 }
983
984 fn capture_upvar<'a, 'tcx>(
985     cx: &mut Cx<'_, 'tcx>,
986     closure_expr: &'tcx hir::Expr<'tcx>,
987     captured_place: &'a ty::CapturedPlace<'tcx>,
988     upvar_ty: Ty<'tcx>,
989 ) -> ExprRef<'tcx> {
990     let upvar_capture = captured_place.info.capture_kind;
991     let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
992     let var_ty = captured_place.place.base_ty;
993
994     // The result of capture analysis in `rustc_typeck/check/upvar.rs`represents a captured path
995     // as it's seen for use within the closure and not at the time of closure creation.
996     //
997     // That is we see expect to see it start from a captured upvar and not something that is local
998     // to the closure's parent.
999     let var_hir_id = match captured_place.place.base {
1000         HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
1001         base => bug!("Expected an upvar, found {:?}", base),
1002     };
1003
1004     let mut captured_place_expr = Expr {
1005         temp_lifetime,
1006         ty: var_ty,
1007         span: closure_expr.span,
1008         kind: convert_var(cx, var_hir_id),
1009     };
1010
1011     for proj in captured_place.place.projections.iter() {
1012         let kind = match proj.kind {
1013             HirProjectionKind::Deref => ExprKind::Deref { arg: captured_place_expr.to_ref() },
1014             HirProjectionKind::Field(field, ..) => {
1015                 // Variant index will always be 0, because for multi-variant
1016                 // enums, we capture the enum entirely.
1017                 ExprKind::Field {
1018                     lhs: captured_place_expr.to_ref(),
1019                     name: Field::new(field as usize),
1020                 }
1021             }
1022             HirProjectionKind::Index | HirProjectionKind::Subslice => {
1023                 // We don't capture these projections, so we can ignore them here
1024                 continue;
1025             }
1026         };
1027
1028         captured_place_expr = Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind };
1029     }
1030
1031     match upvar_capture {
1032         ty::UpvarCapture::ByValue(_) => captured_place_expr.to_ref(),
1033         ty::UpvarCapture::ByRef(upvar_borrow) => {
1034             let borrow_kind = match upvar_borrow.kind {
1035                 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1036                 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1037                 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false },
1038             };
1039             Expr {
1040                 temp_lifetime,
1041                 ty: upvar_ty,
1042                 span: closure_expr.span,
1043                 kind: ExprKind::Borrow { borrow_kind, arg: captured_place_expr.to_ref() },
1044             }
1045             .to_ref()
1046         }
1047     }
1048 }
1049
1050 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1051 fn field_refs<'a, 'tcx>(
1052     cx: &mut Cx<'a, 'tcx>,
1053     fields: &'tcx [hir::Field<'tcx>],
1054 ) -> Vec<FieldExprRef<'tcx>> {
1055     fields
1056         .iter()
1057         .map(|field| FieldExprRef {
1058             name: Field::new(cx.tcx.field_index(field.hir_id, cx.typeck_results)),
1059             expr: field.expr.to_ref(),
1060         })
1061         .collect()
1062 }