Skip to main content

sensor_db_derive/
lib.rs

1//! Derive macro for [`sensor_db::SensorData`].
2//!
3//! This crate is an implementation detail of the `sensor-db` crate's `derive`
4//! feature. Use it through that feature rather than depending on it directly:
5//!
6//! ```toml
7//! sensor-db = { version = "0.1", features = ["derive"] }
8//! zerocopy = { version = "0.8", features = ["derive"] }
9//! ```
10//!
11//! See the [`SensorData`](macro@SensorData) documentation for usage.
12
13#![deny(missing_docs)]
14
15use proc_macro::TokenStream;
16use quote::quote;
17use syn::{Data, DeriveInput, Error, Expr, Path, parse_macro_input, spanned::Spanned};
18
19/// Derive [`sensor_db::SensorData`], binding a type to a sensor ID.
20///
21/// # Example
22///
23/// ```ignore
24/// use sensor_db::SensorData;
25/// use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
26///
27/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, SensorData)]
28/// #[sensor(id = 0x01, version = 1)]
29/// #[repr(C)]
30/// struct Temperature {
31///     celsius: f32,
32/// }
33/// ```
34///
35/// # Attributes
36///
37/// | Key | Required | Meaning |
38/// |-----|----------|---------|
39/// | `id` | yes | The sensor ID. Any `const` expression of type `u16`. |
40/// | `version` | no (default `0`) | The schema version. Any `const` expression of type `u8`. |
41/// | `crate` | no (default `::sensor_db`) | Path to the `sensor_db` crate, if renamed. |
42///
43/// `id` and `version` take arbitrary constant expressions, not just literals,
44/// so a central ID module — the practice that actually prevents collisions —
45/// works directly:
46///
47/// ```ignore
48/// mod ids {
49///     pub const TEMPERATURE: u16 = 0x01;
50/// }
51///
52/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, SensorData)]
53/// #[sensor(id = ids::TEMPERATURE, version = 1)]
54/// #[repr(C)]
55/// struct Temperature { celsius: f32 }
56/// ```
57///
58/// # What this macro does *not* do
59///
60/// It emits the `SensorData` impl and nothing else. In particular it does not
61/// emit the `zerocopy` derives or a `repr` attribute, because a derive macro
62/// cannot add attributes to the item it is applied to, and because `zerocopy`'s
63/// derives expand to absolute `::zerocopy::` paths — so `zerocopy` has to be a
64/// direct dependency of your crate either way. Injecting its derives would make
65/// that requirement invisible and its absence inscrutable.
66///
67/// Padding is already a compile error from `zerocopy`'s `IntoBytes` derive,
68/// which reports the exact number of wasted bytes. This macro does not
69/// second-guess it.
70#[proc_macro_derive(SensorData, attributes(sensor))]
71pub fn derive_sensor_data(input: TokenStream) -> TokenStream {
72    let input = parse_macro_input!(input as DeriveInput);
73    expand(input)
74        .unwrap_or_else(Error::into_compile_error)
75        .into()
76}
77
78/// The parsed contents of `#[sensor(...)]`.
79struct SensorAttr {
80    id: Option<Expr>,
81    version: Option<Expr>,
82    krate: Option<Path>,
83}
84
85fn expand(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
86    reject_unsupported_shape(&input)?;
87
88    let attr = parse_sensor_attr(&input)?;
89
90    let Some(id) = attr.id else {
91        return Err(Error::new(
92            input.ident.span(),
93            "missing `#[sensor(id = ...)]`\n\
94             help: every `SensorData` type must name the sensor ID it is stored \
95             under, e.g. `#[sensor(id = 0x01)]`",
96        ));
97    };
98
99    // The trait's own default is 0; spelling it here keeps the generated impl
100    // self-describing rather than silently inheriting.
101    let version = attr.version.unwrap_or_else(|| syn::parse_quote!(0u8));
102
103    let krate = attr.krate.unwrap_or_else(|| syn::parse_quote!(::sensor_db));
104
105    let name = &input.ident;
106    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
107
108    // The `u16` / `u8` ascriptions do the range checking: an out-of-range
109    // literal or a const of the wrong type fails here, pointing at the
110    // attribute, so the macro does not need to duplicate the check.
111    Ok(quote! {
112        #[automatically_derived]
113        impl #impl_generics #krate::SensorData for #name #ty_generics #where_clause {
114            const SENSOR_ID: u16 = #id;
115            const SCHEMA_VERSION: u8 = #version;
116        }
117    })
118}
119
120/// `SensorData` requires `FromBytes` + `IntoBytes`, which need a fixed layout.
121/// Catching the shape here gives a message about sensor data rather than a
122/// wall of unsatisfied `zerocopy` bounds.
123fn reject_unsupported_shape(input: &DeriveInput) -> Result<(), Error> {
124    match &input.data {
125        Data::Struct(_) => Ok(()),
126        Data::Enum(_) => Err(Error::new(
127            input.ident.span(),
128            "`SensorData` cannot be derived for an enum\n\
129             note: a stored payload is reinterpreted from raw flash bytes, so it \
130             must have a fixed layout with no invalid bit patterns\n\
131             help: store the discriminant as an integer field in a struct",
132        )),
133        Data::Union(_) => Err(Error::new(
134            input.ident.span(),
135            "`SensorData` cannot be derived for a union\n\
136             note: reading a union from flash cannot know which variant was written\n\
137             help: store a tag alongside the bytes, or give each variant its own \
138             sensor ID",
139        )),
140    }
141}
142
143fn parse_sensor_attr(input: &DeriveInput) -> Result<SensorAttr, Error> {
144    let mut parsed = SensorAttr {
145        id: None,
146        version: None,
147        krate: None,
148    };
149
150    for attr in input.attrs.iter().filter(|a| a.path().is_ident("sensor")) {
151        attr.parse_nested_meta(|meta| {
152            if meta.path.is_ident("id") {
153                set_once(&mut parsed.id, meta.value()?.parse()?, &meta.path, "id")
154            } else if meta.path.is_ident("version") {
155                // Parsed as a literal first so that `version = 256` points at the
156                // attribute instead of at the generated `const`.
157                let value: Expr = meta.value()?.parse()?;
158                check_u8_literal(&value)?;
159                set_once(&mut parsed.version, value, &meta.path, "version")
160            } else if meta.path.is_ident("crate") {
161                set_once(
162                    &mut parsed.krate,
163                    meta.value()?.parse()?,
164                    &meta.path,
165                    "crate",
166                )
167            } else {
168                Err(meta.error(
169                    "unrecognised `sensor` option\n\
170                     note: valid options are `id`, `version` and `crate`",
171                ))
172            }
173        })?;
174    }
175
176    Ok(parsed)
177}
178
179fn set_once<T>(slot: &mut Option<T>, value: T, path: &Path, name: &str) -> Result<(), Error> {
180    if slot.is_some() {
181        return Err(Error::new(
182            path.span(),
183            format!("duplicate `sensor` option `{name}`"),
184        ));
185    }
186    *slot = Some(value);
187    Ok(())
188}
189
190/// A schema version is one byte on flash. A literal that does not fit is worth
191/// rejecting at the attribute, where the number is written.
192fn check_u8_literal(value: &Expr) -> Result<(), Error> {
193    let Expr::Lit(lit) = value else {
194        return Ok(()); // A const path; the `u8` ascription checks it.
195    };
196    let syn::Lit::Int(int) = &lit.lit else {
197        return Ok(());
198    };
199    int.base10_parse::<u8>().map_err(|_| {
200        Error::new(
201            int.span(),
202            format!(
203                "schema version {} does not fit in a `u8`\n\
204                 note: the version is stored as a one-byte tag in front of the payload",
205                int.base10_digits()
206            ),
207        )
208    })?;
209    Ok(())
210}