Skip to main content

typst_template_derive/
lib.rs

1//! Derive macro for the `ToDict` trait from the [`typst-template`] crate.
2//!
3//! This crate is an implementation detail of `typst-template`; depend on that
4//! crate (with its default `derive` feature) instead of using this one
5//! directly.
6//!
7//! [`typst-template`]: https://docs.rs/typst-template
8
9#![forbid(unsafe_code)]
10
11use darling::ast::Data;
12use darling::util::Ignored;
13use darling::{FromDeriveInput, FromField, FromMeta};
14use proc_macro::TokenStream;
15use quote::quote;
16use syn::{DeriveInput, Generics, Ident, Path, Type, parse_macro_input, parse_quote};
17
18/// Derives [`ToDict`] (and, through it, [`ToValue`]) for a named struct.
19///
20/// Each field is converted to a Typst value via [`ToValue`] and inserted under
21/// its name. The generated `into_value` wraps the resulting dict in
22/// `Value::Dict`, so derived types nest inside one another.
23///
24/// # Attributes
25///
26/// Container level (`#[typst(...)]` on the struct):
27/// - `rename_all = "..."` — rename every field with one of the rules `lowercase`, `UPPERCASE`,
28///   `PascalCase`, `camelCase`, `snake_case`, `SCREAMING_SNAKE_CASE`, `kebab-case`,
29///   `SCREAMING-KEBAB-CASE`.
30///
31/// Field level (`#[typst(...)]` on a field):
32/// - `rename = "name"` — use a fixed key, overriding `rename_all`.
33/// - `skip` — leave the field out of the dict.
34/// - `with = "path::to::fn"` — call that function (named as a string, like serde) as `fn(field) ->
35///   Value` to produce the value instead of using the field's [`ToValue`] impl. Useful for types
36///   that do not implement the trait or that need a custom representation.
37/// - `flatten` — merge the field's own dict into this one instead of nesting it under a key. The
38///   field type must implement [`ToDict`]; `rename`/`with` are ignored for it.
39///
40/// [`ToDict`]: https://docs.rs/typst-template/latest/typst_template/trait.ToDict.html
41/// [`ToValue`]: https://docs.rs/typst-template/latest/typst_template/trait.ToValue.html
42#[proc_macro_derive(ToDict, attributes(typst))]
43pub fn derive_into_dict(input: TokenStream) -> TokenStream {
44    let parsed = parse_macro_input!(input as DeriveInput);
45    match ToDictInput::from_derive_input(&parsed) {
46        Ok(receiver) => receiver.expand().into(),
47        Err(err) => err.write_errors().into(),
48    }
49}
50
51#[derive(FromDeriveInput)]
52#[darling(attributes(typst), supports(struct_named))]
53struct ToDictInput {
54    ident: Ident,
55    generics: Generics,
56    data: Data<Ignored, ToDictField>,
57    #[darling(default)]
58    rename_all: Option<RenameRule>,
59}
60
61#[derive(FromField)]
62#[darling(attributes(typst))]
63struct ToDictField {
64    ident: Option<Ident>,
65    ty: Type,
66    #[darling(default)]
67    rename: Option<String>,
68    #[darling(default)]
69    skip: bool,
70    #[darling(default)]
71    with: Option<Path>,
72    #[darling(default)]
73    flatten: bool,
74}
75
76impl ToDictInput {
77    fn expand(&self) -> proc_macro2::TokenStream {
78        let ident = &self.ident;
79        let data = self
80            .data
81            .as_ref()
82            .take_struct()
83            .expect("supports(struct_named)");
84        let fields: Vec<&ToDictField> = data.fields.into_iter().filter(|f| !f.skip).collect();
85
86        // One statement per kept field: a flattened field merges its dict,
87        // others insert under their key.
88        let inserts = fields.iter().map(|f| {
89            let field = f.ident.as_ref().expect("named struct field");
90            if f.flatten {
91                return quote! {
92                    ::typst_template::__private::merge_dict(
93                        &mut __dict,
94                        ::typst_template::ToDict::into_dict(self.#field),
95                    );
96                };
97            }
98            let key = self.key_for(f, field);
99            let value = match &f.with {
100                Some(path) => quote!(#path(self.#field)),
101                None => quote!(::typst_template::ToValue::into_value(self.#field)),
102            };
103            quote!(__dict.insert(::typst_template::Str::from(#key), #value);)
104        });
105
106        // Bound each field type: `ToDict` when flattened, `ToValue` when
107        // converted through the trait (a `with` field needs neither).
108        let mut generics = self.generics.clone();
109        let where_clause = generics.make_where_clause();
110        for f in &fields {
111            let ty = &f.ty;
112            if f.flatten {
113                where_clause
114                    .predicates
115                    .push(parse_quote!(#ty: ::typst_template::ToDict));
116            } else if f.with.is_none() {
117                where_clause
118                    .predicates
119                    .push(parse_quote!(#ty: ::typst_template::ToValue));
120            }
121        }
122        let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
123
124        quote! {
125            impl #impl_generics ::typst_template::ToDict for #ident #ty_generics #where_clause {
126                fn into_dict(self) -> ::typst_template::Dict {
127                    let mut __dict = ::typst_template::Dict::new();
128                    #(#inserts)*
129                    __dict
130                }
131            }
132
133            impl #impl_generics ::typst_template::ToValue for #ident #ty_generics #where_clause {
134                fn into_value(self) -> ::typst_template::Value {
135                    ::typst_template::Value::Dict(::typst_template::ToDict::into_dict(self))
136                }
137            }
138        }
139    }
140
141    /// The dict key for a field: explicit `rename`, else `rename_all`, else the
142    /// raw field name.
143    fn key_for(&self, field: &ToDictField, ident: &Ident) -> String {
144        if let Some(name) = &field.rename {
145            return name.clone();
146        }
147        let raw = ident.to_string();
148        let name = raw.strip_prefix("r#").unwrap_or(&raw);
149        match self.rename_all {
150            Some(rule) => rule.apply(name),
151            None => name.to_owned(),
152        }
153    }
154}
155
156/// Field-renaming rules, mirroring serde's `rename_all`.
157#[derive(Clone, Copy)]
158enum RenameRule {
159    Lower,
160    Upper,
161    Pascal,
162    Camel,
163    Snake,
164    ScreamingSnake,
165    Kebab,
166    ScreamingKebab,
167}
168
169impl FromMeta for RenameRule {
170    fn from_string(value: &str) -> darling::Result<Self> {
171        Ok(match value {
172            "lowercase" => Self::Lower,
173            "UPPERCASE" => Self::Upper,
174            "PascalCase" => Self::Pascal,
175            "camelCase" => Self::Camel,
176            "snake_case" => Self::Snake,
177            "SCREAMING_SNAKE_CASE" => Self::ScreamingSnake,
178            "kebab-case" => Self::Kebab,
179            "SCREAMING-KEBAB-CASE" => Self::ScreamingKebab,
180            other => return Err(darling::Error::unknown_value(other)),
181        })
182    }
183}
184
185impl RenameRule {
186    /// Rewrites a `snake_case` field name into the target style.
187    fn apply(self, field: &str) -> String {
188        let words: Vec<&str> = field.split('_').filter(|w| !w.is_empty()).collect();
189        match self {
190            Self::Snake => field.to_owned(),
191            Self::Lower => words.concat(),
192            Self::Upper => words.concat().to_uppercase(),
193            Self::ScreamingSnake => join(&words, "_", str::to_uppercase),
194            Self::Kebab => words.join("-"),
195            Self::ScreamingKebab => join(&words, "-", str::to_uppercase),
196            Self::Pascal => words.iter().map(|w| capitalize(w)).collect(),
197            Self::Camel => {
198                let mut out = String::new();
199                for (i, word) in words.iter().enumerate() {
200                    if i == 0 {
201                        out.push_str(word);
202                    } else {
203                        out.push_str(&capitalize(word));
204                    }
205                }
206                out
207            }
208        }
209    }
210}
211
212fn join(words: &[&str], sep: &str, map: fn(&str) -> String) -> String {
213    words.iter().map(|w| map(w)).collect::<Vec<_>>().join(sep)
214}
215
216fn capitalize(word: &str) -> String {
217    let mut chars = word.chars();
218    match chars.next() {
219        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
220        None => String::new(),
221    }
222}