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