]> git.lizzy.rs Git - rust.git/blob - src/librustc/util/common.rs
Rollup merge of #27934 - MatejLach:spacing_fix, r=steveklabnik
[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 syntax::ast;
24 use syntax::visit;
25 use syntax::visit::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 fn get_resident() -> Option<usize> {
100     use libc::{BOOL, DWORD, HANDLE, SIZE_T, GetCurrentProcess};
101     use std::mem;
102     #[repr(C)] #[allow(non_snake_case)]
103     struct PROCESS_MEMORY_COUNTERS {
104         cb: DWORD,
105         PageFaultCount: DWORD,
106         PeakWorkingSetSize: SIZE_T,
107         WorkingSetSize: SIZE_T,
108         QuotaPeakPagedPoolUsage: SIZE_T,
109         QuotaPagedPoolUsage: SIZE_T,
110         QuotaPeakNonPagedPoolUsage: SIZE_T,
111         QuotaNonPagedPoolUsage: SIZE_T,
112         PagefileUsage: SIZE_T,
113         PeakPagefileUsage: SIZE_T,
114     }
115     type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
116     #[link(name = "psapi")]
117     extern "system" {
118         fn GetProcessMemoryInfo(Process: HANDLE,
119                                 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
120                                 cb: DWORD) -> BOOL;
121     }
122     let mut pmc: PROCESS_MEMORY_COUNTERS = unsafe { mem::zeroed() };
123     pmc.cb = mem::size_of_val(&pmc) as DWORD;
124     match unsafe { GetProcessMemoryInfo(GetCurrentProcess(), &mut pmc, pmc.cb) } {
125         0 => None,
126         _ => Some(pmc.WorkingSetSize as usize),
127     }
128 }
129
130 pub fn indent<R, F>(op: F) -> R where
131     R: Debug,
132     F: FnOnce() -> R,
133 {
134     // Use in conjunction with the log post-processor like `src/etc/indenter`
135     // to make debug output more readable.
136     debug!(">>");
137     let r = op();
138     debug!("<< (Result = {:?})", r);
139     r
140 }
141
142 pub struct Indenter {
143     _cannot_construct_outside_of_this_module: ()
144 }
145
146 impl Drop for Indenter {
147     fn drop(&mut self) { debug!("<<"); }
148 }
149
150 pub fn indenter() -> Indenter {
151     debug!(">>");
152     Indenter { _cannot_construct_outside_of_this_module: () }
153 }
154
155 struct LoopQueryVisitor<P> where P: FnMut(&ast::Expr_) -> bool {
156     p: P,
157     flag: bool,
158 }
159
160 impl<'v, P> Visitor<'v> for LoopQueryVisitor<P> where P: FnMut(&ast::Expr_) -> bool {
161     fn visit_expr(&mut self, e: &ast::Expr) {
162         self.flag |= (self.p)(&e.node);
163         match e.node {
164           // Skip inner loops, since a break in the inner loop isn't a
165           // break inside the outer loop
166           ast::ExprLoop(..) | ast::ExprWhile(..) => {}
167           _ => visit::walk_expr(self, e)
168         }
169     }
170 }
171
172 // Takes a predicate p, returns true iff p is true for any subexpressions
173 // of b -- skipping any inner loops (loop, while, loop_body)
174 pub fn loop_query<P>(b: &ast::Block, p: P) -> bool where P: FnMut(&ast::Expr_) -> bool {
175     let mut v = LoopQueryVisitor {
176         p: p,
177         flag: false,
178     };
179     visit::walk_block(&mut v, b);
180     return v.flag;
181 }
182
183 struct BlockQueryVisitor<P> where P: FnMut(&ast::Expr) -> bool {
184     p: P,
185     flag: bool,
186 }
187
188 impl<'v, P> Visitor<'v> for BlockQueryVisitor<P> where P: FnMut(&ast::Expr) -> bool {
189     fn visit_expr(&mut self, e: &ast::Expr) {
190         self.flag |= (self.p)(e);
191         visit::walk_expr(self, e)
192     }
193 }
194
195 // Takes a predicate p, returns true iff p is true for any subexpressions
196 // of b -- skipping any inner loops (loop, while, loop_body)
197 pub fn block_query<P>(b: &ast::Block, p: P) -> bool where P: FnMut(&ast::Expr) -> bool {
198     let mut v = BlockQueryVisitor {
199         p: p,
200         flag: false,
201     };
202     visit::walk_block(&mut v, &*b);
203     return v.flag;
204 }
205
206 /// Memoizes a one-argument closure using the given RefCell containing
207 /// a type implementing MutableMap to serve as a cache.
208 ///
209 /// In the future the signature of this function is expected to be:
210 /// ```
211 /// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
212 ///    cache: &RefCell<M>,
213 ///    f: &|T| -> U
214 /// ) -> impl |T| -> U {
215 /// ```
216 /// but currently it is not possible.
217 ///
218 /// # Examples
219 /// ```
220 /// struct Context {
221 ///    cache: RefCell<HashMap<usize, usize>>
222 /// }
223 ///
224 /// fn factorial(ctxt: &Context, n: usize) -> usize {
225 ///     memoized(&ctxt.cache, n, |n| match n {
226 ///         0 | 1 => n,
227 ///         _ => factorial(ctxt, n - 2) + factorial(ctxt, n - 1)
228 ///     })
229 /// }
230 /// ```
231 #[inline(always)]
232 pub fn memoized<T, U, S, F>(cache: &RefCell<HashMap<T, U, S>>, arg: T, f: F) -> U
233     where T: Clone + Hash + Eq,
234           U: Clone,
235           S: HashState,
236           F: FnOnce(T) -> U,
237 {
238     let key = arg.clone();
239     let result = cache.borrow().get(&key).cloned();
240     match result {
241         Some(result) => result,
242         None => {
243             let result = f(arg);
244             cache.borrow_mut().insert(key, result.clone());
245             result
246         }
247     }
248 }
249
250 #[cfg(unix)]
251 pub fn path2cstr(p: &Path) -> CString {
252     use std::os::unix::prelude::*;
253     use std::ffi::OsStr;
254     let p: &OsStr = p.as_ref();
255     CString::new(p.as_bytes()).unwrap()
256 }
257 #[cfg(windows)]
258 pub fn path2cstr(p: &Path) -> CString {
259     CString::new(p.to_str().unwrap()).unwrap()
260 }