use std::collections::BTreeSet;
use crate::docs::{self, DocRules, Found};
use crate::lex::{self, Lang, Token};
use crate::python::docstrings;
use crate::rules::Ruleset;
use crate::walk::{self, Options, Root};
use crate::{Lines, Output};
const FUNCTION_WORDS: &[&str] = &[
"a", "an", "the", "is", "are", "was", "were", "be", "been", "not", "no", "to", "of", "in", "on", "at", "by", "for",
"from", "with", "without", "and", "or", "but", "if", "may", "might", "must", "can", "could", "would", "will",
"should", "has", "have", "had", "does", "do", "did", "it", "its", "this", "that", "which", "whose", "than", "as",
"into", "only", "each", "every",
];
pub fn reads(lang: Lang) -> bool {
matches!(lang, Lang::Rust | Lang::Python | Lang::Script)
}
fn test_file(path: &str) -> bool {
regex!(r"(?:^|/)(?:tests?|__tests__)/|(?:^|/)(?:tests\.rs|test_[^/]*\.py|[^/]*_test\.py|conftest\.py)$")
.is_match(path)
|| regex!(r"\.(?:test|spec)\.[cm]?[jt]sx?$").is_match(path)
}
fn test_items(text: &str) -> Vec<(usize, usize)> {
let b = text.as_bytes();
let attributes = regex!(r"#\[\s*(?:cfg\(\s*test\s*\)|(?:\w+::)*test)\s*\]").find_iter(text);
attributes
.filter_map(|attribute| {
let brace = attribute.end() + memchr::memchr2(b'{', b';', &b[attribute.end()..])?;
(b[brace] == b'{').then(|| (attribute.start(), lex::closing(b, brace, b"{", b"}")))
})
.collect()
}
fn body(literal: &str, lang: Lang) -> String {
let body = literal.trim_start_matches(|c: char| c.is_ascii_alphabetic() || c == '#');
let body = body.trim_start_matches(['"', '\'', '`']).trim_end_matches(['"', '\'', '`', '#']);
let body = regex!(r"\\\r?\n\s*").replace_all(body, " ");
let body = regex!(r"\\[nr]").replace_all(&body, "\n");
let body = regex!(r"\\t").replace_all(&body, " ");
let body = regex!(r#"\\(["'`\\])"#).replace_all(&body, "$1");
let body = body.replace("{{", "(").replace("}}", ")");
let body = match lang {
Lang::Script => regex!(r"\$\{[^}]*\}").replace_all(&body, "X").into_owned(),
Lang::Python => {
regex!(r"%(?:\([^)]*\))?[-#0 +]*\d*(?:\.\d+)?[sdifrgexXc]").replace_all(&body, "X").into_owned()
}
_ => body,
};
let body = regex!(r"\{[^{}]*\}").replace_all(&body, "X");
docs::without_code(&body)
}
fn sentence_shaped(text: &str) -> bool {
if !text.contains(' ') || regex!(r"[=\[\]{}]|::|->|=>").is_match(text) {
return false;
}
let words: Vec<&str> = regex!(r"[A-Za-z][A-Za-z'-]*").find_iter(text).map(|m| m.as_str()).collect();
words.len() >= 3 && words.iter().any(|word| FUNCTION_WORDS.contains(word))
}
fn statement(text: &str, start: usize, end: usize) -> bool {
let line_start = text[..start].rfind('\n').map_or(0, |k| k + 1);
let line_end = text[end..].find('\n').map_or(text.len(), |k| end + k);
let after = text[end..line_end].trim();
if !text[line_start..start].trim().is_empty() || !(after.is_empty() || after.starts_with('#')) {
return false;
}
let before = text[..line_start].trim_end();
let previous = before.rsplit('\n').next().unwrap_or_default().split(" #").next().unwrap_or_default().trim_end();
!previous.ends_with(['(', '[', '{', ',', '\\', '"', '\'', '+', '=', '%'])
}
fn check(rules: &'static DocRules, path: &str, text: &str) -> Vec<Found> {
let Some(lang) = Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)).filter(|&lang| reads(lang)) else {
return Vec::new();
};
if test_file(path) {
return Vec::new();
}
let tests = if lang == Lang::Rust { test_items(text) } else { Vec::new() };
let mut literals = Vec::new();
lex::tokens(text, lang, |token| {
if let Token::Str(start, end) = token
&& !tests.iter().any(|&(from, to)| from <= start && start < to)
{
literals.push((start, end));
}
});
let docs: BTreeSet<usize> = match lang {
Lang::Python => docstrings(text, &text.split('\n').collect::<Vec<_>>()).iter().map(|d| d.start).collect(),
_ => BTreeSet::new(),
};
let mut lines = Lines::new(text);
let mut found = Vec::new();
for (start, end) in literals {
let first = lines.at(start);
let last = first + memchr::memchr_iter(b'\n', &text.as_bytes()[start..end]).count();
if docs.range(first - 1..last).next().is_some() || lang == Lang::Python && statement(text, start, end) {
continue;
}
let body = body(&text[start..end], lang);
if !sentence_shaped(&body) {
continue;
}
let parts: Vec<(usize, String)> = body.split('\n').map(|part| (first, part.to_string())).collect();
docs::matches(&mut found, &parts, rules, false);
}
found
}
pub fn run(ruleset: &Ruleset, root: &Root, options: &Options) -> Result<Output, String> {
let rules = DocRules::parse(ruleset.strings.as_deref().unwrap_or_default(), "strings.txt")?;
let results = root.walk(options, |path, buffer| {
let read = Lang::of_suffix(path.rsplit('/').next().unwrap_or(path)).is_some_and(reads);
let found = if read {
check(rules, path, &walk::read(&root.path, path, buffer).unwrap_or_default())
} else {
Vec::new()
};
let lines: String =
found.iter().map(|(line, rule, hit, _)| format!("{path}:{line}: reject: {rule}: {hit}\n")).collect();
let names: BTreeSet<&'static str> = found.iter().map(|f| f.1).collect();
(lines, names)
})?;
let mut out = Output::default();
let mut names = BTreeSet::new();
for (_, (lines, found)) in results {
out.stdout.push_str(&lines);
names.extend(found);
}
if !names.is_empty() {
out.stderr += &format!("Strings of {} found:\n", ruleset.name);
for name in &names {
out.stderr += &format!(" {name}: {}\n", rules.advice(name));
}
out.stderr += &format!("\n{}", ruleset.strings_advice);
}
out.failed = !names.is_empty();
Ok(out)
}