aimdb_derive/lib.rs
1//! Derive macros for AimDB record key types
2//!
3//! This crate provides the `#[derive(RecordKey)]` macro for defining
4//! compile-time checked record keys with optional connector metadata.
5//!
6//! # Example
7//!
8//! Illustrative (not compiled: the generated impl targets `aimdb_core`'s
9//! `RecordKey` trait, a circular dev-dependency for this proc-macro crate —
10//! compiled integration tests live in `aimdb-core`):
11//!
12//! ```rust,ignore
13//! use aimdb_derive::RecordKey;
14//!
15//! // Note: Hash is auto-generated by the derive macro to satisfy the Borrow<str> contract
16//! #[derive(RecordKey, Clone, Copy, PartialEq, Eq)]
17//! pub enum AppKey {
18//! #[key = "temp.indoor"]
19//! #[link_address = "mqtt://sensors/temp/indoor"]
20//! TempIndoor,
21//!
22//! #[key = "temp.outdoor"]
23//! #[link_address = "knx://9/1/0"]
24//! TempOutdoor,
25//! }
26//! ```
27
28use proc_macro::TokenStream;
29use quote::quote;
30use syn::{parse_macro_input, Data, DeriveInput, Error, Fields, Lit, Meta};
31
32mod migration_chain;
33mod ros_message;
34
35/// Variable-arity replacement for `aimdb-data-contracts`'s old 3-arm
36/// `macro_rules! migration_chain`. Re-exported as
37/// `aimdb_data_contracts::migration_chain!` — see that crate's
38/// `migratable` feature and `migratable.rs` for the user-facing grammar
39/// and docs.
40#[proc_macro]
41pub fn migration_chain(input: TokenStream) -> TokenStream {
42 migration_chain::migration_chain(input)
43}
44
45/// Derive `Linkable` (JSON codec) for a schema type.
46///
47/// Emits `from_bytes`/`to_bytes` via `serde_json::from_slice`/`to_vec` — the
48/// boilerplate every hand-written `impl Linkable` for a JSON-wire type repeats.
49/// Requires `T: Serialize + DeserializeOwned` (a normal
50/// compile error surfaces if it's missing) and the `linkable-json` feature of
51/// `aimdb-data-contracts` (for the `Linkable` trait and its `__private::serde_json`
52/// re-export). Binary formats (e.g. KNX DPT codecs) still implement `Linkable`
53/// by hand — this derive is JSON-only.
54///
55/// # Example
56///
57/// Illustrative (not compiled: see the crate-level note — compiled
58/// integration tests live in `aimdb-data-contracts`).
59///
60/// ```rust,ignore
61/// use aimdb_data_contracts::Linkable;
62/// use serde::{Deserialize, Serialize};
63///
64/// #[derive(Clone, Debug, Serialize, Deserialize, Linkable)]
65/// struct Temperature {
66/// celsius: f32,
67/// timestamp: u64,
68/// }
69/// ```
70#[proc_macro_derive(Linkable)]
71pub fn derive_linkable(input: TokenStream) -> TokenStream {
72 let input = parse_macro_input!(input as DeriveInput);
73 let name = &input.ident;
74
75 let expanded = quote! {
76 impl ::aimdb_data_contracts::Linkable for #name {
77 const WIRE_FORMAT: ::aimdb_data_contracts::WireFormat =
78 ::aimdb_data_contracts::WireFormat::Json;
79
80 fn from_bytes(
81 data: &[u8],
82 ) -> Result<Self, ::aimdb_data_contracts::__private::alloc::string::String> {
83 ::aimdb_data_contracts::__private::serde_json::from_slice(data).map_err(|e| {
84 ::aimdb_data_contracts::__private::alloc::string::ToString::to_string(&e)
85 })
86 }
87
88 fn to_bytes(
89 &self,
90 ) -> Result<
91 ::aimdb_data_contracts::__private::alloc::vec::Vec<u8>,
92 ::aimdb_data_contracts::__private::alloc::string::String,
93 > {
94 ::aimdb_data_contracts::__private::serde_json::to_vec(self).map_err(|e| {
95 ::aimdb_data_contracts::__private::alloc::string::ToString::to_string(&e)
96 })
97 }
98 }
99 };
100
101 expanded.into()
102}
103
104/// Derive `RosMessage` for a struct that mirrors a ROS 2 message.
105///
106/// Emits three impls:
107/// - `SchemaType`, with `NAME` set to the ROS type (`pkg/msg/Name`);
108/// - `Linkable` as CDR through `aimdb-cdr`, with a bounded `encode_into`;
109/// - `RosMessage`, with the DDS type name derived from the ROS type.
110///
111/// Requires `Serialize + Deserialize` and the `ros2` feature of
112/// `aimdb-data-contracts`. Fields must follow the `.msg` in order and type,
113/// since CDR is positional; an empty message carries
114/// `structure_needs_at_least_one_member: u8`, as ROS does.
115///
116/// Attributes:
117/// - `#[ros(type = "pkg/msg/Name", hash = "RIHS01_…")]`, both required and
118/// checked at compile time. Copy the hash from `ros2 topic info -v`.
119/// - `#[ros(encode_capacity = N)]`: the scratch buffer for the bounded encode
120/// path, 256 bytes by default.
121/// - `#[ros(max_len = N)]` on a `String` or `Vec` field, for a bounded
122/// `string<=N` or `T[<=N]`: encoding fails when the field is longer
123/// (bytes for a string, elements for a sequence).
124///
125/// # Example
126///
127/// Illustrative (not compiled: see the crate-level note — compiled
128/// integration tests live in `aimdb-data-contracts`).
129///
130/// ```rust,ignore
131/// use aimdb_data_contracts::RosMessage;
132/// use serde::{Deserialize, Serialize};
133///
134/// #[derive(Clone, Debug, Serialize, Deserialize, RosMessage)]
135/// #[ros(type = "cell_msgs/msg/SpindleCommand", hash = "RIHS01_…")]
136/// pub struct SpindleCommand {
137/// pub rpm: f64,
138/// pub enabled: bool,
139/// #[ros(max_len = 32)]
140/// pub tool_id: String,
141/// }
142/// ```
143#[proc_macro_derive(RosMessage, attributes(ros))]
144pub fn derive_ros_message(input: TokenStream) -> TokenStream {
145 let input = parse_macro_input!(input as DeriveInput);
146 ros_message::derive(input)
147 .unwrap_or_else(Error::into_compile_error)
148 .into()
149}
150
151/// Derive the `RecordKey` trait for an enum
152///
153/// Each variant must have a `#[key = "..."]` attribute specifying its string key.
154/// Optionally, the enum can have a `#[key_prefix = "..."]` attribute to prepend
155/// a common prefix to all keys.
156///
157/// ## Connector Metadata
158///
159/// Variants can have a `#[link_address = "..."]` attribute to associate a connector
160/// URL/address with the key (MQTT topics, KNX group addresses, etc.):
161///
162/// # Example
163///
164/// Illustrative (not compiled: see the crate-level note — compiled
165/// integration tests live in `aimdb-core`):
166///
167/// ```rust,ignore
168/// // Note: Hash is auto-generated to satisfy the Borrow<str> contract
169/// #[derive(RecordKey, Clone, Copy, PartialEq, Eq)]
170/// #[key_prefix = "sensors."]
171/// pub enum SensorKey {
172/// #[key = "temp"] // → "sensors.temp"
173/// #[link_address = "mqtt://sensors/temp/indoor"]
174/// Temperature,
175///
176/// #[key = "humid"] // → "sensors.humid"
177/// #[link_address = "knx://9/0/1"]
178/// Humidity,
179/// }
180/// ```
181///
182/// # Generated Code
183///
184/// The macro generates:
185/// - `impl aimdb_core::RecordKey for YourEnum` with `as_str()` and `link_address()` methods
186/// - `impl core::borrow::Borrow<str> for YourEnum` for O(1) HashMap lookups
187/// - `impl core::hash::Hash for YourEnum` that hashes the string key (required by Borrow contract)
188#[proc_macro_derive(RecordKey, attributes(key, key_prefix, link_address))]
189pub fn derive_record_key(input: TokenStream) -> TokenStream {
190 let input = parse_macro_input!(input as DeriveInput);
191
192 match derive_record_key_impl(input) {
193 Ok(tokens) => tokens.into(),
194 Err(err) => err.to_compile_error().into(),
195 }
196}
197
198fn derive_record_key_impl(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
199 let name = &input.ident;
200
201 // Check it's an enum
202 let data_enum = match &input.data {
203 Data::Enum(data) => data,
204 _ => {
205 return Err(Error::new_spanned(
206 &input,
207 "RecordKey can only be derived for enums",
208 ));
209 }
210 };
211
212 // Get optional key_prefix from enum attributes
213 let prefix = get_key_prefix(&input.attrs)?;
214
215 // Collect variant data
216 struct VariantData {
217 name: syn::Ident,
218 key: String,
219 link: Option<String>,
220 }
221
222 let mut variants = Vec::new();
223 let mut seen_keys = std::collections::HashSet::new();
224
225 for variant in &data_enum.variants {
226 // Ensure unit variant (no fields)
227 match &variant.fields {
228 Fields::Unit => {}
229 _ => {
230 return Err(Error::new_spanned(
231 variant,
232 "RecordKey variants must be unit variants (no fields)",
233 ));
234 }
235 }
236
237 let variant_name = &variant.ident;
238 let key = get_variant_key(&variant.attrs, variant_name)?;
239 let link = get_optional_attr(&variant.attrs, "link_address")?;
240
241 // Build full key with prefix
242 let full_key = if let Some(ref p) = prefix {
243 format!("{}{}", p, key)
244 } else {
245 key
246 };
247
248 // Check for duplicate keys
249 if !seen_keys.insert(full_key.clone()) {
250 return Err(Error::new_spanned(
251 variant,
252 format!(
253 "Duplicate key \"{}\" - each variant must have a unique key",
254 full_key
255 ),
256 ));
257 }
258
259 variants.push(VariantData {
260 name: variant_name.clone(),
261 key: full_key,
262 link,
263 });
264 }
265
266 // Check if any variant has link
267 let has_link = variants.iter().any(|v| v.link.is_some());
268
269 // Generate match arms for as_str()
270 let as_str_arms = variants.iter().map(|v| {
271 let variant_name = &v.name;
272 let key = &v.key;
273 quote! {
274 Self::#variant_name => #key
275 }
276 });
277
278 // Generate link_address() implementation if any variant has it
279 let link_impl = if has_link {
280 let arms = variants.iter().map(|v| {
281 let variant_name = &v.name;
282 match &v.link {
283 Some(url) => quote! { Self::#variant_name => Some(#url) },
284 None => quote! { Self::#variant_name => None },
285 }
286 });
287 quote! {
288 #[inline]
289 fn link_address(&self) -> Option<&str> {
290 match self {
291 #(#arms),*
292 }
293 }
294 }
295 } else {
296 quote! {}
297 };
298
299 // Generate the implementations
300 let expanded = quote! {
301 impl aimdb_core::RecordKey for #name {
302 #[inline]
303 fn as_str(&self) -> &'static str {
304 match self {
305 #(#as_str_arms),*
306 }
307 }
308
309 #link_impl
310 }
311
312 impl core::borrow::Borrow<str> for #name {
313 #[inline]
314 fn borrow(&self) -> &str {
315 <Self as aimdb_core::RecordKey>::as_str(self)
316 }
317 }
318
319 // Hash implementation that hashes the string key, ensuring compliance
320 // with Rust's Borrow trait contract: hash(k) == hash(k.borrow())
321 impl core::hash::Hash for #name {
322 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
323 <Self as aimdb_core::RecordKey>::as_str(self).hash(state);
324 }
325 }
326 };
327
328 Ok(expanded)
329}
330
331/// Extract `#[key_prefix = "..."]` from enum attributes
332fn get_key_prefix(attrs: &[syn::Attribute]) -> Result<Option<String>, Error> {
333 get_optional_attr(attrs, "key_prefix")
334}
335
336/// Extract an optional `#[attr_name = "..."]` from attributes
337fn get_optional_attr(attrs: &[syn::Attribute], attr_name: &str) -> Result<Option<String>, Error> {
338 for attr in attrs {
339 if attr.path().is_ident(attr_name) {
340 let meta = &attr.meta;
341 if let Meta::NameValue(nv) = meta {
342 if let syn::Expr::Lit(expr_lit) = &nv.value {
343 if let Lit::Str(lit_str) = &expr_lit.lit {
344 return Ok(Some(lit_str.value()));
345 }
346 }
347 }
348 return Err(Error::new_spanned(
349 attr,
350 format!("Expected #[{} = \"...\"]", attr_name),
351 ));
352 }
353 }
354 Ok(None)
355}
356
357/// Extract `#[key = "..."]` from variant attributes
358fn get_variant_key(attrs: &[syn::Attribute], variant_name: &syn::Ident) -> Result<String, Error> {
359 for attr in attrs {
360 if attr.path().is_ident("key") {
361 let meta = &attr.meta;
362 if let Meta::NameValue(nv) = meta {
363 if let syn::Expr::Lit(expr_lit) = &nv.value {
364 if let Lit::Str(lit_str) = &expr_lit.lit {
365 return Ok(lit_str.value());
366 }
367 }
368 }
369 return Err(Error::new_spanned(attr, "Expected #[key = \"...\"]"));
370 }
371 }
372
373 Err(Error::new_spanned(
374 variant_name,
375 format!(
376 "Missing #[key = \"...\"] attribute on variant `{}`",
377 variant_name
378 ),
379 ))
380}
381
382#[cfg(test)]
383mod tests {
384 // Proc-macro crate tests are limited - integration tests are in aimdb-core
385}