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