day-macros 0.7.6

Compile-time macros for Day.
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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Compile-time macros for Day.
//!
//! [`build_path!`]: SVG path data in, a `PathBuilder` method chain out. [`Observable`]
//! (`#[derive]`): a struct in, typed per-field accessors for day-model out, with
//! [`observable_impls!`] as the same expansion for derives layered on it. [`macro@builder`]: a
//! piece's builder trait and its `Decorated` forwarding, generated from the inherent impl.

mod builder;
mod java;
mod obs;
mod svg;

use proc_macro::TokenStream;
use std::fmt::Write as _;

/// Keep a WASM ID record's archive member in the final link, including unused helpers.
/// The public declaration frontend remains `id!`; this attribute is its linker plumbing.
#[doc(hidden)]
#[proc_macro_attribute]
pub fn retain_element_id(_: TokenStream, item: TokenStream) -> TokenStream {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static NEXT: AtomicUsize = AtomicUsize::new(0);
    let serial = NEXT.fetch_add(1, Ordering::Relaxed);
    let mut out = item;
    // An export roots the archive member containing the custom section. A unique suffix
    // also permits caller macros to repeat the same family at one source location.
    let anchor: TokenStream = format!(
        r#"#[doc(hidden)]
        #[unsafe(export_name = concat!("__day_id_anchor_", env!("CARGO_PKG_NAME"), "_",
            env!("CARGO_PKG_VERSION"), "_", module_path!(), "_", "{serial}"))]
        extern "C" fn __day_id_link_anchor() {{}}
        "#
    )
    .parse()
    .expect("valid element ID anchor");
    out.extend(anchor);
    out
}

/// Turn SVG path data into a `PathBuilder` chain, at compile time.
///
/// ```ignore
/// let heart = build_path!("M 12,21 C 2,14 2,7 7,5 c 3,-1 5,1 5,3 …").build();
/// d.fill(heart, CORAL);
/// ```
///
/// The whole SVG 1.1 path grammar is accepted: absolute and relative commands, `H`/`V`, the
/// smooth forms `S`/`T`, elliptical arcs, implicit command repetition, and SVG's number syntax
/// (`1e2`, `.5.5`, `10-5`). Malformed data is a compile error naming the offending character,
/// not a path that silently draws nothing.
///
/// The result is a `PathBuilder`, so the fill rule and any further segments still chain on:
///
/// ```ignore
/// build_path!("M0,0 h10 v10 h-10 Z").rule(FillRule::EvenOdd).build()
/// ```
///
/// Arcs are converted to cubics here, once, rather than by each of the nine backends at draw
/// time, because an arc is the one command with no counterpart in the 2-D APIs Day draws through.
///
/// Everything is evaluated at compile time, so a path costs the same at runtime as writing the
/// method chain by hand: there is no string left in the binary and no parsing on the draw path.
#[proc_macro]
pub fn build_path(input: TokenStream) -> TokenStream {
    let literal = match string_literal(input) {
        Ok(s) => s,
        Err(e) => return compile_error(&e),
    };
    let segs = match svg::parse(&literal) {
        Ok(s) => s,
        Err(e) => {
            return compile_error(&format!(
                "build_path!: {} at offset {} in {literal:?}",
                e.message, e.at
            ));
        }
    };
    let mut code = String::from("day::prelude::PathBuilder::new()");
    for seg in &segs {
        match seg {
            svg::Seg::Move(x, y) => {
                let _ = write!(code, ".move_to({})", point(*x, *y));
            }
            svg::Seg::Line(x, y) => {
                let _ = write!(code, ".line_to({})", point(*x, *y));
            }
            svg::Seg::Quad(cx, cy, x, y) => {
                let _ = write!(code, ".quad_to({}, {})", point(*cx, *cy), point(*x, *y));
            }
            svg::Seg::Cubic(ax, ay, bx, by, x, y) => {
                let _ = write!(
                    code,
                    ".cubic_to({}, {}, {})",
                    point(*ax, *ay),
                    point(*bx, *by),
                    point(*x, *y)
                );
            }
            svg::Seg::Close => code.push_str(".close()"),
        }
    }
    match code.parse() {
        Ok(ts) => ts,
        Err(e) => compile_error(&format!("build_path!: generated code did not parse: {e}")),
    }
}

/// A `Point::new(x, y)` literal. Coordinates are emitted with full `f64` precision so the
/// generated chain is exactly the path that was parsed.
fn point(x: f64, y: f64) -> String {
    format!("day::prelude::Point::new({x:?}, {y:?})")
}

/// Pull the single string literal out of the macro input, rejecting anything else.
///
/// Done by hand rather than with `syn`: the accepted input is one literal, and a parser
/// framework would be the crate's only dependency.
fn string_literal(input: TokenStream) -> Result<String, String> {
    let mut trees = input.into_iter();
    let first = trees.next().ok_or_else(|| {
        "build_path! takes an SVG path string, e.g. build_path!(\"M0,0 L10,10\")".to_string()
    })?;
    if trees.next().is_some() {
        return Err("build_path! takes exactly one string literal".to_string());
    }
    let text = match first {
        proc_macro::TokenTree::Literal(l) => l.to_string(),
        other => return Err(format!("expected a string literal, found `{other}`")),
    };
    // `Literal::to_string` gives the source spelling, quotes and escapes included, so a plain
    // literal has to be unescaped by hand. A raw string does not (that is what raw means).
    let trimmed = text.trim();
    if let Some(rest) = trimmed.strip_prefix('r') {
        let hashes = rest.len() - rest.trim_start_matches('#').len();
        let inner = rest
            .trim_start_matches('#')
            .strip_prefix('"')
            .ok_or_else(|| "expected a string literal".to_string())?;
        let end = inner
            .len()
            .checked_sub(hashes + 1)
            .ok_or_else(|| "expected a string literal".to_string())?;
        return Ok(inner[..end].to_string());
    }
    let body = trimmed
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .ok_or_else(|| format!("expected a string literal, found `{trimmed}`"))?;
    unescape(body)
}

/// Expand Rust's string escapes.
///
/// The line continuation is the one that matters here: `\` at end of line eats the newline and
/// the next line's leading whitespace, which is how a long path stays readable across several
/// source lines. Without this the backslash reaches the path parser and fails the build on
/// exactly the paths most worth writing that way.
fn unescape(s: &str) -> Result<String, String> {
    let mut out = String::with_capacity(s.len());
    let mut it = s.chars().peekable();
    while let Some(c) = it.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match it.next() {
            Some('\n') => {
                // Line continuation: skip the newline and any indentation after it.
                while it.peek().is_some_and(|c| c.is_whitespace()) {
                    it.next();
                }
            }
            Some('\r') => {
                if it.peek() == Some(&'\n') {
                    it.next();
                }
                while it.peek().is_some_and(|c| c.is_whitespace()) {
                    it.next();
                }
            }
            Some('n') => out.push('\n'),
            Some('r') => out.push('\r'),
            Some('t') => out.push('\t'),
            Some('0') => out.push('\0'),
            Some('\\') => out.push('\\'),
            Some('"') => out.push('"'),
            Some('\'') => out.push('\''),
            Some(other) => {
                return Err(format!("unsupported escape `\\{other}` in the path string"));
            }
            None => return Err("path string ends in a lone backslash".to_string()),
        }
    }
    Ok(out)
}

/// A `compile_error!` invocation, so a bad path fails the build where it is written.
fn compile_error(message: &str) -> TokenStream {
    format!("compile_error!({message:?});")
        .parse()
        .unwrap_or_else(|_| {
            // Unreachable: the message is a formatted Rust string literal.
            TokenStream::new()
        })
}

/// A typed binding to one Java class, for day-platform-android and the pieces and parts built on it
/// (docs/android-jni.md). Use it as `day_platform_android::java_class!`, which re-exports it.
///
/// ```ignore
/// day_platform_android::java_class! {
///     DayCombo => dev.daybrite.day.piece.combobox.DayCombo,
///     methods {
///         static fn makeCombo(id: jlong, items: JString) -> android.view.View,
///         static fn setComboText(view: android.view.View, text: JString),
///     },
/// }
/// ```
///
/// The grammar is jni's `bind_java_type!`. Names are Java's, verbatim: the binding above calls
/// `DayCombo.makeCombo`, and a search for `makeCombo` finds both sides. The expansion also
/// registers the class for day-platform-android's startup check and records an R8 keep rule for exactly
/// the class and members bound.
#[proc_macro]
pub fn java_class(input: TokenStream) -> TokenStream {
    java::java_class(input)
}

/// The code day-build generated for a crate's `day_bridge::bridge!` block (docs/bridge.md),
/// read from `$OUT_DIR/day-bridge/mod.rs` and emitted as this macro's output. `bridge!` expands
/// to it; nothing else should call it.
///
/// Emitted rather than `include!`d so the code is attributed to the `bridge!` call in the crate's
/// source. A panic location in the generated code (the `java_class!` bindings' `unwrap`s, say)
/// then records that file's path, which is the same wherever the project is built. Under
/// `include!` it recorded the absolute `OUT_DIR` path, so two builds of one commit from
/// different directories produced different libraries, and `day rebuild` failed.
#[proc_macro]
pub fn bridge_generated(_input: TokenStream) -> TokenStream {
    let Ok(out_dir) = std::env::var("OUT_DIR") else {
        return compile_error(
            "day_bridge::bridge! needs the crate's build.rs to run \
             `day_build::bridge::generate()`, which writes the generated code to OUT_DIR",
        );
    };
    let path = std::path::Path::new(&out_dir)
        .join("day-bridge")
        .join("mod.rs");
    let text = match std::fs::read_to_string(&path) {
        Ok(text) => text,
        Err(e) => {
            return compile_error(&format!(
                "day_bridge::bridge!: {}: {e} (does build.rs call day_build::bridge::generate()?)",
                path.display()
            ));
        }
    };
    let code: TokenStream = match text.parse() {
        Ok(code) => code,
        Err(e) => {
            return compile_error(&format!(
                "day_bridge::bridge!: the generated code in {} does not parse: {e}",
                path.display()
            ));
        }
    };
    // The build still rebuilds this crate when the generated file changes, as it did under
    // `include!`: `include_bytes!` registers the file, and an unused constant leaves nothing in
    // the binary.
    let mut out: TokenStream = format!(
        "const _: &[u8] = ::core::include_bytes!({:?});",
        path.display().to_string()
    )
    .parse()
    .unwrap_or_default();
    out.extend(code);
    out
}

/// Per-property observation for a struct; see day-model's crate docs and `docs/model.md`.
///
/// Generates typed field accessors on every `Source` of the struct (`store.name()`,
/// `store.elem(id).name()`, nested `item.address().city()`), `Identified` from the field marked
/// `#[obs(key)]` (always explicit), and `OBSERVED_FIELDS`. `#[obs(skip)]` leaves a field out,
/// with no accessor, path or trigger.
///
/// `#[model(…)]` attributes are accepted, so a struct can swap this derive for day-persistence's
/// `Model` per target: `#[model(id)]` marks the key and the rest is ignored.
#[proc_macro_derive(Observable, attributes(obs, model))]
pub fn observable(input: TokenStream) -> TokenStream {
    obs::observable(input)
}

/// Everything [`macro@Observable`] generates, for a struct that is described rather than
/// derived: the hook for a derive layered on `Observable`.
///
/// ```ignore
/// observable_impls! {
///     struct Trip {
///         #[obs(key)]
///         id: u32,
///         name: String,
///     }
/// }
/// ```
///
/// The struct itself is not emitted, only the impls, so the input lists exactly the fields to
/// observe. A derive with its own attribute grammar restates the struct this way and expands to
/// this macro instead of generating the accessors a second time. day-persistence's
/// `#[derive(Model)]` does (docs/persistence.md): it marks its `#[model(id)]` field as the key,
/// leaves out relation markers, and adds the schema impls beside the result.
#[proc_macro]
pub fn observable_impls(input: TokenStream) -> TokenStream {
    obs::observable(input)
}

/// Mark a function that builds a [`Case`](../day_core/conformance/struct.Case.html) as a Day
/// test (docs/testing.md): the function stays as written, and a link-time registry entry is
/// added beside it so `day test` and the mock harness find it. The test is named after the
/// function, with hyphens for underscores: `button_status` runs as `button-status`.
///
/// ```ignore
/// #[day::test]
/// fn button_status() -> Case { Case::new().proves(kinds::BUTTON).page(..).drive(..) }
/// ```
///
/// The registry lives in day-core; a crate below `day` names it: `#[day_macros::test(day_core)]`.
/// Native targets use linkme; WASM uses inventory and a compiler-exported descriptor.
/// `day build` records these exports before linking and validates discovery before tests run.
///
/// # Panics
///
/// Panics if the generated registration does not parse as Rust, which would be a bug in this macro.
#[proc_macro_attribute]
pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
    let krate = attr.to_string();
    let krate = if krate.trim().is_empty() {
        "day".to_owned()
    } else {
        krate.trim().to_owned()
    };
    // The function's name: the identifier after `fn`.
    let mut tokens = item.clone().into_iter();
    let mut name = None;
    while let Some(t) = tokens.next() {
        if let proc_macro::TokenTree::Ident(i) = &t
            && i.to_string() == "fn"
            && let Some(proc_macro::TokenTree::Ident(n)) = tokens.next()
        {
            name = Some(n.to_string());
            break;
        }
    }
    let Some(name) = name else {
        return "compile_error!(\"#[day::test] goes on a function that returns a Case\");"
            .parse()
            .unwrap_or_default();
    };
    // Preserve conditional compilation even when #[cfg] follows #[day::test].
    let cfg: String = item
        .clone()
        .into_iter()
        .filter_map(|token| {
            if let proc_macro::TokenTree::Group(group) = token
                && group.delimiter() == proc_macro::Delimiter::Bracket
            {
                let text = group.stream().to_string();
                if text.starts_with("cfg ")
                    || text.starts_with("cfg(")
                    || text.starts_with("cfg_attr ")
                    || text.starts_with("cfg_attr(")
                {
                    return Some(format!("#[{text}]\n"));
                }
            }
            None
        })
        .collect();
    let entry = format!(
        r#"{cfg}
        const _: () = {{
            #[cfg_attr(not(target_arch = "wasm32"), ::{krate}::linkme::distributed_slice(::{krate}::conformance::TESTS))]
            #[cfg_attr(not(target_arch = "wasm32"), linkme(crate = ::{krate}::linkme))]
            static TEST: ::{krate}::conformance::TestFn = ::{krate}::conformance::TestFn::new(
                concat!(env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION"), "::", module_path!(), "::{name}"), {name});

            #[cfg(target_arch = "wasm32")]
            #[unsafe(export_name = concat!("__day_test_v1__", env!("CARGO_PKG_NAME"), "@", env!("CARGO_PKG_VERSION"), "::", module_path!(), "::{name}"))]
            extern "C" fn descriptor() -> *const ::{krate}::conformance::TestFn {{
                // The export roots the descriptor's object. The separately recorded export
                // expectation detects a missing constructor even if codegen splits it away.
                ::{krate}::inventory::submit! {{ ::{krate}::conformance::Registration(&TEST) }}
                &TEST
            }}
        }};
"#
    );
    let mut out: TokenStream = item;
    out.extend(
        entry
            .parse::<TokenStream>()
            .expect("valid conformance declaration expansion"),
    );
    out
}

/// A piece's builder trait, generated from the inherent `impl` that holds its builder methods
/// (docs/api-style.md "Typed builders and erasure").
///
/// ```ignore
/// #[day::builder(RatingBuilder)]
/// impl Rating {
///     /// The number of stars.
///     pub fn max(mut self, n: u32) -> Self { self.max = n; self }
///     pub fn editable<M>(mut self, on: impl IntoReactive<bool, M>) -> Self { … }
/// }
/// ```
///
/// The block is emitted unchanged, followed by `pub trait RatingBuilder: Sized` declaring every
/// `pub fn …(self, …) -> Self` of the block, `impl RatingBuilder for Rating`, and
/// `impl<Inner: RatingBuilder + Piece> RatingBuilder for Decorated<Inner>`, so
/// `rating(v).padding(8.0).max(10)` resolves. A trait that carries one of the impl's type
/// parameters names it: `#[day::builder(NavBuilder<K>)]` on `impl<K: Route, S: Binding<K>>
/// Nav<S, K>` copies `K: Route` onto the trait. `Decorated` and `Piece` must be in scope.
#[proc_macro_attribute]
pub fn builder(attr: TokenStream, item: TokenStream) -> TokenStream {
    builder::builder(attr, item)
}