Skip to main content

rstorch_derive/
lib.rs

1#![warn(missing_docs)]
2//! The generated paths resolve `rstorch` automatically in the caller. An
3//! in-package expansion uses the runtime library's `::rstorch` self-alias,
4//! while a dependency renamed in `Cargo.toml` (for example
5//! `rstorch_alias = { package = "rstorch", ... }`) uses that alias. If the
6//! macro is expanded outside Cargo, it falls back to `::rstorch` for direct
7//! unit-expansion tests and diagnostics.
8//!
9//! Both derives preserve their existing helper attributes; dependency-name
10//! resolution is independent of `#[module(...)]` and `#[typed_module(...)]`.
11//!
12//! Provides `#[derive(Module)]`: loud-by-default field classification, with
13//! `#[module(param)]`, `#[module(buffer)]`, `#[module(child)]`, and
14//! `#[module(skip)]` as explicit field controls.
15//! # `#[derive(Module)]`
16//!
17//! Generates both walks of the `rstorch::nn::Module` trait (`visit` /
18//! `visit_mut`) for a `struct`, emitting one visitor call per field with the
19//! field name as its dotted-path segment. Field handling is decided **by
20//! token match** on the written type, and is **loud by default**: any field
21//! whose type is not on the whitelist is treated as a child module, so a
22//! non-`Module` field is a compile error rather than a silently untrained
23//! parameter (the exact bug class v3 abolishes).
24//!
25//! | field type (as written) | emitted call |
26//! |---|---|
27//! | `Param` | `v.param("name", &self.name)` |
28//! | `Option<Param>` | `if let Some(p) = &self.name { v.param("name", p) }` |
29//! | `Tensor` | `v.buffer("name", &self.name)` (non-trainable buffer) |
30//! | `Option<Tensor>` | `if let Some(t) = … { v.buffer("name", t) }` |
31//! | `Vec<M>` | `v.module("name.0", &self.name[0])`, `…("name.1", …)`, … (indexed) |
32//! | `Option<M>` | `if let Some(m) = &self.name { v.module("name", m) }` |
33//! | primitive whitelist (`f32`, `f64`, `usize`, `bool`, …) | skipped |
34//! | `#[module(skip)]` (any type) | skipped |
35//! | **anything else** | `v.module("name", &self.name)` — child module |
36//!
37//! The `_mut` walk mirrors this against `visit_mut` / the `&mut` visitor
38//! methods.
39//!
40//! `#[module(skip)]` is an explicit escape hatch. On the dynamic derive it can
41//! skip any field, including a `Param`; a skipped parameter is intentionally
42//! absent from optimizer and state-dict walks. The typed derive applies
43//! stricter validation to typed leaves and containers; see its differences
44//! below.
45//!
46//! ## Type aliases and explicit overrides
47//!
48//! Classification is normally a syntactic token match on the type as written,
49//! so a type alias defeats inference. Use an explicit field override when an
50//! alias is intentional. A plain newtype does not coerce automatically; add a
51//! suitable `Deref` conversion or hand-write its `Module` implementation.
52//!
53//! ```ignore
54//! #[derive(rstorch::Module)]
55//! struct Layer {
56//!     #[module(param)]
57//!     weight: Weights,
58//!     #[module(buffer)]
59//!     running_mean: Tensor,
60//!     #[module(child)]
61//!     encoder: Encoder,
62//! }
63//! ```
64//!
65//! An override is checked before inference and emits the selected visitor
66//! call. `#[module(skip)]` remains the explicit opt-out for dynamic modules.
67//!
68//! # `#[derive(TypedModule)]`
69//!
70//! Generates both walks of the `rstorch::typed::nn::Module` trait for a
71//! `struct`. Classification is again a syntactic token match, but the table
72//! differs from the dynamic derive in one way that bites immediately:
73//! **there is no primitive whitelist.**
74//!
75//! | field type (as written) | emitted call |
76//! |---|---|
77//! | `TypedParam<T>` | `v.param("name", &self.name)` |
78//! | `Option<TypedParam<T>>` | `if let Some(p) = … { v.param("name", p) }` |
79//! | `TypedBuffer<T>` | `v.buffer("name", &self.name)` |
80//! | `Option<TypedBuffer<T>>` | `if let Some(b) = … { v.buffer("name", b) }` |
81//! | `Vec<M>` | `v.module("name.0", …)`, `…("name.1", …)`, … (indexed) |
82//! | `Option<M>` | `if let Some(m) = … { v.module("name", m) }` |
83//! | `#[typed_module(skip)]` on an opaque direct field | skipped |
84//! | **anything else** | `v.module("name", &self.name)` — child module |
85//!
86//! ## Differences from `#[derive(Module)]`
87//!
88//! - **No primitive whitelist.** `hidden: usize` is skipped by the dynamic
89//!   derive but is a child module to this one, so it fails with
90//!   `usize: Module is not satisfied`. Configuration fields need an explicit
91//!   `#[typed_module(skip)]`.
92//! - **`skip` is classified first, then rejected.** It cannot exclude a
93//!   `TypedParam`, a `TypedBuffer`, or an `Option`/`Vec` container, because a
94//!   container may hold module state. A plain configuration value therefore
95//!   has no directly skippable spelling when it is written as `Vec<T>` or
96//!   `Option<T>`: wrap it in a newtype (`struct Config(Vec<usize>)`) and skip
97//!   that, or hand-write `impl Module`.
98//! - **The helper attribute is field-only.** A struct-level
99//!   `#[typed_module(...)]` is a compile error rather than being silently
100//!   ignored.
101//!
102//! Type aliases defeat classification here too, and for the same reason: an
103//! alias for `TypedParam<T>` is treated as a child module.
104
105mod module;
106mod shared;
107mod typed_module;
108
109use proc_macro::TokenStream;
110use proc_macro_crate::{FoundCrate, crate_name};
111use proc_macro2::{Span, TokenStream as TokenStream2};
112use quote::quote;
113
114/// Resolve the runtime crate path in the package that invokes this macro.
115///
116/// `proc-macro-crate` handles dependency aliases. The runtime library also
117/// aliases itself as `rstorch`, so the absolute spelling works both inside the
118/// library and in its separate example/fixture targets; using `crate` would
119/// incorrectly resolve to an example binary's crate root.
120fn runtime_crate() -> TokenStream2 {
121    match crate_name("rstorch") {
122        Ok(FoundCrate::Itself) => quote!(::rstorch),
123        Ok(FoundCrate::Name(name)) => {
124            let ident = syn::Ident::new(&name, Span::call_site());
125            quote!(::#ident)
126        }
127        Err(_) => quote!(::rstorch),
128    }
129}
130
131/// Derive the `rstorch::nn::Module` trait for a `struct`.
132///
133/// See the [crate docs](crate) for the full field-classification table and
134/// the loud-by-default rule. Named-field, tuple, and unit `struct`s are all
135/// supported — a unit struct derives an empty walk, which is what a stateless
136/// layer such as `rstorch::nn::Relu` wants. `enum`s and `union`s are a
137/// compile error, because a module's field set must be statically known for
138/// every parameter to be visited.
139///
140/// # Attributes
141///
142/// - `#[module(skip)]` on a field opts it out of both walks. It is the only
143///   sanctioned way to keep a non-whitelisted, non-`Module` field.
144#[proc_macro_derive(Module, attributes(module))]
145pub fn derive_module(input: TokenStream) -> TokenStream {
146    let input = syn::parse_macro_input!(input as syn::DeriveInput);
147    module::expand_with_crate(input, runtime_crate())
148        .unwrap_or_else(syn::Error::into_compile_error)
149        .into()
150}
151
152/// Derive the `rstorch::typed::nn::Module` trait for a `struct`.
153///
154/// `TypedParam<T>` and `TypedBuffer<T>` fields are emitted as typed leaves;
155/// `Option` and `Vec` containers are walked, and every other field is treated
156/// as a typed child module. Use `#[typed_module(skip)]` to explicitly exclude
157/// an opaque direct configuration field that is not part of the module tree.
158/// The attribute is rejected on typed leaves and on `Option` or `Vec` fields,
159/// because those containers may hold module state. A proc macro cannot tell an
160/// opaque configuration type from a concrete child module, so applying `skip`
161/// to such a child is an explicit contract violation by the caller.
162#[proc_macro_derive(TypedModule, attributes(typed_module))]
163pub fn derive_typed_module(input: TokenStream) -> TokenStream {
164    let input = syn::parse_macro_input!(input as syn::DeriveInput);
165    typed_module::expand_with_crate(input, runtime_crate())
166        .unwrap_or_else(syn::Error::into_compile_error)
167        .into()
168}