mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-02 14:51:20 -05:00
Merge main into fix/rebalance-test-shards
This commit is contained in:
@@ -143,8 +143,8 @@ fn the_fonts_folder_next_to_a_document_is_an_absolute_path() {
|
||||
let (_dir, root) = folder("relative");
|
||||
std::fs::create_dir_all(root.join("pkg/Fonts")).unwrap();
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
let up = "../".repeat(cwd.components().count().saturating_sub(1));
|
||||
let relative = format!("{up}{}", root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap().display());
|
||||
let up: PathBuf = cwd.components().skip(1).map(|_| std::path::Component::ParentDir).collect();
|
||||
let relative = up.join(root.join("pkg/doc.vectorcraft").strip_prefix("/").unwrap()).display().to_string();
|
||||
assert!(Path::new(&relative).is_relative());
|
||||
let mut s = session_for(&root);
|
||||
let mut doc = vectorcraft_doc::Document::new(100.0, 100.0);
|
||||
|
||||
@@ -103,7 +103,8 @@ fn from_workspace(dir: PathBuf) -> PathBuf {
|
||||
return dir;
|
||||
}
|
||||
let crate_dir = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
|
||||
crate_dir.join("../..").join(dir)
|
||||
// The workspace root is two levels above `crates/text`.
|
||||
crate_dir.ancestors().nth(2).unwrap_or(&crate_dir).join(dir)
|
||||
}
|
||||
|
||||
/// The one craft-fonts face web builds embed (family, style).
|
||||
|
||||
+880
-6
@@ -50,7 +50,9 @@
|
||||
//! `entries`, `variants`, `commands`, `builtins` or `palette`, or ending or starting with one of
|
||||
//! those after `_`) where every assertion in the loop only checks presence (`is_some`, `is_ok`,
|
||||
//! `is_empty`, `contains`, `starts_with`, `is_finite`, `len() > 0`) or compares with a lookup or
|
||||
//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table;
|
||||
//! parse of the entry, or asserts `.all(…)` of such a predicate over a whole table. A loop that
|
||||
//! passes the entry to a call together with other state (a command run, a file written, a
|
||||
//! render) is a table of behavior cases and is not reported;
|
||||
//! * `mirror`: `assert_eq!(f(a), f(b) <op> …)`, where the expected side derives its value from a
|
||||
//! second call of the same function (same path) with arithmetic, so a fault in `f` moves both
|
||||
//! sides; builders and conversions (`new`, `from`, `to_string` …) are left out, as are the same
|
||||
@@ -1650,7 +1652,12 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
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 body = &unmessaged[from - v.t.open..to - v.t.open];
|
||||
helpers_in(from, to).is_empty()
|
||||
// A helper counts only where it runs whenever the assertions pass, not after an `||`.
|
||||
let (f, t) = (from + 1 - v.t.open, to - v.t.open);
|
||||
let helper_runs = calls_at(&unmessaged, f, t).into_iter().any(|(at, n, method)| {
|
||||
!(n.ends_with('!') && is_assert_macro(&n)) && is_helper_call(&n, method, helpers) && runs_with_assertion(&unmessaged, f, t, at)
|
||||
});
|
||||
!helper_runs
|
||||
&& !rejects(body)
|
||||
&& !inside.is_empty()
|
||||
&& inside.iter().all(|a| weak_census_check(&a.name, &a.args.iter().map(|&(f, t)| norm_words(&m[f..t])).collect::<Vec<_>>(), var))
|
||||
@@ -1667,6 +1674,7 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
&& helpers_in(kw + 2, open).is_empty()
|
||||
&& words(m, b"break", open, close).is_empty()
|
||||
&& weak_in(open, close, var)
|
||||
&& !feeds_entry(&unmessaged, &pattern, open + 1 - v.t.open, close - v.t.open)
|
||||
{
|
||||
return vec![v.whole(Rule::Census, "loops over every entry of a table and checks only presence or a round trip".into())];
|
||||
}
|
||||
@@ -1680,6 +1688,540 @@ fn census(v: &View, helpers: &HashSet<String>) -> Vec<Hit> {
|
||||
vec![]
|
||||
}
|
||||
|
||||
/// Calls that read or look up a value rather than compute one, so passing the entry to one of them
|
||||
/// together with other state does not make the loop a behavior table.
|
||||
const LOOKUPS: &[&str] = &[
|
||||
"contains",
|
||||
"contains_key",
|
||||
"starts_with",
|
||||
"ends_with",
|
||||
"get",
|
||||
"get_mut",
|
||||
"iter",
|
||||
"into_iter",
|
||||
"any",
|
||||
"find",
|
||||
"position",
|
||||
"binary_search",
|
||||
"eq",
|
||||
"ne",
|
||||
"find_map",
|
||||
];
|
||||
|
||||
/// The lowercase names a `for` or `let` pattern binds. A field label (`Row { c: other }`) binds
|
||||
/// the name after it.
|
||||
fn pattern_names(pattern: &str) -> impl Iterator<Item = String> + '_ {
|
||||
let b = pattern.as_bytes();
|
||||
pattern
|
||||
.match_indices(|c: char| c.is_ascii_alphanumeric() || c == '_')
|
||||
.filter(move |&(at, _)| at == 0 || !is_ident(b[at - 1]))
|
||||
.map(move |(at, _)| (at, at + b[at..].iter().take_while(|&&c| is_ident(c)).count()))
|
||||
.filter(move |&(at, end)| {
|
||||
// Inside braces, `name:` labels a field; outside them it starts a type (`let x: u32`).
|
||||
let in_braces = b[..at].iter().filter(|&&c| c == b'{').count() > b[..at].iter().filter(|&&c| c == b'}').count();
|
||||
let next = end + b[end..].iter().take_while(|c| c.is_ascii_whitespace()).count();
|
||||
!in_braces || b.get(next) != Some(&b':') || b.get(next + 1) == Some(&b':')
|
||||
})
|
||||
.map(move |(at, end)| &pattern[at..end])
|
||||
.filter(|w| !matches!(*w, "" | "_" | "mut" | "ref") && w.starts_with(|c: char| c.is_ascii_lowercase() || c == '_'))
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Whether the body `b[from..to]` of a loop whose pattern is `pattern` feeds the entry into a
|
||||
/// computation with other inputs: a call (not one of [`LOOKUPS`], nor a macro) whose receiver and
|
||||
/// arguments include a value read from the entry and another value that is not a literal, such as
|
||||
/// `app.run("…", json!({"id": id}))`, `export(&doc, &Options { level, .. })` or `check(SCHEMA, ¶ms)`
|
||||
/// with `params` bound from the entry inside the loop. Such a loop runs, renders or writes something
|
||||
/// for each entry, so it is a table of behavior cases. A call that takes the entry alone (`menu(c)`,
|
||||
/// `Kind::from_id(k.id())`) is still a lookup.
|
||||
fn feeds_entry(b: &[u8], pattern: &str, from: usize, to: usize) -> bool {
|
||||
// The names that hold the entry, each from the end of its binding to the end of its block.
|
||||
let mut derived: Vec<(String, usize, usize)> = pattern_names(pattern).map(|n| (n, from, to)).collect();
|
||||
// Where a binding does not read the entry, the name holds another value until its scope ends.
|
||||
let mut shadows: Vec<(String, usize, usize)> = vec![];
|
||||
for at in words(b, b"for", from, to) {
|
||||
let Some(&kw) = words(b, b"in", at + 3, to).first() else { continue };
|
||||
let Some(open) = loop_open(b, kw + 2, to) else { continue };
|
||||
let Some(close) = matching(b, open).filter(|&c| c < to) else { continue };
|
||||
shadows.extend(pattern_names(&String::from_utf8_lossy(&b[at + 3..kw])).map(|n| (n, open + 1, close)));
|
||||
}
|
||||
// Simple closure parameters shadow captures in both block and expression bodies.
|
||||
for at in from..to {
|
||||
if b[at] != b'|' || b.get(at + 1) == Some(&b'|') {
|
||||
continue;
|
||||
}
|
||||
let head = b[from..at].trim_ascii_end();
|
||||
let head = head.strip_suffix(b"move").unwrap_or(head).trim_ascii_end();
|
||||
if !head.is_empty() && !matches!(head.last(), Some(b'=' | b'(' | b',' | b'{' | b';')) {
|
||||
continue;
|
||||
}
|
||||
let Some(end) = (at + 1..to).find(|&i| b[i] == b'|') else { continue };
|
||||
// Parameters may carry types (`|c: Command|`, `|p: &[u8]|`).
|
||||
if !b[at + 1..end]
|
||||
.iter()
|
||||
.all(|&c| is_ident(c) || c.is_ascii_whitespace() || matches!(c, b',' | b'&' | b':' | b'<' | b'>' | b'(' | b')' | b'[' | b']' | b'\''))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let mut until = skip_ws(b, end + 1);
|
||||
if b.get(until) == Some(&b'{') {
|
||||
until = matching(b, until).unwrap_or(to).min(to);
|
||||
} else {
|
||||
while until < to && !matches!(b[until], b',' | b';' | b')' | b']' | b'}') {
|
||||
until = if matches!(b[until], b'(' | b'[' | b'{') { matching(b, until).unwrap_or(to) + 1 } else { until + 1 };
|
||||
}
|
||||
}
|
||||
// Each parameter binds the names before its type.
|
||||
let params = String::from_utf8_lossy(&b[at + 1..end]).into_owned();
|
||||
let names: Vec<String> = params.split(',').flat_map(|p| pattern_names(p.split(':').next().unwrap_or_default()).collect::<Vec<_>>()).collect();
|
||||
shadows.extend(names.into_iter().map(|n| (n, at + 1, until)));
|
||||
}
|
||||
// A field access (`options.c`), a path segment (`defaults::c`) or a field label (`Row { c: x }`)
|
||||
// names a field or an item, not the binding.
|
||||
let is_field = |at: usize, len: usize| {
|
||||
b[..at].trim_ascii_end().last() == Some(&b'.') || b[..at].trim_ascii_end().ends_with(b"::") || {
|
||||
let next = skip_ws(b, at + len);
|
||||
b.get(next) == Some(&b':') && b.get(next + 1) != Some(&b':')
|
||||
}
|
||||
};
|
||||
let live = |f: usize, t: usize, names: &[(String, usize, usize)], shadows: &[(String, usize, usize)]| {
|
||||
names.iter().any(|(n, since, until)| {
|
||||
words(b, n.as_bytes(), f.max(*since), t.min(*until))
|
||||
.into_iter()
|
||||
.any(|at| !is_field(at, n.len()) && !shadows.iter().any(|(s, a, z)| s == n && *a <= at && at < *z))
|
||||
})
|
||||
};
|
||||
// Names bound inside the loop from the entry count as the entry.
|
||||
for at in words(b, b"let", from, to) {
|
||||
let Some(eq) =
|
||||
(at + 3..to).find(|&i| b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>'))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
// `if let` and `while let` end their initializer at the conditional's block.
|
||||
let conditional = [b"if".as_slice(), b"while"].iter().any(|kw| b[from..at].trim_ascii_end().ends_with(kw));
|
||||
let end = if conditional { (eq..to).find(|&i| b[i] == b'{').unwrap_or(to) } else { statement_end(&b[..to], eq) };
|
||||
// A block initializer binds the value of its tail (`{ prepare(); c }`).
|
||||
let mut value = eq + 1;
|
||||
let init = skip_ws(b, value);
|
||||
if !conditional && b.get(init) == Some(&b'{') && matching(b, init).is_some_and(|close| b[close + 1..end].trim_ascii().is_empty()) {
|
||||
let close = matching(b, init).unwrap_or(end);
|
||||
let mut i = init + 1;
|
||||
value = i;
|
||||
while i < close {
|
||||
match b[i] {
|
||||
b'(' | b'[' | b'{' => i = matching(b, i).unwrap_or(close),
|
||||
b';' => value = i + 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let names: Vec<String> = pattern_names(&String::from_utf8_lossy(&b[at + 3..eq])).collect();
|
||||
if live(value, end, &derived, &shadows) {
|
||||
// Rebinding from the entry suspends earlier shadows until this block ends.
|
||||
let until = block_close(b, at).min(to);
|
||||
let mut resumed = vec![];
|
||||
for s in shadows.iter_mut().filter(|s| names.contains(&s.0) && s.1 <= at && at < s.2) {
|
||||
if until < s.2 {
|
||||
resumed.push((s.0.clone(), until, s.2));
|
||||
}
|
||||
s.2 = end;
|
||||
}
|
||||
shadows.extend(resumed);
|
||||
derived.extend(names.into_iter().map(|n| (n, end, until)));
|
||||
} else {
|
||||
let until = block_close(b, at).min(to);
|
||||
shadows.extend(names.into_iter().filter(|n| derived.iter().any(|(d, _, _)| d == n)).map(|n| (n, end, until)));
|
||||
}
|
||||
}
|
||||
let reads = |f: usize, t: usize| live(f, t, &derived, &shadows);
|
||||
let literal = |s: &[u8]| {
|
||||
let s = norm(s);
|
||||
let s = s.trim_start_matches(['&', '*']);
|
||||
// String, byte and raw literals keep their prefix after masking (`r"…"`, `b'…'`, `br#"…"#`).
|
||||
let s = match s.find(['"', '\'']) {
|
||||
Some(q) if q <= 3 && s[..q].bytes().all(|c| matches!(c, b'b' | b'c' | b'r' | b'#')) => &s[q..],
|
||||
_ => s,
|
||||
};
|
||||
// A closure only shapes the call on the entry (`.map(|x| …)`); it is not another input.
|
||||
// A minus sign makes a literal only in front of a number (`-2`, not `-offset`).
|
||||
let s = s.strip_prefix('-').unwrap_or(s);
|
||||
let mut start = 0;
|
||||
let mut operands = 0;
|
||||
let mut numeric = true;
|
||||
for (i, c) in s.char_indices().chain([(s.len(), '+')]) {
|
||||
let range = c == '.' && (s.as_bytes().get(i + 1) == Some(&b'.') || s[..i].ends_with('.')) || c == '=' && s[..i].ends_with("..");
|
||||
if !range && !matches!(c, '+' | '-' | '*' | '/' | '%' | '<' | '>' | '&' | '|' | '^' | '(' | ')') {
|
||||
continue;
|
||||
}
|
||||
let head = &s[start..i];
|
||||
if i < s.len()
|
||||
&& matches!(c, '+' | '-')
|
||||
&& head
|
||||
.strip_suffix(['e', 'E'])
|
||||
.is_some_and(|n| n.starts_with(|c: char| c.is_ascii_digit()) && n.bytes().all(|c| c.is_ascii_digit() || matches!(c, b'_' | b'.')))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if !head.is_empty() {
|
||||
operands += 1;
|
||||
numeric &= numeric_literal(head);
|
||||
}
|
||||
start = i + c.len_utf8();
|
||||
}
|
||||
let numeric = numeric && operands > 0;
|
||||
s.is_empty() || s.starts_with(['"', '\'', '|']) || s.starts_with("move|") || numeric || matches!(s, "true" | "false" | "None")
|
||||
};
|
||||
(from..to).filter_map(|i| (b[i] == b'(' && i > from).then(|| call_name_end(b, from, i)).flatten().map(|e| (i, e))).any(|(open, name_end)| {
|
||||
let mut start = name_end;
|
||||
while start > from && is_ident(b[start - 1]) {
|
||||
start -= 1;
|
||||
}
|
||||
let name = String::from_utf8_lossy(&b[start..name_end]);
|
||||
if start == name_end || LOOKUPS.contains(&name.as_ref()) || b[start].is_ascii_digit() || !runs_with_assertion(b, from, to, start) {
|
||||
return false;
|
||||
}
|
||||
let Some(close) = matching(b, open).filter(|&c| c < to) else { return false };
|
||||
let args = split_args(b, open + 1, close);
|
||||
let mut inputs = args.clone();
|
||||
if start > from && b[start - 1] == b'.' {
|
||||
// The receiver: the chain of names, calls and indexing before the dot.
|
||||
let mut r = start - 1;
|
||||
while r > from {
|
||||
match b[r - 1] {
|
||||
c if is_ident(c) || c == b'.' => r -= 1,
|
||||
// A chain rustfmt splits over lines continues with a `.` after the line break.
|
||||
c if c.is_ascii_whitespace() && b[r..start].iter().find(|c| !c.is_ascii_whitespace()) == Some(&b'.') => r -= 1,
|
||||
b')' | b']' => match (from..r - 1).rev().find(|&o| matching(b, o) == Some(r - 1)) {
|
||||
Some(o) => r = o,
|
||||
None => break,
|
||||
},
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
inputs.push((r, start - 1));
|
||||
}
|
||||
let fed = inputs.iter().any(|&(f, t)| reads(f, t));
|
||||
// A lookup or parse on a table (`registry.lookup(k)`) takes the table as its receiver; only
|
||||
// another argument (`u.parse(&text)`) makes it a computation.
|
||||
let others = if ROUND_TRIP.contains(&name.as_ref()) { &args } else { &inputs };
|
||||
let other = others.iter().any(|&(f, t)| !literal(&b[f..t]) && !reads(f, t));
|
||||
fed && other
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the whitespace-free `s` is one numeric literal (`1`, `0x1F`, `2.5f32`, `1_000`, `1e-3`), not
|
||||
/// an expression that starts with one (`1+offset`, `1..limit`).
|
||||
fn numeric_literal(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
let radix = match b.get(..2) {
|
||||
Some(b"0x") => 16,
|
||||
Some(b"0o") => 8,
|
||||
Some(b"0b") => 2,
|
||||
_ => 10,
|
||||
};
|
||||
let mut i = if radix == 10 { 0 } else { 2 };
|
||||
let mut digits = 0;
|
||||
while let Some(&c) = b.get(i) {
|
||||
if (c as char).is_digit(radix) {
|
||||
digits += 1;
|
||||
} else if c != b'_' {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if digits == 0 || !b.first().is_some_and(u8::is_ascii_digit) {
|
||||
return false;
|
||||
}
|
||||
if radix == 10 {
|
||||
if b.get(i) == Some(&b'.') {
|
||||
i += 1;
|
||||
if i < b.len() && !b[i].is_ascii_digit() {
|
||||
return false;
|
||||
}
|
||||
while b.get(i).is_some_and(|c| c.is_ascii_digit() || *c == b'_') {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
if matches!(b.get(i), Some(b'e' | b'E')) {
|
||||
i += 1;
|
||||
if matches!(b.get(i), Some(b'+' | b'-')) {
|
||||
i += 1;
|
||||
}
|
||||
let mut digits = 0;
|
||||
while let Some(&c) = b.get(i) {
|
||||
if c.is_ascii_digit() {
|
||||
digits += 1;
|
||||
} else if c != b'_' {
|
||||
break;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
if digits == 0 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
matches!(&s[i..], "" | "u8" | "u16" | "u32" | "u64" | "u128" | "usize" | "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "f32" | "f64")
|
||||
}
|
||||
|
||||
/// Where the name of a call whose `(` is at `open` ends: right before the `(`, or before the
|
||||
/// `::<…>` of a turbofish (`app.run::<Mode>(c)`). `None` when no name precedes the `(`.
|
||||
fn call_name_end(b: &[u8], from: usize, open: usize) -> Option<usize> {
|
||||
// Masked comments leave spaces between the name and the `(` (`app.run /* note */ (c)`).
|
||||
let before = from + b[from..open].trim_ascii_end().len();
|
||||
if before > from && is_ident(b[before - 1]) {
|
||||
// A keyword before a parenthesized expression (`if (a)`, `return (x)`) is not a call.
|
||||
let mut start = before;
|
||||
while start > from && is_ident(b[start - 1]) {
|
||||
start -= 1;
|
||||
}
|
||||
const KEYWORDS: [&[u8]; 15] =
|
||||
[b"if", b"else", b"match", b"while", b"for", b"in", b"return", b"break", b"let", b"mut", b"move", b"async", b"await", b"as", b"loop"];
|
||||
let keyword = KEYWORDS.contains(&&b[start..before]);
|
||||
return (before == open || !keyword).then_some(before);
|
||||
}
|
||||
if before == from || b[before - 1] != b'>' {
|
||||
return None;
|
||||
}
|
||||
let mut depth = 0usize;
|
||||
for i in (from..before).rev() {
|
||||
match b[i] {
|
||||
b'>' if i == 0 || b[i - 1] != b'-' => depth += 1,
|
||||
b'<' => {
|
||||
depth = depth.checked_sub(1)?;
|
||||
if depth == 0 {
|
||||
let head = b[from..i].trim_ascii_end();
|
||||
let end = head.strip_suffix(b"::")?.trim_ascii_end().len();
|
||||
return (end > 0 && is_ident(b[from + end - 1])).then_some(from + end);
|
||||
}
|
||||
}
|
||||
b';' | b'{' | b'}' => return None,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a call starting at `start` in the loop body `b[from..to]` runs whenever the loop's
|
||||
/// assertions pass. A call after `||` in its statement may not run (`menu(c).is_some() || app.run(c)`,
|
||||
/// also with a block as the right operand); the right side of `&&` has to run only in an asserted
|
||||
/// condition. A call inside a closure bound with `let` runs only when the loop calls
|
||||
/// that closure.
|
||||
fn runs_with_assertion(b: &[u8], from: usize, to: usize, start: usize) -> bool {
|
||||
runs_with_assertion_within(b, from, to, start, &[])
|
||||
}
|
||||
|
||||
/// [`runs_with_assertion`], where `active` holds the calls whose check is in progress, so a closure
|
||||
/// that calls itself does not recurse without end.
|
||||
fn runs_with_assertion_within(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool {
|
||||
if active.contains(&start) {
|
||||
return false;
|
||||
}
|
||||
let mut active = active.to_vec();
|
||||
active.push(start);
|
||||
if in_uncalled_closure(b, from, to, start, &active) {
|
||||
return false;
|
||||
}
|
||||
// Check enclosing blocks independently of the call's statement: an earlier semicolon inside
|
||||
// a conditional block does not make its later statements run unconditionally.
|
||||
for open in (from..start).filter(|&i| b[i] == b'{' && matching(b, i).is_some_and(|close| start < close)) {
|
||||
let mut head = open;
|
||||
while head > from {
|
||||
head -= 1;
|
||||
match b[head] {
|
||||
b')' | b']' => {
|
||||
let Some(back) = (from..head).rev().find(|&i| matching(b, i) == Some(head)) else { return false };
|
||||
head = back;
|
||||
}
|
||||
b';' | b'{' | b'}' => {
|
||||
head += 1;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let prefix = b[head..open].trim_ascii();
|
||||
if prefix.ends_with(b"||") || prefix.ends_with(b"&&") {
|
||||
if !runs_with_assertion_within(b, from, to, open, &active) {
|
||||
return false;
|
||||
}
|
||||
} else if !prefix.ends_with(b"|")
|
||||
&& !(prefix.starts_with(b"for") && prefix.get(3).is_some_and(u8::is_ascii_whitespace))
|
||||
&& (prefix.ends_with(b"=>")
|
||||
|| [b"async".as_slice(), b"async move"]
|
||||
.iter()
|
||||
.any(|kw| prefix.ends_with(kw) && !prefix[..prefix.len() - kw.len()].last().copied().is_some_and(is_ident))
|
||||
|| [b"if".as_slice(), b"else", b"match", b"while"].iter().any(|kw| !words(prefix, kw, 0, prefix.len()).is_empty())
|
||||
|| (!words(prefix, b"loop", 0, prefix.len()).is_empty()
|
||||
&& matching(b, open).is_some_and(|close| !words(b, b"break", open + 1, close).is_empty())))
|
||||
{
|
||||
// A nested `for` body is taken to run, like the loop body itself; [`feeds_entry`] keeps
|
||||
// its own bindings apart.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// The statement starts after a `;` or an unmatched brace, except for the `{` of a block that is
|
||||
// the operand of `||` or `&&`.
|
||||
let mut stmt = from;
|
||||
let mut braces = 0usize;
|
||||
for i in (from..start).rev() {
|
||||
match b[i] {
|
||||
// A block that ends before the call closes an earlier statement (`if a || b {} app.run(c)`)
|
||||
// unless an operator joins the call's expression to it.
|
||||
b'}' if braces == 0 && {
|
||||
let after = b[i + 1..start].trim_ascii_start();
|
||||
!(after.starts_with(b"||") || after.starts_with(b"&&") || after.starts_with(b".") || after.starts_with(b"?"))
|
||||
} =>
|
||||
{
|
||||
stmt = i + 1;
|
||||
break;
|
||||
}
|
||||
b'}' => braces += 1,
|
||||
b'{' if braces > 0 => braces -= 1,
|
||||
b'{' => {
|
||||
let before = b[from..i].trim_ascii_end();
|
||||
if !(before.ends_with(b"||") || before.ends_with(b"&&")) {
|
||||
stmt = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
b';' if braces == 0 => {
|
||||
stmt = i + 1;
|
||||
break;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
// Only an operator at the call's own nesting level or an enclosing one counts, not one inside
|
||||
// an earlier group (`(a || b) && app.run(c)`). A logical OR follows an operand;
|
||||
// otherwise the pipes open a zero-argument closure, optionally preceded by `move` or `async`.
|
||||
// Earlier sibling elements cannot skip the call, but guards around their group still can.
|
||||
let mut depth = 0usize;
|
||||
let params = (stmt..start).find_map(|pipe| {
|
||||
if b[pipe] != b'|' {
|
||||
return None;
|
||||
}
|
||||
let head = b[stmt..pipe].trim_ascii();
|
||||
let head = head.strip_suffix(b"move").or_else(|| head.strip_suffix(b"async")).unwrap_or(head).trim_ascii_end();
|
||||
if !head.ends_with(b"=") || !head.starts_with(b"let") || !head.get(3).is_some_and(u8::is_ascii_whitespace) {
|
||||
return None;
|
||||
}
|
||||
(pipe + 1..start).find(|&end| b[end] == b'|').map(|end| (pipe, end))
|
||||
});
|
||||
let mut closure = params.map(|(pipe, _)| pipe);
|
||||
let mut sibling = false;
|
||||
for i in (stmt + 1..start).rev() {
|
||||
if params.is_some_and(|(pipe, end)| pipe <= i && i <= end) {
|
||||
continue;
|
||||
}
|
||||
match b[i] {
|
||||
b')' | b']' | b'}' => depth += 1,
|
||||
b'(' | b'[' | b'{' if depth == 0 => sibling = false,
|
||||
b'(' | b'[' | b'{' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
if depth != 0 {
|
||||
continue;
|
||||
}
|
||||
if b[i] == b',' {
|
||||
sibling = true;
|
||||
}
|
||||
if sibling {
|
||||
continue;
|
||||
}
|
||||
if b[i] == b'=' && !matches!(b.get(i + 1), Some(b'=' | b'>')) && !matches!(b[i - 1], b'=' | b'!' | b'<' | b'>') {
|
||||
break;
|
||||
}
|
||||
if b[i] == b'&'
|
||||
&& b[i - 1] == b'&'
|
||||
&& b[stmt..i - 1].trim_ascii_end().last().is_some_and(|&c| is_ident(c) || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}'))
|
||||
&& !asserted_conjunction(b, from, to, i - 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if b[i] == b'|' && b[i - 1] == b'|' {
|
||||
let end = (stmt..i - 1).rev().find(|&j| !b[j].is_ascii_whitespace()).map_or(stmt, |j| j + 1);
|
||||
let prefix = &b[stmt..end];
|
||||
let moved = prefix.ends_with(b"move") && (prefix.len() == 4 || !is_ident(prefix[prefix.len() - 5]));
|
||||
let asynchronous = prefix.ends_with(b"async") && (prefix.len() == 5 || !is_ident(prefix[prefix.len() - 6]));
|
||||
if !moved
|
||||
&& !asynchronous
|
||||
&& prefix.last().is_some_and(|&c| is_ident(c) || c.is_ascii_digit() || matches!(c, b')' | b']' | b'"' | b'\'' | b'?' | b'}'))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
closure = Some(stmt + prefix.len());
|
||||
}
|
||||
}
|
||||
// `let run = || app.run(c);`: the closure's body runs only where the loop calls `run`.
|
||||
let Some(end) = closure else { return true };
|
||||
let head = String::from_utf8_lossy(&b[stmt..end]);
|
||||
let head = head.trim();
|
||||
let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end();
|
||||
let Some(binding) = head.strip_suffix('=').map(str::trim).and_then(|h| h.strip_prefix("let")) else { return true };
|
||||
let Some(name) = pattern_names(binding).last() else { return true };
|
||||
words(b, name.as_bytes(), end, to).into_iter().any(|at| {
|
||||
// `other.run()` calls a method, not the closure.
|
||||
b[..at].trim_ascii_end().last() != Some(&b'.')
|
||||
&& b.get(skip_ws(b, at + name.len())) == Some(&b'(')
|
||||
&& runs_with_assertion_within(b, from, to, at, &active)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an `&&` is at the top level of an assertion's first argument.
|
||||
fn asserted_conjunction(b: &[u8], from: usize, to: usize, at: usize) -> bool {
|
||||
macro_calls(b, from, to).iter().filter(|a| PLAIN_ASSERTS.contains(&a.name.as_str())).any(|a| {
|
||||
let Some(&(mut f, mut t)) = a.args.first() else { return false };
|
||||
loop {
|
||||
f += b[f..t].len() - b[f..t].trim_ascii_start().len();
|
||||
t = f + b[f..t].trim_ascii_end().len();
|
||||
if b.get(f) != Some(&b'(') || matching(b, f) != t.checked_sub(1) {
|
||||
break;
|
||||
}
|
||||
f += 1;
|
||||
t -= 1;
|
||||
}
|
||||
// A top-level `||` lets the assertion pass without the conjunction.
|
||||
let cond = String::from_utf8_lossy(&b[f..t]);
|
||||
f <= at && at < t && top_level_at(&cond, "||").is_empty() && top_level_at(&cond, "&&").contains(&(at - f))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `start` lies in the block body of a closure bound with `let` in
|
||||
/// `b[from..to]` (`let run = || { … };`, also `move` or `async`) that the loop never calls.
|
||||
fn in_uncalled_closure(b: &[u8], from: usize, to: usize, start: usize, active: &[usize]) -> bool {
|
||||
let mut depth = 0usize;
|
||||
for i in (from..start).rev() {
|
||||
match b[i] {
|
||||
b')' | b']' | b'}' => depth += 1,
|
||||
b'(' | b'[' if depth > 0 => depth -= 1,
|
||||
b'{' if depth > 0 => depth -= 1,
|
||||
b'{' => {
|
||||
let Some(params) = b[from..i].trim_ascii_end().strip_suffix(b"|") else { continue };
|
||||
let Some(pipe) = params.iter().rposition(|&c| c == b'|') else { continue };
|
||||
let head = params[..pipe].trim_ascii_end();
|
||||
let head = String::from_utf8_lossy(head);
|
||||
let head = head.trim_end();
|
||||
let head = head.strip_suffix("move").or_else(|| head.strip_suffix("async")).unwrap_or(head).trim_end();
|
||||
let Some(binding) = head.strip_suffix('=').and_then(|h| h.rsplit_once("let")).map(|(_, b)| b) else { continue };
|
||||
let Some(name) = pattern_names(binding).last() else { continue };
|
||||
let close = matching(b, i).unwrap_or(to);
|
||||
if !words(b, name.as_bytes(), close, to).into_iter().any(|at| {
|
||||
b[..at].trim_ascii_end().last() != Some(&b'.')
|
||||
&& b.get(skip_ws(b, at + name.len())) == Some(&b'(')
|
||||
&& runs_with_assertion_within(b, from, to, at, active)
|
||||
}) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -1959,8 +2501,8 @@ fn weak_census_check(name: &str, args: &[String], var: &str) -> bool {
|
||||
/// Whether an operand ([`norm_words`]) is the result of one of [`ROUND_TRIP`], called by its whole
|
||||
/// name with only a path or receiver before it (no arithmetic) and followed only by unwrapping (`.unwrap()`, `.ok()`, `.expect(…)`, `?` and the like), so
|
||||
/// the operand is the parsed or looked-up entry itself and not a value derived from it. The call's
|
||||
/// arguments must read the loop entry `var` (`Kind::from_id(k.id())`); a lookup of a fixed key is
|
||||
/// not a round trip of the entry.
|
||||
/// arguments (`Kind::from_id(k.id())`) or its receiver (`k.parse()`) must read the loop entry `var`;
|
||||
/// a lookup of a fixed key is not a round trip of the entry.
|
||||
fn round_trip_call(op: &str, var: &str) -> bool {
|
||||
let mut op = op.trim_start_matches(['&', '*']);
|
||||
loop {
|
||||
@@ -1976,7 +2518,11 @@ fn round_trip_call(op: &str, var: &str) -> bool {
|
||||
let open = at + r.len();
|
||||
!op.as_bytes()[..at].last().copied().is_some_and(is_ident)
|
||||
&& !op[..at].contains(['+', '-', '*', '/', '%', '^', '|', '!', '=', ',', '&'])
|
||||
&& matching(op.as_bytes(), open).is_some_and(|close| only_unwraps(&op[close + 1..]) && reads_ident(&op[open + 1..close], var))
|
||||
&& matching(op.as_bytes(), open).is_some_and(|close| {
|
||||
// The entry is read in the arguments (`Kind::from_id(k.id())`) or is the receiver (`k.parse()`).
|
||||
let receiver = op[..at].strip_suffix('.').is_some_and(|r| reads_ident(r, var));
|
||||
only_unwraps(&op[close + 1..]) && (receiver || reads_ident(&op[open + 1..close], var))
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -4522,6 +5068,9 @@ fn unescape(s: &str) -> String {
|
||||
continue;
|
||||
}
|
||||
match chars.next() {
|
||||
Some(c @ ('\n' | '\r')) if c == '\n' || chars.peek() == Some(&'\n') => {
|
||||
while chars.next_if(|c| matches!(c, ' ' | '\t' | '\n' | '\r')).is_some() {}
|
||||
}
|
||||
Some('n') => out.push('\n'),
|
||||
Some('t') => out.push('\t'),
|
||||
Some('r') => out.push('\r'),
|
||||
@@ -5034,7 +5583,7 @@ fn cfg_attr_paths(m: &[u8], src: &[u8], from: usize, to: usize) -> Vec<(String,
|
||||
}
|
||||
let open = skip_ws(m, at + "cfg_attr".len());
|
||||
let Some(close) = (m.get(open) == Some(&b'(')).then(|| matching(m, open)).flatten() else { continue };
|
||||
let text = pred_text(&src[open + 1..close]);
|
||||
let text = norm_outside_literals(&mask_parts(&String::from_utf8_lossy(&src[open + 1..close]), true, false));
|
||||
let cuts = attr_commas(&text);
|
||||
let Some(&first) = cuts.first() else { continue };
|
||||
let mut start = first + 1;
|
||||
@@ -8073,6 +8622,30 @@ mod tests {
|
||||
assert_eq!(cfg_attr_paths(&mask(raw_escape), raw_escape.as_bytes(), 0, raw_escape.len()), [("unix".to_owned(), "\\x61.rs".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_paths_decode_string_continuations() {
|
||||
for newline in ["\n", "\r\n"] {
|
||||
let src = format!("#[cfg_attr(unix, path = \"chi\\{newline} \t\r\n ld.rs\")]\nmod c;\n");
|
||||
assert_eq!(cfg_attr_paths(&mask(&src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child.rs".to_owned())]);
|
||||
}
|
||||
let src = "#[cfg_attr(unix, path = \"child file.rs\")]\nmod c;\n";
|
||||
assert_eq!(cfg_attr_paths(&mask(src), src.as_bytes(), 0, src.len()), [("unix".to_owned(), "child file.rs".to_owned())]);
|
||||
let raw = "#[cfg_attr(unix, path = r\"chi\\\n ld.rs\")]\nmod c;\n";
|
||||
assert_eq!(cfg_attr_paths(&mask(raw), raw.as_bytes(), 0, raw.len()), [("unix".to_owned(), "chi\\\n ld.rs".to_owned())]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conditional_paths_keep_sibling_cfg_gates_with_brackets_in_filenames() {
|
||||
let files: HashMap<&str, &str> =
|
||||
[("crates/x/src/lib.rs", "#[cfg_attr(unix, path = \"mac[.rs\", cfg(target_os = \"macos\"))]\nmod platform;\n")].into_iter().collect();
|
||||
let read = |p: &str| files.get(p).map(|s| (*s).to_owned());
|
||||
let overrides = path_overrides(files.iter().map(|(p, s)| (*p, *s)));
|
||||
let child = "crates/x/src/mac[.rs".to_owned();
|
||||
let ctx = Ctx { module_cfgs: module_cfgs(std::slice::from_ref(&child), &read, &overrides), ..ctx() };
|
||||
let test = "#[test]\nfn t() {\n assert_eq!(f(), 1);\n}\n";
|
||||
assert_eq!(hits_in(&child, test, &ctx), [(2, "never-run")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_attributes_accept_raw_strings() {
|
||||
for src in ["#[path = r\"shared.rs\"]\nmod s;\n", "#[path = r#\"shared.rs\"#]\nmod s;\n", "#[path = \"shared.rs\"]\nmod s;\n"] {
|
||||
@@ -8129,6 +8702,307 @@ mod tests {
|
||||
assert_eq!(hits_in("crates/x/src/shared.rs", test, &ctx), []);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_follows_the_calls_that_run_for_each_entry() {
|
||||
let census_in = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
||||
let census = |body: &str| census_in(&loop_of(body));
|
||||
assert_eq!(census("assert!(menu(c).is_some() || verify_fallback(c).is_ok());"), [(2, "census")], "a helper after || can be skipped");
|
||||
assert_eq!(census("assert!(menu(c).is_some() && verify_fallback(c).is_ok());"), [], "a helper after && runs");
|
||||
assert_eq!(census("assert!(menu(c).is_some()); { let c = fallback(); app.run(c); }"), [(2, "census")], "a shadowed entry name");
|
||||
assert_eq!(census("assert!(menu(c).is_some()); app.run(c);"), [], "the entry itself");
|
||||
assert_eq!(census("let _run = || app.run(c); assert!(menu(c).is_some());"), [(2, "census")], "a closure that is never called");
|
||||
assert_eq!(
|
||||
census("let _run = || { let r = app.run(c); r }; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a block closure that is never called"
|
||||
);
|
||||
assert_eq!(census("let run = || { let r = app.run(c); r }; assert!(run().is_ok());"), [], "a block closure the loop calls");
|
||||
assert_eq!(
|
||||
census("let params = fallback(); app.run(params); let params = c; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a binding from the entry does not reach back to an earlier use of its name"
|
||||
);
|
||||
assert_eq!(
|
||||
census("{ let params = c; } app.run(params); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a binding from the entry ends with its block"
|
||||
);
|
||||
assert_eq!(census("app.run(options.c); assert!(menu(c).is_some());"), [(2, "census")], "a field with the entry's name");
|
||||
assert_eq!(census("assert!(app.run::<Mode>(c).is_ok());"), [], "a call with a turbofish");
|
||||
assert_eq!(census("assert!(menu::<Mode>(c).is_some());"), [(2, "census")], "an entry-only call with a turbofish");
|
||||
assert_eq!(census("assert!(render(c, -offset).is_ok());"), [], "a negated variable is another input");
|
||||
assert_eq!(census("assert!(render(c, -2).is_ok());"), [(2, "census")], "a negative literal is not");
|
||||
assert_eq!(
|
||||
census("let _ = menu(c).is_some() || { app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a block on the right of || can be skipped"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let _ = menu(c).is_some() || { foo(); app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a semicolon keeps the enclosing ||"
|
||||
);
|
||||
assert_eq!(census("assert!(menu(c).is_some() && { foo(); app.run(c).is_ok() });"), [], "a semicolon keeps the enclosing &&");
|
||||
assert_eq!(
|
||||
census("let _ = (menu(c).is_some() || other(c).is_some()) && { app.run(c).is_ok() }; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a discarded conjunction can skip the block when its left side is false"
|
||||
);
|
||||
assert_eq!(census("assert!(menu(c).is_some()); if first || second {} app.run(c);"), [], "an || in a finished if does not skip the call");
|
||||
assert_eq!(
|
||||
census("let entry = c; let c = fallback(); let c = entry; assert!(menu(c).is_some()); app.run(c);"),
|
||||
[],
|
||||
"a name rebound from the entry is the entry again"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let entry = c; let c = fallback(); { let c = entry; } assert!(menu(entry).is_some()); app.run(c);"),
|
||||
[(2, "census")],
|
||||
"an inner entry binding does not end the outer fallback binding"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let entry = c; let c = fallback(); { let c = entry; app.run(c); } assert!(menu(entry).is_some());"),
|
||||
[],
|
||||
"the inner entry binding is live inside its block"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let Row { c: other } = fallback(); assert!(menu(c).is_some()); app.run(c);"),
|
||||
[],
|
||||
"a field label does not rebind the entry"
|
||||
);
|
||||
let receiver = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(k.parse(), k);\n }\n}\n";
|
||||
assert_eq!(census_in(receiver), [(2, "census")], "a round trip with the entry as receiver");
|
||||
let fixed = "#[test]\nfn t() {\n for k in KEYS {\n assert_eq!(registry.lookup(\"baseline\"), k);\n }\n}\n";
|
||||
assert_eq!(census_in(fixed), [], "a lookup of a fixed key");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_follows_conditions_and_scopes_around_the_call() {
|
||||
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
||||
let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
census("let _ = false && app.run(c).is_ok(); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a discarded conjunction can skip the call"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let ok = ready && app.run(c).is_ok(); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a bound conjunction can skip the call"
|
||||
);
|
||||
assert_eq!(census("debug_assert!(menu(c).is_some() && app.run(c).is_ok());"), [], "an asserted conjunction requires the call");
|
||||
assert_eq!(
|
||||
census("assert!(other(c).is_some() && app.run(c).is_ok() || menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an || after the conjunction lets the assertion pass without it"
|
||||
);
|
||||
assert_eq!(census("let _ = &&app.run(c); assert!(menu(c).is_some());"), [], "a double borrow does not short-circuit the call");
|
||||
assert_eq!(
|
||||
census("let run = || app.run(c); assert!(menu(c).is_some() || run().is_ok());"),
|
||||
[(2, "census")],
|
||||
"a closure invocation after || can be skipped"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = || { app.run(c) }; assert!(menu(c).is_some() || run().is_ok());"),
|
||||
[(2, "census")],
|
||||
"a block closure invocation after || can be skipped"
|
||||
);
|
||||
assert_eq!(census("let run = || app.run(c); assert!(run().is_ok());"), [], "a closure invocation required by the assertion runs");
|
||||
assert_eq!(
|
||||
census("let run = || app.run(c); other.run(); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a method of the same name does not call the closure"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = || app.run(c).and(run()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a recursive closure does not establish that its body runs"
|
||||
);
|
||||
assert_eq!(census("if false { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an if can skip the call");
|
||||
assert_eq!(census("if flag {} else { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "an else can skip the call");
|
||||
assert_eq!(
|
||||
census("match flag { true => { app.run(c); }, false => {} } assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a match arm can skip the call"
|
||||
);
|
||||
assert_eq!(census("while flag { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a while can skip the call");
|
||||
assert_eq!(census("let entry = c; { let c = entry; app.run(c); } assert!(menu(c).is_some());"), [], "a plain block runs");
|
||||
assert_eq!(census("for c in defaults() { app.run(c); } assert!(menu(c).is_some());"), [(2, "census")], "a nested loop shadows the entry");
|
||||
assert_eq!(census("for c in app.defaults(c) { app.run(c); } assert!(menu(c).is_some());"), [], "the loop source reads the outer entry");
|
||||
assert_eq!(
|
||||
census("for c in defaults() { let params = c; app.run(params); } assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a nested binding stays shadowed through aliases"
|
||||
);
|
||||
assert_eq!(census("for c in defaults() {} app.run(c); assert!(menu(c).is_some());"), [], "the nested loop's shadow ends with its body");
|
||||
assert_eq!(census("for x in 0..3 { app.run(c, x); } assert!(menu(c).is_some());"), [], "a nested loop body runs the call");
|
||||
assert_eq!(
|
||||
census("let run = |c| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a closure parameter shadows the entry"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = |other| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
||||
[],
|
||||
"another closure parameter keeps the entry"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = |c| { app.run(c); }; run(default()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a block closure parameter shadows the entry"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = |other| { app.run(c); }; run(default()); assert!(menu(c).is_some());"),
|
||||
[],
|
||||
"a called block closure keeps its capture"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_follows_block_initializers_argument_guards_and_parameterized_closures() {
|
||||
let loop_of = |body: &str| format!("#[test]\nfn t() {{\n let mut app = app();\n for c in COMMANDS {{\n {body}\n }}\n}}\n");
|
||||
let census = |body: &str| hits(&loop_of(body)).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
assert_eq!(census("let result = { verify(c) }; assert!(result.is_ok());"), [], "a block initializer runs its helper");
|
||||
assert_eq!(
|
||||
census("let _future = async { app.run(c); }; assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an unpolled async block does not run its body"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let result = if ready { verify(c) } else { Ok(()) }; assert!(result.is_ok());"),
|
||||
[(2, "census")],
|
||||
"a conditional initializer can skip its helper"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let _ = false && accept(0, app.run(c)); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an enclosing conjunction survives argument commas"
|
||||
);
|
||||
assert_eq!(census("let _ = accept(flag || other, app.run(c)); assert!(menu(c).is_some());"), [], "a sibling argument cannot skip the call");
|
||||
assert_eq!(
|
||||
census("let _ = ready || accept(0, app.run(c)); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an enclosing disjunction survives argument commas"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let _ = ready && accept((flag || other, 0), app.run(c)); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a nested sibling keeps the enclosing guard"
|
||||
);
|
||||
assert_eq!(
|
||||
census("assert!(menu(c).is_some() && accept(0, app.run(c)).is_some());"),
|
||||
[],
|
||||
"an asserted enclosing conjunction requires the argument"
|
||||
);
|
||||
assert_eq!(census("let _ = accept(0, { app.run(c) }); assert!(menu(c).is_some());"), [], "an argument block runs");
|
||||
assert_eq!(
|
||||
census("let _run = |_: ()| app.run(c); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an uncalled typed closure can skip its body"
|
||||
);
|
||||
assert_eq!(census("let run = |_: ()| app.run(c); assert!(run(()).is_ok());"), [], "an asserted typed closure invocation runs its body");
|
||||
assert_eq!(
|
||||
census("let run = move |x| app.run(c, x); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an uncalled move closure can skip its body"
|
||||
);
|
||||
assert_eq!(census("let run = move |x| app.run(c, x); assert!(run(0).is_ok());"), [], "an asserted move closure invocation runs its body");
|
||||
assert_eq!(
|
||||
census("let run = |_: ()| app.run(c); assert!(menu(c).is_some() || run(()).is_ok());"),
|
||||
[(2, "census")],
|
||||
"a guarded typed closure invocation can skip its body"
|
||||
);
|
||||
assert_eq!(
|
||||
census("let run = |c: Command| app.run(c); run(default()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a typed closure parameter shadows the entry"
|
||||
);
|
||||
assert_eq!(
|
||||
census("app.run(defaults::c); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a path segment named like the entry does not read it"
|
||||
);
|
||||
assert_eq!(census("app.run(c); assert!(menu(c).is_some());"), [], "a plain argument reads the entry");
|
||||
assert_eq!(census("let input = { prepare(); c }; assert!(render(input, offset).is_ok());"), [], "a block initializer's tail binds the entry");
|
||||
assert_eq!(census("assert!(app.run /* note */ (c).is_ok());"), [], "a comment before the arguments keeps the call");
|
||||
assert_eq!(
|
||||
census("let input = { prepare(); let _ = c; fixed }; assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"a block initializer binds its tail, not earlier statements"
|
||||
);
|
||||
assert_eq!(
|
||||
census("if let Some(input) = fallback() { prepare(); } menu(c); assert!(render(input, offset).is_ok()); assert!(menu(c).is_some());"),
|
||||
[(2, "census")],
|
||||
"an if let initializer ends at its block"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_leaves_out_loops_that_feed_the_entry_into_a_computation() {
|
||||
let census = |src: &str| hits(src).into_iter().filter(|h| h.1 == "census").collect::<Vec<_>>();
|
||||
let run = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app.session.execute(CMD, &json!({\"way\": k})).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(run), [], "a command run for each entry");
|
||||
let split = "#[test]\nfn t() {\n let mut app = app();\n for k in Kind::ALL {\n assert!(app\n .run(k)\n .is_ok());\n }\n}\n";
|
||||
assert_eq!(census(split), [], "a chain split over lines keeps its receiver");
|
||||
let rendered = "#[test]\nfn t() {\n let d = doc();\n for level in Level::ALL {\n let ps = export(&d, &Options { level, ..opts() });\n assert!(ps.contains(\"op\"));\n }\n}\n";
|
||||
assert_eq!(census(rendered), [], "a file written for each entry");
|
||||
let bound = "#[test]\nfn t() {\n for (_, kind) in KINDS {\n let params = json!({\"k\": kind});\n assert!(validate_params(SCHEMA, ¶ms).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(bound), [], "a value bound from the entry, checked against a schema");
|
||||
let lookup = "#[test]\nfn t() {\n let names = names();\n for c in COMMANDS {\n assert!(names.contains(c));\n }\n}\n";
|
||||
assert_eq!(census(lookup), [(2, "census")], "a lookup in other state is still a census");
|
||||
let alone = "#[test]\nfn t() {\n for c in COMMANDS {\n let m = menu(c);\n assert!(m.is_some());\n }\n}\n";
|
||||
assert_eq!(census(alone), [(2, "census")], "a call on the entry alone is a lookup");
|
||||
let constant =
|
||||
"#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c, 2, \"x\", r\"y\", b'z', br#\"w\"#).is_some());\n }\n}\n";
|
||||
assert_eq!(census(constant), [(2, "census")], "literal arguments are not other inputs");
|
||||
let message = "#[test]\nfn t() {\n for c in COMMANDS {\n assert!(menu(c).is_some(), \"{}\", app.describe(c));\n }\n}\n";
|
||||
assert_eq!(census(message), [(2, "census")], "a call in a failure message runs only after a failure");
|
||||
let closure = "#[test]\nfn t() {\n let tree = tree();\n for p in PLACES {\n let m = tree.iter().find(|t| t == p).map(|(_, items)| items.len());\n assert!(m.is_some());\n }\n}\n";
|
||||
assert_eq!(census(closure), [(2, "census")], "a closure passed along a lookup is not another input");
|
||||
let registry = "#[test]\nfn t() {\n let registry = registry();\n for k in Kind::ALL {\n assert_eq!(registry.lookup(k.id()), Some(k));\n }\n}\n";
|
||||
assert_eq!(census(registry), [(2, "census")], "a lookup on a table receiver is still a round trip");
|
||||
let parsed = "#[test]\nfn t(text: &str) {\n for u in Unit::ALL {\n assert!(u.parse(text).is_some());\n }\n}\n";
|
||||
assert_eq!(census(parsed), [], "parsing other input with each entry computes a result");
|
||||
let skipped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() || app.run(c).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(skipped), [(2, "census")], "a call after || may never run");
|
||||
let joined = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!(menu(c).is_some() && app.run(c).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(joined), [], "a call after && runs whenever the assertion passes");
|
||||
let grouped = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n assert!((menu(c).is_some() || other(c).is_some()) && app.run(c).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(grouped), [], "an || inside an earlier group does not skip the call");
|
||||
let deferred = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = || app.run(c);\n assert!(run().is_ok());\n }\n}\n";
|
||||
assert_eq!(census(deferred), [], "a zero-argument closure feeds the entry into a computation");
|
||||
let moved = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let mut run = move || app.run(c);\n assert!(run().is_ok());\n }\n}\n";
|
||||
assert_eq!(census(moved), [], "a move closure feeds the entry into a computation");
|
||||
let deferred_async = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let run = async || app.run(c);\n assert!(block_on(run()).is_ok());\n }\n}\n";
|
||||
assert_eq!(census(deferred_async), [], "an async closure feeds the entry into a computation");
|
||||
let sibling = "#[test]\nfn t() {\n let mut app = app();\n for c in COMMANDS {\n let result = (flag || other, app.run(c));\n assert!(result.1.is_ok());\n }\n}\n";
|
||||
assert_eq!(census(sibling), [], "an || in a sibling tuple element does not skip the call");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn census_keeps_diagnostics_for_fixed_range_arguments() {
|
||||
for range in ["1..4", "1..=4", "-4..-1", "1..(2 + 2)"] {
|
||||
let src =
|
||||
format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n");
|
||||
assert_eq!(only("census", &src), [(2, "census")], "{range}");
|
||||
}
|
||||
for range in ["1..limit", "1..=limit", "start..4", "1..(limit + 2)"] {
|
||||
let src =
|
||||
format!("#[test]\nfn t() {{\n for k in Kind::ALL {{\n assert_eq!(Kind::from_id(k.id(), {range}), Some(k));\n }}\n}}\n");
|
||||
assert_eq!(only("census", &src), [], "{range}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_literals_are_one_token() {
|
||||
for s in ["1", "0x1F", "2.5f32", "1_000", "1e-3", "7usize"] {
|
||||
assert!(numeric_literal(s), "{s}");
|
||||
}
|
||||
for s in ["1+offset", "1..limit", "1usize-offset", "1<<4"] {
|
||||
assert!(!numeric_literal(s), "{s}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suffix_check_reads_source_only_when_the_checked_file_is_read() {
|
||||
let name = "#[test]\nfn t() {\n assert!(generated_name().ends_with(\".rs\"));\n}\n";
|
||||
|
||||
Reference in New Issue
Block a user