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