#[allow(clippy::too_many_arguments)]
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_analyze_symbol_table(
project_path: PathBuf,
format: crate::cli::SymbolTableOutputFormat,
filter: Option<crate::cli::SymbolTypeFilter>,
query: Option<String>,
include: &[String],
exclude: &[String],
show_unreferenced: bool,
show_references: bool,
output: Option<PathBuf>,
_perf: bool,
top_files: usize,
) -> Result<()> {
crate::cli::ensure_analysis_path_exists(&project_path)?;
eprintln!("🔍 Building symbol table for project...");
let table = build_symbol_table(&project_path, include, exclude, top_files).await?;
let filtered = apply_filters(table, filter, query, top_files)?;
let content = format_output(filtered, format, show_unreferenced, show_references, top_files)?;
if let Some(output_path) = output {
tokio::fs::write(&output_path, &content).await?;
eprintln!("✅ Symbol table written to: {}", output_path.display());
} else {
println!("{content}");
}
Ok(())
}
async fn build_symbol_table(
project_path: &Path,
include: &[String],
exclude: &[String],
top_files: usize,
) -> Result<SymbolTable> {
let files = collect_files(project_path, include, exclude).await?;
let mut sources = Vec::with_capacity(files.len());
for file in files {
let content = tokio::fs::read_to_string(&file).await?;
sources.push(FileSource {
path: file.to_string_lossy().to_string(),
content,
});
}
let mut symbols = Vec::new();
for source in &sources {
symbols.extend(extract_symbols_simple(&source.content, &source.path)?);
}
let unresolved = resolve_references(&sources, &mut symbols);
let unreferenced = find_unreferenced_symbols(&symbols, &unresolved);
let (most_referenced, referenced_symbol_count) = find_most_referenced(&symbols, top_files);
Ok(SymbolTable {
total_symbols: symbols.len(),
symbols,
unreferenced_symbols: unreferenced,
most_referenced,
referenced_symbol_count,
})
}
async fn collect_files(
project_path: &Path,
include: &[String],
exclude: &[String],
) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
if project_path.is_file() {
process_file(project_path.to_path_buf(), &mut files, include)?;
return Ok(files);
}
collect_files_recursive(project_path, &mut files, include, exclude).await?;
files.sort();
Ok(files)
}
async fn collect_files_recursive(
dir: &Path,
files: &mut Vec<PathBuf>,
include: &[String],
exclude: &[String],
) -> Result<()> {
let mut entries = tokio::fs::read_dir(dir).await?;
while let Some(entry) = entries.next_entry().await? {
process_directory_entry(entry, files, include, exclude).await?;
}
Ok(())
}
async fn process_directory_entry(
entry: tokio::fs::DirEntry,
files: &mut Vec<PathBuf>,
include: &[String],
exclude: &[String],
) -> Result<()> {
let path = entry.path();
if should_skip_path(&path, exclude) {
return Ok(());
}
if path.is_dir() {
process_directory(&path, files, include, exclude).await
} else {
process_file(path, files, include)
}
}
fn should_skip_path(path: &Path, exclude: &[String]) -> bool {
exclude.iter().any(|pattern| matches_pattern(path, pattern))
}
async fn process_directory(
path: &Path,
files: &mut Vec<PathBuf>,
include: &[String],
exclude: &[String],
) -> Result<()> {
if should_process_directory(path) {
Box::pin(collect_files_recursive(path, files, include, exclude)).await?;
}
Ok(())
}
fn should_process_directory(path: &Path) -> bool {
let name = path.file_name().unwrap_or_default().to_string_lossy();
!name.starts_with('.') && name != "node_modules" && name != "target"
}
fn process_file(path: PathBuf, files: &mut Vec<PathBuf>, include: &[String]) -> Result<()> {
if !is_source_file(&path) {
return Ok(());
}
if should_include_file(&path, include) {
files.push(path);
}
Ok(())
}
fn should_include_file(path: &Path, include: &[String]) -> bool {
include.is_empty() || include.iter().any(|pattern| matches_pattern(path, pattern))
}
fn matches_pattern(path: &Path, pattern: &str) -> bool {
if pattern.is_empty() {
return false;
}
let path_str = path.to_string_lossy();
if pattern.contains('*') || pattern.contains('?') || pattern.contains('[') {
if let Ok(glob) = glob::Pattern::new(pattern) {
let file_name = path.file_name().map(|n| n.to_string_lossy().to_string());
return glob.matches(&path_str)
|| file_name.is_some_and(|name| glob.matches(&name));
}
}
path_str.contains(pattern)
}
fn is_source_file(path: &Path) -> bool {
matches!(
path.extension().and_then(|s| s.to_str()),
Some("rs" | "js" | "ts" | "py" | "java" | "cpp" | "c" | "h" | "hpp" | "go" | "rb")
)
}
fn extract_symbols_simple(content: &str, file: &str) -> Result<Vec<Symbol>> {
use regex::Regex;
let mut symbols = Vec::new();
let patterns = vec![
(
Regex::new(r"(?m)^(?:pub\s+)?(?:async\s+)?fn\s+(\w+)")?,
SymbolKind::Function,
),
(Regex::new(r"(?m)^class\s+(\w+)")?, SymbolKind::Class),
(
Regex::new(r"(?m)^(?:export\s+)?(?:async\s+)?function\s+(\w+)")?,
SymbolKind::Function,
),
(Regex::new(r"(?m)^def\s+(\w+)")?, SymbolKind::Function),
(
Regex::new(r"(?m)^(?:pub\s+)?const\s+(\w+)")?,
SymbolKind::Constant,
),
(
Regex::new(r"(?m)^(?:pub\s+)?static\s+(\w+)")?,
SymbolKind::Variable,
),
(
Regex::new(r"(?m)^(?:pub\s+)?mod\s+(\w+)")?,
SymbolKind::Module,
),
(
Regex::new(r"(?m)^(?:pub\s+)?struct\s+(\w+)")?,
SymbolKind::Type,
),
(
Regex::new(r"(?m)^(?:pub\s+)?enum\s+(\w+)")?,
SymbolKind::Enum,
),
(
Regex::new(r"(?m)^interface\s+(\w+)")?,
SymbolKind::Interface,
),
];
for (line_no, line) in content.lines().enumerate() {
for (pattern, kind) in &patterns {
if let Some(captures) = pattern.captures(line) {
if let Some(name) = captures.get(1) {
symbols.push(Symbol {
name: name.as_str().to_string(),
kind: kind.clone(),
file: file.to_string(),
line: line_no + 1,
column: name.start(),
visibility: detect_visibility(&line[..name.start()]),
references: vec![Reference {
file: file.to_string(),
line: line_no + 1,
column: name.start(),
kind: ReferenceKind::Definition,
}],
});
}
}
}
}
Ok(symbols)
}
fn detect_visibility(prefix: &str) -> Visibility {
if prefix.contains("pub ") || prefix.contains("export ") {
Visibility::Public
} else if prefix.contains("private ") {
Visibility::Private
} else if prefix.contains("protected ") {
Visibility::Protected
} else {
Visibility::Internal
}
}
fn usage_counts_by_name(symbols: &[Symbol]) -> HashMap<&str, usize> {
let mut counts: HashMap<&str, usize> = HashMap::new();
for symbol in symbols {
*counts.entry(symbol.name.as_str()).or_insert(0) += usage_count(symbol);
}
counts
}
fn find_unreferenced_symbols(symbols: &[Symbol], unresolved: &HashSet<String>) -> Vec<String> {
let counts = usage_counts_by_name(symbols);
let mut names: Vec<String> = counts
.into_iter()
.filter(|(name, count)| *count == 0 && !unresolved.contains(*name))
.map(|(name, _)| name.to_string())
.collect();
names.sort();
names
}
fn find_most_referenced(symbols: &[Symbol], limit: usize) -> (Vec<(String, usize)>, usize) {
let mut refs: Vec<(String, usize)> = usage_counts_by_name(symbols)
.into_iter()
.filter(|(_, count)| *count > 0)
.map(|(name, count)| (name.to_string(), count))
.collect();
refs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let total = refs.len();
if limit > 0 {
refs.truncate(limit);
}
(refs, total)
}