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.
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.
11 #![allow(non_camel_case_types)]
13 use std::cell::{RefCell, Cell};
14 use std::collections::HashMap;
15 use std::collections::hash_state::HashState;
16 use std::ffi::CString;
19 use std::iter::repeat;
21 use std::time::Duration;
25 use syntax::visit::Visitor;
27 // The name of the associated type for `Fn` return types
28 pub const FN_OUTPUT_NAME: &'static str = "Output";
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;
35 pub fn time<T, F>(do_it: bool, what: &str, f: F) -> T where
38 thread_local!(static DEPTH: Cell<usize> = Cell::new(0));
39 if !do_it { return f(); }
41 let old = DEPTH.with(|slot| {
51 Duration::span(move || {
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;
63 let mem_string = match get_resident() {
65 let mb = n as f64 / 1_000_000.0;
66 format!("; rss: {}MB", mb.round() as usize)
68 None => "".to_owned(),
70 println!("{}time: {:.3}{}\t{}", repeat(" ").take(old).collect::<String>(),
71 secs, mem_string, what);
73 DEPTH.with(|slot| slot.set(old));
78 // Like std::macros::try!, but for Option<>.
79 macro_rules! option_try(
80 ($e:expr) => (match $e { Some(e) => e, None => return None })
85 fn get_resident() -> Option<usize> {
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());
99 fn get_resident() -> Option<usize> {
100 use libc::{BOOL, DWORD, HANDLE, SIZE_T, GetCurrentProcess};
102 #[repr(C)] #[allow(non_snake_case)]
103 struct PROCESS_MEMORY_COUNTERS {
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,
115 type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
116 #[link(name = "psapi")]
118 fn GetProcessMemoryInfo(Process: HANDLE,
119 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
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) } {
126 _ => Some(pmc.WorkingSetSize as usize),
130 pub fn indent<R, F>(op: F) -> R where
134 // Use in conjunction with the log post-processor like `src/etc/indenter`
135 // to make debug output more readable.
138 debug!("<< (Result = {:?})", r);
142 pub struct Indenter {
143 _cannot_construct_outside_of_this_module: ()
146 impl Drop for Indenter {
147 fn drop(&mut self) { debug!("<<"); }
150 pub fn indenter() -> Indenter {
152 Indenter { _cannot_construct_outside_of_this_module: () }
155 struct LoopQueryVisitor<P> where P: FnMut(&ast::Expr_) -> bool {
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);
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)
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 {
179 visit::walk_block(&mut v, b);
183 struct BlockQueryVisitor<P> where P: FnMut(&ast::Expr) -> bool {
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)
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 {
202 visit::walk_block(&mut v, &*b);
206 /// Memoizes a one-argument closure using the given RefCell containing
207 /// a type implementing MutableMap to serve as a cache.
209 /// In the future the signature of this function is expected to be:
211 /// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
212 /// cache: &RefCell<M>,
214 /// ) -> impl |T| -> U {
216 /// but currently it is not possible.
221 /// cache: RefCell<HashMap<usize, usize>>
224 /// fn factorial(ctxt: &Context, n: usize) -> usize {
225 /// memoized(&ctxt.cache, n, |n| match n {
227 /// _ => factorial(ctxt, n - 2) + factorial(ctxt, n - 1)
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,
238 let key = arg.clone();
239 let result = cache.borrow().get(&key).cloned();
241 Some(result) => result,
244 cache.borrow_mut().insert(key, result.clone());
251 pub fn path2cstr(p: &Path) -> CString {
252 use std::os::unix::prelude::*;
254 let p: &OsStr = p.as_ref();
255 CString::new(p.as_bytes()).unwrap()
258 pub fn path2cstr(p: &Path) -> CString {
259 CString::new(p.to_str().unwrap()).unwrap()