cyclone_attributes/lib.rs
1//! The official Cyclone **attributes**.
2//!
3//! ```text
4//! cyclone-attributes → your source → cyclonec → generated code
5//! ```
6//!
7//! This crate defines [`network`] and [`codec`], and does nothing with them. It
8//! is the syntax half of Cyclone: the part that makes annotated Rust *compile*,
9//! so that `cyclonec` has something to read.
10//!
11//! ```
12//! use cyclone_attributes::*;
13//!
14//! #[network]
15//! #[codec]
16//! struct DeviceState {
17//! #[network(u32)]
18//! #[codec(edge, unity)]
19//! id: u32,
20//!
21//! #[network(f32)]
22//! #[codec(edge)]
23//! temperature: f32,
24//!
25//! #[network(string)]
26//! #[codec(unity)]
27//! display_name: String,
28//! }
29//! ```
30//!
31//! # What it does
32//!
33//! The attributes are **inert markers**. Applied to an item, they remove
34//! themselves and every Cyclone attribute inside it, and hand back the item
35//! otherwise untouched — same fields, same types, same derives, same doc
36//! comments, same spans.
37//!
38//! That removal is the entire implementation, and it exists for one narrow
39//! reason: Rust does not allow an attribute macro on a *field*, so
40//! `#[network(u32)]` cannot compile on its own. An attribute on the struct is
41//! what makes the ones on its fields legal, by consuming them.
42//!
43//! So the annotated struct above compiles to exactly:
44//!
45//! ```
46//! struct DeviceState {
47//! id: u32,
48//! temperature: f32,
49//! display_name: String,
50//! }
51//! ```
52//!
53//! # What it does not do
54//!
55//! Everything else. There is no `Reader`, no `Writer`, no `Encode`, no
56//! `Decode`, no registry, no reflection, no dynamic dispatch, and no generated
57//! code of any kind. It reads no Cyclone type, validates no annotation, and
58//! knows no codec name.
59//!
60//! `cyclonec` reads the annotations out of your **source**, not out of this
61//! crate's expansion, and every semantic question belongs to it:
62//!
63//! - Whether `u32` names a Cyclone type.
64//! - Whether a field declared `u64` may carry `#[network(u32)]`.
65//! - What `edge` or `unity` mean, and which fields each one covers.
66//!
67//! On the last of those especially: a codec name is an identifier **you**
68//! invent. This crate has no list of them, no default, and no opinion — `edge`,
69//! `unity`, `server`, `orange_pi` are all the same to it, which is to say
70//! nothing at all.
71//!
72//! # Scope
73//!
74//! This crate is not a serialization runtime and not a networking library. It is
75//! two attributes and the code that takes them back off.
76
77#![forbid(unsafe_code)]
78
79use proc_macro::{Delimiter, Group, TokenStream, TokenTree};
80
81/// Marks a struct as a Cyclone network model, and declares the Cyclone wire
82/// type of a field.
83///
84/// # On a model
85///
86/// ```
87/// # use cyclone_attributes::network;
88/// #[network]
89/// struct DeviceState {
90/// #[network(u32)]
91/// id: u32,
92/// }
93/// ```
94///
95/// # On a field
96///
97/// `#[network(TYPE)]` declares the field's Cyclone wire type. The declared type
98/// is the schema: `cyclonec` believes the attribute and never infers a Cyclone
99/// type from the Rust one, so this
100///
101/// ```
102/// # use cyclone_attributes::network;
103/// #[network]
104/// struct Reading {
105/// #[network(u32)]
106/// value: u64,
107/// }
108/// ```
109///
110/// declares a `u32` on the wire, whatever the Rust field says. Whether the two
111/// are compatible is a question for `cyclonec`'s validation, later, and not for
112/// this crate at any point.
113///
114/// A field attribute is never expanded on its own — Rust does not permit that.
115/// It is consumed by the attribute on the enclosing model, which is why a model
116/// carrying annotated fields must itself be marked.
117///
118/// # Expansion
119///
120/// The item, with every Cyclone attribute removed and nothing else changed.
121#[proc_macro_attribute]
122pub fn network(_arguments: TokenStream, item: TokenStream) -> TokenStream {
123 strip(item)
124}
125
126/// Marks a struct as taking part in codec generation, and declares which codec
127/// profiles a field belongs to.
128///
129/// # On a model
130///
131/// ```
132/// # use cyclone_attributes::codec;
133/// #[codec]
134/// struct DeviceState {
135/// #[codec(edge)]
136/// id: u32,
137/// }
138/// ```
139///
140/// # On a field
141///
142/// `#[codec(...)]` lists the profiles the field belongs to, in the order they
143/// were written. A field may belong to one, or to many, and there is no limit:
144///
145/// ```
146/// # use cyclone_attributes::codec;
147/// #[codec]
148/// struct DeviceState {
149/// #[codec(edge, unity, admin)]
150/// id: u32,
151///
152/// #[codec(edge)]
153/// temperature: f32,
154/// }
155/// ```
156///
157/// A profile name is an identifier **you** invent. This crate holds no list of
158/// them and gives none of them meaning: `edge`, `unity`, `server`, `client`,
159/// `orange_pi` are identifiers and nothing more. Grouping fields by profile is
160/// `cyclonec`'s job, done by reading your source.
161///
162/// # Expansion
163///
164/// The item, with every Cyclone attribute removed and nothing else changed.
165#[proc_macro_attribute]
166pub fn codec(_arguments: TokenStream, item: TokenStream) -> TokenStream {
167 strip(item)
168}
169
170/// Removes every Cyclone attribute from a token stream, at any depth.
171///
172/// Both attributes do exactly this, which makes the pair order-independent and
173/// idempotent: `#[network] #[codec]` and `#[codec] #[network]` produce the same
174/// item, and so does either one alone. Whichever macro the compiler expands
175/// first takes all of them off; the other, if it survives to run, finds nothing
176/// left to do.
177///
178/// Everything that is not a Cyclone attribute is passed through untouched —
179/// derives, `cfg`, doc comments, other macros' attributes — and every token
180/// keeps its span, so an error in an annotated struct still points at the line
181/// the user wrote.
182fn strip(tokens: TokenStream) -> TokenStream {
183 let mut out: Vec<TokenTree> = Vec::new();
184 let mut tokens = tokens.into_iter().peekable();
185
186 while let Some(token) = tokens.next() {
187 // An outer attribute is `#` followed by a bracketed group. An inner one,
188 // `#![...]`, has a `!` between them and is never a Cyclone attribute, so
189 // the `#` falls through and the group is walked like any other.
190 let is_cyclone_attribute = matches!(&token, TokenTree::Punct(punct) if punct.as_char() == '#')
191 && matches!(
192 tokens.peek(),
193 Some(TokenTree::Group(group))
194 if group.delimiter() == Delimiter::Bracket && names_cyclone(group)
195 );
196
197 if is_cyclone_attribute {
198 tokens.next();
199 continue;
200 }
201
202 match token {
203 // A struct's fields live inside its braces, so the walk has to go in.
204 TokenTree::Group(group) => {
205 let mut rebuilt = Group::new(group.delimiter(), strip(group.stream()));
206 rebuilt.set_span(group.span());
207 out.push(TokenTree::Group(rebuilt));
208 }
209 other => out.push(other),
210 }
211 }
212
213 out.into_iter().collect()
214}
215
216/// Whether an attribute's contents name `network` or `codec`.
217///
218/// Only the path is read, and only its last segment, so `#[network(u32)]` and
219/// `#[cyclone_attributes::network(u32)]` are both recognised. Anything else —
220/// `#[derive(Debug)]`, `#[doc = "…"]`, `#[serde(rename = "network")]` — stops at
221/// the first token that cannot be part of a path and is left alone.
222fn names_cyclone(attribute: &Group) -> bool {
223 let mut last_segment = None;
224
225 for token in attribute.stream() {
226 match token {
227 TokenTree::Ident(ident) => last_segment = Some(ident.to_string()),
228 TokenTree::Punct(punct) if punct.as_char() == ':' => {}
229 _ => break,
230 }
231 }
232
233 matches!(last_segment.as_deref(), Some("network") | Some("codec"))
234}