mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 10:15:00 +01:00
craft-testkit: bound collection and use-path allocations and fix guard edge cases
- fonts::collection counts the table directories from each face's numTables before reading any record, then adds the tables one face at a time, so oversized input returns OutputTooLarge without keeping a directory for every face. - fonts::rename_family keeps the rest of each renamed full name, so a family name stored inside that suffix is refused with ConflictingNameStorage. - The guards read `use<...>` as a capturing bound, not a declaration, and keep use paths of at most eight segments, so a long prefix shared by many names is not copied into each. - std_instant finds the modules of a file that a #[path] attribute names next to that file, separately from a plain load of the same file. - predefined_quit reports <muda::PredefinedMenuItem>::quit. - wgsl_float_literals ends line comments and counts lines at every WGSL line break, and skips digits inside Unicode identifiers.
This commit is contained in:
1 parent
3baaac6869
commit
6701acfcf1
5 files changed
+303
-93
No files matched your search
@@ -6,7 +6,7 @@ Source-level platform regression guards and verification utilities for the Craft
|
||||
|
||||
`craft-testkit` provides lightweight, non-panicking source guards that prevent applications in the Craft ecosystem from repeating platform defects that were previously diagnosed and resolved in peer applications:
|
||||
|
||||
1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::` and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors.
|
||||
1. **`predefined_quit`**: Flags direct calls to `muda`'s `PredefinedMenuItem::quit` outside comments, strings and character literals, also with whitespace or a line break around `::`, in the qualified form `<muda::PredefinedMenuItem>::quit`, and through a `use muda::PredefinedMenuItem as ...` rename. On macOS, this predefined menu item routes directly to `NSApplication terminate:`, completely bypassing application dirty document checks and unsaved changes save prompts. Applications should instead wire Quit through `craft-quit` lifecycle interceptors.
|
||||
2. **`wgsl_float_literals` / `wgsl_float_literals_in`**: Scans WGSL shader sources and flags decimal and hexadecimal float literals whose value, rounded to `f64`, exceeds `f32::MAX` (such as `3.40282347e38` or `0x1p+500f`), or 65504, the largest finite `f16`, for a literal with an `h` suffix. A literal that exceeds the maximum by less than `f64` precision rounds to the maximum and is not reported. Integer literals are not checked. Some native compilers round such literals down, but browser WebGPU compilers reject them with pipeline compilation errors, forcing applications into CPU fallback rendering. `f32::MAX` can be written as the hex float `0x1.fffffep+127f`, which equals it, or as the decimal `3.4028234663852886e38`, which rounds to it.
|
||||
3. **`std_instant`**: Flags `std::time::Instant` outside comments and strings: the full path, `<m>::Instant` where a `use` binds `m` to `std::time`, and each `use` that imports `std::time::Instant` or `std::time::*`. Other crates' `Instant` (such as `web_time::Instant`) is not flagged, and neither is an item whose `cfg` attribute is false on `wasm32-unknown-unknown`. A `mod name;` inside such an item also skips the module's file (`name.rs` or `name/mod.rs`, or the file a `#[path]` attribute names) and the files of the modules declared in it, when they are among the files passed in and no declaration outside such items also reaches them. On that target, `std::time::Instant::now()` panics at runtime with `"time not implemented on this platform"`. Code targeting the web must use `web_time::Instant`.
|
||||
4. **`rust_sources`**: Recursively discovers a crate's `.rs` source files while excluding integration tests (`tests/`), test modules (`tests.rs`, `tests_*.rs`, `*_tests.rs`, `*_test.rs`), build artifacts (`target/`, any folder holding a `CACHEDIR.TAG` file that starts with the line `Signature: 8a477f597d28d172789f06886806bc55`, `.git/` and other folders whose name starts with `.`) and symbolic links, which it does not follow. A file over 8 MiB, more than 256 MiB in all or more than 50,000 files returns an error; `rust_sources_with_limits` takes other limits. It is not built for `wasm32`.
|
||||
|
||||
+38
-21
@@ -143,24 +143,26 @@ pub fn rename_family(bytes: &[u8], from: &str, to: &str) -> Result<Vec<u8>, Font
|
||||
/// [`FontError::EmptyCollection`] for no faces, [`FontError::UnsupportedFace`] for a face that is
|
||||
/// itself a collection, [`FontError::MalformedFont`] for a face shorter than its table directory or
|
||||
/// with a table out of range, and [`FontError::OutputTooLarge`] when the collection would pass the
|
||||
/// 4 GiB that its 32-bit offsets reach or cannot be allocated.
|
||||
/// 4 GiB that its 32-bit offsets reach or cannot be allocated. The headers and table directories are
|
||||
/// counted from each face's `numTables` before any table record is read, so faces whose directories
|
||||
/// alone pass 4 GiB return [`FontError::OutputTooLarge`] even when a table record is out of range.
|
||||
pub fn collection(faces: &[&[u8]]) -> Result<Vec<u8>, FontError> {
|
||||
if faces.is_empty() {
|
||||
return Err(FontError::EmptyCollection);
|
||||
}
|
||||
let directories = faces.iter().map(|face| directory(face)).collect::<Result<Vec<_>, _>>()?;
|
||||
let count = u32::try_from(faces.len()).map_err(|_| FontError::OutputTooLarge)?;
|
||||
let size = collection_size(&directories)?;
|
||||
let size = collection_size(faces)?;
|
||||
let mut out = Vec::new();
|
||||
out.try_reserve_exact(size).map_err(|_| FontError::OutputTooLarge)?;
|
||||
out.extend_from_slice(b"ttcf");
|
||||
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
|
||||
out.extend_from_slice(&count.to_be_bytes());
|
||||
out.resize(SFNT_HEADER + faces.len() * 4, 0);
|
||||
for (index, (face, tables)) in faces.iter().zip(&directories).enumerate() {
|
||||
for (index, face) in faces.iter().enumerate() {
|
||||
let tables = directory(face)?;
|
||||
let directory = offset32(out.len())?;
|
||||
put_u32(&mut out, SFNT_HEADER + index * 4, directory)?;
|
||||
write_face(&mut out, face, tables)?;
|
||||
write_face(&mut out, face, &tables)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -176,11 +178,7 @@ struct Table {
|
||||
|
||||
/// Reads a standalone face's table directory, checking that every record and table lies in `face`.
|
||||
fn directory(face: &[u8]) -> Result<Vec<Table>, FontError> {
|
||||
let version = bytes_at(face, 0, 4)?;
|
||||
if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) {
|
||||
return Err(FontError::UnsupportedFace);
|
||||
}
|
||||
let count = usize::from(u16_at(face, 4)?);
|
||||
let count = table_count(face)?;
|
||||
bytes_at(face, 0, SFNT_HEADER + count * TABLE_RECORD)?;
|
||||
let mut tables = Vec::with_capacity(count);
|
||||
for index in 0..count {
|
||||
@@ -194,6 +192,15 @@ fn directory(face: &[u8]) -> Result<Vec<Table>, FontError> {
|
||||
Ok(tables)
|
||||
}
|
||||
|
||||
/// Reads a standalone face's sfnt version and `numTables`, without reading the table records.
|
||||
fn table_count(face: &[u8]) -> Result<usize, FontError> {
|
||||
let version = bytes_at(face, 0, 4)?;
|
||||
if !matches!(version, [0, 1, 0, 0] | [b'O', b'T', b'T', b'O'] | [b't', b'r', b'u', b'e']) {
|
||||
return Err(FontError::UnsupportedFace);
|
||||
}
|
||||
Ok(usize::from(u16_at(face, 4)?))
|
||||
}
|
||||
|
||||
/// Whether `table` shares bytes with the table directory or with another table of the face.
|
||||
fn shares_bytes(tables: &[Table], table: &Table) -> bool {
|
||||
let end = table.offset + table.length;
|
||||
@@ -203,18 +210,24 @@ fn shares_bytes(tables: &[Table], table: &Table) -> bool {
|
||||
}
|
||||
|
||||
/// Bytes a collection of these faces takes, refused past what a 32-bit offset reaches.
|
||||
fn collection_size(directories: &[Vec<Table>]) -> Result<usize, FontError> {
|
||||
let mut size = u64::try_from(SFNT_HEADER + directories.len() * 4).map_err(|_| FontError::OutputTooLarge)?;
|
||||
for tables in directories {
|
||||
let directory = SFNT_HEADER + tables.len() * TABLE_RECORD;
|
||||
size = size.checked_add(u64::try_from(directory).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?;
|
||||
for table in tables {
|
||||
let padded = u64::try_from(table.length).map_err(|_| FontError::OutputTooLarge)?.div_ceil(4) * 4;
|
||||
size = size.checked_add(padded).ok_or(FontError::OutputTooLarge)?;
|
||||
}
|
||||
///
|
||||
/// The headers and table directories are added up first, from each face's `numTables` alone, so that
|
||||
/// input whose directories already pass the limit is refused before any table record is read. The
|
||||
/// tables are then added one face at a time, and no face's directory is kept.
|
||||
fn collection_size(faces: &[&[u8]]) -> Result<usize, FontError> {
|
||||
let add = |size: u64, bytes: usize| -> Result<u64, FontError> {
|
||||
let size = size.checked_add(u64::try_from(bytes).map_err(|_| FontError::OutputTooLarge)?).ok_or(FontError::OutputTooLarge)?;
|
||||
if size > u64::from(u32::MAX) { Err(FontError::OutputTooLarge) } else { Ok(size) }
|
||||
};
|
||||
let mut size = add(0, SFNT_HEADER)?;
|
||||
size = add(size, faces.len().checked_mul(4).ok_or(FontError::OutputTooLarge)?)?;
|
||||
for face in faces {
|
||||
size = add(size, SFNT_HEADER + table_count(face)? * TABLE_RECORD)?;
|
||||
}
|
||||
if size > u64::from(u32::MAX) {
|
||||
return Err(FontError::OutputTooLarge);
|
||||
for face in faces {
|
||||
for table in directory(face)? {
|
||||
size = add(size, table.length.div_ceil(4).checked_mul(4).ok_or(FontError::OutputTooLarge)?)?;
|
||||
}
|
||||
}
|
||||
usize::try_from(size).map_err(|_| FontError::OutputTooLarge)
|
||||
}
|
||||
@@ -342,6 +355,10 @@ fn plan_edits(face: &[u8], strings: &NameStrings, from: &str, to: &str) -> Resul
|
||||
None => {
|
||||
let edit = renamed(string, face, from, to)?;
|
||||
let edited = edit.is_some();
|
||||
if let Some(edit) = &edit {
|
||||
// The rest of a full name, after the family name, must keep its bytes.
|
||||
kept.push(edit.range.end..string.range.end);
|
||||
}
|
||||
edits.extend(edit);
|
||||
read.insert(key, edited);
|
||||
edited
|
||||
|
||||
+162
-71
@@ -114,6 +114,11 @@ impl AsFileSource for &(&str, String) {
|
||||
/// read as far as this depth, so hostile nesting cannot exhaust the stack.
|
||||
const MAX_NESTING: usize = 64;
|
||||
|
||||
/// The most segments of a `use` path that [`use_leaves`] keeps. The guards compare paths of at most
|
||||
/// three segments, so a leaf with a longer path is left out, and a long prefix shared by many leaves
|
||||
/// is not copied into each of them.
|
||||
const MAX_USE_PATH: usize = 8;
|
||||
|
||||
/// The kind of a Rust token. Comments are dropped; string, character and number literals keep no text
|
||||
/// except string contents, which `cfg` predicates compare.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -344,6 +349,29 @@ fn then_path(toks: &[Token], i: usize, name: impl Fn(&str) -> bool) -> bool {
|
||||
&& toks.get(i + 2).is_some_and(|t| matches!(&t.kind, Kind::Ident(s) if name(s)))
|
||||
}
|
||||
|
||||
/// Whether the path that ends at `toks[i]` starts right after the `<` of a qualified path, as in
|
||||
/// `<muda::PredefinedMenuItem>::quit`, rather than after the `<` of generic arguments (`Vec<T>::new`,
|
||||
/// `f::<T>`).
|
||||
fn opens_qualified_path(toks: &[Token], i: usize) -> bool {
|
||||
let mut start = i;
|
||||
while start >= 2 && toks[start - 1].is_punct(':') && toks[start - 2].is_punct(':') {
|
||||
if start >= 3 && matches!(toks[start - 3].kind, Kind::Ident(_)) {
|
||||
start -= 3;
|
||||
} else {
|
||||
start -= 2;
|
||||
break;
|
||||
}
|
||||
}
|
||||
start >= 1
|
||||
&& toks[start - 1].is_punct('<')
|
||||
&& match start.checked_sub(2).map(|j| &toks[j].kind) {
|
||||
None => true,
|
||||
Some(Kind::Ident(s)) => KEYWORDS.contains(&s.as_str()),
|
||||
Some(Kind::Punct(c)) => !matches!(*c, ':' | '>'),
|
||||
Some(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One name a `use` declaration brings into scope.
|
||||
#[derive(Debug)]
|
||||
struct UseLeaf {
|
||||
@@ -361,7 +389,8 @@ fn use_leaves(toks: &[Token]) -> Vec<UseLeaf> {
|
||||
let mut leaves = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < toks.len() {
|
||||
if toks[i].is_ident("use") && !continues_a_path(toks, i) {
|
||||
// `use<...>` is a precise capturing bound on `impl Trait`, not a `use` declaration.
|
||||
if toks[i].is_ident("use") && !continues_a_path(toks, i) && !toks.get(i + 1).is_some_and(|t| t.is_punct('<')) {
|
||||
let start = i;
|
||||
let end = (i + 1..toks.len()).find(|&j| toks[j].is_punct(';')).unwrap_or(toks.len());
|
||||
let mut pos = i + 1;
|
||||
@@ -389,24 +418,30 @@ fn parse_use_tree(toks: &[Token], pos: &mut usize, prefix: &mut Vec<String>, sta
|
||||
*pos += 2;
|
||||
continue;
|
||||
}
|
||||
let mut path = prefix.clone();
|
||||
if name != "self" {
|
||||
path.push(name.clone());
|
||||
}
|
||||
let mut bound = path.last().cloned();
|
||||
if toks.get(*pos).is_some_and(|t| t.is_ident("as"))
|
||||
&& let Some(Kind::Ident(alias)) = toks.get(*pos + 1).map(|t| &t.kind)
|
||||
{
|
||||
bound = Some(alias.clone());
|
||||
*pos += 2;
|
||||
}
|
||||
if let Some(bound) = bound.filter(|b| b != "_") {
|
||||
out.push(UseLeaf { path, name: Some(bound), line: tok.line, start });
|
||||
let length = prefix.len() + usize::from(name != "self");
|
||||
let alias = match (toks.get(*pos), toks.get(*pos + 1).map(|t| &t.kind)) {
|
||||
(Some(t), Some(Kind::Ident(alias))) if t.is_ident("as") => {
|
||||
*pos += 2;
|
||||
Some(alias)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if length <= MAX_USE_PATH {
|
||||
let mut path = prefix.clone();
|
||||
if name != "self" {
|
||||
path.push(name.clone());
|
||||
}
|
||||
let bound = alias.cloned().or_else(|| path.last().cloned());
|
||||
if let Some(bound) = bound.filter(|b| b != "_") {
|
||||
out.push(UseLeaf { path, name: Some(bound), line: tok.line, start });
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
Kind::Punct('*') => {
|
||||
out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start });
|
||||
if prefix.len() <= MAX_USE_PATH {
|
||||
out.push(UseLeaf { path: prefix.clone(), name: None, line: tok.line, start });
|
||||
}
|
||||
*pos += 1;
|
||||
break;
|
||||
}
|
||||
@@ -797,19 +832,20 @@ fn join_path(parent: &str, child: &str) -> String {
|
||||
|
||||
/// The paths, normalized, where the module `decl` declared in the file at `parent` (normalized) can be.
|
||||
///
|
||||
/// The modules of `lib.rs`, `main.rs` and `mod.rs` are in the file's folder, and those of any other file
|
||||
/// are in the folder named after its stem. Each inline module around the declaration adds a folder named
|
||||
/// The modules of `lib.rs`, `main.rs` and `mod.rs`, and with `path_loaded`, of a file that a `#[path]`
|
||||
/// attribute names, are in the file's folder, and those of any other file are in the folder named after
|
||||
/// its stem. Each inline module around the declaration adds a folder named
|
||||
/// after it, or with a `path` attribute, moves to that path relative to the current folder (without the
|
||||
/// stem folder). The module is then `<name>.rs` or `<name>/mod.rs` there, or with a `path` attribute, that
|
||||
/// path relative to the current folder, again without the stem folder.
|
||||
fn module_files(parent: &str, decl: &ModDecl) -> Vec<String> {
|
||||
fn module_files(parent: &str, decl: &ModDecl, path_loaded: bool) -> Vec<String> {
|
||||
let (dir, file) = match parent.rsplit_once('/') {
|
||||
Some(("", file)) => ("/", file),
|
||||
Some(split) => split,
|
||||
None => ("", parent),
|
||||
};
|
||||
let mut folder = dir.to_string();
|
||||
let mut stem = (!matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file));
|
||||
let mut stem = (!path_loaded && !matches!(file, "lib.rs" | "main.rs" | "mod.rs")).then(|| file.strip_suffix(".rs").unwrap_or(file));
|
||||
for inline in &decl.inline {
|
||||
if let Some(attr) = &inline.path_attribute {
|
||||
folder = join_path(&folder, attr);
|
||||
@@ -839,67 +875,88 @@ fn native_only_files(paths: &[String], decls: &[Vec<ModDecl>]) -> Vec<bool> {
|
||||
for (i, path) in paths.iter().enumerate() {
|
||||
index.entry(path.as_str()).or_default().push(i);
|
||||
}
|
||||
// The files each declaration names, in the order of `decls`.
|
||||
let children: Vec<Vec<(bool, Vec<usize>)>> = decls
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(parent, file_decls)| {
|
||||
file_decls
|
||||
.iter()
|
||||
.map(|decl| {
|
||||
let files =
|
||||
module_files(&paths[parent], decl).iter().flat_map(|c| index.get(c.as_str()).into_iter().flatten().copied()).collect();
|
||||
(decl.native, files)
|
||||
})
|
||||
.collect()
|
||||
// rustc reads a file that a `#[path]` attribute names as if it were a `mod.rs`, so the modules it
|
||||
// declares are in its own folder rather than its stem folder. Each file is therefore two nodes: node
|
||||
// `2 * file` for the file loaded by a plain `mod name;` (or as a crate root), and node `2 * file + 1`
|
||||
// for the file loaded through a `#[path]` attribute. Each node lists the nodes its declarations name,
|
||||
// with whether the declaration is in a native-only item.
|
||||
let edges: Vec<Vec<(bool, usize)>> = (0..paths.len() * 2)
|
||||
.map(|node| {
|
||||
let (parent, path_loaded) = (node / 2, node % 2 == 1);
|
||||
let mut targets = Vec::new();
|
||||
for decl in &decls[parent] {
|
||||
let by_path = usize::from(decl.module.path_attribute.is_some());
|
||||
for candidate in module_files(&paths[parent], decl, path_loaded) {
|
||||
for &j in index.get(candidate.as_str()).into_iter().flatten() {
|
||||
targets.push((decl.native, 2 * j + by_path));
|
||||
}
|
||||
}
|
||||
}
|
||||
targets
|
||||
})
|
||||
.collect();
|
||||
|
||||
// The nodes that are loaded: a file that no loaded node names is a crate root, loaded plainly, and a
|
||||
// node is loaded when a loaded node names it. Every file starts out loaded plainly, and the set is
|
||||
// narrowed until it stops changing, or after `MAX_MODULE_ROUNDS` rounds.
|
||||
let mut loaded: Vec<bool> = (0..paths.len() * 2).map(|node| node % 2 == 0).collect();
|
||||
let mut named = vec![false; paths.len()];
|
||||
for _ in 0..MAX_MODULE_ROUNDS {
|
||||
let mut reached = vec![false; paths.len() * 2];
|
||||
for (node, targets) in edges.iter().enumerate() {
|
||||
if loaded[node] {
|
||||
for &(_, target) in targets {
|
||||
reached[target] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
named = (0..paths.len()).map(|j| reached[2 * j] || reached[2 * j + 1]).collect();
|
||||
let next: Vec<bool> = (0..paths.len() * 2).map(|node| reached[node] || (node % 2 == 0 && !named[node / 2])).collect();
|
||||
if next == loaded {
|
||||
break;
|
||||
}
|
||||
loaded = next;
|
||||
}
|
||||
|
||||
// Files the web build compiles: crate roots, and every file a declaration outside a native-only item
|
||||
// of such a file names.
|
||||
let mut named = vec![false; paths.len()];
|
||||
for (_, files) in children.iter().flatten() {
|
||||
for &j in files {
|
||||
named[j] = true;
|
||||
}
|
||||
}
|
||||
let mut web = vec![false; paths.len()];
|
||||
let mut queue: Vec<usize> = (0..paths.len()).filter(|&j| !named[j]).collect();
|
||||
for &j in &queue {
|
||||
web[j] = true;
|
||||
let mut web = vec![false; paths.len() * 2];
|
||||
let mut queue: Vec<usize> = (0..paths.len()).filter(|&j| !named[j]).map(|j| 2 * j).collect();
|
||||
for &node in &queue {
|
||||
web[node] = true;
|
||||
}
|
||||
while let Some(parent) = queue.pop() {
|
||||
for (_, files) in children[parent].iter().filter(|(is_native, _)| !is_native) {
|
||||
for &j in files {
|
||||
if !web[j] {
|
||||
web[j] = true;
|
||||
queue.push(j);
|
||||
}
|
||||
for &(_, target) in edges[parent].iter().filter(|(is_native, _)| !is_native) {
|
||||
if !web[target] {
|
||||
web[target] = true;
|
||||
queue.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Files a native-only declaration names, and their descendants.
|
||||
let mut native = vec![false; paths.len()];
|
||||
let mut mark = |files: &[usize], queue: &mut Vec<usize>| {
|
||||
for &j in files {
|
||||
if !native[j] {
|
||||
native[j] = true;
|
||||
queue.push(j);
|
||||
}
|
||||
// Files a native-only declaration of a loaded node names, and their descendants.
|
||||
let mut native = vec![false; paths.len() * 2];
|
||||
let starts = edges.iter().enumerate().filter(|&(node, _)| loaded[node]).flat_map(|(_, targets)| targets.iter());
|
||||
for &(_, target) in starts.filter(|(is_native, _)| *is_native) {
|
||||
if !native[target] {
|
||||
native[target] = true;
|
||||
queue.push(target);
|
||||
}
|
||||
};
|
||||
for (_, files) in children.iter().flatten().filter(|(is_native, _)| *is_native) {
|
||||
mark(files, &mut queue);
|
||||
}
|
||||
while let Some(parent) = queue.pop() {
|
||||
for (_, files) in &children[parent] {
|
||||
mark(files, &mut queue);
|
||||
for &(_, target) in &edges[parent] {
|
||||
if !native[target] {
|
||||
native[target] = true;
|
||||
queue.push(target);
|
||||
}
|
||||
}
|
||||
}
|
||||
native.iter().zip(&web).map(|(&n, &w)| n && !w).collect()
|
||||
(0..paths.len()).map(|j| (native[2 * j] || native[2 * j + 1]) && !web[2 * j] && !web[2 * j + 1]).collect()
|
||||
}
|
||||
|
||||
/// The most rounds [`native_only_files`] spends narrowing the set of loaded files.
|
||||
const MAX_MODULE_ROUNDS: usize = 16;
|
||||
|
||||
/// Add one finding for each line in `lines`, in line order, with the trimmed text of that line.
|
||||
fn report(findings: &mut Vec<Finding>, path: &str, content: &str, lines: &BTreeSet<usize>) {
|
||||
if lines.is_empty() {
|
||||
@@ -919,7 +976,8 @@ fn report(findings: &mut Vec<Finding>, path: &str, content: &str, lines: &BTreeS
|
||||
/// Applications should route Quit through custom menu items or interceptors connected to `craft-quit`.
|
||||
///
|
||||
/// The guard reads Rust tokens, so comments, strings and character literals are ignored, and whitespace
|
||||
/// or line breaks around `::` do not hide a call. It also follows a `use` that renames muda's type
|
||||
/// or line breaks around `::` do not hide a call. A qualified path such as `<muda::PredefinedMenuItem>::quit`
|
||||
/// is reported too. It also follows a `use` that renames muda's type
|
||||
/// (`use muda::PredefinedMenuItem as Item;` then `Item::quit`); a rename of another crate's
|
||||
/// `PredefinedMenuItem` is not followed. Each finding names the line where the
|
||||
/// type's name starts, once per line, in line order.
|
||||
@@ -943,7 +1001,10 @@ where
|
||||
for (i, tok) in toks.iter().enumerate() {
|
||||
let Kind::Ident(name) = &tok.kind else { continue };
|
||||
let named = name == "PredefinedMenuItem" || (aliases.contains(name) && !continues_a_path(&toks, i));
|
||||
if named && then_path(&toks, i + 1, |s| s == "quit" || s == "Quit") {
|
||||
let quit = |at: usize| then_path(&toks, at, |s| s == "quit" || s == "Quit");
|
||||
// `<muda::PredefinedMenuItem>::quit`, a qualified path to the same function.
|
||||
let qualified = || toks.get(i + 1).is_some_and(|t| t.is_punct('>')) && quit(i + 2) && opens_qualified_path(&toks, i);
|
||||
if named && (quit(i + 1) || qualified()) {
|
||||
lines.insert(tok.line);
|
||||
}
|
||||
}
|
||||
@@ -974,8 +1035,8 @@ where
|
||||
/// * **Module files**: a `mod name;` inside such an item makes the module's file native-only, and so are the
|
||||
/// files of the modules declared in it, when they are among `files`, unless a chain of declarations outside
|
||||
/// such items also reaches the file from a crate root (a file that no declaration names). The module's file is `name.rs` or
|
||||
/// `name/mod.rs` next to `lib.rs`, `main.rs` or `mod.rs`, and in the folder named after any other file's
|
||||
/// stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration
|
||||
/// `name/mod.rs` next to `lib.rs`, `main.rs`, `mod.rs` or a file that a `#[path]` attribute names, and in
|
||||
/// the folder named after any other file's stem, below the folders of enclosing inline modules; a `#[path = "..."]` attribute on the declaration
|
||||
/// or on an enclosing inline module is followed. Paths are compared as text with `\` read as `/`, so the files must be named the same way
|
||||
/// (for example all from one `rust_sources` call), and a crate root other than `lib.rs` or `main.rs`
|
||||
/// (such as `src/bin/tool.rs`) is read as an ordinary module file. A declaration inside more than 64 inline
|
||||
@@ -1050,7 +1111,11 @@ where
|
||||
findings
|
||||
}
|
||||
|
||||
/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, keeping line breaks.
|
||||
/// Replace WGSL comments (`//` and nested `/* ... */`) with spaces, and write each WGSL line break as
|
||||
/// `\n`: line feed, vertical tab, form feed, carriage return, carriage return and line feed as one
|
||||
/// break, next line (U+0085), line separator (U+2028) and paragraph separator (U+2029)
|
||||
/// (<https://www.w3.org/TR/WGSL/#line-break>). A line comment ends at any of them, and `str::lines`
|
||||
/// then counts lines the way WGSL does.
|
||||
fn mask_wgsl_comments(code: &str) -> String {
|
||||
let chars: Vec<char> = code.chars().collect();
|
||||
let len = chars.len();
|
||||
@@ -1061,10 +1126,15 @@ fn mask_wgsl_comments(code: &str) -> String {
|
||||
while i < len {
|
||||
let c = chars[i];
|
||||
let next = chars.get(i + 1).copied();
|
||||
if c == '\n' {
|
||||
let line_break = match c {
|
||||
'\r' if next == Some('\n') => 2,
|
||||
'\n' | '\u{000B}' | '\u{000C}' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}' => 1,
|
||||
_ => 0,
|
||||
};
|
||||
if line_break > 0 {
|
||||
in_line = false;
|
||||
out.push('\n');
|
||||
i += 1;
|
||||
i += line_break;
|
||||
} else if in_line {
|
||||
out.push(' ');
|
||||
i += 1;
|
||||
@@ -1183,7 +1253,9 @@ fn scan_wgsl_hex(code: &[u8], start: usize) -> (usize, usize, bool) {
|
||||
/// * **Which literals**: decimal floats (with a `.`, an exponent or an `f`/`h` suffix) and hexadecimal floats
|
||||
/// (`0x` with a `.` or a `p` exponent). Integer literals (`123`, `123u`, `0xFFi`, `0x1f`) are not floats and
|
||||
/// are not reported. A `-` in front is not part of the literal, so `-1e39` is reported as `1e39`.
|
||||
/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning.
|
||||
/// * **Comments**: Comments (`//` and nested `/* ... */`) are masked out prior to scanning. A `//` comment
|
||||
/// ends at any WGSL line break, a lone carriage return included, and finding lines count every one of them.
|
||||
/// * **Identifiers**: digits inside an identifier, `π1e39` included, are not a literal.
|
||||
pub fn wgsl_float_literals(wgsl: &str) -> Vec<Finding> {
|
||||
wgsl_float_literals_in([("", wgsl)])
|
||||
}
|
||||
@@ -1205,7 +1277,14 @@ where
|
||||
let mut i = 0;
|
||||
while i < code.len() {
|
||||
let digit_or_dot = code[i].is_ascii_digit() || (code[i] == b'.' && code.get(i + 1).is_some_and(u8::is_ascii_digit));
|
||||
let word_before = i > 0 && (code[i - 1].is_ascii_alphanumeric() || code[i - 1] == b'_' || code[i - 1] == b'.');
|
||||
// Outside comments, a character that is not ASCII and not blankspace (U+200E, U+200F) is part of an
|
||||
// identifier, as in `π1e39`.
|
||||
let word_before = digit_or_dot
|
||||
&& i > 0
|
||||
&& (code[i - 1].is_ascii_alphanumeric()
|
||||
|| code[i - 1] == b'_'
|
||||
|| code[i - 1] == b'.'
|
||||
|| (!code[i - 1].is_ascii() && !line[..i].ends_with(['\u{200E}', '\u{200F}'])));
|
||||
if !digit_or_dot || word_before {
|
||||
i += 1;
|
||||
continue;
|
||||
@@ -1392,3 +1471,15 @@ pub fn rust_sources_with_limits(dir: impl AsRef<Path>, limits: SourceLimits) ->
|
||||
files.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
Ok(files)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MAX_USE_PATH, lex_rust, use_leaves};
|
||||
|
||||
#[test]
|
||||
fn use_leaves_keep_no_path_longer_than_the_limit() {
|
||||
let source = format!("use {}{{x, y::z, *}};\nuse std::time::{{Instant, self as t}};\n", "a::".repeat(MAX_USE_PATH));
|
||||
let paths: Vec<Vec<String>> = use_leaves(&lex_rust(&source)).into_iter().map(|leaf| leaf.path).collect();
|
||||
assert_eq!(paths, vec![vec!["a"; MAX_USE_PATH], vec!["std", "time", "Instant"], vec!["std", "time"]]);
|
||||
}
|
||||
}
|
||||
@@ -298,6 +298,16 @@ fn rename_keeps_a_style_sharing_the_full_name_suffix() {
|
||||
assert_eq!(strings(&out), vec![win(1, TO), win(2, "Bold"), win(4, "Sysfont Sans3 Bold")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_a_family_name_in_the_full_name_suffix() {
|
||||
// The full name "A A" is stored once, and the family name (ID 1) is its last "A". Renaming the
|
||||
// family would change the full name's suffix " A".
|
||||
let records =
|
||||
[Rec { platform: 3, encoding: 1, name_id: 4, offset: 0, length: 6 }, Rec { platform: 3, encoding: 1, name_id: 1, offset: 4, length: 2 }];
|
||||
let font = face(&[(b"head", head()), (b"name", name_table(0, &records, &[], &utf16("A A")))]);
|
||||
assert_eq!(rename_family(&font, "A", "B"), Err(FontError::ConflictingNameStorage));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_updates_name_checksum() {
|
||||
let font = family_face(&[win(1, FROM), win(2, "Regular")]);
|
||||
@@ -580,3 +590,27 @@ fn collection_rejects_offset_overflow() {
|
||||
let faces = vec![&big[..]; 4096];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_rejects_directories_past_the_offset_limit() {
|
||||
// 65,536 references to one face with 4,096 empty tables: the table directories alone take more
|
||||
// than 4 GiB. The function refuses without keeping a directory for every face.
|
||||
let tables: Vec<(&[u8; 4], Vec<u8>)> = (0..4096).map(|_| (b"zzzz", Vec::new())).collect();
|
||||
let many = face(&tables);
|
||||
let faces = vec![&many[..]; 65536];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collection_counts_directories_before_reading_records() {
|
||||
// The same number of directories, each with every table record out of range. The size limit is
|
||||
// found from the faces' table counts before any table record is read.
|
||||
let mut directory = vec![0u8; 12 + 16 * 4096];
|
||||
set32(&mut directory, 0, 0x0001_0000);
|
||||
set16(&mut directory, 4, 4096);
|
||||
for index in 0..4096 {
|
||||
set32(&mut directory, 12 + 16 * index + 8, u32::MAX);
|
||||
}
|
||||
let faces = vec![&directory[..]; 65536];
|
||||
assert_eq!(collection(&faces), Err(FontError::OutputTooLarge));
|
||||
}
|
||||
@@ -412,6 +412,21 @@ fn menu() {
|
||||
assert!(predefined_quit([("src/menu.rs", other_crate)]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predefined_quit_reports_a_qualified_path() {
|
||||
let source = r#"
|
||||
use muda::PredefinedMenuItem as Item;
|
||||
fn menu() {
|
||||
let a = <muda::PredefinedMenuItem>::quit(None);
|
||||
let b = < PredefinedMenuItem >::quit(None);
|
||||
let c = <Item>::quit(None);
|
||||
let d = Vec::<PredefinedMenuItem>::quit(None);
|
||||
let e = Wrapper<PredefinedMenuItem>::quit(None);
|
||||
}
|
||||
"#;
|
||||
assert_eq!(lines(&predefined_quit([("src/menu.rs", source)])), vec![4, 5, 6]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_ignores_an_alias_that_only_a_native_cfg_imports() {
|
||||
let source = r#"
|
||||
@@ -566,6 +581,12 @@ use std::time::{
|
||||
assert_eq!(findings[0].text, "Instant");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_reads_a_use_after_a_precise_capturing_bound() {
|
||||
let source = "fn clock() -> impl Fn() + use<> {\n use std::{time::Instant};\n || { let _ = Instant::now(); }\n}\n";
|
||||
assert_eq!(lines(&std_instant([("src/clock.rs", source)])), vec![2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_does_not_count_brace_character_literals_as_braces() {
|
||||
let source = r#"
|
||||
@@ -601,6 +622,15 @@ fn deeply_nested_use_groups_and_cfg_predicates_do_not_exhaust_the_stack() {
|
||||
assert_eq!(lines(&std_instant([("src/shallow.rs", shallow)])), vec![1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_use_path_shared_by_many_names_is_read_without_copying_it_to_each() {
|
||||
// 10,000 path segments shared by 10,000 names, followed by a `use` the guard reports.
|
||||
let names: Vec<String> = (0..10_000).map(|n| format!("x{n}")).collect();
|
||||
let source = format!("use {}{{{}}};\nuse std::time::Instant;\n", "a::".repeat(10_000), names.join(", "));
|
||||
assert_eq!(lines(&std_instant([("src/wide.rs", source.as_str())])), vec![2]);
|
||||
assert!(predefined_quit([("src/wide.rs", source.as_str())]).is_empty());
|
||||
}
|
||||
|
||||
fn finding_paths(findings: &[Finding]) -> Vec<&str> {
|
||||
findings.iter().map(|f| f.path.as_str()).collect()
|
||||
}
|
||||
@@ -733,6 +763,28 @@ mod platform {
|
||||
assert_eq!(finding_paths(&std_instant(files)), vec!["src/a/native.rs", "src/a/native/clock.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_finds_the_modules_of_a_path_attribute_file_next_to_it() {
|
||||
let lib = r#"
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[path = "platform/native.rs"]
|
||||
mod native;
|
||||
"#;
|
||||
let clock = "use std::time::Instant;\n";
|
||||
let files = [("src/lib.rs", lib), ("src/platform/native.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/web.rs", clock)];
|
||||
assert_eq!(finding_paths(&std_instant(files)), vec!["src/web.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_resolves_a_file_loaded_both_plainly_and_by_path_attribute_once_for_each() {
|
||||
// `platform.rs` is a web module, and a native-only `#[path]` declaration loads it again. Its
|
||||
// `mod clock;` is `src/platform/clock.rs` for the first and `src/clock.rs` for the second.
|
||||
let lib = "mod platform;\n#[cfg(unix)]\n#[path = \"platform.rs\"]\nmod native;\n";
|
||||
let clock = "use std::time::Instant;\n";
|
||||
let files = [("src/lib.rs", lib), ("src/platform.rs", "mod clock;\n"), ("src/platform/clock.rs", clock), ("src/clock.rs", clock)];
|
||||
assert_eq!(finding_paths(&std_instant(files)), vec!["src/platform/clock.rs"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn std_instant_checks_module_files_declared_deeper_than_its_nesting_limit() {
|
||||
let lib = format!("{}#[cfg(unix)]\nmod deep;\n{}", "mod m {\n".repeat(70), "}\n".repeat(70));
|
||||
@@ -807,6 +859,22 @@ fn wgsl_half_floats_use_the_f16_range() {
|
||||
assert_eq!(findings[0].text, "70000.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wgsl_line_comments_end_and_lines_count_at_every_line_break() {
|
||||
let shader = "// note\rconst A: f32 = 4e38;\r\nconst B: f32 = 5e38;\n// x\u{2028}const C: f32 = 6e38;\u{2029}const D: f32 = 7e38;\u{000B}// y\u{0085}const E: f32 = 8e38;\u{000C}const F: f32 = 9e38;";
|
||||
let findings = wgsl_float_literals(shader);
|
||||
assert_eq!(lines(&findings), vec![2, 3, 5, 6, 8, 9]);
|
||||
assert_eq!(findings[0].text, "4e38");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wgsl_digits_inside_unicode_identifiers_are_not_literals() {
|
||||
let shader = "const π1e39 = 1.0;\nconst é2e40: f32 = 2.0;\nconst A: f32 =\u{200E}1e39;\n";
|
||||
let findings = wgsl_float_literals(shader);
|
||||
assert_eq!(lines(&findings), vec![3]);
|
||||
assert_eq!(findings[0].text, "1e39");
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn test_rust_sources_filtering() {
|
||||
|
||||
Reference in new issue
Block a user