use std::path::Path;
const FORBIDDEN: [&str; 14] = [
"Plan",
"PlannedSheet",
"PlannedView",
"Problem",
"Spec",
"SheetSpec",
"ViewSpec",
"plan",
"spec",
"embedded_spec",
"edit",
"render",
"api",
"layout",
];
const ALLOWED: [&str; 13] = [
"crate::model::Analysis",
"crate::model::dimension_geometry::Reference",
"crate::bridge",
"crate::pmi",
"crate::pmi_lowering",
"crate::material",
"crate::arc",
"crate::radius",
"crate::output",
"crate::remedy_scope",
"crate::finding",
"crate::quiddity_evidence",
"crate::geometry_ids",
];
fn code_of(source: &str) -> String {
let c: Vec<char> = source.chars().collect();
let mut out = String::with_capacity(source.len());
let mut i = 0;
while i < c.len() {
if c[i] == '/' && c.get(i + 1) == Some(&'/') {
while i < c.len() && c[i] != '\n' {
i += 1;
}
} else if c[i] == '/' && c.get(i + 1) == Some(&'*') {
i += 2;
while i < c.len() && !(c[i] == '*' && c.get(i + 1) == Some(&'/')) {
i += 1;
}
i += 2;
out.push(' ');
} else if c[i] == 'r' && matches!(c.get(i + 1), Some('"' | '#')) {
let mut j = i + 1;
let mut hashes = 0;
while c.get(j) == Some(&'#') {
hashes += 1;
j += 1;
}
if c.get(j) != Some(&'"') {
out.push(c[i]);
i += 1;
continue;
}
j += 1;
let close: Vec<char> = std::iter::once('"')
.chain(std::iter::repeat_n('#', hashes))
.collect();
while j < c.len() && c[j..].iter().take(close.len()).ne(close.iter()) {
j += 1;
}
i = j + close.len();
out.push_str("\"\"");
} else if c[i] == '"' {
i += 1;
while i < c.len() && c[i] != '"' {
if c[i] == '\\' {
i += 1;
}
i += 1;
}
i += 1;
out.push_str("\"\"");
} else if c[i] == '\'' && c.get(i + 2) == Some(&'\'') {
i += 3;
out.push_str("' '");
} else if c[i] == '\'' && c.get(i + 1) == Some(&'\\') {
i += 2;
while i < c.len() && c[i] != '\'' {
i += 1;
}
i += 1;
out.push_str("' '");
} else {
out.push(c[i]);
i += 1;
}
}
out
}
pub fn violations(source: &str) -> Vec<String> {
let code = code_of(source);
let mut out = Vec::new();
for word in code.split(|c: char| !(c.is_alphanumeric() || c == '_')) {
if FORBIDDEN.contains(&word) {
out.push(word.to_string());
}
}
let squeezed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
let mut rest = squeezed.as_str();
while let Some(k) = rest.find("crate::") {
rest = &rest[k..];
let end = rest
.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == ':' || c == '{' || c == ','))
.unwrap_or(rest.len());
let path = &rest[..end];
let paths: Vec<String> = match path.split_once('{') {
Some((stem, names)) => names
.split(',')
.filter(|n| !n.is_empty())
.map(|n| format!("{stem}{n}"))
.collect(),
None => vec![path.to_string()],
};
for p in paths {
let allowed = ALLOWED
.iter()
.any(|a| p == *a || p.starts_with(&format!("{a}::")));
if !allowed {
out.push(p);
}
}
rest = &rest[end.max(1)..];
}
out
}
fn module_violations() -> Vec<(String, Vec<String>)> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lint");
let mut files: Vec<_> = std::fs::read_dir(&dir)
.expect("src/lint is readable")
.map(|e| e.unwrap().path())
.filter(|p| p.extension().is_some_and(|e| e == "rs"))
.collect();
files.sort();
assert!(files.len() >= 2, "src/lint has its files");
let declared: Vec<String> = std::fs::read_to_string(dir.join("mod.rs"))
.unwrap()
.lines()
.filter_map(|l| {
let l = l.trim().strip_prefix("pub ").unwrap_or(l.trim());
l.strip_prefix("mod ")?
.strip_suffix(';')
.map(str::to_string)
})
.collect();
for m in &declared {
assert!(
files.contains(&dir.join(format!("{m}.rs"))),
"lint's module {m} is not a file the guard reads"
);
}
assert!(
declared.len() >= 8,
"the guard reads lint's rule modules: {declared:?}"
);
files.push(dir.parent().unwrap().join("material.rs"));
files.push(dir.parent().unwrap().join("remedy_scope.rs"));
files.push(dir.parent().unwrap().join("arc.rs"));
files.push(dir.parent().unwrap().join("radius.rs"));
files.push(dir.parent().unwrap().join("finding.rs"));
files.push(dir.parent().unwrap().join("geometry_ids.rs"));
files
.into_iter()
.filter(|p| p.file_name().unwrap() != "guard.rs")
.map(|p| {
let source = std::fs::read_to_string(&p).unwrap();
(p.display().to_string(), violations(&source))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lint_never_reads_the_plan_or_the_spec() {
for (file, found) in module_violations() {
assert!(
found.is_empty(),
"{file} reaches the Plan or the Spec (ADR1-9, ADR5-2): {found:?}"
);
}
}
#[test]
fn the_guard_catches_what_it_should() {
let bad = [
"use crate::model::Plan;",
"use crate::model::dimension_geometry::check;",
"use crate::model::{Analysis, Spec};",
"fn f(p: &Plan) {}",
"let s = drawing.spec.clone();",
"crate::model::plan(&a, &s)",
"use crate::api::review;",
"use crate::layout;",
"crate::fixes::scope(&[])",
"let v: Vec<crate::model::PlannedView> = vec![];",
];
for source in bad {
assert!(!violations(source).is_empty(), "missed: {source}");
}
let fine = [
"use crate::model::Analysis;",
"use crate::output::{Claim, Drawing};",
"use crate::bridge::Feature;",
"let scope = crate::remedy_scope::UNBOUND_SCOPE;",
"let m = crate::material::solids(a, f);",
"let r = crate::radius::projected(a, id, n, page);",
"let s = crate::arc::Span { start: 0.0, sweep: 1.0 };",
"// the Plan and the Spec are not read\nlet x = 1;",
"/* Plan */ let s = \"the spec, in a message\";",
"let v = r#\"plan\"#;",
"let c = 'x';",
"fn planned_area() {}",
];
for source in fine {
assert!(
violations(source).is_empty(),
"flagged: {source}: {:?}",
violations(source)
);
}
}
}