tengri/proc/src/proc_view.rs
unspeaker 360b404b69
Some checks failed
/ build (push) Has been cancelled
fix(proc): update macros
2025-07-20 04:54:38 +03:00

136 lines
5.2 KiB
Rust

use crate::*;
#[derive(Debug, Clone)]
pub(crate) struct ViewDef(pub(crate) ViewMeta, pub(crate) ViewImpl);
#[derive(Debug, Clone)]
pub(crate) struct ViewMeta { pub(crate) output: Ident }
#[derive(Debug, Clone)]
pub(crate) struct ViewImpl {
block: ItemImpl,
exposed: BTreeMap<String, Ident>,
}
impl Parse for ViewMeta {
fn parse (input: ParseStream) -> Result<Self> {
Ok(Self {
output: input.parse::<Ident>()?,
})
}
}
impl Parse for ViewImpl {
fn parse (input: ParseStream) -> Result<Self> {
let block = input.parse::<ItemImpl>()?;
let mut exposed: BTreeMap<String, Ident> = Default::default();
for item in block.items.iter() {
if let ImplItem::Fn(ImplItemFn { sig: Signature { ident, .. }, .. }) = item {
let key = format!(":{}", AsKebabCase(format!("{}", &ident)));
if exposed.contains_key(&key) {
return Err(input.error(format!("already defined: {ident}")));
}
exposed.insert(key, ident.clone());
}
}
Ok(Self { block, exposed })
}
}
impl ToTokens for ViewDef {
fn to_tokens (&self, out: &mut TokenStream2) {
let Self(_, ViewImpl { block, .. }) = self;
let generated = self.generated();
write_quote_to(out, quote! {
#block
#generated
})
}
}
impl ViewDef {
fn generated (&self) -> impl ToTokens {
let Self(ViewMeta { output }, ViewImpl { block, exposed }) = self;
let self_ty = &block.self_ty;
// Expressions are handled by built-in functions that operate over constants and symbols.
let builtins = builtins_with_boxes_output(quote! { #output })
.map(|(builtin, builtin_ty)|match builtin {
Single(name) => quote! {
if dsl.exp_head()?.key()? == Some(#name) {
return Ok(Some(#builtin_ty::from_dsl_or_else(self, dsl,
||format!("failed to load builtin").into())?.boxed()))
}
},
Prefix(name) => quote! {
if let Some(key) = dsl.exp_head()?.key()? && key.starts_with(#name) {
return Ok(Some(#builtin_ty::from_dsl_or_else(self, dsl,
||format!("failed to load builtin").into())?.boxed()))
}
},
});
// Symbols are handled by user-provided functions that take no parameters but `&self`.
let exposed = exposed.iter().map(|(key, value)|write_quote(quote! {
#key => return Ok(Some(self.#value().boxed())),
}));
quote! {
/// Generated by [tengri_proc].
///
/// Makes [#self_ty] able to construct the [Render]able
/// which might correspond to a given [TokenStream],
/// while taking [#self_ty]'s state into consideration.
impl<'state> ::tengri::dsl::DslInto<'state,
Box<dyn ::tengri::output::Render<#output> + 'state>
> for #self_ty {
fn dsl_into (&'state self, dsl: &impl ::tengri::dsl::Dsl)
-> Perhaps<Box<dyn ::tengri::output::Render<#output> + 'state>>
{
#(#builtins)*
if let Some(sym) = dsl.sym()? {
match sym {
#(#exposed)*
_ => return Err(format!("unknown symbol {sym}").into())
}
}
Ok(None)
}
}
}
}
}
enum Builtin {
Single(TokenStream2),
Prefix(TokenStream2),
}
use Builtin::*;
fn builtins_with (n: TokenStream2, c: TokenStream2) -> impl Iterator<Item=(Builtin, TokenStream2)> {
[
(Single(quote!("when")), quote!(When::< #c >)),
(Single(quote!("either")), quote!(Either::< #c, #c>)),
(Prefix(quote!("align/")), quote!(Align::< #c >)),
(Prefix(quote!("bsp/")), quote!(Bsp::< #c, #c>)),
(Prefix(quote!("fill/")), quote!(Fill::< #c >)),
(Prefix(quote!("fixed/")), quote!(Fixed::<#n, #c >)),
(Prefix(quote!("min/")), quote!(Min::<#n, #c >)),
(Prefix(quote!("max/")), quote!(Max::<#n, #c >)),
(Prefix(quote!("shrink/")), quote!(Shrink::<#n, #c >)),
(Prefix(quote!("expand/")), quote!(Expand::<#n, #c >)),
(Prefix(quote!("push/")), quote!(Push::<#n, #c >)),
(Prefix(quote!("pull/")), quote!(Pull::<#n, #c >)),
(Prefix(quote!("margin/")), quote!(Margin::<#n, #c >)),
(Prefix(quote!("padding/")), quote!(Padding::<#n, #c >)),
].into_iter()
}
fn _builtins_with_holes () -> impl Iterator<Item=(Builtin, TokenStream2)> {
builtins_with(quote! { _ }, quote! { _ })
}
fn _builtins_with_boxes () -> impl Iterator<Item=(Builtin, TokenStream2)> {
builtins_with(quote! { _ }, quote! { Box<dyn Render<_>> })
}
fn builtins_with_boxes_output (o: TokenStream2) -> impl Iterator<Item=(Builtin, TokenStream2)> {
builtins_with(quote! { _ }, quote! { Box<dyn Render<#o>> })
}