mod builder;
mod java;
mod obs;
mod svg;
use proc_macro::TokenStream;
#[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;
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
}
#[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}")),
}
}
fn point(x: f64, y: f64) -> String {
format!("day::prelude::Point::new({x:?}, {y:?})")
}
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}`")),
};
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)
}
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') => {
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)
}
fn compile_error(message: &str) -> TokenStream {
format!("compile_error!({message:?});")
.parse()
.unwrap_or_else(|_| {
TokenStream::new()
})
}
#[proc_macro]
pub fn java_class(input: TokenStream) -> TokenStream {
java::java_class(input)
}
#[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()
));
}
};
let mut out: TokenStream = format!(
"const _: &[u8] = ::core::include_bytes!({:?});",
path.display().to_string()
)
.parse()
.unwrap_or_default();
out.extend(code);
out
}
#[proc_macro_derive(Observable, attributes(obs, model))]
pub fn observable(input: TokenStream) -> TokenStream {
obs::observable(input)
}
#[proc_macro]
pub fn observable_impls(input: TokenStream) -> TokenStream {
obs::observable(input)
}
#[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()
};
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 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
}
#[proc_macro_attribute]
pub fn builder(attr: TokenStream, item: TokenStream) -> TokenStream {
builder::builder(attr, item)
}