use std::collections::BTreeSet;
use std::path::Path;
const KNOWN_FABRICATORS: &[&str] = &[
];
const INERT_CALLS: &[&str] = &[
"Ok",
"Some",
"None",
"Self",
"new",
"default",
"Default",
"String",
"Vec",
"HashMap",
"BTreeMap",
"HashSet",
"BTreeSet",
"to_string",
"into",
"from",
"unwrap_or_else",
"unwrap_or_default",
"with_capacity",
"clone",
"PhantomData",
];
fn rust_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
fn strip_noise(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let bytes: Vec<char> = src.chars().collect();
let mut i = 0;
while i < bytes.len() {
let rest_two = (bytes[i], bytes.get(i + 1).copied().unwrap_or('\0'));
match rest_two {
('/', '/') => {
while i < bytes.len() && bytes[i] != '\n' {
i += 1;
}
}
('/', '*') => {
i += 2;
while i + 1 < bytes.len() && !(bytes[i] == '*' && bytes[i + 1] == '/') {
i += 1;
}
i = (i + 2).min(bytes.len());
}
('"', _) => {
out.push_str("\"\"");
i += 1;
while i < bytes.len() {
if bytes[i] == '\\' {
i += 2;
continue;
}
if bytes[i] == '"' {
i += 1;
break;
}
i += 1;
}
}
_ => {
out.push(bytes[i]);
i += 1;
}
}
}
out
}
fn brace_body(src: &str, from: usize) -> Option<String> {
let bytes: Vec<char> = src.chars().collect();
let mut i = src[..from].chars().count();
while i < bytes.len() && bytes[i] != '{' {
i += 1;
}
if i >= bytes.len() {
return None;
}
let start = i;
let mut depth = 0usize;
while i < bytes.len() {
match bytes[i] {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
return Some(bytes[start..=i].iter().collect());
}
}
_ => {}
}
i += 1;
}
None
}
fn fabricates_a_number(body: &str) -> bool {
for (i, c) in body.char_indices() {
if c != ':' {
continue;
}
if body[i + 1..].starts_with(':') {
continue;
}
let rest = body[i + 1..].trim_start();
let value: String = rest
.chars()
.take_while(|c| c.is_ascii_digit() || *c == '.' || c.is_alphabetic() || *c == '_')
.collect();
if value.is_empty() {
continue;
}
let terminated = rest[value.len()..].trim_start();
if !(terminated.starts_with(',') || terminated.starts_with('}')) {
continue;
}
let numeric = value.chars().next().is_some_and(|c| c.is_ascii_digit());
if numeric || value == "false" {
return true;
}
}
false
}
fn calls_something_real(body: &str) -> bool {
let inert: BTreeSet<&str> = INERT_CALLS.iter().copied().collect();
let chars: Vec<char> = body.chars().collect();
for i in 0..chars.len() {
if chars[i] != '(' {
continue;
}
let mut j = i;
while j > 0 && (chars[j - 1].is_alphanumeric() || chars[j - 1] == '_') {
j -= 1;
}
if j < i {
let name: String = chars[j..i].iter().collect();
if !inert.contains(name.as_str()) {
return true;
}
}
}
false
}
#[test]
fn no_new_constructor_fabricates_readings_without_being_on_the_list() {
let mut files = Vec::new();
rust_files(Path::new("src"), &mut files);
assert!(
files.len() > 50,
"the walk found only {} files; it is not looking where it thinks it is",
files.len()
);
let mut found: BTreeSet<String> = BTreeSet::new();
for path in &files {
let Ok(raw) = std::fs::read_to_string(path) else {
continue;
};
let src = strip_noise(&raw);
let mut search = 0usize;
while let Some(rel) = src[search..].find("pub fn new(") {
let at = search + rel;
search = at + 11;
let after = &src[at + 11..];
let Some(close) = after.find(')') else {
continue;
};
if !after[..close].trim().is_empty() {
continue;
}
let Some(body) = brace_body(&src, at + 11 + close) else {
continue;
};
if calls_something_real(&body) {
continue;
}
if fabricates_a_number(&body) {
found.insert(path.to_string_lossy().replace('\\', "/"));
}
}
}
let known: BTreeSet<String> = KNOWN_FABRICATORS.iter().map(|s| s.to_string()).collect();
let unexpected: Vec<&String> = found.difference(&known).collect();
assert!(
unexpected.is_empty(),
"new `new()` constructors return fabricated numbers: {unexpected:?}\n\
\n\
A `new()` that returns 0 for a measurement turns 'not read' into 'read \
as zero', behind a name that reads like a proper constructor. That has \
already shipped two defects in this crate.\n\
\n\
If the value genuinely cannot reach a caller as a reading — because it \
is only ever a builder base filled immediately by a platform reader — \
add the file to KNOWN_FABRICATORS with a comment saying so. If it can \
reach a caller, that is the bug, and the list is not where it goes."
);
let vanished: Vec<&String> = known.difference(&found).collect();
assert!(
vanished.is_empty(),
"these are on the fabricator list but no longer detected: {vanished:?}\n\
If they were fixed, delete them from KNOWN_FABRICATORS. If the detector \
stopped seeing them, it is broken and is now certifying nothing."
);
}