Skip to content

Commit

Permalink
new
Browse files Browse the repository at this point in the history
  • Loading branch information
kardeiz committed Nov 19, 2019
0 parents commit 37ab312
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/target
**/*.rs.bk
Cargo.lock
15 changes: 15 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "funtime"
version = "0.1.0"
authors = ["Jacob Brown <[email protected]>"]
edition = "2018"
license = "MIT OR Apache-2.0"

[dependencies]
syn = { version = "1", features = ["full", "extra-traits"] }
quote = "1"
proc-macro2 = "1"


[lib]
proc-macro = true
15 changes: 15 additions & 0 deletions examples/simple.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#[funtime::timed]
fn foo() -> i32 {

let mut x = 1;

x += 1;

10

}


fn main() {
foo();
}
74 changes: 74 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
extern crate proc_macro;

use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::*;

#[proc_macro_attribute]
pub fn timed(attrs: TokenStream, item: TokenStream) -> TokenStream {

if let Ok(mut fun) = parse::<ItemFn>(item) {
let new_stmts = rewrite_stmts(fun.sig.ident.to_string(), &fun.block.stmts);
fun.block.stmts = new_stmts;
return quote!(#fun).into();
// return panic!("{}", quote!(#fun));
}

unimplemented!()
}

fn rewrite_stmts(name: String, stmts: &[Stmt]) -> Vec<Stmt> {

let setup: Block = parse_quote! {{
struct FuntimeTimer(std::time::Instant, String);

impl Drop for FuntimeTimer {
fn drop(&mut self) {
println!("Took {:?}: `{}` complete", self.0.elapsed(), &self.1);
}
}

impl FuntimeTimer {
fn print_elapsed(&self, short: &str) {
println!("Took {:?}: `{}`", self.0.elapsed(), short);
}
}

let funtime_timer = FuntimeTimer(std::time::Instant::now(), String::from(#name));

}};

let mut new_stmts = setup.stmts;

for stmt in stmts {
new_stmts.push(stmt.clone());

if let Stmt::Expr(..) = stmt {
continue;
}

let mut short = format!("{}", quote::ToTokens::to_token_stream(stmt)).chars().collect::<Vec<_>>();

let short = if short.len() > 40 {
let mut short = short[..37].into_iter().collect::<String>();
short.push_str("...");
short
} else {
short.into_iter().collect::<String>()
};

new_stmts.push(parse_quote!(funtime_timer.print_elapsed(#short);));
}

new_stmts
}


#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}

0 comments on commit 37ab312

Please sign in to comment.