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:
Loki 2026-11-16 19:09:10 +01:00
commit 878d144b77
221 changed files with 5316 additions and 0 deletions

96
tools/limits/src/lib.rs Normal file
View 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
View 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
}
}

View 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;

View 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]);
}

View 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
}

View 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
}

View 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"))
}

View 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
View 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
}