use super::*;
fn pair(lang: &LangSpec, src: &str, line: usize) -> SpanDigests {
mint_span_digests(lang, src, line, &[]).expect("pair")
}
mod bash;
mod cedar;
mod css;
mod dockerfile;
mod formatters;
mod hcl;
mod html;
mod javascript;
mod jsonc;
mod markdown;
mod prisma;
mod python;
mod rust;
mod tsx;
mod typescript;
mod yaml;
fn moves(lang: &LangSpec, a: &str, b: &str, line: usize) {
assert_ne!(
pair(lang, a, line).shape,
pair(lang, b, line).shape,
"{a:?} vs {b:?}"
);
}
fn stays(lang: &LangSpec, a: &str, b: &str, line: usize) {
assert_eq!(
pair(lang, a, line).shape,
pair(lang, b, line).shape,
"{a:?} vs {b:?}"
);
}
fn every_byte_reaches_the_walk(lang: &LangSpec, src: &str, line: usize) {
let tree = parse(lang, src).expect("parse");
let (start, end) = span_range(lang, src, &tree, line).expect("span");
let base = pair(lang, src, line).complete;
let in_comment = |at: usize| {
let mut node = tree.root_node().descendant_for_byte_range(at, at + 1);
while let Some(n) = node {
if (lang.skip_kind)(n.kind()) {
return true;
}
node = n.parent();
}
false
};
let mut checked = 0;
for (at, c) in src[start..end].char_indices().map(|(i, c)| (start + i, c)) {
let swapped = match c {
'0'..='8' => char::from(c as u8 + 1),
'9' => '0',
'a'..='y' | 'A'..='Y' => char::from(c as u8 + 1),
'z' => 'a',
'Z' => 'A',
_ => continue,
};
if in_comment(at) {
continue;
}
let mut changed = src.to_string();
changed.replace_range(at..at + 1, &swapped.to_string());
let Some(digests) = mint_span_digests(lang, &changed, line, &[]) else {
continue;
};
checked += 1;
assert_ne!(
digests.complete, base,
"{}: byte {at} {c:?} of {src:?} does not reach the walk",
lang.id
);
}
assert!(checked > 0, "{}: no byte checked", lang.id);
}
#[test]
fn a_crlf_file_hashes_as_its_lf_form() {
let cases: [(&LangSpec, &str, usize); 15] = [
(&RUST, "fn f() -> String {\n // pin\n let s = \"a\nb\";\n let r = r#\"c\nd\"#;\n go(s, r)\n}\n", 2),
(&PYTHON, "def f(x):\n # pin\n s = \"\"\"a\nb\"\"\"\n t = f\"\"\"c\n{x}\nd\"\"\"\n return 'e\\\nf' + s + t\n", 2),
(&JAVASCRIPT, "function f(x) {\n // pin\n const s = `a\nb${x}\nc`;\n const t = 'd\\\ne';\n return <p>\n g\n </p>;\n}\n", 2),
(&TYPESCRIPT, "function f(x: number): string {\n // pin\n return `a\nb${x}\nc`;\n}\n", 2),
(&TSX, "function f(x: number) {\n // pin\n return <p title={`a\nb`}>\n c\n </p>;\n}\n", 2),
(&HTML, "<div>\n<!-- pin -->\n<pre>a\nb</pre>\n<p title=\"c\nd\">e\nf</p>\n<script>\nlet s = `g\nh`;\n</script>\n</div>\n", 2),
(&CSS, "a {\n /* pin */\n content: \"b c\";\n color:\n red;\n}\n", 2),
(&MARKDOWN, "# T\n\n<!-- pin -->\n\n```\na\nb\n```\n\n c\n d\n\n<pre>\ne\nf\n</pre>\n\ng `h\ni` j\n", 3),
(&BASH, "f() {\n # pin\n cat <<EOF\na\nEOF\n echo \"b\nc\" 'd\ne' $'f\ng'\n}\n", 2),
(&HCL, "resource \"a\" \"b\" {\n # pin\n x = <<EOT\nc\nd\nEOT\n y = \"e\"\n}\n", 2),
(&YAML, "m:\n # pin\n a:\n b: |\n c\n d\n e: \"f\n g\"\n h: i\n j\n", 2),
(&CEDAR, "permit (principal, action, resource)\nwhen {\n // pin\n context.a == \"b\"\n};\n", 3),
(&DOCKERFILE, "FROM a\n# pin\nRUN b && \\\n c <<EOF\nd\nEOF\n", 2),
(&PRISMA, "model A {\n // pin\n b String @default(\"c\")\n}\n", 2),
(&JSONC, "{\n // pin\n \"a\": [\"b\",\n \"c\",],\n}\n", 2),
];
for (lang, src, line) in cases {
let crlf = src.replace('\n', "\r\n");
assert!(
!parse(lang, &crlf).unwrap().root_node().has_error(),
"{}",
lang.id
);
assert_eq!(
pair(lang, src, line),
pair(lang, &crlf, line),
"{}",
lang.id
);
}
}
#[test]
fn every_byte_of_a_span_reaches_the_walk() {
for (lang, src) in [
(&CSS, ".a {\n width: 100px;\n w: 50%;\n color: #0af;\n content: \"a b\";\n}\n"),
(&PYTHON, "def f(x, v):\n a = f\"{x:.2f} {x: >10}\"\n b = \"a\\n b\\tc\"\n return \", \".join(v) + r\"x y\"\n"),
(&JAVASCRIPT, "function f(s) {\n return / a/.test(`x ${s} y`) + 'b c' + 0x1f;\n}\n"),
(&TYPESCRIPT, "function f(s) {\n return / a/.test(`x ${s} y`) + 'b c';\n}\n"),
(&RUST, "fn f(v: &[&str]) -> String {\n let r = r#\"x y\"#;\n v.join(\", \") + \"a\\n b\" + r\n}\n"),
(&BASH, "f() {\n curl -X POST \"a b $(c d)\" <<EOF\n hi there $x\nEOF\n}\n"),
(&HCL, "resource \"a\" \"b\" {\n x = \"p ${var.q} r\"\n y = 10\n}\n"),
(&YAML, "# pin\nm:\n a: \"x y\"\n b: 'p q'\n c: |\n r s\n d: [t, 2]\n e: &u v\n f: *u\n"),
(&HTML, "<div title=\"a b\">\n <pre>x y</pre>\n <p>t u</p>\n</div>\n"),
(&MARKDOWN, "# S\n\nSome prose.\n\n```js\npay(10)\n```\n\n indented(1)\n\n<p>Price is 10</p>\n"),
] {
every_byte_reaches_the_walk(lang, src, 1);
}
}
#[test]
fn the_prefix_is_the_function_up_to_the_span_and_the_rest_of_its_loop() {
let rust = "impl<T: Ord> Book<T> {\n pub fn pay(&self, a: u32, b: u32) -> u32 {\n let x = a * 2;\n let y = b * 3;\n for i in 0..a {\n if x > 1 {\n // pin\n go(x, y, i);\n }\n tail(i);\n }\n after(a)\n }\n}\n";
let python = "class Book(Base):\n def pay(self, a, b):\n x = a * 2\n y = b * 3\n for i in range(a):\n if x > 1:\n # pin\n go(x, y, i)\n tail(i)\n return after(a)\n";
let ts = "class Book extends Base {\n pay(a: number, b: number): number {\n const x = a * 2;\n const y = b * 3;\n for (const i of range(a)) {\n if (x > 1) {\n // pin\n go(x, y, i);\n }\n tail(i);\n }\n return after(a);\n }\n}\n";
let bash = "pay() {\n local x=$1\n for i in 1 2; do\n if [ \"$x\" -gt 1 ]; then\n # pin\n go \"$x\" \"$i\"\n fi\n tail \"$i\"\n done\n after \"$x\"\n}\n";
let swap = |src: &str| {
src.replacen("x = a * 2", "@", 1)
.replacen("y = b * 3", "x = b * 3", 1)
.replacen('@', "y = a * 2", 1)
};
let rename = |src: &str| {
src.replace("x =", "u =")
.replace("x >", "u >")
.replace("(x,", "(u,")
};
type Edits<'a> = &'a [(&'a str, &'a str)];
let cases: [(&LangSpec, &str, usize, Edits, Edits); 4] = [
(
&RUST,
rust,
7,
&[
("T: Ord", "T: Eq"),
("b: u32", "b: u64"),
("a * 2", "a * 3"),
("tail(i)", "tail(a)"),
],
&[("pub fn pay", "fn charge"), ("after(a)", "after(b)")],
),
(
&PYTHON,
python,
7,
&[
("(Base)", "(Other)"),
("a, b)", "a, b=1)"),
("a * 2", "a * 3"),
("tail(i)", "tail(a)"),
],
&[("def pay", "def charge"), ("after(a)", "after(b)")],
),
(
&TYPESCRIPT,
ts,
7,
&[
("extends Base", "extends Other"),
("b: number)", "b = 1)"),
("a * 2", "a * 3"),
("tail(i)", "tail(a)"),
],
&[("pay(a", "charge(a"), ("after(a)", "after(b)")],
),
(
&BASH,
bash,
5,
&[
("local x=$1", "local x=$2"),
("tail \"$i\"", "tail \"$x\""),
("1 2; do", "1 3; do"),
],
&[("after \"$x\"", "after \"$i\"")],
),
];
for (lang, src, line, moved, kept) in cases {
for (from, to) in moved {
moves(lang, src, &src.replacen(from, to, 1), line);
}
for (from, to) in kept {
stays(lang, src, &src.replacen(from, to, 1), line);
}
if lang.id != "bash" {
moves(lang, src, &swap(src), line);
stays(lang, src, &rename(src), line);
}
}
}
#[test]
fn a_nested_function_reads_the_outermost_function_before_it() {
let py_def = "def make(a):\n limit = 500\n floor = 1\n def check(amount):\n # pin\n return floor <= amount <= limit\n return check\n";
let py_class = "def make(a):\n limit = 500\n floor = 1\n class View:\n def check(self, amount):\n # pin\n return floor <= amount <= limit\n return View\n";
let ts_fn = "function make(a: number) {\n const limit = 500;\n const floor = 1;\n function check(amount: number): boolean {\n // pin\n return floor <= amount && amount <= limit;\n }\n return check;\n}\n";
let ts_class = "function make(a: number) {\n const limit = 500;\n const floor = 1;\n return class {\n check(amount: number): boolean {\n // pin\n return floor <= amount && amount <= limit;\n }\n };\n}\n";
let swap = |src: &str| {
src.replacen("500", "@", 1)
.replacen("= 1", "= 500", 1)
.replacen('@', "1", 1)
};
for (lang, src, line, after) in [
(&PYTHON, py_def, 5, ("return check", "return None")),
(&PYTHON, py_class, 6, ("return View", "return None")),
(&TYPESCRIPT, ts_fn, 5, ("return check;", "return null;")),
(&TYPESCRIPT, ts_class, 6, ("};\n}", "};\n go();\n}")),
] {
moves(lang, src, &src.replacen("500", "5000000", 1), line);
moves(lang, src, &swap(src), line);
stays(lang, src, &src.replacen("make(", "build(", 1), line);
stays(lang, src, &src.replacen(after.0, after.1, 1), line);
}
}
#[test]
fn a_local_bound_in_a_nested_span_keeps_its_number_in_the_outer_span() {
let ts = "function pay(r: R) {\n // pin\n const approvers = load(r);\n const others = load(r);\n if (approvers.length < 2) {\n go(approvers, others);\n }\n}\n";
let py = "def pay(r):\n # pin\n approvers = load(r)\n others = load(r)\n if len(approvers) < 2:\n go(approvers, others)\n";
let rs = "fn pay(r: R) {\n // pin\n let approvers = load(r);\n let others = load(r);\n if approvers.len() < 2 {\n go(approvers, others);\n }\n}\n";
let shape = |lang: &LangSpec, src: &str| {
let line_at = |n: usize| {
src.split_inclusive('\n')
.take(n)
.map(str::len)
.sum::<usize>()
};
let (from, to) = (line_at(2), line_at(4));
mint_span_digests(lang, src, 2, &[(from, to)])
.expect("span")
.shape
};
for (lang, src) in [(&TYPESCRIPT, ts), (&PYTHON, py), (&RUST, rs)] {
let base = shape(lang, src);
let renamed = src.replace("approvers", "reviewers");
assert_eq!(base, shape(lang, &renamed), "{}: rename", lang.id);
let rebound = src
.replacen("approvers.length", "others.length", 1)
.replacen("len(approvers)", "len(others)", 1);
let rebound = rebound.replacen("approvers.len()", "others.len()", 1);
assert_ne!(base, shape(lang, &rebound), "{}: rebind", lang.id);
let swapped = src.replace("go(approvers, others)", "go(others, approvers)");
assert_ne!(base, shape(lang, &swapped), "{}: swap", lang.id);
let one = |name: &str| {
let reads = src
.replace("approvers.length < 2", "r.ok")
.replace("len(approvers) < 2", "r.ok")
.replace("approvers.len() < 2", "r.ok");
reads.replace("go(approvers, others)", &format!("go({name})"))
};
assert_ne!(
shape(lang, &one("approvers")),
shape(lang, &one("others")),
"{}: lone rebind",
lang.id
);
}
}