Trait wagon_codegen::ToTokensState
source · pub trait ToTokensState<U> {
// Required method
fn to_tokens(
&self,
state: &mut U,
label: Rc<Ident>,
attr_fun: fn(_: &mut U, _: Rc<Ident>, _: SpannableIdent)
) -> TokenStream;
}
Expand description
A trait for anything that does codegen while having to keep track of some state object U
.
Required Methods§
sourcefn to_tokens(
&self,
state: &mut U,
label: Rc<Ident>,
attr_fun: fn(_: &mut U, _: Rc<Ident>, _: SpannableIdent)
) -> TokenStream
fn to_tokens( &self, state: &mut U, label: Rc<Ident>, attr_fun: fn(_: &mut U, _: Rc<Ident>, _: SpannableIdent) ) -> TokenStream
A method to do codegen based on state and possibly modify that state.
This method takes a given mutable state U
, as well as a reference to some proc_macro2::Ident
and a function to modify the state.
It then potentially calls this function to modify the state and returns a TokenStream
for the generated code.
§Example
struct A;
struct State { toggle: bool }
impl State {
fn new() -> Self {
Self { toggle: false }
}
fn toggle(&mut self, _: Rc<proc_macro2::Ident>, _: SpannableIdent) {
self.toggle = true;
}
}
impl ToTokensState<State> for A {
fn to_tokens(&self, state: &mut State, label: Rc<proc_macro2::Ident>, attr_fun: fn(&mut State, Rc<proc_macro2::Ident>, SpannableIdent)) -> TokenStream {
attr_fun(state, label, SpannableNode::from(wagon_ident::Ident::default()));
TokenStream::new()
}
}
let a = A;
let mut state = State { toggle: false };
let label = Rc::new(proc_macro2::Ident::new("label", proc_macro2::Span::call_site()));
a.to_tokens(&mut state, label, State::toggle);
assert!(state.toggle) // this is now true
For practical examples. Look at the implementations in this crate as well as how they are called in the [wagon-codegen-gll
] crate.