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
878d144b77
221 changed files with 5316 additions and 0 deletions
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
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue