day-macros 0.6.0

Compile-time macros for Day.
Documentation
// 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;

/// 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) => {
                code.push_str(&format!(".move_to({})", point(*x, *y)));
            }
            svg::Seg::Line(x, y) => {
                code.push_str(&format!(".line_to({})", point(*x, *y)));
            }
            svg::Seg::Quad(cx, cy, x, y) => {
                code.push_str(&format!(".quad_to({}, {})", point(*cx, *cy), point(*x, *y)));
            }
            svg::Seg::Cubic(ax, ay, bx, by, x, y) => {
                code.push_str(&format!(
                    ".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-android and the pieces and parts built on it
/// (docs/android-jni.md). Use it as `day_android::java_class!`, which re-exports it.
///
/// ```ignore
/// day_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-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)]`.
/// On wasm there is no link-time registry, so a crate also lists its tests in a
/// `day::tests! { .. }` roster, which the app registers at launch.
#[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();
    };
    let entry = format!(
        "#[cfg(not(target_arch = \"wasm32\"))]\n\
         #[::{krate}::linkme::distributed_slice(::{krate}::conformance::TESTS)]\n\
         #[linkme(crate = ::{krate}::linkme)]\n\
         #[allow(non_upper_case_globals)]\n\
         static __day_test_{name}: ::{krate}::conformance::TestFn =\n\
             ::{krate}::conformance::TestFn::new(\"{name}\", {name});\n"
    );
    let mut out: TokenStream = item;
    out.extend(entry.parse::<TokenStream>().unwrap_or_default());
    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)
}