pub mod ast_cache;
pub mod command_parser;
pub mod dependency_graph;
pub mod struct_parser;
pub mod type_resolver;
pub mod validator_parser;
use crate::models::{CommandInfo, StructInfo};
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use ast_cache::AstCache;
use command_parser::CommandParser;
use dependency_graph::TypeDependencyGraph;
use struct_parser::StructParser;
use type_resolver::TypeResolver;
pub struct CommandAnalyzer {
ast_cache: AstCache,
command_parser: CommandParser,
struct_parser: StructParser,
type_resolver: TypeResolver,
dependency_graph: TypeDependencyGraph,
discovered_structs: HashMap<String, StructInfo>,
}
impl CommandAnalyzer {
pub fn new() -> Self {
Self {
ast_cache: AstCache::new(),
command_parser: CommandParser::new(),
struct_parser: StructParser::new(),
type_resolver: TypeResolver::new(),
dependency_graph: TypeDependencyGraph::new(),
discovered_structs: HashMap::new(),
}
}
pub fn analyze_project(
&mut self,
project_path: &str,
) -> Result<Vec<CommandInfo>, Box<dyn std::error::Error>> {
self.ast_cache.parse_and_cache_all_files(project_path)?;
let file_paths: Vec<PathBuf> = self.ast_cache.keys().cloned().collect();
let mut commands = Vec::new();
let mut type_names_to_discover = HashSet::new();
for file_path in file_paths {
if let Some(parsed_file) = self.ast_cache.get_cloned(&file_path) {
println!("🔍 Analyzing file: {}", parsed_file.path.display());
let file_commands = self.command_parser.extract_commands_from_ast(
&parsed_file.ast,
parsed_file.path.as_path(),
&mut self.type_resolver,
)?;
file_commands.iter().for_each(|cmd| {
cmd.parameters.iter().for_each(|param| {
self.extract_type_names(¶m.rust_type, &mut type_names_to_discover);
});
self.extract_type_names(&cmd.return_type, &mut type_names_to_discover);
});
commands.extend(file_commands);
self.index_type_definitions(&parsed_file.ast, parsed_file.path.as_path());
}
}
println!("🔍 Type names to discover: {:?}", type_names_to_discover);
self.resolve_types_lazily(&type_names_to_discover)?;
println!(
"🏗️ Discovered {} structs total",
self.discovered_structs.len()
);
for (name, info) in &self.discovered_structs {
println!(" - {}: {} fields", name, info.fields.len());
}
Ok(commands)
}
pub fn analyze_file(
&mut self,
file_path: &std::path::Path,
) -> Result<Vec<CommandInfo>, Box<dyn std::error::Error>> {
let path_buf = file_path.to_path_buf();
match self.ast_cache.parse_and_cache_file(&path_buf) {
Ok(_) => {
if let Some(parsed_file) = self.ast_cache.get_cloned(&path_buf) {
self.command_parser.extract_commands_from_ast(
&parsed_file.ast,
path_buf.as_path(),
&mut self.type_resolver,
)
} else {
Ok(vec![])
}
}
Err(_) => {
Ok(vec![])
}
}
}
fn index_type_definitions(&mut self, ast: &syn::File, file_path: &Path) {
for item in &ast.items {
match item {
syn::Item::Struct(item_struct) => {
if self.struct_parser.should_include_struct(item_struct) {
let struct_name = item_struct.ident.to_string();
self.dependency_graph
.add_type_definition(struct_name, file_path.to_path_buf());
}
}
syn::Item::Enum(item_enum) => {
if self.struct_parser.should_include_enum(item_enum) {
let enum_name = item_enum.ident.to_string();
self.dependency_graph
.add_type_definition(enum_name, file_path.to_path_buf());
}
}
_ => {}
}
}
}
fn resolve_types_lazily(
&mut self,
initial_types: &HashSet<String>,
) -> Result<(), Box<dyn std::error::Error>> {
let mut types_to_resolve: Vec<String> = initial_types.iter().cloned().collect();
let mut resolved_types = HashSet::new();
while let Some(type_name) = types_to_resolve.pop() {
if resolved_types.contains(&type_name)
|| self.discovered_structs.contains_key(&type_name)
{
continue;
}
if let Some(file_path) = self
.dependency_graph
.get_type_definition_path(&type_name)
.cloned()
{
if let Some(parsed_file) = self.ast_cache.get_cloned(&file_path) {
if let Some(struct_info) = self.extract_type_from_ast(
&parsed_file.ast,
&type_name,
file_path.as_path(),
) {
let mut type_dependencies = HashSet::new();
for field in &struct_info.fields {
self.extract_type_names(&field.rust_type, &mut type_dependencies);
}
for dep_type in &type_dependencies {
if !resolved_types.contains(dep_type)
&& !self.discovered_structs.contains_key(dep_type)
&& self.dependency_graph.has_type_definition(dep_type)
{
types_to_resolve.push(dep_type.clone());
}
}
self.dependency_graph
.add_dependencies(type_name.clone(), type_dependencies.clone());
self.dependency_graph
.add_resolved_type(type_name.clone(), struct_info.clone());
self.discovered_structs
.insert(type_name.clone(), struct_info);
resolved_types.insert(type_name);
}
}
}
}
Ok(())
}
fn extract_type_from_ast(
&mut self,
ast: &syn::File,
type_name: &str,
file_path: &Path,
) -> Option<StructInfo> {
for item in &ast.items {
match item {
syn::Item::Struct(item_struct) => {
if item_struct.ident == type_name
&& self.struct_parser.should_include_struct(item_struct)
{
return self.struct_parser.parse_struct(
item_struct,
file_path,
&mut self.type_resolver,
);
}
}
syn::Item::Enum(item_enum) => {
if item_enum.ident == type_name
&& self.struct_parser.should_include_enum(item_enum)
{
return self.struct_parser.parse_enum(
item_enum,
file_path,
&mut self.type_resolver,
);
}
}
_ => {}
}
}
None
}
pub fn extract_type_names(&self, rust_type: &str, type_names: &mut HashSet<String>) {
self.extract_type_names_recursive(rust_type, type_names);
}
fn extract_type_names_recursive(&self, rust_type: &str, type_names: &mut HashSet<String>) {
let rust_type = rust_type.trim();
if rust_type.starts_with("Result<") {
if let Some(inner) = rust_type
.strip_prefix("Result<")
.and_then(|s| s.strip_suffix(">"))
{
if let Some(comma_pos) = inner.find(',') {
let ok_type = inner[..comma_pos].trim();
let err_type = inner[comma_pos + 1..].trim();
self.extract_type_names_recursive(ok_type, type_names);
self.extract_type_names_recursive(err_type, type_names);
}
}
return;
}
if rust_type.starts_with("Option<") {
if let Some(inner) = rust_type
.strip_prefix("Option<")
.and_then(|s| s.strip_suffix(">"))
{
self.extract_type_names_recursive(inner, type_names);
}
return;
}
if rust_type.starts_with("Vec<") {
if let Some(inner) = rust_type
.strip_prefix("Vec<")
.and_then(|s| s.strip_suffix(">"))
{
self.extract_type_names_recursive(inner, type_names);
}
return;
}
if rust_type.starts_with("HashMap<") || rust_type.starts_with("BTreeMap<") {
let prefix = if rust_type.starts_with("HashMap<") {
"HashMap<"
} else {
"BTreeMap<"
};
if let Some(inner) = rust_type
.strip_prefix(prefix)
.and_then(|s| s.strip_suffix(">"))
{
if let Some(comma_pos) = inner.find(',') {
let key_type = inner[..comma_pos].trim();
let value_type = inner[comma_pos + 1..].trim();
self.extract_type_names_recursive(key_type, type_names);
self.extract_type_names_recursive(value_type, type_names);
}
}
return;
}
if rust_type.starts_with("HashSet<") || rust_type.starts_with("BTreeSet<") {
let prefix = if rust_type.starts_with("HashSet<") {
"HashSet<"
} else {
"BTreeSet<"
};
if let Some(inner) = rust_type
.strip_prefix(prefix)
.and_then(|s| s.strip_suffix(">"))
{
self.extract_type_names_recursive(inner, type_names);
}
return;
}
if rust_type.starts_with('(') && rust_type.ends_with(')') && rust_type != "()" {
let inner = &rust_type[1..rust_type.len() - 1];
for part in inner.split(',') {
self.extract_type_names_recursive(part.trim(), type_names);
}
return;
}
if rust_type.starts_with('&') {
let without_ref = rust_type.trim_start_matches('&');
self.extract_type_names_recursive(without_ref, type_names);
return;
}
if !rust_type.is_empty()
&& !self.type_resolver.get_type_mappings().contains_key(rust_type)
&& !rust_type.starts_with(char::is_lowercase) && rust_type.chars().next().is_some_and(char::is_alphabetic)
&& !rust_type.contains('<')
{
type_names.insert(rust_type.to_string());
}
}
pub fn get_discovered_structs(&self) -> &HashMap<String, StructInfo> {
&self.discovered_structs
}
pub fn get_dependency_graph(&self) -> &TypeDependencyGraph {
&self.dependency_graph
}
pub fn topological_sort_types(&self, types: &HashSet<String>) -> Vec<String> {
self.dependency_graph.topological_sort_types(types)
}
pub fn visualize_dependencies(&self, commands: &[CommandInfo]) -> String {
self.dependency_graph.visualize_dependencies(commands)
}
pub fn generate_dot_graph(&self, commands: &[CommandInfo]) -> String {
self.dependency_graph.generate_dot_graph(commands)
}
pub fn map_rust_type_to_typescript(&mut self, rust_type: &str) -> String {
self.type_resolver.map_rust_type_to_typescript(rust_type)
}
}
impl Default for CommandAnalyzer {
fn default() -> Self {
Self::new()
}
}