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