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