mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
xtask: census counts rejections and asserting helpers as checks
A loop over a table that also calls unwrap_err or expect_err checks that some inputs are rejected, so it is no longer reported as census. Calls in failure messages do not count, and a panic! that only enforces success does not exempt the loop. An asserting helper called in an .all(...) predicate also counts as a check, unless a presence check can pass without the helper running (the other side of an ||). Helpers called with a turbofish are matched too.
This commit is contained in:
1 parent
aa44d2a3a0
commit
7f6ff4d60e
1 file changed
+103
-22
+103
-22
@@ -1335,10 +1335,21 @@ fn all_unguarded(v: &View) -> Vec<Hit> {
|
||||
/// whose assertions only check presence, non-emptiness or a round trip.
|
||||
fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
let m = &v.file.exec;
|
||||
// Failure messages run only after an assertion has failed, so a check there does not count.
|
||||
let unmessaged = v.body_without_messages();
|
||||
let helpers_in = |from: usize, to: usize| -> Vec<String> {
|
||||
calls(&unmessaged, from - v.t.open, to - v.t.open)
|
||||
.into_iter()
|
||||
.filter(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers))
|
||||
.map(|(n, _)| n)
|
||||
.collect()
|
||||
};
|
||||
let weak_in = |from: usize, to: usize, var: &str| {
|
||||
let inside: Vec<&MacroCall> = v.asserts.iter().filter(|a| a.at > from && a.at < to).collect();
|
||||
let helper = calls(m, from, to).iter().any(|(n, method)| !(n.ends_with('!') && is_assert_macro(n)) && is_helper_call(n, *method, helpers));
|
||||
!helper
|
||||
let body = &unmessaged[from - v.t.open..to - v.t.open];
|
||||
let rejects = contains(body, b".unwrap_err()") || contains(body, b".expect_err(");
|
||||
helpers_in(from, to).is_empty()
|
||||
&& !rejects
|
||||
&& !inside.is_empty()
|
||||
&& inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm(&m[f..t])).collect::<Vec<_>>(), var))
|
||||
};
|
||||
@@ -1353,7 +1364,8 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
}
|
||||
}
|
||||
for a in v.asserts.iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())) {
|
||||
if census_condition(&v.first_arg(a), 0) == (true, true) {
|
||||
let called = a.args.first().map(|&(f, t)| helpers_in(f, t)).unwrap_or_default();
|
||||
if census_condition(&v.first_arg(a), 0, &called) == (true, true) {
|
||||
return vec![v.whole(Rule::Census, "checks .all(…) over every entry of a table for presence only".into())];
|
||||
}
|
||||
}
|
||||
@@ -1363,35 +1375,73 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
/// For a (whitespace-free) assertion condition: whether it holds on presence checks alone, and
|
||||
/// whether one of those is a [`weak_table_all`]. Operands joined by `&&` all have to be weak, while
|
||||
/// one weak side of an `||` is enough, since the assertion passes on that side alone. Conditions
|
||||
/// nested deeper than 64 operators are not judged.
|
||||
fn census_condition(cond: &str, depth: usize) -> (bool, bool) {
|
||||
if depth > 64 || !cond.contains(".all(") {
|
||||
return (false, false);
|
||||
}
|
||||
if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) {
|
||||
return census_condition(&cond[1..cond.len() - 1], depth + 1);
|
||||
}
|
||||
/// nested deeper than 64 operators are not judged. An operand that calls one of `helpers` (asserting
|
||||
/// helpers called in the condition) is not a presence check, and a weak right side of an `||` does
|
||||
/// not count when the left side calls one, since the left side always runs.
|
||||
fn census_condition(cond: &str, depth: usize, helpers: &[String]) -> (bool, bool) {
|
||||
let or = top_level_at(cond, "||").first().copied();
|
||||
if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) {
|
||||
let side = |s: &str| if s.contains(".all(") { census_condition(s, depth + 1) } else { (weak_predicate(s), false) };
|
||||
let (l, r) = (side(&cond[..at]), side(&cond[at + 2..]));
|
||||
return if or.is_some() {
|
||||
if l == (true, true) || r == (true, true) { (true, true) } else { (l.0 || r.0, false) }
|
||||
} else {
|
||||
(l.0 && r.0, l.1 || r.1)
|
||||
if depth > 64 || !cond.contains(".all(") {
|
||||
(false, false)
|
||||
} else if cond.starts_with('(') && matching(cond.as_bytes(), 0) == Some(cond.len() - 1) {
|
||||
census_condition(&cond[1..cond.len() - 1], depth + 1, helpers)
|
||||
} else if let Some(at) = or.or_else(|| top_level_at(cond, "&&").first().copied()) {
|
||||
let side = |s: &str| {
|
||||
if s.contains(".all(") { census_condition(s, depth + 1, helpers) } else { (weak_predicate(s) && !calls_any(s, helpers), false) }
|
||||
};
|
||||
let (l, r) = (side(&cond[..at]), side(&cond[at + 2..]));
|
||||
let r = if or.is_some() && calls_any(&cond[..at], helpers) { (false, false) } else { r };
|
||||
if or.is_none() {
|
||||
(l.0 && r.0, l.1 || r.1)
|
||||
} else if l == (true, true) || r == (true, true) {
|
||||
(true, true)
|
||||
} else {
|
||||
(l.0 || r.0, false)
|
||||
}
|
||||
} else {
|
||||
let table = weak_table_all(cond, helpers);
|
||||
(table || weak_predicate(cond) && !calls_any(cond, helpers), table)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `s` calls a function or method named in `names`, with or without a turbofish.
|
||||
fn calls_any(s: &str, names: &[String]) -> bool {
|
||||
names.iter().any(|n| {
|
||||
[format!("{n}("), format!("{n}::<")]
|
||||
.iter()
|
||||
.any(|call| s.match_indices(call.as_str()).any(|(at, _)| at == 0 || !is_ident(s.as_bytes()[at - 1])))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether a (whitespace-free) `.all(…)` predicate checks only presence. A predicate that calls one
|
||||
/// of `helpers` is weak only when a presence check can pass without the helper running: a weak left
|
||||
/// side of an `||`, a weak right side after a left side that calls no helper, or weak operands on
|
||||
/// both sides of an `&&`.
|
||||
fn presence_only(pred: &str, helpers: &[String], depth: usize) -> bool {
|
||||
let body = pred.strip_prefix('|').and_then(|r| r.split_once('|')).map_or(pred, |(_, body)| body);
|
||||
let (or, and) = (top_level_at(body, "||").first().copied(), top_level_at(body, "&&").first().copied());
|
||||
if !calls_any(pred, helpers) {
|
||||
weak_predicate(pred)
|
||||
} else if depth > 64 {
|
||||
false
|
||||
} else if body.starts_with('(') && matching(body.as_bytes(), 0) == Some(body.len() - 1) {
|
||||
presence_only(&body[1..body.len() - 1], helpers, depth + 1)
|
||||
} else if let Some(at) = or {
|
||||
let left = &body[..at];
|
||||
presence_only(left, helpers, depth + 1) || !calls_any(left, helpers) && presence_only(&body[at + 2..], helpers, depth + 1)
|
||||
} else if let Some(at) = and {
|
||||
presence_only(&body[..at], helpers, depth + 1) && presence_only(&body[at + 2..], helpers, depth + 1)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
let table = weak_table_all(cond);
|
||||
(table || weak_predicate(cond), table)
|
||||
}
|
||||
|
||||
/// Whether a (whitespace-free) operand is exactly `TABLE.iter().all(…)` with a presence-only predicate.
|
||||
fn weak_table_all(op: &str) -> bool {
|
||||
fn weak_table_all(op: &str, helpers: &[String]) -> bool {
|
||||
let Some(&i) = top_level_at(op, ".all(").last() else { return false };
|
||||
let receiver = op[..i].trim_end_matches(".iter()").trim_end_matches(".into_iter()");
|
||||
let rest = &op[i + ".all(".len()..];
|
||||
let end = arg_end(rest);
|
||||
rest[end..] == *")" && whole_table(receiver) && weak_predicate(&rest[..end])
|
||||
rest[end..] == *")" && whole_table(receiver) && presence_only(&rest[..end], helpers, 0)
|
||||
}
|
||||
|
||||
/// The `{` that opens a `for` loop's body: the first one outside brackets after `from`.
|
||||
@@ -2934,6 +2984,37 @@ mod tests {
|
||||
assert_eq!(census(subsets), [], "subset adapters pick a few entries");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_counts_rejections_and_helpers_as_checks() {
|
||||
let census_in = |src: &str, ctx: &Ctx| hits_in("crates/x/src/tests.rs", src, ctx).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
let rejected = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).unwrap_err();\n }\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n parse(case.invalid).expect_err(\"rejects\");\n }\n}\n";
|
||||
assert_eq!(census_in(rejected, &ctx()), [], "an unwrap_err or expect_err in the loop checks a rejection");
|
||||
let only_ok = "#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok());\n }\n}\n";
|
||||
assert_eq!(census_in(only_ok, &ctx()), [(2, "census")]);
|
||||
let all_helper = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| exercise(c).is_some()));\n}\nfn exercise(c: &Color) -> Option<()> {\n assert_eq!(blend(c), WHITE);\n Some(())\n}\n";
|
||||
let files = [("crates/x/src/tests.rs".to_owned(), all_helper.to_owned())];
|
||||
let with_helpers = Ctx { helpers: asserting_helpers(&files), ..ctx() };
|
||||
assert_eq!(census_in(all_helper, &with_helpers), [], "an asserting helper in the .all(…) predicate");
|
||||
assert_eq!(census_in(all_helper, &ctx()), [(2, "census")], "a predicate whose call does not assert");
|
||||
let message =
|
||||
"#[test]\nfn t() {\n for case in CASES {\n assert!(parse(case.valid).is_ok(),\"{:?}\", probe().unwrap_err());\n }\n}\n";
|
||||
assert_eq!(census_in(message, &ctx()), [(2, "census")], "an unwrap_err in a failure message runs only after a failure");
|
||||
let skipped = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some()) || verify_fallback());\n}\n";
|
||||
assert_eq!(census_in(skipped, &ctx()), [(2, "census")], "a helper on the other side of an || can be skipped");
|
||||
let inner = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| c.is_some() || verify_fallback(c).is_some()));\n}\n";
|
||||
assert_eq!(census_in(inner, &ctx()), [(2, "census")], "a helper inside the predicate behind an || can be skipped");
|
||||
let outer = "#[test]\nfn t() {\n assert!(verify_entry() || COLORS.iter().all(|c| c.is_some()));\n}\n";
|
||||
assert_eq!(census_in(outer, &ctx()), [], "a helper on the left of an outer || always runs");
|
||||
let in_message = "#[test]\nfn t() {\n for c in COLORS {\n assert!(c.is_some(), \"{:?}\", verify_entry(c));\n }\n}\n";
|
||||
assert_eq!(census_in(in_message, &ctx()), [(2, "census")], "a helper in a failure message runs only after a failure");
|
||||
let first = "#[test]\nfn t() {\n assert!(COLORS.iter().all(|c| verify_entry(c) || c.is_some()));\n}\n";
|
||||
assert_eq!(census_in(first, &ctx()), [], "a helper on the left of an || always runs");
|
||||
let generic = all_helper.replace("exercise(c)", "exercise::<Color>(c)");
|
||||
assert_eq!(census_in(&generic, &with_helpers), [], "a helper called with a turbofish");
|
||||
let enforced = "#[test]\nfn t() {\n for case in CASES {\n assert!(!case.is_empty());\n let Ok(_) = parse(case) else { panic!(\"parse failed\") };\n }\n}\n";
|
||||
assert_eq!(census_in(enforced, &ctx()), [(2, "census")], "a panic that only enforces success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_is_report_only() {
|
||||
assert!(!Rule::Census.fails());
|
||||
|
||||
Reference in new issue
Block a user