]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/hair/cx/expr.rs
Improve some compiletest documentation
[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::{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};
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::ReifyFnPointer => {
79             ExprKind::ReifyFnPointer { source: expr.to_ref() }
80         }
81         Adjust::UnsafeFnPointer => {
82             ExprKind::UnsafeFnPointer { source: expr.to_ref() }
83         }
84         Adjust::ClosureFnPointer => {
85             ExprKind::ClosureFnPointer { source: expr.to_ref() }
86         }
87         Adjust::NeverToAny => {
88             ExprKind::NeverToAny { source: expr.to_ref() }
89         }
90         Adjust::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::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::VariantCtor(variant_id, CtorKind::Fn) => {
265                                 Some((adt_def, adt_def.variant_index_with_id(variant_id)))
266                             }
267                             Def::StructCtor(_, CtorKind::Fn) |
268                             Def::SelfCtor(..) => Some((adt_def, VariantIdx::new(0))),
269                             _ => None,
270                         }
271                     })
272                 } else {
273                     None
274                 };
275                 if let Some((adt_def, index)) = adt_data {
276                     let substs = cx.tables().node_substs(fun.hir_id);
277                     let user_provided_types = cx.tables().user_provided_types();
278                     let user_ty = user_provided_types.get(fun.hir_id)
279                         .map(|u_ty| *u_ty)
280                         .map(|mut u_ty| {
281                             if let UserType::TypeOf(ref mut did, _) = &mut u_ty.value {
282                                 *did = adt_def.did;
283                             }
284                             u_ty
285                         });
286                     debug!("make_mirror_unadjusted: (call) user_ty={:?}", user_ty);
287
288                     let field_refs = args.iter()
289                         .enumerate()
290                         .map(|(idx, e)| {
291                             FieldExprRef {
292                                 name: Field::new(idx),
293                                 expr: e.to_ref(),
294                             }
295                         })
296                         .collect();
297                     ExprKind::Adt {
298                         adt_def,
299                         substs,
300                         variant_index: index,
301                         fields: field_refs,
302                         user_ty,
303                         base: None,
304                     }
305                 } else {
306                     ExprKind::Call {
307                         ty: cx.tables().node_type(fun.hir_id),
308                         fun: fun.to_ref(),
309                         args: args.to_ref(),
310                         from_hir_call: true,
311                     }
312                 }
313             }
314         }
315
316         hir::ExprKind::AddrOf(mutbl, ref expr) => {
317             ExprKind::Borrow {
318                 borrow_kind: mutbl.to_borrow_kind(),
319                 arg: expr.to_ref(),
320             }
321         }
322
323         hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: &blk },
324
325         hir::ExprKind::Assign(ref lhs, ref rhs) => {
326             ExprKind::Assign {
327                 lhs: lhs.to_ref(),
328                 rhs: rhs.to_ref(),
329             }
330         }
331
332         hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
333             if cx.tables().is_method_call(expr) {
334                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
335             } else {
336                 ExprKind::AssignOp {
337                     op: bin_op(op.node),
338                     lhs: lhs.to_ref(),
339                     rhs: rhs.to_ref(),
340                 }
341             }
342         }
343
344         hir::ExprKind::Lit(ref lit) => ExprKind::Literal {
345             literal: cx.tcx.mk_const(
346                 cx.const_eval_literal(&lit.node, expr_ty, lit.span, false)
347             ),
348             user_ty: None,
349         },
350
351         hir::ExprKind::Binary(op, ref lhs, ref rhs) => {
352             if cx.tables().is_method_call(expr) {
353                 overloaded_operator(cx, expr, vec![lhs.to_ref(), rhs.to_ref()])
354             } else {
355                 // FIXME overflow
356                 match (op.node, cx.constness) {
357                     // FIXME(eddyb) use logical ops in constants when
358                     // they can handle that kind of control-flow.
359                     (hir::BinOpKind::And, hir::Constness::Const) => {
360                         cx.control_flow_destroyed.push((
361                             op.span,
362                             "`&&` operator".into(),
363                         ));
364                         ExprKind::Binary {
365                             op: BinOp::BitAnd,
366                             lhs: lhs.to_ref(),
367                             rhs: rhs.to_ref(),
368                         }
369                     }
370                     (hir::BinOpKind::Or, hir::Constness::Const) => {
371                         cx.control_flow_destroyed.push((
372                             op.span,
373                             "`||` operator".into(),
374                         ));
375                         ExprKind::Binary {
376                             op: BinOp::BitOr,
377                             lhs: lhs.to_ref(),
378                             rhs: rhs.to_ref(),
379                         }
380                     }
381
382                     (hir::BinOpKind::And, hir::Constness::NotConst) => {
383                         ExprKind::LogicalOp {
384                             op: LogicalOp::And,
385                             lhs: lhs.to_ref(),
386                             rhs: rhs.to_ref(),
387                         }
388                     }
389                     (hir::BinOpKind::Or, hir::Constness::NotConst) => {
390                         ExprKind::LogicalOp {
391                             op: LogicalOp::Or,
392                             lhs: lhs.to_ref(),
393                             rhs: rhs.to_ref(),
394                         }
395                     }
396
397                     _ => {
398                         let op = bin_op(op.node);
399                         ExprKind::Binary {
400                             op,
401                             lhs: lhs.to_ref(),
402                             rhs: rhs.to_ref(),
403                         }
404                     }
405                 }
406             }
407         }
408
409         hir::ExprKind::Index(ref lhs, ref index) => {
410             if cx.tables().is_method_call(expr) {
411                 overloaded_place(cx, expr, expr_ty, None, vec![lhs.to_ref(), index.to_ref()])
412             } else {
413                 ExprKind::Index {
414                     lhs: lhs.to_ref(),
415                     index: index.to_ref(),
416                 }
417             }
418         }
419
420         hir::ExprKind::Unary(hir::UnOp::UnDeref, ref arg) => {
421             if cx.tables().is_method_call(expr) {
422                 overloaded_place(cx, expr, expr_ty, None, vec![arg.to_ref()])
423             } else {
424                 ExprKind::Deref { arg: arg.to_ref() }
425             }
426         }
427
428         hir::ExprKind::Unary(hir::UnOp::UnNot, ref arg) => {
429             if cx.tables().is_method_call(expr) {
430                 overloaded_operator(cx, expr, vec![arg.to_ref()])
431             } else {
432                 ExprKind::Unary {
433                     op: UnOp::Not,
434                     arg: arg.to_ref(),
435                 }
436             }
437         }
438
439         hir::ExprKind::Unary(hir::UnOp::UnNeg, ref arg) => {
440             if cx.tables().is_method_call(expr) {
441                 overloaded_operator(cx, expr, vec![arg.to_ref()])
442             } else {
443                 if let hir::ExprKind::Lit(ref lit) = arg.node {
444                     ExprKind::Literal {
445                         literal: cx.tcx.mk_const(
446                             cx.const_eval_literal(&lit.node, expr_ty, lit.span, true)
447                         ),
448                         user_ty: None,
449                     }
450                 } else {
451                     ExprKind::Unary {
452                         op: UnOp::Neg,
453                         arg: arg.to_ref(),
454                     }
455                 }
456             }
457         }
458
459         hir::ExprKind::Struct(ref qpath, ref fields, ref base) => {
460             match expr_ty.sty {
461                 ty::Adt(adt, substs) => {
462                     match adt.adt_kind() {
463                         AdtKind::Struct | AdtKind::Union => {
464                             let user_provided_types = cx.tables().user_provided_types();
465                             let user_ty = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
466                             debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty);
467                             ExprKind::Adt {
468                                 adt_def: adt,
469                                 variant_index: VariantIdx::new(0),
470                                 substs,
471                                 user_ty,
472                                 fields: field_refs(cx, fields),
473                                 base: base.as_ref().map(|base| {
474                                     FruInfo {
475                                         base: base.to_ref(),
476                                         field_types: cx.tables()
477                                                        .fru_field_types()[expr.hir_id]
478                                                        .clone(),
479                                     }
480                                 }),
481                             }
482                         }
483                         AdtKind::Enum => {
484                             let def = cx.tables().qpath_def(qpath, expr.hir_id);
485                             match def {
486                                 Def::Variant(variant_id) => {
487                                     assert!(base.is_none());
488
489                                     let index = adt.variant_index_with_id(variant_id);
490                                     let user_provided_types = cx.tables().user_provided_types();
491                                     let user_ty = user_provided_types.get(expr.hir_id)
492                                         .map(|u_ty| *u_ty);
493                                     debug!(
494                                         "make_mirror_unadjusted: (variant) user_ty={:?}",
495                                         user_ty
496                                     );
497                                     ExprKind::Adt {
498                                         adt_def: adt,
499                                         variant_index: index,
500                                         substs,
501                                         user_ty,
502                                         fields: field_refs(cx, fields),
503                                         base: None,
504                                     }
505                                 }
506                                 _ => {
507                                     span_bug!(expr.span, "unexpected def: {:?}", def);
508                                 }
509                             }
510                         }
511                     }
512                 }
513                 _ => {
514                     span_bug!(expr.span,
515                               "unexpected type for struct literal: {:?}",
516                               expr_ty);
517                 }
518             }
519         }
520
521         hir::ExprKind::Closure(..) => {
522             let closure_ty = cx.tables().expr_ty(expr);
523             let (def_id, substs, movability) = match closure_ty.sty {
524                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None),
525                 ty::Generator(def_id, substs, movability) => {
526                     (def_id, UpvarSubsts::Generator(substs), Some(movability))
527                 }
528                 _ => {
529                     span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty);
530                 }
531             };
532             let upvars = cx.tcx.with_freevars(expr.hir_id, |freevars| {
533                 freevars.iter()
534                     .zip(substs.upvar_tys(def_id, cx.tcx))
535                     .map(|(fv, ty)| capture_freevar(cx, expr, fv, ty))
536                     .collect()
537             });
538             ExprKind::Closure {
539                 closure_id: def_id,
540                 substs,
541                 upvars,
542                 movability,
543             }
544         }
545
546         hir::ExprKind::Path(ref qpath) => {
547             let def = cx.tables().qpath_def(qpath, expr.hir_id);
548             convert_path_expr(cx, expr, def)
549         }
550
551         hir::ExprKind::InlineAsm(ref asm, ref outputs, ref inputs) => {
552             ExprKind::InlineAsm {
553                 asm,
554                 outputs: outputs.to_ref(),
555                 inputs: inputs.to_ref(),
556             }
557         }
558
559         // Now comes the rote stuff:
560         hir::ExprKind::Repeat(ref v, ref count) => {
561             let def_id = cx.tcx.hir().local_def_id_from_hir_id(count.hir_id);
562             let substs = InternalSubsts::identity_for_item(cx.tcx.global_tcx(), def_id);
563             let instance = ty::Instance::resolve(
564                 cx.tcx.global_tcx(),
565                 cx.param_env,
566                 def_id,
567                 substs,
568             ).unwrap();
569             let global_id = GlobalId {
570                 instance,
571                 promoted: None
572             };
573             let span = cx.tcx.def_span(def_id);
574             let count = match cx.tcx.at(span).const_eval(cx.param_env.and(global_id)) {
575                 Ok(cv) => cv.unwrap_usize(cx.tcx),
576                 Err(ErrorHandled::Reported) => 0,
577                 Err(ErrorHandled::TooGeneric) => {
578                     cx.tcx.sess.span_err(span, "array lengths can't depend on generic parameters");
579                     0
580                 },
581             };
582
583             ExprKind::Repeat {
584                 value: v.to_ref(),
585                 count,
586             }
587         }
588         hir::ExprKind::Ret(ref v) => ExprKind::Return { value: v.to_ref() },
589         hir::ExprKind::Break(dest, ref value) => {
590             match dest.target_id {
591                 Ok(target_id) => ExprKind::Break {
592                     label: region::Scope {
593                         id: target_id.local_id,
594                         data: region::ScopeData::Node
595                     },
596                     value: value.to_ref(),
597                 },
598                 Err(err) => bug!("invalid loop id for break: {}", err)
599             }
600         }
601         hir::ExprKind::Continue(dest) => {
602             match dest.target_id {
603                 Ok(loop_id) => ExprKind::Continue {
604                     label: region::Scope {
605                         id: loop_id.local_id,
606                         data: region::ScopeData::Node
607                     },
608                 },
609                 Err(err) => bug!("invalid loop id for continue: {}", err)
610             }
611         }
612         hir::ExprKind::Match(ref discr, ref arms, _) => {
613             ExprKind::Match {
614                 scrutinee: discr.to_ref(),
615                 arms: arms.iter().map(|a| convert_arm(cx, a)).collect(),
616             }
617         }
618         hir::ExprKind::If(ref cond, ref then, ref otherwise) => {
619             ExprKind::If {
620                 condition: cond.to_ref(),
621                 then: then.to_ref(),
622                 otherwise: otherwise.to_ref(),
623             }
624         }
625         hir::ExprKind::While(ref cond, ref body, _) => {
626             ExprKind::Loop {
627                 condition: Some(cond.to_ref()),
628                 body: block::to_expr_ref(cx, body),
629             }
630         }
631         hir::ExprKind::Loop(ref body, _, _) => {
632             ExprKind::Loop {
633                 condition: None,
634                 body: block::to_expr_ref(cx, body),
635             }
636         }
637         hir::ExprKind::Field(ref source, ..) => {
638             ExprKind::Field {
639                 lhs: source.to_ref(),
640                 name: Field::new(cx.tcx.field_index(expr.hir_id, cx.tables)),
641             }
642         }
643         hir::ExprKind::Cast(ref source, ref cast_ty) => {
644             // Check for a user-given type annotation on this `cast`
645             let user_provided_types = cx.tables.user_provided_types();
646             let user_ty = user_provided_types.get(cast_ty.hir_id);
647
648             debug!(
649                 "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}",
650                 expr,
651                 cast_ty.hir_id,
652                 user_ty,
653             );
654
655             // Check to see if this cast is a "coercion cast", where the cast is actually done
656             // using a coercion (or is a no-op).
657             let cast = if cx.tables().is_coercion_cast(source.hir_id) {
658                 // Convert the lexpr to a vexpr.
659                 ExprKind::Use { source: source.to_ref() }
660             } else {
661                 // check whether this is casting an enum variant discriminant
662                 // to prevent cycles, we refer to the discriminant initializer
663                 // which is always an integer and thus doesn't need to know the
664                 // enum's layout (or its tag type) to compute it during const eval
665                 // Example:
666                 // enum Foo {
667                 //     A,
668                 //     B = A as isize + 4,
669                 // }
670                 // The correct solution would be to add symbolic computations to miri,
671                 // so we wouldn't have to compute and store the actual value
672                 let var = if let hir::ExprKind::Path(ref qpath) = source.node {
673                     let def = cx.tables().qpath_def(qpath, source.hir_id);
674                     cx
675                         .tables()
676                         .node_type(source.hir_id)
677                         .ty_adt_def()
678                         .and_then(|adt_def| {
679                         match def {
680                             Def::VariantCtor(variant_id, CtorKind::Const) => {
681                                 let idx = adt_def.variant_index_with_id(variant_id);
682                                 let (d, o) = adt_def.discriminant_def_for_variant(idx);
683                                 use rustc::ty::util::IntTypeExt;
684                                 let ty = adt_def.repr.discr_type();
685                                 let ty = ty.to_ty(cx.tcx());
686                                 Some((d, o, ty))
687                             }
688                             _ => None,
689                         }
690                     })
691                 } else {
692                     None
693                 };
694
695                 let source = if let Some((did, offset, var_ty)) = var {
696                     let mk_const = |literal| Expr {
697                         temp_lifetime,
698                         ty: var_ty,
699                         span: expr.span,
700                         kind: ExprKind::Literal {
701                             literal: cx.tcx.mk_const(literal),
702                             user_ty: None
703                         },
704                     }.to_ref();
705                     let offset = mk_const(ty::Const::from_bits(
706                         cx.tcx,
707                         offset as u128,
708                         cx.param_env.and(var_ty),
709                     ));
710                     match did {
711                         Some(did) => {
712                             // in case we are offsetting from a computed discriminant
713                             // and not the beginning of discriminants (which is always `0`)
714                             let substs = InternalSubsts::identity_for_item(cx.tcx(), did);
715                             let lhs = mk_const(ty::Const {
716                                 val: ConstValue::Unevaluated(did, substs),
717                                 ty: var_ty,
718                             });
719                             let bin = ExprKind::Binary {
720                                 op: BinOp::Add,
721                                 lhs,
722                                 rhs: offset,
723                             };
724                             Expr {
725                                 temp_lifetime,
726                                 ty: var_ty,
727                                 span: expr.span,
728                                 kind: bin,
729                             }.to_ref()
730                         },
731                         None => offset,
732                     }
733                 } else {
734                     source.to_ref()
735                 };
736
737                 ExprKind::Cast { source }
738             };
739
740             if let Some(user_ty) = user_ty {
741                 // NOTE: Creating a new Expr and wrapping a Cast inside of it may be
742                 //       inefficient, revisit this when performance becomes an issue.
743                 let cast_expr = Expr {
744                     temp_lifetime,
745                     ty: expr_ty,
746                     span: expr.span,
747                     kind: cast,
748                 };
749                 debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty);
750
751                 ExprKind::ValueTypeAscription {
752                     source: cast_expr.to_ref(),
753                     user_ty: Some(*user_ty),
754                 }
755             } else {
756                 cast
757             }
758         }
759         hir::ExprKind::Type(ref source, ref ty) => {
760             let user_provided_types = cx.tables.user_provided_types();
761             let user_ty = user_provided_types.get(ty.hir_id).map(|u_ty| *u_ty);
762             debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty);
763             if source.is_place_expr() {
764                 ExprKind::PlaceTypeAscription {
765                     source: source.to_ref(),
766                     user_ty,
767                 }
768             } else {
769                 ExprKind::ValueTypeAscription {
770                     source: source.to_ref(),
771                     user_ty,
772                 }
773             }
774         }
775         hir::ExprKind::Box(ref value) => {
776             ExprKind::Box {
777                 value: value.to_ref(),
778             }
779         }
780         hir::ExprKind::Array(ref fields) => ExprKind::Array { fields: fields.to_ref() },
781         hir::ExprKind::Tup(ref fields) => ExprKind::Tuple { fields: fields.to_ref() },
782
783         hir::ExprKind::Yield(ref v) => ExprKind::Yield { value: v.to_ref() },
784         hir::ExprKind::Err => unreachable!(),
785     };
786
787     Expr {
788         temp_lifetime,
789         ty: expr_ty,
790         span: expr.span,
791         kind,
792     }
793 }
794
795 fn user_substs_applied_to_def(
796     cx: &mut Cx<'a, 'gcx, 'tcx>,
797     hir_id: hir::HirId,
798     def: &Def,
799 ) -> Option<ty::CanonicalUserType<'tcx>> {
800     debug!("user_substs_applied_to_def: def={:?}", def);
801     let user_provided_type = match def {
802         // A reference to something callable -- e.g., a fn, method, or
803         // a tuple-struct or tuple-variant. This has the type of a
804         // `Fn` but with the user-given substitutions.
805         Def::Fn(_) |
806         Def::Method(_) |
807         Def::StructCtor(_, CtorKind::Fn) |
808         Def::VariantCtor(_, CtorKind::Fn) |
809         Def::Const(_) |
810         Def::AssociatedConst(_) => cx.tables().user_provided_types().get(hir_id).map(|u_ty| *u_ty),
811
812         // A unit struct/variant which is used as a value (e.g.,
813         // `None`). This has the type of the enum/struct that defines
814         // this variant -- but with the substitutions given by the
815         // user.
816         Def::StructCtor(_def_id, CtorKind::Const) |
817         Def::VariantCtor(_def_id, CtorKind::Const) =>
818             cx.user_substs_applied_to_ty_of_hir_id(hir_id),
819
820         // `Self` is used in expression as a tuple struct constructor or an unit struct constructor
821         Def::SelfCtor(_) =>
822             cx.user_substs_applied_to_ty_of_hir_id(hir_id),
823
824         _ =>
825             bug!("user_substs_applied_to_def: unexpected def {:?} at {:?}", def, hir_id)
826     };
827     debug!("user_substs_applied_to_def: user_provided_type={:?}", user_provided_type);
828     user_provided_type
829 }
830
831 fn method_callee<'a, 'gcx, 'tcx>(
832     cx: &mut Cx<'a, 'gcx, 'tcx>,
833     expr: &hir::Expr,
834     span: Span,
835     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
836 ) -> Expr<'tcx> {
837     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
838     let (def_id, substs, user_ty) = match overloaded_callee {
839         Some((def_id, substs)) => (def_id, substs, None),
840         None => {
841             let type_dependent_defs = cx.tables().type_dependent_defs();
842             let def = type_dependent_defs
843                 .get(expr.hir_id)
844                 .unwrap_or_else(|| {
845                     span_bug!(expr.span, "no type-dependent def for method callee")
846                 });
847             let user_ty = user_substs_applied_to_def(cx, expr.hir_id, def);
848             debug!("method_callee: user_ty={:?}", user_ty);
849             (def.def_id(), cx.tables().node_substs(expr.hir_id), user_ty)
850         }
851     };
852     let ty = cx.tcx().mk_fn_def(def_id, substs);
853     Expr {
854         temp_lifetime,
855         ty,
856         span,
857         kind: ExprKind::Literal {
858             literal: cx.tcx().mk_const(
859                 ty::Const::zero_sized(ty)
860             ),
861             user_ty,
862         },
863     }
864 }
865
866 trait ToBorrowKind { fn to_borrow_kind(&self) -> BorrowKind; }
867
868 impl ToBorrowKind for AutoBorrowMutability {
869     fn to_borrow_kind(&self) -> BorrowKind {
870         use rustc::ty::adjustment::AllowTwoPhase;
871         match *self {
872             AutoBorrowMutability::Mutable { allow_two_phase_borrow } =>
873                 BorrowKind::Mut { allow_two_phase_borrow: match allow_two_phase_borrow {
874                     AllowTwoPhase::Yes => true,
875                     AllowTwoPhase::No => false
876                 }},
877             AutoBorrowMutability::Immutable =>
878                 BorrowKind::Shared,
879         }
880     }
881 }
882
883 impl ToBorrowKind for hir::Mutability {
884     fn to_borrow_kind(&self) -> BorrowKind {
885         match *self {
886             hir::MutMutable => BorrowKind::Mut { allow_two_phase_borrow: false },
887             hir::MutImmutable => BorrowKind::Shared,
888         }
889     }
890 }
891
892 fn convert_arm<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, arm: &'tcx hir::Arm) -> Arm<'tcx> {
893     Arm {
894         patterns: arm.pats.iter().map(|p| cx.pattern_from_hir(p)).collect(),
895         guard: match arm.guard {
896                 Some(hir::Guard::If(ref e)) => Some(Guard::If(e.to_ref())),
897                 _ => None,
898             },
899         body: arm.body.to_ref(),
900         // BUG: fix this
901         lint_level: LintLevel::Inherited,
902     }
903 }
904
905 fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
906                                      expr: &'tcx hir::Expr,
907                                      def: Def)
908                                      -> ExprKind<'tcx> {
909     let substs = cx.tables().node_substs(expr.hir_id);
910     match def {
911         // A regular function, constructor function or a constant.
912         Def::Fn(_) |
913         Def::Method(_) |
914         Def::StructCtor(_, CtorKind::Fn) |
915         Def::VariantCtor(_, CtorKind::Fn) |
916         Def::SelfCtor(..) => {
917             let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
918             debug!("convert_path_expr: user_ty={:?}", user_ty);
919             ExprKind::Literal {
920                 literal: cx.tcx.mk_const(ty::Const::zero_sized(
921                     cx.tables().node_type(expr.hir_id),
922                 )),
923                 user_ty,
924             }
925         }
926
927         Def::ConstParam(def_id) => {
928             let node_id = cx.tcx.hir().as_local_node_id(def_id).unwrap();
929             let item_id = cx.tcx.hir().get_parent_node(node_id);
930             let item_def_id = cx.tcx.hir().local_def_id(item_id);
931             let generics = cx.tcx.generics_of(item_def_id);
932             let index = generics.param_def_id_to_index[&cx.tcx.hir().local_def_id(node_id)];
933             let name = cx.tcx.hir().name(node_id).as_interned_str();
934             let val = ConstValue::Param(ty::ParamConst::new(index, name));
935             ExprKind::Literal {
936                 literal: cx.tcx.mk_const(
937                     ty::Const {
938                         val,
939                         ty: cx.tables().node_type(expr.hir_id),
940                     }
941                 ),
942                 user_ty: None,
943             }
944         }
945
946         Def::Const(def_id) |
947         Def::AssociatedConst(def_id) => {
948             let user_ty = user_substs_applied_to_def(cx, expr.hir_id, &def);
949             debug!("convert_path_expr: (const) user_ty={:?}", user_ty);
950             ExprKind::Literal {
951                 literal: cx.tcx.mk_const(ty::Const {
952                     val: ConstValue::Unevaluated(def_id, substs),
953                     ty: cx.tcx.type_of(def_id),
954                 }),
955                 user_ty,
956             }
957         },
958
959         Def::StructCtor(def_id, CtorKind::Const) |
960         Def::VariantCtor(def_id, CtorKind::Const) => {
961             let user_provided_types = cx.tables.user_provided_types();
962             let user_provided_type = user_provided_types.get(expr.hir_id).map(|u_ty| *u_ty);
963             debug!("convert_path_expr: user_provided_type={:?}", user_provided_type);
964             let ty = cx.tables().node_type(expr.hir_id);
965             match ty.sty {
966                 // A unit struct/variant which is used as a value.
967                 // We return a completely different ExprKind here to account for this special case.
968                 ty::Adt(adt_def, substs) => {
969                     ExprKind::Adt {
970                         adt_def,
971                         variant_index: adt_def.variant_index_with_id(def_id),
972                         substs,
973                         user_ty: user_provided_type,
974                         fields: vec![],
975                         base: None,
976                     }
977                 }
978                 _ => bug!("unexpected ty: {:?}", ty),
979             }
980         }
981
982         Def::Static(node_id, _) => ExprKind::StaticRef { id: node_id },
983
984         Def::Local(..) | Def::Upvar(..) => convert_var(cx, expr, def),
985
986         _ => span_bug!(expr.span, "def `{:?}` not yet implemented", def),
987     }
988 }
989
990 fn convert_var<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
991                                expr: &'tcx hir::Expr,
992                                def: Def)
993                                -> ExprKind<'tcx> {
994     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
995
996     match def {
997         Def::Local(id) => ExprKind::VarRef { id: cx.tcx.hir().node_to_hir_id(id) },
998
999         Def::Upvar(var_id, index, closure_expr_id) => {
1000             debug!("convert_var(upvar({:?}, {:?}, {:?}))",
1001                    var_id,
1002                    index,
1003                    closure_expr_id);
1004             let var_hir_id = cx.tcx.hir().node_to_hir_id(var_id);
1005             let var_ty = cx.tables().node_type(var_hir_id);
1006
1007             // FIXME free regions in closures are not right
1008             let closure_ty = cx.tables()
1009                                .node_type(cx.tcx.hir().node_to_hir_id(closure_expr_id));
1010
1011             // FIXME we're just hard-coding the idea that the
1012             // signature will be &self or &mut self and hence will
1013             // have a bound region with number 0
1014             let closure_def_id = cx.tcx.hir().local_def_id(closure_expr_id);
1015             let region = ty::ReFree(ty::FreeRegion {
1016                 scope: closure_def_id,
1017                 bound_region: ty::BoundRegion::BrAnon(0),
1018             });
1019             let region = cx.tcx.mk_region(region);
1020
1021             let self_expr = if let ty::Closure(_, closure_substs) = closure_ty.sty {
1022                 match cx.infcx.closure_kind(closure_def_id, closure_substs).unwrap() {
1023                     ty::ClosureKind::Fn => {
1024                         let ref_closure_ty = cx.tcx.mk_ref(region,
1025                                                            ty::TypeAndMut {
1026                                                                ty: closure_ty,
1027                                                                mutbl: hir::MutImmutable,
1028                                                            });
1029                         Expr {
1030                             ty: closure_ty,
1031                             temp_lifetime: temp_lifetime,
1032                             span: expr.span,
1033                             kind: ExprKind::Deref {
1034                                 arg: Expr {
1035                                     ty: ref_closure_ty,
1036                                     temp_lifetime,
1037                                     span: expr.span,
1038                                     kind: ExprKind::SelfRef,
1039                                 }
1040                                 .to_ref(),
1041                             },
1042                         }
1043                     }
1044                     ty::ClosureKind::FnMut => {
1045                         let ref_closure_ty = cx.tcx.mk_ref(region,
1046                                                            ty::TypeAndMut {
1047                                                                ty: closure_ty,
1048                                                                mutbl: hir::MutMutable,
1049                                                            });
1050                         Expr {
1051                             ty: closure_ty,
1052                             temp_lifetime,
1053                             span: expr.span,
1054                             kind: ExprKind::Deref {
1055                                 arg: Expr {
1056                                     ty: ref_closure_ty,
1057                                     temp_lifetime,
1058                                     span: expr.span,
1059                                     kind: ExprKind::SelfRef,
1060                                 }.to_ref(),
1061                             },
1062                         }
1063                     }
1064                     ty::ClosureKind::FnOnce => {
1065                         Expr {
1066                             ty: closure_ty,
1067                             temp_lifetime,
1068                             span: expr.span,
1069                             kind: ExprKind::SelfRef,
1070                         }
1071                     }
1072                 }
1073             } else {
1074                 Expr {
1075                     ty: closure_ty,
1076                     temp_lifetime,
1077                     span: expr.span,
1078                     kind: ExprKind::SelfRef,
1079                 }
1080             };
1081
1082             // at this point we have `self.n`, which loads up the upvar
1083             let field_kind = ExprKind::Field {
1084                 lhs: self_expr.to_ref(),
1085                 name: Field::new(index),
1086             };
1087
1088             // ...but the upvar might be an `&T` or `&mut T` capture, at which
1089             // point we need an implicit deref
1090             let upvar_id = ty::UpvarId {
1091                 var_path: ty::UpvarPath {hir_id: var_hir_id},
1092                 closure_expr_id: LocalDefId::from_def_id(closure_def_id),
1093             };
1094             match cx.tables().upvar_capture(upvar_id) {
1095                 ty::UpvarCapture::ByValue => field_kind,
1096                 ty::UpvarCapture::ByRef(borrow) => {
1097                     ExprKind::Deref {
1098                         arg: Expr {
1099                             temp_lifetime,
1100                             ty: cx.tcx.mk_ref(borrow.region,
1101                                               ty::TypeAndMut {
1102                                                   ty: var_ty,
1103                                                   mutbl: borrow.kind.to_mutbl_lossy(),
1104                                               }),
1105                             span: expr.span,
1106                             kind: field_kind,
1107                         }.to_ref(),
1108                     }
1109                 }
1110             }
1111         }
1112
1113         _ => span_bug!(expr.span, "type of & not region"),
1114     }
1115 }
1116
1117
1118 fn bin_op(op: hir::BinOpKind) -> BinOp {
1119     match op {
1120         hir::BinOpKind::Add => BinOp::Add,
1121         hir::BinOpKind::Sub => BinOp::Sub,
1122         hir::BinOpKind::Mul => BinOp::Mul,
1123         hir::BinOpKind::Div => BinOp::Div,
1124         hir::BinOpKind::Rem => BinOp::Rem,
1125         hir::BinOpKind::BitXor => BinOp::BitXor,
1126         hir::BinOpKind::BitAnd => BinOp::BitAnd,
1127         hir::BinOpKind::BitOr => BinOp::BitOr,
1128         hir::BinOpKind::Shl => BinOp::Shl,
1129         hir::BinOpKind::Shr => BinOp::Shr,
1130         hir::BinOpKind::Eq => BinOp::Eq,
1131         hir::BinOpKind::Lt => BinOp::Lt,
1132         hir::BinOpKind::Le => BinOp::Le,
1133         hir::BinOpKind::Ne => BinOp::Ne,
1134         hir::BinOpKind::Ge => BinOp::Ge,
1135         hir::BinOpKind::Gt => BinOp::Gt,
1136         _ => bug!("no equivalent for ast binop {:?}", op),
1137     }
1138 }
1139
1140 fn overloaded_operator<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1141                                        expr: &'tcx hir::Expr,
1142                                        args: Vec<ExprRef<'tcx>>)
1143                                        -> ExprKind<'tcx> {
1144     let fun = method_callee(cx, expr, expr.span, None);
1145     ExprKind::Call {
1146         ty: fun.ty,
1147         fun: fun.to_ref(),
1148         args,
1149         from_hir_call: false,
1150     }
1151 }
1152
1153 fn overloaded_place<'a, 'gcx, 'tcx>(
1154     cx: &mut Cx<'a, 'gcx, 'tcx>,
1155     expr: &'tcx hir::Expr,
1156     place_ty: Ty<'tcx>,
1157     overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>,
1158     args: Vec<ExprRef<'tcx>>,
1159 ) -> ExprKind<'tcx> {
1160     // For an overloaded *x or x[y] expression of type T, the method
1161     // call returns an &T and we must add the deref so that the types
1162     // line up (this is because `*x` and `x[y]` represent places):
1163
1164     let recv_ty = match args[0] {
1165         ExprRef::Hair(e) => cx.tables().expr_ty_adjusted(e),
1166         ExprRef::Mirror(ref e) => e.ty
1167     };
1168
1169     // Reconstruct the output assuming it's a reference with the
1170     // same region and mutability as the receiver. This holds for
1171     // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`.
1172     let (region, mutbl) = match recv_ty.sty {
1173         ty::Ref(region, _, mutbl) => (region, mutbl),
1174         _ => span_bug!(expr.span, "overloaded_place: receiver is not a reference"),
1175     };
1176     let ref_ty = cx.tcx.mk_ref(region, ty::TypeAndMut {
1177         ty: place_ty,
1178         mutbl,
1179     });
1180
1181     // construct the complete expression `foo()` for the overloaded call,
1182     // which will yield the &T type
1183     let temp_lifetime = cx.region_scope_tree.temporary_scope(expr.hir_id.local_id);
1184     let fun = method_callee(cx, expr, expr.span, overloaded_callee);
1185     let ref_expr = Expr {
1186         temp_lifetime,
1187         ty: ref_ty,
1188         span: expr.span,
1189         kind: ExprKind::Call {
1190             ty: fun.ty,
1191             fun: fun.to_ref(),
1192             args,
1193             from_hir_call: false,
1194         },
1195     };
1196
1197     // construct and return a deref wrapper `*foo()`
1198     ExprKind::Deref { arg: ref_expr.to_ref() }
1199 }
1200
1201 fn capture_freevar<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1202                                    closure_expr: &'tcx hir::Expr,
1203                                    freevar: &hir::Freevar,
1204                                    freevar_ty: Ty<'tcx>)
1205                                    -> ExprRef<'tcx> {
1206     let var_hir_id = cx.tcx.hir().node_to_hir_id(freevar.var_id());
1207     let upvar_id = ty::UpvarId {
1208         var_path: ty::UpvarPath { hir_id: var_hir_id },
1209         closure_expr_id: cx.tcx.hir().local_def_id_from_hir_id(closure_expr.hir_id).to_local(),
1210     };
1211     let upvar_capture = cx.tables().upvar_capture(upvar_id);
1212     let temp_lifetime = cx.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id);
1213     let var_ty = cx.tables().node_type(var_hir_id);
1214     let captured_var = Expr {
1215         temp_lifetime,
1216         ty: var_ty,
1217         span: closure_expr.span,
1218         kind: convert_var(cx, closure_expr, freevar.def),
1219     };
1220     match upvar_capture {
1221         ty::UpvarCapture::ByValue => captured_var.to_ref(),
1222         ty::UpvarCapture::ByRef(upvar_borrow) => {
1223             let borrow_kind = match upvar_borrow.kind {
1224                 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
1225                 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
1226                 ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }
1227             };
1228             Expr {
1229                 temp_lifetime,
1230                 ty: freevar_ty,
1231                 span: closure_expr.span,
1232                 kind: ExprKind::Borrow {
1233                     borrow_kind,
1234                     arg: captured_var.to_ref(),
1235                 },
1236             }.to_ref()
1237         }
1238     }
1239 }
1240
1241 /// Converts a list of named fields (i.e., for struct-like struct/enum ADTs) into FieldExprRef.
1242 fn field_refs<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>,
1243                               fields: &'tcx [hir::Field])
1244                               -> Vec<FieldExprRef<'tcx>> {
1245     fields.iter()
1246         .map(|field| {
1247             FieldExprRef {
1248                 name: Field::new(cx.tcx.field_index(field.hir_id, cx.tables)),
1249                 expr: field.expr.to_ref(),
1250             }
1251         })
1252         .collect()
1253 }