sensor-db-derive 0.1.0

Derive macro for sensor-db's SensorData trait
Documentation
//! Derive macro for [`sensor_db::SensorData`].
//!
//! This crate is an implementation detail of the `sensor-db` crate's `derive`
//! feature. Use it through that feature rather than depending on it directly:
//!
//! ```toml
//! sensor-db = { version = "0.1", features = ["derive"] }
//! zerocopy = { version = "0.8", features = ["derive"] }
//! ```
//!
//! See the [`SensorData`](macro@SensorData) documentation for usage.

#![deny(missing_docs)]

use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Error, Expr, Path, parse_macro_input, spanned::Spanned};

/// Derive [`sensor_db::SensorData`], binding a type to a sensor ID.
///
/// # Example
///
/// ```ignore
/// use sensor_db::SensorData;
/// use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};
///
/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, SensorData)]
/// #[sensor(id = 0x01, version = 1)]
/// #[repr(C)]
/// struct Temperature {
///     celsius: f32,
/// }
/// ```
///
/// # Attributes
///
/// | Key | Required | Meaning |
/// |-----|----------|---------|
/// | `id` | yes | The sensor ID. Any `const` expression of type `u16`. |
/// | `version` | no (default `0`) | The schema version. Any `const` expression of type `u8`. |
/// | `crate` | no (default `::sensor_db`) | Path to the `sensor_db` crate, if renamed. |
///
/// `id` and `version` take arbitrary constant expressions, not just literals,
/// so a central ID module — the practice that actually prevents collisions —
/// works directly:
///
/// ```ignore
/// mod ids {
///     pub const TEMPERATURE: u16 = 0x01;
/// }
///
/// #[derive(FromBytes, IntoBytes, KnownLayout, Immutable, SensorData)]
/// #[sensor(id = ids::TEMPERATURE, version = 1)]
/// #[repr(C)]
/// struct Temperature { celsius: f32 }
/// ```
///
/// # What this macro does *not* do
///
/// It emits the `SensorData` impl and nothing else. In particular it does not
/// emit the `zerocopy` derives or a `repr` attribute, because a derive macro
/// cannot add attributes to the item it is applied to, and because `zerocopy`'s
/// derives expand to absolute `::zerocopy::` paths — so `zerocopy` has to be a
/// direct dependency of your crate either way. Injecting its derives would make
/// that requirement invisible and its absence inscrutable.
///
/// Padding is already a compile error from `zerocopy`'s `IntoBytes` derive,
/// which reports the exact number of wasted bytes. This macro does not
/// second-guess it.
#[proc_macro_derive(SensorData, attributes(sensor))]
pub fn derive_sensor_data(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    expand(input)
        .unwrap_or_else(Error::into_compile_error)
        .into()
}

/// The parsed contents of `#[sensor(...)]`.
struct SensorAttr {
    id: Option<Expr>,
    version: Option<Expr>,
    krate: Option<Path>,
}

fn expand(input: DeriveInput) -> Result<proc_macro2::TokenStream, Error> {
    reject_unsupported_shape(&input)?;

    let attr = parse_sensor_attr(&input)?;

    let Some(id) = attr.id else {
        return Err(Error::new(
            input.ident.span(),
            "missing `#[sensor(id = ...)]`\n\
             help: every `SensorData` type must name the sensor ID it is stored \
             under, e.g. `#[sensor(id = 0x01)]`",
        ));
    };

    // The trait's own default is 0; spelling it here keeps the generated impl
    // self-describing rather than silently inheriting.
    let version = attr.version.unwrap_or_else(|| syn::parse_quote!(0u8));

    let krate = attr.krate.unwrap_or_else(|| syn::parse_quote!(::sensor_db));

    let name = &input.ident;
    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    // The `u16` / `u8` ascriptions do the range checking: an out-of-range
    // literal or a const of the wrong type fails here, pointing at the
    // attribute, so the macro does not need to duplicate the check.
    Ok(quote! {
        #[automatically_derived]
        impl #impl_generics #krate::SensorData for #name #ty_generics #where_clause {
            const SENSOR_ID: u16 = #id;
            const SCHEMA_VERSION: u8 = #version;
        }
    })
}

/// `SensorData` requires `FromBytes` + `IntoBytes`, which need a fixed layout.
/// Catching the shape here gives a message about sensor data rather than a
/// wall of unsatisfied `zerocopy` bounds.
fn reject_unsupported_shape(input: &DeriveInput) -> Result<(), Error> {
    match &input.data {
        Data::Struct(_) => Ok(()),
        Data::Enum(_) => Err(Error::new(
            input.ident.span(),
            "`SensorData` cannot be derived for an enum\n\
             note: a stored payload is reinterpreted from raw flash bytes, so it \
             must have a fixed layout with no invalid bit patterns\n\
             help: store the discriminant as an integer field in a struct",
        )),
        Data::Union(_) => Err(Error::new(
            input.ident.span(),
            "`SensorData` cannot be derived for a union\n\
             note: reading a union from flash cannot know which variant was written\n\
             help: store a tag alongside the bytes, or give each variant its own \
             sensor ID",
        )),
    }
}

fn parse_sensor_attr(input: &DeriveInput) -> Result<SensorAttr, Error> {
    let mut parsed = SensorAttr {
        id: None,
        version: None,
        krate: None,
    };

    for attr in input.attrs.iter().filter(|a| a.path().is_ident("sensor")) {
        attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("id") {
                set_once(&mut parsed.id, meta.value()?.parse()?, &meta.path, "id")
            } else if meta.path.is_ident("version") {
                // Parsed as a literal first so that `version = 256` points at the
                // attribute instead of at the generated `const`.
                let value: Expr = meta.value()?.parse()?;
                check_u8_literal(&value)?;
                set_once(&mut parsed.version, value, &meta.path, "version")
            } else if meta.path.is_ident("crate") {
                set_once(
                    &mut parsed.krate,
                    meta.value()?.parse()?,
                    &meta.path,
                    "crate",
                )
            } else {
                Err(meta.error(
                    "unrecognised `sensor` option\n\
                     note: valid options are `id`, `version` and `crate`",
                ))
            }
        })?;
    }

    Ok(parsed)
}

fn set_once<T>(slot: &mut Option<T>, value: T, path: &Path, name: &str) -> Result<(), Error> {
    if slot.is_some() {
        return Err(Error::new(
            path.span(),
            format!("duplicate `sensor` option `{name}`"),
        ));
    }
    *slot = Some(value);
    Ok(())
}

/// A schema version is one byte on flash. A literal that does not fit is worth
/// rejecting at the attribute, where the number is written.
fn check_u8_literal(value: &Expr) -> Result<(), Error> {
    let Expr::Lit(lit) = value else {
        return Ok(()); // A const path; the `u8` ascription checks it.
    };
    let syn::Lit::Int(int) = &lit.lit else {
        return Ok(());
    };
    int.base10_parse::<u8>().map_err(|_| {
        Error::new(
            int.span(),
            format!(
                "schema version {} does not fit in a `u8`\n\
                 note: the version is stored as a one-byte tag in front of the payload",
                int.base10_digits()
            ),
        )
    })?;
    Ok(())
}