Skip to main content

day_macros/
lib.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Compile-time macros for Day.
5//!
6//! [`build_path!`]: SVG path data in, a `PathBuilder` method chain out. [`Observable`]
7//! (`#[derive]`): a struct in, typed per-field accessors for day-model out, with
8//! [`observable_impls!`] as the same expansion for derives layered on it. [`macro@builder`]: a
9//! piece's builder trait and its `Decorated` forwarding, generated from the inherent impl.
10
11mod builder;
12mod java;
13mod obs;
14mod svg;
15
16use proc_macro::TokenStream;
17
18/// Keep a WASM ID record's archive member in the final link, including unused helpers.
19/// The public declaration frontend remains `id!`; this attribute is its linker plumbing.
20#[doc(hidden)]
21#[proc_macro_attribute]
22pub fn retain_element_id(_: TokenStream, item: TokenStream) -> TokenStream {
23    use std::sync::atomic::{AtomicUsize, Ordering};
24    static NEXT: AtomicUsize = AtomicUsize::new(0);
25    let serial = NEXT.fetch_add(1, Ordering::Relaxed);
26    let mut out = item;
27    // An export roots the archive member containing the custom section. A unique suffix
28    // also permits caller macros to repeat the same family at one source location.
29    let anchor: TokenStream = format!(
30        r#"#[doc(hidden)]
31        #[unsafe(export_name = concat!("__day_id_anchor_", env!("CARGO_PKG_NAME"), "_",
32            env!("CARGO_PKG_VERSION"), "_", module_path!(), "_", "{serial}"))]
33        extern "C" fn __day_id_link_anchor() {{}}
34        "#
35    )
36    .parse()
37    .expect("valid element ID anchor");
38    out.extend(anchor);
39    out
40}
41
42/// Turn SVG path data into a `PathBuilder` chain, at compile time.
43///
44/// ```ignore
45/// let heart = build_path!("M 12,21 C 2,14 2,7 7,5 c 3,-1 5,1 5,3 …").build();
46/// d.fill(heart, CORAL);
47/// ```
48///
49/// The whole SVG 1.1 path grammar is accepted: absolute and relative commands, `H`/`V`, the
50/// smooth forms `S`/`T`, elliptical arcs, implicit command repetition, and SVG's number syntax
51/// (`1e2`, `.5.5`, `10-5`). Malformed data is a compile error naming the offending character,
52/// not a path that silently draws nothing.
53///
54/// The result is a `PathBuilder`, so the fill rule and any further segments still chain on:
55///
56/// ```ignore
57/// build_path!("M0,0 h10 v10 h-10 Z").rule(FillRule::EvenOdd).build()
58/// ```
59///
60/// Arcs are converted to cubics here, once, rather than by each of the nine backends at draw
61/// time, because an arc is the one command with no counterpart in the 2-D APIs Day draws through.
62///
63/// Everything is evaluated at compile time, so a path costs the same at runtime as writing the
64/// method chain by hand: there is no string left in the binary and no parsing on the draw path.
65#[proc_macro]
66pub fn build_path(input: TokenStream) -> TokenStream {
67    let literal = match string_literal(input) {
68        Ok(s) => s,
69        Err(e) => return compile_error(&e),
70    };
71    let segs = match svg::parse(&literal) {
72        Ok(s) => s,
73        Err(e) => {
74            return compile_error(&format!(
75                "build_path!: {} at offset {} in {literal:?}",
76                e.message, e.at
77            ));
78        }
79    };
80    let mut code = String::from("day::prelude::PathBuilder::new()");
81    for seg in &segs {
82        match seg {
83            svg::Seg::Move(x, y) => {
84                code.push_str(&format!(".move_to({})", point(*x, *y)));
85            }
86            svg::Seg::Line(x, y) => {
87                code.push_str(&format!(".line_to({})", point(*x, *y)));
88            }
89            svg::Seg::Quad(cx, cy, x, y) => {
90                code.push_str(&format!(".quad_to({}, {})", point(*cx, *cy), point(*x, *y)));
91            }
92            svg::Seg::Cubic(ax, ay, bx, by, x, y) => {
93                code.push_str(&format!(
94                    ".cubic_to({}, {}, {})",
95                    point(*ax, *ay),
96                    point(*bx, *by),
97                    point(*x, *y)
98                ));
99            }
100            svg::Seg::Close => code.push_str(".close()"),
101        }
102    }
103    match code.parse() {
104        Ok(ts) => ts,
105        Err(e) => compile_error(&format!("build_path!: generated code did not parse: {e}")),
106    }
107}
108
109/// A `Point::new(x, y)` literal. Coordinates are emitted with full `f64` precision so the
110/// generated chain is exactly the path that was parsed.
111fn point(x: f64, y: f64) -> String {
112    format!("day::prelude::Point::new({x:?}, {y:?})")
113}
114
115/// Pull the single string literal out of the macro input, rejecting anything else.
116///
117/// Done by hand rather than with `syn`: the accepted input is one literal, and a parser
118/// framework would be the crate's only dependency.
119fn string_literal(input: TokenStream) -> Result<String, String> {
120    let mut trees = input.into_iter();
121    let first = trees.next().ok_or_else(|| {
122        "build_path! takes an SVG path string, e.g. build_path!(\"M0,0 L10,10\")".to_string()
123    })?;
124    if trees.next().is_some() {
125        return Err("build_path! takes exactly one string literal".to_string());
126    }
127    let text = match first {
128        proc_macro::TokenTree::Literal(l) => l.to_string(),
129        other => return Err(format!("expected a string literal, found `{other}`")),
130    };
131    // `Literal::to_string` gives the source spelling, quotes and escapes included, so a plain
132    // literal has to be unescaped by hand. A raw string does not (that is what raw means).
133    let trimmed = text.trim();
134    if let Some(rest) = trimmed.strip_prefix('r') {
135        let hashes = rest.len() - rest.trim_start_matches('#').len();
136        let inner = rest
137            .trim_start_matches('#')
138            .strip_prefix('"')
139            .ok_or_else(|| "expected a string literal".to_string())?;
140        let end = inner
141            .len()
142            .checked_sub(hashes + 1)
143            .ok_or_else(|| "expected a string literal".to_string())?;
144        return Ok(inner[..end].to_string());
145    }
146    let body = trimmed
147        .strip_prefix('"')
148        .and_then(|s| s.strip_suffix('"'))
149        .ok_or_else(|| format!("expected a string literal, found `{trimmed}`"))?;
150    unescape(body)
151}
152
153/// Expand Rust's string escapes.
154///
155/// The line continuation is the one that matters here: `\` at end of line eats the newline and
156/// the next line's leading whitespace, which is how a long path stays readable across several
157/// source lines. Without this the backslash reaches the path parser and fails the build on
158/// exactly the paths most worth writing that way.
159fn unescape(s: &str) -> Result<String, String> {
160    let mut out = String::with_capacity(s.len());
161    let mut it = s.chars().peekable();
162    while let Some(c) = it.next() {
163        if c != '\\' {
164            out.push(c);
165            continue;
166        }
167        match it.next() {
168            Some('\n') => {
169                // Line continuation: skip the newline and any indentation after it.
170                while it.peek().is_some_and(|c| c.is_whitespace()) {
171                    it.next();
172                }
173            }
174            Some('\r') => {
175                if it.peek() == Some(&'\n') {
176                    it.next();
177                }
178                while it.peek().is_some_and(|c| c.is_whitespace()) {
179                    it.next();
180                }
181            }
182            Some('n') => out.push('\n'),
183            Some('r') => out.push('\r'),
184            Some('t') => out.push('\t'),
185            Some('0') => out.push('\0'),
186            Some('\\') => out.push('\\'),
187            Some('"') => out.push('"'),
188            Some('\'') => out.push('\''),
189            Some(other) => {
190                return Err(format!("unsupported escape `\\{other}` in the path string"));
191            }
192            None => return Err("path string ends in a lone backslash".to_string()),
193        }
194    }
195    Ok(out)
196}
197
198/// A `compile_error!` invocation, so a bad path fails the build where it is written.
199fn compile_error(message: &str) -> TokenStream {
200    format!("compile_error!({message:?});")
201        .parse()
202        .unwrap_or_else(|_| {
203            // Unreachable: the message is a formatted Rust string literal.
204            TokenStream::new()
205        })
206}
207
208/// A typed binding to one Java class, for day-platform-android and the pieces and parts built on it
209/// (docs/android-jni.md). Use it as `day_platform_android::java_class!`, which re-exports it.
210///
211/// ```ignore
212/// day_platform_android::java_class! {
213///     DayCombo => dev.daybrite.day.piece.combobox.DayCombo,
214///     methods {
215///         static fn makeCombo(id: jlong, items: JString) -> android.view.View,
216///         static fn setComboText(view: android.view.View, text: JString),
217///     },
218/// }
219/// ```
220///
221/// The grammar is jni's `bind_java_type!`. Names are Java's, verbatim: the binding above calls
222/// `DayCombo.makeCombo`, and a search for `makeCombo` finds both sides. The expansion also
223/// registers the class for day-platform-android's startup check and records an R8 keep rule for exactly
224/// the class and members bound.
225#[proc_macro]
226pub fn java_class(input: TokenStream) -> TokenStream {
227    java::java_class(input)
228}
229
230/// The code day-build generated for a crate's `day_bridge::bridge!` block (docs/bridge.md),
231/// read from `$OUT_DIR/day-bridge/mod.rs` and emitted as this macro's output. `bridge!` expands
232/// to it; nothing else should call it.
233///
234/// Emitted rather than `include!`d so the code is attributed to the `bridge!` call in the crate's
235/// source. A panic location in the generated code (the `java_class!` bindings' `unwrap`s, say)
236/// then records that file's path, which is the same wherever the project is built. Under
237/// `include!` it recorded the absolute `OUT_DIR` path, so two builds of one commit from
238/// different directories produced different libraries, and `day rebuild` failed.
239#[proc_macro]
240pub fn bridge_generated(_input: TokenStream) -> TokenStream {
241    let Ok(out_dir) = std::env::var("OUT_DIR") else {
242        return compile_error(
243            "day_bridge::bridge! needs the crate's build.rs to run \
244             `day_build::bridge::generate()`, which writes the generated code to OUT_DIR",
245        );
246    };
247    let path = std::path::Path::new(&out_dir)
248        .join("day-bridge")
249        .join("mod.rs");
250    let text = match std::fs::read_to_string(&path) {
251        Ok(text) => text,
252        Err(e) => {
253            return compile_error(&format!(
254                "day_bridge::bridge!: {}: {e} (does build.rs call day_build::bridge::generate()?)",
255                path.display()
256            ));
257        }
258    };
259    let code: TokenStream = match text.parse() {
260        Ok(code) => code,
261        Err(e) => {
262            return compile_error(&format!(
263                "day_bridge::bridge!: the generated code in {} does not parse: {e}",
264                path.display()
265            ));
266        }
267    };
268    // The build still rebuilds this crate when the generated file changes, as it did under
269    // `include!`: `include_bytes!` registers the file, and an unused constant leaves nothing in
270    // the binary.
271    let mut out: TokenStream = format!(
272        "const _: &[u8] = ::core::include_bytes!({:?});",
273        path.display().to_string()
274    )
275    .parse()
276    .unwrap_or_default();
277    out.extend(code);
278    out
279}
280
281/// Per-property observation for a struct; see day-model's crate docs and `docs/model.md`.
282///
283/// Generates typed field accessors on every `Source` of the struct (`store.name()`,
284/// `store.elem(id).name()`, nested `item.address().city()`), `Identified` from the field marked
285/// `#[obs(key)]` (always explicit), and `OBSERVED_FIELDS`. `#[obs(skip)]` leaves a field out,
286/// with no accessor, path or trigger.
287///
288/// `#[model(…)]` attributes are accepted, so a struct can swap this derive for day-persistence's
289/// `Model` per target: `#[model(id)]` marks the key and the rest is ignored.
290#[proc_macro_derive(Observable, attributes(obs, model))]
291pub fn observable(input: TokenStream) -> TokenStream {
292    obs::observable(input)
293}
294
295/// Everything [`macro@Observable`] generates, for a struct that is described rather than
296/// derived: the hook for a derive layered on `Observable`.
297///
298/// ```ignore
299/// observable_impls! {
300///     struct Trip {
301///         #[obs(key)]
302///         id: u32,
303///         name: String,
304///     }
305/// }
306/// ```
307///
308/// The struct itself is not emitted, only the impls, so the input lists exactly the fields to
309/// observe. A derive with its own attribute grammar restates the struct this way and expands to
310/// this macro instead of generating the accessors a second time. day-persistence's
311/// `#[derive(Model)]` does (docs/persistence.md): it marks its `#[model(id)]` field as the key,
312/// leaves out relation markers, and adds the schema impls beside the result.
313#[proc_macro]
314pub fn observable_impls(input: TokenStream) -> TokenStream {
315    obs::observable(input)
316}
317
318/// Mark a function that builds a [`Case`](../day_core/conformance/struct.Case.html) as a Day
319/// test (docs/testing.md): the function stays as written, and a link-time registry entry is
320/// added beside it so `day test` and the mock harness find it. The test is named after the
321/// function, with hyphens for underscores: `button_status` runs as `button-status`.
322///
323/// ```ignore
324/// #[day::test]
325/// fn button_status() -> Case { Case::new().proves(kinds::BUTTON).page(..).drive(..) }
326/// ```
327///
328/// The registry lives in day-core; a crate below `day` names it: `#[day_macros::test(day_core)]`.
329/// Native targets use linkme; WASM uses inventory and a compiler-exported descriptor.
330/// `day build` records these exports before linking and validates discovery before tests run.
331#[proc_macro_attribute]
332pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
333    let krate = attr.to_string();
334    let krate = if krate.trim().is_empty() {
335        "day".to_owned()
336    } else {
337        krate.trim().to_owned()
338    };
339    // The function's name: the identifier after `fn`.
340    let mut tokens = item.clone().into_iter();
341    let mut name = None;
342    while let Some(t) = tokens.next() {
343        if let proc_macro::TokenTree::Ident(i) = &t
344            && i.to_string() == "fn"
345            && let Some(proc_macro::TokenTree::Ident(n)) = tokens.next()
346        {
347            name = Some(n.to_string());
348            break;
349        }
350    }
351    let Some(name) = name else {
352        return "compile_error!(\"#[day::test] goes on a function that returns a Case\");"
353            .parse()
354            .unwrap_or_default();
355    };
356    // Preserve conditional compilation even when #[cfg] follows #[day::test].
357    let cfg: String = item
358        .clone()
359        .into_iter()
360        .filter_map(|token| {
361            if let proc_macro::TokenTree::Group(group) = token
362                && group.delimiter() == proc_macro::Delimiter::Bracket
363            {
364                let text = group.stream().to_string();
365                if text.starts_with("cfg ")
366                    || text.starts_with("cfg(")
367                    || text.starts_with("cfg_attr ")
368                    || text.starts_with("cfg_attr(")
369                {
370                    return Some(format!("#[{text}]\n"));
371                }
372            }
373            None
374        })
375        .collect();
376    let entry = format!(
377        r#"{cfg}
378        const _: () = {{
379            #[cfg_attr(not(target_arch = "wasm32"), ::{krate}::linkme::distributed_slice(::{krate}::conformance::TESTS))]
380            #[cfg_attr(not(target_arch = "wasm32"), linkme(crate = ::{krate}::linkme))]
381            static TEST: ::{krate}::conformance::TestFn = ::{krate}::conformance::TestFn::new(
382                concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION"), "::", module_path!(), "::{name}"), {name});
383
384            #[cfg(target_arch = "wasm32")]
385            #[unsafe(export_name = concat!("__day_test_v1__", env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION"), "::", module_path!(), "::{name}"))]
386            extern "C" fn descriptor() -> *const ::{krate}::conformance::TestFn {{
387                // The export roots the descriptor's object. The separately recorded export
388                // expectation detects a missing constructor even if codegen splits it away.
389                ::{krate}::inventory::submit! {{ ::{krate}::conformance::Registration(&TEST) }}
390                &TEST
391            }}
392        }};
393"#
394    );
395    let mut out: TokenStream = item;
396    out.extend(
397        entry
398            .parse::<TokenStream>()
399            .expect("valid conformance declaration expansion"),
400    );
401    out
402}
403
404/// A piece's builder trait, generated from the inherent `impl` that holds its builder methods
405/// (docs/api-style.md "Typed builders and erasure").
406///
407/// ```ignore
408/// #[day::builder(RatingBuilder)]
409/// impl Rating {
410///     /// The number of stars.
411///     pub fn max(mut self, n: u32) -> Self { self.max = n; self }
412///     pub fn editable<M>(mut self, on: impl IntoReactive<bool, M>) -> Self { … }
413/// }
414/// ```
415///
416/// The block is emitted unchanged, followed by `pub trait RatingBuilder: Sized` declaring every
417/// `pub fn …(self, …) -> Self` of the block, `impl RatingBuilder for Rating`, and
418/// `impl<Inner: RatingBuilder + Piece> RatingBuilder for Decorated<Inner>`, so
419/// `rating(v).padding(8.0).max(10)` resolves. A trait that carries one of the impl's type
420/// parameters names it: `#[day::builder(NavBuilder<K>)]` on `impl<K: Route, S: Binding<K>>
421/// Nav<S, K>` copies `K: Route` onto the trait. `Decorated` and `Piece` must be in scope.
422#[proc_macro_attribute]
423pub fn builder(attr: TokenStream, item: TokenStream) -> TokenStream {
424    builder::builder(attr, item)
425}