explainable-macros 0.1.1

Procedural macros for the explainable crate.
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
//! Procedural macro support for the `explainable` crate.
//!
//! This crate is an implementation detail. Use the re-exported
//! `explainable::explainable` attribute macro rather than depending on this
//! crate directly.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
    FnArg, GenericArgument, ItemTrait, Pat, PathArguments, ReturnType, TraitItem, Type,
    TypeParamBound, WherePredicate, parse_macro_input,
};

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Returns `true` when `ty` looks like a `Result`-style type.
fn looks_like_result(ty: &Type) -> bool {
    match ty {
        Type::Path(tp) => tp
            .path
            .segments
            .last()
            .map(|s| {
                let name = s.ident.to_string();
                name == "Result" || name.ends_with("Result")
            })
            .unwrap_or(false),
        _ => false,
    }
}

/// Returns `true` when `ty` is a Result-style type whose first generic arg is `()`.
fn result_ok_is_unit(ty: &Type) -> bool {
    let Type::Path(tp) = ty else { return false };
    let Some(seg) = tp.path.segments.last() else {
        return false;
    };
    let PathArguments::AngleBracketed(args) = &seg.arguments else {
        return false;
    };
    let Some(GenericArgument::Type(first_ty)) = args.args.first() else {
        return false;
    };
    matches!(first_ty, Type::Tuple(t) if t.elems.is_empty())
}

/// Returns `true` when `ty` is a Result-style type whose first generic arg is `Self`.
fn result_ok_is_self(ty: &Type) -> bool {
    let Type::Path(tp) = ty else { return false };
    let Some(seg) = tp.path.segments.last() else {
        return false;
    };
    let PathArguments::AngleBracketed(args) = &seg.arguments else {
        return false;
    };
    let Some(GenericArgument::Type(ok_ty)) = args.args.first() else {
        return false;
    };
    match ok_ty {
        Type::Path(p) => p.path.is_ident("Self"),
        _ => false,
    }
}

/// Returns `true` when the return type is chainable — i.e. the method can be
/// included in the `FooExt` / blanket-impl chain.
///
/// A method is chainable when its return is one of:
/// - `Self` — assign directly
/// - `Result<Self, _>` / `FooResult<Self>` — unwrap and assign
/// - `()` or `Result<(), _>` — call for side-effect, no assignment
///
/// Methods returning a *concrete* type (e.g. `AudioSamples<'static, Self::Sample>`)
/// that is *not* `Self` cannot be assigned back to `self.inner: T` in the generic
/// blanket impl and are excluded from the chain.
fn is_chainable_return(ret: &ReturnType) -> bool {
    match ret {
        // `fn foo() { ... }` — void, chainable
        ReturnType::Default => true,
        ReturnType::Type(_, ty) => {
            // Direct `Self`
            if matches!(ty.as_ref(), Type::Path(p) if p.path.is_ident("Self")) {
                return true;
            }
            // `()` tuple type
            if matches!(ty.as_ref(), Type::Tuple(t) if t.elems.is_empty()) {
                return true;
            }
            if looks_like_result(ty) {
                // Result<(), _> or Result<Self, _> — both chainable
                return result_ok_is_unit(ty) || result_ok_is_self(ty);
            }
            false
        }
    }
}

/// Returns `true` when the `FnArg` is a consuming `self` receiver.
fn is_consuming_receiver(arg: &FnArg) -> bool {
    matches!(arg, FnArg::Receiver(r) if r.reference.is_none())
}

/// Walk `ty` recursively and collect every `Self::X` associated-type reference,
/// appending unique `X` idents to `found`.
fn collect_self_assoc_in_type(ty: &Type, found: &mut Vec<syn::Ident>) {
    match ty {
        Type::Path(tp) if tp.qself.is_none() => {
            let segs: Vec<_> = tp.path.segments.iter().collect();
            // Detect bare `Self::X` paths (two segments, first is "Self").
            if segs.len() == 2 && segs[0].ident == "Self" {
                let name = segs[1].ident.clone();
                if !found.iter().any(|i: &syn::Ident| *i == name) {
                    found.push(name);
                }
            }
            // Recurse into every set of angle-bracketed generic arguments.
            for seg in &tp.path.segments {
                if let PathArguments::AngleBracketed(args) = &seg.arguments {
                    for ga in &args.args {
                        if let GenericArgument::Type(inner) = ga {
                            collect_self_assoc_in_type(inner, found);
                        }
                    }
                }
            }
        }
        Type::Reference(r) => collect_self_assoc_in_type(&r.elem, found),
        Type::Slice(s) => collect_self_assoc_in_type(&s.elem, found),
        Type::Array(a) => collect_self_assoc_in_type(&a.elem, found),
        Type::Tuple(t) => t
            .elems
            .iter()
            .for_each(|e| collect_self_assoc_in_type(e, found)),
        _ => {}
    }
}

// ─── Attribute macro ──────────────────────────────────────────────────────────

/// Annotate an operation trait to generate the full explaining scaffolding for
/// every method in that trait.
///
/// # Receiver-type handling
///
/// - **`self`** (consuming) — uses `std::mem::replace` to move the value out safely.
/// - **`&self` / `&mut self`** returning `Self` or `Result<Self, E>` — calls directly.
/// - **`&mut self`** returning `()` or `Result<(), E>` — calls for side-effect only.
///
/// # Associated-type propagation
///
/// Method parameters that reference `Self::X` (associated types from a supertrait) are
/// handled by declaring `type X;` in the generated `FooExt` trait and setting
/// `type X = T::X;` in the blanket impl. No substitution of method signatures is needed.
///
/// # `#[cfg(…)]` propagation
///
/// `#[cfg(…)]` attributes on individual trait methods are forwarded to all generated items.
#[proc_macro_attribute]
pub fn explainable(_args: TokenStream, input: TokenStream) -> TokenStream {
    let trait_def = parse_macro_input!(input as ItemTrait);
    let trait_name = &trait_def.ident;
    let explain_text_trait_name = format_ident!("{}ExplainText", trait_name);
    let ext_trait_name = format_ident!("{}Ext", trait_name);
    let vis = &trait_def.vis;

    let self_methods: Vec<_> = trait_def
        .items
        .iter()
        .filter_map(|item| {
            if let TraitItem::Fn(f) = item {
                let has_receiver = f
                    .sig
                    .inputs
                    .first()
                    .map(|a| matches!(a, FnArg::Receiver(_)))
                    .unwrap_or(false);
                // Exclude methods whose return type cannot be assigned back to
                // `self.inner: T` in the generic blanket impl (e.g. methods that
                // return a concrete `AudioSamples<'static, Self::Sample>` rather
                // than `Self`).
                let chainable = is_chainable_return(&f.sig.output);
                if has_receiver && chainable {
                    Some(f)
                } else {
                    None
                }
            } else {
                None
            }
        })
        .collect();

    // ── Collect Self::X associated-type refs from all method params ────────────

    let mut assoc_idents: Vec<syn::Ident> = Vec::new();
    for m in &self_methods {
        for param in m.sig.inputs.iter() {
            if let FnArg::Typed(pt) = param {
                collect_self_assoc_in_type(&pt.ty, &mut assoc_idents);
            }
        }
    }

    // ── Collect bounds on Self::X from the original trait's where clause ───────
    // Maps assoc ident → list of bounds so we can emit `type X: Bound1 + Bound2;`.

    let where_bounds: Vec<Vec<&TypeParamBound>> = assoc_idents
        .iter()
        .map(|name| {
            let mut bounds: Vec<&TypeParamBound> = Vec::new();
            if let Some(wc) = &trait_def.generics.where_clause {
                for pred in &wc.predicates {
                    if let WherePredicate::Type(pt) = pred {
                        // Look for `Self::Name: Bound` predicates.
                        if let Type::Path(tp) = &pt.bounded_ty {
                            let segs: Vec<_> = tp.path.segments.iter().collect();
                            if segs.len() == 2 && segs[0].ident == "Self" && &segs[1].ident == name
                            {
                                bounds.extend(pt.bounds.iter());
                            }
                        }
                    }
                }
            }
            bounds
        })
        .collect();

    // type X: Bound; declarations for FooExt (with doc so missing_docs is satisfied)
    let ext_assoc_type_decls: Vec<TokenStream2> = assoc_idents
        .iter()
        .zip(where_bounds.iter())
        .map(|(name, bounds)| {
            let doc = format!("Associated type `{}` forwarded from the domain type.", name);
            if bounds.is_empty() {
                quote! {
                    #[doc = #doc]
                    type #name;
                }
            } else {
                quote! {
                    #[doc = #doc]
                    type #name: #(#bounds)+*;
                }
            }
        })
        .collect();

    // type X = T::X; definitions for the blanket impl
    let ext_assoc_type_impls: Vec<TokenStream2> = assoc_idents
        .iter()
        .map(|name| quote! { type #name = T::#name; })
        .collect();

    // ── Companion ExplainText trait ───────────────────────────────────────────

    let explain_text_methods: Vec<TokenStream2> = self_methods
        .iter()
        .map(|m| {
            let method_name = &m.sig.ident;
            let explain_fn = format_ident!("explain_text_{}", method_name);
            let cfg_attrs: Vec<_> = m
                .attrs
                .iter()
                .filter(|a| a.path().is_ident("cfg"))
                .collect();
            quote! {
                #(#cfg_attrs)*
                fn #explain_fn(before: &Self, after: &Self) -> String;
            }
        })
        .collect();

    // ── Extension trait — method signatures ───────────────────────────────────

    let ext_method_sigs: Vec<TokenStream2> = self_methods
        .iter()
        .map(|m| {
            let method_name = &m.sig.ident;
            let cfg_attrs: Vec<_> = m
                .attrs
                .iter()
                .filter(|a| a.path().is_ident("cfg"))
                .collect();
            let non_recv_params: Vec<_> = m
                .sig
                .inputs
                .iter()
                .filter(|a| !matches!(a, FnArg::Receiver(_)))
                .collect();
            quote! {
                #(#cfg_attrs)*
                fn #method_name(&mut self, #(#non_recv_params),*) -> &mut Self;
            }
        })
        .collect();

    // ── Blanket impl — method bodies ──────────────────────────────────────────

    let ext_method_impls: Vec<TokenStream2> = self_methods
        .iter()
        .map(|m| {
            let method_name = &m.sig.ident;
            let explain_fn = format_ident!("explain_text_{}", method_name);
            let cfg_attrs: Vec<_> = m
                .attrs
                .iter()
                .filter(|a| a.path().is_ident("cfg"))
                .collect();

            let non_recv_params: Vec<_> = m
                .sig
                .inputs
                .iter()
                .filter(|a| !matches!(a, FnArg::Receiver(_)))
                .collect();

            let arg_idents: Vec<_> = non_recv_params
                .iter()
                .filter_map(|a| {
                    if let FnArg::Typed(pt) = a {
                        if let Pat::Ident(pi) = pt.pat.as_ref() {
                            Some(&pi.ident)
                        } else {
                            None
                        }
                    } else {
                        None
                    }
                })
                .collect();

            let consuming = m
                .sig
                .inputs
                .first()
                .map(|a| is_consuming_receiver(a))
                .unwrap_or(false);

            let (is_result, is_void) = match &m.sig.output {
                ReturnType::Type(_, ty) => {
                    let r = looks_like_result(ty);
                    (r, r && result_ok_is_unit(ty))
                }
                ReturnType::Default => (false, true),
            };

            let update_inner = if is_void {
                if is_result {
                    quote! { self.inner.#method_name(#(#arg_idents),*).unwrap(); }
                } else {
                    quote! { self.inner.#method_name(#(#arg_idents),*); }
                }
            } else if consuming {
                if is_result {
                    quote! {
                        let __taken = ::std::mem::replace(&mut self.inner, before.clone());
                        self.inner = __taken.#method_name(#(#arg_idents),*).unwrap();
                    }
                } else {
                    quote! {
                        let __taken = ::std::mem::replace(&mut self.inner, before.clone());
                        self.inner = __taken.#method_name(#(#arg_idents),*);
                    }
                }
            } else if is_result {
                quote! { self.inner = self.inner.#method_name(#(#arg_idents),*).unwrap(); }
            } else {
                quote! { self.inner = self.inner.#method_name(#(#arg_idents),*); }
            };

            quote! {
                #(#cfg_attrs)*
                fn #method_name(&mut self, #(#non_recv_params),*) -> &mut Self {
                    let before = self.inner.clone();
                    #update_inner
                    let text = match self.mode {
                        ::explainable::ExplainMode::Text
                        | ::explainable::ExplainMode::Both => Some(
                            <T as #explain_text_trait_name>::#explain_fn(
                                &before,
                                &self.inner,
                            ),
                        ),
                        _ => None,
                    };
                    let visual = match self.mode {
                        ::explainable::ExplainMode::Visual
                        | ::explainable::ExplainMode::Both => Some(
                            <T as ::explainable::RenderVisual>::render_visual(
                                &before,
                                &self.inner,
                            ),
                        ),
                        _ => None,
                    };
                    self.explanations.push(::explainable::Explanation::new(
                        self.mode,
                        text,
                        visual,
                    ));
                    self
                }
            }
        })
        .collect();

    // ── Assemble output ───────────────────────────────────────────────────────

    let explain_text_doc = format!(
        "Companion text trait generated by `#[explainable]` for [`{}`].\n\n\
         Implement one `explain_text_<method>` per operation to supply the pedagogical \
         text explanation shown when that operation runs inside an explaining chain.",
        trait_name
    );
    let ext_trait_doc = format!(
        "Extension trait generated by `#[explainable]` for [`{}`].\n\n\
         Bring this into scope to call `{}` operations on an \
         [`explainable::Explaining`] chain.",
        trait_name, trait_name
    );

    let output = quote! {
        #trait_def

        #[doc = #explain_text_doc]
        #[allow(missing_docs)]
        #vis trait #explain_text_trait_name:
            ::explainable::Explainable + #trait_name
        {
            #(#explain_text_methods)*
        }

        #[doc = #ext_trait_doc]
        #[allow(missing_docs)]
        #vis trait #ext_trait_name {
            #(#ext_assoc_type_decls)*
            #(#ext_method_sigs)*
        }

        #[allow(missing_docs)]
        impl<T> #ext_trait_name for ::explainable::Explaining<T>
        where
            T: ::explainable::Explainable + #trait_name + #explain_text_trait_name,
        {
            #(#ext_assoc_type_impls)*
            #(#ext_method_impls)*
        }
    };

    output.into()
}