Initial commit: Fabrilis docs, rules and deterministic core
Docs (architecture, decisions, coupling, determinism, UI, references), code rules enforced by tools/limits, deterministic core with units, time, math, sched, snapshot, vec and rng, plus smoke tests. ref/ stays out of git.
This commit is contained in:
commit
79928b645b
222 changed files with 5335 additions and 0 deletions
10
tools/limits/Cargo.toml
Normal file
10
tools/limits/Cargo.toml
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "fabrilis-limits"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
publish = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
96
tools/limits/src/lib.rs
Normal file
96
tools/limits/src/lib.rs
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
//! Repository rules, enforced for every code file and crate manifest:
|
||||
//! file length, files per directory, English-only comments, tests in separate files,
|
||||
//! no vague file names, no work markers in comments, crate layering.
|
||||
//!
|
||||
//! Used by the `fabrilis-limits` binary (whole repository: pre-commit and CI) and by
|
||||
//! `build.rs` of every crate, so a violation of a hard rule breaks the build.
|
||||
|
||||
mod rules;
|
||||
mod walk;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// More lines than this in one file produces a warning.
|
||||
pub const WARN_LINES: usize = 350;
|
||||
/// More lines than this in one file is an error.
|
||||
pub const MAX_LINES: usize = 500;
|
||||
/// More code files than this in one directory (subdirectories and test files do not
|
||||
/// count) is an error.
|
||||
pub const MAX_FILES_PER_DIR: usize = 4;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Report {
|
||||
pub errors: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
fn check_file(root: &Path, file: &Path, report: &mut Report) {
|
||||
let relative = file.strip_prefix(root).unwrap_or(file);
|
||||
let shown = relative.display();
|
||||
let Ok(text) = std::fs::read_to_string(file) else {
|
||||
report
|
||||
.errors
|
||||
.push(format!("{shown}: cannot read file as UTF-8"));
|
||||
return;
|
||||
};
|
||||
|
||||
let lines = text.lines().count();
|
||||
if !walk::is_test_file(file) {
|
||||
if lines > MAX_LINES {
|
||||
report
|
||||
.errors
|
||||
.push(format!("{shown}: {lines} lines, hard limit is {MAX_LINES}"));
|
||||
} else if lines > WARN_LINES {
|
||||
report.warnings.push(format!(
|
||||
"{shown}: {lines} lines, soft limit is {WARN_LINES}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
report.errors.extend(rules::check_source(relative, &text));
|
||||
}
|
||||
|
||||
/// Scans every code file and manifest under `root`.
|
||||
#[must_use]
|
||||
pub fn scan(root: &Path) -> Report {
|
||||
let mut report = Report::default();
|
||||
let files = walk::code_files(root);
|
||||
for file in &files {
|
||||
check_file(root, file, &mut report);
|
||||
}
|
||||
for (dir, count) in walk::files_per_dir(&files) {
|
||||
if count > MAX_FILES_PER_DIR {
|
||||
let shown = dir.strip_prefix(root).unwrap_or(&dir).display();
|
||||
report.errors.push(format!(
|
||||
"{shown}: {count} code files in one directory, limit is {MAX_FILES_PER_DIR}"
|
||||
));
|
||||
}
|
||||
}
|
||||
report.errors.extend(rules::check_layers(root));
|
||||
report
|
||||
}
|
||||
|
||||
/// For `build.rs`: checks the current crate, prints warnings as cargo warnings and
|
||||
/// aborts the build when a hard rule is broken.
|
||||
pub fn enforce_crate() {
|
||||
let Some(dir) = std::env::var_os("CARGO_MANIFEST_DIR").map(PathBuf::from) else {
|
||||
eprintln!("error: CARGO_MANIFEST_DIR is not set; call this from a build script");
|
||||
std::process::exit(1);
|
||||
};
|
||||
for sub in ["src", "tests", "benches", "build.rs"] {
|
||||
if dir.join(sub).exists() {
|
||||
println!("cargo::rerun-if-changed={sub}");
|
||||
}
|
||||
}
|
||||
|
||||
let report = scan(&dir);
|
||||
for warning in &report.warnings {
|
||||
println!("cargo::warning={warning}");
|
||||
}
|
||||
if !report.errors.is_empty() {
|
||||
for error in &report.errors {
|
||||
eprintln!("error: {error}");
|
||||
}
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
27
tools/limits/src/main.rs
Normal file
27
tools/limits/src/main.rs
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
//! Checks the whole repository: `cargo run -p fabrilis-limits [root]`.
|
||||
|
||||
use std::env;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let root = env::args()
|
||||
.nth(1)
|
||||
.map_or_else(|| PathBuf::from("."), PathBuf::from);
|
||||
let report = fabrilis_limits::scan(&root);
|
||||
|
||||
for warning in &report.warnings {
|
||||
println!("warning: {warning}");
|
||||
}
|
||||
for error in &report.errors {
|
||||
eprintln!("error: {error}");
|
||||
}
|
||||
|
||||
if report.errors.is_empty() {
|
||||
println!("OK: limits respected ({} warnings)", report.warnings.len());
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
eprintln!("FAIL: {} errors", report.errors.len());
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
211
tools/limits/src/rules/comments/mod.rs
Normal file
211
tools/limits/src/rules/comments/mod.rs
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
//! Comment rules: comments are written in English and carry no work markers.
|
||||
//!
|
||||
//! A tiny scanner that understands line comments, nested block comments, string,
|
||||
//! raw string and char literals, so text inside literals is never flagged.
|
||||
|
||||
/// Work markers are forbidden in comments: open work is tracked in TODO.md.
|
||||
const WORK_MARKERS: [&str; 4] = ["TODO", "FIXME", "HACK", "XXX"];
|
||||
|
||||
/// A comment that breaks a comment rule.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Finding {
|
||||
pub line: usize,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
fn is_cyrillic(c: char) -> bool {
|
||||
('\u{0400}'..='\u{04FF}').contains(&c)
|
||||
}
|
||||
|
||||
fn is_ident(c: char) -> bool {
|
||||
c.is_alphanumeric() || c == '_'
|
||||
}
|
||||
|
||||
/// Line number of the byte `offset` inside a comment that starts on `first_line`.
|
||||
fn line_at(text: &str, offset: usize, first_line: usize) -> usize {
|
||||
first_line + text[..offset].matches('\n').count()
|
||||
}
|
||||
|
||||
/// The problem with one comment, if any. Cyrillic text takes priority over markers.
|
||||
fn judge(text: &str, first_line: usize) -> Option<Finding> {
|
||||
if let Some(offset) = text.find(is_cyrillic) {
|
||||
let snippet: String = text[offset..]
|
||||
.chars()
|
||||
.take_while(|&c| c != '\n')
|
||||
.take(40)
|
||||
.collect();
|
||||
return Some(Finding {
|
||||
line: line_at(text, offset, first_line),
|
||||
message: format!("comment must be in English: {snippet}"),
|
||||
});
|
||||
}
|
||||
// A reference to the TODO.md file is not a marker. Removing it keeps line numbers.
|
||||
let cleaned = text.replace("TODO.md", "");
|
||||
let (offset, marker) = WORK_MARKERS
|
||||
.iter()
|
||||
.filter_map(|marker| cleaned.find(marker).map(|offset| (offset, *marker)))
|
||||
.min_by_key(|&(offset, _)| offset)?;
|
||||
Some(Finding {
|
||||
line: line_at(&cleaned, offset, first_line),
|
||||
message: format!("`{marker}` comments are not allowed; track the work in TODO.md"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns one finding per offending comment.
|
||||
pub fn check(source: &str) -> Vec<Finding> {
|
||||
let mut scanner = Scanner {
|
||||
chars: source.chars().collect(),
|
||||
pos: 0,
|
||||
line: 1,
|
||||
findings: Vec::new(),
|
||||
};
|
||||
scanner.run();
|
||||
scanner.findings
|
||||
}
|
||||
|
||||
struct Scanner {
|
||||
chars: Vec<char>,
|
||||
pos: usize,
|
||||
line: usize,
|
||||
findings: Vec<Finding>,
|
||||
}
|
||||
|
||||
impl Scanner {
|
||||
fn peek(&self, offset: usize) -> Option<char> {
|
||||
self.chars.get(self.pos + offset).copied()
|
||||
}
|
||||
|
||||
fn run(&mut self) {
|
||||
while let Some(c) = self.peek(0) {
|
||||
match c {
|
||||
'\n' => {
|
||||
self.line += 1;
|
||||
self.pos += 1;
|
||||
}
|
||||
'/' if self.peek(1) == Some('/') => self.line_comment(),
|
||||
'/' if self.peek(1) == Some('*') => self.block_comment(),
|
||||
'"' => self.string(),
|
||||
'r' if self.raw_string_hashes().is_some() => self.raw_string(),
|
||||
'\'' => self.quote(),
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn report_range(&mut self, start: usize, end: usize, first_line: usize) {
|
||||
let text: String = self.chars[start..end].iter().collect();
|
||||
if let Some(finding) = judge(&text, first_line) {
|
||||
self.findings.push(finding);
|
||||
}
|
||||
}
|
||||
|
||||
fn line_comment(&mut self) {
|
||||
let start = self.pos;
|
||||
while self.peek(0).is_some_and(|c| c != '\n') {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.report_range(start, self.pos, self.line);
|
||||
}
|
||||
|
||||
fn block_comment(&mut self) {
|
||||
let (start, start_line) = (self.pos, self.line);
|
||||
self.pos += 2;
|
||||
let mut depth = 1;
|
||||
while depth > 0 {
|
||||
match (self.peek(0), self.peek(1)) {
|
||||
(None, _) => break,
|
||||
(Some('/'), Some('*')) => {
|
||||
depth += 1;
|
||||
self.pos += 2;
|
||||
}
|
||||
(Some('*'), Some('/')) => {
|
||||
depth -= 1;
|
||||
self.pos += 2;
|
||||
}
|
||||
(Some('\n'), _) => {
|
||||
self.line += 1;
|
||||
self.pos += 1;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
self.report_range(start, self.pos, start_line);
|
||||
}
|
||||
|
||||
fn string(&mut self) {
|
||||
self.pos += 1;
|
||||
while let Some(c) = self.peek(0) {
|
||||
match c {
|
||||
'\\' => {
|
||||
if self.peek(1) == Some('\n') {
|
||||
self.line += 1;
|
||||
}
|
||||
self.pos += 2;
|
||||
}
|
||||
'"' => {
|
||||
self.pos += 1;
|
||||
return;
|
||||
}
|
||||
'\n' => {
|
||||
self.line += 1;
|
||||
self.pos += 1;
|
||||
}
|
||||
_ => self.pos += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// At an `r`: the number of `#` if a raw string literal starts here.
|
||||
fn raw_string_hashes(&self) -> Option<usize> {
|
||||
let prev = self.pos.checked_sub(1).map(|p| self.chars[p]);
|
||||
if prev.is_some_and(is_ident) {
|
||||
let byte_prefix = prev == Some('b')
|
||||
&& self
|
||||
.pos
|
||||
.checked_sub(2)
|
||||
.is_none_or(|p| !is_ident(self.chars[p]));
|
||||
if !byte_prefix {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let mut hashes = 0;
|
||||
while self.peek(1 + hashes) == Some('#') {
|
||||
hashes += 1;
|
||||
}
|
||||
(self.peek(1 + hashes) == Some('"')).then_some(hashes)
|
||||
}
|
||||
|
||||
fn raw_string(&mut self) {
|
||||
let hashes = self.raw_string_hashes().unwrap_or(0);
|
||||
// Skip `r`, the hashes and the opening quote.
|
||||
self.pos += 2 + hashes;
|
||||
while let Some(c) = self.peek(0) {
|
||||
if c == '\n' {
|
||||
self.line += 1;
|
||||
}
|
||||
if c == '"' && (1..=hashes).all(|k| self.peek(k) == Some('#')) {
|
||||
self.pos += 1 + hashes;
|
||||
return;
|
||||
}
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// A `'` starts a char literal or a lifetime/label.
|
||||
fn quote(&mut self) {
|
||||
if self.peek(1) == Some('\\') {
|
||||
self.pos += 3;
|
||||
while self.peek(0).is_some_and(|c| c != '\'') {
|
||||
self.pos += 1;
|
||||
}
|
||||
self.pos += 1;
|
||||
} else if self.peek(2) == Some('\'') {
|
||||
self.pos += 3;
|
||||
} else {
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
51
tools/limits/src/rules/comments/tests.rs
Normal file
51
tools/limits/src/rules/comments/tests.rs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
use super::*;
|
||||
|
||||
fn lines(source: &str) -> Vec<usize> {
|
||||
check(source).iter().map(|f| f.line).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_line_and_doc_comments() {
|
||||
let src = "fn a() {}\n// привет\n/// док\n//! мир\n";
|
||||
assert_eq!(lines(src), [2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_block_comments_with_the_right_line() {
|
||||
let src = "/* english\n and русский */\nfn a() {}\n";
|
||||
assert_eq!(lines(src), [2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flags_nested_block_comments() {
|
||||
assert_eq!(lines("/* a /* б */ c */"), [1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn english_comments_pass() {
|
||||
assert!(lines("// plain text, symbols → ≤ × and Greek σ ε\n").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_inside_literals_is_ignored() {
|
||||
let src = "let a = \"// не комментарий\";\nlet b = r#\"// тоже \" нет\"#;\nlet c = 'я';\n";
|
||||
assert!(lines(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escaped_quotes_do_not_end_a_string() {
|
||||
let src = "let a = \"say \\\"привет\\\"\";\n// ok\n";
|
||||
assert!(lines(src).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifetimes_do_not_swallow_following_comments() {
|
||||
let src = "fn f<'a>(x: &'a str) -> &'a str { x } // русский\n";
|
||||
assert_eq!(lines(src), [1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn char_literals_with_quotes_are_handled() {
|
||||
let src = "let q = '\"';\nlet e = '\\'';\n// плохо\n";
|
||||
assert_eq!(lines(src), [3]);
|
||||
}
|
||||
134
tools/limits/src/rules/layers.rs
Normal file
134
tools/limits/src/rules/layers.rs
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
//! Enforces the crate layering from docs/ARCHITECTURE.md: dependencies point down
|
||||
//! only, and simulation crates never depend on GUI crates.
|
||||
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::walk;
|
||||
|
||||
/// Crate name without the `fabrilis-` prefix and its layer. A crate may depend only on
|
||||
/// crates of a strictly lower layer. Add every new crate here.
|
||||
const LAYERS: &[(&str, u8)] = &[
|
||||
("core", 0),
|
||||
("platform", 1),
|
||||
("storage", 1),
|
||||
("materials", 1),
|
||||
("physics", 1),
|
||||
("aero", 1),
|
||||
("actuators", 1),
|
||||
("analog", 1),
|
||||
("cpu", 1),
|
||||
("worldgen", 1),
|
||||
("scripting", 1),
|
||||
("sensors", 1),
|
||||
("analysis", 1),
|
||||
("render", 1),
|
||||
("scene", 2),
|
||||
("structure", 2),
|
||||
("thermal", 2),
|
||||
("soc", 2),
|
||||
("ui", 2),
|
||||
("parts", 3),
|
||||
("wiring", 3),
|
||||
("bridge", 3),
|
||||
("modes", 4),
|
||||
("app", 5),
|
||||
];
|
||||
|
||||
/// Only these crates (and each other) may depend on GUI crates.
|
||||
const GUI: [&str; 3] = ["render", "ui", "app"];
|
||||
/// Tooling crates sit outside the layering.
|
||||
const TOOLS: [&str; 1] = ["limits"];
|
||||
|
||||
struct Manifest {
|
||||
name: String,
|
||||
dependencies: Vec<String>,
|
||||
}
|
||||
|
||||
fn layer_of(name: &str) -> Option<u8> {
|
||||
LAYERS
|
||||
.iter()
|
||||
.find(|(known, _)| *known == name)
|
||||
.map(|&(_, layer)| layer)
|
||||
}
|
||||
|
||||
fn parse(text: &str) -> Option<Manifest> {
|
||||
let mut section = "";
|
||||
let mut name = None;
|
||||
let mut dependencies = Vec::new();
|
||||
for line in text.lines().map(str::trim) {
|
||||
if line.starts_with('[') {
|
||||
section = line;
|
||||
continue;
|
||||
}
|
||||
match section {
|
||||
"[package]" if line.starts_with("name") => {
|
||||
name = line.split('"').nth(1).map(str::to_string);
|
||||
}
|
||||
"[dependencies]" => {
|
||||
if let Some(rest) = line.strip_prefix("fabrilis-") {
|
||||
let dep = rest.split([' ', '=']).next().unwrap_or("");
|
||||
dependencies.push(dep.to_string());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Some(Manifest {
|
||||
name: name?,
|
||||
dependencies,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_manifest(shown: &str, name: &str, dependencies: &[String]) -> Vec<String> {
|
||||
let Some(layer) = layer_of(name) else {
|
||||
return vec![format!(
|
||||
"{shown}: crate `{name}` is not in the layer table (tools/limits/src/rules/layers.rs)"
|
||||
)];
|
||||
};
|
||||
let mut errors = Vec::new();
|
||||
for dep in dependencies {
|
||||
let Some(dep_layer) = layer_of(dep) else {
|
||||
errors.push(format!(
|
||||
"{shown}: dependency `{dep}` is not in the layer table"
|
||||
));
|
||||
continue;
|
||||
};
|
||||
if dep_layer >= layer {
|
||||
errors.push(format!(
|
||||
"{shown}: `{name}` (layer {layer}) must not depend on `{dep}` (layer {dep_layer}); dependencies point down only"
|
||||
));
|
||||
}
|
||||
if GUI.contains(&dep.as_str()) && !GUI.contains(&name) {
|
||||
errors.push(format!(
|
||||
"{shown}: simulation crate `{name}` must not depend on GUI crate `{dep}`"
|
||||
));
|
||||
}
|
||||
}
|
||||
errors
|
||||
}
|
||||
|
||||
/// Layering violations in every `fabrilis-*` manifest under `root`.
|
||||
pub fn check(root: &Path) -> Vec<String> {
|
||||
let mut errors = Vec::new();
|
||||
for path in walk::manifests(root) {
|
||||
let shown = path
|
||||
.strip_prefix(root)
|
||||
.unwrap_or(&path)
|
||||
.display()
|
||||
.to_string();
|
||||
let Ok(text) = fs::read_to_string(&path) else {
|
||||
continue;
|
||||
};
|
||||
let Some(manifest) = parse(&text) else {
|
||||
continue;
|
||||
};
|
||||
let Some(name) = manifest.name.strip_prefix("fabrilis-") else {
|
||||
continue;
|
||||
};
|
||||
if !TOOLS.contains(&name) {
|
||||
errors.extend(check_manifest(&shown, name, &manifest.dependencies));
|
||||
}
|
||||
}
|
||||
errors
|
||||
}
|
||||
33
tools/limits/src/rules/mod.rs
Normal file
33
tools/limits/src/rules/mod.rs
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
//! Per-file source rules and the workspace layering rule.
|
||||
|
||||
mod comments;
|
||||
mod layers;
|
||||
mod names;
|
||||
mod separation;
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::walk;
|
||||
|
||||
pub use layers::check as check_layers;
|
||||
|
||||
/// Violations of the per-file rules, formatted as `path[:line]: message`.
|
||||
pub fn check_source(relative: &Path, text: &str) -> Vec<String> {
|
||||
let shown = relative.display();
|
||||
let mut errors = Vec::new();
|
||||
|
||||
if let Some(message) = names::violation(relative) {
|
||||
errors.push(format!("{shown}: {message}"));
|
||||
}
|
||||
if walk::is_comment_checked(relative) {
|
||||
for finding in comments::check(text) {
|
||||
errors.push(format!("{shown}:{}: {}", finding.line, finding.message));
|
||||
}
|
||||
}
|
||||
if relative.extension().is_some_and(|ext| ext == "rs") {
|
||||
for (line, message) in separation::violations(relative, text) {
|
||||
errors.push(format!("{shown}:{line}: {message}"));
|
||||
}
|
||||
}
|
||||
errors
|
||||
}
|
||||
15
tools/limits/src/rules/names.rs
Normal file
15
tools/limits/src/rules/names.rs
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
//! Forbids catch-all names: a file or directory is named after what it contains.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
const VAGUE_NAMES: [&str; 8] = [
|
||||
"utils", "util", "helpers", "helper", "common", "misc", "stuff", "shared",
|
||||
];
|
||||
|
||||
/// A message if any component of `path` is a vague name.
|
||||
pub fn violation(path: &Path) -> Option<String> {
|
||||
path.iter()
|
||||
.filter_map(|component| Path::new(component).file_stem()?.to_str())
|
||||
.find(|stem| VAGUE_NAMES.contains(stem))
|
||||
.map(|stem| format!("name `{stem}` is too vague; name it after what it contains"))
|
||||
}
|
||||
60
tools/limits/src/rules/separation.rs
Normal file
60
tools/limits/src/rules/separation.rs
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
//! Tests live in separate files: no inline test modules and no `#[test]` in code files.
|
||||
//!
|
||||
//! Allowed: `#[cfg(test)] mod tests;` pointing to a `tests.rs` file, and anything
|
||||
//! under a `tests/` or `benches/` directory.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use crate::walk::is_test_file;
|
||||
|
||||
/// `mod name;` with an optional visibility: the module body lives in another file.
|
||||
fn is_out_of_line_mod(declaration: &str) -> bool {
|
||||
let rest = declaration
|
||||
.strip_prefix("pub(crate) ")
|
||||
.or_else(|| declaration.strip_prefix("pub "))
|
||||
.unwrap_or(declaration);
|
||||
rest.strip_prefix("mod ")
|
||||
.and_then(|r| r.strip_suffix(';'))
|
||||
.is_some_and(|name| {
|
||||
!name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_')
|
||||
})
|
||||
}
|
||||
|
||||
/// The item that follows a `#[cfg(test)]` attribute found at `index`.
|
||||
fn declaration_after<'a>(lines: &[&'a str], index: usize, rest: &'a str) -> &'a str {
|
||||
if !rest.is_empty() {
|
||||
return rest;
|
||||
}
|
||||
lines[index + 1..]
|
||||
.iter()
|
||||
.find(|line| !line.is_empty() && !line.starts_with("#["))
|
||||
.copied()
|
||||
.unwrap_or("")
|
||||
}
|
||||
|
||||
/// `(line, message)` for every place where test code sits inside a code file.
|
||||
pub fn violations(path: &Path, text: &str) -> Vec<(usize, String)> {
|
||||
if is_test_file(path) {
|
||||
return Vec::new();
|
||||
}
|
||||
let lines: Vec<&str> = text.lines().map(str::trim).collect();
|
||||
let mut found = Vec::new();
|
||||
for (index, line) in lines.iter().enumerate() {
|
||||
if line.starts_with("#[test]") {
|
||||
found.push((
|
||||
index + 1,
|
||||
"`#[test]` outside a test file; move the test to tests.rs".to_string(),
|
||||
));
|
||||
} else if let Some(rest) = line.strip_prefix("#[cfg(test)]") {
|
||||
let declaration = declaration_after(&lines, index, rest.trim());
|
||||
if !is_out_of_line_mod(declaration) {
|
||||
found.push((
|
||||
index + 1,
|
||||
"inline test code; use `#[cfg(test)] mod tests;` with a separate tests.rs"
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
81
tools/limits/src/walk.rs
Normal file
81
tools/limits/src/walk.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
//! Repository traversal: finds code files and manifests, groups files by directory.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const CODE_EXTENSIONS: [&str; 4] = ["rs", "wgsl", "rhai", "sh"];
|
||||
const COMMENT_CHECKED_EXTENSIONS: [&str; 3] = ["rs", "wgsl", "rhai"];
|
||||
/// Documentation and local reference clones are not our code, so they are exempt.
|
||||
const SKIPPED_DIRS: [&str; 4] = ["target", "docs", "node_modules", "ref"];
|
||||
|
||||
fn has_extension(path: &Path, allowed: &[&str]) -> bool {
|
||||
path.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.is_some_and(|e| allowed.contains(&e))
|
||||
}
|
||||
|
||||
/// Files whose `//` and `/* */` comments are checked.
|
||||
pub fn is_comment_checked(path: &Path) -> bool {
|
||||
has_extension(path, &COMMENT_CHECKED_EXTENSIONS)
|
||||
}
|
||||
|
||||
/// A test file: `tests.rs` next to a module, or anything under `tests/` or `benches/`.
|
||||
/// Tests are exempt from the file size limit and from the files-per-directory limit.
|
||||
pub fn is_test_file(path: &Path) -> bool {
|
||||
path.file_name().is_some_and(|name| name == "tests.rs")
|
||||
|| path
|
||||
.iter()
|
||||
.any(|component| component == "tests" || component == "benches")
|
||||
}
|
||||
|
||||
/// Every file under `root` accepted by `keep`, sorted so reports are stable.
|
||||
fn collect(root: &Path, keep: impl Fn(&Path) -> bool) -> Vec<PathBuf> {
|
||||
let mut files = Vec::new();
|
||||
let mut stack = vec![root.to_path_buf()];
|
||||
while let Some(dir) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if path.is_dir() {
|
||||
let skipped = name.starts_with('.') || SKIPPED_DIRS.contains(&name.as_str());
|
||||
if !skipped {
|
||||
stack.push(path);
|
||||
}
|
||||
} else if keep(&path) {
|
||||
files.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
files.sort();
|
||||
files
|
||||
}
|
||||
|
||||
/// All code files under `root`.
|
||||
pub fn code_files(root: &Path) -> Vec<PathBuf> {
|
||||
collect(root, |path| has_extension(path, &CODE_EXTENSIONS))
|
||||
}
|
||||
|
||||
/// All `Cargo.toml` files under `root`.
|
||||
pub fn manifests(root: &Path) -> Vec<PathBuf> {
|
||||
collect(root, |path| {
|
||||
path.file_name().is_some_and(|name| name == "Cargo.toml")
|
||||
})
|
||||
}
|
||||
|
||||
/// Number of code files directly inside each directory; test files do not count.
|
||||
pub fn files_per_dir(files: &[PathBuf]) -> BTreeMap<PathBuf, usize> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for file in files {
|
||||
if is_test_file(file) {
|
||||
continue;
|
||||
}
|
||||
if let Some(dir) = file.parent() {
|
||||
*counts.entry(dir.to_path_buf()).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
163
tools/limits/tests/rules.rs
Normal file
163
tools/limits/tests/rules.rs
Normal file
|
|
@ -0,0 +1,163 @@
|
|||
mod tree;
|
||||
|
||||
use fabrilis_limits::{MAX_LINES, scan};
|
||||
use tree::TempTree;
|
||||
|
||||
fn errors(tree: &TempTree) -> Vec<String> {
|
||||
scan(tree.path()).errors
|
||||
}
|
||||
|
||||
fn manifest(name: &str, dependencies: &[&str]) -> String {
|
||||
let deps: String = dependencies
|
||||
.iter()
|
||||
.map(|d| format!("fabrilis-{d} = {{ path = \"../{d}\" }}\n"))
|
||||
.collect();
|
||||
format!("[package]\nname = \"fabrilis-{name}\"\n\n[dependencies]\n{deps}")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_test_module_is_rejected() {
|
||||
let tree = TempTree::new("inline");
|
||||
tree.write(
|
||||
"a.rs",
|
||||
"fn f() {}\n\n#[cfg(test)]\nmod tests {\n#[test]\nfn t() {}\n}\n",
|
||||
);
|
||||
let found = errors(&tree);
|
||||
assert!(found.iter().any(|e| e.contains("a.rs:3")), "{found:?}");
|
||||
assert!(found.iter().any(|e| e.contains("a.rs:5")), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_line_test_module_is_accepted() {
|
||||
let tree = TempTree::new("outline");
|
||||
tree.write("a.rs", "fn f() {}\n#[cfg(test)]\nmod tests;\n");
|
||||
tree.write(
|
||||
"b.rs",
|
||||
"#[cfg(test)]\n\n#[allow(dead_code)]\npub mod tests;\n",
|
||||
);
|
||||
assert!(errors(&tree).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_helpers_behind_cfg_test_are_rejected() {
|
||||
let tree = TempTree::new("helper");
|
||||
tree.write("a.rs", "#[cfg(test)]\nfn helper() {}\n");
|
||||
assert_eq!(errors(&tree).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_attribute_is_fine_in_test_files() {
|
||||
let tree = TempTree::new("testfiles");
|
||||
tree.write("sched/tests.rs", "#[test]\nfn t() {}\n");
|
||||
tree.write("tests/it.rs", "#[test]\nfn t() {}\n");
|
||||
tree.write("benches/b.rs", "#[test]\nfn t() {}\n");
|
||||
assert!(errors(&tree).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vague_names_are_rejected() {
|
||||
let tree = TempTree::new("names");
|
||||
tree.write("utils.rs", "");
|
||||
tree.write("ok/helpers/a.rs", "");
|
||||
tree.write("fine/units.rs", "");
|
||||
assert_eq!(errors(&tree).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn work_markers_in_comments_are_rejected() {
|
||||
let tree = TempTree::new("markers");
|
||||
tree.write("a.rs", "// TODO: fix\n/* FIXME later */\nfn f() {}\n");
|
||||
assert_eq!(errors(&tree).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn markers_in_strings_and_todo_md_references_are_fine() {
|
||||
let tree = TempTree::new("markers-ok");
|
||||
tree.write("a.rs", "// tracked in TODO.md\nlet s = \"TODO FIXME\";\n");
|
||||
assert!(errors(&tree).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layering_accepts_downward_dependencies() {
|
||||
let tree = TempTree::new("layers-ok");
|
||||
tree.write("crates/core/Cargo.toml", &manifest("core", &[]));
|
||||
tree.write(
|
||||
"crates/scene/Cargo.toml",
|
||||
&manifest("scene", &["core", "storage"]),
|
||||
);
|
||||
tree.write("crates/storage/Cargo.toml", &manifest("storage", &["core"]));
|
||||
assert!(errors(&tree).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layering_rejects_same_layer_and_upward_dependencies() {
|
||||
let tree = TempTree::new("layers-up");
|
||||
tree.write("crates/physics/Cargo.toml", &manifest("physics", &["aero"]));
|
||||
tree.write("crates/core/Cargo.toml", &manifest("core", &["modes"]));
|
||||
assert_eq!(errors(&tree).len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simulation_crates_must_not_use_gui_crates() {
|
||||
let tree = TempTree::new("layers-gui");
|
||||
tree.write("crates/modes/Cargo.toml", &manifest("modes", &["render"]));
|
||||
let found = errors(&tree);
|
||||
assert!(found.iter().any(|e| e.contains("GUI crate")), "{found:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_crates_must_be_registered() {
|
||||
let tree = TempTree::new("layers-unknown");
|
||||
tree.write("crates/zzz/Cargo.toml", &manifest("zzz", &[]));
|
||||
let found = errors(&tree);
|
||||
assert!(found.iter().any(|e| e.contains("layer table")), "{found:?}");
|
||||
}
|
||||
|
||||
fn lines(count: usize) -> String {
|
||||
"let _x = 1;\n".repeat(count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_files_do_not_count_towards_the_file_limit() {
|
||||
let tree = TempTree::new("files-tests");
|
||||
for i in 0..4 {
|
||||
tree.write(&format!("src/f{i}.rs"), "");
|
||||
}
|
||||
tree.write("src/tests.rs", "");
|
||||
assert!(errors(&tree).is_empty(), "{:?}", errors(&tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_directory_is_limited_on_its_own() {
|
||||
let tree = TempTree::new("files-nested");
|
||||
for i in 0..4 {
|
||||
tree.write(&format!("src/f{i}.rs"), "");
|
||||
tree.write(&format!("src/sub{i}/a.rs"), "");
|
||||
}
|
||||
assert!(errors(&tree).is_empty(), "{:?}", errors(&tree));
|
||||
|
||||
tree.write("src/sub0/b.rs", "");
|
||||
tree.write("src/sub0/c.rs", "");
|
||||
tree.write("src/sub0/d.rs", "");
|
||||
tree.write("src/sub0/e.rs", "");
|
||||
assert_eq!(errors(&tree).len(), 1, "{:?}", errors(&tree));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_test_files_are_exempt_from_the_size_limit() {
|
||||
let tree = TempTree::new("size-tests");
|
||||
tree.write("src/tests.rs", &lines(MAX_LINES + 100));
|
||||
tree.write("tests/it.rs", &lines(MAX_LINES + 100));
|
||||
tree.write("benches/b.rs", &lines(MAX_LINES + 100));
|
||||
assert!(errors(&tree).is_empty(), "{:?}", errors(&tree));
|
||||
let report = scan(tree.path());
|
||||
assert!(report.warnings.is_empty(), "{:?}", report.warnings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_clones_are_not_checked() {
|
||||
let tree = TempTree::new("ref");
|
||||
tree.write("ref/bad.rs", &lines(MAX_LINES + 10));
|
||||
tree.write("ref/utils/common.rs", "");
|
||||
assert!(errors(&tree).is_empty(), "{:?}", errors(&tree));
|
||||
}
|
||||
81
tools/limits/tests/scan.rs
Normal file
81
tools/limits/tests/scan.rs
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
mod tree;
|
||||
|
||||
use fabrilis_limits::{MAX_FILES_PER_DIR, MAX_LINES, WARN_LINES, scan};
|
||||
use tree::TempTree;
|
||||
|
||||
fn lines(count: usize) -> String {
|
||||
"let _x = 1;\n".repeat(count)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clean_tree_has_no_findings() {
|
||||
let tree = TempTree::new("clean");
|
||||
tree.write("a.rs", &lines(10));
|
||||
let report = scan(tree.path());
|
||||
assert!(report.errors.is_empty() && report.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_limit_warns_but_does_not_fail() {
|
||||
let tree = TempTree::new("soft");
|
||||
tree.write("a.rs", &lines(WARN_LINES + 1));
|
||||
let report = scan(tree.path());
|
||||
assert!(report.errors.is_empty());
|
||||
assert_eq!(report.warnings.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_at_limits_is_fine() {
|
||||
let tree = TempTree::new("edge");
|
||||
tree.write("a.rs", &lines(MAX_LINES));
|
||||
let report = scan(tree.path());
|
||||
assert!(report.errors.is_empty());
|
||||
assert_eq!(report.warnings.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_limit_is_an_error() {
|
||||
let tree = TempTree::new("hard");
|
||||
tree.write("a.rs", &lines(MAX_LINES + 1));
|
||||
let report = scan(tree.path());
|
||||
assert_eq!(report.errors.len(), 1);
|
||||
assert!(report.warnings.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_files_in_one_directory_is_an_error() {
|
||||
let tree = TempTree::new("files");
|
||||
for i in 0..=MAX_FILES_PER_DIR {
|
||||
tree.write(&format!("d/f{i}.rs"), "");
|
||||
}
|
||||
tree.write("other/a.rs", "");
|
||||
let report = scan(tree.path());
|
||||
assert_eq!(report.errors.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subdirectories_do_not_count_towards_the_file_limit() {
|
||||
let tree = TempTree::new("subdirs");
|
||||
for i in 0..MAX_FILES_PER_DIR {
|
||||
tree.write(&format!("d/f{i}.rs"), "");
|
||||
tree.write(&format!("d/sub{i}/mod.rs"), "");
|
||||
}
|
||||
assert!(scan(tree.path()).errors.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_english_comment_is_an_error_with_a_location() {
|
||||
let tree = TempTree::new("lang");
|
||||
tree.write("a.rs", "fn a() {}\n// комментарий\n");
|
||||
let report = scan(tree.path());
|
||||
assert_eq!(report.errors.len(), 1);
|
||||
assert!(report.errors[0].contains("a.rs:2"), "{:?}", report.errors);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn docs_and_target_are_ignored() {
|
||||
let tree = TempTree::new("skip");
|
||||
tree.write("docs/x.rs", &lines(MAX_LINES + 10));
|
||||
tree.write("target/y.rs", &lines(MAX_LINES + 10));
|
||||
assert!(scan(tree.path()).errors.is_empty());
|
||||
}
|
||||
37
tools/limits/tests/tree/mod.rs
Normal file
37
tools/limits/tests/tree/mod.rs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
//! A temporary directory tree for rule tests.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
reason = "test helper: a failure should abort the test"
|
||||
)]
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub struct TempTree(PathBuf);
|
||||
|
||||
impl TempTree {
|
||||
pub fn new(name: &str) -> Self {
|
||||
let root =
|
||||
std::env::temp_dir().join(format!("fabrilis-limits-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(&root).unwrap();
|
||||
Self(root)
|
||||
}
|
||||
|
||||
pub fn path(&self) -> &Path {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub fn write(&self, relative: &str, content: &str) {
|
||||
let path = self.0.join(relative);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, content).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TempTree {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue