use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
static CMP_STDERR: AtomicBool = AtomicBool::new(false);
struct Rng(u64);
impl Rng {
fn seed(s: u64) -> Rng {
Rng(s ^ 0x9E37_79B9_7F4A_7C15)
}
fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn below(&mut self, n: usize) -> usize {
(self.next_u64() % n as u64) as usize
}
fn range(&mut self, lo: i64, hi: i64) -> i64 {
lo + (self.next_u64() % (hi - lo + 1) as u64) as i64
}
fn pick<'a, T>(&mut self, xs: &'a [T]) -> &'a T {
&xs[self.below(xs.len())]
}
}
fn ours_bin() -> PathBuf {
if let Ok(p) = std::env::var("CARGO_BIN_EXE_ruby") {
return PathBuf::from(p);
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
let cand = dir.join("ruby");
if cand.exists() {
return cand;
}
}
}
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("debug")
.join("ruby")
}
fn oracle() -> &'static rubylang::oracle::Oracle {
static ORACLE: std::sync::OnceLock<rubylang::oracle::Oracle> = std::sync::OnceLock::new();
ORACLE.get_or_init(|| rubylang::oracle::require_oracle("parity-fuzz"))
}
fn oracle_id() -> String {
oracle().id()
}
struct RunOut {
stdout: Vec<u8>,
stderr: Vec<u8>,
exit: i32,
timed_out: bool,
}
fn render(bytes: &[u8]) -> String {
let text = String::from_utf8_lossy(bytes);
let text = text.trim_end_matches('\n');
if std::str::from_utf8(bytes).is_err() {
let hex: Vec<String> = bytes.iter().map(|b| format!("{b:02x}")).collect();
return format!("{text}\n (hex) {}", hex.join(" "));
}
text.to_string()
}
fn norm_stderr(s: &[u8]) -> Vec<u8> {
let text = String::from_utf8_lossy(s);
let mut out = String::new();
for (i, line) in text.split('\n').enumerate() {
if i > 0 {
out.push('\n');
}
let l = match line.find(':') {
Some(idx) if line[..idx].contains("-e") || line[..idx].ends_with(".rb") => {
let rest = &line[idx + 1..];
match rest.find(": ") {
Some(j) => &rest[j + 2..],
None => line,
}
}
_ => line,
};
let l = l.strip_prefix("ruby: ").unwrap_or(l);
out.push_str(l);
}
out.into_bytes()
}
fn differs(a: &RunOut, b: &RunOut) -> bool {
if a.stdout != b.stdout || a.exit != b.exit {
return true;
}
if CMP_STDERR.load(Ordering::Relaxed) {
return norm_stderr(&a.stderr) != norm_stderr(&b.stderr);
}
false
}
fn run_with_timeout(mut cmd: Command, timeout: Duration) -> RunOut {
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(_) => {
return RunOut {
stdout: Vec::new(),
stderr: Vec::new(),
exit: -999,
timed_out: false,
}
}
};
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) => {
use std::io::Read;
let mut buf = Vec::new();
if let Some(mut out) = child.stdout.take() {
let _ = out.read_to_end(&mut buf);
}
let mut ebuf = Vec::new();
if let Some(mut err) = child.stderr.take() {
let _ = err.read_to_end(&mut ebuf);
}
return RunOut {
stdout: buf,
stderr: ebuf,
exit: status.code().unwrap_or(-1),
timed_out: false,
};
}
Ok(None) => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
return RunOut {
stdout: Vec::new(),
stderr: Vec::new(),
exit: -1,
timed_out: true,
};
}
std::thread::sleep(Duration::from_millis(2));
}
Err(_) => {
return RunOut {
stdout: Vec::new(),
stderr: Vec::new(),
exit: -998,
timed_out: false,
}
}
}
}
}
fn run_oracle(script: &str, timeout: Duration) -> RunOut {
let mut cmd = Command::new(&oracle().path);
cmd.args(["-e", script]);
run_with_timeout(cmd, timeout)
}
fn run_ours(script: &str, bin: &Path, timeout: Duration) -> RunOut {
let mut cmd = Command::new(bin);
cmd.args(["-e", script]);
cmd.env_remove("RUBYLANG_CACHE");
run_with_timeout(cmd, timeout)
}
const INTS: &[&str] = &[
"0", "1", "2", "7", "10", "-3", "-7", "42", "100", "-1", "5", "9",
];
const FLOATS: &[&str] = &[
"0.1", "0.2", "1.5", "3.14", "2.0", "-1.5", "10.0", "0.0", "100.25", "-0.5", "1e10", "1.0",
];
const WORDS: &[&str] = &[
"foo", "bar", "baz", "hello", "world", "abc", "xyz", "Ruby", "Lang",
];
const MIXED: &[&str] = &[
"1",
"\"a\"",
"nil",
":s",
"2.5",
"[9]",
"true",
"1r",
"Float::NAN",
"2**70",
];
fn ii<'a>(r: &mut Rng) -> &'a str {
r.pick(INTS)
}
fn mixed<'a>(r: &mut Rng) -> &'a str {
r.pick(MIXED)
}
fn ff<'a>(r: &mut Rng) -> &'a str {
r.pick(FLOATS)
}
fn ww<'a>(r: &mut Rng) -> &'a str {
r.pick(WORDS)
}
fn one(s: String) -> Vec<String> {
vec![s]
}
fn gen_arith(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let ops = ["+", "-", "*", "/", "%", "**"];
let a = ii(r);
let b = ii(r);
let c = ii(r);
let op1 = r.pick(&ops);
let op2 = r.pick(&ops);
one(match r.below(4) {
0 => format!("p {a} {op1} {b} {op2} {c}"),
1 => format!("p ({a} {op1} {b}) {op2} {c}"),
2 => format!("p -{a} {op1} {b}"),
_ => format!("p {a}.fdiv({b})"),
})
}
fn gen_bignum(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let e = r.range(20, 200);
let base = r.pick(&["2", "3", "7", "10"]);
one(match r.below(4) {
0 => format!("p {base} ** {e}"),
1 => format!("p (1..{}).reduce(1, :*)", r.range(15, 40)),
2 => format!("p ({base} ** {e}).to_s.length"),
_ => format!("p ({base} ** {e}) + 1"),
})
}
fn gen_floatfmt(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = ff(r);
let b = ff(r);
let ops = ["+", "-", "*", "/"];
let op = r.pick(&ops);
one(match r.below(6) {
0 => format!("p {a} {op} {b}"),
1 => format!("p {}.0 / {}.0", r.range(1, 9), r.range(1, 9)),
2 => format!("p ({a} {op} {b}).round({})", r.range(0, 6)),
3 => format!("p {a}.to_s"),
4 => format!("p 1e{}", r.range(-20, 300)),
_ => format!("p {a} {op} {b} {op} {}", ff(r)),
})
}
fn gen_strings(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = ww(r);
let i = r.range(-4, 5);
let j = r.range(-4, 5);
one(match r.below(6) {
0 => format!("p \"{w}\"[{i}]"),
1 => format!("p \"{w}\"[{i}, {}]", r.range(0, 4)),
2 => format!("p \"{w}\"[{i}..{j}]"),
3 => format!("p \"{w}\"[{i}...{j}]"),
4 => format!("p \"{w}\" * {}", r.range(0, 4)),
_ => format!("p \"{w}\".include?(\"{}\")", &w[..1.min(w.len())]),
})
}
fn gen_interp(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = ww(r);
let n = ii(r);
one(match r.below(5) {
0 => format!("p \"val=#{{{n} + {}}}\"", ii(r)),
1 => format!("p \"#{{'{w}'.upcase}}!\""),
2 => format!(
"p \"[#{{[1,2,3].map {{ |x| x * {} }}.join(',')}}]\"",
r.range(1, 4)
),
3 => format!("p \"#{{{n}}}-#{{'{w}'.length}}\""),
_ => format!("puts \"a#{{{n} * 2}}b#{{'{w}'.reverse}}c\""),
})
}
fn gen_ranges(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = r.range(-3, 5);
let b = r.range(a, a + 8);
one(match r.below(6) {
0 => format!("p ({a}..{b}).to_a"),
1 => format!("p ({a}...{b}).to_a"),
2 => format!("p ({a}..{b}).sum"),
3 => format!("p ({a}..{b}).step({}).to_a", r.range(2, 3)),
4 => format!("p ({a}..{b}).map {{ |x| x * x }}"),
_ => format!("p ({a}..{b}).select {{ |x| x % 2 == 0 }}"),
})
}
fn arr_lit(r: &mut Rng) -> String {
let n = r.range(3, 6) as usize;
let items: Vec<String> = (0..n).map(|_| ii(r).to_string()).collect();
format!("[{}]", items.join(", "))
}
fn gen_arraymeth(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = arr_lit(r);
one(match r.below(12) {
0 => format!("p {a}.map {{ |x| x + 1 }}"),
1 => format!("p {a}.select {{ |x| x > 0 }}"),
2 => format!("p {a}.reject {{ |x| x > 0 }}"),
3 => format!("p {a}.reduce(:+)"),
4 => format!("p {a}.uniq.sort"),
5 => format!("p {a}.min"),
6 => format!("p {a}.max"),
7 => format!("p {a}.first({})", r.range(1, 3)),
8 => format!("p {a}.last({})", r.range(1, 3)),
9 => format!(
"p {a}.take({}) + {a}.drop({})",
r.range(1, 3),
r.range(1, 3)
),
10 => format!("p {a}.zip({a})"),
_ => format!("p {a}.each_with_index.map {{ |x, i| x * i }}"),
})
}
fn hash_lit(r: &mut Rng) -> String {
let n = r.range(2, 4) as usize;
let items: Vec<String> = (0..n)
.map(|k| format!("{:?} => {}", format!("k{k}"), ii(r)))
.collect();
format!("{{{}}}", items.join(", "))
}
fn gen_hashmeth(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let h = hash_lit(r);
one(match r.below(6) {
0 => format!("p({h}.keys)"),
1 => format!("p({h}.values)"),
2 => format!("p({h}.map {{ |k, v| [k, v + 1] }})"),
3 => format!("p({h}.select {{ |k, v| v > 0 }})"),
4 => format!("p({h}.to_a.sort)"),
_ => format!("p({h}.each_pair.map {{ |k, v| \"#{{k}}=#{{v}}\" }}.sort)"),
})
}
fn gen_sorting(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = arr_lit(r);
let w = format!(
"[{}]",
(0..4)
.map(|_| format!("{:?}", ww(r)))
.collect::<Vec<_>>()
.join(", ")
);
let (x, y, z) = (mixed(r), mixed(r), mixed(r));
let m = r.pick(&["sort", "min", "max", "minmax"]);
let mb = r.pick(&["sort_by", "min_by", "max_by", "minmax_by"]);
let guard =
|body: &str| format!("begin\n p {body}\nrescue => e\n p [e.class, e.message]\nend");
let guard3 = |body: &str| format!("begin\n p {body}\nrescue => e\n p e.class\nend");
one(match r.below(12) {
0 => format!("p {a}.sort"),
1 => format!("p {a}.sort {{ |x, y| y <=> x }}"),
2 => format!("p {a}.sort_by {{ |x| -x }}"),
3 => format!("p {w}.sort_by(&:length)"),
4 => format!("p {a}.min_by {{ |x| x.abs }}"),
5 => format!("p {a}.max_by {{ |x| x.abs }}"),
6 => guard(&format!("[{x}, {y}].{m}")),
7 => guard3(&format!("[{x}, {y}, {z}].{m}")),
8 => guard(&format!("[{x}, {y}].{mb} {{ |e| e }}")),
9 => guard3(&format!("[{x}, {y}, {z}].{mb} {{ |e| e }}")),
10 => guard3(&format!(
"[{x}, {y}, {z}].{}({})",
if r.below(2) == 0 { "min" } else { "max" },
r.range(1, 3)
)),
_ => guard(&format!(
"[{x}, {y}].{} {{ |c, d| c <=> d }}",
r.pick(&["sort", "min", "max", "minmax"])
)),
})
}
fn gen_formatspec(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(-100, 100);
let f = ff(r);
one(match r.below(8) {
0 => format!("p format(\"%.3f\", {f})"),
1 => format!("p \"%05d\" % {n}"),
2 => format!("p \"%x\" % {}", n.abs()),
3 => format!("p \"%b\" % {}", n.abs()),
4 => format!("p \"%e\" % {f}"),
5 => format!("p \"%o\" % {}", n.abs()),
6 => format!("p \"%-8s|\" % \"{}\"", ww(r)),
_ => format!("p sprintf(\"%+d %8.2f\", {n}, {f})"),
})
}
fn gen_blocks(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(3, 6);
one(match r.below(6) {
0 => format!("p (1..{n}).map {{ |x| x ** 2 }}"),
1 => format!("p (1..{n}).select(&:even?)"),
2 => format!("p (1..{n}).reduce(0) {{ |acc, x| acc + x }}"),
3 => format!("r = []; {n}.times {{ |i| r << i }}; p r"),
4 => format!("r = []; 1.upto({n}) {{ |i| r << i * i }}; p r"),
_ => format!("p (1..{n}).each_with_object([]) {{ |x, a| a << x + 1 }}"),
})
}
fn gen_symbols(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = ww(r);
one(match r.below(5) {
0 => format!("p :{w}"),
1 => format!("p \"{w}\".to_sym"),
2 => format!("p :{w}.to_s"),
3 => format!("h = {{ {w}: {} }}; p h[:{w}]", ii(r)),
_ => format!("p %i[{} {} {}]", ww(r), ww(r), ww(r)),
})
}
fn gen_ternary(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = ii(r);
let b = ii(r);
one(match r.below(5) {
0 => format!("p {a} > {b} ? \"hi\" : \"lo\""),
1 => format!("x = nil; x ||= {a}; p x"),
2 => format!("x = {a}; x ||= {b}; p x"),
3 => format!("x = {a}; x += {b}; p x"),
_ => format!("x = {a}; x &&= {b}; p x"),
})
}
fn gen_comparison(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = ii(r);
let b = ii(r);
let bound = r.pick(&["1", "3", "nil", "\"s\"", "2.5", "Float::NAN"]);
let recv = r.pick(&["5", "0", "2.5", "\"m\"", "Float::NAN"]);
let guard =
|body: &str| format!("begin\n p {body}\nrescue => e\n p [e.class, e.message]\nend");
one(match r.below(10) {
0 => format!("p {a} <=> {b}"),
1 => format!("p {a}.0 == {a}"),
2 => format!("p [{a}, {b}] <=> [{b}, {a}]"),
3 => format!("p [{a}, {b}, {}].min", ii(r)),
4 => format!("p ({a}..{b}).include?({})", ii(r)),
5 => format!("p \"{}\" <=> \"{}\"", ww(r), ww(r)),
6 => guard(&format!(
"{recv}.clamp({bound}, {})",
r.pick(&["1", "3", "nil"])
)),
7 => guard(&format!(
"{recv}.between?({bound}, {})",
r.pick(&["1", "3", "nil"])
)),
8 => guard(&format!(
"{recv}.clamp({}{}{})",
r.pick(&["1", "3"]),
r.pick(&["..", "..."]),
r.pick(&["1", "3"])
)),
_ => guard(&format!("{recv}.clamp({bound})")),
})
}
fn gen_printf(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = ii(r);
let a = arr_lit(r);
one(match r.below(6) {
0 => format!("printf(\"%d-%d\\n\", {n}, {})", ii(r)),
1 => format!("puts {a}"),
2 => format!("print {n}, \" \", {}, \"\\n\"", ii(r)),
3 => format!("p {a}"),
4 => format!("puts [{}, [{}, {}]].inspect", ii(r), ii(r), ii(r)),
_ => format!("$stdout.write(\"{}\\n\")", ww(r)),
})
}
fn gen_string_ops(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = ww(r);
one(match r.below(11) {
0 => format!("p \"{w}\".upcase"),
1 => format!("p \"{w}\".reverse"),
2 => format!("p \"{w} {w}\".split"),
3 => format!("p [\"{w}\", \"{}\"].join(\"-\")", ww(r)),
4 => format!("p \"{w}\".gsub(\"{}\", \"X\")", &w[..1.min(w.len())]),
5 => format!("p \"{w}\".sub(/./, \"Q\")"),
6 => format!("p \" {w} \".strip"),
7 => format!("p \"{w}\".chars"),
8 => format!("p \"{w}\".center({}, \"*\")", r.range(6, 12)),
9 => format!("p \"{w}\".ljust({}, \".\")", r.range(6, 12)),
_ => format!("p \"{w}\".tr(\"a-y\", \"b-z\")"),
})
}
fn gen_caseexpr(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(0, 12);
let w = ww(r);
one(match r.below(4) {
0 => format!(
"x = {n}; p (case x; when 0..3 then \"lo\"; when 4..8 then \"mid\"; else \"hi\"; end)"
),
1 => format!(
"v = {n}; p (case v; when Integer then \"int\"; when String then \"str\"; else \"?\"; end)"
),
2 => format!(
"s = \"{w}\"; p (case s; when /^[a-c]/ then \"early\"; when /^[x-z]/ then \"late\"; else \"mid\"; end)"
),
_ => format!(
"x = {n}; r = case x when 0 then :zero when 1..5 then :small else :big end; p r"
),
})
}
fn gen_strcase(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = r.pick(&[
"Hello World",
"hello",
"HELLO",
"hElLo",
"",
"a",
"az",
"zz",
"a9",
"Zz",
"abc\n",
"abc\r\n",
" pad ",
"ÉLan",
"élan",
"Mixed123",
]);
let other = r.pick(&["hello", "HELLO", "Hello World", "zebra", "", "a"]);
let cmparg = r.pick(&["\"HELLO\"", "\"hello\"", "1", "nil", ":sym", "[1]", "2.5"]);
let aff = r.pick(&["he", "lo", "", "Hello", "xx", "\\n"]);
let width = r.range(0, 12);
let pad = r.pick(&["\" \"", "\"*\"", "\"12\"", "\"ab\""]);
one(match r.below(18) {
0 => format!("p {w:?}.downcase"),
1 => format!("p {w:?}.upcase"),
2 => format!("p {w:?}.capitalize"),
3 => format!("p {w:?}.swapcase"),
4 => format!("p {w:?}.casecmp({cmparg})"),
5 => format!("p {w:?}.casecmp?({cmparg})"),
6 => format!("p {w:?}.casecmp({other:?})"),
7 => format!("p {w:?}.chomp"),
8 => format!("p {w:?}.chomp({aff:?})"),
9 => format!("p {w:?}.chop"),
10 => format!("p {w:?}.delete_prefix({aff:?})"),
11 => format!("p {w:?}.delete_suffix({aff:?})"),
12 => format!("p {w:?}.succ"),
13 => format!("p {w:?}.succ.succ"),
14 => format!("p {w:?}.center({width}, {pad})"),
15 => format!("p {w:?}.ljust({width}, {pad})"),
16 => format!("p {w:?}.rjust({width}, {pad})"),
_ => format!("p [{w:?}.start_with?({aff:?}), {w:?}.end_with?({aff:?})]"),
})
}
fn gen_strpart(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = r.pick(&[
"hello world",
"aaa",
"a-b-c",
"abcabc",
"",
"a\nb\nc",
"a\n\nb\n\nc",
"a,b,c",
"a,b,",
"aXXbXXc",
"\n\na\n\nb",
"one two three",
]);
let ssep = r.pick(&[
"\"o\"", "\"-\"", "\"\"", "\"b\"", "\"zz\"", "\"XX\"", "\",\"",
]);
let rsep = r.pick(&[
"/o/", "/o./", "/a*/", "/[bc]/", "/(o)(.)/", "/z/", "/^a/", "/\\s+/", "/b|c/",
]);
let sep = if r.below(2) == 0 { ssep } else { rsep };
let lsep = r.pick(&["\",\"", "\"\"", "nil", "\"XX\"", "\"\\n\""]);
let pos = r.range(-3, 8);
one(match r.below(14) {
0 => format!("p {w:?}.partition({sep})"),
1 => format!("p {w:?}.rpartition({sep})"),
2 => format!("p [{w:?}.partition({sep}), $~ && $~[0]]"),
3 => format!("p [{w:?}.rpartition({sep}), $~ && $~[0]]"),
4 => format!("p {w:?}.index({sep})"),
5 => format!("p {w:?}.rindex({sep})"),
6 => format!("p {w:?}.index({sep}, {pos})"),
7 => format!("p {w:?}.rindex({sep}, {pos})"),
8 => format!("p {w:?}.lines({lsep})"),
9 => format!("p {w:?}.lines({lsep}, chomp: true)"),
10 => format!("p {w:?}.each_line({lsep}).to_a"),
11 => format!("r = []\n{w:?}.each_line({lsep}) {{ |l| r << l }}\np r"),
12 => format!("p {w:?}.partition({sep}).join(\"|\")"),
_ => format!("p [{w:?}.lines({lsep}).size, {w:?}.lines({lsep}).join]"),
})
}
fn gen_arrreshape(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = r.pick(&[
"[1, 2, 3]",
"[1, 2, 3, 4, 5]",
"[]",
"[1]",
"[1, nil, 2, nil]",
"[[1, 2], [3, 4]]",
"[[1, 2], [3, 4, 5]]",
"[[1, :a], [2, :b], [3, :a]]",
"[[1, [2, 3]], [4]]",
"[3, 1, 2]",
]);
let b = r.pick(&["[4, 5]", "[]", "[:x]", "[1, 2]"]);
let n = r.range(0, 4);
let i1 = r.range(-4, 7);
let i2 = r.range(-4, 7);
let key = r.pick(&["1", "2", ":a", ":b", "9", "nil"]);
one(match r.below(19) {
0 => format!("p {a}.combination({n}).to_a"),
1 => format!("p {a}.permutation({n}).to_a"),
2 => format!("p {a}.combination({n}).size"),
3 => format!("p {a}.product({b})"),
4 => format!("begin\n p {a}.transpose\nrescue => e\n p e.class\nend"),
5 => format!("p {a}.values_at({i1}, {i2})"),
6 => format!("p {a}.values_at({i1}..{i2})"),
7 => format!("p {a}.assoc({key})"),
8 => format!("p {a}.rassoc({key})"),
9 => format!("p {a}.rotate({i1})"),
10 => format!("p {a}.flatten"),
11 => format!("p {a}.flatten({n})"),
12 => format!("p {a}.compact"),
13 => format!("p {a}.sort.bsearch {{ |x| x >= {n} }}"),
14 => format!("p {a}.member?({key})"),
15 => format!("p {a}.values_at({i1}...{i2})"),
16 => format!("p {a}.values_at({i1}..)"),
17 => format!("p {a}.values_at(..{i2})"),
_ => format!("p [{a}.include?({key}), {a}.member?({key})]"),
})
}
fn gen_numprec(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let iv = r.pick(&[
"0", "7", "-7", "99", "100", "255", "999", "1234", "1250", "-1250", "12345", "2**70",
]);
let fv = r.pick(&[
"3.567",
"-3.567",
"2.5",
"3.5",
"-2.5",
"0.125",
"1234.5678",
"1250.0",
"0.0",
"1e10",
]);
let prec = r.range(-3, 4);
let m = r.pick(&["3", "8", "12", "18", "1", "255"]);
let mask = r.pick(&["1", "2", "4", "5", "255", "0"]);
let base = r.pick(&["2", "8", "10", "16"]);
one(match r.below(18) {
0 => format!("p ({iv}).round({prec})"),
1 => format!("p ({fv}).round({prec})"),
2 => format!("p ({fv}).round"),
3 => format!("p ({iv}).ceil({prec})"),
4 => format!("p ({fv}).ceil({prec})"),
5 => format!("p ({iv}).floor({prec})"),
6 => format!("p ({fv}).floor({prec})"),
7 => format!("p ({fv}).truncate({prec})"),
8 => format!("p ({iv}).divmod({m})"),
9 => format!("p ({fv}).divmod({m})"),
10 => format!("p [({iv}).remainder({m}), ({iv}) % ({m})]"),
11 => format!("p ({iv}).digits"),
12 => format!("p ({iv}).abs.digits({base})"),
13 => format!("p [({iv}).gcd({m}), ({iv}).lcm({m})]"),
14 => format!("p ({iv}).bit_length"),
15 => {
format!("p [({iv}).allbits?({mask}), ({iv}).anybits?({mask}), ({iv}).nobits?({mask})]")
}
16 => format!("p ({iv}).abs.to_s({base})"),
_ => format!("p ({fv}).divmod({m}).map {{ |x| x.round(3) }}"),
})
}
fn gen_objmodel(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let cname = r.pick(&["Alpha", "Beta", "Gamma9", "Delta_x"]);
let ivname = r.pick(&[
"\"@a\"",
":@a",
"\"a\"",
"\"@\"",
"\"@@a\"",
"\"@1\"",
":\"@a b\"",
"\"@\\u00e9\"",
"3",
]);
let recv = r.pick(&[
"Object.new",
"3",
"\"s\"",
"[]",
"nil",
"Class.new",
"Comparable",
]);
let meth = r.pick(&[
":puts",
":initialize",
":freeze",
":to_s",
":format",
":instance_variable_get",
":extend",
":new",
":attr_accessor",
":module_function",
":respond_to_missing?",
":binding",
]);
let succ = r.pick(&[
"-9",
"a-9",
"-a",
"1.9.9",
"9.9",
"z.z",
"Az-9",
"$9",
"1-9",
"a--9",
"zz99",
"<<koala>>",
"a!9",
"9z",
"--",
"a.9",
]);
one(match r.below(9) {
0 => format!(
"c = Class.new {{ attr_accessor :v; def hi = :hi }}\no = c.new\no.v = 1\n\
{cname} = c\np [c.name, o.class, o.hi, o.v, {cname}.new.hi, c.equal?({cname})]"
),
1 => format!(
"m = Module.new {{ def hi = :hi }}\n{cname} = m\n\
class Host_{cname}; include {cname}; end\np [m.name, Host_{cname}.new.hi, m.equal?({cname})]"
),
2 => format!(
"base = Class.new\nsub = Class.new(base)\n{cname} = base\n\
p [sub.superclass, sub.superclass.name, {{base => 1}}[{cname}]]"
),
3 => format!(
"o = Object.new\no.instance_variable_set(:@a, 1)\n\
[:instance_variable_get, :instance_variable_defined?, :remove_instance_variable].each do |m|\n \
begin\n p [m, o.send(m, {ivname})]\n rescue NameError, TypeError => e\n \
p [m, e.class, e.message]\n end\nend\np o.instance_variables"
),
4 => "o = Object.new\no.freeze\nbegin\n o.remove_instance_variable(:@a)\nrescue => e\n \
p e.class\nend"
.to_string(),
5 => format!("p [{recv}.respond_to?({meth}), {recv}.respond_to?({meth}, true)]"),
6 => "p [String.equal?(String), Object.object_id == Object.object_id, String.object_id == Object.object_id]".to_string(),
7 => format!("p {succ:?}.succ"),
_ => format!(
"c = Class.new\n{cname} = c\np [{cname}.equal?(c), {cname}.object_id == c.object_id, \
c.to_s, c.inspect]"
),
})
}
fn gen_intbits(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(-300, 300);
let (i, len) = (r.range(0, 12), r.range(0, 6));
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
one(match r.below(16) {
0 => format!("p {n}[{i}]"),
1 => format!("p {n}[{i}, {len}]"),
2 => format!("p {n}[{i}..{}]", i + len),
3 => format!("p {n}[{i}...{}]", i + len),
4 => format!("p {n}[{i}..]"),
5 => format!("p (2**70 + {n})[{}]", r.range(0, 80)),
6 => format!("p (-(2**70) + {n})[{}, 4]", r.range(0, 80)),
7 => guard(&format!(
"{}.digits({})",
n.abs(),
r.pick(&["-2", "0", "1", "2", "16", "\"a\"", "2.5"])
)),
8 => format!("p [{n} << {i}, {n} >> {i}, {n} << -{i}, {n} >> -{i}]"),
9 => format!("p [{n} >> 200, {n} << 0, 5 << {}]", r.range(-5, 5)),
10 => guard(&format!(
"{n} {} {}",
r.pick(&["&", "|", "^"]),
r.pick(&["3.0", "nil", "\"a\"", ":s", "2**70"])
)),
11 => guard(&format!(
"{n} {} {}",
r.pick(&["<<", ">>"]),
r.pick(&["1.5", "nil", "\"a\"", "2**70", "-(2**70)"])
)),
12 => guard(&format!(
"{}.pow({}, {})",
r.range(-9, 9),
r.range(-3, 40),
r.range(-9, 9)
)),
13 => guard(&format!(
"{n}.pow({}, 5)",
r.pick(&["0.5", "nil", "\"a\"", "2"])
)),
14 => guard(&format!(
"Integer({})",
r.pick(&[
"Float::NAN",
"Float::INFINITY",
"-Float::INFINITY",
"1e30",
"-1e20",
"12.9"
])
)),
_ => guard(&format!("{n}.step({}, {})", r.range(-5, 5), r.range(-2, 2))),
})
}
fn gen_structinit(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
one(match r.below(16) {
0 => format!(
"class P < Struct.new(:a, :b)\n def initialize(a, b = {b})\n super\n end\nend\np P.new({a}), P.new({a}, {b} + 1)"
),
1 => format!(
"S = Struct.new(:a) do\n def initialize(a = {a}) = super(a * 2)\nend\np S.new, S.new({b})"
),
2 => format!(
"class Q < Struct.new(:x)\n def initialize(*)\n super\n self.x ||= {a}\n end\nend\np Q.new, Q.new({b})"
),
3 => format!(
"D = Data.define(:v) do\n def initialize(v: {a}) = super(v: v * 2)\nend\np D.new, D.new({b}), D.new(v: {b})"
),
4 => format!(
"class A < Struct.new(:x); end\nclass B < A; def y = x * 2; end\np B.new({a}).y, B.new({a}) == B.new({a}), B.members"
),
5 => format!("S = Struct.new(:a, :b)\np S.new({a}, {b}).values_at({})", r.pick(&["0", "-1", "0, 1", "0..1", "1..5", "-2..-1"])),
6 => guard(&format!("S = Struct.new(:a, :b)\nS.new({a}, {b}).values_at({})", r.pick(&["2", "-3", "5", "0, 9"]))),
7 => guard(&format!("S = Struct.new(:a)\ns = S.new({a}).freeze\ns.a = {b}")),
8 => guard(&format!("D = Data.define(:a, :b)\nD.new({a}, {b}).{}", r.pick(&["a = 1", "to_a", "each", "size", "to_h", "members", "deconstruct", "inspect"]))),
9 => guard(&format!("D = Data.define(:a, :b)\nD.new({})", r.pick(&["1", "1, 2, 3", "a: 1", "a: 1, b: 2, c: 3", "\"a\" => 1, \"b\" => 2", "b: 1, a: 2"]))),
10 => guard(&format!("D = Data.define(:a, :b)\nD.new({a}, {b}).with({})", r.pick(&["", "a: 9", "c: 1", "9", "b: 0, a: 7"]))),
11 => guard(&format!("Struct.new({}); :ok", r.pick(&[":a, :a", "1", "\"Foo\", :x", "\"foo\"", "", "keyword_init: true"]))),
12 => guard(&format!("Data.define({}); :ok", r.pick(&[":a, :a", "\"a\"", ":a=", ":a?", ""]))),
13 => guard(&format!("S = Struct.new(:a, :b)\nS.new({a}, {b}).deconstruct_keys({})", r.pick(&["nil", "[:a]", "[:a, :z]", "[:z, :a]", "1", "[:a, :b, :c]"]))),
14 => "S = Struct.new(:a, :b)\np S.instance_methods(false).sort, S.method_defined?(:a=), S.new(1, 2).instance_variables".to_string(),
_ => format!("D = Data.define(:a, :b)\np D.instance_methods(false).sort, D.method_defined?(:with), D.respond_to?(:new), D.new({a}, {b}).respond_to?(:a=)"),
})
}
fn gen_hashdefault(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let copy = r.pick(&[
"merge({z: 1})",
"select { true }",
"reject { false }",
"compact",
"slice(:a)",
"except(:b)",
"transform_values { _1 }",
"dup",
"to_h",
"invert",
"sort_by { 0 }.to_h",
]);
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
one(match r.below(12) {
0 => format!("h = Hash.new({a}); h[:a] = {b}; r = h.{copy}; p [r.default, r.compare_by_identity?, r.size]"),
1 => format!("h = Hash.new {{ |hh, k| {a} }}; h[:a] = {b}; r = h.{copy}; p [r.default_proc.nil?, r[:q], r.size]"),
2 => format!("h = {{a: {a}, b: {b}}}.compare_by_identity; r = h.{copy}; p [r.compare_by_identity?, r.size]"),
3 => format!("h = Hash.new({a}); p [h.dig(:x), h.dig(:q)]"),
4 => format!("h = Hash.new {{ 1 }}; h.default = {a}; p [h.default_proc, h[:q], h.default]"),
5 => format!("h = Hash.new({a}); h.default_proc = proc {{ {b} }}; p [h.default, h[:q]]"),
6 => guard(&format!("h = {{}}; h.default_proc = {}; :ok", r.pick(&["5", "nil", "->(a) { 1 }", "->(a, b) { 1 }", "proc { |a| 1 }", "->(*a) { 1 }"]))),
7 => guard(&format!("{{a: 1}}.freeze.{}", r.pick(&["default = 1", "compare_by_identity", "default_proc = nil", "store(:b, 1)", "merge(b: 1).frozen?"]))),
8 => guard(&format!("{{a: {a}}}.dig(:a, {})", r.pick(&[":b", "0", "1"]))),
9 => format!("p [{{a: {a}}}, [1, 2]].map {{ |x| x.zip({{b: {b}}}).size }}"),
10 => format!("p [1, 2, 3].zip({}, {})", r.pick(&["{a: 1}", "1..", "(5..9)", "[7]", "Set[8, 9]"]), r.pick(&["[4]", "{}", "10..11"])),
_ => format!("h = Hash.new({a}); h2 = h.merge({{a: {b}}}); p [h2.default, h2[:zz], h2[:a]]"),
})
}
fn gen_refinement(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(1, 9);
let target = r.pick(&["String", "Integer", "Array", "Symbol"]);
let recv = match *target {
"String" => "\"ab\"",
"Integer" => "7",
"Array" => "[1, 2]",
_ => ":ab",
};
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
let defn = format!(
"module Ext\n refine {target} do\n def fz = {n}\n def size = super + 100\n end\nend\n"
);
one(match r.below(10) {
0 => format!("{defn}p({recv}.fz) rescue p $!.class\nusing Ext\np {recv}.fz"),
1 => format!("{defn}using Ext\np {recv}.size"),
2 => format!("{defn}using Ext\np {recv}.send(:fz)"),
3 => format!("{defn}using Ext\np [{recv}].map(&:fz)"),
4 => format!("{defn}using Ext\np {recv}.method(:fz).call"),
5 => format!("{defn}p Ext.refinements.size, Ext.refinements[0].target, Ext.refinements[0].class"),
6 => guard("Module.new { refine(3) {} }"),
7 => guard("Module.new { refine(String) }"),
8 => guard("using Class"),
_ => format!(
"class Box\n def v = {n}\nend\nmodule BoxExt\n refine Box do\n def v = super * 2\n def w = v + 1\n end\nend\nusing BoxExt\np Box.new.v, Box.new.w"
),
})
}
fn gen_kwsplat(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
one(match r.below(10) {
0 => format!("def m(*a, **k) = [a, k]\nh = {{k: {a}, z: {b}}}\np m(**h, k: {b}), m(k: {b}, **h)"),
1 => format!("def m(k: 0, **o) = [k, o]\nh = {{k: {a}, z: {b}}}\np m(**h, k: {b}), m(k: {b}, **h), m(z: 1, **h, w: 2)"),
2 => format!("def m(a, **nil) = a\np m({a}), m({{b: 1}})"),
3 => guard(&format!("def m(a, **nil) = a\nm({a}, b: {b})")),
4 => "def m(a, **nil) = a\np method(:m).parameters, method(:m).arity".to_string(),
5 => format!("p proc {{ |a, | a }}.call([{a}, {b}]), proc {{ |a,| }}.arity, [[{a}, {b}]].map {{ |x,| x }}"),
6 => format!("def m(a, k: {a}) = [a, k]\np m({b}), m({b}, k: 1), m({{k: 2}})"),
7 => guard(&format!("def m(a, k:) = [a, k]\nm({})", r.pick(&["1", "k: 1", "1, k: 2, j: 3", "{k: 1}", "1, {k: 2}"]))),
8 => guard("def bb(&b) = b\nbb(&5)"),
_ => format!("def m(*, **, &) = n(*, **, &)\ndef n(*a, **k) = [a, k]\np m({a}, {b}, z: 1)"),
})
}
fn gen_heredoc(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let ind = r.pick(&[" ", " ", "\t", " \t", " "]);
let ind2 = r.pick(&["", " ", "\t", " "]);
let n = r.range(0, 9);
one(match r.below(9) {
0 => format!("s = <<~EOS\n{ind}one\n{ind}{ind2}two\n{ind}three\nEOS\np s"),
1 => format!("s = <<~EOS\n{ind}one\n\n{ind}{ind2}two\nEOS\np s"),
2 => format!("s = <<~EOS\n{ind}a #{{{n}}}\n{ind2}{ind}b\nEOS\np s"),
3 => format!("s = <<~'EOS'\n{ind}raw #{{x}}\n{ind}\\n\nEOS\np s"),
4 => format!("s = <<~EOS\n{ind}x\n{ind2}\n{ind}y\nEOS\np s"),
5 => format!("x = {n}\np x<<2, [x]<<3, {n}<<-1, {n}>>1"),
6 => format!("a = [<<~A, <<~B]\n{ind}first\nA\n{ind}{ind2}second\nB\np a"),
7 => format!("s = <<-EOS\n{ind}keep\n{ind}EOS\np s"),
_ => format!("def m(s, t) = [s, t]\np m(<<~X, {n})\n{ind}xx\nX"),
})
}
fn gen_toplevelpriv(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(0, 9);
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
let d = format!("def helper = {n}\nclass Foo\n def t = helper\n def u = self.helper\nend\n");
one(match r.below(8) {
0 => format!("{d}p self.helper, send(:helper), Foo.new.t, Foo.new.u"),
1 => guard(&format!("{d}Foo.new.helper")),
2 => guard(&format!("{d}Object.new.helper")),
3 => guard(&format!("{d}public_send(:helper)")),
4 => guard(&format!("{d}Foo.new.public_send(:helper)")),
5 => format!("{d}p respond_to?(:helper), respond_to?(:helper, true), Foo.new.respond_to?(:helper)"),
6 => format!("{d}p Foo.new.send(:helper), Foo.new.method(:helper).call"),
_ => format!("o = Object.new\nbegin\n def o.sing = {n}\nend\np o.sing\nf = Object.new.freeze\nbegin; def f.x; end; rescue => e; p e.class; end"),
})
}
fn gen_raiseforms(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let msg = r.pick(&["\"m\"", "\"two words\"", "nil", ":sym", "5"]);
let cls = r.pick(&[
"RuntimeError",
"ArgumentError",
"TypeError",
"KeyError",
"IOError",
"Errno::ENOENT",
"Errno::EEXIST",
"SystemExit",
]);
let shown = "[e.class, e.message]";
let guard = |body: &str| {
format!("begin\n {body}\nrescue Exception => e\n p {shown}\nelse\n p :none\nend")
};
one(match r.below(14) {
0 => guard(&format!("raise {cls}")),
1 => guard(&format!("raise {cls}, {msg}")),
2 => guard(&format!("raise {cls}.new({msg})")),
3 => guard(&format!("raise {cls}.new, {msg}")),
4 => guard(&format!("raise {msg}")),
5 => guard(&format!("raise {}", r.pick(&["Class", "5", "nil", "Object.new", "String", ":sym", "[]"]))),
6 => guard(&format!("raise {cls}, {msg}, cause: {}", r.pick(&["nil", "RuntimeError.new(\"c\")"]))),
7 => guard("raise"),
8 => format!("e = {cls}.new({msg})\np [e.exception.equal?(e), e.exception(\"z\").message, e.exception(e).equal?(e)]"),
9 => format!("p {cls}.exception({msg}).message"),
10 => guard(&format!("raise {cls}, {msg}, [\"bt:1\"]")),
11 => guard(&format!("begin\n raise \"in\"\nrescue\n raise {cls}, {msg}\nend")).replace("p [e.class, e.message]", "p [e.class, e.message, e.cause&.message]"),
12 => format!("p Errno::{}.new({msg}).message", r.pick(&["ENOENT", "EACCES", "EEXIST", "EPIPE", "EINVAL", "ENOTDIR"])),
_ => guard(&format!("raise o = Object.new, {msg}; def o.exception(*a) = RuntimeError.new(\"obj\")")),
})
}
fn gen_rangeedge(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(-3, 6), r.range(-3, 6));
let op = r.pick(&["..", "..."]);
let guard = |body: &str| format!("p(begin; {body}; rescue => e; [e.class, e.message]; end)");
one(match r.below(14) {
0 => format!("p (({a}{op}{b}).min), (({a}{op}{b}).max), (({a}{op}{b}).minmax)"),
1 => format!("p (({a}{op}{b}).count), (({a}{op}{b}).count(&:even?)), (({a}{op}{b}).count({a}))"),
2 => format!("p (({a}{op}{b}).sum), (({a}{op}{b}).size), (({a}{op}{b}).to_a)"),
3 => format!("p (({a}{op}{b}).first), (({a}{op}{b}).last), (({a}{op}{b}).first(2)), (({a}{op}{b}).last(2))"),
4 => format!("p ({a}{op}nil).size, ({a}{op}nil).first(2), ({a}{op}nil).inspect, (nil{op}{b}).inspect"),
5 => guard(&format!("({a}..\"a\")")),
6 => guard(&format!("Range.new({a}, {}, {})", r.pick(&["nil", "\"a\"", "Object.new", "2.5"]), r.pick(&["true", "false"]))),
7 => format!("p (({a}..{b}) == ({a}..{b}.0)), (({a}..{b}).eql?({a}..{b})), (({a}..{b}).hash == ({a}..{b}).hash)"),
8 => format!("p (({a}{op}{b}).step(2).to_a), (({a}{op}{b}) % 3).to_a"),
9 => guard(&format!("({a}..{b}).step({})", r.pick(&["0", "-1", "0.5", "\"a\""]))),
10 => format!("p [1, 2, 3, 4, 5].chunk {{ |x| {} }}.to_a", r.pick(&["x > 3 ? :_separator : true", "x.even? ? nil : :odd", "x == 3 ? :_alone : :k", "x % 3"])),
11 => guard("[1, 2].chunk { :_other }.to_a"),
12 => format!("a = [1, 2, 3]\np a.fill({a}, {}, {})", r.range(0, 5), r.range(0, 3)),
_ => guard(&format!("a = [1, 2, 3]\na.insert({}, :x)\na", r.range(-6, 5))),
})
}
#[derive(Clone, Copy)]
enum Mode {
Arith,
Bignum,
Floatfmt,
Strings,
Interp,
Ranges,
Arraymeth,
Hashmeth,
Sorting,
Formatspec,
Blocks,
Symbols,
Ternary,
Comparison,
Printf,
StringOps,
Caseexpr,
Intmeth,
Regex,
Enumerable,
Exceptions,
Struct,
Rational,
Patternmatch,
Kernelconv,
Loopflow,
Hashenum,
Enumext,
Kwargs,
Metaprog,
Mixins,
Lambda,
Enumlazy,
Setops,
Frozen,
Datacls,
Strenc,
Complexnum,
Objintro,
Blockflow,
Methobj,
Multiyield,
Eqlident,
Numwide,
Typeerr,
Timefmt,
Bytestr,
Packfmt,
Trsets,
Strcase,
Strpart,
Arrreshape,
Numprec,
Objmodel,
Intbits,
Structinit,
Hashdefault,
Refinement,
Kwsplat,
Heredoc,
Toplevelpriv,
Raiseforms,
Rangeedge,
All,
}
const ALL_MODES: &[Mode] = &[
Mode::Arith,
Mode::Bignum,
Mode::Floatfmt,
Mode::Strings,
Mode::Interp,
Mode::Ranges,
Mode::Arraymeth,
Mode::Hashmeth,
Mode::Sorting,
Mode::Formatspec,
Mode::Blocks,
Mode::Symbols,
Mode::Ternary,
Mode::Comparison,
Mode::Printf,
Mode::StringOps,
Mode::Caseexpr,
Mode::Intmeth,
Mode::Regex,
Mode::Enumerable,
Mode::Exceptions,
Mode::Struct,
Mode::Rational,
Mode::Patternmatch,
Mode::Kernelconv,
Mode::Loopflow,
Mode::Hashenum,
Mode::Enumext,
Mode::Kwargs,
Mode::Metaprog,
Mode::Mixins,
Mode::Lambda,
Mode::Enumlazy,
Mode::Setops,
Mode::Frozen,
Mode::Datacls,
Mode::Strenc,
Mode::Complexnum,
Mode::Objintro,
Mode::Blockflow,
Mode::Methobj,
Mode::Multiyield,
Mode::Eqlident,
Mode::Numwide,
Mode::Typeerr,
Mode::Timefmt,
Mode::Bytestr,
Mode::Packfmt,
Mode::Trsets,
Mode::Strcase,
Mode::Strpart,
Mode::Arrreshape,
Mode::Numprec,
Mode::Objmodel,
Mode::Intbits,
Mode::Structinit,
Mode::Hashdefault,
Mode::Refinement,
Mode::Kwsplat,
Mode::Heredoc,
Mode::Toplevelpriv,
Mode::Raiseforms,
Mode::Rangeedge,
];
fn gen_intmeth(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = ii(r);
let b = ii(r);
one(match r.below(14) {
0 => format!("p {a}.gcd({b})"),
1 => format!("p {a}.lcm({b})"),
2 => format!("p {a}.abs"),
3 => format!("p {a}.divmod({b})"),
4 => format!("p {a}.abs.bit_length"),
5 => format!("p {a}.abs.digits"),
6 => format!("p {a}.to_s(2)"),
7 => format!(
"p {}.pow({}, {})",
r.range(2, 9),
r.range(1, 6),
r.range(2, 9)
),
8 => format!("p({a} & {b})"),
9 => format!("p({a} | {b})"),
10 => format!("p({a} ^ {b})"),
11 => format!("p({a} << {})", r.range(0, 5)),
12 => format!("p [{a}.even?, {a}.odd?, {a}.zero?]"),
_ => format!(
"p {a}.abs.to_s({}).to_i({})",
r.range(2, 17),
r.range(2, 17)
),
})
}
fn gen_regex(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let s = format!("{}{}", ww(r), ww(r));
let pats = [
"[a-c]+", "o+", "[aeiou]", "\\w+", "l+", "[a-z]{2}", "^.", ".$",
];
let p = r.pick(&pats);
let q = r.pick(&pats);
let flags = ["", "i", "m", "x", "im", "mi", "imx"];
let (f, g) = (r.pick(&flags), r.pick(&flags));
one(match r.below(19) {
0 => format!("p(\"{s}\" =~ /{p}/)"),
1 => format!("p \"{s}\".match?(/{p}/)"),
2 => format!("p \"{s}\".scan(/{p}/)"),
3 => format!("p \"{s}\".gsub(/{p}/, \"X\")"),
4 => format!("p \"{s}\".sub(/{p}/, \"X\")"),
5 => format!("p \"{s}\"[/{p}/]"),
6 => format!("p \"{s}\".match(/{p}/) ? \"m\" : \"no\""),
7 => format!("p \"{s}\".gsub(/([a-z])\\1/, \"D\")"),
8 => format!("p \"{s}\".split(/{p}/)"),
9 => format!("p \"{s}\".scan(/{p}/).length"),
10 => format!("p(/{p}/{f} == /{q}/{g})"),
11 => format!("p(/{p}/{f}.eql?(/{q}/{g}))"),
12 => format!("p(/{p}/{f}.hash == /{q}/{g}.hash)"),
13 => format!("p([/{p}/{f}, /{q}/{g}, /{p}/{f}].uniq.size)"),
14 => format!("p({{/{p}/{f} => 1}}[/{q}/{g}])"),
15 => format!("p([/{p}/{f}].include?(/{q}/{g}))"),
16 => format!("p(([/{p}/{f}, /{q}/{g}] - [/{p}/{f}]).size)"),
17 => format!("p([/{p}/{f}.options, /{p}/{f}.inspect, /{p}/{f}.source])"),
_ => format!("p(Regexp.new('{p}') == /{p}/)"),
})
}
fn gen_enumerable(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let a = arr_lit(r);
one(match r.below(14) {
0 => format!("p {a}.each_slice(2).to_a"),
1 => format!("p {a}.each_cons(2).to_a"),
2 => format!("p {a}.partition {{ |x| x > 0 }}"),
3 => format!("p {a}.group_by {{ |x| x % 2 }}"),
4 => format!("p {a}.flat_map {{ |x| [x, -x] }}"),
5 => format!("p {a}.chunk_while {{ |a, b| b > a }}.to_a"),
6 => format!("p {a}.take_while {{ |x| x > 0 }}"),
7 => format!("p {a}.drop_while {{ |x| x > 0 }}"),
8 => format!("p {a}.each_with_object([]) {{ |x, m| m << x * 2 }}"),
9 => format!("p {a}.tally"),
10 => format!("p {a}.min_by {{ |x| x.abs }}"),
11 => format!("p {a}.max_by {{ |x| x.abs }}"),
12 => format!("p {a}.sum"),
_ => format!("p {a}.sort_by {{ |x| -x }}"),
})
}
fn gen_exceptions(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = ww(r);
let n = ii(r);
let bad_recv = r.pick(&["{}", "(1..2)", ":s", "nil", "true", "proc {}"]);
one(match r.below(11) {
0 => format!("p (begin; raise \"{w}\"; rescue => e; e.message; end)"),
1 => format!("p (begin; Integer(\"{w}\"); rescue ArgumentError; :caught; end)"),
2 => format!("p (begin; {n} / 0; rescue ZeroDivisionError => e; e.message; end)"),
3 => "p (begin; [].fetch(9); rescue IndexError; :idx; end)".to_string(),
4 => format!(
"p (begin; raise ArgumentError, \"{w}\"; rescue => e; [e.class.to_s, e.message]; end)"
),
5 => "r = []; begin; r << 1; raise \"x\"; rescue; r << 2; ensure; r << 3; end; p r"
.to_string(),
6 => format!("p (begin; {{}}.fetch(:{w}); rescue KeyError; :key; end)"),
7 => "class E1 < StandardError; end; p (begin; raise E1; rescue E1; :custom; end)"
.to_string(),
8 => format!("p (begin; -{bad_recv}; rescue NoMethodError => e; e.message; end)"),
9 => format!(
"p (begin; {bad_recv} {} 1; rescue NoMethodError => e; e.message; end)",
r.pick(&["+", "-", "*", "/"])
),
_ => "p (begin; nil.foo; rescue NoMethodError; :nome; end)".to_string(),
})
}
fn gen_struct(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (x, y) = (ii(r), ii(r));
one(match r.below(8) {
0 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).to_a"),
1 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).to_h"),
2 => format!("S = Struct.new(:a, :b); p S.new({x}, {y}).members"),
3 => format!("S = Struct.new(:a, :b); p(S.new({x}, {y}) == S.new({x}, {y}))"),
4 => format!("S = Struct.new(:a, :b); s = S.new({x}, {y}); p [s.a, s.b]"),
5 => format!("S = Struct.new(:a, :b); s = S.new({x}, {y}); s.a = {y}; p s.a"),
6 => format!("S = Struct.new(:a, :b, keyword_init: true); p S.new(a: {x}, b: {y}).to_h"),
_ => format!("S = Struct.new(:a, :b); p S.new({x}, {y})[0]"),
})
}
fn gen_loopflow(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(2, 5);
let k = r.range(1, 3);
one(match r.below(18) {
0 => format!("c = 0; {n}.times {{ |i| c += 1; redo if c == {k} }}; p c"),
1 => format!(
"c = 0; r = []; [1, 2, 3].each {{ |x| c += 1; redo if c == {k}; r << [x, c] }}; p [r, c]"
),
2 => format!(
"i = 0; c = 0\nwhile i < {n}\n c += 1\n if c == {k}\n i += 1\n redo\n end\n i += 1\nend\np [i, c]"
),
3 => format!("c = 0\nfor x in 1..{n}\n c += 1\n redo if c == {k}\nend\np [c, x]"),
4 => format!(
"c = 0\nuntil c >= {n}\n c += 1\n redo if c == {k}\nend\np c"
),
5 => format!(
"c = 0\ni = 0\nwhile i < {n}\n begin\n c += 1\n redo if c == {k}\n end\n i += 1\nend\np [i, c]"
),
6 => format!("r = []; [1, 2, 3].each {{ |x| next if x == {k}; r << x }}; p r"),
7 => format!("p (while true do break {n} end)"),
8 => format!("i = 0; while i < {n}; i += 1; break if i == {k}; end; p i"),
9 => format!("for i in 1..{n}\n sq = i * i\nend\np [i, sq, defined?(sq)]"),
10 => format!("for i in []\n z = {n}\nend\np [i, z, defined?(z)]"),
11 => format!(
"ps = []\nfor i in 0...{n}\n t = i * 2\n ps << -> {{ [i, t] }}\nend\np ps.map(&:call)"
),
12 => format!(
"for k, v in {{a: 1, b: {n}}}\n s = \"#{{k}}=#{{v}}\"\nend\np [k, v, s]"
),
13 => format!(
"a = 0\nbegin\n a += 1\n raise \"x\" if a < {k}\nrescue\n retry if a < {k}\nend\np a"
),
14 => format!(
"for i in 1..{n}\n if i == {k}\n m = i\n end\nend\np [m, defined?(m)]"
),
15 => format!(
"out = []\nfor i in 1..{n}\n for j in 1..2\n out << i * j\n end\nend\np [out, i, j]"
),
16 => format!("c = 0; [1, 2].map {{ |x| c += 1; redo if c == {k}; x * 10 }}.then {{ |a| p [a, c] }}"),
_ => format!(
"r = []\n{n}.times do |i|\n r << i\n break if i == {k}\nend\np r"
),
})
}
fn gen_hashenum(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let h = hash_lit(r);
one(match r.below(20) {
0 => format!("r = []; {h}.each {{ |x| r << x }}; p r"),
1 => format!("r = []; {h}.each_pair {{ |x| r << x }}; p r"),
2 => format!("p({h}.map {{ |x| x }})"),
3 => format!("p({h}.collect {{ |x| x }})"),
4 => format!("p({h}.find {{ |x| x.is_a?(Array) }})"),
5 => format!("p({h}.detect {{ |x| x[1] > 0 }})"),
6 => format!("p({h}.count {{ |x| x.is_a?(Array) }})"),
7 => format!("p({h}.count)"),
8 => format!("p({h}.sum(0) {{ |x| x[1] }})"),
9 => format!("p({h}.flat_map {{ |x| x }})"),
10 => format!("p({h}.filter_map {{ |x| x[0] }})"),
11 => format!("p [{h}.any? {{ |x| x.is_a?(Array) }}, {h}.all? {{ |x| x.size == 2 }}, {h}.none? {{ |x| x.nil? }}]"),
12 => format!("p({h}.take_while {{ |x| x.is_a?(Array) }})"),
13 => format!("p({h}.drop_while {{ |x| x.is_a?(Array) }})"),
14 => format!("p({h}.find_index {{ |x| x[1] > 0 }})"),
15 => format!("p({h}.min_by {{ |x| x[1] }})"),
16 => format!("p({h}.sort_by {{ |x| x[0] }})"),
17 => format!("p({h}.to_h {{ |k, v| [k.to_s, v] }})"),
18 => format!("p({h}.each_with_object([]) {{ |x, a| a << x }})"),
_ => format!("p [{h}.first, {h}.reverse_each.to_a, {h}.tally.size]"),
})
}
fn gen_enumext(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(1, 4);
let m = r.range(2, 5);
one(match r.below(14) {
0 => "e = Enumerator.new { |y| y << 1; y << 2; y << 3 }; p [e.next, e.next, e.next]".to_string(),
1 => "e = Enumerator.new { |y| y << 1; y << 2 }; p [e.next, e.peek, e.next]".to_string(),
2 => "log = []\ne = Enumerator.new { |y| log << :a; y << 1; log << :b; y << 2; log << :c }\np log\np e.next\np log\np e.next\np log"
.to_string(),
3 => "e = Enumerator.new { |y| y << 1; raise \"boom\" }\np e.next\nbegin\n e.next\nrescue => ex\n p [ex.class, ex.message]\nend"
.to_string(),
4 => "e = Enumerator.new { |y| y << 1; raise ArgumentError, \"bad\" }\np e.next\nbegin\n e.next\nrescue ArgumentError => ex\n p [ex.class, ex.is_a?(StandardError)]\nend"
.to_string(),
5 => "e = Enumerator.new { |y| i = 0; loop { y << i; i += 1 } }\np [e.next, e.next, e.next]"
.to_string(),
6 => format!(
"e = Enumerator.new {{ |y| i = 0; loop {{ y << i; i += 1 }} }}\np e.first({m})\np e.take({n})"
),
7 => format!(
"e = Enumerator.new {{ |y| i = 0; loop {{ y << i * 2; i += 1 }} }}\np e.lazy.map {{ |x| x + 1 }}.first({m})"
),
8 => format!(
"e = Enumerator.new {{ |y| {n}.times {{ |i| y << i }} }}\nr = []\nloop {{ r << e.next }}\np r"
),
9 => "e = Enumerator.new { |y| y << 1; y << 2 }\np e.next\ne.rewind\np e.next\np e.to_a"
.to_string(),
10 => "e = Enumerator.new { |y| y << 1 }\np e.next\nbegin\n e.next\nrescue StopIteration => ex\n p ex.class\nend"
.to_string(),
11 => format!(
"a = Enumerator.new {{ |y| {m}.times {{ |i| y << \"a#{{i}}\" }} }}\nb = Enumerator.new {{ |y| {m}.times {{ |i| y << \"b#{{i}}\" }} }}\np [a.next, b.next, a.next, b.next]"
),
12 => format!("e = Enumerator.new {{ |y| y.yield({n}, {m}); y << 9 }}; p [e.next, e.next]"),
_ => "e = [1, 2, 3].each; p [e.next, e.peek, e.next, e.next]".to_string(),
})
}
fn gen_kwargs(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (ii(r), ii(r));
one(match r.below(12) {
0 => format!("def f(x:, y: {b}) = [x, y]\np f(x: {a})"),
1 => format!("def f(x:, y:) = [x, y]\np f(y: {b}, x: {a})"),
2 => format!("def f(a, x: {b}) = [a, x]\np f({a})"),
3 => format!("def f(**o) = o\np f(a: {a}, b: {b})"),
4 => format!("def f(x:, **o) = [x, o]\np f(x: {a}, z: {b})"),
5 => format!("def f(x:, y: {b}) = [x, y]\nh = {{x: {a}, y: {b}}}\np f(**h)"),
6 => format!("def f(a, b = {b}, *r, k:, **o) = [a, b, r, k, o]\np f({a}, k: {b})"),
7 => "def f(x:) = x\nbegin\n f\nrescue ArgumentError => e\n p e.class\nend".to_string(),
8 => format!("def f(x:) = x\nbegin\n f(x: {a}, y: {b})\nrescue ArgumentError => e\n p e.class\nend"),
9 => format!("f = ->(x:, y: {b}) {{ [x, y] }}\np f.call(x: {a})"),
10 => format!("def f(*a, **o) = [a, o]\np f({a}, {b}, k: {a})"),
_ => format!("def f(x: {a}) = x\np [f, f(x: {b})]"),
})
}
fn gen_metaprog(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (ii(r), ii(r));
let w = ww(r);
one(match r.below(14) {
0 => format!(
"class C\n def method_missing(n, *a) = [n, a]\n def respond_to_missing?(n, p = false) = true\nend\np C.new.{w}({a})"
),
1 => format!(
"class C\n def method_missing(n, *a) = n.to_s\nend\np [C.new.respond_to?(:{w}), C.new.{w}]"
),
2 => format!(
"class C\n define_method(:m) {{ |x| x + {a} }}\nend\np C.new.m({b})"
),
3 => format!(
"class C\n [:a, :b].each {{ |n| define_method(n) {{ n.to_s * {} }} }}\nend\np [C.new.a, C.new.b]",
r.range(1, 3)
),
4 => "module M\n def m = \"M\" + super\nend\nclass C\n prepend M\n def m = \"C\"\nend\np C.new.m"
.to_string(),
5 => "module M\n def m = \"M\"\nend\nclass C\n include M\n def m = \"C\" + super\nend\np C.new.m"
.to_string(),
6 => format!("class C; def m = {a}; end\np [C.new.send(:m), C.new.public_send(:m)]"),
7 => format!(
"o = Object.new\ndef o.m = {a}\np [o.m, o.singleton_methods.sort]"
),
8 => format!(
"class C\n def m = {a}\nend\nC.class_eval {{ def n = {b} }}\np [C.new.m, C.new.n]"
),
9 => format!(
"class C; end\nC.define_method(:m) {{ {a} }}\np C.new.m"
),
10 => format!(
"class C\n def initialize; @x = {a}; end\nend\np C.new.instance_variable_get(:@x)"
),
11 => format!(
"class C; def m = {a}; end\np [C.instance_methods(false).sort, C.new.respond_to?(:m)]"
),
12 => format!(
"module M\n def self.included(b) = b.const_set(:TAG, {a})\nend\nclass C\n include M\nend\np C::TAG"
),
_ => format!(
"class C\n def method_missing(n, *a)\n n.to_s.start_with?(\"get_\") ? {a} : super\n end\nend\nbegin\n C.new.nope\nrescue NoMethodError => e\n p e.class\nend\np C.new.get_x"
),
})
}
fn gen_mixins(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let cmp = "class N\n include Comparable\n attr_reader :v\n def initialize(v) = @v = v\n def <=>(o) = v <=> o.v\n def to_s = \"N(#{v})\"\nend";
let enu = "class Bag\n include Enumerable\n def initialize(*xs) = @xs = xs\n def each(&b) = @xs.each(&b)\nend";
one(match r.below(14) {
0 => format!("{cmp}\np(N.new({a}) < N.new({b}))"),
1 => format!("{cmp}\np(N.new({a}) >= N.new({b}))"),
2 => format!("{cmp}\np N.new({a}).between?(N.new(0), N.new(9))"),
3 => format!("{cmp}\np N.new({a}).clamp(N.new(2), N.new(6)).to_s"),
4 => format!("{cmp}\np [N.new({a}), N.new({b})].max.to_s"),
5 => format!("{cmp}\np [N.new({a}), N.new({b})].sort.map(&:to_s)"),
6 => format!("{enu}\np Bag.new({a}, {b}, 3).map {{ |x| x * 2 }}"),
7 => format!("{enu}\np Bag.new({a}, {b}, 3).select(&:even?)"),
8 => format!("{enu}\np Bag.new({a}, {b}, 3).sort"),
9 => format!("{enu}\np Bag.new({a}, {b}, 3).include?({a})"),
10 => format!("{enu}\np Bag.new({a}, {b}, 3).each_with_index.to_a"),
11 => format!(
"{enu}\np [Bag.new({a}, {b}).min, Bag.new({a}, {b}).max, Bag.new({a}, {b}).sum]"
),
12 => format!("{enu}\np Bag.new({a}, {b}, 3).partition(&:odd?)"),
_ => format!("{enu}\np Bag.new({a}, {b}, 3).each_slice(2).to_a"),
})
}
fn gen_rational(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(1, 12), r.range(1, 12));
let (c, d) = (r.range(1, 12), r.range(1, 12));
let n = ii(r);
let relop = r.pick(&["<", ">", "<=", ">="]);
let operand = r.pick(&["Float::NAN", "nil", ":sym", "\"s\"", "[1]", "Object.new"]);
one(match r.below(19) {
0 => format!("p(Rational({a}, {b}) + Rational({c}, {d}))"),
1 => format!("p(Rational({a}, {b}) - Rational({c}, {d}))"),
2 => format!("p(Rational({a}, {b}) * Rational({c}, {d}))"),
3 => format!("p(Rational({a}, {b}) / Rational({c}, {d}))"),
4 => format!("p(Rational({a}, {b}) % Rational({c}, {d}))"),
5 => format!("p(Rational({a}, {b}) ** {})", r.range(-3, 4)),
6 => format!("p(Rational({a}, {b}) <=> Rational({c}, {d}))"),
7 => format!("p(Rational({a}, {b}) + {n})"),
8 => format!("p(Rational({a}, {b}).to_f.round(6))"),
9 => format!("p [Rational({a}, {b}).numerator, Rational({a}, {b}).denominator]"),
10 => format!("p({n} / Rational({c}, {d}))"),
11 => format!(
"begin\n p(Rational({a}, {b}) {relop} Float::NAN)\nrescue ArgumentError => e\n p e.message\nend"
),
12 => format!(
"begin\n p(Float::NAN {relop} Rational({a}, {b}))\nrescue ArgumentError => e\n p e.message\nend"
),
13 => format!(
"begin\n p(Rational({a}, {b}) {relop} {operand})\nrescue => e\n p [e.class, e.message]\nend"
),
14 => format!("p(Rational({a}, {b}) <=> Float::NAN)"),
15 => format!(
"begin\n p(Rational({a}, {b}).send(:{relop}, {operand}))\nrescue => e\n p [e.class, e.message]\nend"
),
16 => format!(
"begin\n p(Rational({a}, {b}).{}({}, {}))\nrescue => e\n p [e.class, e.message]\nend",
r.pick(&["between?", "clamp"]),
r.pick(&["0", "1", "nil", "Rational(1, 2)", "\"s\""]),
r.pick(&["0", "1", "nil", "Rational(9, 2)"])
),
17 => format!(
"begin\n p(Rational({a}, {b}).clamp({}{}{}))\nrescue => e\n p [e.class, e.message]\nend",
r.pick(&["0", "1"]),
r.pick(&["..", "..."]),
r.pick(&["0", "3"])
),
_ => format!(
"p [Rational({a}, {b}) {relop} Rational({c}, {d}), Rational({a}, {b}) {relop} {c}, Rational({a}, {b}) {relop} {c}.0, Rational({a}, {b}) {relop} (10 ** 20)]"
),
})
}
fn gen_patternmatch(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(0, 12);
let (x, y) = (ii(r), ii(r));
one(match r.below(8) {
0 => format!("case [{x}, {y}]; in [a, b]; p a + b; end"),
1 => format!("case {{a: {x}, b: {y}}}; in {{a:, b:}}; p [a, b]; end"),
2 => format!("case [1, {x}, 3]; in [1, m, 3]; p m; in _; p :no; end"),
3 => format!("case {n}; in 0..5; p :lo; in Integer; p :hi; end"),
4 => format!("case [{x}, {y}]; in [Integer => a, Integer => b]; p a * b; end"),
5 => format!("case [1, 2, {x}, {y}]; in [_, _, *rest]; p rest; end"),
6 => format!(
"case {{name: \"{}\", age: {n}}}; in {{name: String => s}}; p s; end",
ww(r)
),
_ => {
format!("r = (case {n}; in 0 then :z; in n if n > 5 then :big; else :small; end); p r")
}
})
}
fn gen_blockflow(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let v = ii(r);
let w = ww(r);
let arr_meths = [
"each",
"map",
"select",
"filter",
"reject",
"find",
"detect",
"find_index",
"sort_by",
"min_by",
"max_by",
"group_by",
"partition",
"take_while",
"drop_while",
"sum",
"count",
"flat_map",
"each_with_index",
"each_entry",
"find_all",
"filter_map",
"reverse_each",
"each_index",
"any?",
"all?",
"none?",
"one?",
"delete_if",
"keep_if",
];
let hash_meths = [
"each",
"each_pair",
"map",
"select",
"filter",
"reject",
"find",
"detect",
"each_with_index",
"each_key",
"each_value",
"sort_by",
"min_by",
"max_by",
"group_by",
"partition",
"sum",
"count",
"any?",
"all?",
"none?",
"one?",
"delete_if",
"keep_if",
"transform_values",
"transform_keys",
"filter_map",
"flat_map",
"each_entry",
"find_all",
];
one(match r.below(24) {
0 => format!("p([1, 2, 3].{} {{ |x| break {v} }})", r.pick(&arr_meths)),
1 => format!(
"p({{a: 1, b: 2}}.{} {{ |k, vv| break {v} }})",
r.pick(&hash_meths)
),
2 => format!(
"p([1, 2, 3, 4].{} {{ |x| break x * 10 if x == {}; x }})",
r.pick(&arr_meths),
r.range(1, 4)
),
3 => format!("p([1, 2, 3, 4].each_slice({}) {{ |s| break {v} }})", r.range(1, 3)),
4 => format!("p([1, 2, 3, 4].each_cons({}) {{ |s| break {v} }})", r.range(1, 3)),
5 => format!("p([1, 2, 3].each_with_object([]) {{ |x, acc| break {v} }})"),
6 => format!("p(\"{w}\".each_char {{ |c| break {v} }})"),
7 => format!("p(\"a\\nb\\nc\".each_line {{ |l| break {v} }})"),
8 => format!("p((1..{}).each_with_index {{ |x, i| break {v} }})", r.range(2, 5)),
9 => format!("p({}.times {{ |i| break {v} }})", r.range(1, 4)),
10 => format!("p(1.upto({}) {{ |i| break {v} }})", r.range(2, 5)),
11 => format!(
"def y\n yield 1\n :after\nend\np(y {{ |x| break {v} }})"
),
12 => format!(
"def y2\n r = yield 1\n [:got, r]\nend\np(y2 {{ |x| next {v} }})"
),
13 => format!(
"p([1, 2].map {{ |a| [3, 4].each {{ |b| break {v} }} }})"
),
14 => format!(
"p([1, 2].each {{ |a| [3, 4].each {{ |b| break {v} }}; }})"
),
15 => format!(
"def m\n [1, 2, 3].each {{ |x| return x + {} if x == 2 }}\n :fell\nend\np m",
r.range(0, 9)
),
16 => "def m2\n [1, 2].each { |a| [3, 4].each { |b| return [a, b] if b == 4 } }\n :none\nend\np m2".to_string(),
17 => format!(
"def pr\n q = Proc.new {{ return {v} }}\n q.call\n :after\nend\np pr"
),
18 => format!(
"def la\n q = lambda {{ return {v} }}\n q.call\n :after\nend\np la"
),
19 => format!("l = lambda {{ break {v} }}\np l.call"),
20 => "def e\n o = []\n [1, 2, 3].each { |i| begin; o << i; break if i == 2; ensure; o << :E; end }\n o\nend\np e".to_string(),
21 => format!(
"def e2\n begin\n [1, 2].each {{ |i| return {v} if i == 2 }}\n ensure\n nil\n end\n :no\nend\np e2"
),
22 => format!(
"def e3\n r = begin\n {v}\n rescue\n -1\n ensure\n -2\n end\n r\nend\np e3"
),
_ => format!(
"for i in 1..{}\n sq = i\nend\np [i, sq, defined?(sq)]\n[9].each {{ |jj| kk = jj }}\np [defined?(jj), defined?(kk)]",
r.range(2, 4)
),
})
}
fn gen_kernelconv(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = ii(r);
let w = ww(r);
one(match r.below(11) {
0 => format!("p Integer(\"{}\")", r.range(0, 999)),
1 => "p Integer(\"ff\", 16)".to_string(),
2 => format!(
"p Integer(\"{}\", 2)",
if r.below(2) == 0 { "1010" } else { "1101" }
),
3 => format!("p Float(\"{}.5\")", r.range(0, 99)),
4 => "p Array(nil)".to_string(),
5 => format!("p Array([{n}])"),
6 => format!("p Array({n})"),
7 => format!("p (begin; Integer(\"{w}\"); rescue ArgumentError; :bad; end)"),
8 => format!("p String({n})"),
9 => format!("p format(\"%05.2f\", {})", r.range(0, 99)),
_ => format!("p Integer({n}.to_f)"),
})
}
fn gen_multiyield(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let pair_srcs = [
"[10, 20, 30].each_with_index",
"[10, 20].each_with_object([])",
"%w[a b c].each_with_index",
"(1..3).each_with_index",
"Enumerator.new { |y| y.yield 1, 2; y.yield 3, 4 }",
"Enumerator.new { |y| y.yield 5, 6 }",
];
let pack_srcs = [
"{a: 1, b: 2}",
"[[1, 2], [3, 4]]",
"[1, 2, 3, 4].each_slice(2)",
"[1, 2, 3].each_cons(2)",
"Enumerator.new { |y| y << [1, 2]; y << [3, 4] }",
];
let probes = [
"{ |x| x.is_a?(Array) }",
"{ |x| x.to_s.size > 1 }",
"{ |x, i| x.is_a?(Array) }",
"{ |*a| a.size > 1 }",
"{ |x, i| i.nil? }",
];
let src = if r.below(3) == 0 {
r.pick(&pack_srcs)
} else {
r.pick(&pair_srcs)
};
let b = r.pick(&probes);
let consumers = [
"map",
"collect",
"flat_map",
"filter_map",
"take_while",
"count",
"find_index",
"any?",
"all?",
"none?",
"one?",
"select",
"filter",
"reject",
"sort_by",
"group_by",
"partition",
"drop_while",
"find",
"detect",
"min_by",
"max_by",
"uniq",
"find_all",
];
one(match r.below(13) {
10 if !src.starts_with("Enumerator.new") => format!(
"p({src}.lazy.{}{})",
r.pick(&["map { |x| x }", "select { |x| x }", "take_while { |x| x }", "reject { |x| x }"]),
r.pick(&["", ".take(2)", ".drop(1)", ".zip([1, 2])", ".map { |x| x }"])
),
11 => format!(
"p({src}.lazy.{} {{ break {} }}.to_a)",
r.pick(&["map", "select", "reject", "take_while", "drop_while", "filter_map"]),
r.range(1, 9)
),
12 => format!(
"begin\n {src}.lazy.{} {{ break }}.first(1)\nrescue LocalJumpError => e\n p e.message\nend",
r.pick(&["map", "select", "take_while", "filter_map"])
),
0 | 10 => format!("p({src}.{} {b})", r.pick(&consumers)),
1 => format!("p({src}.to_a)"),
2 => format!("{src}.each {b}\np :done"),
3 if !src.starts_with("Enumerator.new") => {
format!("p({src}.each {} .to_a)", "{ |x| x }")
}
3 => format!("p({src}.to_a.size)"),
4 => format!("p({src}.map {b})"),
5 => format!("p({src}.take_while {b})"),
6 => format!(
"p({src}.lazy.{} {b}.first(2))",
r.pick(&[
"map",
"select",
"take_while",
"reject",
"filter_map",
"drop_while"
])
),
7 => format!("p({src}.lazy.map {} .to_a)", "{ |x| x }"),
8 => format!("p({src}.each_with_object([]) {} )", "{ |x, acc| acc << x }"),
_ => format!(
"p({src}.{} {b})",
r.pick(&[
"count",
"find_index",
"any?",
"all?",
"none?",
"one?",
"take_while"
])
),
})
}
fn gen_methobj(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let recvs: &[(&str, &[&str])] = &[
(
"3",
&[
"+",
"*",
"divmod",
"gcd",
"times",
"to_s",
"round",
"between?",
"clamp",
"digits",
"fdiv",
"pow",
"abs",
"upto",
"coerce",
"puts",
"frozen?",
"instance_of?",
],
),
(
"1.5",
&[
"+", "round", "floor", "divmod", "between?", "step", "to_i", "nan?", "coerce",
],
),
(
"\"ab\"",
&[
"upcase",
"sub",
"gsub",
"split",
"each_char",
"center",
"index",
"between?",
"start_with?",
"delete",
"count",
"tr",
"slice",
"unpack",
"%",
],
),
(
":sym",
&["to_proc", "to_s", "succ", "between?", "start_with?", "[]"],
),
(
"[1, 2]",
&[
"push",
"map",
"first",
"include?",
"each_slice",
"inject",
"flatten",
"join",
"rotate",
"sample",
"sum",
"zip",
"each_cons",
"min_by",
"take_while",
"dig",
],
),
(
"{a: 1}",
&[
"each",
"fetch",
"map",
"merge",
"store",
"dig",
"any?",
"each_with_object",
"min_by",
"group_by",
"count",
"to_a",
],
),
(
"(1..3)",
&["step", "each", "cover?", "sum", "each_slice", "min", "to_a"],
),
(
"nil",
&[
"to_a",
"to_s",
"inspect",
"&",
"frozen?",
"instance_variable_get",
],
),
(
"Object.new",
&[
"frozen?",
"instance_variable_get",
"respond_to?",
"tap",
"then",
"send",
],
),
];
let classes: &[(&str, &[&str])] = &[
(
"Integer",
&[
"sqrt",
"try_convert",
"name",
"instance_method",
"ancestors",
],
),
(
"String",
&["new", "try_convert", "name", "instance_methods"],
),
("Array", &["new", "[]", "try_convert", "superclass"]),
("Hash", &["new", "[]", "name", "include?"]),
("Math", &["sqrt", "hypot", "log", "atan2", "cbrt"]),
("Struct", &["new", "name"]),
];
let defs = [
("def m(a); end", "m"),
("def m(a, b); end", "m"),
("def m(a, b = 1); end", "m"),
("def m(a, *b); end", "m"),
("def m(*a); end", "m"),
("def m(a, *b, c); end", "m"),
("def m(a, b: 1); end", "m"),
("def m(a, b:); end", "m"),
("def m(a, **b); end", "m"),
("def m(a, &b); end", "m"),
("def m(a, b = 1, *c, d:, e: 2, **f, &g); end", "m"),
("def m; end", "m"),
];
let (rc, ms) = r.pick(recvs);
let m = r.pick(ms);
let (cls, cms) = r.pick(classes);
let cm = r.pick(cms);
let (d, dn) = r.pick(&defs);
one(match r.below(20) {
0 => format!("p({rc}.method(:{m}).arity)"),
1 => format!("p({rc}.method(:{m}).owner.to_s)"),
2 => format!("p({rc}.method(:{m}).parameters)"),
3 => format!("p([{rc}.method(:{m}).arity, {rc}.method(:{m}).owner.to_s])"),
4 => format!("p({rc}.method(:{m}).name)"),
5 => format!("p {cls}.method(:{cm}).arity"),
6 => format!("p {cls}.method(:{cm}).owner.to_s"),
7 => format!("p {cls}.method(:{cm}).parameters"),
8 => format!("class C\n {d}\nend\np C.new.method(:{dn}).arity"),
9 => format!("class C\n {d}\nend\np C.new.method(:{dn}).parameters"),
10 => format!("class C\n {d}\nend\np C.new.method(:{dn}).owner.to_s"),
11 => format!("class C\n {d}\nend\np C.instance_method(:{dn}).owner.to_s"),
12 => format!("class C\n {d}\nend\np C.instance_method(:{dn}).arity"),
13 => format!("class C\n {d}\nend\np C.new.method(:{dn}).unbind.owner.to_s"),
14 => format!(
"module M\n {d}\nend\nclass C\n {}\nend\np [C.new.method(:{dn}).owner.to_s, C.new.method(:{dn}).arity]",
if r.below(2) == 0 { "include M" } else { "prepend M" }
),
15 => format!(
"class C\n include Comparable\n def <=>(o) = 0\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
r.pick(&["between?", "clamp", "<", ">="]),
r.pick(&["between?", "clamp", "<", ">="])
),
16 => format!(
"class C\n include Enumerable\n def each; yield 1; end\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
r.pick(&["map", "each_slice", "sort_by", "include?", "first"]),
r.pick(&["map", "each_slice", "sort_by", "include?", "first"])
),
17 => format!(
"class C\n define_method(:d) {{ |{}| }}\nend\np [C.new.method(:d).arity, C.new.method(:d).parameters]",
r.pick(&["x", "x, y", "x, y = 1", "x, *y", "", "x, k: 1"])
),
18 => format!("p 3.method(:{}).curry[{}]", r.pick(&["+", "*", "-", "gcd"]), r.range(1, 9)),
_ => {
let (parent, pms): &(&str, &[&str]) = r.pick(&[
("Array", &["each", "size", "first", "frozen?", "instance_of?", "to_s"] as &[&str]),
("Hash", &["each", "size", "frozen?", "instance_of?", "to_s", "fetch"]),
("String", &["size", "upcase", "frozen?", "instance_of?", "to_s", "sub"]),
]);
format!(
"class C < {parent}\nend\np [C.new.method(:{}).owner.to_s, C.new.method(:{}).arity]",
r.pick(pms),
r.pick(pms)
)
}
})
}
fn gen_eqlident(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(1, 6);
let m = r.range(1, 6);
let same = format!("{n}");
let wide = format!("{n}.0");
let pre = "require \"set\"";
one(match r.below(24) {
0 => format!("p [{same}.eql?({same}), {same}.eql?({wide}), {wide}.eql?({wide})]"),
1 => format!("p [[{same}].eql?([{same}]), [{same}].eql?([{wide}])]"),
2 => format!("p [[[{same}]].eql?([[{same}]]), [[{same}]].eql?([[{wide}]])]"),
3 => format!("p [{{ a: {same} }}.eql?({{ a: {same} }}), {{ a: {same} }}.eql?({{ a: {wide} }})]"),
4 => format!("p [{same}, {wide}, {same}, {m}].uniq"),
5 => format!("p [[{same}], [{wide}], [{same}]].uniq"),
6 => format!("p([{same}, {m}] | [{wide}])"),
7 => format!("p([{same}, {m}] & [{wide}])"),
8 => format!("p([{same}, {wide}] - [{same}])"),
9 => format!("p [[{same}], [{m}]].intersect?([[{wide}]])"),
10 => format!("h = {{}}\nh[{same}] = :i\nh[{wide}] = :f\np [h.size, h[{same}], h[{wide}]]"),
11 => format!(
"h = {{}}\nh[[{same}]] = :i\nh[[{wide}]] = :f\np [h.size, h[[{same}]], h[[{wide}]]]"
),
12 => format!(
"h = {{}}\nh[{{ a: {same} }}] = :i\nh[{{ a: {wide} }}] = :f\np [h.size, h[{{ a: {same} }}]]"
),
13 => format!("h = {{}}\nh[{{ a: {same} }}] = :i\np h.keys"),
14 => format!("{pre}\ns = Set.new\ns << {{ a: {same} }}\ns << {{ a: {same} }}\np [s.size, s.to_a]"),
15 => format!("{pre}\np [(Set[{same}] & Set[{wide}]).to_a, (Set[{same}] - Set[{wide}]).to_a]"),
16 => format!(
"{pre}\np [Set[{same}].subset?(Set[{wide}]), Set[{same}].subset?(Set[{same}, {m}])]"
),
17 => format!(
"{pre}\np [Set[{same}].disjoint?(Set[{wide}]), Set[{same}].intersect?(Set[{same}])]"
),
18 => format!("{pre}\nh = {{}}\nh[Set[{same}]] = :x\np [h[Set[{same}]], h.keys]"),
19 => format!("p [{{ a: {n}, b: {m} }}.hash == {{ b: {m}, a: {n} }}.hash, {{ a: {n} }}.hash == {{ a: {n}.0 }}.hash]"),
20 => format!("p [[{same}].hash == [{same}].hash, [{same}].hash == [{wide}].hash]"),
21 => format!(
"S = Struct.new(:a)\np [S.new({same}).eql?(S.new({same})), S.new({same}).eql?(S.new({wide}))]"
),
22 => format!(
"D = Data.define(:a)\np [D.new(a: {same}).eql?(D.new(a: {same})), D.new(a: {same}).eql?(D.new(a: {wide}))]"
),
_ => format!("p [{same}.eql?({wide}), {same} == {wide}, [{same}] == [{wide}], [{same}].eql?([{wide}])]"),
})
}
fn gen_numwide(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let e = r.range(20, 90);
let base = r.pick(&["2", "3", "7", "10"]);
let big = format!("{base}**{e}");
let (n, d) = (r.range(1, 9), r.range(2, 9));
one(match r.below(18) {
0 => format!("p [{big} == ({big}).to_f, ({big}).to_f == {big}]"),
1 => format!("p [{big} == ({big}).to_f + 1, {big} + 1 == ({big}).to_f]"),
2 => format!("p [{big} != ({big}).to_f, {big} != ({big}).to_f * 2]"),
3 => format!("p [{big} <=> ({big}).to_f, {big} <=> ({big}).to_f * 2]"),
4 => format!("p [({big}).to_f <=> {big}, {big} <=> {big}]"),
5 => format!("p [{big} < ({big}).to_f * 2, {big} > ({big}).to_f / 2]"),
6 => format!("p [{big} <= ({big}).to_f, {big} >= ({big}).to_f]"),
7 => format!("p [{big} == Float::INFINITY, {big} < Float::INFINITY]"),
8 => format!("p [{big} == Float::NAN, {big} <=> Float::NAN]"),
9 => format!("p [Rational({n}, {d}) == {n}.0 / {d}, Rational({n}, {d}) == 0.0]"),
10 => format!("p [{n}.0 / {d} == Rational({n}, {d}), Rational({n}, {d}) <=> {n}.0 / {d}]"),
11 => format!("p [Rational({n}, 1) == {n}, Rational({n}, 1) == {n}.0]"),
12 => format!("p [Complex({n}, 0) == {n}.0, Complex({n}, 1) == {n}.0]"),
13 => format!("p [{n}.0 == Complex({n}, 0), Complex({n}.0, 0) == {n}]"),
14 => format!("p [{big} == Rational({big}, 1), Rational({big}, 1) == ({big}).to_f]"),
15 => format!("p [({big}).eql?(({big}).to_f), ({big}).eql?({big})]"),
16 => format!("p [[{big}, ({big}).to_f].uniq.size, [{big}, {big}].uniq.size]"),
_ => format!("p [({big}).coerce(1.0), ({big}).coerce(1)]"),
})
}
fn gen_case(seed: u64, mode: Mode) -> Vec<String> {
match mode {
Mode::Arith => gen_arith(seed),
Mode::Bignum => gen_bignum(seed),
Mode::Floatfmt => gen_floatfmt(seed),
Mode::Strings => gen_strings(seed),
Mode::Interp => gen_interp(seed),
Mode::Ranges => gen_ranges(seed),
Mode::Arraymeth => gen_arraymeth(seed),
Mode::Hashmeth => gen_hashmeth(seed),
Mode::Sorting => gen_sorting(seed),
Mode::Formatspec => gen_formatspec(seed),
Mode::Blocks => gen_blocks(seed),
Mode::Symbols => gen_symbols(seed),
Mode::Ternary => gen_ternary(seed),
Mode::Comparison => gen_comparison(seed),
Mode::Printf => gen_printf(seed),
Mode::StringOps => gen_string_ops(seed),
Mode::Caseexpr => gen_caseexpr(seed),
Mode::Intmeth => gen_intmeth(seed),
Mode::Regex => gen_regex(seed),
Mode::Enumerable => gen_enumerable(seed),
Mode::Exceptions => gen_exceptions(seed),
Mode::Struct => gen_struct(seed),
Mode::Rational => gen_rational(seed),
Mode::Patternmatch => gen_patternmatch(seed),
Mode::Kernelconv => gen_kernelconv(seed),
Mode::Loopflow => gen_loopflow(seed),
Mode::Hashenum => gen_hashenum(seed),
Mode::Enumext => gen_enumext(seed),
Mode::Kwargs => gen_kwargs(seed),
Mode::Metaprog => gen_metaprog(seed),
Mode::Mixins => gen_mixins(seed),
Mode::Lambda => gen_lambda(seed),
Mode::Enumlazy => gen_enumlazy(seed),
Mode::Setops => gen_setops(seed),
Mode::Frozen => gen_frozen(seed),
Mode::Datacls => gen_datacls(seed),
Mode::Strenc => gen_strenc(seed),
Mode::Complexnum => gen_complexnum(seed),
Mode::Objintro => gen_objintro(seed),
Mode::Blockflow => gen_blockflow(seed),
Mode::Methobj => gen_methobj(seed),
Mode::Multiyield => gen_multiyield(seed),
Mode::Eqlident => gen_eqlident(seed),
Mode::Numwide => gen_numwide(seed),
Mode::Typeerr => gen_typeerr(seed),
Mode::Timefmt => gen_timefmt(seed),
Mode::Bytestr => gen_bytestr(seed),
Mode::Packfmt => gen_packfmt(seed),
Mode::Trsets => gen_trsets(seed),
Mode::Strcase => gen_strcase(seed),
Mode::Strpart => gen_strpart(seed),
Mode::Arrreshape => gen_arrreshape(seed),
Mode::Numprec => gen_numprec(seed),
Mode::Objmodel => gen_objmodel(seed),
Mode::Intbits => gen_intbits(seed),
Mode::Structinit => gen_structinit(seed),
Mode::Hashdefault => gen_hashdefault(seed),
Mode::Refinement => gen_refinement(seed),
Mode::Kwsplat => gen_kwsplat(seed),
Mode::Heredoc => gen_heredoc(seed),
Mode::Toplevelpriv => gen_toplevelpriv(seed),
Mode::Raiseforms => gen_raiseforms(seed),
Mode::Rangeedge => gen_rangeedge(seed),
Mode::All => gen_case(seed, ALL_MODES[(seed as usize) % ALL_MODES.len()]),
}
}
fn gen_lambda(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let guard =
|body: &str| format!("begin\n p({body})\nrescue ArgumentError => e\n p e.message\nend");
one(match r.below(24) {
0 => guard(&format!("->(x, y) {{ [x, y] }}.call({a})")),
1 => guard(&format!("->(x, y) {{ [x, y] }}.call({a}, {b}, 1)")),
2 => guard(&format!("->(x, y = {b}) {{ [x, y] }}.call({a})")),
3 => guard(&format!("->(x, *r) {{ [x, r] }}.call({a}, {b})")),
4 => guard("->(x, *r) { [x, r] }.call"),
5 => guard(&format!("->(k:) {{ k }}.call(k: {a})")),
6 => guard("->(k:) { k }.call"),
7 => guard(&format!("->(k:) {{ k }}.call(k: {a}, j: {b})")),
8 => guard(&format!("->(x, k: {b}) {{ [x, k] }}.call({a})")),
9 => guard(&format!("->(x, **o) {{ [x, o] }}.call({a}, z: {b})")),
10 => guard(&format!("proc {{ |x, y| [x, y] }}.call({a})")),
11 => guard(&format!("proc {{ |x, y| [x, y] }}.call({a}, {b}, 1)")),
12 => guard(&format!("lambda {{ |x, y| [x, y] }}.call({a})")),
13 => guard(&format!("[[{a}, {b}]].map(&->(x, y) {{ x + y }})")),
14 => guard(&format!("[[{a}, {b}]].map {{ |x, y| x + y }}")),
15 => "p [->(){}.arity, ->(x){}.arity, ->(x, y = 1){}.arity, ->(*a){}.arity, ->(k:){}.arity, ->(k: 1){}.arity]".to_string(),
16 => "p [proc{}.arity, proc{|x|}.arity, proc{|x, y = 1|}.arity, proc{|*a|}.arity, proc{|k: 1|}.arity]".to_string(),
17 => format!("p ->(x, y) {{ x + y }}.curry[{a}][{b}]"),
18 => guard(&format!("->(x, y) {{ x + y }}.curry.call({a}, {b}, 1)")),
19 => format!("f = ->(x) {{ x + {a} }} >> ->(y) {{ y * 2 }}\np [f.call({b}), f.lambda?]"),
20 => format!(
"class C\n define_method(:m) {{ |x, y| [x, y] }}\nend\nbegin\n p C.new.m({a})\nrescue ArgumentError => e\n p e.message\nend"
),
21 => format!(
"def m(x, y) = [x, y]\nbegin\n p method(:m).call({a})\nrescue ArgumentError => e\n p e.message\nend\np [method(:m).arity, method(:m).to_proc.lambda?]"
),
22 => format!("p ->(&b) {{ b.call({a}) }}.call {{ |v| v * 2 }}"),
_ => format!(
"p [(->(x) {{ x > {a} }} === {b}), (case {b} when ->(x) {{ x > {a} }} then :hi else :lo end)]"
),
})
}
fn gen_enumlazy(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let n = r.range(1, 3);
let k = r.range(2, 4);
let arr = "[1, 2, 4, 5, 7]";
let gen = "e = Enumerator.new { |y| i = 0; loop { y << i; i += 1 } }";
let m = r.range(3, 6);
let j = k.min(m - 1);
one(match r.below(26) {
0 => format!("p {arr}.each_slice({k}).class"),
1 => format!("p {arr}.each_cons({k}).class"),
2 => format!("p {arr}.chunk_while {{ |a, b| b == a + 1 }}.class"),
3 => format!("p {arr}.slice_when {{ |a, b| b > a + 1 }}.class"),
4 => format!("p {arr}.chunk {{ |x| x.even? }}.class"),
5 => format!("p {arr}.each_slice({k}).to_a"),
6 => format!("p {arr}.each_cons({k}).to_a"),
7 => format!("p {arr}.chunk_while {{ |a, b| b == a + 1 }}.to_a"),
8 => format!("p {arr}.slice_when {{ |a, b| b > a + 1 }}.to_a"),
9 => format!("p {arr}.chunk {{ |x| x.even? }}.to_a"),
10 => {
format!("begin\n p {arr}.chunk_while\nrescue ArgumentError => e\n p e.message\nend")
}
11 => format!("begin\n p {arr}.slice_when\nrescue ArgumentError => e\n p e.message\nend"),
12 => format!("{gen}\np e.first({k})"),
13 => format!("{gen}\np e.take({k})"),
14 => format!("{gen}\np e.each_slice({n}).first({k})"),
15 => format!("{gen}\np e.each_cons({n}).first({k})"),
16 => format!("{gen}\np e.each_with_index.first({k})"),
17 => format!("{gen}\np e.map.first({k})"),
18 => format!("{gen}\np e.each_with_object([]).first({n})"),
19 => format!("p (1..).each_slice({n}).first({k})"),
20 => format!("p (1..).each_with_index.first({k})"),
21 => format!("p (1..Float::INFINITY).each_cons({n}).first({k})"),
22 => "p [1, 1, 2, 4, 2, 1, 5].lazy.uniq.to_a".to_string(),
23 => format!("p {arr}.lazy.uniq {{ |x| x % {m} }}.to_a"),
24 => format!("p (1..).lazy.map {{ |x| x % {m} }}.uniq.first({j})"),
_ => format!(
"p (1..).lazy.map {{ |x| x % {m} }}.uniq.map {{ |x| x * 2 }}.reject {{ |x| x == 0 }}.first({j})"
),
})
}
fn gen_setops(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(1, 5), r.range(1, 5));
let pre = "require \"set\"";
one(match r.below(21) {
0 => format!("{pre}\np Set.new([{a}, {b}, {a}]).to_a.sort"),
1 => format!("{pre}\np (Set[{a}, {b}] | Set[3, 4]).to_a.sort"),
2 => format!("{pre}\np (Set[{a}, {b}, 3] & Set[3, 4]).to_a.sort"),
3 => format!("{pre}\np (Set[{a}, {b}, 3] - Set[3]).to_a.sort"),
4 => format!("{pre}\np (Set[{a}, {b}] ^ Set[{b}, 9]).to_a.sort"),
5 => format!("{pre}\np Set[{a}, {b}].include?({a})"),
6 => {
format!("{pre}\np [Set[{a}].subset?(Set[{a}, {b}]), Set[{a}, {b}].superset?(Set[{a}])]")
}
7 => {
format!("{pre}\ns = Set.new\ns << {a}\ns.add({b})\ns.add({a})\np [s.size, s.to_a.sort]")
}
8 => format!("{pre}\ns = Set[{a}, {b}, 3]\ns.delete({a})\np s.to_a.sort"),
9 => format!("{pre}\np Set[{a}, {b}].map {{ |x| x * 2 }}.sort"),
10 => format!("{pre}\np Set[{a}, {b}].select(&:even?).to_a.sort"),
11 => format!("{pre}\np [Set[{a}].empty?, Set.new.empty?]"),
12 => format!("{pre}\np (Set[{a}, {b}] == Set[{b}, {a}])"),
13 => format!("{pre}\np Set[{a}, {b}].disjoint?(Set[7, 8])"),
14 => format!("{pre}\np Set[{a}, {b}].to_a.sum"),
15 => format!("{pre}\np Set.new([{a}, {b}]).each_with_object([]) {{ |x, m| m << x }}.sort"),
16 => format!("{pre}\np (Set[{a}, {b}] <=> Set[{a}, {b}, 9])"),
17 => format!("{pre}\np (Set[{a}, {b}, 9] <=> Set[{a}, {b}])"),
18 => format!("{pre}\np (Set[{a}, {b}] <=> Set[{b}, {a}])"),
19 => format!("{pre}\np [Set[{a}, 7] <=> Set[{b}, 8], Set[] <=> Set[{a}]]"),
_ => format!("{pre}\np [Set[{a}, {b}] <=> [{a}, {b}], Set[{a}] <=> {b}]"),
})
}
fn gen_frozen(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, w) = (r.range(1, 9), ww(r));
one(match r.below(16) {
0 => format!("p [{a}.frozen?, :{w}.frozen?, nil.frozen?, true.frozen?]"),
1 => format!("p \"{w}\".freeze.frozen?"),
2 => format!("p [{a}, {a}].freeze.frozen?"),
3 => format!("p({{ a: {a} }}.freeze.frozen?)"),
4 => format!("begin\n [{a}] .freeze << 1\nrescue => e\n p e.class\nend"),
5 => format!("begin\n \"{w}\".freeze << \"x\"\nrescue => e\n p e.class\nend"),
6 => format!("begin\n h = {{ a: {a} }}.freeze\n h[:b] = 1\nrescue => e\n p e.class\nend"),
7 => format!("s = \"{w}\".freeze\np [s.dup.frozen?, s.clone.frozen?]"),
8 => format!("s = \"{w}\".freeze\np s.clone(freeze: false).frozen?"),
9 => format!("a = [{a}].freeze\np [a.dup.frozen?, a.frozen?]"),
10 => format!("class C; end\nc = C.new.freeze\nbegin\n c.instance_variable_set(:@x, {a})\nrescue => e\n p e.class\nend"),
11 => format!("p \"{w}\".frozen?"),
12 => format!("p [{a}.freeze.equal?({a}), :{w}.freeze.equal?(:{w})]"),
13 => format!("a = [{a}, {a} + 1].freeze\np a.map {{ |x| x * 2 }}"),
14 => format!("p [(1..{a}).frozen?, ({a}..).frozen?]"),
_ => format!("s = \"{w}\"\ns.freeze\np [s.frozen?, s.upcase.frozen?]"),
})
}
fn gen_typeerr(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let bad = ["nil", "\"x\"", ":s", "true", "false", "[]", "{}", "1.5"];
let b = *r.pick(&bad);
let w = ww(r);
let n = r.range(1, 4);
let probe =
|expr: &str| format!("begin\n p({expr})\nrescue => e\n p [e.class, e.message]\nend");
one(match r.below(22) {
0 => probe(&format!("\"{w}\" * {b}")),
1 => probe(&format!("\"{w}\" + {b}")),
2 => probe(&format!("\"{w}\".dup << {b}")),
3 => probe(&format!("\"{w}\"[{b}]")),
4 => probe(&format!("\"{w}\".center({b})")),
5 => probe(&format!("\"{w}\".ljust({b})")),
6 => probe(&format!("\"{w}\".rjust({b})")),
7 => probe(&format!("[{n}, {n} + 1] * {b}")),
8 => probe(&format!("[{n}, {n} + 1][{b}]")),
9 => probe(&format!("[{n}, {n} + 1].first({b})")),
10 => probe(&format!("[{n}, {n} + 1].last({b})")),
11 => probe(&format!("[{n}, {n} + 1].take({b})")),
12 => probe(&format!("[{n}, {n} + 1].drop({b})")),
13 => probe(&format!("[{n}, {n} + 1].fetch({b})")),
14 => probe(&format!("[{n}, {n} + 1].rotate({b})")),
15 => probe(&format!("[{n}] + {b}")),
16 => probe(&format!("{{ a: {n} }}.merge({b})")),
17 => probe(&format!("{n} + {b}")),
18 => probe(&format!("{n} / {b}")),
19 => probe(&format!("{n} % {b}")),
20 => probe(&format!("{n}.gcd({b})")),
_ => probe(&format!("Array.new({b})")),
})
}
fn gen_timefmt(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
const EPOCHS: &[&str] = &[
"0",
"1234567890",
"946684800",
"1104537600",
"1230768000",
"1262304000",
"1609459200",
"1709164800",
"-86400",
"2147483647",
"1199059200",
"1451606400",
];
const DIRECTIVES: &[&str] = &[
"%Y-%m-%d",
"%H:%M:%S",
"%c",
"%x",
"%X",
"%r",
"%v",
"%N",
"%L",
"%U",
"%W",
"%V",
"%G",
"%g",
"%j",
"%u",
"%w",
"%a %b",
"%A %B",
"%F %T",
"%D",
"%R",
"%e",
"%k",
"%l",
"%I %p",
"%C",
"%y",
"%s",
"%-d/%-m",
"%_d|%0e",
"%G-W%V-%u",
"%%Y",
"%n%t",
];
let e = *r.pick(EPOCHS);
let d = *r.pick(DIRECTIVES);
let t = format!("Time.at({e}).utc");
one(match r.below(6) {
0 => format!("p {t}.strftime({d:?})"),
1 => format!("p [{t}.year, {t}.month, {t}.day]"),
2 => format!("p [{t}.hour, {t}.min, {t}.sec]"),
3 => format!("p [{t}.wday, {t}.yday, {t}.leap?]"),
4 => format!("p [{t}.to_i, {t}.utc?, {t}.monday?]"),
_ => format!("p {t}.strftime({:?})", format!("{d}|{d}")),
})
}
fn gen_datacls(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 9), r.range(0, 9));
let d = "P = Data.define(:x, :y)";
one(match r.below(14) {
0 => format!("{d}\np P.new(x: {a}, y: {b}).to_h"),
1 => format!("{d}\np P.new({a}, {b}).to_h"),
2 => format!("{d}\np [P.new({a}, {b}).x, P.new({a}, {b}).y]"),
3 => format!("{d}\np P.new({a}, {b}) == P.new({a}, {b})"),
4 => format!("{d}\np P.new({a}, {b}).with(y: {b} + 1).to_h"),
5 => format!("{d}\np P.members"),
6 => format!("{d}\nbegin\n P.new({a})\nrescue ArgumentError => e\n p e.class\nend"),
7 => {
format!("{d}\nbegin\n P.new({a}, {b}, 1)\nrescue ArgumentError => e\n p e.class\nend")
}
8 => format!("{d}\np(case P.new({a}, {b})\n in {{ x:, y: }} then [x, y]\n end)"),
9 => format!("{d}\np P.new({a}, {b}).frozen?"),
10 => format!("{d}\np P.new({a}, {b}).deconstruct_keys([:x])"),
11 => format!("{d}\np P.new({a}, {b}).inspect.include?(\"x=\")"),
12 => format!("{d}\np [P.new({a}, {b}).hash == P.new({a}, {b}).hash]"),
_ => format!(
"{d}\nbegin\n P.new(x: {a}, z: {b})\nrescue ArgumentError => e\n p e.class\nend"
),
})
}
fn gen_strenc(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let s = r.pick(&["héllo", "naïve", "日本語", "aéb", "straße", "abc"]);
let n = r.range(0, 3);
one(match r.below(16) {
0 => format!("p \"{s}\".length"),
1 => format!("p \"{s}\".bytesize"),
2 => format!("p \"{s}\".bytes.size"),
3 => format!("p \"{s}\".chars"),
4 => format!("p \"{s}\".encoding.to_s"),
5 => format!("p \"{s}\".valid_encoding?"),
6 => format!("p \"{s}\"[{n}]"),
7 => format!("p \"{s}\".reverse"),
8 => format!("p \"{s}\".upcase"),
9 => format!("p \"{s}\".each_char.to_a.size"),
10 => format!("p \"{s}\".each_byte.to_a.size"),
11 => format!("p \"{s}\".b.encoding.to_s"),
12 => format!("p \"{s}\".codepoints.size"),
13 => format!("p \"{s}\".sub(/./, \"X\")"),
14 => format!("p \"{s}\".scan(/./).size"),
_ => format!("p \"{s}\".slice({n}, 2)"),
})
}
fn gen_bytestr(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let byte = match r.below(3) {
0 => r.range(0, 0x1f),
1 => r.range(0x20, 0x7e),
_ => r.range(0x7f, 0xff),
};
let b2 = r.range(0, 255);
let enc = r.pick(&["BINARY", "ASCII-8BIT", "US-ASCII", "UTF-8"]);
let txt = r.pick(&[
"abc", "a b", "a,b", "hi", "Az", "héllo", "é", "aé,b", "日本",
]);
let n = r.range(0, 3);
one(match r.below(36) {
0 => format!("p {byte}.chr"),
1 => format!("p {byte}.chr.encoding.to_s"),
2 => format!("p {byte}.chr.ord"),
3 => format!("p [{byte}, {b2}].pack(\"C*\")"),
4 => format!("p [{byte}, {b2}].pack(\"C*\").encoding.to_s"),
5 => format!("p [{byte}, {b2}].pack(\"C*\").unpack(\"C*\")"),
6 => format!("p [{byte}].pack(\"C*\").dup"),
7 => format!("p [{byte}].pack(\"C*\") * 2"),
8 => format!("p {byte}.chr + {b2}.chr"),
9 => format!("p {byte}.chr.dup.encoding.to_s"),
10 => format!("p \"{txt}\".b"),
11 => format!("p \"{txt}\".b.encoding.to_s"),
12 => format!("p \"{txt}\".force_encoding(\"{enc}\").encoding.to_s"),
13 => format!("p \"{txt}\".b.upcase.encoding.to_s"),
14 => format!("p \"{txt}\".b.reverse"),
15 => format!("p \"{txt}\".b[{n}].to_s.encoding.to_s"),
16 => format!("p \"{txt}\".b.split(\",\").map {{ |x| x.encoding.to_s }}"),
17 => format!("p \"{txt}\".b.chars.map {{ |x| x.encoding.to_s }}"),
18 => format!("p \"{txt}\".b.inspect.encoding.to_s"),
19 => format!("p ([{byte}].pack(\"C*\") + \"{txt}\").encoding.to_s"),
20 => format!("p [{byte}, {b2}].pack(\"C*\").bytes.size"),
21 => format!("p {byte}.chr.b"),
22 => format!("p \"{txt}\".b.sub(\"a\", \"z\")"),
23 => format!("p [{byte}].pack(\"C*\").length"),
24 => format!("p \"{txt}\".b.bytes"),
25 => format!("p [\"{txt}\".b.bytesize, \"{txt}\".bytesize]"),
26 => format!("p [\"{txt}\".b.length, \"{txt}\".b.size]"),
27 => format!("p \"{txt}\".b.each_byte.to_a"),
28 => format!("p \"{txt}\".b.getbyte({n})"),
29 => format!("p \"{txt}\".b.unpack(\"C*\")"),
30 => format!("p \"{txt}\".b.byteslice({n}, 2)"),
31 => format!("p \"{txt}\".force_encoding(\"{enc}\").bytes"),
32 => format!("p \"{txt}\".b.force_encoding(\"UTF-8\")"),
33 => format!("p [\"{txt}\".b == \"{txt}\", \"{txt}\".b.index(\"b\")]"),
34 => format!("s = \"{txt}\".b\ns.setbyte(0, {byte})\np [s, s.bytes]"),
_ => format!("p(begin; ({byte}.chr + \"{txt}\"); rescue; $!.class.to_s; end)"),
})
}
fn gen_packfmt(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b) = (r.range(0, 255), r.range(0, 65535));
let big = r.range(0, 1 << 30);
let neg = r.range(-128, 128);
let w = r.pick(&["abc", "hi", "a", "abcdef", ""]);
let count = r.pick(&["", "*", "2", "3"]);
let intdir = r.pick(&[
"C", "c", "S", "s", "L", "l", "Q", "q", "N", "n", "V", "v", "w",
]);
let strdir = r.pick(&["a", "A", "Z", "H", "h", "B", "b", "m", "M", "u"]);
one(match r.below(16) {
0 => format!("p [{a}, {b}].pack(\"{intdir}{count}\").bytes"),
1 => format!("p [{a}, {b}].pack(\"{intdir}{count}\").unpack(\"{intdir}{count}\")"),
2 => format!("p [{neg}].pack(\"{intdir}\").bytes rescue p $!.class.to_s"),
3 => format!("p [\"{w}\"].pack(\"{strdir}{count}\").bytes"),
4 => format!("p [\"{w}\"].pack(\"{strdir}{count}\").unpack(\"{strdir}{count}\")"),
5 => format!("p [{a}, {b}].pack(\"CN\").bytes"),
6 => format!("p [{big}].pack(\"N\").unpack1(\"N\")"),
7 => format!("p [{big}].pack(\"V\").bytes"),
8 => format!("p [{a}].pack(\"C\").encoding.to_s"),
9 => format!("p [\"{w}\"].pack(\"m0\")"),
10 => format!("p [\"{w}\"].pack(\"m0\").unpack1(\"m0\")"),
11 => format!("p [{a}, {b}].pack(\"x{intdir}\").bytes"),
12 => format!("p [{big}].pack(\"{intdir}\").bytes rescue p $!.class.to_s"),
13 => format!("p \"{w}\".unpack(\"{strdir}{count}\")"),
14 => format!("p \"{w}\".unpack(\"C*\")"),
_ => format!("p [{a}].pack(\"{intdir}\") * 2"),
})
}
fn gen_trsets(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let w = r.pick(&[
"hello",
"aabbcc",
"Mississippi",
"a-b-c",
"abc123",
"AaBbCc",
" x ",
"^abc",
]);
let from = r.pick(&[
"a-y", "abc", "^abc", "a-z", "^a-z", "l", "aeiou", "A-Z", "-",
]);
let to = r.pick(&["b-z", "*", "xyz", "ABC", "", "A-Z"]);
let set = r.pick(&["a-z", "^a-z", "lo", "abc", "A-Za-z", "^ ", "s"]);
one(match r.below(12) {
0 => format!("p \"{w}\".tr(\"{from}\", \"{to}\")"),
1 => format!("p \"{w}\".tr_s(\"{from}\", \"{to}\")"),
2 => format!("p \"{w}\".delete(\"{set}\")"),
3 => format!("p \"{w}\".squeeze"),
4 => format!("p \"{w}\".squeeze(\"{set}\")"),
5 => format!("p \"{w}\".count(\"{set}\")"),
6 => format!("p \"{w}\".count(\"{set}\", \"{from}\")"),
7 => format!("p \"{w}\".delete(\"{set}\", \"{from}\")"),
8 => format!("s = \"{w}\".dup\np [s.tr!(\"{from}\", \"{to}\"), s]"),
9 => format!("s = \"{w}\".dup\np [s.squeeze!, s]"),
10 => format!("s = \"{w}\".dup\np [s.delete!(\"{set}\"), s]"),
_ => format!("p \"{w}\".tr(\"{from}\", \"{to}\").tr(\"{to}\", \"{from}\")"),
})
}
fn gen_complexnum(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, b, c, d) = (r.range(-4, 5), r.range(-4, 5), r.range(1, 5), r.range(1, 5));
one(match r.below(14) {
0 => format!("p Complex({a}, {b}) + Complex({c}, {d})"),
1 => format!("p Complex({a}, {b}) - Complex({c}, {d})"),
2 => format!("p Complex({a}, {b}) * Complex({c}, {d})"),
3 => format!("p Complex({a}, {b}) / Complex({c}, {d})"),
4 => format!("p [Complex({a}, {b}).real, Complex({a}, {b}).imaginary]"),
5 => format!("p Complex({a}, {b}).conjugate"),
6 => format!("p Complex({a}, {b}).abs2"),
7 => format!("p Complex({a}, {b}) == Complex({a}, {b})"),
8 => format!("p Complex({a}, {b}).to_s"),
9 => format!("p ({a} + {b}i)"),
10 => format!("p Complex({a}, 0).to_i"),
11 => format!("p Complex({a}, {b}).rectangular"),
12 => format!("p [Complex({a}, {b}).zero?, Complex(0, 0).zero?]"),
_ => format!("p Complex({a}, {b}) * {c}"),
})
}
fn gen_objintro(seed: u64) -> Vec<String> {
let r = &mut Rng::seed(seed);
let (a, w) = (r.range(1, 9), ww(r));
let cls =
format!("class C\n def initialize; @x = {a}; @y = \"{w}\"; end\n def m(z) = z\nend");
one(match r.below(18) {
0 => format!("{cls}\np C.new.instance_variables.sort"),
1 => format!("{cls}\np C.new.instance_variable_get(:@x)"),
2 => format!("{cls}\np C.new.instance_variable_defined?(:@z)"),
3 => format!("{cls}\np C.instance_methods(false).sort"),
4 => format!("{cls}\np C.new.respond_to?(:m)"),
5 => format!("{cls}\np [C.new.is_a?(C), C.new.is_a?(Object), C.new.kind_of?(Comparable)]"),
6 => format!("{cls}\np C.ancestors.first(2).map(&:to_s)"),
7 => format!("{cls}\np C.new.class.name"),
8 => format!("p [{a}.class, \"{w}\".class, :{w}.class, nil.class, (1..2).class]"),
9 => format!("p {a}.then {{ |x| x * 2 }}"),
10 => format!("p [{a}].tap {{ |x| x << {a} }}"),
11 => format!("{cls}\np C.new.methods.include?(:m)"),
12 => format!("{cls}\np [C.new.respond_to?(:m), C.new.respond_to?(:nope)]"),
13 => format!("{cls}\np C.superclass.to_s"),
14 => "p Integer.ancestors.include?(Comparable)".to_string(),
15 => format!(
"{cls}\nc = C.new\nc.instance_variable_set(:@z, {a})\np c.instance_variable_get(:@z)"
),
16 => format!("p [{a}.singleton_class.to_s.start_with?(\"#<Class\"), Integer.name]"),
_ => format!("{cls}\np C.new.public_methods(false).sort"),
})
}
fn mode_name(m: Mode) -> &'static str {
match m {
Mode::Arith => "arith",
Mode::Bignum => "bignum",
Mode::Floatfmt => "floatfmt",
Mode::Strings => "strings",
Mode::Interp => "interp",
Mode::Ranges => "ranges",
Mode::Arraymeth => "arraymeth",
Mode::Hashmeth => "hashmeth",
Mode::Sorting => "sorting",
Mode::Formatspec => "formatspec",
Mode::Blocks => "blocks",
Mode::Symbols => "symbols",
Mode::Ternary => "ternary",
Mode::Comparison => "comparison",
Mode::Printf => "printf",
Mode::StringOps => "string_ops",
Mode::Caseexpr => "caseexpr",
Mode::Intmeth => "intmeth",
Mode::Regex => "regex",
Mode::Enumerable => "enumerable",
Mode::Exceptions => "exceptions",
Mode::Struct => "struct",
Mode::Rational => "rational",
Mode::Patternmatch => "patternmatch",
Mode::Kernelconv => "kernelconv",
Mode::Loopflow => "loopflow",
Mode::Hashenum => "hashenum",
Mode::Enumext => "enumext",
Mode::Kwargs => "kwargs",
Mode::Metaprog => "metaprog",
Mode::Mixins => "mixins",
Mode::Lambda => "lambda",
Mode::Enumlazy => "enumlazy",
Mode::Setops => "setops",
Mode::Frozen => "frozen",
Mode::Datacls => "datacls",
Mode::Strenc => "strenc",
Mode::Complexnum => "complexnum",
Mode::Objintro => "objintro",
Mode::Blockflow => "blockflow",
Mode::Methobj => "methobj",
Mode::Multiyield => "multiyield",
Mode::Eqlident => "eqlident",
Mode::Numwide => "numwide",
Mode::Typeerr => "typeerr",
Mode::Timefmt => "timefmt",
Mode::Bytestr => "bytestr",
Mode::Packfmt => "packfmt",
Mode::Trsets => "trsets",
Mode::Strcase => "strcase",
Mode::Strpart => "strpart",
Mode::Arrreshape => "arrreshape",
Mode::Numprec => "numprec",
Mode::Objmodel => "objmodel",
Mode::Intbits => "intbits",
Mode::Structinit => "structinit",
Mode::Hashdefault => "hashdefault",
Mode::Refinement => "refinement",
Mode::Kwsplat => "kwsplat",
Mode::Heredoc => "heredoc",
Mode::Toplevelpriv => "toplevelpriv",
Mode::Raiseforms => "raiseforms",
Mode::Rangeedge => "rangeedge",
Mode::All => "all",
}
}
fn mode_from_name(s: &str) -> Option<Mode> {
if s == "all" {
return Some(Mode::All);
}
ALL_MODES.iter().copied().find(|&m| mode_name(m) == s)
}
fn build_program(stmts: &[String]) -> String {
stmts.join("\n")
}
fn diverges(script: &str, bin: &Path, timeout: Duration) -> bool {
let o = run_oracle(script, timeout);
if o.timed_out {
return false;
}
let r = run_ours(script, bin, timeout);
if r.exit == -999 || r.exit == -998 || r.timed_out || o.exit == -999 || o.exit == -998 {
return false;
}
differs(&o, &r)
}
fn minimize(stmts: Vec<String>, bin: &Path, timeout: Duration) -> Vec<String> {
let mut cur = stmts;
loop {
let mut removed = false;
let mut i = 0;
while i < cur.len() {
let mut cand = cur.clone();
cand.remove(i);
if !cand.is_empty() && diverges(&build_program(&cand), bin, timeout) {
cur = cand;
removed = true;
} else {
i += 1;
}
}
if !removed {
break;
}
}
cur
}
fn signature(program: &str) -> String {
let body = program
.lines()
.map(|l| l.trim())
.rfind(|l| !l.is_empty())
.unwrap_or("")
.to_string();
let mut s = body;
for (pat, rep) in [
(r"[0-9]+\.[0-9]+([eE][-+]?[0-9]+)?", "F"),
(r"[0-9]+[eE][-+]?[0-9]+", "F"),
(r"-?[0-9]+", "N"),
("\"[^\"]*\"", "W"),
("'[^']*'", "W"),
] {
s = regex_lite_replace(&s, pat, rep);
}
s
}
fn regex_lite_replace(s: &str, pat: &str, rep: &str) -> String {
match regex::Regex::new(pat) {
Ok(re) => re.replace_all(s, rep).into_owned(),
Err(_) => s.to_string(),
}
}
struct Args {
count: u64,
base_seed: u64,
once: bool,
dump: bool,
timeout_ms: u64,
out_path: PathBuf,
max_report: usize,
jobs: usize,
mode: Mode,
verify: usize,
baseline: Option<PathBuf>,
}
fn parse_args() -> Args {
let mut count = 2000u64;
let mut base_seed = 1u64;
let mut once = false;
let mut dump = false;
let mut timeout_ms = 5000u64;
let mut max_report = 200usize;
let mut mode = Mode::Arith;
let mut verify = 1usize;
let mut baseline: Option<PathBuf> = None;
let mut jobs = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(4);
let mut out_path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("target")
.join("parity-fuzz")
.join("divergences.txt");
let argv: Vec<String> = std::env::args().skip(1).collect();
let mut i = 0;
while i < argv.len() {
match argv[i].as_str() {
"--count" | "-c" => {
i += 1;
count = argv.get(i).and_then(|s| s.parse().ok()).unwrap_or(count);
}
"--seed" | "-s" => {
i += 1;
base_seed = argv
.get(i)
.and_then(|s| s.parse().ok())
.unwrap_or(base_seed);
}
"--once" => once = true,
"--dump" => dump = true,
"--timeout-ms" => {
i += 1;
timeout_ms = argv
.get(i)
.and_then(|s| s.parse().ok())
.unwrap_or(timeout_ms);
}
"--out" | "-o" => {
i += 1;
if let Some(p) = argv.get(i) {
out_path = PathBuf::from(p);
}
}
"--max-report" => {
i += 1;
max_report = argv
.get(i)
.and_then(|s| s.parse().ok())
.unwrap_or(max_report);
}
"--jobs" | "-j" => {
i += 1;
jobs = argv
.get(i)
.and_then(|s| s.parse().ok())
.filter(|&j| j >= 1)
.unwrap_or(jobs);
}
"--mode" | "-m" => {
i += 1;
match argv.get(i).and_then(|s| mode_from_name(s)) {
Some(m) => mode = m,
None => {
eprintln!(
"unknown --mode '{}'",
argv.get(i).map(|s| s.as_str()).unwrap_or("")
);
std::process::exit(2);
}
}
}
a if a.starts_with("--") && mode_from_name(&a[2..]).is_some() => {
mode = mode_from_name(&a[2..]).unwrap();
}
"--verify" => {
i += 1;
verify = argv
.get(i)
.and_then(|s| s.parse().ok())
.filter(|&k| k >= 1)
.unwrap_or(verify);
}
"--baseline" => {
i += 1;
baseline = argv.get(i).map(PathBuf::from);
}
"--stderr" => {
CMP_STDERR.store(true, Ordering::Relaxed);
}
"--help" | "-h" => {
let modes: Vec<&str> = ALL_MODES.iter().copied().map(mode_name).collect();
eprintln!(
"parity-fuzz — differential ruby/rubylang parity fuzzer\n\
\n\
--count N number of cases (default 2000)\n\
--seed N base seed; case i uses seed+i (default 1)\n\
--mode M one of: {}\n\
--mode all round-robin over every mode above\n\
(each also accepted as a `--<mode>` shorthand)\n\
--stderr also require the diagnostics to match\n\
--once run a single case (seed) and print both outputs\n\
--dump print the generated programs and exit; runs\n\
\u{20} nothing, so it cannot affect any result\n\
--timeout-ms N per-interpreter wall-clock timeout (default 5000)\n\
--out PATH divergence corpus file\n\
--max-report N stop after N divergences (default 200)\n\
--jobs N parallel workers (default = CPU count)\n\
--verify K require K consecutive divergences to report (default 1)\n\
--baseline FILE allowlist of known-gap signatures; only a NEW\n\
divergence fails the run (exit 1)\n\
\n\
env RUBYLANG_FUZZ_RUBY=PATH the reference ruby to compare against.\n\
The oracle is part of the result; every run prints it.",
modes.join(", ")
);
std::process::exit(0);
}
_ => {}
}
i += 1;
}
Args {
count,
base_seed,
once,
dump,
timeout_ms,
out_path,
max_report,
jobs,
mode,
verify,
baseline,
}
}
fn warn_if_stale(bin: &Path) {
let Ok(bin_time) = std::fs::metadata(bin).and_then(|m| m.modified()) else {
return;
};
let src = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src");
let mut newest: Option<(std::time::SystemTime, PathBuf)> = None;
let mut stack = vec![src];
while let Some(dir) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
if path.file_name().map(|n| n != "bin").unwrap_or(true) {
stack.push(path);
}
continue;
}
if path.extension().map(|e| e != "rs").unwrap_or(true) {
continue;
}
let Ok(t) = entry.metadata().and_then(|m| m.modified()) else {
continue;
};
if newest.as_ref().map(|(n, _)| t > *n).unwrap_or(true) {
newest = Some((t, path));
}
}
}
if let Some((t, path)) = newest {
if t > bin_time {
eprintln!(
"parity-fuzz: WARNING — {} is OLDER than {}.\n\
parity-fuzz: this run measures the previous build; \
`cargo build` first for results about the current source.",
bin.display(),
path.display()
);
}
}
}
fn main() {
let args = parse_args();
let bin = ours_bin();
let timeout = Duration::from_millis(args.timeout_ms);
if !bin.exists() {
eprintln!(
"rubylang binary not found at {}; run `cargo build` first",
bin.display()
);
std::process::exit(2);
}
warn_if_stale(&bin);
eprintln!("parity-fuzz: oracle = {}", oracle_id());
eprintln!("parity-fuzz: under test = {}", bin.display());
if args.dump {
for i in 0..args.count {
let seed = args.base_seed + i;
let mode = if matches!(args.mode, Mode::All) {
ALL_MODES[(i as usize) % ALL_MODES.len()]
} else {
args.mode
};
println!("=== seed {seed} mode {} ===", mode_name(mode));
println!("{}", build_program(&gen_case(seed, mode)));
}
return;
}
if args.once {
let stmts = gen_case(args.base_seed, args.mode);
let script = build_program(&stmts);
let o = run_oracle(&script, timeout);
let r = run_ours(&script, &bin, timeout);
let diverged = !o.timed_out && differs(&o, &r);
println!("seed : {}", args.base_seed);
println!("mode : {}", mode_name(args.mode));
println!("oracle : {}", oracle_id());
let (show, o, r) = if diverged && stmts.len() > 1 {
let m = minimize(stmts, &bin, timeout);
let ms = build_program(&m);
let mo = run_oracle(&ms, timeout);
let mr = run_ours(&ms, &bin, timeout);
(ms, mo, mr)
} else {
(script, o, r)
};
println!("program:\n {}", show.replace('\n', "\n "));
println!("--- ruby exit={} timeout={} ---", o.exit, o.timed_out);
let _ = std::io::stdout().write_all(&o.stdout);
println!("--- rubylang exit={} timeout={} ---", r.exit, r.timed_out);
let _ = std::io::stdout().write_all(&r.stdout);
println!("--- {} ---", if diverged { "DIVERGE" } else { "match" });
std::process::exit(if diverged { 1 } else { 0 });
}
use std::sync::atomic::AtomicU64;
use std::sync::Mutex;
let next = AtomicU64::new(0);
let checked = AtomicU64::new(0);
let timeouts = AtomicU64::new(0);
let stop = AtomicBool::new(false);
let divergences: Mutex<Vec<(u64, String)>> = Mutex::new(Vec::new());
let start = Instant::now();
eprintln!(
"fuzzing {} cases across {} workers (mode {})…",
args.count,
args.jobs,
mode_name(args.mode)
);
std::thread::scope(|scope| {
for _ in 0..args.jobs {
scope.spawn(|| loop {
if stop.load(Ordering::Relaxed) {
break;
}
let idx = next.fetch_add(1, Ordering::Relaxed);
if idx >= args.count {
break;
}
let seed = args.base_seed.wrapping_add(idx);
let stmts = gen_case(seed, args.mode);
let script = build_program(&stmts);
let o = run_oracle(&script, timeout);
let r = run_ours(&script, &bin, timeout);
let done = checked.fetch_add(1, Ordering::Relaxed) + 1;
if o.timed_out || r.timed_out {
timeouts.fetch_add(1, Ordering::Relaxed);
}
if !o.timed_out && differs(&o, &r) {
let minimal = minimize(stmts, &bin, timeout);
let mscript = build_program(&minimal);
let mo = run_oracle(&mscript, timeout);
let mr = run_ours(&mscript, &bin, timeout);
let mut confirmed = differs(&mo, &mr);
for _ in 1..args.verify.max(1) {
if !confirmed {
break;
}
confirmed = diverges(&mscript, &bin, timeout);
}
if !confirmed {
return; }
let err_of = |o: &RunOut| -> String {
if CMP_STDERR.load(Ordering::Relaxed) {
format!(
"\n stderr: {}",
render(&norm_stderr(&o.stderr)).replace('\n', "\n ")
)
} else {
String::new()
}
};
let rec = format!(
"==== seed {seed} ====\n\
program:\n {}\n\
ruby : exit={} timeout={}{}\n{}\n\
rubylang : exit={} timeout={}{}\n{}\n",
mscript.replace('\n', "\n "),
mo.exit,
mo.timed_out,
err_of(&mo),
render(&mo.stdout),
mr.exit,
mr.timed_out,
err_of(&mr),
render(&mr.stdout),
);
let mut d = divergences.lock().unwrap();
d.push((seed, rec));
if d.len() >= args.max_report {
stop.store(true, Ordering::Relaxed);
}
}
if done % 500 == 0 {
let n = divergences.lock().unwrap().len();
eprintln!(
" {done}/{} checked, {n} divergences, {:.0}/s",
args.count,
done as f64 / start.elapsed().as_secs_f64().max(0.001)
);
}
});
}
});
let checked = checked.load(Ordering::Relaxed);
let timeouts = timeouts.load(Ordering::Relaxed);
let mut divergences: Vec<(u64, String)> = divergences.into_inner().unwrap();
divergences.sort_by_key(|(seed, _)| *seed);
let divergences: Vec<String> = divergences.into_iter().map(|(_, r)| r).collect();
let elapsed = start.elapsed();
let sig_of = |rec: &str| -> String {
let prog = rec
.split("program:\n")
.nth(1)
.and_then(|s| s.split("\nruby :").next())
.unwrap_or(rec);
signature(prog)
};
let allowed: std::collections::HashSet<String> = match &args.baseline {
Some(bp) => std::fs::read_to_string(bp)
.unwrap_or_default()
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.collect(),
None => std::collections::HashSet::new(),
};
let mut new_records: Vec<&String> = Vec::new();
let mut new_sigs: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
let mut known = 0usize;
for rec in &divergences {
let sig = sig_of(rec);
if args.baseline.is_some() && allowed.contains(&sig) {
known += 1;
} else {
new_records.push(rec);
new_sigs.insert(sig);
}
}
let oracle = oracle_id();
println!(
"\nfuzzed {checked} cases in {:.1}s ({:.0}/s)\n\
oracle : {}\n\
divergences : {} ({} known / {} new)\n\
timeouts : {}",
elapsed.as_secs_f64(),
checked as f64 / elapsed.as_secs_f64().max(0.001),
oracle,
divergences.len(),
known,
new_records.len(),
timeouts,
);
if !divergences.is_empty() {
if let Some(parent) = args.out_path.parent() {
let _ = std::fs::create_dir_all(parent);
}
if let Ok(mut f) = std::fs::File::create(&args.out_path) {
let _ = writeln!(f, "# oracle: {oracle}");
for d in &divergences {
let _ = writeln!(f, "{d}");
}
println!(
"wrote {} divergences to {}",
divergences.len(),
args.out_path.display()
);
}
}
if !new_records.is_empty() {
println!(
"\n--- {} NEW gap signature(s) (add to baseline once triaged) ---",
new_sigs.len()
);
for s in &new_sigs {
println!("{s}");
}
println!(
"\n--- first {} new divergence record(s) ---",
new_records.len().min(5)
);
for d in new_records.iter().take(5) {
println!("{d}");
}
std::process::exit(1);
}
if known > 0 {
println!("all {known} divergences are known (in baseline) — OK");
}
}