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