]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/mod.rs
adjust privacy of various types in `build`
[rust.git] / src / librustc_mir / build / mod.rs
1 // Copyright 2012-2014 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::cx::Cx;
12 use hair::Pattern;
13
14 use rustc::middle::region::{CodeExtent, CodeExtentData};
15 use rustc::ty::{self, Ty};
16 use rustc::mir::*;
17 use rustc::util::nodemap::NodeMap;
18 use rustc::hir;
19 use syntax::abi::Abi;
20 use syntax::ast;
21 use syntax::symbol::keywords;
22 use syntax_pos::Span;
23
24 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
25
26 use std::u32;
27
28 struct Builder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
29     hir: Cx<'a, 'gcx, 'tcx>,
30     cfg: CFG<'tcx>,
31
32     fn_span: Span,
33     arg_count: usize,
34
35     /// the current set of scopes, updated as we traverse;
36     /// see the `scope` module for more details
37     scopes: Vec<scope::Scope<'tcx>>,
38
39     /// the current set of breakables; see the `scope` module for more
40     /// details
41     breakable_scopes: Vec<scope::BreakableScope<'tcx>>,
42
43     /// the vector of all scopes that we have created thus far;
44     /// we track this for debuginfo later
45     visibility_scopes: IndexVec<VisibilityScope, VisibilityScopeData>,
46     visibility_scope: VisibilityScope,
47
48     /// Maps node ids of variable bindings to the `Local`s created for them.
49     var_indices: NodeMap<Local>,
50     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
51     unit_temp: Option<Lvalue<'tcx>>,
52
53     /// cached block with the RESUME terminator; this is created
54     /// when first set of cleanups are built.
55     cached_resume_block: Option<BasicBlock>,
56     /// cached block with the RETURN terminator
57     cached_return_block: Option<BasicBlock>,
58 }
59
60 struct CFG<'tcx> {
61     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
62 }
63
64 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
65 pub struct ScopeId(u32);
66
67 impl Idx for ScopeId {
68     fn new(index: usize) -> ScopeId {
69         assert!(index < (u32::MAX as usize));
70         ScopeId(index as u32)
71     }
72
73     fn index(self) -> usize {
74         self.0 as usize
75     }
76 }
77
78 ///////////////////////////////////////////////////////////////////////////
79 /// The `BlockAnd` "monad" packages up the new basic block along with a
80 /// produced value (sometimes just unit, of course). The `unpack!`
81 /// macro (and methods below) makes working with `BlockAnd` much more
82 /// convenient.
83
84 #[must_use] // if you don't use one of these results, you're leaving a dangling edge
85 struct BlockAnd<T>(BasicBlock, T);
86
87 trait BlockAndExtension {
88     fn and<T>(self, v: T) -> BlockAnd<T>;
89     fn unit(self) -> BlockAnd<()>;
90 }
91
92 impl BlockAndExtension for BasicBlock {
93     fn and<T>(self, v: T) -> BlockAnd<T> {
94         BlockAnd(self, v)
95     }
96
97     fn unit(self) -> BlockAnd<()> {
98         BlockAnd(self, ())
99     }
100 }
101
102 /// Update a block pointer and return the value.
103 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
104 macro_rules! unpack {
105     ($x:ident = $c:expr) => {
106         {
107             let BlockAnd(b, v) = $c;
108             $x = b;
109             v
110         }
111     };
112
113     ($c:expr) => {
114         {
115             let BlockAnd(b, ()) = $c;
116             b
117         }
118     };
119 }
120
121 ///////////////////////////////////////////////////////////////////////////
122 /// the main entry point for building MIR for a function
123
124 pub fn construct_fn<'a, 'gcx, 'tcx, A>(hir: Cx<'a, 'gcx, 'tcx>,
125                                        fn_id: ast::NodeId,
126                                        arguments: A,
127                                        abi: Abi,
128                                        return_ty: Ty<'gcx>,
129                                        body: &'gcx hir::Body)
130                                        -> Mir<'tcx>
131     where A: Iterator<Item=(Ty<'gcx>, Option<&'gcx hir::Pat>)>
132 {
133     let arguments: Vec<_> = arguments.collect();
134
135     let tcx = hir.tcx();
136     let span = tcx.hir.span(fn_id);
137     let mut builder = Builder::new(hir.clone(), span, arguments.len(), return_ty);
138
139     let call_site_extent =
140         tcx.intern_code_extent(
141             CodeExtentData::CallSiteScope { fn_id: fn_id, body_id: body.value.id });
142     let arg_extent =
143         tcx.intern_code_extent(
144             CodeExtentData::ParameterScope { fn_id: fn_id, body_id: body.value.id });
145     let mut block = START_BLOCK;
146     unpack!(block = builder.in_scope(call_site_extent, block, |builder| {
147         unpack!(block = builder.in_scope(arg_extent, block, |builder| {
148             builder.args_and_body(block, &arguments, arg_extent, &body.value)
149         }));
150         // Attribute epilogue to function's closing brace
151         let fn_end = Span { lo: span.hi, ..span };
152         let source_info = builder.source_info(fn_end);
153         let return_block = builder.return_block();
154         builder.cfg.terminate(block, source_info,
155                               TerminatorKind::Goto { target: return_block });
156         builder.cfg.terminate(return_block, source_info,
157                               TerminatorKind::Return);
158         return_block.unit()
159     }));
160     assert_eq!(block, builder.return_block());
161
162     let mut spread_arg = None;
163     if abi == Abi::RustCall {
164         // RustCall pseudo-ABI untuples the last argument.
165         spread_arg = Some(Local::new(arguments.len()));
166     }
167
168     // Gather the upvars of a closure, if any.
169     let upvar_decls: Vec<_> = tcx.with_freevars(fn_id, |freevars| {
170         freevars.iter().map(|fv| {
171             let var_id = tcx.hir.as_local_node_id(fv.def.def_id()).unwrap();
172             let by_ref = hir.tables().upvar_capture(ty::UpvarId {
173                 var_id: var_id,
174                 closure_expr_id: fn_id
175             }).map_or(false, |capture| match capture {
176                 ty::UpvarCapture::ByValue => false,
177                 ty::UpvarCapture::ByRef(..) => true
178             });
179             let mut decl = UpvarDecl {
180                 debug_name: keywords::Invalid.name(),
181                 by_ref: by_ref
182             };
183             if let Some(hir::map::NodeLocal(pat)) = tcx.hir.find(var_id) {
184                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
185                     decl.debug_name = ident.node;
186                 }
187             }
188             decl
189         }).collect()
190     });
191
192     let mut mir = builder.finish(upvar_decls, return_ty);
193     mir.spread_arg = spread_arg;
194     mir
195 }
196
197 pub fn construct_const<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
198                                        body_id: hir::BodyId)
199                                        -> Mir<'tcx> {
200     let tcx = hir.tcx();
201     let ast_expr = &tcx.hir.body(body_id).value;
202     let ty = hir.tables().expr_ty_adjusted(ast_expr);
203     let owner_id = tcx.hir.body_owner(body_id);
204     let span = tcx.hir.span(owner_id);
205     let mut builder = Builder::new(hir.clone(), span, 0, ty);
206
207     let extent = hir.region_maps.temporary_scope(tcx, ast_expr.id)
208                                 .unwrap_or(tcx.item_extent(owner_id));
209     let mut block = START_BLOCK;
210     let _ = builder.in_scope(extent, block, |builder| {
211         let expr = builder.hir.mirror(ast_expr);
212         unpack!(block = builder.into(&Lvalue::Local(RETURN_POINTER), block, expr));
213
214         let source_info = builder.source_info(span);
215         let return_block = builder.return_block();
216         builder.cfg.terminate(block, source_info,
217                               TerminatorKind::Goto { target: return_block });
218         builder.cfg.terminate(return_block, source_info,
219                               TerminatorKind::Return);
220
221         return_block.unit()
222     });
223
224     builder.finish(vec![], ty)
225 }
226
227 pub fn construct_error<'a, 'gcx, 'tcx>(hir: Cx<'a, 'gcx, 'tcx>,
228                                        body_id: hir::BodyId)
229                                        -> Mir<'tcx> {
230     let span = hir.tcx().hir.span(hir.tcx().hir.body_owner(body_id));
231     let ty = hir.tcx().types.err;
232     let mut builder = Builder::new(hir, span, 0, ty);
233     let source_info = builder.source_info(span);
234     builder.cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
235     builder.finish(vec![], ty)
236 }
237
238 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
239     fn new(hir: Cx<'a, 'gcx, 'tcx>,
240            span: Span,
241            arg_count: usize,
242            return_ty: Ty<'tcx>)
243            -> Builder<'a, 'gcx, 'tcx> {
244         let mut builder = Builder {
245             hir: hir,
246             cfg: CFG { basic_blocks: IndexVec::new() },
247             fn_span: span,
248             arg_count: arg_count,
249             scopes: vec![],
250             visibility_scopes: IndexVec::new(),
251             visibility_scope: ARGUMENT_VISIBILITY_SCOPE,
252             breakable_scopes: vec![],
253             local_decls: IndexVec::from_elem_n(LocalDecl::new_return_pointer(return_ty,
254                                                                              span), 1),
255             var_indices: NodeMap(),
256             unit_temp: None,
257             cached_resume_block: None,
258             cached_return_block: None
259         };
260
261         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
262         assert_eq!(builder.new_visibility_scope(span), ARGUMENT_VISIBILITY_SCOPE);
263         builder.visibility_scopes[ARGUMENT_VISIBILITY_SCOPE].parent_scope = None;
264
265         builder
266     }
267
268     fn finish(self,
269               upvar_decls: Vec<UpvarDecl>,
270               return_ty: Ty<'tcx>)
271               -> Mir<'tcx> {
272         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
273             if block.terminator.is_none() {
274                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
275             }
276         }
277
278         Mir::new(self.cfg.basic_blocks,
279                  self.visibility_scopes,
280                  IndexVec::new(),
281                  return_ty,
282                  self.local_decls,
283                  self.arg_count,
284                  upvar_decls,
285                  self.fn_span
286         )
287     }
288
289     fn args_and_body(&mut self,
290                      mut block: BasicBlock,
291                      arguments: &[(Ty<'gcx>, Option<&'gcx hir::Pat>)],
292                      argument_extent: CodeExtent<'tcx>,
293                      ast_body: &'gcx hir::Expr)
294                      -> BlockAnd<()>
295     {
296         // Allocate locals for the function arguments
297         for &(ty, pattern) in arguments.iter() {
298             // If this is a simple binding pattern, give the local a nice name for debuginfo.
299             let mut name = None;
300             if let Some(pat) = pattern {
301                 if let hir::PatKind::Binding(_, _, ref ident, _) = pat.node {
302                     name = Some(ident.node);
303                 }
304             }
305
306             self.local_decls.push(LocalDecl {
307                 mutability: Mutability::Not,
308                 ty: ty,
309                 source_info: SourceInfo {
310                     scope: ARGUMENT_VISIBILITY_SCOPE,
311                     span: pattern.map_or(self.fn_span, |pat| pat.span)
312                 },
313                 name: name,
314                 is_user_variable: false,
315             });
316         }
317
318         let mut scope = None;
319         // Bind the argument patterns
320         for (index, &(ty, pattern)) in arguments.iter().enumerate() {
321             // Function arguments always get the first Local indices after the return pointer
322             let lvalue = Lvalue::Local(Local::new(index + 1));
323
324             if let Some(pattern) = pattern {
325                 let pattern = Pattern::from_hir(self.hir.tcx(), self.hir.tables(), pattern);
326                 scope = self.declare_bindings(scope, ast_body.span, &pattern);
327                 unpack!(block = self.lvalue_into_pattern(block, pattern, &lvalue));
328             }
329
330             // Make sure we drop (parts of) the argument even when not matched on.
331             self.schedule_drop(pattern.as_ref().map_or(ast_body.span, |pat| pat.span),
332                                argument_extent, &lvalue, ty);
333
334         }
335
336         // Enter the argument pattern bindings visibility scope, if it exists.
337         if let Some(visibility_scope) = scope {
338             self.visibility_scope = visibility_scope;
339         }
340
341         let body = self.hir.mirror(ast_body);
342         self.into(&Lvalue::Local(RETURN_POINTER), block, body)
343     }
344
345     fn get_unit_temp(&mut self) -> Lvalue<'tcx> {
346         match self.unit_temp {
347             Some(ref tmp) => tmp.clone(),
348             None => {
349                 let ty = self.hir.unit_ty();
350                 let fn_span = self.fn_span;
351                 let tmp = self.temp(ty, fn_span);
352                 self.unit_temp = Some(tmp.clone());
353                 tmp
354             }
355         }
356     }
357
358     fn return_block(&mut self) -> BasicBlock {
359         match self.cached_return_block {
360             Some(rb) => rb,
361             None => {
362                 let rb = self.cfg.start_new_block();
363                 self.cached_return_block = Some(rb);
364                 rb
365             }
366         }
367     }
368 }
369
370 ///////////////////////////////////////////////////////////////////////////
371 // Builder methods are broken up into modules, depending on what kind
372 // of thing is being translated. Note that they use the `unpack` macro
373 // above extensively.
374
375 mod block;
376 mod cfg;
377 mod expr;
378 mod into;
379 mod matches;
380 mod misc;
381 mod scope;