use super::*;
use std::collections::BTreeMap;
pub(crate) fn is_test_path(path: &Path) -> bool {
path.components()
.any(|component| component.as_os_str().to_str() == Some("tests"))
|| is_cfg_test_module_file(path)
}
fn is_cfg_test_module_file(path: &Path) -> bool {
is_test_only_module(path, &mut Vec::new())
}
fn is_test_only_module(path: &Path, visiting: &mut Vec<PathBuf>) -> bool {
if visiting.iter().any(|seen| seen == path) {
return false;
}
visiting.push(path.to_path_buf());
let test_only = owners_are_test_only(path, visiting);
visiting.pop();
test_only
}
fn owners_are_test_only(path: &Path, visiting: &mut Vec<PathBuf>) -> bool {
let (Some(stem), Some(dir)) = (path.file_stem().and_then(|s| s.to_str()), path.parent()) else {
return false;
};
let (name, module_dir) = match stem {
"lib" | "main" => return false,
"mod" => match (dir.file_name().and_then(|n| n.to_str()), dir.parent()) {
(Some(name), Some(parent)) => (name, parent),
_ => return false,
},
name => (name, dir),
};
let mut parents = vec![
module_dir.join("mod.rs"),
module_dir.join("lib.rs"),
module_dir.join("main.rs"),
];
if let (Some(dir_name), Some(outer)) = (
module_dir.file_name().and_then(|n| n.to_str()),
module_dir.parent(),
) {
parents.push(outer.join(format!("{dir_name}.rs")));
}
let mut test_owner = false;
for parent in &parents {
let Some(test_only) = module_declarations(parent).and_then(|d| d.names.get(name).copied())
else {
continue;
};
if test_only || is_test_only_module(parent, visiting) {
test_owner = true;
} else {
return false;
}
}
match path_owners_are_test_only(path, dir, visiting) {
Some(test_only) => test_only,
None => test_owner,
}
}
fn path_owners_are_test_only(path: &Path, dir: &Path, visiting: &mut Vec<PathBuf>) -> Option<bool> {
let file_name = path.file_name().and_then(|name| name.to_str())?;
let entries = std::fs::read_dir(dir).ok()?;
let mut test_owner = None;
for sibling in entries.flatten().map(|entry| entry.path()) {
if sibling == path || sibling.extension().is_none_or(|ext| ext != "rs") {
continue;
}
let Some(test_only) =
module_declarations(&sibling).and_then(|d| d.paths.get(file_name).copied())
else {
continue;
};
if test_only || is_test_only_module(&sibling, visiting) {
test_owner = Some(true);
} else {
return Some(false);
}
}
test_owner
}
#[derive(Debug, Default)]
struct ModuleDeclarations {
names: BTreeMap<String, bool>,
paths: BTreeMap<String, bool>,
}
fn parse_module_declarations(source: &str) -> ModuleDeclarations {
let mut declarations = ModuleDeclarations::default();
for (name, test_only, path) in crate::source::top_level_module_declarations(source) {
let map = match path {
Some(path) => declarations.paths.entry(path),
None => declarations.names.entry(name),
};
map.and_modify(|all_test| *all_test &= test_only)
.or_insert(test_only);
}
declarations
}
thread_local! {
static SOURCE_OVERRIDES: std::cell::RefCell<
HashMap<PathBuf, (String, Option<std::sync::Arc<ModuleDeclarations>>)>,
> = Default::default();
}
pub(crate) struct SourceOverrides {
previous: HashMap<PathBuf, (String, Option<std::sync::Arc<ModuleDeclarations>>)>,
}
impl SourceOverrides {
pub(crate) fn install(sources: impl IntoIterator<Item = (PathBuf, String)>) -> Self {
let overrides = sources
.into_iter()
.map(|(path, source)| (path, (source, None)))
.collect();
let previous = SOURCE_OVERRIDES.with(|cell| cell.replace(overrides));
Self { previous }
}
}
impl Drop for SourceOverrides {
fn drop(&mut self) {
let previous = std::mem::take(&mut self.previous);
SOURCE_OVERRIDES.with(|cell| *cell.borrow_mut() = previous);
}
}
fn module_declarations(parent: &Path) -> Option<std::sync::Arc<ModuleDeclarations>> {
use std::sync::{Arc, Mutex, OnceLock};
type Stamp = (std::time::SystemTime, u64);
static CACHE: OnceLock<Mutex<HashMap<PathBuf, (Stamp, Arc<ModuleDeclarations>)>>> =
OnceLock::new();
if let Some(declarations) = SOURCE_OVERRIDES.with(|cell| {
let mut overrides = cell.borrow_mut();
let (source, parsed) = overrides.get_mut(parent)?;
Some(Arc::clone(parsed.get_or_insert_with(|| {
Arc::new(parse_module_declarations(source))
})))
}) {
return Some(declarations);
}
let metadata = std::fs::metadata(parent).ok()?;
let stamp = (metadata.modified().ok()?, metadata.len());
let cache = CACHE.get_or_init(Default::default);
let lock = || {
cache
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
};
if let Some((cached, declarations)) = lock().get(parent) {
if *cached == stamp {
return Some(Arc::clone(declarations));
}
}
let declarations = Arc::new(parse_module_declarations(
&std::fs::read_to_string(parent).ok()?,
));
lock().insert(parent.to_path_buf(), (stamp, Arc::clone(&declarations)));
Some(declarations)
}
pub(crate) fn cfg_test_module_line_ranges(source: &str) -> Vec<RangeInclusive<usize>> {
let mut ranges = Vec::new();
let mut cfg_test_pending = false;
let mut active_start = None;
let mut depth = 0isize;
for (idx, line) in source.lines().enumerate() {
let line_no = idx + 1;
let stripped = line.trim();
if active_start.is_some() {
depth += brace_delta(line);
if depth <= 0 {
ranges.push(active_start.take().unwrap()..=line_no);
depth = 0;
}
continue;
}
if stripped.starts_with("#[cfg(test)]") {
cfg_test_pending = true;
continue;
}
if cfg_test_pending && stripped.contains("mod tests") {
if line.contains('{') {
active_start = Some(line_no);
depth = brace_delta(line).max(1);
if depth <= 0 {
ranges.push(line_no..=line_no);
active_start = None;
depth = 0;
}
}
cfg_test_pending = false;
continue;
}
if !stripped.is_empty() && !stripped.starts_with("#[") {
cfg_test_pending = false;
}
}
if let Some(start) = active_start {
ranges.push(start..=source.lines().count().max(start));
}
ranges
}
pub(crate) fn brace_delta(line: &str) -> isize {
line.bytes().fold(0, |acc, byte| match byte {
b'{' => acc + 1,
b'}' => acc - 1,
_ => acc,
})
}
pub(crate) fn line_in_ranges(line: usize, ranges: &[RangeInclusive<usize>]) -> bool {
ranges.iter().any(|range| range.contains(&line))
}
pub(crate) fn dedupe_diagnostics(diagnostics: &mut Vec<Diagnostic>) {
let mut seen = HashSet::new();
let keep: Vec<bool> = diagnostics
.iter()
.map(|diag| {
seen.insert((
diag.path.as_path(),
diag.line,
diag.column,
diag.code,
diag.message.as_str(),
))
})
.collect();
drop(seen);
let mut keep = keep.into_iter();
diagnostics.retain(|_| keep.next().unwrap_or(true));
}