stylo_derive/
compute_squared_distance.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use crate::animate::{AnimationFieldAttrs, AnimationInputAttrs, AnimationVariantAttrs};
6use crate::cg;
7use proc_macro2::TokenStream;
8use quote::TokenStreamExt;
9use syn::{DeriveInput, WhereClause};
10use synstructure;
11
12pub fn derive(mut input: DeriveInput) -> TokenStream {
13    let animation_input_attrs = cg::parse_input_attrs::<AnimationInputAttrs>(&input);
14    let no_bound = animation_input_attrs.no_bound.unwrap_or_default();
15    let mut where_clause = input.generics.where_clause.take();
16    for param in input.generics.type_params() {
17        if !no_bound.iter().any(|name| name.is_ident(&param.ident)) {
18            cg::add_predicate(
19                &mut where_clause,
20                parse_quote!(#param: crate::values::distance::ComputeSquaredDistance),
21            );
22        }
23    }
24
25    let (mut match_body, needs_catchall_branch) = {
26        let s = synstructure::Structure::new(&input);
27        let needs_catchall_branch = s.variants().len() > 1;
28
29        let match_body = s.variants().iter().fold(quote!(), |body, variant| {
30            let arm = derive_variant_arm(variant, &mut where_clause);
31            quote! { #body #arm }
32        });
33
34        (match_body, needs_catchall_branch)
35    };
36
37    input.generics.where_clause = where_clause;
38
39    if needs_catchall_branch {
40        // This ideally shouldn't be needed, but see:
41        // https://github.com/rust-lang/rust/issues/68867
42        match_body.append_all(quote! { _ => unsafe { debug_unreachable!() } });
43    }
44
45    let name = &input.ident;
46    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
47
48    quote! {
49        impl #impl_generics crate::values::distance::ComputeSquaredDistance for #name #ty_generics #where_clause {
50            #[allow(unused_variables, unused_imports)]
51            #[inline]
52            fn compute_squared_distance(
53                &self,
54                other: &Self,
55            ) -> Result<crate::values::distance::SquaredDistance, ()> {
56                if std::mem::discriminant(self) != std::mem::discriminant(other) {
57                    return Err(());
58                }
59                match (self, other) {
60                    #match_body
61                }
62            }
63        }
64    }
65}
66
67fn derive_variant_arm(
68    variant: &synstructure::VariantInfo,
69    mut where_clause: &mut Option<WhereClause>,
70) -> TokenStream {
71    let variant_attrs = cg::parse_variant_attrs_from_ast::<AnimationVariantAttrs>(&variant.ast());
72    let (this_pattern, this_info) = cg::ref_pattern(&variant, "this");
73    let (other_pattern, other_info) = cg::ref_pattern(&variant, "other");
74
75    if variant_attrs.error {
76        return quote! {
77            (&#this_pattern, &#other_pattern) => Err(()),
78        };
79    }
80
81    let sum = if this_info.is_empty() {
82        quote! { crate::values::distance::SquaredDistance::from_sqrt(0.) }
83    } else {
84        let mut sum = quote!();
85        sum.append_separated(this_info.iter().zip(&other_info).map(|(this, other)| {
86            let field_attrs = cg::parse_field_attrs::<DistanceFieldAttrs>(&this.ast());
87            if field_attrs.field_bound {
88                let ty = &this.ast().ty;
89                cg::add_predicate(
90                    &mut where_clause,
91                    parse_quote!(#ty: crate::values::distance::ComputeSquaredDistance),
92                );
93            }
94
95            let animation_field_attrs =
96                cg::parse_field_attrs::<AnimationFieldAttrs>(&this.ast());
97
98            if animation_field_attrs.constant {
99                quote! {
100                    {
101                        if #this != #other {
102                            return Err(());
103                        }
104                        crate::values::distance::SquaredDistance::from_sqrt(0.)
105                    }
106                }
107            } else {
108                quote! {
109                    crate::values::distance::ComputeSquaredDistance::compute_squared_distance(#this, #other)?
110                }
111            }
112        }), quote!(+));
113        sum
114    };
115
116    return quote! {
117        (&#this_pattern, &#other_pattern) => Ok(#sum),
118    };
119}
120
121#[derive(Default, FromField)]
122#[darling(attributes(distance), default)]
123struct DistanceFieldAttrs {
124    field_bound: bool,
125}