phoxal-macros 0.14.0

Proc-macros for the phoxal framework: phoxal_api_tree!, #[derive(Runtime)], #[phoxal::runtime].
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! `phoxal_api_tree!` — the single API layer (D60/D61).
//!
//! Grammar. A `topic` is static (`topic state: pubsub State;` → key
//! `<family>/state`) or **dynamic/parameterized**
//! (`topic command(instance): pubsub Command = "component/{instance}/command";` →
//! a builder method taking the params and filling the key template; the body's
//! `ContractBody::TOPIC` is the template). `extends` API inheritance is supported.
//!
//! ```text
//! phoxal_api_tree! {
//!     version y2026_1 {
//!         drive {
//!             enum  StopReason { NoTarget, Estop }
//!             enum  ActuatorAuthority { Active, Stopped }
//!             struct Target { linear_x_mps: f32, angular_z_radps: f32 }
//!             struct State  { target: Target, authority: ActuatorAuthority }
//!             topic target: pubsub Target;
//!             topic state:  pubsub State;
//!         }
//!         map {
//!             struct SubmapRequest  { region: u32 }
//!             struct SubmapResponse { cells: Vec<u8> }
//!             topic submap: query SubmapRequest => SubmapResponse;
//!         }
//!     }
//!     version y2026_2 extends y2026_1 {
//!         // inherits every y2026_1 family/type; overrides drive::Target and adds
//!         // a new `battery` family — inherited types are re-emitted fresh.
//!         drive { struct Target { linear_x_mps: f32, angular_z_radps: f32, curvature: Option<f32> }
//!                 topic target: pubsub Target; }
//!         battery { struct State { soc: f32 } topic state: pubsub State; }
//!     }
//! }
//! ```
//!
//! Each `version` becomes a `pub mod y2026_N` carrying a marker `enum Api {}`
//! (`ApiVersion`), the version-local body/helper types (plain serde types, no
//! `{"v":…}` wrapper — D62), `ContractBody` impls binding each on-bus body to
//! that version, and an api-local `topic` builder module. A `version … extends P`
//! inherits `P`'s effective families: a child family merges into the parent
//! family of the same name (child types/topics override by name), a new child
//! family is added, and every inherited type is re-emitted *fresh* under the
//! child version — same `FAMILY`/`TOPIC`, a different `Api` (D61).
//!
//! Wire identity is **per-type, by transitive shape**: an inherited type re-emits
//! the parent's definition verbatim, so a type that does **not** transitively
//! reference an overridden type is byte-identical to its parent (e.g. a flat
//! `localize::State`). A type that *contains* an overridden type resolves that
//! name to the child's overridden version — e.g. if the child overrides
//! `drive::Target`, the inherited `drive::State { target: Target, … }` embeds the
//! **new** `Target` and is therefore *not* identical to the parent's `State`.
//! That is correct versioning: a contract changes with its dependencies, and the
//! whole change is coherent because one graph runs one API version (D59).

use proc_macro2::TokenStream;
use quote::quote;
use syn::parse::{Parse, ParseStream};
use syn::{Ident, ItemEnum, ItemStruct, Token};

use crate::util::{body_derives, phoxal};

mod kw {
    syn::custom_keyword!(version);
    syn::custom_keyword!(extends);
    syn::custom_keyword!(topic);
    syn::custom_keyword!(pubsub);
    syn::custom_keyword!(query);
}

pub fn expand(input: TokenStream) -> syn::Result<TokenStream> {
    let tree: ApiTree = syn::parse2(input)?;
    tree.expand()
}

struct ApiTree {
    versions: Vec<Version>,
}

struct Version {
    name: Ident,
    extends: Option<Ident>,
    families: Vec<Family>,
}

#[derive(Clone)]
struct Family {
    name: Ident,
    types: Vec<TypeDef>,
    topics: Vec<TopicDef>,
}

#[derive(Clone)]
enum TypeDef {
    Struct(ItemStruct),
    Enum(ItemEnum),
}

impl TypeDef {
    /// The declared name of the type (for inheritance overlay by name).
    fn ident(&self) -> &Ident {
        match self {
            TypeDef::Struct(item) => &item.ident,
            TypeDef::Enum(item) => &item.ident,
        }
    }
}

#[derive(Clone)]
struct TopicDef {
    leaf: Ident,
    kind: TopicKind,
    /// Dynamic-topic params (empty for a static topic). When non-empty the topic
    /// is keyed by a `key_template` instead of `<family>/<leaf>`.
    params: Vec<Ident>,
    /// Key template with `{param}` placeholders (set iff `params` is non-empty).
    key_template: Option<syn::LitStr>,
}

impl TopicDef {
    /// The canonical versionless topic key/pattern: the key template for a dynamic
    /// topic, else `<family>/<leaf>`.
    fn topic_key(&self, family: &str) -> String {
        match &self.key_template {
            Some(t) => t.value(),
            None => format!("{}/{}", family, self.leaf),
        }
    }
}

#[derive(Clone)]
enum TopicKind {
    PubSub(Ident),
    Query { request: Ident, response: Ident },
}

impl Parse for ApiTree {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut versions = Vec::new();
        while !input.is_empty() {
            versions.push(input.parse()?);
        }
        if versions.is_empty() {
            return Err(input.error("phoxal_api_tree! requires at least one `version` block"));
        }
        Ok(ApiTree { versions })
    }
}

impl Parse for Version {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::version>()?;
        let name: Ident = input.parse()?;
        let extends = if input.peek(kw::extends) {
            input.parse::<kw::extends>()?;
            Some(input.parse::<Ident>()?)
        } else {
            None
        };
        let body;
        syn::braced!(body in input);
        let mut families = Vec::new();
        while !body.is_empty() {
            families.push(body.parse()?);
        }
        Ok(Version {
            name,
            extends,
            families,
        })
    }
}

impl Parse for Family {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let name: Ident = input.parse()?;
        let body;
        syn::braced!(body in input);
        let mut types = Vec::new();
        let mut topics = Vec::new();
        while !body.is_empty() {
            // Leading doc-comments / attributes apply to the next item; `topic`
            // declarations take none.
            let attrs = body.call(syn::Attribute::parse_outer)?;
            if body.peek(kw::topic) {
                if let Some(attr) = attrs.first() {
                    return Err(syn::Error::new_spanned(
                        attr,
                        "attributes are not allowed on a `topic` declaration",
                    ));
                }
                topics.push(body.parse()?);
            } else if body.peek(Token![struct]) {
                let mut item: ItemStruct = body.parse()?;
                item.attrs = attrs;
                item.vis = syn::Visibility::Public(syn::token::Pub::default());
                types.push(TypeDef::Struct(item));
            } else if body.peek(Token![enum]) {
                let mut item: ItemEnum = body.parse()?;
                item.attrs = attrs;
                item.vis = syn::Visibility::Public(syn::token::Pub::default());
                types.push(TypeDef::Enum(item));
            } else {
                return Err(body
                    .error("expected `struct`, `enum`, or `topic …;` inside an API family block"));
            }
        }
        Ok(Family {
            name,
            types,
            topics,
        })
    }
}

impl Parse for TopicDef {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        input.parse::<kw::topic>()?;
        let leaf: Ident = input.parse()?;

        // Optional dynamic params: `topic motor_command(instance, name): …`.
        let mut params = Vec::new();
        if input.peek(syn::token::Paren) {
            let content;
            syn::parenthesized!(content in input);
            let parsed =
                syn::punctuated::Punctuated::<Ident, Token![,]>::parse_terminated(&content)?;
            params = parsed.into_iter().collect();
            if params.is_empty() {
                return Err(syn::Error::new_spanned(
                    &leaf,
                    "a dynamic topic must declare at least one param, e.g. `topic foo(id): …`",
                ));
            }
        }

        input.parse::<Token![:]>()?;
        let kind = if input.peek(kw::pubsub) {
            input.parse::<kw::pubsub>()?;
            let body: Ident = input.parse()?;
            TopicKind::PubSub(body)
        } else if input.peek(kw::query) {
            input.parse::<kw::query>()?;
            let request: Ident = input.parse()?;
            input.parse::<Token![=>]>()?;
            let response: Ident = input.parse()?;
            TopicKind::Query { request, response }
        } else {
            return Err(input.error("expected `pubsub <Type>` or `query <Req> => <Resp>`"));
        };

        // A dynamic topic requires a `= "key/{param}/template"`; a static one
        // forbids it (its key is `<family>/<leaf>`).
        let key_template = if input.peek(Token![=]) {
            input.parse::<Token![=]>()?;
            Some(input.parse::<syn::LitStr>()?)
        } else {
            None
        };
        if params.is_empty() && key_template.is_some() {
            return Err(syn::Error::new_spanned(
                &leaf,
                "a static topic must not declare a key template; add params to make it dynamic",
            ));
        }
        if !params.is_empty() && key_template.is_none() {
            return Err(syn::Error::new_spanned(
                &leaf,
                "a dynamic topic requires a key template, e.g. `= \"component/{id}/command\"`",
            ));
        }

        input.parse::<Token![;]>()?;
        Ok(TopicDef {
            leaf,
            kind,
            params,
            key_template,
        })
    }
}

impl ApiTree {
    fn expand(&self) -> syn::Result<TokenStream> {
        let mut out = TokenStream::new();
        // Resolve each version's effective families (inheriting from `extends`)
        // and generate from the resolved set. Inherited types are re-emitted
        // *fresh* under the child version — same `FAMILY`/`TOPIC`, a different
        // `Api` marker — so unchanged contracts are wire-identical by construction
        // while the compile-time `Api` bound stays sound (D61).
        let mut resolved: std::collections::HashMap<String, Vec<Family>> =
            std::collections::HashMap::new();

        for version in &self.versions {
            let effective = match &version.extends {
                None => version.families.clone(),
                Some(parent) => {
                    let base = resolved.get(&parent.to_string()).ok_or_else(|| {
                        syn::Error::new_spanned(
                            parent,
                            format!(
                                "`extends {parent}`: unknown API version (it must be declared \
                                 earlier in the same phoxal_api_tree! invocation)"
                            ),
                        )
                    })?;
                    overlay_families(base, &version.families)
                }
            };
            resolved.insert(version.name.to_string(), effective.clone());
            out.extend(expand_version(&version.name, &effective)?);
        }
        Ok(out)
    }
}

/// Overlay a child version's declared families onto the parent's effective set:
/// a child family merges into the parent family of the same name (child types
/// override parent types by name; child topics override by leaf), and a wholly
/// new child family is appended (D61).
fn overlay_families(base: &[Family], child: &[Family]) -> Vec<Family> {
    let mut result: Vec<Family> = base.to_vec();
    for cf in child {
        if let Some(bf) = result.iter_mut().find(|f| f.name == cf.name) {
            for ct in &cf.types {
                if let Some(slot) = bf.types.iter_mut().find(|t| t.ident() == ct.ident()) {
                    *slot = ct.clone();
                } else {
                    bf.types.push(ct.clone());
                }
            }
            for ctp in &cf.topics {
                if let Some(slot) = bf.topics.iter_mut().find(|t| t.leaf == ctp.leaf) {
                    *slot = ctp.clone();
                } else {
                    bf.topics.push(ctp.clone());
                }
            }
        } else {
            result.push(cf.clone());
        }
    }
    result
}

fn expand_version(name: &Ident, families: &[Family]) -> syn::Result<TokenStream> {
    let phoxal = phoxal();
    let mod_name = name;
    let id = name.to_string();

    let mut family_mods = TokenStream::new();
    for family in families {
        family_mods.extend(family.expand_module()?);
    }

    let topic_mod = expand_topic_module(families)?;

    Ok(quote! {
        pub mod #mod_name {
            //! Dated API version `#id` — version-local wire bodies + topics.

            /// Zero-variant marker identifying this API version (D60).
            #[derive(Clone, Copy, Debug)]
            pub enum Api {}
            impl #phoxal::api::ApiVersion for Api {
                const ID: &'static str = #id;
            }

            #family_mods

            #topic_mod
        }
    })
}

fn expand_topic_module(families: &[Family]) -> syn::Result<TokenStream> {
    let phoxal = phoxal();
    let mut root_methods = TokenStream::new();
    let mut builder_mods = TokenStream::new();

    for family in families {
        let fam = &family.name;
        let fam_str = fam.to_string();

        root_methods.extend(quote! {
            /// Enter the `#fam_str` family topic builder.
            pub fn #fam(self) -> #fam::Builder { #fam::Builder }
        });

        let mut leaf_methods = TokenStream::new();
        for topic in &family.topics {
            let leaf = &topic.leaf;
            let key = topic.topic_key(&fam_str);
            let kind_ty = match &topic.kind {
                TopicKind::PubSub(body) => quote! {
                    #phoxal::bus::PubSub<super::super::#fam::#body>
                },
                TopicKind::Query { request, response } => quote! {
                    #phoxal::bus::Query<
                        super::super::#fam::#request,
                        super::super::#fam::#response,
                    >
                },
            };

            if topic.params.is_empty() {
                // Static topic: a zero-arg leaf returning the fixed key.
                leaf_methods.extend(quote! {
                    #[doc = #key]
                    pub fn #leaf(self) -> #phoxal::bus::Topic<#kind_ty> {
                        #phoxal::bus::Topic::new_static(#key)
                    }
                });
            } else {
                // Dynamic topic: the leaf takes the declared params and fills the
                // key template (named placeholders). Pass `"*"`/`"**"` for a
                // subscribe wildcard; publishing on a wildcard key is rejected.
                let params = &topic.params;
                let template = topic
                    .key_template
                    .as_ref()
                    .expect("dynamic topic has a template");
                leaf_methods.extend(quote! {
                    #[doc = #key]
                    pub fn #leaf(
                        self,
                        #(#params: impl ::core::fmt::Display),*
                    ) -> #phoxal::bus::Topic<#kind_ty> {
                        #phoxal::bus::Topic::new_owned(::std::format!(#template, #(#params = #params),*))
                    }
                });
            }
        }

        builder_mods.extend(quote! {
            pub mod #fam {
                /// Topic builder for the `#fam_str` family.
                pub struct Builder;
                impl Builder {
                    #leaf_methods
                }
            }
        });
    }

    Ok(quote! {
        /// Api-local topic builders (D61). `topic::new()` is the entrypoint;
        /// every leaf binds the topic's family/kind to a version-local body.
        pub mod topic {
            /// Begin a topic path for this API version.
            pub fn new() -> Root {
                Root
            }

            /// Root of the topic builder chain.
            pub struct Root;
            impl Root {
                #root_methods
            }

            #builder_mods
        }
    })
}

impl Family {
    fn expand_module(&self) -> syn::Result<TokenStream> {
        let phoxal = phoxal();
        let fam = &self.name;
        let fam_str = fam.to_string();
        let derives = body_derives();

        let mut types = TokenStream::new();
        for ty in &self.types {
            match ty {
                TypeDef::Struct(item) => {
                    let item = with_pub_fields_struct(item.clone());
                    types.extend(quote! { #derives #item });
                }
                TypeDef::Enum(item) => {
                    types.extend(quote! { #derives #item });
                }
            }
        }

        let mut impls = TokenStream::new();
        for topic in &self.topics {
            // For a dynamic topic the canonical TOPIC is the key *template*
            // (with `{param}` placeholders); for a static topic it is `fam/leaf`.
            let key = topic.topic_key(&fam_str);
            match &topic.kind {
                TopicKind::PubSub(body) => {
                    let family_const = format!("{}::{}", fam_str, body);
                    impls.extend(quote! {
                        impl #phoxal::api::ContractBody for #body {
                            type Api = super::Api;
                            const FAMILY: &'static str = #family_const;
                            const TOPIC: &'static str = #key;
                        }
                    });
                }
                TopicKind::Query { request, response } => {
                    let req_family = format!("{}::{}", fam_str, request);
                    let resp_family = format!("{}::{}", fam_str, response);
                    impls.extend(quote! {
                        impl #phoxal::api::ContractBody for #request {
                            type Api = super::Api;
                            const FAMILY: &'static str = #req_family;
                            const TOPIC: &'static str = #key;
                        }
                        impl #phoxal::api::ContractBody for #response {
                            type Api = super::Api;
                            const FAMILY: &'static str = #resp_family;
                            const TOPIC: &'static str = #key;
                        }
                    });
                }
            }
        }

        Ok(quote! {
            pub mod #fam {
                //! Version-local bodies for the `#fam_str` family.
                #![allow(unused_imports)]
                use super::Api;

                #types
                #impls
            }
        })
    }
}

/// Force every named field of a macro-declared body struct to `pub` so runtime
/// code in other modules can construct and read the wire body directly.
fn with_pub_fields_struct(mut item: ItemStruct) -> ItemStruct {
    if let syn::Fields::Named(named) = &mut item.fields {
        for field in &mut named.named {
            field.vis = syn::Visibility::Public(syn::token::Pub::default());
        }
    }
    item
}