use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Duration;
use texrs::parity::Oracle;
fn main() -> std::process::ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let cfg = match Config::parse(&args) {
Ok(c) => c,
Err(e) => {
eprintln!("{e}");
return std::process::ExitCode::from(2);
}
};
if cfg.help {
print!("{USAGE}");
return std::process::ExitCode::SUCCESS;
}
let oracle = match texrs::parity::oracle(&repo()) {
Ok(o) => o,
Err(e) => {
eprintln!("parity-fuzz: {e}");
return std::process::ExitCode::from(2);
}
};
println!(
"oracle: tex {} · {} program(s) × {} probes · seed {}",
oracle.version, cfg.programs, cfg.probes, cfg.seed
);
let Ok(dir) = scratch_dir() else {
eprintln!("parity-fuzz: cannot make a scratch directory");
return std::process::ExitCode::from(2);
};
let mut diverged = 0usize;
for i in 0..cfg.programs {
let index = match cfg.once {
true => cfg.seed,
false => cfg.seed.wrapping_add(i as u64),
};
let probes = generate(index, cfg.probes);
if !diverges(&probes, &oracle, &dir, cfg.timeout) {
continue;
}
diverged += 1;
let minimal = minimize(&probes, &oracle, &dir, cfg.timeout);
let source = document(&minimal);
let (want, got) = run_both(&source, &oracle, &dir, cfg.timeout);
println!(
"\nDIVERGES program {index}, minimized to {} probe(s)\n tex : {want}\n texrs : {got}\n{}",
minimal.len(),
indent(&source)
);
}
let _ = std::fs::remove_dir_all(&dir);
match diverged {
0 => {
println!("\nPARITY: {} program(s) agree with tex.", cfg.programs);
std::process::ExitCode::SUCCESS
}
n => {
println!("\n{n}/{} program(s) diverge from tex", cfg.programs);
std::process::ExitCode::from(u8::try_from(n.min(250)).unwrap_or(250))
}
}
}
const USAGE: &str = "\
usage: parity-fuzz [OPTIONS]
--seed N first program index (default 1)
--programs N how many to generate (default 50)
--probes N constructs packed into each one (default 40)
--once run only the program named by --seed
--timeout SECS per-engine limit for one program (default 20)
-h, --help print this
";
struct Config {
seed: u64,
programs: usize,
probes: usize,
once: bool,
timeout: Duration,
help: bool,
}
impl Config {
fn parse(args: &[String]) -> Result<Self, String> {
let mut cfg = Config {
seed: 1,
programs: 50,
probes: 40,
once: false,
timeout: Duration::from_secs(20),
help: false,
};
let mut i = 0;
while i < args.len() {
let arg = args[i].as_str();
i += 1;
let mut value = |name: &str| -> Result<String, String> {
let v = args
.get(i)
.cloned()
.ok_or_else(|| format!("parity-fuzz: {name} needs a value"))?;
i += 1;
Ok(v)
};
match arg {
"-h" | "--help" => cfg.help = true,
"--once" => cfg.once = true,
"--seed" => cfg.seed = value("--seed")?.parse().map_err(|_| "bad --seed")?,
"--programs" => {
cfg.programs = value("--programs")?.parse().map_err(|_| "bad --programs")?
}
"--probes" => {
cfg.probes = value("--probes")?.parse().map_err(|_| "bad --probes")?
}
"--timeout" => {
let secs: u64 = value("--timeout")?.parse().map_err(|_| "bad --timeout")?;
cfg.timeout = Duration::from_secs(secs);
}
other => return Err(format!("parity-fuzz: unknown option: {other}")),
}
}
if cfg.once {
cfg.programs = 1;
}
Ok(cfg)
}
}
fn repo() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}
fn scratch_dir() -> std::io::Result<PathBuf> {
let dir = std::env::temp_dir().join(format!("texrs-parity-fuzz-{}", std::process::id()));
std::fs::create_dir_all(&dir)?;
Ok(dir)
}
struct Rng(u64);
impl Rng {
fn new(seed: u64) -> Self {
Rng(seed.wrapping_add(1) & 0xFFFF_FFFF)
}
fn next(&mut self, m: usize) -> usize {
self.0 = (self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)) & 0xFFFF_FFFF;
((self.0 >> 16) as usize) % m.max(1)
}
fn pick<'a, T>(&mut self, xs: &'a [T]) -> &'a T {
&xs[self.next(xs.len())]
}
}
fn reg(rng: &mut Rng) -> usize {
1 + rng.next(9)
}
fn letters(mut id: usize) -> String {
let mut out = String::new();
loop {
out.push((b'a' + (id % 26) as u8) as char);
id /= 26;
if id == 0 {
return out;
}
}
}
const WORDS: &[&str] = &[
"ALPHA", "BETA", "GAMMA", "DELTA", "EPS", "ZETA", "ETA", "THETA",
];
fn probe(rng: &mut Rng, id: usize) -> String {
let w = rng.pick(WORDS);
let r = reg(rng);
let m = format!("\\m{}", letters(id));
match rng.next(10) {
0 => format!("\\count{r}={n} \\message{{p{id}:\\the\\count{r} }}", n = rng.next(2000)),
1 => format!(
"\\count{r}={a} \\advance\\count{r} by {b} \\multiply\\count{r} by {c} \\message{{p{id}:\\the\\count{r} }}",
a = rng.next(200),
b = rng.next(100),
c = 1 + rng.next(9)
),
2 => format!(
"\\count{r}={a} \\divide\\count{r} by {d} \\message{{p{id}:\\the\\count{r} }}",
a = rng.next(1000),
d = 1 + rng.next(9)
),
3 => format!(
"\\count{r}={a} \\message{{p{id}:\\ifnum\\count{r}>{b} BIG\\else SMALL\\fi }}",
a = rng.next(50),
b = rng.next(50)
),
4 => format!(
"\\count{r}={a} \\message{{p{id}:\\ifodd\\count{r} ODD\\else EVEN\\fi }}",
a = rng.next(50)
),
5 => format!(
"\\count{r}={a} \\message{{p{id}:\\ifcase\\count{r} Z\\or O\\or T\\else M\\fi }}",
a = rng.next(5)
),
6 => format!("\\def{m}#1{{{w}-#1}}\\message{{p{id}:{m}{{{x}}} }}", x = rng.pick(WORDS)),
7 => format!(
"\\def{m}{{{w}}}\\message{{p{id}:{m} }}{{\\def{m}{{{x}}}\\message{{p{id}i:{m} }}}}\\message{{p{id}o:{m} }}",
x = rng.pick(WORDS)
),
8 => format!(
"\\count{r}={a} \\edef{m}{{\\the\\count{r} }}\\count{r}={b} \\message{{p{id}:{m}\\the\\count{r} }}",
a = rng.next(100),
b = rng.next(100)
),
_ => format!(
"\\def{m}{{{w}}}\\message{{p{id}:\\string{m} \\number{n} \\csname m{name}\\endcsname }}",
n = rng.next(1000),
name = letters(id)
),
}
}
fn generate(index: u64, count: usize) -> Vec<String> {
let mut rng = Rng::new(index);
(0..count).map(|id| probe(&mut rng, id)).collect()
}
fn document(probes: &[String]) -> String {
let mut src = String::from("\\catcode`\\{=1 \\catcode`\\}=2 \\catcode`\\#=6\n");
for p in probes {
src.push_str(p);
src.push('\n');
}
src.push_str("\\end\n");
src
}
fn run_both(source: &str, oracle: &Oracle, dir: &Path, timeout: Duration) -> (String, String) {
let path = dir.join("case.tex");
if std::fs::write(&path, source).is_err() {
return ("<unwritable>".into(), "<unwritable>".into());
}
let want = run_with_timeout(
Command::new(&oracle.program)
.arg("-interaction=nonstopmode")
.arg("case.tex")
.env("max_print_line", "8000")
.current_dir(dir),
timeout,
);
let got = run_with_timeout(
Command::new(texrs_binary()).arg(&path).current_dir(dir),
timeout,
);
(
texrs::parity::messages_of(&want),
texrs::parity::messages_of(&got),
)
}
fn texrs_binary() -> PathBuf {
std::env::current_exe()
.ok()
.and_then(|p| p.parent().map(|d| d.join("texrs")))
.unwrap_or_else(|| PathBuf::from("texrs"))
}
fn run_with_timeout(cmd: &mut Command, timeout: Duration) -> String {
use std::process::Stdio;
let Ok(mut child) = cmd.stdout(Stdio::piped()).stderr(Stdio::null()).spawn() else {
return "<unstartable>".into();
};
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(_)) => break,
Ok(None) if start.elapsed() > timeout => {
let _ = child.kill();
return "<timeout>".into();
}
Ok(None) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => return "<unwaitable>".into(),
}
}
let out = child
.wait_with_output()
.map(|o| o.stdout)
.unwrap_or_default();
String::from_utf8_lossy(&out).into_owned()
}
fn diverges(probes: &[String], oracle: &Oracle, dir: &Path, timeout: Duration) -> bool {
let (want, got) = run_both(&document(probes), oracle, dir, timeout);
want != got
}
fn minimize(probes: &[String], oracle: &Oracle, dir: &Path, timeout: Duration) -> Vec<String> {
for p in probes {
let one = vec![p.clone()];
if diverges(&one, oracle, dir, timeout) {
return one;
}
}
let mut cur = probes.to_vec();
let mut i = 0;
while i < cur.len() && cur.len() > 1 {
let mut trial = cur.clone();
trial.remove(i);
match diverges(&trial, oracle, dir, timeout) {
true => cur = trial,
false => i += 1,
}
}
cur
}
fn indent(source: &str) -> String {
source
.lines()
.map(|l| format!(" {l}\n"))
.collect::<String>()
}
#[allow(dead_code)]
fn flush() {
let _ = std::io::stdout().flush();
}