mod obs;
mod svg;
use proc_macro::TokenStream;
#[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_derive(Observable, attributes(obs))]
pub fn observable(input: TokenStream) -> TokenStream {
obs::observable(input)
}