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