astrs_operator_macros/lib.rs
1//! Procedural macros for the AstRS operator API.
2//!
3//! Companion crate to `astrs-operator-api` (blueprint §9.3). Hosts the
4//! derive and attribute macros that generate operator registration glue,
5//! typed input/output accessors and the schema wiring an operator would
6//! otherwise write by hand:
7//!
8//! - `#[derive(AstrsMessage)]` (blueprint §9.1, §9.2): maps a struct's
9//! fields onto the closed columnar type set and implements
10//! `astrs_data::AstrsMessage` — the trait itself lives in `astrs-data`,
11//! not here (see that crate's `message` module docs for why: it is a
12//! Layer 1 crate every future implementor, including `astrs-node-api` and
13//! `astrs-idl`'s ROS 2 codegen, already depends on; this derive is one
14//! consumer among several, not the trait's owner).
15//! - `#[astrs::operator]`: optional sugar adding a ready-made registry
16//! entry to an `astrs_operator_api::Operator` impl.
17//!
18//! # Why this crate has no dependency on `astrs-data`
19//!
20//! A proc-macro crate emits *references* to paths (`::astrs_data::...`)
21//! that resolve in the *invoking* crate's own dependency graph — it does
22//! not need to depend on the crate whose types it names, any more than
23//! `serde_derive` depends on `serde`'s data types. This crate's `[dev-
24//! dependencies]` do include `astrs-data` (and, for the expansion tests
25//! below, this crate itself), because its own tests exercise the derive by
26//! actually invoking it.
27//!
28//! # Testing strategy
29//!
30//! Trybuild-style negative compile tests are unavailable here without
31//! adding a dependency this workspace's retained list (blueprint §18.1)
32//! does not include. Instead:
33//!
34//! - `shape`, `urn_check` and `attr` (private modules) factor every
35//! parsing/validation rule into plain functions over `syn`/`proc_macro2`
36//! values, unit-tested directly in each module — including every
37//! rejection path a real negative compile test would otherwise cover (a
38//! unit struct, a tuple struct, `Vec<NestedType>`, `Option<Option<_>>`, a
39//! malformed URN, and so on).
40//! - `tests/derive_expansion.rs` is the positive path: real
41//! `#[derive(AstrsMessage)]` uses on six representative structs (scalars
42//! plus a nullable field, a nested message, `Vec`-of-scalar and
43//! `Vec`-of-fixed-array per blueprint §9.1's own `Detections` example,
44//! bare fixed arrays, and a `String`/`Vec<String>`/`bool` struct), each
45//! round-tripped through `to_record_batch`/`from_record_batch` and, where
46//! the target URN is one of `astrs-data`'s registered `std` types,
47//! cross-checked against `astrs_data::urn::layout_of_str` — the
48//! "compile-time layout assertion" the blueprint asks for realized as a
49//! generated-code-exercising test, since the registry it must agree with
50//! is a runtime data structure and cannot be consulted from inside a
51//! `#[proc_macro_derive]`. The genuinely compile-time half — the one a
52//! `#[proc_macro_derive]` really can enforce — is `urn_check`:
53//! `#[astrs(urn = "...")]`'s literal text is checked against the URN
54//! grammar's shape at macro-expansion time, so a malformed URN fails the
55//! derive itself with a real `compile_error!`, no `cargo test` required.
56
57mod attr;
58mod codegen;
59mod crate_path;
60mod message_derive;
61mod operator_attr;
62mod shape;
63mod urn_check;
64
65use proc_macro::TokenStream;
66
67/// Derives `astrs_data::AstrsMessage` for a struct (blueprint §9.1, §9.2).
68///
69/// ```
70/// # #[allow(dead_code)]
71/// use astrs_operator_macros::AstrsMessage;
72///
73/// #[derive(AstrsMessage)]
74/// #[astrs(urn = "std/vision/v1/Detections")]
75/// struct Detections {
76/// boxes: Vec<[f32; 4]>,
77/// scores: Vec<f32>,
78/// labels: Vec<u32>,
79/// }
80/// ```
81///
82/// See the [crate docs](self) for the supported field grammar and this
83/// crate's testing strategy.
84///
85/// # Which crate the generated code names
86///
87/// The expansion implements a trait that lives in `astrs-data`, so it has to
88/// name that crate — and the name it must use depends on the *invoking*
89/// crate's own dependency list, because Rust only puts **direct**
90/// dependencies in the extern prelude. A crate whose entire `[dependencies]`
91/// section is `astrs = "0.1"` cannot name `astrs_data` at all, however
92/// faithfully the facade re-exports it.
93///
94/// The macro therefore resolves the path at expansion time from the invoking
95/// crate's `Cargo.toml`: a direct `astrs-data` dependency (under whatever
96/// name that manifest gives it) wins; otherwise a direct `astrs` dependency
97/// is reached through the facade's re-export chain; otherwise `::astrs_data`
98/// is assumed. All three are correct for the crate they describe, and no
99/// single hardcoded path is correct for more than one of them.
100///
101/// # `#[astrs(crate = "...")]`
102///
103/// The escape hatch, for a build the manifest lookup cannot see through — a
104/// vendored tree, a non-cargo build system, or a crate that re-exports this
105/// derive under its own name. Its value is the path at which **`astrs-data`
106/// itself** is reachable, exactly as `serde`'s `#[serde(crate = "...")]`
107/// names `serde`:
108///
109/// ```
110/// # #[allow(dead_code)]
111/// use astrs_operator_macros::AstrsMessage;
112///
113/// #[derive(AstrsMessage)]
114/// #[astrs(urn = "std/test/v1/Reading", crate = "::astrs_data")]
115/// struct Reading {
116/// values: Vec<f64>,
117/// }
118/// ```
119///
120/// Through the facade, that path is `::astrs::__private::data` — which is
121/// what the automatic resolution already emits, so the override is only ever
122/// needed when the automatic answer is unavailable.
123#[proc_macro_derive(AstrsMessage, attributes(astrs))]
124pub fn derive_astrs_message(input: TokenStream) -> TokenStream {
125 let input = match syn::parse::<syn::DeriveInput>(input) {
126 Ok(input) => input,
127 Err(err) => return err.to_compile_error().into(),
128 };
129 match message_derive::expand(&input) {
130 Ok(tokens) => tokens.into(),
131 Err(err) => err.to_compile_error().into(),
132 }
133}
134
135/// Optional sugar adding a ready-made `astrs_operator_api::OperatorRegistry`
136/// entry to an `astrs_operator_api::Operator` impl (blueprint §9.3).
137///
138/// ```ignore
139/// // `ignore`d: exercising this for real needs `astrs-operator-api` as a
140/// // dependency, and this crate cannot add one — `astrs-operator-api`
141/// // already depends on `astrs-operator-macros` for the derive above, so
142/// // the reverse dependency would be circular. The real, compiled,
143/// // end-to-end exercise of this macro lives in `astrs-operator-api`'s own
144/// // test suite instead, where both crates are legitimately available;
145/// // this crate's own tests check the expansion at the token level (see
146/// // `operator_attr`'s `#[cfg(test)]` module).
147/// use astrs_operator_macros::operator;
148///
149/// #[operator]
150/// #[derive(Default)]
151/// struct Crop;
152/// ```
153///
154/// gives `Crop` an inherent `operator_entry()` returning `(&'static str,
155/// astrs_operator_api::OperatorConstructor)` — the same shape
156/// `astrs_operator_api::register_operator!(Crop)` produces, so either can
157/// feed `OperatorRegistry::from_entries`. See the `operator_attr` module
158/// docs for the default name it picks and how to override it.
159#[proc_macro_attribute]
160pub fn operator(attr: TokenStream, item: TokenStream) -> TokenStream {
161 match operator_attr::expand(attr.into(), item.into()) {
162 Ok(tokens) => tokens.into(),
163 Err(err) => err.to_compile_error().into(),
164 }
165}