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;
24 use rustc_front::visit;
25 use rustc_front::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 #[cfg_attr(stage0, allow(improper_ctypes))]
100 fn get_resident() -> Option<usize> {
103 type HANDLE = *mut u8;
106 #[repr(C)] #[allow(non_snake_case)]
107 struct PROCESS_MEMORY_COUNTERS {
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,
119 type PPROCESS_MEMORY_COUNTERS = *mut PROCESS_MEMORY_COUNTERS;
120 #[link(name = "psapi")]
122 fn GetCurrentProcess() -> HANDLE;
123 fn GetProcessMemoryInfo(Process: HANDLE,
124 ppsmemCounters: PPROCESS_MEMORY_COUNTERS,
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) } {
131 _ => Some(pmc.WorkingSetSize as usize),
135 pub fn indent<R, F>(op: F) -> R where
139 // Use in conjunction with the log post-processor like `src/etc/indenter`
140 // to make debug output more readable.
143 debug!("<< (Result = {:?})", r);
147 pub struct Indenter {
148 _cannot_construct_outside_of_this_module: ()
151 impl Drop for Indenter {
152 fn drop(&mut self) { debug!("<<"); }
155 pub fn indenter() -> Indenter {
157 Indenter { _cannot_construct_outside_of_this_module: () }
160 struct LoopQueryVisitor<P> where P: FnMut(&hir::Expr_) -> bool {
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);
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 _ => visit::walk_expr(self, e)
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 {
184 visit::walk_block(&mut v, b);
188 struct BlockQueryVisitor<P> where P: FnMut(&hir::Expr) -> bool {
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 visit::walk_expr(self, e)
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 {
207 visit::walk_block(&mut v, &*b);
211 /// Memoizes a one-argument closure using the given RefCell containing
212 /// a type implementing MutableMap to serve as a cache.
214 /// In the future the signature of this function is expected to be:
216 /// pub fn memoized<T: Clone, U: Clone, M: MutableMap<T, U>>(
217 /// cache: &RefCell<M>,
219 /// ) -> impl |T| -> U {
221 /// but currently it is not possible.
226 /// cache: RefCell<HashMap<usize, usize>>
229 /// fn factorial(ctxt: &Context, n: usize) -> usize {
230 /// memoized(&ctxt.cache, n, |n| match n {
232 /// _ => factorial(ctxt, n - 2) + factorial(ctxt, n - 1)
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,
243 let key = arg.clone();
244 let result = cache.borrow().get(&key).cloned();
246 Some(result) => result,
249 cache.borrow_mut().insert(key, result.clone());
256 pub fn path2cstr(p: &Path) -> CString {
257 use std::os::unix::prelude::*;
259 let p: &OsStr = p.as_ref();
260 CString::new(p.as_bytes()).unwrap()
263 pub fn path2cstr(p: &Path) -> CString {
264 CString::new(p.to_str().unwrap()).unwrap()