1use proc_macro::TokenStream;
5use proc_macro2::TokenStream as TokenStream2;
6use quote::quote;
7use syn::{Data, DataStruct, DeriveInput, Expr, Field, Fields, Ident, Type, parse_macro_input};
8
9#[proc_macro_derive(Animatable, attributes(animate))]
17pub fn derive_animatable(input: TokenStream) -> TokenStream {
18 let input = parse_macro_input!(input as DeriveInput);
19 expand(&input)
20 .unwrap_or_else(syn::Error::into_compile_error)
21 .into()
22}
23
24fn expand(input: &DeriveInput) -> syn::Result<TokenStream2> {
25 let name = &input.ident;
26 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
27
28 let fields = match &input.data {
29 Data::Struct(DataStruct {
30 fields: Fields::Named(named),
31 ..
32 }) => &named.named,
33 _ => {
34 return Err(syn::Error::new_spanned(
35 input,
36 "Animatable can only be derived on structs with named fields",
37 ));
38 }
39 };
40
41 let settle_eps = container_settle_eps(input)?;
42
43 let mut animation: Vec<(&Ident, &Type)> = Vec::new();
44 let mut snap: Vec<(&Ident, &Type)> = Vec::new();
45 for f in fields {
46 let ident = f.ident.as_ref().expect("named fields have idents");
47 match FieldKind::of(f)? {
48 FieldKind::Snap => snap.push((ident, &f.ty)),
49 FieldKind::Animated => animation.push((ident, &f.ty)),
50 }
51 }
52
53 let lerp_animation = animation.iter().map(|(f, _)| {
54 quote! { #f: ::palantir::widget::Animatable::lerp(a.#f, b.#f, t), }
55 });
56 let lerp_snap = snap.iter().map(|(f, _)| {
57 quote! { #f: b.#f, }
58 });
59 let keep_snap: Vec<TokenStream2> = snap.iter().map(|(f, _)| quote! { #f: self.#f, }).collect();
60
61 let sub_animation = animation.iter().map(|(f, _)| {
62 quote! { #f: ::palantir::widget::Animatable::sub(self.#f, other.#f), }
63 });
64
65 let add_animation = animation.iter().map(|(f, _)| {
66 quote! { #f: ::palantir::widget::Animatable::add(self.#f, other.#f), }
67 });
68
69 let scale_animation = animation.iter().map(|(f, _)| {
70 quote! { #f: ::palantir::widget::Animatable::scale(self.#f, k), }
71 });
72
73 let magnitude_squared_body = sum_or_zero(
74 animation
75 .iter()
76 .map(|(f, _)| quote! { ::palantir::widget::Animatable::magnitude_squared(self.#f) }),
77 );
78
79 let settle_distance_squared_body = if let Some(eps) = &settle_eps {
80 quote! {
81 let eps: f32 = #eps;
82 ::palantir::widget::Animatable::magnitude_squared(self) / (eps * eps)
83 }
84 } else {
85 sum_or_zero(animation.iter().map(|(f, _)| {
86 quote! { ::palantir::widget::Animatable::settle_distance_squared(self.#f) }
87 }))
88 };
89
90 let zero_animation = animation.iter().map(|(f, ty)| {
91 quote! { #f: <#ty as ::palantir::widget::Animatable>::zero(), }
92 });
93 let zero_snap = snap.iter().map(|(f, ty)| {
94 quote! { #f: <#ty as ::core::default::Default>::default(), }
95 });
96 let normalize_for_spring_animation = animation.iter().map(|(f, ty)| {
97 quote! {
98 <#ty as ::palantir::widget::Animatable>::normalize_for_spring(
99 &mut self.#f,
100 &target.#f,
101 &mut velocity.#f,
102 );
103 }
104 });
105
106 let expanded = quote! {
108 impl #impl_generics ::palantir::widget::Animatable for #name #ty_generics #where_clause {
109 #[inline]
110 fn lerp(a: Self, b: Self, t: f32) -> Self {
111 Self {
112 #(#lerp_animation)*
113 #(#lerp_snap)*
114 }
115 }
116 #[inline]
117 fn sub(self, other: Self) -> Self {
118 Self {
119 #(#sub_animation)*
120 #(#keep_snap)*
121 }
122 }
123 #[inline]
124 fn add(self, other: Self) -> Self {
125 Self {
126 #(#add_animation)*
127 #(#keep_snap)*
128 }
129 }
130 #[inline]
131 fn scale(self, k: f32) -> Self {
132 Self {
133 #(#scale_animation)*
134 #(#keep_snap)*
135 }
136 }
137 #[inline]
138 fn magnitude_squared(self) -> f32 {
139 #magnitude_squared_body
140 }
141 #[inline]
142 fn settle_distance_squared(self) -> f32 {
143 #settle_distance_squared_body
144 }
145 #[inline]
146 fn zero() -> Self {
147 Self {
148 #(#zero_animation)*
149 #(#zero_snap)*
150 }
151 }
152 #[inline]
153 fn normalize_for_spring(&mut self, target: &Self, velocity: &mut Self) {
154 let _ = (&*self, target, &*velocity);
155 #(#normalize_for_spring_animation)*
156 }
157 }
158 };
159
160 Ok(expanded)
161}
162
163fn sum_or_zero(terms: impl IntoIterator<Item = TokenStream2>) -> TokenStream2 {
165 let terms: Vec<TokenStream2> = terms.into_iter().collect();
166 if terms.is_empty() {
167 quote! { 0.0_f32 }
168 } else {
169 quote! { #(#terms)+* }
170 }
171}
172
173fn container_settle_eps(input: &DeriveInput) -> syn::Result<Option<Expr>> {
175 let mut eps = None;
176 for attr in &input.attrs {
177 if !attr.path().is_ident("animate") {
178 continue;
179 }
180 attr.parse_nested_meta(|meta| {
181 if meta.path.is_ident("settle_eps") {
182 if eps.is_some() {
183 return Err(meta.error("`settle_eps` given twice"));
184 }
185 eps = Some(meta.value()?.parse::<Expr>()?);
186 Ok(())
187 } else {
188 Err(meta.error("unknown #[animate(...)] option on a struct; expected `settle_eps`"))
189 }
190 })?;
191 }
192 Ok(eps)
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
197enum FieldKind {
198 Animated,
200 Snap,
202}
203
204impl FieldKind {
205 fn of(f: &Field) -> syn::Result<Self> {
207 let mut kind = Self::Animated;
208 for attr in &f.attrs {
209 if !attr.path().is_ident("animate") {
210 continue;
211 }
212 attr.parse_nested_meta(|meta| {
213 if meta.path.is_ident("snap") || meta.path.is_ident("skip") {
214 kind = Self::Snap;
215 Ok(())
216 } else {
217 Err(meta.error("unknown #[animate(...)] option; expected `snap` or `skip`"))
218 }
219 })?;
220 }
221 Ok(kind)
222 }
223}
224
225#[cfg(test)]
226mod tests {
227 use crate::expand;
228 use syn::{DeriveInput, parse_quote};
229
230 #[test]
232 fn refused_inputs_name_the_reason() {
233 let shape = "Animatable can only be derived on structs with named fields";
234 let option = "unknown #[animate(...)] option; expected `snap` or `skip`";
235 let container = "unknown #[animate(...)] option on a struct; expected `settle_eps`";
236 let cases: [(&str, DeriveInput, &str); 6] = [
237 ("enum", parse_quote! { enum E { A } }, shape),
238 ("tuple struct", parse_quote! { struct T(f32); }, shape),
239 ("unit struct", parse_quote! { struct U; }, shape),
240 (
241 "typo",
242 parse_quote! { struct S { #[animate(snip)] a: f32 } },
243 option,
244 ),
245 (
246 "field option on the struct",
247 parse_quote! { #[animate(snap)] struct S { a: f32 } },
248 container,
249 ),
250 (
251 "two tolerances",
252 parse_quote! { #[animate(settle_eps = 0.5, settle_eps = 0.25)] struct S { a: f32 } },
253 "`settle_eps` given twice",
254 ),
255 ];
256 for (label, input, message) in cases {
257 let error = expand(&input).expect_err(label);
258 assert_eq!(error.to_string(), message, "{label}");
259 }
260 }
261}