Tests: test-lint reads the path a join adds after a format call

read_to_string(PathBuf::from(format!("{}/fixtures.rs", root)).join("input.json"))
was reported as reading Rust source, and a join of "lib.rs" after a
format call was missed. path_literal now takes a literal after the
format call's closing parenthesis as the end of the path.
This commit is contained in:
dotCooCoo committed 2026-12-01 03:32:16 -08:00
1 parent 0b41498af6
commit cefd2ed69e
1 file changed
+34 -5
+34 -5
View File
@@ -2966,14 +2966,39 @@ fn last_literal(s: &str) -> Option<&str> {
Some(&s[open + 1..close])
}
/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call, since
/// its arguments fill placeholders inside it, otherwise the last string literal.
/// The literal that ends the path built by `arg`: the format string of a `format!(…)` call that ends the path, since
/// its arguments fill placeholders inside it, otherwise the last string literal. A literal after the `format!(…)`
/// call (`PathBuf::from(format!(…)).join("lib.rs")`) ends the path instead.
fn path_literal(arg: &str) -> Option<&str> {
let Some(at) = arg.find("format!(") else { return last_literal(arg) };
let rest = &arg[at + "format!(".len()..];
let open = rest.find('"')?;
let close = rest[open + 1..].find('"')? + open + 1;
Some(&rest[open + 1..close])
let b = rest.as_bytes();
let (mut depth, mut i, mut end) = (0usize, 0, None);
while i < b.len() {
match b[i] {
b'"' => {
i += 1;
while i < b.len() && b[i] != b'"' {
i += if b[i] == b'\\' { 2 } else { 1 };
}
}
b'(' => depth += 1,
b')' if depth == 0 => {
end = Some(i);
break;
}
b')' => depth -= 1,
_ => {}
}
i += 1;
}
let call = &rest[..end.unwrap_or(rest.len())];
if let Some(tail) = end.map(|e| &rest[e + 1..]).filter(|t| t.contains('"')) {
return path_literal(tail);
}
let open = call.find('"')?;
let close = call[open + 1..].find('"')? + open + 1;
Some(&call[open + 1..close])
}
fn reads_source_hits(file: &File) -> Vec<Hit> {
@@ -5388,6 +5413,10 @@ mod tests {
let formatted_rs =
"#[test]\nfn t() {\n let s = fs::read_to_string(format!(\"{}/lib.rs\", dir)).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", formatted_rs), [(3, "reads-source")]);
let joined_json = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures.rs\", root)).join(\"input.json\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", joined_json), [], "a join after the format call ends the path");
let joined_rs = "#[test]\nfn t() {\n let s = fs::read_to_string(PathBuf::from(format!(\"{}/fixtures\", root)).join(\"lib.rs\")).unwrap();\n assert!(s.contains(\"x\"));\n}\n";
assert_eq!(only("reads-source", joined_rs), [(3, "reads-source")]);
}
#[test]