layline_derive/lib.rs
1//! Derive macros for `layline`: `Layout`, `Message`, `FieldCodec` and `Dispatch`.
2//!
3//! Each attribute, and each key inside it, may appear once.
4//! A rejected type still implements its trait, so the build reports only the real error.
5
6use proc_macro::TokenStream;
7
8mod attr;
9mod check;
10mod claim;
11mod codec;
12mod dispatch;
13mod layout;
14mod message;
15#[cfg(test)]
16mod refusals;
17mod root;
18mod stub;
19mod ty;
20mod width;
21
22fn refused(err: syn::Error, stub: proc_macro2::TokenStream) -> TokenStream {
23 let mut out = err.to_compile_error();
24 out.extend(stub);
25 out.into()
26}
27
28/// Derives `Layout` for a fixed-size struct.
29///
30/// Fields are laid out in declaration order and must cover every bit.
31/// `decode` returns `Result<Self, ParseError>` if the struct uses `#[magic]`, `#[checksum]`,
32/// `#[range]`, `prefix_value`, `internal` or a byte-mode `bool`. Otherwise it returns `Self`.
33///
34/// # Container attributes
35///
36/// Choose one size:
37///
38/// - `#[layout(bits = N)]`: `N` bits of bit fields. `N` is a multiple of 8.
39/// - `#[layout(bytes = N)]`: `N` bytes of scalars, arrays and nested layouts. A `bool` is one
40/// byte: decode reads 0 as `false` and 1 as `true` and refuses any other byte with
41/// `ParseError::Malformed`, and encode writes 0 or 1. For a flag byte the format sets with any
42/// nonzero value, declare `#[codec(8)] flag: layline::Nonzero`.
43/// - `#[layout(words = N)]`: `N` 16-bit words of bit fields.
44///
45/// Optional keys:
46///
47/// - `endian = le | be`: byte order. Default `le`.
48/// - `order = lsb | msb`: bit order for `bits` and `words`. With `msb`, the first field takes the
49/// most significant bits. Default `lsb`.
50/// - `prefix = K`: the low `K` bits hold a `Dispatch` id. Sets `Layout::PREFIX_BITS`. `bits` only.
51/// - `prefix_value = V`: the prefix value. Encode writes it and decode checks it. Needs `prefix`.
52/// - `view`: also generates `<Name>View`, which reads and writes the fields in place in a byte
53/// buffer. A view is unchecked, so a reader can inspect a corrupt record: `verify()` runs the
54/// checks `decode` runs on magic bytes, `prefix_value` and checksums, `checked(&wire)` views
55/// only bytes that pass them, and `seal()` rewrites the prefix, magic and checksums after the
56/// setters. Not allowed with `#[range]` or a byte-mode `bool`.
57/// - `truncate`: encode keeps the low `N` bits of a value wider than its `#[bits(N)]` field, as a
58/// hardware register does, instead of panicking. Decode is unchanged. Without it, encode panics
59/// rather than write bits that read back as a different value. A view's setters always keep the
60/// low bits.
61/// - `internal`: marks a block that `Message` generates. Makes `decode` fallible.
62/// - `crate = path`: the path to `layline`. Default `::layline`.
63///
64/// # Field attributes
65///
66/// - `#[bits(N)]`: the width in bits, for `bits` and `words`. The type is an integer, `bool`,
67/// `U<N>`, `I<N>`, or a `FieldCodec` whose `BITS` is `N`. In `words`, a field fits in one word.
68/// - `#[codec(N)]`: a `FieldCodec` stored as an 8, 16, 32 or 64-bit integer, or an array of
69/// them. `bytes` only.
70/// - `#[bytes(N)]`: a nested layout of `N` bytes, or an array of them. `N` must match its
71/// `WIRE_BYTES`. `bytes` and `words` only.
72/// - `#[at(bit = N)]`, `#[at(byte = N)]`: the field's expected position. The build fails if the
73/// widths put it elsewhere. `STATED` lists these positions.
74/// - `#[overlay(name: T)]`: adds `name` and `set_name`, which read and write the field's bits as
75/// the `FieldCodec` `T`. `bits` and `words` only.
76/// - `#[magic(0xAA55)]`, `#[magic(b"\x7fELF")]`: fixed bytes. Decode checks them and encode
77/// writes them. `bytes` only.
78/// - `#[checksum(Alg, over = a..=b)]`: a checksum over fields `a` to `b`. Decode verifies it and
79/// encode computes it. `bytes` only.
80/// - `#[range(lo..=hi)]`, `#[range(..=hi)]`, `#[range(lo..)]`: the allowed values. Decode rejects
81/// others.
82///
83/// # Word-sized layouts
84///
85/// A `bits = N` layout with `N <= 64` loads into one native register (`u8`, `u16`, `u32` or `u64`,
86/// the smallest that holds `N` bits), and `decode`, `encode` and the view's accessors are inline
87/// shifts and masks on it. When `N` is 8, 16, 32 or 64 the layout also has
88/// `from_bits(uN) -> Self` and `to_bits(&self) -> uN`, which skip the byte array: bit `n` of the
89/// integer is container bit `n`, so `from_bits(u32::from_le_bytes(wire))` is `decode(&wire)` for
90/// an `endian = le` layout. `from_bits` returns what `decode` returns.
91///
92/// `Layout` rejects the `Message` attributes `#[count]`, `#[len]`, `#[stride]`, `#[fill]`,
93/// `#[seek]`, `#[text]`, `#[until]`, `#[var]`, `#[message]`, `#[switch]`, `#[when]` and
94/// `#[align]` with a clear error.
95///
96/// ```
97/// # use layline::{FieldCodec, Layout};
98/// # #[derive(FieldCodec, Debug, Clone, PartialEq)] #[bits(4)] pub struct State(pub u8);
99/// #[derive(Layout)]
100/// #[layout(bits = 32)]
101/// pub struct StatusWord {
102/// #[bits(3)] pub version: u8,
103/// #[bits(1)] pub urgent: bool,
104/// #[bits(12)] #[at(bit = 4)] pub sequence: u16,
105/// #[bits(4)] pub state: State,
106/// #[bits(10)] pub payload_len: u16,
107/// #[bits(2)] pub spare: u8,
108/// }
109/// ```
110#[proc_macro_derive(
111 Layout,
112 attributes(
113 layout, bits, codec, bytes, at, overlay, magic, checksum, range, count, len, stride, fill,
114 seek, text, until, var, message, switch, when, align
115 )
116)]
117pub fn derive_layout(input: TokenStream) -> TokenStream {
118 let input = syn::parse_macro_input!(input as syn::DeriveInput);
119 match layout::derive(&input) {
120 Ok(tokens) => tokens.into(),
121 Err(err) => refused(err, stub::layout(&input)),
122 }
123}
124
125/// Derives `Dispatch` for an enum of `Layout` payloads selected by an id.
126///
127/// A payload type used by only one variant also gets `From<T>` and `Slot<T>`.
128///
129/// # Container attributes
130///
131/// - `#[dispatch(id = u16)]`: the id type.
132/// - `prefix = K`: the id is the low `K` bits of each payload. Sets `Dispatch::PREFIX_BITS`.
133/// Each payload must declare `#[layout(prefix = K)]`.
134/// - `crate = path`: the path to `layline`. Default `::layline`.
135///
136/// # Variant attributes
137///
138/// - `#[value(N)]`: the variant's id.
139/// - `#[other]`: the fallback `Unknown { id, body }`, for unknown ids and payloads that fail to
140/// decode. `body` is `&'a [u8]` if the enum has a lifetime, and `Vec<u8>` otherwise.
141///
142/// ```
143/// # use layline::{Dispatch, Layout};
144/// # #[derive(Layout, Debug, Clone, PartialEq)] #[layout(bytes = 2)] pub struct Sample { pub a: u16 }
145/// # #[derive(Layout, Debug, Clone, PartialEq)] #[layout(bytes = 2)] pub struct TimePulse { pub a: u16 }
146/// #[derive(Dispatch)]
147/// #[dispatch(id = u16)]
148/// pub enum Payload<'a> {
149/// #[value(4)] Sample(Sample),
150/// #[value(13)] TimePulse(TimePulse),
151/// #[other] Unknown { id: u16, body: &'a [u8] },
152/// }
153/// ```
154#[proc_macro_derive(Dispatch, attributes(dispatch, value, other))]
155pub fn derive_dispatch(input: TokenStream) -> TokenStream {
156 let input = syn::parse_macro_input!(input as syn::DeriveInput);
157 match dispatch::derive(&input) {
158 Ok(tokens) => tokens.into(),
159 Err(err) => refused(err, stub::dispatch(&input)),
160 }
161}
162
163/// Derives `FieldCodec` and `WireInt` for an integer newtype or an enum of named values, and
164/// `FieldCodec` for a group of bit fields.
165///
166/// Every `N`-bit value decodes.
167///
168/// # Container attributes
169///
170/// - `#[bits(N)]`: the width, 1 to 64. The newtype's integer and every variant's value must fit.
171/// - `#[bits(N, crate = path)]`: the path to `layline`. Default `::layline`.
172///
173/// # Groups
174///
175/// A struct with named fields is a group: each field states `#[bits(K)]`, as in a
176/// `#[layout(bits = N)]`, and the widths must add up to `N`. A group is a field narrower than a
177/// whole number of bytes with fields of its own, so it can be an `#[overlay]` or a `#[bits(N)]`
178/// field. Fields are an integer, `bool`, `U<K>`, `I<K>` or a `FieldCodec`. Group keys:
179///
180/// - `order = lsb | msb`: with `msb`, the first field takes the most significant bits. Default
181/// `lsb`.
182/// - `truncate`: `to_raw` keeps the low `K` bits of a value wider than its field, instead of
183/// panicking.
184///
185/// ```
186/// # use layline::FieldCodec;
187/// #[derive(FieldCodec)]
188/// #[bits(21)]
189/// pub struct Descriptor {
190/// #[bits(13)] pub words: u16,
191/// #[bits(8)] pub buffer_index: u8,
192/// }
193///
194/// assert_eq!(Descriptor { words: 1024, buffer_index: 42 }.to_raw(), 42 << 13 | 1024);
195/// ```
196///
197/// # Variant attributes
198///
199/// - `#[value(N)]`: the raw value of a unit variant. An integer discriminant, `Variant = N`,
200/// states it too. A variant with neither is refused: its position is not a value, unless the
201/// enum is `#[repr(u8)]`, `#[repr(u16)]`, `#[repr(u32)]` or `#[repr(u64)]`. Rust then defines
202/// it, as zero for the first variant and one past the variant before otherwise, so the raw value
203/// is what `as` gives. An implicit variant after a `#[value(N)]` or `#[other]` one is refused,
204/// since that variant's raw value is not its Rust discriminant.
205/// - `#[other]`: a one-field variant, over an unsigned integer, for every unlisted value. Without
206/// it, the variants must list every `N`-bit value.
207///
208/// ```
209/// # use layline::FieldCodec;
210/// #[derive(FieldCodec)]
211/// #[bits(15)]
212/// pub struct TrackNumber(u16);
213///
214/// #[derive(FieldCodec)]
215/// #[bits(3)]
216/// pub enum Identity {
217/// #[value(0)] Pending,
218/// #[value(2)] Friend,
219/// #[other] Undefined(u8),
220/// }
221/// ```
222#[proc_macro_derive(FieldCodec, attributes(bits, value, other))]
223pub fn derive_field_codec(input: TokenStream) -> TokenStream {
224 let input = syn::parse_macro_input!(input as syn::DeriveInput);
225 match codec::derive(&input) {
226 Ok(tokens) => tokens.into(),
227 Err(err) => refused(err, stub::field_codec(&input)),
228 }
229}
230
231/// Derives `Message` for a variable-size struct or enum, or `Choice` for an enum that
232/// `#[switch]` selects.
233///
234/// Consecutive plain fields become a hidden `#[derive(Layout)]` struct. Encode fills in count,
235/// length, offset, discriminant and flag fields from the fields they describe. In a byte-mode
236/// message a `bool` is one strict byte, as in a `bytes = N` layout.
237///
238/// # Container attributes
239///
240/// - `#[message(endian = le | be)]`: byte order. Default `le`.
241/// - `#[message(bits)]`, `#[message(bits, order = lsb | msb)]`: all fields are bit fields, padded
242/// with zero bits to a whole byte. Default order `lsb`.
243/// - `#[message(needs(a: u8, b: u16))]`: parameters the parent message supplies. They become
244/// `Message::Ctx`, a generated `<Name>Ctx` struct. The holder writes a parameter, so encode
245/// cannot derive it: encode panics when a `#[count]`, `#[len]` or `#[switch]` it drives
246/// disagrees with the value.
247/// - `#[message(closed)]`: on an enum, an unknown discriminant fails with
248/// `ParseError::Malformed`.
249/// - `#[message(crate = path)]`: the path to `layline`. Default `::layline`.
250///
251/// # Collection attributes
252///
253/// A `Vec<T>` or `Box<[T]>` field takes one of these:
254///
255/// - `#[count(f)]`: `f` elements. `f` is an earlier field, or `hdr.f` in an earlier nested layout.
256/// - `#[count(f * f)]`: `f` squared elements.
257/// - `#[count(f, scale = S, offset = O, cap = N)]`: `f * S + O` elements. Decode rejects more
258/// than `N`.
259/// - `#[len(f)]`: `f` bytes. Takes the same keys. Also sizes a `#[text]` string or a `#[switch]`
260/// body.
261/// - `#[fill]`, `#[fill(cap = N)]`: whole elements until the message ends.
262/// - `#[until(b)]`: bytes up to the terminator `b`. Decode consumes it and encode appends it.
263/// - `#[until(mask = M)]`: elements up to and including the first whose first byte has the `M`
264/// bits set.
265///
266/// # Field attributes
267///
268/// - `#[stride(f)]`, `#[stride(f, scale = S, offset = O)]`: the byte size of one element. Use with
269/// `#[count]`.
270/// - `#[seek(f)]`: read at the byte offset in `f`, counted from the start of the message. An
271/// `Option<T>` at offset zero is `None`.
272/// - `#[at(byte = N)]`: the byte offset where the field starts.
273/// - `#[bytes(N)]`: the size of a nested layout, one element, a `#[switch]` body, or a NUL-padded
274/// `#[text]` string.
275/// - `#[codec(N)]`: a `FieldCodec` stored as an 8, 16, 32 or 64-bit integer.
276/// - `#[var]`: a `VarCodec` value, whose size is read from the wire.
277/// - `#[text]`, `#[text(Codec)]`: a `String`, as UTF-8 or through the `TextCodec` `Codec`.
278/// - `#[message]`: a nested `Message`, boxed or not.
279/// - `#[with(f, g)]`: earlier fields passed, in order, as the nested message's `needs`. Use with
280/// `#[message]`.
281/// - `#[switch(f)]`: an enum whose variant `f` selects. `#[switch(..)]` selects by the remaining
282/// length.
283/// - `#[when(flags & MASK)]`, `#[when(flag)]`: an `Option<T>` present when the bits are set.
284/// Encode sets them for `Some` and clears them for `None`.
285/// - `#[when(flags & MASK == 0)]`, `#[when(!flag)]`: an `Option<T>` present when the bits are
286/// clear, as with a flag that says a default applies. Encode clears them for `Some` and sets
287/// them for `None`. `!(flags & MASK)` is refused: on an integer, `!` flips the bits.
288/// - `#[when(n > 0)]`: an `Option<T>` present when `n` is non-zero. Use with `#[seek]`. `n` is the
289/// record's exact byte length: decode refuses a record of any other length, and encode writes
290/// the length. With `#[align(N)]`, `n` does not count the padding up to a multiple of `N`
291/// bytes, and the record may end anywhere from `n` to that bound, as a block that states its
292/// own size, padding included, does. For a number that only marks presence, use `#[seek]`
293/// alone: an offset of zero is `None`.
294/// - `#[align(N)]`: zero bytes after a field, up to the next multiple of `N` bytes counted from
295/// the field's first byte, that its length does not count. Use with a `#[len(n)]` collection,
296/// string or switch, or a `#[seek]` record with `#[when(n > 0)]`. `n` holds the field's own
297/// length. Decode skips the padding without reading it, and encode writes zeros. A RIFF chunk
298/// is `#[len(size)] #[align(2)] body: Vec<u8>`.
299/// - `#[fill]` on an `Option<T>`: present when bytes remain.
300/// - `#[magic(0xFE)]`, `#[magic(b"SEAL")]`: fixed bytes. Decode checks them and encode writes
301/// them.
302/// - `#[checksum(Alg, over = a..=b)]`: a checksum over fields `a` to `b`. Decode verifies it and
303/// encode computes it.
304/// - `#[range(lo..=hi)]`: the allowed values. Decode rejects others, and encode panics on them,
305/// checking a derived length or offset once it is known.
306///
307/// # Borrowed fields
308///
309/// A struct with one lifetime, `Name<'a>`, implements `MessageRef<'a>` instead of `Message`: its
310/// `&'a [u8]` and `&'a [u8; N]` fields are views of the bytes it decodes from, so decode needs
311/// no allocator. Size a `&'a [u8]` with `#[len(n)]`, `#[count(n)]`, `#[bytes(N)]` or `#[fill]`;
312/// `&'a [u8; N]` is `N` bytes. Encode writes each run in one piece and states its length as for
313/// a `Vec<u8>`. A borrowing message takes no `needs(..)`, and no other message can hold it.
314///
315/// ```
316/// use layline::{Message, MessageRef};
317///
318/// #[derive(Message, Debug, PartialEq)]
319/// pub struct Chunk<'a> {
320/// pub offset: u32,
321/// #[fill]
322/// pub data: &'a [u8],
323/// }
324///
325/// let wire = [0x10, 0, 0, 0, 0xAA, 0xBB];
326/// let (chunk, used) = Chunk::decode(&wire).unwrap();
327/// assert_eq!((chunk.offset, chunk.data, used), (0x10, &[0xAA, 0xBB][..], 6));
328/// ```
329///
330/// # Bit message attributes
331///
332/// With `#[message(bits)]`:
333///
334/// - `#[bits(N)]`: the width in bits, 1 to 64. `bool` is 1 bit. `U<N>` and `I<N>` are `N` bits.
335/// - `#[present]`: an `Option<T>` preceded by its own presence bit.
336/// - `#[when(..)]`: as above.
337/// - `#[var]`: a `BitCodec` value, whose width is read from the wire.
338///
339/// # Variant attributes
340///
341/// - `#[value(N)]`: the discriminant. The payload is a `Message`, a scalar, or a `#[bytes(N)]`
342/// layout.
343/// - `#[other]`: a one-field variant for every unlisted discriminant. It holds `Vec<u8>`, or
344/// `[u8; N]` in a fixed-size enum.
345///
346/// ```
347/// # use layline::{Layout, Message};
348/// # #[derive(Message, Debug, Clone, PartialEq)] #[message(closed)]
349/// # pub enum Body { #[value(0)] A(u8), #[value(1)] B(u8) }
350/// # #[derive(Layout, Debug, Clone, PartialEq)] #[layout(bytes = 2)] pub struct Entry { pub a: u16 }
351/// #[derive(Layout, Debug, Clone, PartialEq)]
352/// #[layout(bits = 24)]
353/// pub struct Header {
354/// #[bits(2)] pub kind: u8,
355/// #[bits(4)] pub n_entries: u8,
356/// #[bits(2)] pub flags: u8,
357/// #[bits(6)] pub table_offset: u8,
358/// #[bits(10)] pub spare: u16,
359/// }
360///
361/// #[derive(Message)]
362/// pub struct Packet {
363/// #[bytes(3)] pub header: Header,
364/// #[when(header.flags & 0x01)] pub stamp: Option<u16>,
365/// #[switch(header.kind)] pub body: Body,
366/// #[count(header.n_entries)] #[seek(header.table_offset)] #[bytes(2)]
367/// pub entries: Vec<Entry>,
368/// }
369/// ```
370#[proc_macro_derive(
371 Message,
372 attributes(
373 message, count, len, stride, fill, seek, at, codec, bits, bytes, text, until, var, switch,
374 when, with, present, checksum, magic, value, other, range, align
375 )
376)]
377pub fn derive_message(input: TokenStream) -> TokenStream {
378 let input = syn::parse_macro_input!(input as syn::DeriveInput);
379 match message::derive(&input) {
380 Ok(tokens) => tokens.into(),
381 Err(err) => refused(err, stub::message(&input)),
382 }
383}