use std::collections::{HashMap, HashSet};
use crate::finding::ModuleFact;
use super::lexer::{is_ident_byte, strip_comments_and_strings, strip_macro_bodies};
use super::path_vocab::{
brace_content, canonical_module_path, canonical_segment, effective_module, inline_mod_at,
is_crate_root_shadow, path_within, resolve_self_super, split_top_commas,
};
struct ResolveCtx {
defs: HashMap<String, String>,
glob_reexports: Vec<(String, String)>,
}
pub(crate) struct InlineFinding {
pub fact: ModuleFact,
pub file: String,
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn inline_symbol_findings(
all_files: &[(std::path::PathBuf, String)],
governed: &[(std::path::PathBuf, String)],
root_modules: &[String],
prefix: &str,
ending_with: Option<&[String]>,
strict: bool,
external: bool,
dependency_names: &[String],
) -> Result<Vec<InlineFinding>, String> {
let prefix = canonical_module_path(prefix);
let verbs: Option<Vec<String>> =
ending_with.map(|vs| vs.iter().map(|v| canonical_module_path(v)).collect());
let mut ctx = ResolveCtx {
defs: HashMap::new(),
glob_reexports: Vec::new(),
};
let mut file_text: HashMap<std::path::PathBuf, String> = HashMap::new();
let mut use_maps: HashMap<std::path::PathBuf, HashMap<String, String>> = HashMap::new();
let mut module_paths: HashSet<String> = HashSet::new();
let mut item_defs: HashSet<String> = HashSet::new();
for (file, module) in all_files {
let raw = std::fs::read_to_string(file)
.map_err(|err| crate::errors::unreadable_governed_file_error(file, &err.to_string()))?;
let decl_text = strip_macro_bodies(&strip_comments_and_strings(&raw));
let use_map = collect_use_map(&decl_text, module, root_modules);
collect_defs(&decl_text, module, root_modules, &use_map, &mut ctx);
if external {
module_paths.insert(module.clone());
collect_item_definition_names(module, &decl_text, &mut item_defs);
}
use_maps.insert(file.clone(), use_map);
file_text.insert(file.clone(), raw);
}
let dep_names: HashSet<String> = if external {
dependency_names.iter().cloned().collect()
} else {
HashSet::new()
};
let external_vocab = external.then_some(ExternalVocab {
module_paths: &module_paths,
item_defs: &item_defs,
dep_names: &dep_names,
});
let mut findings: Vec<InlineFinding> = Vec::new();
for (file, module) in governed {
let raw = &file_text[file];
let use_map = &use_maps[file];
let decl_text = strip_macro_bodies(&strip_comments_and_strings(raw));
let mut chase_defs = ctx.defs.clone();
for (alias, target) in use_map {
chase_defs
.entry(format!("{module}::{alias}"))
.or_insert_with(|| target.clone());
}
for glob_path in glob_import_paths(&decl_text) {
if let Some(resolved) = resolve_head(
&glob_path,
module,
module,
use_map,
root_modules,
external_vocab.as_ref(),
) {
if glob_reaches_prefix(&resolved, &prefix, &ctx, &mut HashSet::new()) {
findings.push(InlineFinding {
fact: ModuleFact::InlineGlob {
path: glob_path,
module: module.clone(),
},
file: file.display().to_string(),
});
}
}
}
let call_text = strip_comments_and_strings(raw);
for occurrence in path_occurrences(&call_text, module, external) {
let Some(resolved) = resolve_head(
&occurrence.segments,
module,
&occurrence.module,
use_map,
root_modules,
external_vocab.as_ref(),
) else {
continue; };
let resolved = chase_closure(&resolved, &chase_defs, &mut HashSet::new());
if !path_within(&resolved, &prefix) {
continue;
}
let react = if strict {
true } else if !occurrence.is_call {
false } else if let Some(verbs) = &verbs {
resolved
.rsplit("::")
.next()
.is_some_and(|leaf| verbs.iter().any(|v| v == leaf))
} else {
true };
if react {
findings.push(InlineFinding {
fact: ModuleFact::InlinePath {
path: resolved,
module: module.clone(),
},
file: file.display().to_string(),
});
}
}
}
findings.sort_by(|a, b| a.fact.cmp(&b.fact).then(a.file.cmp(&b.file)));
findings.dedup_by(|a, b| a.fact == b.fact);
Ok(findings)
}
struct PathOccurrence {
segments: String,
is_call: bool,
module: String,
}
fn path_occurrences(source: &str, base_module: &str, external: bool) -> Vec<PathOccurrence> {
let bytes = source.as_bytes();
let mut out = Vec::new();
let mut i = 0;
let mut depth = 0usize;
let mut mod_stack: Vec<(String, usize)> = Vec::new();
while i < bytes.len() {
if external {
if let Some((name_start, name_end, brace)) = inline_mod_at(bytes, i) {
mod_stack.push((
canonical_segment(&normalize_segments(&bytes[name_start..name_end]))
.to_string(),
depth,
));
i = brace; continue;
}
match bytes[i] {
b'{' => {
depth += 1;
i += 1;
continue;
}
b'}' => {
depth = depth.saturating_sub(1);
while mod_stack.last().is_some_and(|(_, d)| *d == depth) {
mod_stack.pop();
}
i += 1;
continue;
}
_ => {}
}
}
if !is_ident_byte(bytes[i]) || bytes[i].is_ascii_digit() {
i += 1;
continue;
}
let prev = i.checked_sub(1).map(|p| bytes[p]);
if prev.is_some_and(is_ident_byte) || prev == Some(b'.') {
i = end_of_ident(bytes, i);
continue;
}
let start = i;
let mut end = end_of_ident(bytes, i);
loop {
let j = skip_ws(bytes, end);
if bytes.get(j) == Some(&b':') && bytes.get(j + 1) == Some(&b':') {
let after = skip_ws(bytes, j + 2);
if bytes
.get(after)
.is_some_and(|b| is_ident_byte(*b) && !b.is_ascii_digit())
{
end = end_of_ident(bytes, after);
continue;
}
if bytes.get(after) == Some(&b'<') {
end = skip_angles(bytes, after);
continue;
}
}
break;
}
let segments = normalize_segments(&bytes[start..end]);
let is_call = is_call_application(bytes, end);
if segments.contains("::") || is_call {
let module = if external {
effective_module(base_module, &mod_stack)
} else {
base_module.to_string()
};
out.push(PathOccurrence {
segments,
is_call,
module,
});
}
i = end.max(i + 1);
}
out
}
fn end_of_ident(bytes: &[u8], i: usize) -> usize {
let mut j = i;
if bytes.get(j) == Some(&b'r') && bytes.get(j + 1) == Some(&b'#') {
j += 2;
}
while j < bytes.len() && is_ident_byte(bytes[j]) {
j += 1;
}
j.max(i + 1)
}
fn skip_ws(bytes: &[u8], i: usize) -> usize {
let mut j = i;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
j
}
fn skip_angles(bytes: &[u8], start: usize) -> usize {
let mut depth = 0usize;
let mut k = start;
while k < bytes.len() {
match bytes[k] {
b'<' => depth += 1,
b'>' => {
depth -= 1;
if depth == 0 {
return k + 1;
}
}
_ => {}
}
k += 1;
}
bytes.len()
}
fn normalize_segments(span: &[u8]) -> String {
let mut segs: Vec<String> = Vec::new();
let mut k = 0;
while k < span.len() {
if span[k] == b'<' {
k = skip_angles(span, k);
} else if is_ident_byte(span[k]) || (span[k] == b'r' && span.get(k + 1) == Some(&b'#')) {
let s = end_of_ident(span, k);
let seg = String::from_utf8_lossy(&span[k..s]).into_owned();
segs.push(seg.strip_prefix("r#").unwrap_or(&seg).to_string());
k = s;
} else {
k += 1;
}
}
segs.join("::")
}
fn is_call_application(bytes: &[u8], end: usize) -> bool {
let mut j = skip_ws(bytes, end);
if bytes.get(j) == Some(&b':') && bytes.get(j + 1) == Some(&b':') {
let after = skip_ws(bytes, j + 2);
if bytes.get(after) == Some(&b'<') {
j = skip_ws(bytes, skip_angles(bytes, after));
}
}
bytes.get(j) == Some(&b'(')
}
fn glob_import_paths(source: &str) -> Vec<String> {
let mut paths = Vec::new();
for tree in use_statements(source) {
glob_bases(&tree, &mut paths, 0);
}
paths
}
fn glob_bases(tree: &str, out: &mut Vec<String>, depth: usize) {
if depth > 64 {
return;
}
let tree = tree.trim();
match tree.find('{') {
Some(open) => {
let prefix = tree[..open].trim();
for part in split_top_commas(&brace_content(&tree[open..])) {
let part = part.trim();
if part.is_empty() {
continue;
}
if part == "*" {
let base = prefix.trim_end_matches(':').trim();
if !base.is_empty() {
out.push(base.to_string());
}
} else {
glob_bases(&format!("{prefix}{part}"), out, depth + 1);
}
}
}
None => {
if let Some(base) = tree.strip_suffix("::*") {
let base = base.trim();
if !base.is_empty() {
out.push(base.to_string());
}
}
}
}
}
fn use_statements(source: &str) -> Vec<String> {
let bytes = source.as_bytes();
let mut trees = Vec::new();
let mut i = 0;
while i < bytes.len() {
if super::lexer::keyword_starts_at(bytes, i, b"use") {
let start = i + 3;
let mut p = start;
while p < bytes.len() && bytes[p].is_ascii_whitespace() {
p += 1;
}
if bytes.get(p) == Some(&b'<') {
i = start; continue;
}
if let Some(rel) = source[start..].find(';') {
trees.push(source[start..start + rel].trim().to_string());
i = start + rel + 1;
continue;
}
break;
}
i += 1;
}
trees
}
fn collect_use_map(
source: &str,
current_module: &str,
root_modules: &[String],
) -> HashMap<String, String> {
let mut map = HashMap::new();
for tree in use_statements(source) {
for (alias, path) in expand_use_leaves(&tree) {
if let Some(canonical) = resolve_written_path(&path, current_module, root_modules) {
map.insert(alias, canonical);
}
}
}
map
}
fn expand_use_leaves(tree: &str) -> Vec<(String, String)> {
fn go(tree: &str, out: &mut Vec<(String, String)>, depth: usize) {
if depth > 64 {
return;
}
let tree = tree.trim();
match tree.find('{') {
Some(open) => {
let prefix = tree[..open].trim();
let inner = brace_content(&tree[open..]);
for part in split_top_commas(&inner) {
let part = part.trim();
let head = match part.find(" as ") {
Some(idx) => part[..idx].trim(),
None => part,
};
if part.is_empty() || part == "*" || head == "self" {
continue;
}
go(&format!("{prefix}{part}"), out, depth + 1);
}
}
None => {
if tree.ends_with("::*") || tree.is_empty() {
return;
}
let (path, alias) = match tree.split_once(" as ") {
Some((p, a)) => (p.trim().to_string(), a.trim().to_string()),
None => {
let leaf = tree.rsplit("::").next().unwrap_or(tree).trim();
(tree.to_string(), leaf.to_string())
}
};
let alias = canonical_module_path(&alias);
if !alias.is_empty() {
out.push((alias, path));
}
}
}
}
let mut out = Vec::new();
go(tree, &mut out, 0);
out
}
fn collect_defs(
source: &str,
module: &str,
root_modules: &[String],
use_map: &HashMap<String, String>,
ctx: &mut ResolveCtx,
) {
for (name, target) in type_aliases(source) {
if let Some(canonical) = resolve_target(&target, module, use_map, root_modules) {
ctx.defs.insert(
format!("{module}::{}", canonical_module_path(&name)),
canonical,
);
}
}
for tree in pub_use_statements(source) {
let mut globs = Vec::new();
glob_bases(&tree, &mut globs, 0);
for base in globs {
if let Some(canonical) = resolve_written_path(&base, module, root_modules) {
ctx.glob_reexports.push((module.to_string(), canonical));
}
}
for (alias, path) in expand_use_leaves(&tree) {
if let Some(canonical) = resolve_written_path(&path, module, root_modules) {
ctx.defs.insert(format!("{module}::{alias}"), canonical);
}
}
}
}
fn collect_item_definition_names(module: &str, source: &str, out: &mut HashSet<String>) {
const KEYWORDS: [&[u8]; 9] = [
b"mod", b"struct", b"enum", b"union", b"trait", b"type", b"fn", b"const", b"static",
];
let bytes = source.as_bytes();
let mut i = 0;
let mut depth = 0usize;
let mut mod_stack: Vec<(String, usize)> = Vec::new();
while i < bytes.len() {
let top = mod_stack.last().map_or(0, |(_, d)| d + 1);
if let Some((name_start, name_end, brace)) = inline_mod_at(bytes, i) {
let name = normalize_segments(&bytes[name_start..name_end]);
if depth == top && !name.is_empty() {
out.insert(format!("{}::{name}", effective_module(module, &mod_stack)));
}
mod_stack.push((canonical_segment(name.trim()).to_string(), depth));
i = brace; continue;
}
match bytes[i] {
b'{' => {
depth += 1;
i += 1;
continue;
}
b'}' => {
depth = depth.saturating_sub(1);
while mod_stack.last().is_some_and(|(_, d)| *d == depth) {
mod_stack.pop();
}
i += 1;
continue;
}
_ => {}
}
if !is_ident_byte(bytes[i]) {
i += 1;
continue;
}
if depth == top {
if let Some(kw) = KEYWORDS
.iter()
.find(|kw| super::lexer::keyword_starts_at(bytes, i, kw))
{
let name_start = skip_ws(bytes, i + kw.len());
if bytes.get(name_start).is_some_and(|b| is_ident_byte(*b)) {
let name =
normalize_segments(&bytes[name_start..end_of_ident(bytes, name_start)]);
if !name.is_empty() {
out.insert(format!("{}::{name}", effective_module(module, &mod_stack)));
}
}
}
}
i = end_of_ident(bytes, i);
}
}
fn type_aliases(source: &str) -> Vec<(String, String)> {
let bytes = source.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < bytes.len() {
if super::lexer::keyword_starts_at(bytes, i, b"type") {
let mut j = i + 4;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
let name_start = j;
while j < bytes.len() && is_ident_byte(bytes[j]) {
j += 1;
}
let name = source[name_start..j].to_string();
while j < bytes.len() && bytes[j] != b'=' && bytes[j] != b';' {
if bytes[j] == b'<' {
j = skip_angles(bytes, j);
} else {
j += 1;
}
}
if !name.is_empty() && bytes.get(j) == Some(&b'=') {
if let Some(end) = alias_target_end(bytes, j + 1) {
let target = source[j + 1..end].trim();
let target_path = leading_path(target);
if !target_path.is_empty() {
out.push((name, target_path));
}
i = end + 1;
continue;
}
}
i = j.max(i + 1);
continue;
}
i += 1;
}
out
}
fn alias_target_end(bytes: &[u8], from: usize) -> Option<usize> {
let mut depth = 0i32;
let mut k = from;
while k < bytes.len() {
match bytes[k] {
b'<' => {
k = skip_angles(bytes, k);
continue;
}
b'[' | b'(' | b'{' => depth += 1,
b']' | b')' | b'}' => depth -= 1,
b';' if depth <= 0 => return Some(k),
_ => {}
}
k += 1;
}
None
}
fn leading_path(expr: &str) -> String {
let expr = expr.trim_start_matches(['&', ' ', '*']);
let bytes = expr.as_bytes();
let mut j = 0;
while j < bytes.len() && (is_ident_byte(bytes[j]) || bytes[j] == b':') {
j += 1;
}
expr[..j].trim_end_matches(':').to_string()
}
fn pub_use_statements(source: &str) -> Vec<String> {
let bytes = source.as_bytes();
let mut trees = Vec::new();
let mut i = 0;
while i < bytes.len() {
if super::lexer::keyword_starts_at(bytes, i, b"pub") {
let mut j = i + 3;
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
if bytes.get(j) == Some(&b'(') {
let mut depth = 0usize;
while j < bytes.len() {
match bytes[j] {
b'(' => depth += 1,
b')' => {
depth -= 1;
if depth == 0 {
j += 1;
break;
}
}
_ => {}
}
j += 1;
}
while j < bytes.len() && bytes[j].is_ascii_whitespace() {
j += 1;
}
}
if super::lexer::keyword_starts_at(bytes, j, b"use") {
let start = j + 3;
if let Some(rel) = source[start..].find(';') {
trees.push(source[start..start + rel].trim().to_string());
i = start + rel + 1;
continue;
}
break;
}
}
i += 1;
}
trees
}
struct ExternalVocab<'a> {
module_paths: &'a HashSet<String>,
item_defs: &'a HashSet<String>,
dep_names: &'a HashSet<String>,
}
fn head_is_external_dependency(
head: &str,
occurrence_module: &str,
root_modules: &[String],
vocab: &ExternalVocab,
) -> bool {
let locally_shadowed = is_crate_root_shadow(occurrence_module, head, root_modules)
|| vocab
.module_paths
.contains(&format!("{occurrence_module}::{head}"))
|| vocab
.item_defs
.contains(&format!("{occurrence_module}::{head}"));
!locally_shadowed && vocab.dep_names.contains(head)
}
fn resolve_head(
segments: &str,
current_module: &str,
occurrence_module: &str,
use_map: &HashMap<String, String>,
root_modules: &[String],
external: Option<&ExternalVocab>,
) -> Option<String> {
let raw = segments.trim().trim_start_matches("::");
let parts: Vec<String> = raw
.split("::")
.map(|s| canonical_module_path(s.trim()))
.filter(|s| !s.is_empty())
.collect();
let (head, rest) = parts.split_first()?;
let parts_str: Vec<&str> = parts.iter().map(String::as_str).collect();
let base: String = match head.as_str() {
"std" | "core" | "alloc" => parts.join("::"),
"crate" => parts.join("::"),
"self" | "super" => resolve_self_super(current_module, &parts_str)?,
other => {
if let Some(target) = use_map.get(other) {
let mut base = target.clone();
for seg in rest {
base.push_str("::");
base.push_str(seg);
}
base
} else if external.is_some_and(|v| {
head_is_external_dependency(other, occurrence_module, root_modules, v)
}) {
parts.join("::")
} else {
format!("{current_module}::{}", parts.join("::"))
}
}
};
Some(base)
}
fn chase_closure(
path: &str,
defs: &HashMap<String, String>,
visited: &mut HashSet<String>,
) -> String {
let mut current = path.to_string();
for _ in 0..256 {
if !visited.insert(current.clone()) {
return current; }
let mut matched: Option<(String, String)> = None;
let segments: Vec<&str> = current.split("::").collect();
for take in (1..=segments.len()).rev() {
let key = segments[..take].join("::");
if let Some(target) = defs.get(&key) {
let remainder = &segments[take..];
let mut next = target.clone();
for seg in remainder {
next.push_str("::");
next.push_str(seg);
}
matched = Some((key, next));
break;
}
}
match matched {
Some((_, next)) => current = next,
None => return current,
}
}
current }
fn glob_reaches_prefix(
glob: &str,
prefix: &str,
ctx: &ResolveCtx,
visited: &mut HashSet<String>,
) -> bool {
if !visited.insert(glob.to_string()) {
return false; }
if path_within(glob, prefix) || path_within(prefix, glob) {
return true;
}
for (name, target) in &ctx.defs {
if path_within(name, glob) {
let resolved = chase_closure(target, &ctx.defs, &mut HashSet::new());
if path_within(&resolved, prefix) {
return true;
}
}
}
let inner: Vec<String> = ctx
.glob_reexports
.iter()
.filter(|(module, _)| path_within(module, glob))
.map(|(_, gp)| gp.clone())
.collect();
for gp in inner {
if glob_reaches_prefix(&gp, prefix, ctx, visited) {
return true;
}
}
false
}
fn resolve_written_path(
path: &str,
current_module: &str,
root_modules: &[String],
) -> Option<String> {
let raw = path.trim();
let global = raw.starts_with("::");
let parts: Vec<String> = raw
.trim_start_matches("::")
.split("::")
.map(|s| canonical_module_path(s.trim()))
.filter(|s| !s.is_empty())
.collect();
let (head, _rest) = parts.split_first()?;
let parts_str: Vec<&str> = parts.iter().map(String::as_str).collect();
match head.as_str() {
"crate" | "std" | "core" | "alloc" => Some(parts.join("::")),
_ if global => Some(parts.join("::")), "self" | "super" => resolve_self_super(current_module, &parts_str),
other => {
if is_crate_root_shadow(current_module, other, root_modules) {
let mut out = vec!["crate".to_string()];
out.extend(parts.iter().cloned());
Some(out.join("::"))
} else {
Some(parts.join("::"))
}
}
}
}
fn resolve_target(
target: &str,
module: &str,
use_map: &HashMap<String, String>,
root_modules: &[String],
) -> Option<String> {
let raw = target.trim();
if raw.starts_with("::") {
return resolve_written_path(raw, module, root_modules);
}
let parts: Vec<String> = raw
.split("::")
.map(|s| canonical_module_path(s.trim()))
.filter(|s| !s.is_empty())
.collect();
let (head, rest) = parts.split_first()?;
if let Some(mapped) = use_map.get(head) {
let mut base = mapped.clone();
for seg in rest {
base.push_str("::");
base.push_str(seg);
}
return Some(base);
}
match head.as_str() {
"std" | "core" | "alloc" | "crate" => Some(parts.join("::")),
"self" | "super" => resolve_written_path(raw, module, root_modules),
_ => Some(format!("{module}::{}", parts.join("::"))),
}
}