Skip to content

Commit

Permalink
added the parameters for the log frontend
Browse files Browse the repository at this point in the history
Still needs some tests
  • Loading branch information
gbin committed May 25, 2024
1 parent 44d7a83 commit 600a759
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 12 deletions.
59 changes: 47 additions & 12 deletions copper_log/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,58 @@ use crate::index::check_and_insert;
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenTree};
use quote::quote;
use syn::{custom_keyword, parse_macro_input, LitStr};
use syn::parse::Parser;
use syn::Token;
use syn::{custom_keyword, parse_macro_input, Expr, ExprAssign, ExprLit, Lit, LitStr};

#[proc_macro]
pub fn debug(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as LitStr);
let message = input.value();
// We put dummy locations here because we cannot get the actual location of the macro invocation
let index = check_and_insert("dummy", 0, &message).expect("Failed to insert log string.");
let parser = syn::punctuated::Punctuated::<Expr, Token![,]>::parse_terminated;
let exprs = parser.parse(input).expect("Failed to parse input");

let expanded = quote! {
{
let log_message = #message;
println!("#{}:{}:{} Log: {:?}", #index, file!(), line!(), log_message);
log_message
let mut exprs_iter = exprs.iter();

let msg_expr = exprs_iter.next().expect("Expected at least one expression");
let (index, msg) = if let Expr::Lit(ExprLit {
lit: Lit::Str(msg), ..
}) = msg_expr
{
let msg = msg.value();
let index = check_and_insert("dummy", 0, &msg).expect("Failed to insert log string.");
(index, msg)
} else {
panic!("The first parameter of the argument needs to be a string literal.");
};
println!("{} -> [{}]", index, msg);

let mut unnamed_params = vec![];
let mut named_params = vec![];

for expr in exprs_iter {
if let Expr::Assign(ExprAssign { left, right, .. }) = expr {
named_params.push((left, right));
} else {
unnamed_params.push(expr);
}
}

let unnamed_prints = unnamed_params.iter().map(|param| {
quote! {
println!("{:?}", #param);
}
});

let named_prints = named_params.iter().map(|(name, value)| {
quote! {
println!("{} = {:?}", stringify!(#name), #value);
}
});

let expanded = quote! {
println!("Message: {}", #msg);
#(#unnamed_prints)*
#(#named_prints)*
};
println!("#{} -> [{}]", index, message);

TokenStream::from(expanded)
expanded.into()
}
1 change: 1 addition & 0 deletions copper_log_test/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ fn main() {
let b = 3;
// debug!("Hello, world! {} {}", a, b);
debug!("Hello, world!");
debug!("Hello, world2!", a);
}

0 comments on commit 600a759

Please sign in to comment.