]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/common.rs
Port a bunch of code new-visitor; all of these ports were
[rust.git] / src / librustc / util / common.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 #![allow(non_camel_case_types)]
12
13 use std::cell::{RefCell, Cell};
14 use std::collections::HashMap;
15 use std::collections::hash_state::HashState;
16 use std::ffi::CString;
17 use std::fmt::Debug;
18 use std::hash::Hash;
19 use std::iter::repeat;
20 use std::path::Path;
21 use std::time::Duration;
22
23 use rustc_front::hir;
24 use rustc_front::intravisit;
25 use rustc_front::intravisit::Visitor;
26
27 // The name of the associated type for `Fn` return types
28 pub const FN_OUTPUT_NAME: &'static str = "Output";
29
30 // Useful type to use with `Result<>` indicate that an error has already
31 // been reported to the user, so no need to continue checking.
32 #[derive(Clone, Copy, Debug)]
33 pub struct ErrorReported;
34
35 pub fn time<T, F>(do_it: bool, what: &str, f: F) -> T where
36     F: FnOnce() -> T,
37 {
38     thread_local!(static DEPTH: Cell<usize> = Cell::new(0));
39     if !do_it { return f(); }
40
41     let old = DEPTH.with(|slot| {
42         let r = slot.get();
43         slot.set(r + 1);
44         r
45     });
46
47     let mut rv = None;
48     let dur = {
49         let ref mut rvp = rv;
50
51         Duration::span(move || {
52             *rvp = Some(f())
53         })
54     };
55     let rv = rv.unwrap();
56
57     // Hack up our own formatting for the duration to make it easier for scripts
58     // to parse (always use the same number of decimal places and the same unit).
59     const NANOS_PER_SEC: f64 = 1_000_000_000.0;
60     let secs = dur.as_secs() as f64;
61     let secs = secs + dur.subsec_nanos() as f64 / NANOS_PER_SEC;
62
63     let mem_string = match get_resident() {
64         Some(n) => {
65             let mb = n as f64 / 1_000_000.0;
66             format!("; rss: {}MB", mb.round() as usize)
67         }
68         None => "".to_owned(),
69     };
70     println!("{}time: {:.3}{}\t{}", repeat("  ").take(old).collect::<String>(),
71              secs, mem_string, what);
72
73     DEPTH.with(|slot| slot.set(old));
74
75     rv
76 }
77
78 // Like std::macros::try!, but for Option<>.
79 macro_rules! option_try(
80     ($e:expr) => (match $e { Some(e) => e, None => return None })
81 );
82
83 // Memory reporting
84 #[cfg(unix)]
85 fn get_resident() -> Option<usize> {
86     use std::fs::File;
87     use std::io::Read;
88
89     let field = 1;
90     let mut f = option_try!(File::open("/proc/self/statm").ok());
91     let mut contents = String::new();
92     option_try!(f.read_to_string(&mut contents).ok());
93     let s = option_try!(contents.split_whitespace().nth(field));
94     let npages = option_try!(s.parse::<usize>().ok());
95     Some(npages * 4096)
96 }
97
98 #[cfg(windows)]
99 #[cfg_attr(stage0, allow(improper_ctypes))]
100 fn get_resident() -> Option<usize> {
101     type BOOL = i32;
102     type DWORD = u32;
103     type HANDLE = *mut u8;
104     use libc::size_t;
105     use std::mem;
106     #[repr(C)] #[allow(non_snake_case)]
107     struct PROCESS_MEMORY_COUNTERS {
108         cb: DWORD,
109         PageFaultCount: DWORD,
110         PeakWorkingSetSize: size_t,
111         WorkingSetSize: size_t,
112         QuotaPeakPagedPoolUsage: size_t,
113         QuotaPagedPoolUsage: size_t,
114         QuotaPeakNonPagedPoolUsage: size_t,
115         QuotaNonPagedPoolUsage: size_t,
116         PagefileUsage: size_t,
117         PeakPagefileUsage: size_t,
118     }
119     type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
120     #[link(name = "psapi")]
121     extern "system" {
122         fn GetCurrentProcess() -> HANDLE;
123         fn GetProcessMemoryInfo(Process: HANDLE,
124                                 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
125                                 cb: DWORD) -> BOOL;
126     }
127     let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { mem::zeroed() };
128     pmc.cb = mem::size_of_val(&pmc) as DWORD;
129     match unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) } {
130         0 => None,
131         _ => Some(pmc.WorkingSetSize as usize),
132     }
133 }
134
135 pub fn indent<R, F>(op: F) -> R where
136     R: Debug,
137     F: FnOnce() -> R,
138 {
139     // Use in conjunction with the log post-processor like `src/etc/indenter`
140     // to make debug output more readable.
141     debug!(">>");
142     let r = op();
143     debug!("<< (Result = {:?})", r);
144     r
145 }
146
147 pub struct Indenter {
148     _cannot_construct_outside_of_this_module: ()
149 }
150
151 impl Drop for Indenter {
152     fn drop(&mut self) { debug!("<<"); }
153 }
154
155 pub fn indenter() -> Indenter {
156     debug!(">>");
157     Indenter { _cannot_construct_outside_of_this_module: () }
158 }
159
160 struct LoopQueryVisitor<P> where P: FnMut(&hir::Expr_) -> bool {
161     p: P,
162     flag: bool,
163 }
164
165 impl<'v, P> Visitor<'v> for LoopQueryVisitor<P> where P: FnMut(&hir::Expr_) -> bool {
166     fn visit_expr(&mut self, e: &hir::Expr) {
167         self.flag |= (self.p)(&e.node);
168         match e.node {
169           // Skip inner loops, since a break in the inner loop isn't a
170           // break inside the outer loop
171           hir::ExprLoop(..) | hir::ExprWhile(..) => {}
172           _ => intravisit::walk_expr(self, e)
173         }
174     }
175 }
176
177 // Takes a predicate p, returns true iff p is true for any subexpressions
178 // of b -- skipping any inner loops (loop, while, loop_body)
179 pub fn loop_query<P>(b: &hir::Block, p: P) -> bool where P: FnMut(&hir::Expr_) -> bool {
180     let mut v = LoopQueryVisitor {
181         p: p,
182         flag: false,
183     };
184     intravisit::walk_block(&mut v, b);
185     return v.flag;
186 }
187
188 struct BlockQueryVisitor<P> where P: FnMut(&hir::Expr) -> bool {
189     p: P,
190     flag: bool,
191 }
192
193 impl<'v, P> Visitor<'v> for BlockQueryVisitor<P> where P: FnMut(&hir::Expr) -> bool {
194     fn visit_expr(&mut self, e: &hir::Expr) {
195         self.flag |= (self.p)(e);
196         intravisit::walk_expr(self, e)
197     }
198 }
199
200 // Takes a predicate p, returns true iff p is true for any subexpressions
201 // of b -- skipping any inner loops (loop, while, loop_body)
202 pub fn block_query<P>(b: &hir::Block, p: P) -> bool where P: FnMut(&hir::Expr) -> bool {
203     let mut v = BlockQueryVisitor {
204         p: p,
205         flag: false,
206     };
207     intravisit::walk_block(&mut v, &*b);
208     return v.flag;
209 }
210
211 /// Memoizes a one-argument closure using the given RefCell containing
212 /// a type implementing MutableMap to serve as a cache.
213 ///
214 /// In the future the signature of this function is expected to be:
215 /// ```
216 /// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
217 ///    cache: &RefCell<M>,
218 ///    f: &|T| -> U
219 /// ) -> impl |T| -> U {
220 /// ```
221 /// but currently it is not possible.
222 ///
223 /// # Examples
224 /// ```
225 /// struct Context {
226 ///    cache: RefCell<HashMap<usize, usize>>
227 /// }
228 ///
229 /// fn factorial(ctxt: &Context, n: usize) -> usize {
230 ///     memoized(&ctxt.cache, n, |n| match n {
231 ///         0 | 1 => n,
232 ///         _ => factorial(ctxt, n - 2) + factorial(ctxt, n - 1)
233 ///     })
234 /// }
235 /// ```
236 #[inline(always)]
237 pub fn memoized<T, U, S, F>(cache: &RefCell<HashMap<T, U, S>>, arg: T, f: F) -> U
238     where T: Clone + Hash + Eq,
239           U: Clone,
240           S: HashState,
241           F: FnOnce(T) -> U,
242 {
243     let key = arg.clone();
244     let result = cache.borrow().get(&key).cloned();
245     match result {
246         Some(result) => result,
247         None => {
248             let result = f(arg);
249             cache.borrow_mut().insert(key, result.clone());
250             result
251         }
252     }
253 }
254
255 #[cfg(unix)]
256 pub fn path2cstr(p: &Path) -> CString {
257     use std::os::unix::prelude::*;
258     use std::ffi::OsStr;
259     let p: &OsStr = p.as_ref();
260     CString::new(p.as_bytes()).unwrap()
261 }
262 #[cfg(windows)]
263 pub fn path2cstr(p: &Path) -> CString {
264     CString::new(p.to_str().unwrap()).unwrap()
265 }