]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/thir/cx/expr.rs
Use `summary_opts()` in another spot
[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::mir::interpret::Scalar;
10 use rustc_middle::mir::BorrowKind;
11 use rustc_middle::ty::adjustment::{
12     Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, PointerCast,
13 };
14 use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
15 use rustc_middle::ty::{self, AdtKind, Ty};
16 use rustc_span::Span;
17
18 impl<'tcx> Mirror<'tcx> for &'tcx hir::Expr<'tcx> {
19     type Output = Expr<'tcx>;
20
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 };
24
25         debug!("Expr::make_mirror(): id={}, span={:?}", self.hir_id, self.span);
26
27         let mut expr = make_mirror_unadjusted(cx, self);
28
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);
33         }
34
35         // Next, wrap this up in the expr's scope.
36         expr = Expr {
37             temp_lifetime,
38             ty: expr.ty,
39             span: self.span,
40             kind: ExprKind::Scope {
41                 region_scope: expr_scope,
42                 value: expr.to_ref(),
43                 lint_level: LintLevel::Explicit(self.hir_id),
44             },
45         };
46
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)
49         {
50             expr = Expr {
51                 temp_lifetime,
52                 ty: expr.ty,
53                 span: self.span,
54                 kind: ExprKind::Scope {
55                     region_scope,
56                     value: expr.to_ref(),
57                     lint_level: LintLevel::Inherited,
58                 },
59             };
60         }
61
62         // OK, all done!
63         expr
64     }
65 }
66
67 fn apply_adjustment<'a, 'tcx>(
68     cx: &mut Cx<'a, 'tcx>,
69     hir_expr: &'tcx hir::Expr<'tcx>,
70     mut expr: Expr<'tcx>,
71     adjustment: &Adjustment<'tcx>,
72 ) -> Expr<'tcx> {
73     let Expr { temp_lifetime, mut span, .. } = expr;
74
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.
80     //
81     // fn return_short_lived<'a>(x: &'a mut i32) -> &'static mut i32 {
82     //      x
83     //   // ^ error message points at this expression.
84     // }
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;
89                 expr.span = span;
90             }
91         }
92     };
93
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() }
98         }
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() }
104         }
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);
109
110             expr = Expr {
111                 temp_lifetime,
112                 ty: cx.tcx.mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }),
113                 span,
114                 kind: ExprKind::Borrow {
115                     borrow_kind: deref.mutbl.to_borrow_kind(),
116                     arg: expr.to_ref(),
117                 },
118             };
119
120             overloaded_place(
121                 cx,
122                 hir_expr,
123                 adjustment.target,
124                 Some(call),
125                 vec![expr.to_ref()],
126                 deref.span,
127             )
128         }
129         Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
130             ExprKind::Borrow { borrow_kind: m.to_borrow_kind(), arg: expr.to_ref() }
131         }
132         Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
133             ExprKind::AddressOf { mutability, arg: expr.to_ref() }
134         }
135     };
136
137     Expr { temp_lifetime, ty: adjustment.target, span, kind }
138 }
139
140 fn make_mirror_unadjusted<'a, 'tcx>(
141     cx: &mut Cx<'a, 'tcx>,
142     expr: &'tcx hir::Expr<'tcx>,
143 ) -> 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);
146
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 }
154         }
155
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.
162
163                 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
164
165                 let method = method_callee(cx, expr, fun.span, None);
166
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),
170                     temp_lifetime,
171                     span: expr.span,
172                     kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
173                 };
174
175                 ExprKind::Call {
176                     ty: method.ty,
177                     fun: method.to_ref(),
178                     args: vec![fun.to_ref(), tupled_args.to_ref()],
179                     from_hir_call: true,
180                     fn_span: expr.span,
181                 }
182             } else {
183                 let adt_data =
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)))
189                             }
190                             Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
191                             _ => None,
192                         })
193                     } else {
194                         None
195                     };
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 {
201                             *did = adt_def.did;
202                         }
203                         u_ty
204                     });
205                     debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
206
207                     let field_refs = args
208                         .iter()
209                         .enumerate()
210                         .map(|(idx, e)| FieldExprRef { name: Field::new(idx), expr: e.to_ref() })
211                         .collect();
212                     ExprKind::Adt {
213                         adt_def,
214                         substs,
215                         variant_index: index,
216                         fields: field_refs,
217                         user_ty,
218                         base: None,
219                     }
220                 } else {
221                     ExprKind::Call {
222                         ty: cx.typeck_results().node_type(fun.hir_id),
223                         fun: fun.to_ref(),
224                         args: args.to_ref(),
225                         from_hir_call: true,
226                         fn_span: expr.span,
227                     }
228                 }
229             }
230         }
231
232         hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
233             ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: arg.to_ref() }
234         }
235
236         hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
237             ExprKind::AddressOf { mutability, arg: arg.to_ref() }
238         }
239
240         hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
241
242         hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
243             ExprKind::Assign { lhs: lhs.to_ref(), rhs: rhs.to_ref() }
244         }
245
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()])
249             } else {
250                 ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() }
251             }
252         }
253
254         hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
255             literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
256             user_ty: None,
257             const_id: None,
258         },
259
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()])
263             } else {
264                 // FIXME overflow
265                 match (op.node, cx.constness) {
266                     (hir::BinOpKind::And, _) => ExprKind::LogicalOp {
267                         op: LogicalOp::And,
268                         lhs: lhs.to_ref(),
269                         rhs: rhs.to_ref(),
270                     },
271                     (hir::BinOpKind::Or, _) => ExprKind::LogicalOp {
272                         op: LogicalOp::Or,
273                         lhs: lhs.to_ref(),
274                         rhs: rhs.to_ref(),
275                     },
276
277                     _ => {
278                         let op = bin_op(op.node);
279                         ExprKind::Binary { op, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
280                     }
281                 }
282             }
283         }
284
285         hir::ExprKind::Index(ref lhs, ref index) => {
286             if cx.typeck_results().is_method_call(expr) {
287                 overloaded_place(
288                     cx,
289                     expr,
290                     expr_ty,
291                     None,
292                     vec![lhs.to_ref(), index.to_ref()],
293                     expr.span,
294                 )
295             } else {
296                 ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() }
297             }
298         }
299
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)
303             } else {
304                 ExprKind::Deref { arg: arg.to_ref() }
305             }
306         }
307
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()])
311             } else {
312                 ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() }
313             }
314         }
315
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 {
320                 ExprKind::Literal {
321                     literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
322                     user_ty: None,
323                     const_id: None,
324                 }
325             } else {
326                 ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
327             }
328         }
329
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);
336                     ExprKind::Adt {
337                         adt_def: adt,
338                         variant_index: VariantIdx::new(0),
339                         substs,
340                         user_ty,
341                         fields: field_refs(cx, fields),
342                         base: base.as_ref().map(|base| FruInfo {
343                             base: base.to_ref(),
344                             field_types: cx.typeck_results().fru_field_types()[expr.hir_id].clone(),
345                         }),
346                     }
347                 }
348                 AdtKind::Enum => {
349                     let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
350                     match res {
351                         Res::Def(DefKind::Variant, variant_id) => {
352                             assert!(base.is_none());
353
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);
358                             ExprKind::Adt {
359                                 adt_def: adt,
360                                 variant_index: index,
361                                 substs,
362                                 user_ty,
363                                 fields: field_refs(cx, fields),
364                                 base: None,
365                             }
366                         }
367                         _ => {
368                             span_bug!(expr.span, "unexpected res: {:?}", res);
369                         }
370                     }
371                 }
372             },
373             _ => {
374                 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
375             }
376         },
377
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))
384                 }
385                 _ => {
386                     span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
387                 }
388             };
389             let upvars = cx
390                 .typeck_results()
391                 .closure_captures
392                 .get(&def_id)
393                 .iter()
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))
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| {
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: match arm.guard {
780             Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
781             _ => None,
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<'tcx>(
985     cx: &mut Cx<'_, 'tcx>,
986     closure_expr: &'tcx hir::Expr<'tcx>,
987     var_hir_id: hir::HirId,
988     upvar_ty: Ty<'tcx>,
989 ) -> ExprRef<'tcx> {
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),
993     };
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 {
998         temp_lifetime,
999         ty: var_ty,
1000         span: closure_expr.span,
1001         kind: convert_var(cx, var_hir_id),
1002     };
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 },
1010             };
1011             Expr {
1012                 temp_lifetime,
1013                 ty: upvar_ty,
1014                 span: closure_expr.span,
1015                 kind: ExprKind::Borrow { borrow_kind, arg: captured_var.to_ref() },
1016             }
1017             .to_ref()
1018         }
1019     }
1020 }
1021
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>> {
1027     fields
1028         .iter()
1029         .map(|field| FieldExprRef {
1030             name: Field::new(cx.tcx.field_index(field.hir_id, cx.typeck_results)),
1031             expr: field.expr.to_ref(),
1032         })
1033         .collect()
1034 }