]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir_build/thir/cx/expr.rs
pin docs: add some forward references
[rust.git] / src / librustc_mir_build / 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(cx, hir_expr, adjustment.target, Some(call), vec![expr.to_ref()])
121         }
122         Adjust::Borrow(AutoBorrow::Ref(_, m)) => {
123             ExprKind::Borrow { borrow_kind: m.to_borrow_kind(), arg: expr.to_ref() }
124         }
125         Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => {
126             ExprKind::AddressOf { mutability, arg: expr.to_ref() }
127         }
128     };
129
130     Expr { temp_lifetime, ty: adjustment.target, span, kind }
131 }
132
133 fn make_mirror_unadjusted<'a, 'tcx>(
134     cx: &mut Cx<'a, 'tcx>,
135     expr: &'tcx hir::Expr<'tcx>,
136 ) -> Expr<'tcx> {
137     let expr_ty = cx.typeck_results().expr_ty(expr);
138     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
139
140     let kind = match expr.kind {
141         // Here comes the interesting stuff:
142         hir::ExprKind::MethodCall(_, method_span, ref args, fn_span) => {
143             // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
144             let expr = method_callee(cx, expr, method_span, None);
145             let args = args.iter().map(|e| e.to_ref()).collect();
146             ExprKind::Call { ty: expr.ty, fun: expr.to_ref(), args, from_hir_call: true, fn_span }
147         }
148
149         hir::ExprKind::Call(ref fun, ref args) => {
150             if cx.typeck_results().is_method_call(expr) {
151                 // The callee is something implementing Fn, FnMut, or FnOnce.
152                 // Find the actual method implementation being called and
153                 // build the appropriate UFCS call expression with the
154                 // callee-object as expr parameter.
155
156                 // rewrite f(u, v) into FnOnce::call_once(f, (u, v))
157
158                 let method = method_callee(cx, expr, fun.span, None);
159
160                 let arg_tys = args.iter().map(|e| cx.typeck_results().expr_ty_adjusted(e));
161                 let tupled_args = Expr {
162                     ty: cx.tcx.mk_tup(arg_tys),
163                     temp_lifetime,
164                     span: expr.span,
165                     kind: ExprKind::Tuple { fields: args.iter().map(ToRef::to_ref).collect() },
166                 };
167
168                 ExprKind::Call {
169                     ty: method.ty,
170                     fun: method.to_ref(),
171                     args: vec![fun.to_ref(), tupled_args.to_ref()],
172                     from_hir_call: true,
173                     fn_span: expr.span,
174                 }
175             } else {
176                 let adt_data =
177                     if let hir::ExprKind::Path(hir::QPath::Resolved(_, ref path)) = fun.kind {
178                         // Tuple-like ADTs are represented as ExprKind::Call. We convert them here.
179                         expr_ty.ty_adt_def().and_then(|adt_def| match path.res {
180                             Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => {
181                                 Some((adt_def, adt_def.variant_index_with_ctor_id(ctor_id)))
182                             }
183                             Res::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
184                             _ => None,
185                         })
186                     } else {
187                         None
188                     };
189                 if let Some((adt_def, index)) = adt_data {
190                     let substs = cx.typeck_results().node_substs(fun.hir_id);
191                     let user_provided_types = cx.typeck_results().user_provided_types();
192                     let user_ty = user_provided_types.get(fun.hir_id).copied().map(|mut u_ty| {
193                         if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
194                             *did = adt_def.did;
195                         }
196                         u_ty
197                     });
198                     debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
199
200                     let field_refs = args
201                         .iter()
202                         .enumerate()
203                         .map(|(idx, e)| FieldExprRef { name: Field::new(idx), expr: e.to_ref() })
204                         .collect();
205                     ExprKind::Adt {
206                         adt_def,
207                         substs,
208                         variant_index: index,
209                         fields: field_refs,
210                         user_ty,
211                         base: None,
212                     }
213                 } else {
214                     ExprKind::Call {
215                         ty: cx.typeck_results().node_type(fun.hir_id),
216                         fun: fun.to_ref(),
217                         args: args.to_ref(),
218                         from_hir_call: true,
219                         fn_span: expr.span,
220                     }
221                 }
222             }
223         }
224
225         hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => {
226             ExprKind::Borrow { borrow_kind: mutbl.to_borrow_kind(), arg: arg.to_ref() }
227         }
228
229         hir::ExprKind::AddrOf(hir::BorrowKind::Raw, mutability, ref arg) => {
230             ExprKind::AddressOf { mutability, arg: arg.to_ref() }
231         }
232
233         hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
234
235         hir::ExprKind::Assign(ref lhs, ref rhs, _) => {
236             ExprKind::Assign { lhs: lhs.to_ref(), rhs: rhs.to_ref() }
237         }
238
239         hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
240             if cx.typeck_results().is_method_call(expr) {
241                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
242             } else {
243                 ExprKind::AssignOp { op: bin_op(op.node), lhs: lhs.to_ref(), rhs: rhs.to_ref() }
244             }
245         }
246
247         hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
248             literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, false),
249             user_ty: None,
250         },
251
252         hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
253             if cx.typeck_results().is_method_call(expr) {
254                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
255             } else {
256                 // FIXME overflow
257                 match (op.node, cx.constness) {
258                     (hir::BinOpKind::And, _) => ExprKind::LogicalOp {
259                         op: LogicalOp::And,
260                         lhs: lhs.to_ref(),
261                         rhs: rhs.to_ref(),
262                     },
263                     (hir::BinOpKind::Or, _) => ExprKind::LogicalOp {
264                         op: LogicalOp::Or,
265                         lhs: lhs.to_ref(),
266                         rhs: rhs.to_ref(),
267                     },
268
269                     _ => {
270                         let op = bin_op(op.node);
271                         ExprKind::Binary { op, lhs: lhs.to_ref(), rhs: rhs.to_ref() }
272                     }
273                 }
274             }
275         }
276
277         hir::ExprKind::Index(ref lhs, ref index) => {
278             if cx.typeck_results().is_method_call(expr) {
279                 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
280             } else {
281                 ExprKind::Index { lhs: lhs.to_ref(), index: index.to_ref() }
282             }
283         }
284
285         hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
286             if cx.typeck_results().is_method_call(expr) {
287                 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
288             } else {
289                 ExprKind::Deref { arg: arg.to_ref() }
290             }
291         }
292
293         hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
294             if cx.typeck_results().is_method_call(expr) {
295                 overloaded_operator(cx, expr, vec![arg.to_ref()])
296             } else {
297                 ExprKind::Unary { op: UnOp::Not, arg: arg.to_ref() }
298             }
299         }
300
301         hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
302             if cx.typeck_results().is_method_call(expr) {
303                 overloaded_operator(cx, expr, vec![arg.to_ref()])
304             } else {
305                 if let hir::ExprKind::Lit(ref lit) = arg.kind {
306                     ExprKind::Literal {
307                         literal: cx.const_eval_literal(&lit.node, expr_ty, lit.span, true),
308                         user_ty: None,
309                     }
310                 } else {
311                     ExprKind::Unary { op: UnOp::Neg, arg: arg.to_ref() }
312                 }
313             }
314         }
315
316         hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind {
317             ty::Adt(adt, substs) => match adt.adt_kind() {
318                 AdtKind::Struct | AdtKind::Union => {
319                     let user_provided_types = cx.typeck_results().user_provided_types();
320                     let user_ty = user_provided_types.get(expr.hir_id).copied();
321                     debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
322                     ExprKind::Adt {
323                         adt_def: adt,
324                         variant_index: VariantIdx::new(0),
325                         substs,
326                         user_ty,
327                         fields: field_refs(cx, fields),
328                         base: base.as_ref().map(|base| FruInfo {
329                             base: base.to_ref(),
330                             field_types: cx.typeck_results().fru_field_types()[expr.hir_id].clone(),
331                         }),
332                     }
333                 }
334                 AdtKind::Enum => {
335                     let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
336                     match res {
337                         Res::Def(DefKind::Variant, variant_id) => {
338                             assert!(base.is_none());
339
340                             let index = adt.variant_index_with_id(variant_id);
341                             let user_provided_types = cx.typeck_results().user_provided_types();
342                             let user_ty = user_provided_types.get(expr.hir_id).copied();
343                             debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty);
344                             ExprKind::Adt {
345                                 adt_def: adt,
346                                 variant_index: index,
347                                 substs,
348                                 user_ty,
349                                 fields: field_refs(cx, fields),
350                                 base: None,
351                             }
352                         }
353                         _ => {
354                             span_bug!(expr.span, "unexpected res: {:?}", res);
355                         }
356                     }
357                 }
358             },
359             _ => {
360                 span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty);
361             }
362         },
363
364         hir::ExprKind::Closure(..) => {
365             let closure_ty = cx.typeck_results().expr_ty(expr);
366             let (def_id, substs, movability) = match closure_ty.kind {
367                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
368                 ty::Generator(def_id, substs, movability) => {
369                     (def_id, UpvarSubsts::Generator(substs), Some(movability))
370                 }
371                 _ => {
372                     span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
373                 }
374             };
375             let upvars = cx
376                 .tcx
377                 .upvars_mentioned(def_id)
378                 .iter()
379                 .flat_map(|upvars| upvars.iter())
380                 .zip(substs.upvar_tys())
381                 .map(|((&var_hir_id, _), ty)| capture_upvar(cx, expr, var_hir_id, ty))
382                 .collect();
383             ExprKind::Closure { closure_id: def_id, substs, upvars, movability }
384         }
385
386         hir::ExprKind::Path(ref qpath) => {
387             let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
388             convert_path_expr(cx, expr, res)
389         }
390
391         hir::ExprKind::InlineAsm(ref asm) => ExprKind::InlineAsm {
392             template: asm.template,
393             operands: asm
394                 .operands
395                 .iter()
396                 .map(|op| {
397                     match *op {
398                         hir::InlineAsmOperand::In { reg, ref expr } => {
399                             InlineAsmOperand::In { reg, expr: expr.to_ref() }
400                         }
401                         hir::InlineAsmOperand::Out { reg, late, ref expr } => {
402                             InlineAsmOperand::Out {
403                                 reg,
404                                 late,
405                                 expr: expr.as_ref().map(|expr| expr.to_ref()),
406                             }
407                         }
408                         hir::InlineAsmOperand::InOut { reg, late, ref expr } => {
409                             InlineAsmOperand::InOut { reg, late, expr: expr.to_ref() }
410                         }
411                         hir::InlineAsmOperand::SplitInOut {
412                             reg,
413                             late,
414                             ref in_expr,
415                             ref out_expr,
416                         } => InlineAsmOperand::SplitInOut {
417                             reg,
418                             late,
419                             in_expr: in_expr.to_ref(),
420                             out_expr: out_expr.as_ref().map(|expr| expr.to_ref()),
421                         },
422                         hir::InlineAsmOperand::Const { ref expr } => {
423                             InlineAsmOperand::Const { expr: expr.to_ref() }
424                         }
425                         hir::InlineAsmOperand::Sym { ref expr } => {
426                             let qpath = match expr.kind {
427                                 hir::ExprKind::Path(ref qpath) => qpath,
428                                 _ => span_bug!(
429                                     expr.span,
430                                     "asm `sym` operand should be a path, found {:?}",
431                                     expr.kind
432                                 ),
433                             };
434                             let temp_lifetime =
435                                 cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
436                             let res = cx.typeck_results().qpath_res(qpath, expr.hir_id);
437                             let ty;
438                             match res {
439                                 Res::Def(DefKind::Fn, _) | Res::Def(DefKind::AssocFn, _) => {
440                                     ty = cx.typeck_results().node_type(expr.hir_id);
441                                     let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
442                                     InlineAsmOperand::SymFn {
443                                         expr: Expr {
444                                             ty,
445                                             temp_lifetime,
446                                             span: expr.span,
447                                             kind: ExprKind::Literal {
448                                                 literal: ty::Const::zero_sized(cx.tcx, ty),
449                                                 user_ty,
450                                             },
451                                         }
452                                         .to_ref(),
453                                     }
454                                 }
455
456                                 Res::Def(DefKind::Static, def_id) => {
457                                     InlineAsmOperand::SymStatic { def_id }
458                                 }
459
460                                 _ => {
461                                     cx.tcx.sess.span_err(
462                                         expr.span,
463                                         "asm `sym` operand must point to a fn or static",
464                                     );
465
466                                     // Not a real fn, but we're not reaching codegen anyways...
467                                     ty = cx.tcx.ty_error();
468                                     InlineAsmOperand::SymFn {
469                                         expr: Expr {
470                                             ty,
471                                             temp_lifetime,
472                                             span: expr.span,
473                                             kind: ExprKind::Literal {
474                                                 literal: ty::Const::zero_sized(cx.tcx, ty),
475                                                 user_ty: None,
476                                             },
477                                         }
478                                         .to_ref(),
479                                     }
480                                 }
481                             }
482                         }
483                     }
484                 })
485                 .collect(),
486             options: asm.options,
487             line_spans: asm.line_spans,
488         },
489
490         hir::ExprKind::LlvmInlineAsm(ref asm) => ExprKind::LlvmInlineAsm {
491             asm: &asm.inner,
492             outputs: asm.outputs_exprs.to_ref(),
493             inputs: asm.inputs_exprs.to_ref(),
494         },
495
496         // Now comes the rote stuff:
497         hir::ExprKind::Repeat(ref v, ref count) => {
498             let count_def_id = cx.tcx.hir().local_def_id(count.hir_id);
499             let count = ty::Const::from_anon_const(cx.tcx, count_def_id);
500
501             ExprKind::Repeat { value: v.to_ref(), count }
502         }
503         hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
504         hir::ExprKind::Break(dest, ref value) => match dest.target_id {
505             Ok(target_id) => ExprKind::Break {
506                 label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node },
507                 value: value.to_ref(),
508             },
509             Err(err) => bug!("invalid loop id for break: {}", err),
510         },
511         hir::ExprKind::Continue(dest) => match dest.target_id {
512             Ok(loop_id) => ExprKind::Continue {
513                 label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node },
514             },
515             Err(err) => bug!("invalid loop id for continue: {}", err),
516         },
517         hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match {
518             scrutinee: discr.to_ref(),
519             arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
520         },
521         hir::ExprKind::Loop(ref body, _, _) => {
522             ExprKind::Loop { body: block::to_expr_ref(cx, body) }
523         }
524         hir::ExprKind::Field(ref source, ..) => ExprKind::Field {
525             lhs: source.to_ref(),
526             name: Field::new(cx.tcx.field_index(expr.hir_id, cx.typeck_results)),
527         },
528         hir::ExprKind::Cast(ref source, ref cast_ty) => {
529             // Check for a user-given type annotation on this `cast`
530             let user_provided_types = cx.typeck_results.user_provided_types();
531             let user_ty = user_provided_types.get(cast_ty.hir_id);
532
533             debug!(
534                 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
535                 expr, cast_ty.hir_id, user_ty,
536             );
537
538             // Check to see if this cast is a "coercion cast", where the cast is actually done
539             // using a coercion (or is a no-op).
540             let cast = if cx.typeck_results().is_coercion_cast(source.hir_id) {
541                 // Convert the lexpr to a vexpr.
542                 ExprKind::Use { source: source.to_ref() }
543             } else if cx.typeck_results().expr_ty(source).is_region_ptr() {
544                 // Special cased so that we can type check that the element
545                 // type of the source matches the pointed to type of the
546                 // destination.
547                 ExprKind::Pointer { source: source.to_ref(), cast: PointerCast::ArrayToPointer }
548             } else {
549                 // check whether this is casting an enum variant discriminant
550                 // to prevent cycles, we refer to the discriminant initializer
551                 // which is always an integer and thus doesn't need to know the
552                 // enum's layout (or its tag type) to compute it during const eval
553                 // Example:
554                 // enum Foo {
555                 //     A,
556                 //     B = A as isize + 4,
557                 // }
558                 // The correct solution would be to add symbolic computations to miri,
559                 // so we wouldn't have to compute and store the actual value
560                 let var = if let hir::ExprKind::Path(ref qpath) = source.kind {
561                     let res = cx.typeck_results().qpath_res(qpath, source.hir_id);
562                     cx.typeck_results().node_type(source.hir_id).ty_adt_def().and_then(|adt_def| {
563                         match res {
564                             Res::Def(
565                                 DefKind::Ctor(CtorOf::Variant, CtorKind::Const),
566                                 variant_ctor_id,
567                             ) => {
568                                 let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id);
569                                 let (d, o) = adt_def.discriminant_def_for_variant(idx);
570                                 use rustc_middle::ty::util::IntTypeExt;
571                                 let ty = adt_def.repr.discr_type();
572                                 let ty = ty.to_ty(cx.tcx());
573                                 Some((d, o, ty))
574                             }
575                             _ => None,
576                         }
577                     })
578                 } else {
579                     None
580                 };
581
582                 let source = if let Some((did, offset, var_ty)) = var {
583                     let mk_const = |literal| {
584                         Expr {
585                             temp_lifetime,
586                             ty: var_ty,
587                             span: expr.span,
588                             kind: ExprKind::Literal { literal, user_ty: None },
589                         }
590                         .to_ref()
591                     };
592                     let offset = mk_const(ty::Const::from_bits(
593                         cx.tcx,
594                         offset as u128,
595                         cx.param_env.and(var_ty),
596                     ));
597                     match did {
598                         Some(did) => {
599                             // in case we are offsetting from a computed discriminant
600                             // and not the beginning of discriminants (which is always `0`)
601                             let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
602                             let lhs = mk_const(cx.tcx().mk_const(ty::Const {
603                                 val: ty::ConstKind::Unevaluated(
604                                     ty::WithOptConstParam::unknown(did),
605                                     substs,
606                                     None,
607                                 ),
608                                 ty: var_ty,
609                             }));
610                             let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
611                             Expr { temp_lifetime, ty: var_ty, span: expr.span, kind: bin }.to_ref()
612                         }
613                         None => offset,
614                     }
615                 } else {
616                     source.to_ref()
617                 };
618
619                 ExprKind::Cast { source }
620             };
621
622             if let Some(user_ty) = user_ty {
623                 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
624                 //       inefficient, revisit this when performance becomes an issue.
625                 let cast_expr = Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind: cast };
626                 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
627
628                 ExprKind::ValueTypeAscription {
629                     source: cast_expr.to_ref(),
630                     user_ty: Some(*user_ty),
631                 }
632             } else {
633                 cast
634             }
635         }
636         hir::ExprKind::Type(ref source, ref ty) => {
637             let user_provided_types = cx.typeck_results.user_provided_types();
638             let user_ty = user_provided_types.get(ty.hir_id).copied();
639             debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
640             if source.is_syntactic_place_expr() {
641                 ExprKind::PlaceTypeAscription { source: source.to_ref(), user_ty }
642             } else {
643                 ExprKind::ValueTypeAscription { source: source.to_ref(), user_ty }
644             }
645         }
646         hir::ExprKind::DropTemps(ref source) => ExprKind::Use { source: source.to_ref() },
647         hir::ExprKind::Box(ref value) => ExprKind::Box { value: value.to_ref() },
648         hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
649         hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
650
651         hir::ExprKind::Yield(ref v, _) => ExprKind::Yield { value: v.to_ref() },
652         hir::ExprKind::Err => unreachable!(),
653     };
654
655     Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind }
656 }
657
658 fn user_substs_applied_to_res<'tcx>(
659     cx: &mut Cx<'_, 'tcx>,
660     hir_id: hir::HirId,
661     res: Res,
662 ) -> Option<ty::CanonicalUserType<'tcx>> {
663     debug!("user_substs_applied_to_res: res={:?}", res);
664     let user_provided_type = match res {
665         // A reference to something callable -- e.g., a fn, method, or
666         // a tuple-struct or tuple-variant. This has the type of a
667         // `Fn` but with the user-given substitutions.
668         Res::Def(DefKind::Fn, _)
669         | Res::Def(DefKind::AssocFn, _)
670         | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
671         | Res::Def(DefKind::Const, _)
672         | Res::Def(DefKind::AssocConst, _) => {
673             cx.typeck_results().user_provided_types().get(hir_id).copied()
674         }
675
676         // A unit struct/variant which is used as a value (e.g.,
677         // `None`). This has the type of the enum/struct that defines
678         // this variant -- but with the substitutions given by the
679         // user.
680         Res::Def(DefKind::Ctor(_, CtorKind::Const), _) => {
681             cx.user_substs_applied_to_ty_of_hir_id(hir_id)
682         }
683
684         // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
685         Res::SelfCtor(_) => cx.user_substs_applied_to_ty_of_hir_id(hir_id),
686
687         _ => bug!("user_substs_applied_to_res: unexpected res {:?} at {:?}", res, hir_id),
688     };
689     debug!("user_substs_applied_to_res: user_provided_type={:?}", user_provided_type);
690     user_provided_type
691 }
692
693 fn method_callee<'a, 'tcx>(
694     cx: &mut Cx<'a, 'tcx>,
695     expr: &hir::Expr<'_>,
696     span: Span,
697     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
698 ) -> Expr<'tcx> {
699     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
700     let (def_id, substs, user_ty) = match overloaded_callee {
701         Some((def_id, substs)) => (def_id, substs, None),
702         None => {
703             let (kind, def_id) = cx
704                 .typeck_results()
705                 .type_dependent_def(expr.hir_id)
706                 .unwrap_or_else(|| span_bug!(expr.span, "no type-dependent def for method callee"));
707             let user_ty = user_substs_applied_to_res(cx, expr.hir_id, Res::Def(kind, def_id));
708             debug!("method_callee: user_ty={:?}", user_ty);
709             (def_id, cx.typeck_results().node_substs(expr.hir_id), user_ty)
710         }
711     };
712     let ty = cx.tcx().mk_fn_def(def_id, substs);
713     Expr {
714         temp_lifetime,
715         ty,
716         span,
717         kind: ExprKind::Literal { literal: ty::Const::zero_sized(cx.tcx(), ty), user_ty },
718     }
719 }
720
721 trait ToBorrowKind {
722     fn to_borrow_kind(&self) -> BorrowKind;
723 }
724
725 impl ToBorrowKind for AutoBorrowMutability {
726     fn to_borrow_kind(&self) -> BorrowKind {
727         use rustc_middle::ty::adjustment::AllowTwoPhase;
728         match *self {
729             AutoBorrowMutability::Mut { allow_two_phase_borrow } => BorrowKind::Mut {
730                 allow_two_phase_borrow: match allow_two_phase_borrow {
731                     AllowTwoPhase::Yes => true,
732                     AllowTwoPhase::No => false,
733                 },
734             },
735             AutoBorrowMutability::Not => BorrowKind::Shared,
736         }
737     }
738 }
739
740 impl ToBorrowKind for hir::Mutability {
741     fn to_borrow_kind(&self) -> BorrowKind {
742         match *self {
743             hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false },
744             hir::Mutability::Not => BorrowKind::Shared,
745         }
746     }
747 }
748
749 fn convert_arm<'tcx>(cx: &mut Cx<'_, 'tcx>, arm: &'tcx hir::Arm<'tcx>) -> Arm<'tcx> {
750     Arm {
751         pattern: cx.pattern_from_hir(&arm.pat),
752         guard: match arm.guard {
753             Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
754             _ => None,
755         },
756         body: arm.body.to_ref(),
757         lint_level: LintLevel::Explicit(arm.hir_id),
758         scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node },
759         span: arm.span,
760     }
761 }
762
763 fn convert_path_expr<'a, 'tcx>(
764     cx: &mut Cx<'a, 'tcx>,
765     expr: &'tcx hir::Expr<'tcx>,
766     res: Res,
767 ) -> ExprKind<'tcx> {
768     let substs = cx.typeck_results().node_substs(expr.hir_id);
769     match res {
770         // A regular function, constructor function or a constant.
771         Res::Def(DefKind::Fn, _)
772         | Res::Def(DefKind::AssocFn, _)
773         | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _)
774         | Res::SelfCtor(..) => {
775             let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
776             debug!("convert_path_expr: user_ty={:?}", user_ty);
777             ExprKind::Literal {
778                 literal: ty::Const::zero_sized(cx.tcx, cx.typeck_results().node_type(expr.hir_id)),
779                 user_ty,
780             }
781         }
782
783         Res::Def(DefKind::ConstParam, def_id) => {
784             let hir_id = cx.tcx.hir().as_local_hir_id(def_id.expect_local());
785             let item_id = cx.tcx.hir().get_parent_node(hir_id);
786             let item_def_id = cx.tcx.hir().local_def_id(item_id);
787             let generics = cx.tcx.generics_of(item_def_id);
788             let local_def_id = cx.tcx.hir().local_def_id(hir_id);
789             let index = generics.param_def_id_to_index[&local_def_id.to_def_id()];
790             let name = cx.tcx.hir().name(hir_id);
791             let val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
792             ExprKind::Literal {
793                 literal: cx
794                     .tcx
795                     .mk_const(ty::Const { val, ty: cx.typeck_results().node_type(expr.hir_id) }),
796                 user_ty: None,
797             }
798         }
799
800         Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => {
801             let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res);
802             debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
803             ExprKind::Literal {
804                 literal: cx.tcx.mk_const(ty::Const {
805                     val: ty::ConstKind::Unevaluated(
806                         ty::WithOptConstParam::unknown(def_id),
807                         substs,
808                         None,
809                     ),
810                     ty: cx.typeck_results().node_type(expr.hir_id),
811                 }),
812                 user_ty,
813             }
814         }
815
816         Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => {
817             let user_provided_types = cx.typeck_results.user_provided_types();
818             let user_provided_type = user_provided_types.get(expr.hir_id).copied();
819             debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
820             let ty = cx.typeck_results().node_type(expr.hir_id);
821             match ty.kind {
822                 // A unit struct/variant which is used as a value.
823                 // We return a completely different ExprKind here to account for this special case.
824                 ty::Adt(adt_def, substs) => ExprKind::Adt {
825                     adt_def,
826                     variant_index: adt_def.variant_index_with_ctor_id(def_id),
827                     substs,
828                     user_ty: user_provided_type,
829                     fields: vec![],
830                     base: None,
831                 },
832                 _ => bug!("unexpected ty: {:?}", ty),
833             }
834         }
835
836         // We encode uses of statics as a `*&STATIC` where the `&STATIC` part is
837         // a constant reference (or constant raw pointer for `static mut`) in MIR
838         Res::Def(DefKind::Static, id) => {
839             let ty = cx.tcx.static_ptr_ty(id);
840             let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
841             let kind = if cx.tcx.is_thread_local_static(id) {
842                 ExprKind::ThreadLocalRef(id)
843             } else {
844                 let ptr = cx.tcx.create_static_alloc(id);
845                 ExprKind::StaticRef {
846                     literal: ty::Const::from_scalar(cx.tcx, Scalar::Ptr(ptr.into()), ty),
847                     def_id: id,
848                 }
849             };
850             ExprKind::Deref { arg: Expr { ty, temp_lifetime, span: expr.span, kind }.to_ref() }
851         }
852
853         Res::Local(var_hir_id) => convert_var(cx, expr, var_hir_id),
854
855         _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res),
856     }
857 }
858
859 fn convert_var<'tcx>(
860     cx: &mut Cx<'_, 'tcx>,
861     expr: &'tcx hir::Expr<'tcx>,
862     var_hir_id: hir::HirId,
863 ) -> ExprKind<'tcx> {
864     let upvar_index = cx
865         .typeck_results()
866         .closure_captures
867         .get(&cx.body_owner)
868         .and_then(|upvars| upvars.get_full(&var_hir_id).map(|(i, _, _)| i));
869
870     debug!(
871         "convert_var({:?}): upvar_index={:?}, body_owner={:?}",
872         var_hir_id, upvar_index, cx.body_owner
873     );
874
875     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
876
877     match upvar_index {
878         None => ExprKind::VarRef { id: var_hir_id },
879
880         Some(upvar_index) => {
881             let closure_def_id = cx.body_owner;
882             let upvar_id = ty::UpvarId {
883                 var_path: ty::UpvarPath { hir_id: var_hir_id },
884                 closure_expr_id: closure_def_id.expect_local(),
885             };
886             let var_ty = cx.typeck_results().node_type(var_hir_id);
887
888             // FIXME free regions in closures are not right
889             let closure_ty = cx
890                 .typeck_results()
891                 .node_type(cx.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
892
893             // FIXME we're just hard-coding the idea that the
894             // signature will be &self or &mut self and hence will
895             // have a bound region with number 0
896             let region = ty::ReFree(ty::FreeRegion {
897                 scope: closure_def_id,
898                 bound_region: ty::BoundRegion::BrAnon(0),
899             });
900             let region = cx.tcx.mk_region(region);
901
902             let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.kind {
903                 match cx.infcx.closure_kind(closure_substs).unwrap() {
904                     ty::ClosureKind::Fn => {
905                         let ref_closure_ty = cx.tcx.mk_ref(
906                             region,
907                             ty::TypeAndMut { ty: closure_ty, mutbl: hir::Mutability::Not },
908                         );
909                         Expr {
910                             ty: closure_ty,
911                             temp_lifetime,
912                             span: expr.span,
913                             kind: ExprKind::Deref {
914                                 arg: Expr {
915                                     ty: ref_closure_ty,
916                                     temp_lifetime,
917                                     span: expr.span,
918                                     kind: ExprKind::SelfRef,
919                                 }
920                                 .to_ref(),
921                             },
922                         }
923                     }
924                     ty::ClosureKind::FnMut => {
925                         let ref_closure_ty = cx.tcx.mk_ref(
926                             region,
927                             ty::TypeAndMut { ty: closure_ty, mutbl: hir::Mutability::Mut },
928                         );
929                         Expr {
930                             ty: closure_ty,
931                             temp_lifetime,
932                             span: expr.span,
933                             kind: ExprKind::Deref {
934                                 arg: Expr {
935                                     ty: ref_closure_ty,
936                                     temp_lifetime,
937                                     span: expr.span,
938                                     kind: ExprKind::SelfRef,
939                                 }
940                                 .to_ref(),
941                             },
942                         }
943                     }
944                     ty::ClosureKind::FnOnce => Expr {
945                         ty: closure_ty,
946                         temp_lifetime,
947                         span: expr.span,
948                         kind: ExprKind::SelfRef,
949                     },
950                 }
951             } else {
952                 Expr { ty: closure_ty, temp_lifetime, span: expr.span, kind: ExprKind::SelfRef }
953             };
954
955             // at this point we have `self.n`, which loads up the upvar
956             let field_kind =
957                 ExprKind::Field { lhs: self_expr.to_ref(), name: Field::new(upvar_index) };
958
959             // ...but the upvar might be an `&T` or `&mut T` capture, at which
960             // point we need an implicit deref
961             match cx.typeck_results().upvar_capture(upvar_id) {
962                 ty::UpvarCapture::ByValue => field_kind,
963                 ty::UpvarCapture::ByRef(borrow) => ExprKind::Deref {
964                     arg: Expr {
965                         temp_lifetime,
966                         ty: cx.tcx.mk_ref(
967                             borrow.region,
968                             ty::TypeAndMut { ty: var_ty, mutbl: borrow.kind.to_mutbl_lossy() },
969                         ),
970                         span: expr.span,
971                         kind: field_kind,
972                     }
973                     .to_ref(),
974                 },
975             }
976         }
977     }
978 }
979
980 fn bin_op(op: hir::BinOpKind) -> BinOp {
981     match op {
982         hir::BinOpKind::Add => BinOp::Add,
983         hir::BinOpKind::Sub => BinOp::Sub,
984         hir::BinOpKind::Mul => BinOp::Mul,
985         hir::BinOpKind::Div => BinOp::Div,
986         hir::BinOpKind::Rem => BinOp::Rem,
987         hir::BinOpKind::BitXor => BinOp::BitXor,
988         hir::BinOpKind::BitAnd => BinOp::BitAnd,
989         hir::BinOpKind::BitOr => BinOp::BitOr,
990         hir::BinOpKind::Shl => BinOp::Shl,
991         hir::BinOpKind::Shr => BinOp::Shr,
992         hir::BinOpKind::Eq => BinOp::Eq,
993         hir::BinOpKind::Lt => BinOp::Lt,
994         hir::BinOpKind::Le => BinOp::Le,
995         hir::BinOpKind::Ne => BinOp::Ne,
996         hir::BinOpKind::Ge => BinOp::Ge,
997         hir::BinOpKind::Gt => BinOp::Gt,
998         _ => bug!("no equivalent for ast binop {:?}", op),
999     }
1000 }
1001
1002 fn overloaded_operator<'a, 'tcx>(
1003     cx: &mut Cx<'a, 'tcx>,
1004     expr: &'tcx hir::Expr<'tcx>,
1005     args: Vec<ExprRef<'tcx>>,
1006 ) -> ExprKind<'tcx> {
1007     let fun = method_callee(cx, expr, expr.span, None);
1008     ExprKind::Call { ty: fun.ty, fun: fun.to_ref(), args, from_hir_call: false, fn_span: expr.span }
1009 }
1010
1011 fn overloaded_place<'a, 'tcx>(
1012     cx: &mut Cx<'a, 'tcx>,
1013     expr: &'tcx hir::Expr<'tcx>,
1014     place_ty: Ty<'tcx>,
1015     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
1016     args: Vec<ExprRef<'tcx>>,
1017 ) -> ExprKind<'tcx> {
1018     // For an overloaded *x or x[y] expression of type T, the method
1019     // call returns an &T and we must add the deref so that the types
1020     // line up (this is because `*x` and `x[y]` represent places):
1021
1022     let recv_ty = match args[0] {
1023         ExprRef::Thir(e) => cx.typeck_results().expr_ty_adjusted(e),
1024         ExprRef::Mirror(ref e) => e.ty,
1025     };
1026
1027     // Reconstruct the output assuming it's a reference with the
1028     // same region and mutability as the receiver. This holds for
1029     // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1030     let (region, mutbl) = match recv_ty.kind {
1031         ty::Ref(region, _, mutbl) => (region, mutbl),
1032         _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
1033     };
1034     let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl });
1035
1036     // construct the complete expression `foo()` for the overloaded call,
1037     // which will yield the &T type
1038     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1039     let fun = method_callee(cx, expr, expr.span, overloaded_callee);
1040     let ref_expr = Expr {
1041         temp_lifetime,
1042         ty: ref_ty,
1043         span: expr.span,
1044         kind: ExprKind::Call {
1045             ty: fun.ty,
1046             fun: fun.to_ref(),
1047             args,
1048             from_hir_call: false,
1049             fn_span: expr.span,
1050         },
1051     };
1052
1053     // construct and return a deref wrapper `*foo()`
1054     ExprKind::Deref { arg: ref_expr.to_ref() }
1055 }
1056
1057 fn capture_upvar<'tcx>(
1058     cx: &mut Cx<'_, 'tcx>,
1059     closure_expr: &'tcx hir::Expr<'tcx>,
1060     var_hir_id: hir::HirId,
1061     upvar_ty: Ty<'tcx>,
1062 ) -> ExprRef<'tcx> {
1063     let upvar_id = ty::UpvarId {
1064         var_path: ty::UpvarPath { hir_id: var_hir_id },
1065         closure_expr_id: cx.tcx.hir().local_def_id(closure_expr.hir_id),
1066     };
1067     let upvar_capture = cx.typeck_results().upvar_capture(upvar_id);
1068     let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1069     let var_ty = cx.typeck_results().node_type(var_hir_id);
1070     let captured_var = Expr {
1071         temp_lifetime,
1072         ty: var_ty,
1073         span: closure_expr.span,
1074         kind: convert_var(cx, closure_expr, var_hir_id),
1075     };
1076     match upvar_capture {
1077         ty::UpvarCapture::ByValue => captured_var.to_ref(),
1078         ty::UpvarCapture::ByRef(upvar_borrow) => {
1079             let borrow_kind = match upvar_borrow.kind {
1080                 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1081                 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1082                 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false },
1083             };
1084             Expr {
1085                 temp_lifetime,
1086                 ty: upvar_ty,
1087                 span: closure_expr.span,
1088                 kind: ExprKind::Borrow { borrow_kind, arg: captured_var.to_ref() },
1089             }
1090             .to_ref()
1091         }
1092     }
1093 }
1094
1095 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1096 fn field_refs<'a, 'tcx>(
1097     cx: &mut Cx<'a, 'tcx>,
1098     fields: &'tcx [hir::Field<'tcx>],
1099 ) -> Vec<FieldExprRef<'tcx>> {
1100     fields
1101         .iter()
1102         .map(|field| FieldExprRef {
1103             name: Field::new(cx.tcx.field_index(field.hir_id, cx.typeck_results)),
1104             expr: field.expr.to_ref(),
1105         })
1106         .collect()
1107 }