]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/controlflow.rs
librustc: Stop desugaring `for` expressions and translate them directly.
[rust.git] / src / librustc / middle / trans / controlflow.rs
1 // Copyright 2012 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 llvm::*;
12 use driver::config::FullDebugInfo;
13 use middle::def;
14 use middle::lang_items::{FailFnLangItem, FailBoundsCheckFnLangItem};
15 use middle::trans::_match;
16 use middle::trans::adt;
17 use middle::trans::base::*;
18 use middle::trans::build::*;
19 use middle::trans::callee;
20 use middle::trans::cleanup::CleanupMethods;
21 use middle::trans::cleanup;
22 use middle::trans::common::*;
23 use middle::trans::datum;
24 use middle::trans::debuginfo;
25 use middle::trans::expr;
26 use middle::trans::meth;
27 use middle::trans::type_::Type;
28 use middle::ty;
29 use middle::typeck::MethodCall;
30 use util::ppaux::Repr;
31 use util::ppaux;
32
33 use syntax::ast;
34 use syntax::ast::Ident;
35 use syntax::ast_util;
36 use syntax::codemap::Span;
37 use syntax::parse::token::InternedString;
38 use syntax::parse::token;
39 use syntax::visit::Visitor;
40
41 use std::gc::Gc;
42
43 pub fn trans_stmt<'a>(cx: &'a Block<'a>,
44                       s: &ast::Stmt)
45                       -> &'a Block<'a> {
46     let _icx = push_ctxt("trans_stmt");
47     let fcx = cx.fcx;
48     debug!("trans_stmt({})", s.repr(cx.tcx()));
49
50     if cx.sess().asm_comments() {
51         add_span_comment(cx, s.span, s.repr(cx.tcx()).as_slice());
52     }
53
54     let mut bcx = cx;
55
56     let id = ast_util::stmt_id(s);
57     fcx.push_ast_cleanup_scope(id);
58
59     match s.node {
60         ast::StmtExpr(ref e, _) | ast::StmtSemi(ref e, _) => {
61             bcx = trans_stmt_semi(bcx, &**e);
62         }
63         ast::StmtDecl(d, _) => {
64             match d.node {
65                 ast::DeclLocal(ref local) => {
66                     bcx = init_local(bcx, &**local);
67                     if cx.sess().opts.debuginfo == FullDebugInfo {
68                         debuginfo::create_local_var_metadata(bcx, &**local);
69                     }
70                 }
71                 ast::DeclItem(ref i) => trans_item(cx.fcx.ccx, &**i)
72             }
73         }
74         ast::StmtMac(..) => cx.tcx().sess.bug("unexpanded macro")
75     }
76
77     bcx = fcx.pop_and_trans_ast_cleanup_scope(
78         bcx, ast_util::stmt_id(s));
79
80     return bcx;
81 }
82
83 pub fn trans_stmt_semi<'a>(cx: &'a Block<'a>, e: &ast::Expr) -> &'a Block<'a> {
84     let _icx = push_ctxt("trans_stmt_semi");
85     let ty = expr_ty(cx, e);
86     if ty::type_needs_drop(cx.tcx(), ty) {
87         expr::trans_to_lvalue(cx, e, "stmt").bcx
88     } else {
89         expr::trans_into(cx, e, expr::Ignore)
90     }
91 }
92
93 pub fn trans_block<'a>(bcx: &'a Block<'a>,
94                        b: &ast::Block,
95                        mut dest: expr::Dest)
96                        -> &'a Block<'a> {
97     let _icx = push_ctxt("trans_block");
98     let fcx = bcx.fcx;
99     let mut bcx = bcx;
100
101     fcx.push_ast_cleanup_scope(b.id);
102
103     for s in b.stmts.iter() {
104         bcx = trans_stmt(bcx, &**s);
105     }
106
107     if dest != expr::Ignore {
108         let block_ty = node_id_type(bcx, b.id);
109         if b.expr.is_none() || type_is_zero_size(bcx.ccx(), block_ty) {
110             dest = expr::Ignore;
111         }
112     }
113
114     match b.expr {
115         Some(ref e) => {
116             bcx = expr::trans_into(bcx, &**e, dest);
117         }
118         None => {
119             assert!(dest == expr::Ignore || bcx.unreachable.get());
120         }
121     }
122
123     bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, b.id);
124
125     return bcx;
126 }
127
128 pub fn trans_if<'a>(bcx: &'a Block<'a>,
129                     if_id: ast::NodeId,
130                     cond: &ast::Expr,
131                     thn: ast::P<ast::Block>,
132                     els: Option<Gc<ast::Expr>>,
133                     dest: expr::Dest)
134                     -> &'a Block<'a> {
135     debug!("trans_if(bcx={}, if_id={}, cond={}, thn={:?}, dest={})",
136            bcx.to_str(), if_id, bcx.expr_to_string(cond), thn.id,
137            dest.to_string(bcx.ccx()));
138     let _icx = push_ctxt("trans_if");
139     let mut bcx = bcx;
140
141     let cond_val = unpack_result!(bcx, expr::trans(bcx, cond).to_llbool());
142
143     // Drop branches that are known to be impossible
144     if is_const(cond_val) && !is_undef(cond_val) {
145         if const_to_uint(cond_val) == 1 {
146             match els {
147                 Some(elexpr) => {
148                     let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx };
149                     trans.visit_expr(&*elexpr, ());
150                 }
151                 None => {}
152             }
153             // if true { .. } [else { .. }]
154             bcx = trans_block(bcx, &*thn, dest);
155             debuginfo::clear_source_location(bcx.fcx);
156         } else {
157             let mut trans = TransItemVisitor { ccx: bcx.fcx.ccx } ;
158             trans.visit_block(&*thn, ());
159
160             match els {
161                 // if false { .. } else { .. }
162                 Some(elexpr) => {
163                     bcx = expr::trans_into(bcx, &*elexpr, dest);
164                     debuginfo::clear_source_location(bcx.fcx);
165                 }
166
167                 // if false { .. }
168                 None => { }
169             }
170         }
171
172         return bcx;
173     }
174
175     let name = format!("then-block-{}-", thn.id);
176     let then_bcx_in = bcx.fcx.new_id_block(name.as_slice(), thn.id);
177     let then_bcx_out = trans_block(then_bcx_in, &*thn, dest);
178     debuginfo::clear_source_location(bcx.fcx);
179
180     let next_bcx;
181     match els {
182         Some(elexpr) => {
183             let else_bcx_in = bcx.fcx.new_id_block("else-block", elexpr.id);
184             let else_bcx_out = expr::trans_into(else_bcx_in, &*elexpr, dest);
185             next_bcx = bcx.fcx.join_blocks(if_id,
186                                            [then_bcx_out, else_bcx_out]);
187             CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb);
188         }
189
190         None => {
191             next_bcx = bcx.fcx.new_id_block("next-block", if_id);
192             Br(then_bcx_out, next_bcx.llbb);
193             CondBr(bcx, cond_val, then_bcx_in.llbb, next_bcx.llbb);
194         }
195     }
196
197     // Clear the source location because it is still set to whatever has been translated
198     // right before.
199     debuginfo::clear_source_location(next_bcx.fcx);
200
201     next_bcx
202 }
203
204 pub fn trans_while<'a>(bcx: &'a Block<'a>,
205                        loop_id: ast::NodeId,
206                        cond: &ast::Expr,
207                        body: &ast::Block)
208                        -> &'a Block<'a> {
209     let _icx = push_ctxt("trans_while");
210     let fcx = bcx.fcx;
211
212     //            bcx
213     //             |
214     //         cond_bcx_in  <--------+
215     //             |                 |
216     //         cond_bcx_out          |
217     //           |      |            |
218     //           |    body_bcx_in    |
219     // cleanup_blk      |            |
220     //    |           body_bcx_out --+
221     // next_bcx_in
222
223     let next_bcx_in = fcx.new_id_block("while_exit", loop_id);
224     let cond_bcx_in = fcx.new_id_block("while_cond", cond.id);
225     let body_bcx_in = fcx.new_id_block("while_body", body.id);
226
227     fcx.push_loop_cleanup_scope(loop_id, [next_bcx_in, cond_bcx_in]);
228
229     Br(bcx, cond_bcx_in.llbb);
230
231     // compile the block where we will handle loop cleanups
232     let cleanup_llbb = fcx.normal_exit_block(loop_id, cleanup::EXIT_BREAK);
233
234     // compile the condition
235     let Result {bcx: cond_bcx_out, val: cond_val} =
236         expr::trans(cond_bcx_in, cond).to_llbool();
237     CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, cleanup_llbb);
238
239     // loop body:
240     let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
241     Br(body_bcx_out, cond_bcx_in.llbb);
242
243     fcx.pop_loop_cleanup_scope(loop_id);
244     return next_bcx_in;
245 }
246
247 /// Translates a `for` loop.
248 pub fn trans_for<'a>(
249                  mut bcx: &'a Block<'a>,
250                  loop_info: NodeInfo,
251                  pat: Gc<ast::Pat>,
252                  head: &ast::Expr,
253                  body: &ast::Block)
254                  -> &'a Block<'a> {
255     let _icx = push_ctxt("trans_for");
256
257     //            bcx
258     //             |
259     //      loopback_bcx_in  <-------+
260     //             |                 |
261     //      loopback_bcx_out         |
262     //           |      |            |
263     //           |    body_bcx_in    |
264     // cleanup_blk      |            |
265     //    |           body_bcx_out --+
266     // next_bcx_in
267
268     // Codegen the head to create the iterator value.
269     let iterator_datum =
270         unpack_datum!(bcx, expr::trans_to_lvalue(bcx, head, "for_head"));
271     let iterator_type = node_id_type(bcx, head.id);
272     debug!("iterator type is {}, datum type is {}",
273            ppaux::ty_to_string(bcx.tcx(), iterator_type),
274            ppaux::ty_to_string(bcx.tcx(), iterator_datum.ty));
275     let lliterator = load_ty(bcx, iterator_datum.val, iterator_datum.ty);
276
277     // Create our basic blocks and set up our loop cleanups.
278     let next_bcx_in = bcx.fcx.new_id_block("for_exit", loop_info.id);
279     let loopback_bcx_in = bcx.fcx.new_id_block("for_loopback", head.id);
280     let body_bcx_in = bcx.fcx.new_id_block("for_body", body.id);
281     bcx.fcx.push_loop_cleanup_scope(loop_info.id,
282                                     [next_bcx_in, loopback_bcx_in]);
283     Br(bcx, loopback_bcx_in.llbb);
284     let cleanup_llbb = bcx.fcx.normal_exit_block(loop_info.id,
285                                                  cleanup::EXIT_BREAK);
286
287     // Set up the method call (to `.next()`).
288     let method_call = MethodCall::expr(loop_info.id);
289     let method_type = loopback_bcx_in.tcx()
290                                      .method_map
291                                      .borrow()
292                                      .get(&method_call)
293                                      .ty;
294     let method_type = monomorphize_type(loopback_bcx_in, method_type);
295     let method_result_type = ty::ty_fn_ret(method_type);
296     let option_cleanup_scope = body_bcx_in.fcx.push_custom_cleanup_scope();
297     let option_cleanup_scope_id = cleanup::CustomScope(option_cleanup_scope);
298
299     // Compile the method call (to `.next()`).
300     let mut loopback_bcx_out = loopback_bcx_in;
301     let option_datum =
302         unpack_datum!(loopback_bcx_out,
303                       datum::lvalue_scratch_datum(loopback_bcx_out,
304                                                   method_result_type,
305                                                   "loop_option",
306                                                   false,
307                                                   option_cleanup_scope_id,
308                                                   (),
309                                                   |(), bcx, lloption| {
310         let Result {
311             bcx: bcx,
312             val: _
313         } = callee::trans_call_inner(bcx,
314                                      Some(loop_info),
315                                      method_type,
316                                      |bcx, arg_cleanup_scope| {
317                                          meth::trans_method_callee(
318                                              bcx,
319                                              method_call,
320                                              None,
321                                              arg_cleanup_scope)
322                                      },
323                                      callee::ArgVals([lliterator]),
324                                      Some(expr::SaveIn(lloption)));
325         bcx
326     }));
327
328     // Check the discriminant; if the `None` case, exit the loop.
329     let option_representation = adt::represent_type(loopback_bcx_out.ccx(),
330                                                     method_result_type);
331     let i8_type = Type::i8(loopback_bcx_out.ccx());
332     let lldiscriminant = adt::trans_get_discr(loopback_bcx_out,
333                                               &*option_representation,
334                                               option_datum.val,
335                                               Some(i8_type));
336     let llzero = C_u8(loopback_bcx_out.ccx(), 0);
337     let llcondition = ICmp(loopback_bcx_out, IntNE, lldiscriminant, llzero);
338     CondBr(loopback_bcx_out, llcondition, body_bcx_in.llbb, cleanup_llbb);
339
340     // Now we're in the body. Unpack the `Option` value into the programmer-
341     // supplied pattern.
342     let llpayload = adt::trans_field_ptr(body_bcx_in,
343                                          &*option_representation,
344                                          option_datum.val,
345                                          1,
346                                          0);
347     let binding_cleanup_scope = body_bcx_in.fcx.push_custom_cleanup_scope();
348     let binding_cleanup_scope_id =
349         cleanup::CustomScope(binding_cleanup_scope);
350     let mut body_bcx_out =
351         _match::store_for_loop_binding(body_bcx_in,
352                                        pat,
353                                        llpayload,
354                                        binding_cleanup_scope_id);
355
356     // Codegen the body.
357     body_bcx_out = trans_block(body_bcx_out, body, expr::Ignore);
358     body_bcx_out.fcx.pop_custom_cleanup_scope(binding_cleanup_scope);
359     body_bcx_out =
360         body_bcx_out.fcx
361                     .pop_and_trans_custom_cleanup_scope(body_bcx_out,
362                                                         option_cleanup_scope);
363     Br(body_bcx_out, loopback_bcx_in.llbb);
364
365     // Codegen cleanups and leave.
366     next_bcx_in.fcx.pop_loop_cleanup_scope(loop_info.id);
367     next_bcx_in
368 }
369
370 pub fn trans_loop<'a>(bcx:&'a Block<'a>,
371                       loop_id: ast::NodeId,
372                       body: &ast::Block)
373                       -> &'a Block<'a> {
374     let _icx = push_ctxt("trans_loop");
375     let fcx = bcx.fcx;
376
377     //            bcx
378     //             |
379     //         body_bcx_in
380     //             |
381     //         body_bcx_out
382     //
383     // next_bcx
384     //
385     // Links between body_bcx_in and next_bcx are created by
386     // break statements.
387
388     let next_bcx_in = bcx.fcx.new_id_block("loop_exit", loop_id);
389     let body_bcx_in = bcx.fcx.new_id_block("loop_body", body.id);
390
391     fcx.push_loop_cleanup_scope(loop_id, [next_bcx_in, body_bcx_in]);
392
393     Br(bcx, body_bcx_in.llbb);
394     let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
395     Br(body_bcx_out, body_bcx_in.llbb);
396
397     fcx.pop_loop_cleanup_scope(loop_id);
398
399     if ty::type_is_bot(node_id_type(bcx, loop_id)) {
400         Unreachable(next_bcx_in);
401     }
402
403     return next_bcx_in;
404 }
405
406 pub fn trans_break_cont<'a>(bcx: &'a Block<'a>,
407                             expr_id: ast::NodeId,
408                             opt_label: Option<Ident>,
409                             exit: uint)
410                             -> &'a Block<'a> {
411     let _icx = push_ctxt("trans_break_cont");
412     let fcx = bcx.fcx;
413
414     if bcx.unreachable.get() {
415         return bcx;
416     }
417
418     // Locate loop that we will break to
419     let loop_id = match opt_label {
420         None => fcx.top_loop_scope(),
421         Some(_) => {
422             match bcx.tcx().def_map.borrow().find(&expr_id) {
423                 Some(&def::DefLabel(loop_id)) => loop_id,
424                 ref r => {
425                     bcx.tcx().sess.bug(format!("{:?} in def-map for label",
426                                                r).as_slice())
427                 }
428             }
429         }
430     };
431
432     // Generate appropriate cleanup code and branch
433     let cleanup_llbb = fcx.normal_exit_block(loop_id, exit);
434     Br(bcx, cleanup_llbb);
435     Unreachable(bcx); // anything afterwards should be ignored
436     return bcx;
437 }
438
439 pub fn trans_break<'a>(bcx: &'a Block<'a>,
440                        expr_id: ast::NodeId,
441                        label_opt: Option<Ident>)
442                        -> &'a Block<'a> {
443     return trans_break_cont(bcx, expr_id, label_opt, cleanup::EXIT_BREAK);
444 }
445
446 pub fn trans_cont<'a>(bcx: &'a Block<'a>,
447                       expr_id: ast::NodeId,
448                       label_opt: Option<Ident>)
449                       -> &'a Block<'a> {
450     return trans_break_cont(bcx, expr_id, label_opt, cleanup::EXIT_LOOP);
451 }
452
453 pub fn trans_ret<'a>(bcx: &'a Block<'a>,
454                      e: Option<Gc<ast::Expr>>)
455                      -> &'a Block<'a> {
456     let _icx = push_ctxt("trans_ret");
457     let fcx = bcx.fcx;
458     let mut bcx = bcx;
459     let dest = match bcx.fcx.llretptr.get() {
460         None => expr::Ignore,
461         Some(retptr) => expr::SaveIn(retptr),
462     };
463     match e {
464         Some(x) => {
465             bcx = expr::trans_into(bcx, &*x, dest);
466         }
467         _ => {}
468     }
469     let cleanup_llbb = fcx.return_exit_block();
470     Br(bcx, cleanup_llbb);
471     Unreachable(bcx);
472     return bcx;
473 }
474
475 fn str_slice_arg<'a>(bcx: &'a Block<'a>, s: InternedString) -> ValueRef {
476     let ccx = bcx.ccx();
477     let s = C_str_slice(ccx, s);
478     let slot = alloca(bcx, val_ty(s), "__temp");
479     Store(bcx, s, slot);
480     slot
481 }
482
483 pub fn trans_fail<'a>(
484                   bcx: &'a Block<'a>,
485                   sp: Span,
486                   fail_str: InternedString)
487                   -> &'a Block<'a> {
488     let ccx = bcx.ccx();
489     let _icx = push_ctxt("trans_fail_value");
490
491     let v_str = str_slice_arg(bcx, fail_str);
492     let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
493     let filename = token::intern_and_get_ident(loc.file.name.as_slice());
494     let v_filename = str_slice_arg(bcx, filename);
495     let v_line = loc.line as int;
496     let args = vec!(v_str, v_filename, C_int(ccx, v_line));
497     let did = langcall(bcx, Some(sp), "", FailFnLangItem);
498     let bcx = callee::trans_lang_call(bcx,
499                                       did,
500                                       args.as_slice(),
501                                       Some(expr::Ignore)).bcx;
502     Unreachable(bcx);
503     return bcx;
504 }
505
506 pub fn trans_fail_bounds_check<'a>(
507                                bcx: &'a Block<'a>,
508                                sp: Span,
509                                index: ValueRef,
510                                len: ValueRef)
511                                -> &'a Block<'a> {
512     let _icx = push_ctxt("trans_fail_bounds_check");
513
514     // Extract the file/line from the span
515     let loc = bcx.sess().codemap().lookup_char_pos(sp.lo);
516     let filename = token::intern_and_get_ident(loc.file.name.as_slice());
517
518     // Invoke the lang item
519     let filename = str_slice_arg(bcx, filename);
520     let line = C_int(bcx.ccx(), loc.line as int);
521     let args = vec!(filename, line, index, len);
522     let did = langcall(bcx, Some(sp), "", FailBoundsCheckFnLangItem);
523     let bcx = callee::trans_lang_call(bcx,
524                                       did,
525                                       args.as_slice(),
526                                       Some(expr::Ignore)).bcx;
527     Unreachable(bcx);
528     return bcx;
529 }