Skip to content

Commit

Permalink
Evolve: Quiet warnings
Browse files Browse the repository at this point in the history
Signed-off-by: Mark Van de Vyver <[email protected]>
  • Loading branch information
taqtiqa-mark committed Apr 6, 2022
1 parent 873c080 commit c6cbd1d
Show file tree
Hide file tree
Showing 6 changed files with 110 additions and 59 deletions.
2 changes: 1 addition & 1 deletion minitrace-macro/src/darling.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ extern crate syn;

use {
darling::*,
std::path::*,
// std::path::*,
};

#[derive(FromMeta)]
Expand Down
15 changes: 9 additions & 6 deletions minitrace-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,24 +34,27 @@ use syn::{punctuated::Punctuated, visit_mut::VisitMut, Ident, *};
use crate::trace::validate::TraceAttr;

mod trace;
mod darling;
//mod darling;

#[proc_macro_attribute]
#[proc_macro_error]
pub fn trace2(
pub fn trace(
args: proc_macro::TokenStream,
items: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
// Parse TokenStream in context of `#[proc_macro_attribute]`.
// This context is required by `parse_macro_input!(...)`.
// NOTE: See comment above Trace
println!("{:#?}", args);
println!("{:#?}", items);
let argsc = args.clone();
let attr_args = parse_macro_input!(argsc as TraceAttr);
let args2: proc_macro2::TokenStream = args.clone().into();

// Validate - Analyze - Lower - Generate - Rust (VALGR)

println!("{:#?}", args2);
trace::validate(args2, items.clone().into());
println!("{:#?}", attr_args);
let models = trace::analyze(attr_args, items.into());
let ir = trace::lower(models);
let rust = trace::generate(ir);
Expand Down Expand Up @@ -101,7 +104,7 @@ impl Args {

#[proc_macro_attribute]
#[proc_macro_error]
pub fn trace(
pub fn trace2(
args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
Expand Down Expand Up @@ -604,7 +607,7 @@ fn get_async_trait_info(block: &Block, block_is_async: bool) -> Option<AsyncTrai
}

// Return a path as a String
fn path_to_string(path: &Path) -> String {
fn path_to_string(path: &syn::Path) -> String {
use std::fmt::Write;
// some heuristic to prevent too many allocations
let mut res = String::with_capacity(path.segments.len() * 5);
Expand Down Expand Up @@ -662,7 +665,7 @@ struct AsyncTraitBlockReplacer<'a> {

impl<'a> syn::visit_mut::VisitMut for AsyncTraitBlockReplacer<'a> {
fn visit_block_mut(&mut self, i: &mut Block) {
if i == self.block {
if i == self.block {
*i = self.patched_block.clone();
}
}
Expand Down
90 changes: 55 additions & 35 deletions minitrace-macro/src/trace/analyze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@ use proc_macro_error::{abort, abort_call_site};
use syn::{
parenthesized,
parse::{Parse, ParseStream},
spanned::Spanned,
Expr, ItemFn,
Expr,
};

use crate::trace::validate::Ast;
//use crate::trace::validate::Ast;

// - `<Macro>.name: syn::LitStr,` // String`
// - `<Macro>.enter_on_poll: syn::LitBool,` // boolean
Expand Down Expand Up @@ -112,8 +111,8 @@ enum Scope {
)]
pub struct Trace {
// Anything that implements `syn::parse::Parse` is supported.
name: syn::LitStr,
scope: Scope, // Scope::Local, Scope::Thread, etc.
name: Option<syn::LitStr>,
scope: Option<Scope>, // Scope::Local, Scope::Thread, etc.

// Fields wrapped in `Option` are and default to `None` if
// not specified in the attribute.
Expand Down Expand Up @@ -154,17 +153,27 @@ impl Parse for Scope {
//
// The `Models` container is built based on the attribute parameters
// held in the `Trace` type.
//
// The inputs are:
// - `meta`: A `syn::Attribute` encapsulated in `TraceAttr`.
// - `items`: A `proc_macr2::TokenStream`.
use syn::visit::Visit;
pub fn analyze(
meta: crate::trace::validate::TraceAttr,
items: proc_macro2::TokenStream,
) -> Models<Model> {
let mut models = Models::<Model>::new();
//println!("Meta {:#?}", meta);
// `from_attributes(..)` takes a slice reference.
// `meta.attrs` is a `Vec<>`, which implements `AsRef`, so is coerced to `&[]`
let attrs: &[syn::Attribute] = &meta.attrs;
// let attribute = Trace::from_attributes(attrs).unwrap();
//println!("Attrs {:#?}", attrs);
let attribute = match Trace::from_attributes(attrs) {
Ok(attrs) => attrs,
Err(err) => return err.into_compile_error().into(),
Ok(trace) => trace,
Err(err) => {
return err.into_compile_error().into();
}
};

models.push(Model::Attribute(attribute));
Expand All @@ -180,21 +189,10 @@ pub fn analyze(
models.push(Model::Item(syn::Item::Fn((*f).clone())));
}

// Move this check for duplicate `#[trace]` attributes to validate
//
// for index in (0..attrs.len()).rev() {
// if let Some(ident) = attrs[index].path.get_ident() {
// if ident.to_string().as_str() == "precondition" {
// let attr = attrs.remove(index);
// let _span = attr.tokens.span();
// }
// }
// }

models
}

// `Models` a Vec-newtype
// `Models` are a Vec-newtype
//
// A wrapper that allows us to implement the [`From`] trait.
// The [`From`] trait provides these conveniences (`match` branch):
Expand All @@ -216,6 +214,7 @@ impl<T: std::fmt::Debug> Models<T> {
Models(Vec::<T>::new())
}

#[allow(dead_code)]
pub fn with_capacity(capacity: usize) -> Models<T> {
Models(Vec::<T>::with_capacity(capacity))
}
Expand Down Expand Up @@ -248,7 +247,7 @@ impl<T: std::fmt::Debug> std::ops::DerefMut for Models<T> {

#[derive(Debug)]
struct Item {
item: syn::Item,
//item: syn::Item,
}

#[derive(Clone, Debug, PartialEq, thiserror::Error)]
Expand Down Expand Up @@ -290,7 +289,7 @@ impl<'ast> syn::visit::Visit<'ast> for FnVisitor<'ast> {
// Err(err) => return err.into_compile_error().into(),
//
impl std::convert::From<proc_macro2::TokenStream> for Model {
fn from(inner: proc_macro2::TokenStream) -> Model {
fn from(_inner: proc_macro2::TokenStream) -> Model {
let attribute = Default::default();
Model::Attribute(attribute)
}
Expand All @@ -302,7 +301,7 @@ impl std::convert::From<proc_macro2::TokenStream> for Model {
//
//
impl std::convert::From<proc_macro2::TokenStream> for Models<Model> {
fn from(inner: proc_macro2::TokenStream) -> Models<Model> {
fn from(_inner: proc_macro2::TokenStream) -> Models<Model> {
let attribute = Default::default();
let mut models = Models::<Model>::new();
models.push(Model::Attribute(attribute));
Expand All @@ -314,15 +313,15 @@ impl Default for Trace {
fn default() -> Self {
// let scope = proc_macro2::Ident::new("Local", proc_macro2::Span::call_site());
// Some(syn::LitBool::new(false, proc_macro2::Span::call_site()));
let name = syn::LitStr::new("root", proc_macro2::Span::call_site());
let scope = Scope::Local;
let name = Some(syn::LitStr::new("root", proc_macro2::Span::call_site()));
let scope = Some(Scope::Local);
let enter_on_poll = Some(syn::LitBool::new(true, proc_macro2::Span::call_site()));
let recorder = Some(proc_macro2::Ident::new(
"span",
proc_macro2::Span::call_site(),
));
let recurse = None;
let root= Some(syn::LitBool::new(false, proc_macro2::Span::call_site()));
let root = Some(syn::LitBool::new(false, proc_macro2::Span::call_site()));
let variables = None;
let parent = Some(syn::LitStr::new("root", proc_macro2::Span::call_site()));
let async_trait = None;
Expand Down Expand Up @@ -412,8 +411,9 @@ mod tests {
#[test]
fn with_traces() {
let models = analyze(
parse_quote!(#[trace]),
parse_quote!(),
parse_quote!(
#[trace]
fn f(x: bool) {}
),
);
Expand Down Expand Up @@ -454,30 +454,37 @@ mod tests {
}

#[test]
#[should_panic]
fn error_without_trace() {
fn with_no_trace() {
analyze(
parse_quote!(),
parse_quote!(
#[without_trace]
fn f(x: bool) {}
fn f(x: bool) -> bool {
x
}
),
);
}

// There is no filtering/validation in the `analyze` function.
// All such checks are done in `validate` function.
#[test]
fn preserve_non_dsl_attributes() {
fn others_with_traces() {
let models = analyze(
parse_quote!(#[trace]),
parse_quote!(#[trace()]),
parse_quote!(
#[a]
#[trace]
#[b]
fn f(x: bool) {}
fn f(x: bool) -> bool {
x
}
),
);

let expected: &[Attribute] = &[parse_quote!(#[a]), parse_quote!(#[b])];
let expected: &[Attribute] = &[
parse_quote!(#[a]),
parse_quote!(#[trace]),
parse_quote!(#[b]),
];
let model = models.get(1).unwrap();
let item = if let Model::Item(item) = model {
item
Expand All @@ -491,4 +498,17 @@ mod tests {
};
assert_eq!(expected, actual.attrs);
}

#[test]
fn others_with_no_trace() {
let models = analyze(
parse_quote!(),
parse_quote!(
#[a]
#[b]
fn f(x: bool) {}
),
);
assert_eq!(models.len(),1);
}
}
9 changes: 5 additions & 4 deletions minitrace-macro/src/trace/generate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use syn::{parse_quote, Stmt};

use crate::trace::lower::Assertion;

pub type Rust = proc_macro2::TokenStream;
//pub type Rust = proc_macro2::TokenStream;

use crate::trace::lower::Quotable;
use crate::trace::lower::Quotables;
Expand All @@ -17,6 +17,7 @@ pub fn generate(quotes: Quotables<Quotable>) -> proc_macro2::TokenStream {
// Have a logic check earlier to error if there is not **at least one**
// `syn::Item`
#[allow(clippy::collapsible_match)]
#[allow(unreachable_patterns)]
let it = match quotes.get(0).expect("An item") {
Quotable::Item(item) => match item {
syn::Item::Fn(itemf) => Some(itemf),
Expand Down Expand Up @@ -59,11 +60,11 @@ mod tests {
fn f(x: bool) {}
),
);
println!("{:?}",models.clone());
println!("{:?}", models.clone());
let ir = crate::trace::lower(models);
println!("{:?}",ir.clone());
println!("{:?}", ir.clone());
let rust = crate::trace::generate(ir);
println!("{:?}",rust.clone());
println!("{:?}", rust.clone());

assert!(syn::parse2::<syn::ItemFn>(rust).is_ok());
}
Expand Down
7 changes: 4 additions & 3 deletions minitrace-macro/src/trace/lower.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#[allow(unused_imports)]
use quote::quote;
use syn::{Expr, ItemFn};
use syn::{Expr};

use crate::trace::analyze::Model;
use crate::trace::analyze::Models;
Expand All @@ -15,7 +15,7 @@ pub fn lower(models: Models<Model>) -> Quotables<Quotable>
//where Model: std::fmt::Display + std::fmt::Debug + From<Model>,
{
let quotes = Quotables::new();
if let Some(Model::Attribute(attribute)) = models.get(0) {};
if let Some(Model::Attribute(_attribute)) = models.get(0) {};

// let assertions = preconditions
// .into_iter()
Expand Down Expand Up @@ -50,6 +50,7 @@ impl<T: std::fmt::Debug> Quotables<T> {
Quotables(Vec::<T>::new())
}

#[allow(dead_code)]
pub fn with_capacity(capacity: usize) -> Quotables<T> {
Quotables(Vec::<T>::with_capacity(capacity))
}
Expand Down Expand Up @@ -84,7 +85,7 @@ impl<T: std::fmt::Debug> std::ops::DerefMut for Quotables<T> {
// struct Quote2 {
// item: syn::Item,
// }

#[allow(dead_code)]
#[derive(Clone, Debug, thiserror::Error)]
#[error("Validation logic error")]
pub enum Quotable {
Expand Down
Loading

0 comments on commit c6cbd1d

Please sign in to comment.