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