Skip to main content

chunk

Macro chunk 

Source
chunk!() { /* proc-macro */ }
Expand description

append to TokenStream code generating the input tokens.

syntax: chunk!(stream: ident, ...).

all not interpolated tokens inherit the Span::call_site span.

supported syntax:

  • #ident: append the resolved value of ident through ToTokens.
  • #{expr}: append the resolved value of expr through ToTokens.
  • ##: append a #.
  • #op expr #{tokens}: append tokens based on the evaluation of op expr. op can be if, for, while, else, match.
  • #do {expr}: execute expr at its difinition point in the strucutre.
  • other tokens gets appended.

ยงexample

let fields = &[
    (Ident::new("a", Span::call_site()), Ident::new("u32", Span::call_site())),
	(Ident::new("b", Span::call_site()), Ident::new("bool", Span::call_site())),
	(Ident::new("c", Span::call_site()), Ident::new("char", Span::call_site())),
	];
let mut stream = TokenStream::new();
let public = true;
chunk!(stream,
	#if public #{ pub }
	struct Example {
        #for (field, ty) in fields #{ #field: #ty, }
	}
	impl Example {
        #do { gen_accessors(stream, fields) }
	}
);
fn gen_accessors(mut stream: &mut TokenStream, fields: &[(Ident, Ident)]) {
    chunk!(stream, #for (field, ty) in fields #{
        fn #{format_ident!("get_{field}")} (&self) -> #ty {
            self.#field
		}
	});
}