alga2-derive 0.1.0

Derive macro for alga2: one line brings a struct into the whole algebraic tower
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! `#[derive(Alga)]` — one line brings a struct into the alga2 tower.
//!
//! Generates the algebraic chain as component-wise forwarders. The target
//! level is controlled by `#[alga(level = "...")]` (default `"Ring"`; the
//! field types must reach it — Rust rejects a level the fields cannot
//! satisfy, which is exactly the check you want):
//!
//! - `"Monoid"` — additive Magma → Monoid, multiplicative Magma → Monoid
//! - `"Group"` — + additive Group/AbelianGroup (and Quasigroup/Loop on the
//!   additive side; the multiplicative ladder stops at Monoid)
//! - `"Ring"` (default) — + Semiring → CommutativeRing, plus Module/VectorSpace
//! - `"Field"` — + DivisionRing → Field (field-typed fields only)
//!
//! Requirements and bounds:
//!
//! - Structs only (named, tuple, or generic — including where-clause
//!   constraints); enums, unions, unit and empty structs are rejected with
//!   a clear error.
//! - Every field must reach the target level; mixed field types need a
//!   common `Module::Scalar` (the first field's scalar is used).
//! - No tower imports are needed at the call site: the generated method
//!   bodies resolve through the impls they live in.
//!
//! ```
//! use alga2::op::Additive;
//! use alga2::tower::Magma;
//! use alga2_derive::Alga;
//!
//! #[derive(Alga)]
//! #[alga(level = "Field")]
//! struct Vec2 { x: f64, y: f64 }
//!
//! let a = Vec2 { x: 1.0, y: 2.0 };
//! let b = Vec2 { x: 3.0, y: 4.0 };
//! assert_eq!(<Vec2 as Magma<Additive>>::combine(&a, &b).x, 4.0);
//! ```

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TS;
use quote::{quote, ToTokens};
use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident, Index, Type};

/// Generates the tower impls for a struct.
#[proc_macro_derive(Alga, attributes(alga))]
pub fn derive_alga(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match expand(&input) {
        Ok(ts) => ts.into(),
        Err(e) => e.into_compile_error().into(),
    }
}

/// The target level parsed from `#[alga(level = "...")]`.
#[derive(PartialEq, Clone, Copy)]
enum Level {
    Monoid,
    Group,
    Ring,
    Field,
}

impl Level {
    fn parse(input: &DeriveInput) -> syn::Result<Self> {
        let mut level = Level::Ring;
        for attr in &input.attrs {
            if attr.path().is_ident("alga") {
                attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("level") {
                        let value = meta.value()?;
                        let s: syn::LitStr = value.parse()?;
                        level = match s.value().as_str() {
                            "Monoid" => Level::Monoid,
                            "Group" => Level::Group,
                            "Ring" => Level::Ring,
                            "Field" => Level::Field,
                            other => {
                                return Err(meta.error(format!(
                                    "unknown alga level `{other}` (expected Monoid, Group, Ring or Field)"
                                )))
                            }
                        };
                        Ok(())
                    } else {
                        Err(meta.error("unknown `#[alga(...)]` option (only `level` is supported)"))
                    }
                })?;
            }
        }
        Ok(level)
    }
}

/// A struct field: its type, and how to name it in `self.x` / `self.0`.
struct FieldInfo {
    ty: Type,
    suffix: TS,
    name: Option<Ident>,
}

fn expand(input: &DeriveInput) -> syn::Result<TS> {
    let name = &input.ident;
    let generics = &input.generics;
    let (impl_g, ty_g, where_g) = generics.split_for_impl();

    let fields = match &input.data {
        Data::Struct(s) => fields_of(&s.fields)?,
        Data::Enum(_) | Data::Union(_) => {
            return Err(syn::Error::new_spanned(input, "#[derive(Alga)] supports structs only"))
        }
    };

    let level = Level::parse(input)?;
    let g = Gen { name, impl_g: &impl_g, ty_g: &ty_g, where_g };
    let mut out = TS::new();
    // The additive ladder runs to `max_level`; the multiplicative ladder
    // stops at Monoid (numerics have no multiplicative inverses in general —
    // the ring/field levels are the two-operator chain below).
    let add_max = if level == Level::Monoid { "Monoid" } else { "Group" };
    out.extend(g.single_op_chain(&fields, "Additive", add_max));
    out.extend(g.single_op_chain(&fields, "Multiplicative", "Monoid"));
    if matches!(level, Level::Ring | Level::Field) {
        out.extend(g.two_op_chain(&fields, level));
        out.extend(g.module_level(&fields));
    }
    Ok(out)
}

fn fields_of(fields: &Fields) -> syn::Result<Vec<FieldInfo>> {
    let mut out = vec![];
    match fields {
        Fields::Named(n) => {
            for f in &n.named {
                let id = f.ident.clone().unwrap();
                out.push(FieldInfo { ty: f.ty.clone(), suffix: id.to_token_stream(), name: Some(id) });
            }
        }
        Fields::Unnamed(u) => {
            for (i, f) in u.unnamed.iter().enumerate() {
                let idx = Index::from(i);
                out.push(FieldInfo { ty: f.ty.clone(), suffix: idx.to_token_stream(), name: None });
            }
        }
        Fields::Unit => {
            return Err(syn::Error::new_spanned(fields, "#[derive(Alga)] needs at least one field"))
        }
    }
    if out.is_empty() {
        return Err(syn::Error::new_spanned(fields, "#[derive(Alga)] needs at least one field"));
    }
    Ok(out)
}

/// `self.<suffix>` — the receiver-side field access.
fn self_access(f: &FieldInfo) -> TS {
    let s = &f.suffix;
    quote!(self.#s)
}

/// `rhs.<suffix>` — the other-side field access.
fn rhs_access(f: &FieldInfo) -> TS {
    let s = &f.suffix;
    quote!(rhs.#s)
}

/// `Self { x: <e0>, y: <e1> }` for named fields, `Self(<e0>, <e1>)` for tuples.
fn construct(fields: &[FieldInfo], exprs: &[TS]) -> TS {
    match fields.first().map(|f| f.name.is_some()) {
        Some(true) => {
            let pairs = fields.iter().zip(exprs).map(|(f, e)| {
                let n = f.name.as_ref().unwrap();
                quote!(#n: #e)
            });
            quote!(Self { #(#pairs),* })
        }
        _ => quote!(Self( #(#exprs),* )),
    }
}

/// Deduplicated field types (a `where` bound per distinct type), in field
/// order — deterministic expansion output.
fn field_types(fields: &[FieldInfo]) -> Vec<&Type> {
    let mut seen: Vec<String> = vec![];
    fields
        .iter()
        .map(|f| &f.ty)
        .filter(|t| {
            let key = t.to_token_stream().to_string();
            if seen.contains(&key) {
                false
            } else {
                seen.push(key);
                true
            }
        })
        .collect()
}

fn op_path(op: &str) -> TS {
    let op = Ident::new(op, proc_macro2::Span::call_site());
    quote!(::alga2::op::#op)
}

fn trait_path(name: &str) -> TS {
    let name = Ident::new(name, proc_macro2::Span::call_site());
    quote!(::alga2::tower::#name)
}

struct Gen<'a> {
    name: &'a Ident,
    impl_g: &'a syn::ImplGenerics<'a>,
    ty_g: &'a syn::TypeGenerics<'a>,
    where_g: Option<&'a syn::WhereClause>,
}

impl Gen<'_> {
    /// The struct's own where predicates (if any) plus the field bounds,
    /// as one `where` clause — or nothing when there are no predicates.
    fn where_clause(&self, extra: &[TS]) -> TS {
        let mut preds: Vec<syn::WherePredicate> = Vec::new();
        if let Some(w) = self.where_g {
            preds.extend(w.predicates.iter().cloned());
        }
        for e in extra {
            preds.push(syn::parse_quote!(#e));
        }
        if preds.is_empty() {
            quote!()
        } else {
            quote!(where #(#preds),*)
        }
    }

    /// Per-field `T: Trait<Op>` bound list.
    fn bounds(&self, fields: &[FieldInfo], trait_name: &str, op: &str) -> Vec<TS> {
        let tr = trait_path(trait_name);
        let op = op_path(op);
        field_types(fields).iter().map(|ty| quote!(#ty: #tr<#op>)).collect()
    }

    /// Magma → `max_level` for one operator, component-wise.
    fn single_op_chain(&self, fields: &[FieldInfo], op: &str, max_level: &str) -> TS {
        let n = self.name;
        let impl_g = self.impl_g;
        let ty_g = self.ty_g;
        let op_ts = op_path(op);
        let mag = trait_path("Magma");
        let semi = trait_path("Semigroup");
        let quasi = trait_path("Quasigroup");
        let mon = trait_path("Monoid");
        let loop_t = trait_path("Loop");
        let grp = trait_path("Group");
        let abel = trait_path("AbelianGroup");

        let combine_exprs = fields.iter().map(|f| {
            let a = self_access(f);
            let b = rhs_access(f);
            let ty = &f.ty;
            quote!(<#ty as #mag<#op_ts>>::combine(&#a, &#b))
        }).collect::<Vec<_>>();
        let identity_exprs = fields.iter().map(|f| {
            let ty = &f.ty;
            quote!(<#ty as #mon<#op_ts>>::identity())
        }).collect::<Vec<_>>();
        let inverse_exprs = fields.iter().map(|f| {
            let a = self_access(f);
            quote!(#a.inverse())
        }).collect::<Vec<_>>();

        let magma_b = self.bounds(fields, "Magma", op);
        let monoid_b = self.bounds(fields, "Monoid", op);
        let group_b = self.bounds(fields, "Group", op);
        let w_magma = self.where_clause(&magma_b);
        let w_monoid = self.where_clause(&monoid_b);
        let w_group = self.where_clause(&group_b);

        let c_combine = construct(fields, &combine_exprs);
        let c_identity = construct(fields, &identity_exprs);
        let c_inverse = construct(fields, &inverse_exprs);

        // The quasigroup ladder (Quasigroup → Loop) is additive-only in the
        // crate too; the multiplicative side stops at Monoid.
        let quasigroup_ladder = (op == "Additive").then(|| quote! {
            impl #impl_g #quasi<#op_ts> for #n #ty_g
            #w_magma
            {}
            impl #impl_g #loop_t<#op_ts> for #n #ty_g
            #w_monoid
            {}
        });

        // Group/AbelianGroup only when the ladder runs that far.
        let group_ladder = (max_level == "Group").then(|| quote! {
            impl #impl_g #grp<#op_ts> for #n #ty_g
            #w_group
            {
                fn inverse(&self) -> Self { #c_inverse }
            }
            impl #impl_g #abel<#op_ts> for #n #ty_g
            #w_group
            {}
        });

        quote! {
            impl #impl_g #mag<#op_ts> for #n #ty_g
            #w_magma
            {
                fn combine(&self, rhs: &Self) -> Self { #c_combine }
            }
            impl #impl_g #semi<#op_ts> for #n #ty_g
            #w_magma
            {}
            #quasigroup_ladder
            impl #impl_g #mon<#op_ts> for #n #ty_g
            #w_monoid
            {
                fn identity() -> Self { #c_identity }
            }
            #group_ladder
        }
    }

    /// Semiring → Field (or through CommutativeRing for `Ring` level),
    /// component-wise.
    fn two_op_chain(&self, fields: &[FieldInfo], level: Level) -> TS {
        let n = self.name;
        let impl_g = self.impl_g;
        let ty_g = self.ty_g;

        let semiring_b = field_types(fields).iter().map(|ty| {
            quote!(#ty: ::alga2::tower::Semiring<::alga2::op::Additive, ::alga2::op::Multiplicative>)
        }).collect::<Vec<_>>();
        let field_b = field_types(fields).iter().map(|ty| {
            quote!(#ty: ::alga2::tower::Field<::alga2::op::Additive, ::alga2::op::Multiplicative>)
        }).collect::<Vec<_>>();

        // CommutativeRing needs the fields to be commutative rings; at `Ring`
        // level we use the semiring bound (a commutative ring implies it).
        let comm_b = if level == Level::Field {
            &field_b
        } else {
            &semiring_b
        };
        let w_semiring = self.where_clause(&semiring_b);
        let w_comm = self.where_clause(comm_b);
        let w_field = self.where_clause(&field_b);

        let inv_exprs = fields.iter().map(|f| {
            let a = self_access(f);
            quote!(#a.inv())
        }).collect::<Vec<_>>();
        let c_inv = construct(fields, &inv_exprs);

        // DivisionRing/Field only at `Field` level.
        let field_ladder = (level == Level::Field).then(|| quote! {
            impl #impl_g ::alga2::tower::DivisionRing<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_field
            {
                fn inv(&self) -> Self { #c_inv }
            }
            impl #impl_g ::alga2::tower::Field<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_field
            {}
        });

        quote! {
            impl #impl_g ::alga2::tower::Semiring<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_semiring
            {}
            impl #impl_g ::alga2::tower::Ring<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_semiring
            {}
            impl #impl_g ::alga2::tower::CommutativeRing<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_comm
            {}
            #field_ladder
        }
    }

    /// Module / VectorSpace: scalar from the first field, scale component-wise.
    fn module_level(&self, fields: &[FieldInfo]) -> TS {
        let n = self.name;
        let impl_g = self.impl_g;
        let ty_g = self.ty_g;
        let first = fields.first().unwrap();

        let module_b = field_types(fields).iter().map(|ty| {
            quote!(#ty: ::alga2::tower::Module<::alga2::op::Additive, ::alga2::op::Multiplicative>)
        }).collect::<Vec<_>>();
        let w_module = self.where_clause(&module_b);

        let scale_exprs = fields.iter().map(|f| {
            let s_ = &f.suffix;
            let a = quote!(v.#s_);
            quote!(::alga2::tower::Module::<::alga2::op::Additive, ::alga2::op::Multiplicative>::scale(s, #a))
        }).collect::<Vec<_>>();
        let c_scale = construct(fields, &scale_exprs);

        let ft = &first.ty;
        quote! {
            impl #impl_g ::alga2::tower::Module<::alga2::op::Additive, ::alga2::op::Multiplicative> for #n #ty_g
            #w_module
            {
                type Scalar = <#ft as ::alga2::tower::Module<::alga2::op::Additive, ::alga2::op::Multiplicative>>::Scalar;
                fn scale(s: &Self::Scalar, v: Self) -> Self { #c_scale }
            }
        }
    }
}