]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/tcx/expr.rs
Remove random Idents outside of libsyntax
[rust.git] / src / librustc_mir / tcx / expr.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use hair::*;
12 use repr::*;
13 use rustc_data_structures::fnv::FnvHashMap;
14 use std::rc::Rc;
15 use tcx::Cx;
16 use tcx::block;
17 use tcx::pattern::PatNode;
18 use tcx::rustc::front::map;
19 use tcx::rustc::middle::def;
20 use tcx::rustc::middle::def_id::DefId;
21 use tcx::rustc::middle::region::CodeExtent;
22 use tcx::rustc::middle::pat_util;
23 use tcx::rustc::middle::ty::{self, Ty};
24 use tcx::rustc_front::hir;
25 use tcx::rustc_front::util as hir_util;
26 use tcx::syntax::ast;
27 use tcx::syntax::codemap::Span;
28 use tcx::syntax::parse::token;
29 use tcx::syntax::ptr::P;
30 use tcx::to_ref::ToRef;
31
32 impl<'a,'tcx:'a> Mirror<Cx<'a,'tcx>> for &'tcx hir::Expr {
33     type Output = Expr<Cx<'a,'tcx>>;
34
35     fn make_mirror(self, cx: &mut Cx<'a,'tcx>) -> Expr<Cx<'a,'tcx>> {
36         debug!("Expr::make_mirror(): id={}, span={:?}", self.id, self.span);
37
38         let expr_ty = cx.tcx.expr_ty(self); // note: no adjustments (yet)!
39
40         let kind = match self.node {
41             // Here comes the interesting stuff:
42
43             hir::ExprMethodCall(_, _, ref args) => {
44                 // Rewrite a.b(c) into UFCS form like Trait::b(a, c)
45                 let expr = method_callee(cx, self, ty::MethodCall::expr(self.id));
46                 let args = args.iter()
47                                .map(|e| e.to_ref())
48                                .collect();
49                 ExprKind::Call {
50                     fun: expr.to_ref(),
51                     args: args
52                 }
53             }
54
55             hir::ExprAddrOf(mutbl, ref expr) => {
56                 let region = match expr_ty.sty {
57                     ty::TyRef(r, _) => r,
58                     _ => cx.tcx.sess.span_bug(expr.span, "type of & not region")
59                 };
60                 ExprKind::Borrow { region: *region,
61                                    borrow_kind: to_borrow_kind(mutbl),
62                                    arg: expr.to_ref() }
63             }
64
65             hir::ExprBlock(ref blk) => {
66                 ExprKind::Block {
67                     body: &**blk
68                 }
69             }
70
71             hir::ExprAssign(ref lhs, ref rhs) => {
72                 ExprKind::Assign {
73                     lhs: lhs.to_ref(),
74                     rhs: rhs.to_ref(),
75                 }
76             }
77
78             hir::ExprAssignOp(op, ref lhs, ref rhs) => {
79                 let op = bin_op(op.node);
80                 ExprKind::AssignOp {
81                     op: op,
82                     lhs: lhs.to_ref(),
83                     rhs: rhs.to_ref(),
84                 }
85             }
86
87             hir::ExprLit(ref lit) => {
88                 let literal = convert_literal(cx, self.span, expr_ty, lit);
89                 ExprKind::Literal { literal: literal }
90             }
91
92             hir::ExprBinary(op, ref lhs, ref rhs) => {
93                 if cx.tcx.is_method_call(self.id) {
94                     let pass_args = if hir_util::is_by_value_binop(op.node) {
95                         PassArgs::ByValue
96                     } else {
97                         PassArgs::ByRef
98                     };
99                     overloaded_operator(cx, self, ty::MethodCall::expr(self.id),
100                                         pass_args, lhs.to_ref(), vec![rhs])
101                 } else {
102                     // FIXME overflow
103                     match op.node {
104                         hir::BinOp_::BiAnd => {
105                             ExprKind::LogicalOp { op: LogicalOp::And,
106                                                   lhs: lhs.to_ref(),
107                                                   rhs: rhs.to_ref() }
108                         }
109                         hir::BinOp_::BiOr => {
110                             ExprKind::LogicalOp { op: LogicalOp::Or,
111                                                   lhs: lhs.to_ref(),
112                                                   rhs: rhs.to_ref() }
113                         }
114                         _ => {
115                             let op = bin_op(op.node);
116                             ExprKind::Binary { op: op,
117                                                lhs: lhs.to_ref(),
118                                                rhs: rhs.to_ref() }
119                         }
120                     }
121                 }
122             }
123
124             hir::ExprIndex(ref lhs, ref index) => {
125                 if cx.tcx.is_method_call(self.id) {
126                     overloaded_lvalue(cx, self, ty::MethodCall::expr(self.id),
127                                       PassArgs::ByValue, lhs.to_ref(), vec![index])
128                 } else {
129                     ExprKind::Index { lhs: lhs.to_ref(),
130                                       index: index.to_ref() }
131                 }
132             }
133
134             hir::ExprUnary(hir::UnOp::UnDeref, ref arg) => {
135                 if cx.tcx.is_method_call(self.id) {
136                     overloaded_lvalue(cx, self, ty::MethodCall::expr(self.id),
137                                       PassArgs::ByValue, arg.to_ref(), vec![])
138                 } else {
139                     ExprKind::Deref { arg: arg.to_ref() }
140                 }
141             }
142
143             hir::ExprUnary(hir::UnOp::UnUniq, ref arg) => {
144                 assert!(!cx.tcx.is_method_call(self.id));
145                 ExprKind::Box { place: None, value: arg.to_ref() }
146             }
147
148             hir::ExprUnary(op, ref arg) => {
149                 if cx.tcx.is_method_call(self.id) {
150                     overloaded_operator(cx, self, ty::MethodCall::expr(self.id),
151                                         PassArgs::ByValue, arg.to_ref(), vec![])
152                 } else {
153                     // FIXME overflow
154                     let op = match op {
155                         hir::UnOp::UnNot => UnOp::Not,
156                         hir::UnOp::UnNeg => UnOp::Neg,
157                         hir::UnOp::UnUniq | hir::UnOp::UnDeref => {
158                             cx.tcx.sess.span_bug(
159                                 self.span,
160                                 &format!("operator should have been handled elsewhere {:?}", op));
161                         }
162                     };
163                     ExprKind::Unary { op: op, arg: arg.to_ref() }
164                 }
165             }
166
167             hir::ExprStruct(_, ref fields, ref base) => {
168                 match expr_ty.sty {
169                     ty::TyStruct(adt, substs) => {
170                         ExprKind::Adt {
171                             adt_def: adt,
172                             variant_index: 0,
173                             substs: substs,
174                             fields: fields.to_ref(),
175                             base: base.to_ref(),
176                         }
177                     }
178                     ty::TyEnum(adt, substs) => {
179                         match cx.tcx.def_map.borrow()[&self.id].full_def() {
180                             def::DefVariant(enum_id, variant_id, true) => {
181                                 debug_assert!(adt.did == enum_id);
182                                 let index = adt.variant_index_with_id(variant_id);
183                                 ExprKind::Adt {
184                                     adt_def: adt,
185                                     variant_index: index,
186                                     substs: substs,
187                                     fields: fields.to_ref(),
188                                     base: base.to_ref(),
189                                 }
190                             }
191                             ref def => {
192                                 cx.tcx.sess.span_bug(
193                                     self.span,
194                                     &format!("unexpected def: {:?}", def));
195                             }
196                         }
197                     }
198                     _ => {
199                         cx.tcx.sess.span_bug(
200                             self.span,
201                             &format!("unexpected type for struct literal: {:?}", expr_ty));
202                     }
203                 }
204             }
205
206             hir::ExprClosure(..) => {
207                 let closure_ty = cx.tcx.expr_ty(self);
208                 let (def_id, substs) = match closure_ty.sty {
209                     ty::TyClosure(def_id, ref substs) => (def_id, substs),
210                     _ => {
211                         cx.tcx.sess.span_bug(self.span,
212                                           &format!("closure expr w/o closure type: {:?}",
213                                                    closure_ty));
214                     }
215                 };
216                 let upvars = cx.tcx.with_freevars(self.id, |freevars| {
217                     freevars.iter()
218                             .enumerate()
219                             .map(|(i, fv)| capture_freevar(cx, self, fv, substs.upvar_tys[i]))
220                             .collect()
221                 });
222                 ExprKind::Closure {
223                     closure_id: def_id,
224                     substs: &**substs,
225                     upvars: upvars,
226                 }
227             }
228
229             hir::ExprRange(ref start, ref end) => {
230                 let range_ty = cx.tcx.expr_ty(self);
231                 let (adt_def, substs) = match range_ty.sty {
232                     ty::TyStruct(adt_def, substs) => (adt_def, substs),
233                     _ => {
234                         cx.tcx.sess.span_bug(
235                             self.span,
236                             &format!("unexpanded ast"));
237                     }
238                 };
239
240                 let field_expr_ref = |s: &'tcx P<hir::Expr>, nm: &str| {
241                     FieldExprRef { name: Field::Named(token::intern(nm)),
242                                    expr: s.to_ref() }
243                 };
244
245                 let start_field = start.as_ref()
246                                        .into_iter()
247                                        .map(|s| field_expr_ref(s, "start"));
248
249                 let end_field = end.as_ref()
250                                    .into_iter()
251                                    .map(|e| field_expr_ref(e, "end"));
252
253                 ExprKind::Adt { adt_def: adt_def,
254                                 variant_index: 0,
255                                 substs: substs,
256                                 fields: start_field.chain(end_field).collect(),
257                                 base: None }
258             }
259
260             hir::ExprPath(..) => {
261                 convert_path_expr(cx, self)
262             }
263
264             hir::ExprInlineAsm(ref asm) => {
265                 ExprKind::InlineAsm { asm: asm }
266             }
267
268             // Now comes the rote stuff:
269
270             hir::ExprRepeat(ref v, ref c) =>
271                 ExprKind::Repeat { value: v.to_ref(), count: c.to_ref() },
272             hir::ExprRet(ref v) =>
273                 ExprKind::Return { value: v.to_ref() },
274             hir::ExprBreak(label) =>
275                 ExprKind::Break { label: label.map(|_| loop_label(cx, self)) },
276             hir::ExprAgain(label) =>
277                 ExprKind::Continue { label: label.map(|_| loop_label(cx, self)) },
278             hir::ExprMatch(ref discr, ref arms, _) =>
279                 ExprKind::Match { discriminant: discr.to_ref(),
280                                   arms: arms.iter().map(|a| convert_arm(cx, a)).collect() },
281             hir::ExprIf(ref cond, ref then, ref otherwise) =>
282                 ExprKind::If { condition: cond.to_ref(),
283                                then: block::to_expr_ref(cx, then),
284                                otherwise: otherwise.to_ref() },
285             hir::ExprWhile(ref cond, ref body, _) =>
286                 ExprKind::Loop { condition: Some(cond.to_ref()),
287                                  body: block::to_expr_ref(cx, body) },
288             hir::ExprLoop(ref body, _) =>
289                 ExprKind::Loop { condition: None,
290                                  body: block::to_expr_ref(cx, body) },
291             hir::ExprField(ref source, name) =>
292                 ExprKind::Field { lhs: source.to_ref(),
293                                   name: Field::Named(name.node) },
294             hir::ExprTupField(ref source, index) =>
295                 ExprKind::Field { lhs: source.to_ref(),
296                                   name: Field::Indexed(index.node) },
297             hir::ExprCast(ref source, _) =>
298                 ExprKind::Cast { source: source.to_ref() },
299             hir::ExprBox(ref place, ref value) =>
300                 ExprKind::Box { place: place.to_ref(), value: value.to_ref() },
301             hir::ExprVec(ref fields) =>
302                 ExprKind::Vec { fields: fields.to_ref() },
303             hir::ExprTup(ref fields) =>
304                 ExprKind::Tuple { fields: fields.to_ref() },
305             hir::ExprCall(ref fun, ref args) =>
306                 ExprKind::Call { fun: fun.to_ref(), args: args.to_ref() },
307         };
308
309         let temp_lifetime = cx.tcx.region_maps.temporary_scope(self.id);
310         let expr_extent = cx.tcx.region_maps.node_extent(self.id);
311
312         let mut expr = Expr {
313             temp_lifetime: temp_lifetime,
314             ty: expr_ty,
315             span: self.span,
316             kind: kind,
317         };
318
319         // Now apply adjustments, if any.
320         match cx.tcx.tables.borrow().adjustments.get(&self.id) {
321             None => { }
322             Some(&ty::adjustment::AdjustReifyFnPointer) => {
323                 let adjusted_ty = cx.tcx.expr_ty_adjusted(self);
324                 expr = Expr {
325                     temp_lifetime: temp_lifetime,
326                     ty: adjusted_ty,
327                     span: self.span,
328                     kind: ExprKind::ReifyFnPointer { source: expr.to_ref() },
329                 };
330             }
331             Some(&ty::adjustment::AdjustUnsafeFnPointer) => {
332                 let adjusted_ty = cx.tcx.expr_ty_adjusted(self);
333                 expr = Expr {
334                     temp_lifetime: temp_lifetime,
335                     ty: adjusted_ty,
336                     span: self.span,
337                     kind: ExprKind::UnsafeFnPointer { source: expr.to_ref() },
338                 };
339             }
340             Some(&ty::adjustment::AdjustDerefRef(ref adj)) => {
341                 for i in 0..adj.autoderefs {
342                     let i = i as u32;
343                     let adjusted_ty =
344                         expr.ty.adjust_for_autoderef(
345                             cx.tcx,
346                             self.id,
347                             self.span,
348                             i,
349                             |mc| cx.tcx.tables.borrow().method_map.get(&mc).map(|m| m.ty));
350                     let kind = if cx.tcx.is_overloaded_autoderef(self.id, i) {
351                         overloaded_lvalue(cx, self, ty::MethodCall::autoderef(self.id, i),
352                                           PassArgs::ByValue, expr.to_ref(), vec![])
353                     } else {
354                         ExprKind::Deref { arg: expr.to_ref() }
355                     };
356                     expr = Expr {
357                         temp_lifetime: temp_lifetime,
358                         ty: adjusted_ty,
359                         span: self.span,
360                         kind: kind
361                     };
362                 }
363
364                 if let Some(target) = adj.unsize {
365                     expr = Expr {
366                         temp_lifetime: temp_lifetime,
367                         ty: target,
368                         span: self.span,
369                         kind: ExprKind::Unsize { source: expr.to_ref() }
370                     };
371                 } else if let Some(autoref) = adj.autoref {
372                     let adjusted_ty = expr.ty.adjust_for_autoref(cx.tcx, Some(autoref));
373                     match autoref {
374                         ty::adjustment::AutoPtr(r, m) => {
375                             expr = Expr {
376                                 temp_lifetime: temp_lifetime,
377                                 ty: adjusted_ty,
378                                 span: self.span,
379                                 kind: ExprKind::Borrow { region: *r,
380                                                          borrow_kind: to_borrow_kind(m),
381                                                          arg: expr.to_ref() }
382                             };
383                         }
384                         ty::adjustment::AutoUnsafe(m) => {
385                             // Convert this to a suitable `&foo` and
386                             // then an unsafe coercion. Limit the region to be just this
387                             // expression.
388                             let region = ty::ReScope(expr_extent);
389                             let region = cx.tcx.mk_region(region);
390                             expr = Expr {
391                                 temp_lifetime: temp_lifetime,
392                                 ty: cx.tcx.mk_ref(region, ty::TypeAndMut { ty: expr.ty, mutbl: m }),
393                                 span: self.span,
394                                 kind: ExprKind::Borrow { region: *region,
395                                                          borrow_kind: to_borrow_kind(m),
396                                                          arg: expr.to_ref() }
397                             };
398                             expr = Expr {
399                                 temp_lifetime: temp_lifetime,
400                                 ty: adjusted_ty,
401                                 span: self.span,
402                                 kind: ExprKind::Cast { source: expr.to_ref() }
403                             };
404                         }
405                     }
406                 }
407             }
408         }
409
410         // Next, wrap this up in the expr's scope.
411         expr = Expr {
412             temp_lifetime: temp_lifetime,
413             ty: expr.ty,
414             span: self.span,
415             kind: ExprKind::Scope { extent: expr_extent,
416                                     value: expr.to_ref() }
417         };
418
419         // Finally, create a destruction scope, if any.
420         if let Some(extent) = cx.tcx.region_maps.opt_destruction_extent(self.id) {
421             expr = Expr {
422                 temp_lifetime: temp_lifetime,
423                 ty: expr.ty,
424                 span: self.span,
425                 kind: ExprKind::Scope { extent: extent, value: expr.to_ref() }
426             };
427         }
428
429         // OK, all done!
430         expr
431     }
432 }
433
434 fn method_callee<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
435                              expr: &hir::Expr,
436                              method_call: ty::MethodCall)
437                              -> Expr<Cx<'a,'tcx>> {
438     let tables = cx.tcx.tables.borrow();
439     let callee = &tables.method_map[&method_call];
440     let temp_lifetime = cx.tcx.region_maps.temporary_scope(expr.id);
441     Expr {
442         temp_lifetime: temp_lifetime,
443         ty: callee.ty,
444         span: expr.span,
445         kind: ExprKind::Literal {
446             literal: Literal::Item {
447                 def_id: callee.def_id,
448                 substs: callee.substs,
449             }
450         }
451     }
452 }
453
454 fn to_borrow_kind(m: hir::Mutability) -> BorrowKind {
455     match m {
456         hir::MutMutable => BorrowKind::Mut,
457         hir::MutImmutable => BorrowKind::Shared,
458     }
459 }
460
461 fn convert_literal<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
462                                expr_span: Span,
463                                expr_ty: Ty<'tcx>,
464                                literal: &ast::Lit)
465                                -> Literal<Cx<'a,'tcx>>
466 {
467     use repr::IntegralBits::*;
468     match (&literal.node, &expr_ty.sty) {
469         (&ast::LitStr(ref text, _), _) =>
470             Literal::String { value: text.clone() },
471         (&ast::LitByteStr(ref bytes), _) =>
472             Literal::Bytes { value: bytes.clone() },
473         (&ast::LitByte(c), _) =>
474             Literal::Uint { bits: B8, value: c as u64 },
475         (&ast::LitChar(c), _) =>
476             Literal::Char { c: c },
477         (&ast::LitInt(v, _), &ty::TyUint(ast::TyU8)) =>
478             Literal::Uint { bits: B8, value: v },
479         (&ast::LitInt(v, _), &ty::TyUint(ast::TyU16)) =>
480             Literal::Uint { bits: B16, value: v },
481         (&ast::LitInt(v, _), &ty::TyUint(ast::TyU32)) =>
482             Literal::Uint { bits: B32, value: v },
483         (&ast::LitInt(v, _), &ty::TyUint(ast::TyU64)) =>
484             Literal::Uint { bits: B64, value: v },
485         (&ast::LitInt(v, _), &ty::TyUint(ast::TyUs)) =>
486             Literal::Uint { bits: BSize, value: v },
487         (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI8)) =>
488             Literal::Int { bits: B8, value: -(v as i64) },
489         (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI16)) =>
490             Literal::Int { bits: B16, value: -(v as i64) },
491         (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI32)) =>
492             Literal::Int { bits: B32, value: -(v as i64) },
493         (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyI64)) =>
494             Literal::Int { bits: B64, value: -(v as i64) },
495         (&ast::LitInt(v, ast::SignedIntLit(_, ast::Sign::Minus)), &ty::TyInt(ast::TyIs)) =>
496             Literal::Int { bits: BSize, value: -(v as i64) },
497         (&ast::LitInt(v, _), &ty::TyInt(ast::TyI8)) =>
498             Literal::Int { bits: B8, value: v as i64 },
499         (&ast::LitInt(v, _), &ty::TyInt(ast::TyI16)) =>
500             Literal::Int { bits: B16, value: v as i64 },
501         (&ast::LitInt(v, _), &ty::TyInt(ast::TyI32)) =>
502             Literal::Int { bits: B32, value: v as i64 },
503         (&ast::LitInt(v, _), &ty::TyInt(ast::TyI64)) =>
504             Literal::Int { bits: B64, value: v as i64 },
505         (&ast::LitInt(v, _), &ty::TyInt(ast::TyIs)) =>
506             Literal::Int { bits: BSize, value: v as i64 },
507         (&ast::LitFloat(ref v, _), &ty::TyFloat(ast::TyF32)) |
508         (&ast::LitFloatUnsuffixed(ref v), &ty::TyFloat(ast::TyF32)) =>
509             Literal::Float { bits: FloatBits::F32, value: v.parse::<f64>().unwrap() },
510         (&ast::LitFloat(ref v, _), &ty::TyFloat(ast::TyF64)) |
511         (&ast::LitFloatUnsuffixed(ref v), &ty::TyFloat(ast::TyF64)) =>
512             Literal::Float { bits: FloatBits::F64, value: v.parse::<f64>().unwrap() },
513         (&ast::LitBool(v), _) =>
514             Literal::Bool { value: v },
515         (ref l, ref t) =>
516             cx.tcx.sess.span_bug(
517                 expr_span,
518                 &format!("Invalid literal/type combination: {:?},{:?}", l, t))
519     }
520 }
521
522 fn convert_arm<'a,'tcx:'a>(cx: &Cx<'a,'tcx>, arm: &'tcx hir::Arm) -> Arm<Cx<'a,'tcx>> {
523     let map = if arm.pats.len() == 1 {
524         None
525     } else {
526         let mut map = FnvHashMap();
527         pat_util::pat_bindings(&cx.tcx.def_map, &arm.pats[0], |_, p_id, _, path| {
528             map.insert(path.node, p_id);
529         });
530         Some(Rc::new(map))
531     };
532
533     Arm { patterns: arm.pats.iter().map(|p| PatNode::new(p, map.clone()).to_ref()).collect(),
534           guard: arm.guard.to_ref(),
535           body: arm.body.to_ref() }
536 }
537
538 fn convert_path_expr<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
539                                  expr: &'tcx hir::Expr)
540                                  -> ExprKind<Cx<'a,'tcx>>
541 {
542     let substs = cx.tcx.mk_substs(cx.tcx.node_id_item_substs(expr.id).substs);
543     match cx.tcx.def_map.borrow()[&expr.id].full_def() {
544         def::DefVariant(_, def_id, false) |
545         def::DefStruct(def_id) |
546         def::DefFn(def_id, _) |
547         def::DefConst(def_id) |
548         def::DefMethod(def_id) |
549         def::DefAssociatedConst(def_id) =>
550             ExprKind::Literal {
551                 literal: Literal::Item { def_id: def_id, substs: substs }
552             },
553
554         def::DefStatic(node_id, _) =>
555             ExprKind::StaticRef {
556                 id: node_id,
557             },
558
559         def @ def::DefLocal(..) |
560         def @ def::DefUpvar(..) =>
561             convert_var(cx, expr, def),
562
563         def =>
564             cx.tcx.sess.span_bug(
565                 expr.span,
566                 &format!("def `{:?}` not yet implemented", def)),
567     }
568 }
569
570 fn convert_var<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
571                            expr: &'tcx hir::Expr,
572                            def: def::Def)
573                            -> ExprKind<Cx<'a,'tcx>>
574 {
575     let temp_lifetime = cx.tcx.region_maps.temporary_scope(expr.id);
576
577     match def {
578         def::DefLocal(node_id) => {
579             ExprKind::VarRef {
580                 id: node_id,
581             }
582         }
583
584         def::DefUpvar(id_var, index, closure_expr_id) => {
585             debug!("convert_var(upvar({:?}, {:?}, {:?}))", id_var, index, closure_expr_id);
586             let var_ty = cx.tcx.node_id_to_type(id_var);
587
588             let body_id = match cx.tcx.map.find(closure_expr_id) {
589                 Some(map::NodeExpr(expr)) => {
590                     match expr.node {
591                         hir::ExprClosure(_, _, ref body) => body.id,
592                         _ => {
593                             cx.tcx.sess.span_bug(expr.span,
594                                               &format!("closure expr is not a closure expr"));
595                         }
596                     }
597                 }
598                 _ => {
599                     cx.tcx.sess.span_bug(expr.span,
600                                       &format!("ast-map has garbage for closure expr"));
601                 }
602             };
603
604             // FIXME free regions in closures are not right
605             let closure_ty =
606                 cx.tcx.node_id_to_type(closure_expr_id);
607
608             // FIXME we're just hard-coding the idea that the
609             // signature will be &self or &mut self and hence will
610             // have a bound region with number 0
611             let region =
612                 ty::Region::ReFree(
613                     ty::FreeRegion {
614                         scope: cx.tcx.region_maps.node_extent(body_id),
615                         bound_region: ty::BoundRegion::BrAnon(0)
616                     });
617             let region =
618                 cx.tcx.mk_region(region);
619
620             let self_expr = match cx.tcx.closure_kind(DefId::local(closure_expr_id)) {
621                 ty::ClosureKind::FnClosureKind => {
622                     let ref_closure_ty =
623                         cx.tcx.mk_ref(region,
624                                    ty::TypeAndMut { ty: closure_ty,
625                                                     mutbl: hir::MutImmutable });
626                     Expr {
627                         ty: closure_ty,
628                         temp_lifetime: temp_lifetime,
629                         span: expr.span,
630                         kind: ExprKind::Deref {
631                             arg: Expr {
632                                 ty: ref_closure_ty,
633                                 temp_lifetime: temp_lifetime,
634                                 span: expr.span,
635                                 kind: ExprKind::SelfRef
636                             }.to_ref()
637                         }
638                     }
639                 }
640                 ty::ClosureKind::FnMutClosureKind => {
641                     let ref_closure_ty =
642                         cx.tcx.mk_ref(region,
643                                    ty::TypeAndMut { ty: closure_ty,
644                                                     mutbl: hir::MutMutable });
645                     Expr {
646                         ty: closure_ty,
647                         temp_lifetime: temp_lifetime,
648                         span: expr.span,
649                         kind: ExprKind::Deref {
650                             arg: Expr {
651                                 ty: ref_closure_ty,
652                                 temp_lifetime: temp_lifetime,
653                                 span: expr.span,
654                                 kind: ExprKind::SelfRef
655                             }.to_ref()
656                         }
657                     }
658                 }
659                 ty::ClosureKind::FnOnceClosureKind => {
660                     Expr {
661                         ty: closure_ty,
662                         temp_lifetime: temp_lifetime,
663                         span: expr.span,
664                         kind: ExprKind::SelfRef
665                     }
666                 }
667             };
668
669             // at this point we have `self.n`, which loads up the upvar
670             let field_kind =
671                 ExprKind::Field { lhs: self_expr.to_ref(),
672                                   name: Field::Indexed(index) };
673
674             // ...but the upvar might be an `&T` or `&mut T` capture, at which
675             // point we need an implicit deref
676             let upvar_id = ty::UpvarId { var_id: id_var, closure_expr_id: closure_expr_id };
677             let upvar_capture = match cx.tcx.upvar_capture(upvar_id) {
678                 Some(c) => c,
679                 None => {
680                     cx.tcx.sess.span_bug(
681                         expr.span,
682                         &format!("no upvar_capture for {:?}", upvar_id));
683                 }
684             };
685             match upvar_capture {
686                 ty::UpvarCapture::ByValue => field_kind,
687                 ty::UpvarCapture::ByRef(_) => {
688                     ExprKind::Deref {
689                         arg: Expr {
690                             temp_lifetime: temp_lifetime,
691                             ty: var_ty,
692                             span: expr.span,
693                             kind: field_kind,
694                         }.to_ref()
695                     }
696                 }
697             }
698         }
699
700         _ => cx.tcx.sess.span_bug(expr.span, "type of & not region")
701     }
702 }
703
704
705 fn bin_op(op: hir::BinOp_) -> BinOp {
706     match op {
707         hir::BinOp_::BiAdd => BinOp::Add,
708         hir::BinOp_::BiSub => BinOp::Sub,
709         hir::BinOp_::BiMul => BinOp::Mul,
710         hir::BinOp_::BiDiv => BinOp::Div,
711         hir::BinOp_::BiRem => BinOp::Rem,
712         hir::BinOp_::BiBitXor => BinOp::BitXor,
713         hir::BinOp_::BiBitAnd => BinOp::BitAnd,
714         hir::BinOp_::BiBitOr => BinOp::BitOr,
715         hir::BinOp_::BiShl => BinOp::Shl,
716         hir::BinOp_::BiShr => BinOp::Shr,
717         hir::BinOp_::BiEq => BinOp::Eq,
718         hir::BinOp_::BiLt => BinOp::Lt,
719         hir::BinOp_::BiLe => BinOp::Le,
720         hir::BinOp_::BiNe => BinOp::Ne,
721         hir::BinOp_::BiGe => BinOp::Ge,
722         hir::BinOp_::BiGt => BinOp::Gt,
723         _ => panic!("no equivalent for ast binop {:?}", op)
724     }
725 }
726
727 enum PassArgs {
728     ByValue,
729     ByRef
730 }
731
732 fn overloaded_operator<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
733                                    expr: &'tcx hir::Expr,
734                                    method_call: ty::MethodCall,
735                                    pass_args: PassArgs,
736                                    receiver: ExprRef<Cx<'a,'tcx>>,
737                                    args: Vec<&'tcx P<hir::Expr>>)
738                                    -> ExprKind<Cx<'a,'tcx>>
739 {
740     // the receiver has all the adjustments that are needed, so we can
741     // just push a reference to it
742     let mut argrefs = vec![receiver];
743
744     // the arguments, unfortunately, do not, so if this is a ByRef
745     // operator, we have to gin up the autorefs (but by value is easy)
746     match pass_args {
747         PassArgs::ByValue => {
748             argrefs.extend(
749                 args.iter()
750                     .map(|arg| arg.to_ref()))
751         }
752
753         PassArgs::ByRef => {
754             let scope = cx.tcx.region_maps.node_extent(expr.id);
755             let region = cx.tcx.mk_region(ty::ReScope(scope));
756             let temp_lifetime = cx.tcx.region_maps.temporary_scope(expr.id);
757             argrefs.extend(
758                 args.iter()
759                     .map(|arg| {
760                         let arg_ty = cx.tcx.expr_ty_adjusted(arg);
761                         let adjusted_ty =
762                             cx.tcx.mk_ref(region,
763                                        ty::TypeAndMut { ty: arg_ty,
764                                                         mutbl: hir::MutImmutable });
765                         Expr {
766                             temp_lifetime: temp_lifetime,
767                             ty: adjusted_ty,
768                             span: expr.span,
769                             kind: ExprKind::Borrow { region: *region,
770                                                      borrow_kind: BorrowKind::Shared,
771                                                      arg: arg.to_ref() }
772                         }.to_ref()
773                     }))
774         }
775     }
776
777     // now create the call itself
778     let fun = method_callee(cx, expr, method_call);
779     ExprKind::Call {
780         fun: fun.to_ref(),
781         args: argrefs,
782     }
783 }
784
785 fn overloaded_lvalue<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
786                                  expr: &'tcx hir::Expr,
787                                  method_call: ty::MethodCall,
788                                  pass_args: PassArgs,
789                                  receiver: ExprRef<Cx<'a,'tcx>>,
790                                  args: Vec<&'tcx P<hir::Expr>>)
791                                  -> ExprKind<Cx<'a,'tcx>>
792 {
793     // For an overloaded *x or x[y] expression of type T, the method
794     // call returns an &T and we must add the deref so that the types
795     // line up (this is because `*x` and `x[y]` represent lvalues):
796
797     // to find the type &T of the content returned by the method;
798     let tables = cx.tcx.tables.borrow();
799     let callee = &tables.method_map[&method_call];
800     let ref_ty = callee.ty.fn_ret();
801     let ref_ty = cx.tcx.no_late_bound_regions(&ref_ty).unwrap().unwrap();
802     //                                              1~~~~~   2~~~~~
803     // (1) callees always have all late-bound regions fully instantiated,
804     // (2) overloaded methods don't return `!`
805
806     // construct the complete expression `foo()` for the overloaded call,
807     // which will yield the &T type
808     let temp_lifetime = cx.tcx.region_maps.temporary_scope(expr.id);
809     let ref_kind = overloaded_operator(cx, expr, method_call, pass_args, receiver, args);
810     let ref_expr = Expr {
811         temp_lifetime: temp_lifetime,
812         ty: ref_ty,
813         span: expr.span,
814         kind: ref_kind,
815     };
816
817     // construct and return a deref wrapper `*foo()`
818     ExprKind::Deref { arg: ref_expr.to_ref() }
819 }
820
821 fn capture_freevar<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
822                                closure_expr: &'tcx hir::Expr,
823                                freevar: &ty::Freevar,
824                                freevar_ty: Ty<'tcx>)
825                                -> ExprRef<Cx<'a,'tcx>> {
826     let id_var = freevar.def.def_id().node;
827     let upvar_id = ty::UpvarId { var_id: id_var, closure_expr_id: closure_expr.id };
828     let upvar_capture = cx.tcx.upvar_capture(upvar_id).unwrap();
829     let temp_lifetime = cx.tcx.region_maps.temporary_scope(closure_expr.id);
830     let var_ty = cx.tcx.node_id_to_type(id_var);
831     let captured_var = Expr { temp_lifetime: temp_lifetime,
832                               ty: var_ty,
833                               span: closure_expr.span,
834                               kind: convert_var(cx, closure_expr, freevar.def) };
835     match upvar_capture {
836         ty::UpvarCapture::ByValue => {
837             captured_var.to_ref()
838         }
839         ty::UpvarCapture::ByRef(upvar_borrow) => {
840             let borrow_kind = match upvar_borrow.kind {
841                 ty::BorrowKind::ImmBorrow => BorrowKind::Shared,
842                 ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique,
843                 ty::BorrowKind::MutBorrow => BorrowKind::Mut,
844             };
845             Expr {
846                 temp_lifetime: temp_lifetime,
847                 ty: freevar_ty,
848                 span: closure_expr.span,
849                 kind: ExprKind::Borrow { region: upvar_borrow.region,
850                                          borrow_kind: borrow_kind,
851                                          arg: captured_var.to_ref() }
852             }.to_ref()
853         }
854     }
855 }
856
857 fn loop_label<'a,'tcx:'a>(cx: &mut Cx<'a,'tcx>,
858                           expr: &'tcx hir::Expr)
859                           -> CodeExtent
860 {
861     match cx.tcx.def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
862         Some(def::DefLabel(loop_id)) => cx.tcx.region_maps.node_extent(loop_id),
863         d => {
864             cx.tcx.sess.span_bug(
865                 expr.span,
866                 &format!("loop scope resolved to {:?}", d));
867         }
868     }
869 }