app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

@@ -0,0 +1,3 @@
target-repro/
pack/target/
+273
View File
@@ -0,0 +1,273 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "fastrand"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "phf"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
dependencies = [
"phf_macros",
"phf_shared",
"serde",
]
[[package]]
name = "phf_generator"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
dependencies = [
"fastrand",
"phf_shared",
]
[[package]]
name = "phf_macros"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
dependencies = [
"phf_generator",
"phf_shared",
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "phf_shared"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
dependencies = [
"siphasher",
]
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "ratex-font"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c3599bafdf0e0637d1bb9cf97c01528eaa46fab0c6810c3959c2da5f66b2242"
dependencies = [
"phf",
"ratex-types",
]
[[package]]
name = "ratex-layout"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "667f0b07c558d07d77c53208d90a5bd1918cbe5f76c1c36f3547bf08bc3d625a"
dependencies = [
"ratex-font",
"ratex-parser",
"ratex-types",
"serde_json",
]
[[package]]
name = "ratex-lexer"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d0fb77ea76a6f650f382f9660949cddc8afd695901f1c9293f92175a3d9e62f"
dependencies = [
"ratex-types",
"serde",
"thiserror",
]
[[package]]
name = "ratex-math-wasm"
version = "0.1.0"
dependencies = [
"ratex-layout",
"ratex-parser",
"ratex-types",
]
[[package]]
name = "ratex-parser"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dbc57077b89566bde9fc17f468b83d6b17df90930874f8a3d0e7ef988f1ae9c"
dependencies = [
"ratex-font",
"ratex-lexer",
"ratex-types",
"regex-lite",
"serde",
"serde_json",
"thiserror",
"unicode-normalization",
]
[[package]]
name = "ratex-types"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74b856c4a2c1d4b9669a10f03b207f97e16a53119bf607501732b97b5c87007f"
dependencies = [
"serde",
]
[[package]]
name = "regex-lite"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "siphasher"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+24
View File
@@ -0,0 +1,24 @@
[workspace]
[package]
name = "ratex-math-wasm"
version = "0.1.0"
edition = "2021"
license = "MIT"
publish = false
description = "Sandboxed wasm32-unknown-unknown LaTeX math parser and layout guest for rune-kit"
[lib]
crate-type = ["cdylib"]
[dependencies]
ratex-layout = { version = "=0.1.16", default-features = false }
ratex-parser = { version = "=0.1.16", default-features = false }
ratex-types = { version = "=0.1.16", default-features = false }
[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
panic = "abort"
strip = true
+32
View File
@@ -0,0 +1,32 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
]
[[package]]
name = "ratex-katex-fonts"
version = "0.1.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "575eb89e2ab455fe9618b5f06d1838dff40064642d8ec454fedf14852d2ed0a3"
[[package]]
name = "ratex-math-pack"
version = "0.1.0"
dependencies = [
"miniz_oxide",
"ratex-katex-fonts",
]
+12
View File
@@ -0,0 +1,12 @@
[workspace]
[package]
name = "ratex-math-pack"
version = "0.1.0"
edition = "2021"
license = "MIT"
publish = false
[dependencies]
miniz_oxide = "0.9"
ratex-katex-fonts = "=0.1.16"
+230
View File
@@ -0,0 +1,230 @@
//! Deterministic builder and freshness verifier for `crates/rune-kit/assets/math/*` and
//! `crates/rune-kit/src/math/wasm_hash.rs`.
use std::path::{Path, PathBuf};
use std::process::Command;
const FONT_NAMES: [&str; 20] = [
"AMS-Regular",
"Caligraphic-Bold",
"Caligraphic-Regular",
"Fraktur-Bold",
"Fraktur-Regular",
"Main-Bold",
"Main-BoldItalic",
"Main-Italic",
"Main-Regular",
"Math-BoldItalic",
"Math-Italic",
"SansSerif-Bold",
"SansSerif-Italic",
"SansSerif-Regular",
"Script-Regular",
"Size1-Regular",
"Size2-Regular",
"Size3-Regular",
"Size4-Regular",
"Typewriter-Regular",
];
fn sha256(data: &[u8]) -> [u8; 32] {
const K: [u32; 64] = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
];
let mut h: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
let bit_len = (data.len() as u64).wrapping_mul(8);
let mut msg = Vec::with_capacity(((data.len() + 9 + 63) / 64) * 64);
msg.extend_from_slice(data);
msg.push(0x80);
while (msg.len() % 64) != 56 {
msg.push(0);
}
msg.extend_from_slice(&bit_len.to_be_bytes());
for chunk in msg.chunks_exact(64) {
let mut w = [0u32; 64];
for i in 0..16 {
w[i] = u32::from_be_bytes([chunk[4 * i], chunk[4 * i + 1], chunk[4 * i + 2], chunk[4 * i + 3]]);
}
for i in 16..64 {
let s0 = w[i - 15].rotate_right(7) ^ w[i - 15].rotate_right(18) ^ (w[i - 15] >> 3);
let s1 = w[i - 2].rotate_right(17) ^ w[i - 2].rotate_right(19) ^ (w[i - 2] >> 10);
w[i] = w[i - 16].wrapping_add(s0).wrapping_add(w[i - 7]).wrapping_add(s1);
}
let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut hh] = h;
for i in 0..64 {
let s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
let ch = (e & f) ^ ((!e) & g);
let t1 = hh.wrapping_add(s1).wrapping_add(ch).wrapping_add(K[i]).wrapping_add(w[i]);
let s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
let maj = (a & b) ^ (a & c) ^ (b & c);
let t2 = s0.wrapping_add(maj);
hh = g;
g = f;
f = e;
e = d.wrapping_add(t1);
d = c;
c = b;
b = a;
a = t1.wrapping_add(t2);
}
for (slot, delta) in h.iter_mut().zip([a, b, c, d, e, f, g, hh]) {
*slot = slot.wrapping_add(delta);
}
}
let mut out = [0u8; 32];
for (i, word) in h.iter().enumerate() {
out[4 * i..4 * i + 4].copy_from_slice(&word.to_be_bytes());
}
out
}
fn hex(bytes: &[u8; 32]) -> String {
let mut s = String::with_capacity(64);
for b in bytes {
s.push_str(&format!("{b:02x}"));
}
s
}
fn hash_guest_sources(guest_dir: &Path) -> String {
let mut buf = Vec::new();
for rel in ["rust-toolchain.toml", "Cargo.toml", "Cargo.lock", "src/lib.rs"] {
let p = guest_dir.join(rel);
let raw = std::fs::read(&p).unwrap_or_else(|e| panic!("read {}: {e}", p.display()));
buf.extend_from_slice(rel.as_bytes());
buf.push(0);
// Normalize CRLF -> LF so Windows and Unix checkouts hash identically.
for &b in &raw {
if b != b'\r' {
buf.push(b);
}
}
buf.push(0);
}
hex(&sha256(&buf))
}
fn build_wasm_deflate(repo_root: &Path, guest_dir: &Path) -> Vec<u8> {
let remap_repo = format!("--remap-path-prefix={}=/rune", repo_root.display());
let cargo_home = std::env::var("CARGO_HOME").unwrap_or_else(|_| {
let home = std::env::var("USERPROFILE")
.or_else(|_| std::env::var("HOME"))
.unwrap_or_default();
format!("{home}/.cargo")
});
let remap_cargo = format!("--remap-path-prefix={cargo_home}=/cargo");
// Hard-cap linear memory at 16 MiB (256 pages) inside the wasm binary itself as well as
// host-side `StoreLimits`, so browser Web Workers also enforce the 16 MiB memory cap.
let rustflags = format!("{remap_repo} {remap_cargo} -C link-arg=--max-memory=16777216");
let target_dir = guest_dir.join("target-repro");
let mut cmd = Command::new("cargo");
cmd.arg("build")
.arg("--release")
.arg("--target")
.arg("wasm32-unknown-unknown")
.arg("--manifest-path")
.arg(guest_dir.join("Cargo.toml"))
.arg("--target-dir")
.arg(&target_dir)
.env("RUSTFLAGS", rustflags);
if guest_dir.join("Cargo.lock").exists() {
cmd.arg("--locked");
}
let status = cmd.status().expect("spawn cargo build for ratex-math-wasm");
assert!(status.success(), "cargo build for ratex-math-wasm failed");
let wasm_path = target_dir
.join("wasm32-unknown-unknown")
.join("release")
.join("ratex_math_wasm.wasm");
let wasm = std::fs::read(&wasm_path).expect("read compiled ratex_math_wasm.wasm");
let deflated = miniz_oxide::deflate::compress_to_vec(&wasm, 9);
eprintln!(
"ratex_math_wasm.wasm: raw={} B, deflated={} B",
wasm.len(),
deflated.len()
);
deflated
}
fn build_fonts_pack_deflate() -> Vec<u8> {
let mut pack = Vec::with_capacity(520 * 1024);
pack.extend_from_slice(b"KF01");
pack.extend_from_slice(&(FONT_NAMES.len() as u32).to_le_bytes());
let mut raw_total = 0usize;
for name in FONT_NAMES {
let file = format!("KaTeX_{name}.ttf");
let data = ratex_katex_fonts::ttf_bytes(&file)
.unwrap_or_else(|| panic!("missing KaTeX font {file}"));
let data = data.as_ref();
raw_total += data.len();
pack.push(name.len() as u8);
pack.extend_from_slice(name.as_bytes());
pack.extend_from_slice(&(data.len() as u32).to_le_bytes());
pack.extend_from_slice(data);
}
let deflated = miniz_oxide::deflate::compress_to_vec(&pack, 9);
eprintln!(
"katex-fonts.pack: {} fonts, raw={} B, pack={} B, deflated={} B",
FONT_NAMES.len(),
raw_total,
pack.len(),
deflated.len()
);
deflated
}
fn main() {
let check_only = std::env::args().any(|a| a == "--check");
let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let guest_dir = manifest_dir.parent().expect("tools/ratex-math-wasm");
let repo_root = guest_dir
.parent()
.and_then(Path::parent)
.expect("repo root");
let wasm_deflate = build_wasm_deflate(repo_root, guest_dir);
let fonts_deflate = build_fonts_pack_deflate();
let guest_src_sha = hash_guest_sources(guest_dir);
let wasm_sha = hex(&sha256(&wasm_deflate));
let fonts_sha = hex(&sha256(&fonts_deflate));
let assets_dir = repo_root.join("crates/rune-kit/assets/math");
let wasm_out = assets_dir.join("ratex-math.wasm.deflate");
let fonts_out = assets_dir.join("katex-fonts.pack.deflate");
let hash_rs_out = repo_root.join("crates/rune-kit/src/math/wasm_hash.rs");
let hash_rs = format!(
"// Generated by `scripts/build-math-wasm.sh` from `tools/ratex-math-wasm/` and `ratex-katex-fonts 0.1.16`.\n\
// Do not edit by hand; `crates/rune-kit/build.rs` verifies these digests when `feature = \"math\"` is enabled.\n\
pub(crate) const GUEST_SOURCE_SHA256: &str = \"{guest_src_sha}\";\n\
pub(crate) const WASM_DEFLATE_SHA256: &str = \"{wasm_sha}\";\n\
pub(crate) const KATEX_FONTS_SHA256: &str = \"{fonts_sha}\";\n"
);
if check_only {
let cur_wasm = std::fs::read(&wasm_out).expect("read committed ratex-math.wasm.deflate");
let cur_fonts = std::fs::read(&fonts_out).expect("read committed katex-fonts.pack.deflate");
let cur_hash = std::fs::read_to_string(&hash_rs_out).expect("read committed wasm_hash.rs");
assert_eq!(cur_wasm, wasm_deflate, "ratex-math.wasm.deflate differs from fresh build");
assert_eq!(cur_fonts, fonts_deflate, "katex-fonts.pack.deflate differs from fresh build");
assert_eq!(cur_hash.replace("\r\n", "\n"), hash_rs, "wasm_hash.rs differs from fresh build");
println!("OK: ratex-math.wasm.deflate, katex-fonts.pack.deflate, and wasm_hash.rs match byte-for-byte.");
return;
}
std::fs::create_dir_all(&assets_dir).expect("create assets/math");
std::fs::create_dir_all(hash_rs_out.parent().unwrap()).expect("create src/math");
std::fs::write(&wasm_out, &wasm_deflate).expect("write ratex-math.wasm.deflate");
std::fs::write(&fonts_out, &fonts_deflate).expect("write katex-fonts.pack.deflate");
std::fs::write(&hash_rs_out, &hash_rs).expect("write wasm_hash.rs");
println!("Wrote assets and wasm_hash.rs (guest={guest_src_sha}, wasm={wasm_sha}, fonts={fonts_sha})");
}
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.99.1"
targets = ["wasm32-unknown-unknown"]
+196
View File
@@ -0,0 +1,196 @@
//! Sandboxed `wasm32-unknown-unknown` LaTeX display-math parser & layout module for `rune-kit`.
//!
//! All security limits (fuel, linear memory, wall-clock deadline, and full binary wire validation)
//! are enforced on the host outside this module. This guest is kept minimal and emits a compact
//! little-endian `RM01` display list for host-side `skrifa` + `tiny-skia` rasterisation.
use core::cell::RefCell;
use ratex_layout::{layout, to_display_list, LayoutOptions};
use ratex_types::{DisplayItem, PathCommand};
const MAX_INPUT_BYTES: usize = 16 * 1024;
const MAX_ITEMS: usize = 4096;
const MAX_PATH_COMMANDS: usize = 16_384;
const MAX_WIRE_BYTES: usize = 1024 * 1024;
struct State {
input: Vec<u8>,
output: Vec<u8>,
}
struct SingleThread<T>(RefCell<T>);
// SAFETY: `wasm32-unknown-unknown` without atomics is strictly single-threaded.
unsafe impl<T> Sync for SingleThread<T> {}
static STATE: SingleThread<State> = SingleThread(RefCell::new(State {
input: Vec::new(),
output: Vec::new(),
}));
/// Allocates/resizes the guest input buffer to `len` bytes and returns its linear-memory pointer,
/// or `0` if `len` exceeds the input cap.
#[no_mangle]
pub extern "C" fn alloc_input(len: u32) -> u32 {
let n = len as usize;
if n == 0 || n > MAX_INPUT_BYTES {
return 0;
}
let mut st = STATE.0.borrow_mut();
st.input.clear();
st.input.resize(n, 0);
st.input.as_mut_ptr() as u32
}
/// Returns the linear-memory pointer of the most recent `RM01` output buffer.
#[no_mangle]
pub extern "C" fn out_ptr() -> u32 {
let st = STATE.0.borrow();
st.output.as_ptr() as u32
}
fn push_f32(out: &mut Vec<u8>, v: f64) {
out.extend_from_slice(&(v as f32).to_le_bytes());
}
fn push_color(out: &mut Vec<u8>, c: ratex_types::Color) {
out.push((c.r.clamp(0.0, 1.0) * 255.0).round() as u8);
out.push((c.g.clamp(0.0, 1.0) * 255.0).round() as u8);
out.push((c.b.clamp(0.0, 1.0) * 255.0).round() as u8);
out.push((c.a.clamp(0.0, 1.0) * 255.0).round() as u8);
}
/// Parses and lays out the `len`-byte UTF-8 TeX source written into `alloc_input(len)`.
/// Returns the byte length of the `RM01` binary display list in `out_ptr()`, or `0` on failure.
#[no_mangle]
pub extern "C" fn render_tex(len: u32) -> u32 {
let mut st = STATE.0.borrow_mut();
let n = (len as usize).min(st.input.len()).min(MAX_INPUT_BYTES);
let trimmed = match core::str::from_utf8(&st.input[..n]) {
Ok(s) => s.trim(),
Err(_) => return 0,
};
if trimmed.is_empty() {
return 0;
}
let nodes = match ratex_parser::parse(trimmed) {
Ok(nodes) => nodes,
Err(_) => return 0,
};
let opts = LayoutOptions::default();
let root = layout(&nodes, &opts);
let dl = to_display_list(&root);
if dl.items.is_empty() || dl.items.len() > MAX_ITEMS {
return 0;
}
if !dl.width.is_finite()
|| !dl.height.is_finite()
|| !dl.depth.is_finite()
|| dl.width < 0.0
|| dl.height < 0.0
|| dl.depth < 0.0
{
return 0;
}
let out = &mut st.output;
out.clear();
out.extend_from_slice(b"RM01");
push_f32(out, dl.width);
push_f32(out, dl.height);
push_f32(out, dl.depth);
out.extend_from_slice(&(dl.items.len() as u32).to_le_bytes());
let mut total_cmds = 0usize;
for item in &dl.items {
if out.len() > MAX_WIRE_BYTES {
out.clear();
return 0;
}
match item {
DisplayItem::GlyphPath { x, y, scale, font, char_code, color } => {
let fb = font.as_bytes();
if fb.is_empty() || fb.len() > 64 {
out.clear();
return 0;
}
out.push(0);
push_f32(out, *x);
push_f32(out, *y);
push_f32(out, *scale);
out.extend_from_slice(&char_code.to_le_bytes());
push_color(out, *color);
out.push(fb.len() as u8);
out.extend_from_slice(fb);
}
DisplayItem::Line { x, y, width, thickness, color, dashed } => {
out.push(1);
push_f32(out, *x);
push_f32(out, *y);
push_f32(out, *width);
push_f32(out, *thickness);
push_color(out, *color);
out.push(u8::from(*dashed));
}
DisplayItem::Rect { x, y, width, height, color } => {
out.push(2);
push_f32(out, *x);
push_f32(out, *y);
push_f32(out, *width);
push_f32(out, *height);
push_color(out, *color);
}
DisplayItem::Path { x, y, commands, fill, color } => {
total_cmds = total_cmds.saturating_add(commands.len());
if total_cmds > MAX_PATH_COMMANDS {
out.clear();
return 0;
}
out.push(3);
push_f32(out, *x);
push_f32(out, *y);
out.push(u8::from(*fill));
push_color(out, *color);
out.extend_from_slice(&(commands.len() as u32).to_le_bytes());
for cmd in commands {
match cmd {
PathCommand::MoveTo { x, y } => {
out.push(0);
push_f32(out, *x);
push_f32(out, *y);
}
PathCommand::LineTo { x, y } => {
out.push(1);
push_f32(out, *x);
push_f32(out, *y);
}
PathCommand::QuadTo { x1, y1, x, y } => {
out.push(2);
push_f32(out, *x1);
push_f32(out, *y1);
push_f32(out, *x);
push_f32(out, *y);
}
PathCommand::CubicTo { x1, y1, x2, y2, x, y } => {
out.push(3);
push_f32(out, *x1);
push_f32(out, *y1);
push_f32(out, *x2);
push_f32(out, *y2);
push_f32(out, *x);
push_f32(out, *y);
}
PathCommand::Close => {
out.push(4);
}
}
}
}
}
}
if out.len() > MAX_WIRE_BYTES {
out.clear();
return 0;
}
out.len() as u32
}
+46
View File
@@ -0,0 +1,46 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rune-dev-guard"
version = "0.0.1"
dependencies = [
"quote",
"syn",
]
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "rune-dev-guard"
version = "0.0.1"
edition = "2024"
publish = false
[workspace]
[dependencies]
syn = { version = "2", features = ["full", "visit", "visit-mut"] }
quote = "1"
[profile.dev]
debug = 0
+114
View File
@@ -0,0 +1,114 @@
//! A syntax guard, not a size_of guess: same-size field/type/signature edits are incompatible too.
use quote::ToTokens;
use syn::{parse::Parser, visit::Visit, visit_mut::VisitMut};
#[derive(Default)]
struct Contracts(Vec<String>);
impl<'ast> Visit<'ast> for Contracts {
fn visit_item(&mut self, item: &'ast syn::Item) {
// Local types, statics, functions and imports are also contracts. Do not erase them.
self.0.push(item.to_token_stream().to_string());
}
fn visit_macro(&mut self, m: &'ast syn::Macro) {
// Unknown macros could expand to persistent types/statics. Keep their entire invocation.
let safe = ["format", "format_args", "vec", "matches", "println", "eprintln", "assert", "assert_eq", "debug_assert", "panic", "unreachable", "todo"];
if m.path.get_ident().is_some_and(|i| safe.iter().any(|s| i == s)) {
// syn does not visit macro tokens. Parse their expressions explicitly so a
// local type/static or nested unknown macro cannot hide inside vec!/format!.
if m.path.is_ident("vec") {
let tokens = &m.tokens;
if let Ok(expr) = syn::parse2::<syn::Expr>(quote::quote!([#tokens])) {
self.visit_expr(&expr);
return;
}
} else if let Ok(args) = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated.parse2(m.tokens.clone()) {
for arg in args { self.visit_expr(&arg); }
return;
}
}
self.0.push(m.to_token_stream().to_string());
}
}
#[derive(Default)]
struct Scrub(Contracts);
impl VisitMut for Scrub {
fn visit_item_fn_mut(&mut self, f: &mut syn::ItemFn) {
// Const bodies can determine persistent layouts. Unknown attributes can
// expand the body into types or statics, even on an ordinary function.
let inert = ["doc", "inline", "cold", "allow"];
if f.sig.ident == "main" || f.sig.constness.is_some()
|| f.attrs.iter().any(|a| !a.path().get_ident().is_some_and(|i| inert.iter().any(|s| i == s)))
{ return; }
self.0.visit_block(&f.block);
f.block = syn::parse_quote!({});
}
// Impl methods, initializers, constants, attributes and module declarations stay byte-token exact.
fn visit_impl_item_fn_mut(&mut self, _: &mut syn::ImplItemFn) {}
}
fn contract(src: &str) -> Result<String, syn::Error> {
let mut ast = syn::parse_file(src)?;
let mut scrub = Scrub::default();
scrub.visit_file_mut(&mut ast);
Ok(format!("{}\n{:?}", ast.to_token_stream(), scrub.0.0))
}
fn main() {
let args: Vec<_> = std::env::args().skip(1).collect();
assert_eq!(args.len(), 2, "rune-dev-guard BEFORE.rs AFTER.rs");
let read = |p: &str| contract(&std::fs::read_to_string(p).expect("read source"));
match (read(&args[0]), read(&args[1])) {
(Ok(a), Ok(b)) if a == b => {}
(Ok(_), Ok(_)) => { eprintln!("restart needed: declaration, state schema, signature, startup code or persistent macro changed"); std::process::exit(3); }
(_, Err(e)) | (Err(e), _) => { eprintln!("edit not ready: {e}"); std::process::exit(2); }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn compatible_bodies_but_not_state_or_boundary_changes() {
let base = "struct S { a: u32, b: u32 } fn view(s: &S) -> u32 { s.a + 1 } fn main() { let s = S { a: 1, b: 2 }; }";
assert_eq!(contract(base).unwrap(), contract(&base.replace("s.a + 1", "s.b + 20")).unwrap());
for edit in [base.replace("a: u32, b: u32", "b: u32, a: u32"), base.replace("s: &S", "s: &mut S"), base.replace("a: 1", "a: 9"), base.replace("s.a + 1", "static X: u32 = 3; s.a + X"), base.replace("s.a + 1", "mystery!(s)")] {
assert_ne!(contract(base).unwrap(), contract(&edit).unwrap());
}
}
#[test]
fn nested_types_and_impls_cannot_change() {
let base = "fn view() { struct S { x: u32 } } impl S { fn init() -> u32 { 1 } }";
assert_ne!(contract(base).unwrap(), contract(&base.replace("x: u32", "x: f32")).unwrap());
assert_ne!(contract(base).unwrap(), contract(&base.replace("{ 1 }", "{ 2 }")).unwrap());
assert!(contract("fn view( {").is_err());
}
#[test]
fn const_function_bodies_are_layout_contracts() {
for layout in ["struct S { buf: [u8; cap()] }", "const N: usize = cap(); struct S { buf: [u8; N] }"] {
let base = format!("const fn cap() -> usize {{ 8 }} {layout} fn view() {{}}");
assert_ne!(contract(&base).unwrap(), contract(&base.replace("{ 8 }", "{ 16 }")).unwrap());
}
}
#[test]
fn unknown_attributes_keep_bodies_but_inert_attributes_allow_edits() {
for attribute in ["#[persistent]", "#[some::macro_attr]", "#[cfg_attr(feature = \"x\", persistent)]"] {
let base = format!("{attribute} fn view() {{ let n = 1; }}");
assert_ne!(contract(&base).unwrap(), contract(&base.replace("n = 1", "n = 2")).unwrap());
}
let base = "#[doc = \"view\"] #[inline(never)] #[cold] #[allow(unused)] fn view() { let n = 1; }";
assert_eq!(contract(base).unwrap(), contract(&base.replace("n = 1", "n = 2")).unwrap());
assert_ne!(contract(base).unwrap(), contract(&base.replace("inline(never)", "inline(always)")).unwrap());
}
#[test]
fn macro_arguments_cannot_hide_persistent_contracts() {
for body in ["vec![{ static X: u32 = 1; X }]", "format!(\"{}\", { struct S { x: u32 } 1 })", "vec![unknown!(1)]"] {
let base = format!("fn view() {{ {body}; }}");
assert_ne!(contract(&base).unwrap(), contract(&base.replace("u32", "f32").replace("unknown!(1)", "unknown!(2)")).unwrap());
}
assert_eq!(contract("fn view() { vec![1, 2]; }").unwrap(), contract("fn view() { vec![3; 4]; }").unwrap());
}
}