use std::path::{Path, PathBuf};
fn rust_files(directory: &Path, found: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(directory) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
rust_files(&path, found);
} else if path.extension().is_some_and(|extension| extension == "rs") {
found.push(path);
}
}
}
fn without_string_contents(text: &str) -> String {
let mut masked = String::with_capacity(text.len());
let mut characters = text.chars().peekable();
while let Some(character) = characters.next() {
match character {
'"' => {
masked.push('"');
while let Some(inner) = characters.next() {
match inner {
'\\' => {
let escaped = characters.next().unwrap_or(' ');
masked.push(' ');
masked.extend(std::iter::repeat_n(' ', escaped.len_utf8()));
}
'"' => {
masked.push('"');
break;
}
'\n' => masked.push('\n'),
_ => masked.extend(std::iter::repeat_n(' ', inner.len_utf8())),
}
}
}
_ => masked.push(character),
}
}
masked
}
fn end_of_call(masked: &str, open: usize) -> Option<usize> {
let mut depth = 0usize;
for (offset, character) in masked[open..].char_indices() {
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return Some(open + offset + 1);
}
}
_ => {}
}
}
None
}
#[test]
fn every_t_call_fills_its_placeholders() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
rust_files(&root, &mut files);
assert!(!files.is_empty(), "the crate's sources are where they are");
let mut unfilled: Vec<String> = Vec::new();
let mut calls = 0usize;
for file in &files {
let Ok(source) = std::fs::read_to_string(file) else {
continue;
};
let masked = without_string_contents(&source);
let mut from = 0usize;
while let Some(found) = masked[from..].find("t!(") {
let at = from + found;
from = at + 3;
let open = at + 2;
let Some(close) = end_of_call(&masked, open) else {
continue;
};
let call = &source[open..close];
if !call.contains("%{") {
continue;
}
calls += 1;
let mut names: Vec<&str> = Vec::new();
let mut rest = call;
while let Some(start) = rest.find("%{") {
let after = &rest[start + 2..];
let Some(end) = after.find('}') else {
break;
};
let name = &after[..end];
if !name.is_empty()
&& name
.chars()
.all(|character| character.is_alphanumeric() || character == '_')
&& !names.contains(&name)
{
names.push(name);
}
rest = &after[end + 1..];
}
for name in names {
let argument = format!("{name} =");
if !masked[open..close].contains(&argument) {
let line = source[..at].matches('\n').count() + 1;
unfilled.push(format!(
"{}:{line}: `%{{{name}}}` has no `{name} =` argument",
file.file_name().unwrap_or_default().to_string_lossy()
));
}
}
}
}
assert!(
calls > 0,
"the scan found no `t!` call with a placeholder at all, which means it is looking at nothing"
);
assert!(
unfilled.is_empty(),
"these messages would show a placeholder to the user:\n {}",
unfilled.join("\n ")
);
}