cargomap 0.0.1

A simple context fetcher for Rust projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! cargomap - Rust Architecture Analysis Tool
//!
//! A CLI tool for analyzing Rust project architecture with:
//! - Resilient partial parsing (handles broken code)
//! - Dependency bridge to cargo registry sources
//! - Semantic gravity ranking for intelligent search
//! - Call-site teleportation (local usage of external symbols)
//! - MCP server for LLM tool integration

use cargomap::{DependencyBridge, SemanticGravity};
use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "cargomap")]
#[command(author, version, about = "Rust Architecture Analysis Tool", long_about = None)]
struct Cli {
    /// Path to the Rust project to analyze
    #[arg(short, long, default_value = ".")]
    path: PathBuf,

    /// Suppress non-essential output
    #[arg(short, long)]
    quiet: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Analyze project and show summary
    Analyze {
        /// Show external symbol usage
        #[arg(short, long)]
        externals: bool,

        /// Maximum number of items to display
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },

    /// Search for items by name
    Search {
        /// Search query
        query: String,

        /// Maximum number of results
        #[arg(short, long, default_value = "10")]
        limit: usize,
    },

    /// Resolve an external crate path and show local usages
    Resolve {
        /// External path to resolve (e.g., tokio::spawn)
        path: String,

        /// Maximum number of usages to show
        #[arg(short, long, default_value = "5")]
        limit: usize,
    },

    /// List all dependencies
    Deps {
        /// Maximum number of dependencies to show
        #[arg(short, long, default_value = "20")]
        limit: usize,
    },

    /// Start MCP server over stdio for LLM tool integration
    Serve,
}

fn main() {
    let cli = Cli::parse();

    let project_root = if cli.path.is_absolute() {
        cli.path.clone()
    } else {
        std::env::current_dir()
            .expect("Failed to get current directory")
            .join(&cli.path)
    };

    // Handle MCP serve command separately (runs async)
    if let Some(Commands::Serve) = &cli.command {
        let rt = tokio::runtime::Runtime::new().expect("Failed to create tokio runtime");
        if let Err(e) = rt.block_on(cargomap::mcp::run_mcp_server(project_root)) {
            eprintln!("MCP server error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Initialize components for non-MCP commands
    let mut gravity = SemanticGravity::new();
    let mut dep_bridge = match DependencyBridge::new(&project_root) {
        Ok(bridge) => Some(bridge),
        Err(e) => {
            if !cli.quiet {
                eprintln!("Warning: Could not initialize dependency bridge: {}", e);
            }
            None
        }
    };

    // Analyze the project
    if !cli.quiet {
        println!("Analyzing: {}", project_root.display());
    }

    if let Err(e) = gravity.analyze_project(&project_root) {
        eprintln!("Error analyzing project: {}", e);
        std::process::exit(1);
    }

    match cli.command {
        Some(Commands::Analyze { externals, limit }) => {
            cmd_analyze(&gravity, &mut dep_bridge, externals, limit, cli.quiet);
        }
        Some(Commands::Search { query, limit }) => {
            cmd_search(&gravity, &query, limit);
        }
        Some(Commands::Resolve { path, limit }) => {
            cmd_resolve(&gravity, &mut dep_bridge, &path, limit);
        }
        Some(Commands::Deps { limit }) => {
            cmd_deps(&mut dep_bridge, limit);
        }
        Some(Commands::Serve) => unreachable!(), // Handled above
        None => {
            // Default behavior: show summary
            cmd_analyze(&gravity, &mut dep_bridge, false, 10, cli.quiet);
        }
    }
}

fn cmd_analyze(
    gravity: &SemanticGravity,
    dep_bridge: &mut Option<DependencyBridge>,
    show_externals: bool,
    limit: usize,
    quiet: bool,
) {
    let files = gravity.get_files();
    let total_errors: usize = files.iter().map(|f| f.parse_errors.len()).sum();

    if !quiet {
        println!(
            "Parsed {} files ({} with partial recovery)",
            files.len(),
            total_errors
        );
    }

    // Load dependencies
    if let Some(bridge) = dep_bridge {
        if let Ok(deps) = bridge.load_dependencies() {
            if !quiet {
                println!("Found {} external dependencies", deps.len());
            }
        }
    }

    // Generate summary
    let summary = gravity.summarize();
    println!("{}", summary);

    // Show top external symbols used
    if show_externals {
        let external_symbols = gravity.get_all_external_symbols();
        if !external_symbols.is_empty() {
            println!("\n=== External Symbol Usage ===");
            for (path, count) in external_symbols.iter().take(limit) {
                println!("  {} ({} usages)", path, count);
            }
            if external_symbols.len() > limit {
                println!("  ... and {} more", external_symbols.len() - limit);
            }
        }
    }
}

fn cmd_search(gravity: &SemanticGravity, query: &str, limit: usize) {
    println!("=== Search Results for '{}' ===\n", query);

    let results = gravity.search(query);
    if results.is_empty() {
        println!("No results found.");
        return;
    }

    for (i, result) in results.iter().take(limit).enumerate() {
        let test_marker = if result.factors.is_test {
            " [TEST]"
        } else {
            ""
        };
        println!(
            "{}. {}{} (score: {:.1})",
            i + 1,
            result.item.name,
            test_marker,
            result.score
        );

        // Breadcrumbs (module path)
        println!("   Path: {}", result.context.breadcrumbs);

        println!(
            "   File: {}:{}",
            result.item.file_path.display(),
            result.item.span.start_line
        );

        // Parent context if available
        if let Some(parent) = &result.context.parent_context {
            println!("   In: {}", parent);
        }

        // Generic bounds (the "Live Signature")
        if !result.context.generic_bounds.is_empty() {
            let bounds_str: Vec<String> = result
                .context
                .generic_bounds
                .iter()
                .map(|gb| {
                    if gb.bounds.is_empty() {
                        gb.param.clone()
                    } else {
                        format!("{}: {}", gb.param, gb.bounds.join(" + "))
                    }
                })
                .collect();
            println!("   Generics: <{}>", bounds_str.join(", "));
        }

        println!(
            "   Factors: x-mod={}, generics={}, calls={}, site={}",
            result.factors.cross_module_count,
            result.factors.generic_depth,
            result.factors.call_count,
            result.factors.is_site
        );

        if result.factors.impl_count > 0 {
            println!(
                "   Impls: {} ({:?})",
                result.factors.impl_count, result.factors.trait_impls
            );
        }

        // Siblings with shared generics
        let siblings_with_shared: Vec<_> = result
            .context
            .siblings
            .iter()
            .filter(|s| !s.shared_generics.is_empty())
            .collect();
        if !siblings_with_shared.is_empty() {
            println!("   Related (shared generics):");
            for sib in siblings_with_shared.iter().take(3) {
                println!(
                    "     - {} {} (shares: {})",
                    sib.kind,
                    sib.name,
                    sib.shared_generics.join(", ")
                );
            }
        }

        println!();
    }

    if results.len() > limit {
        println!("... and {} more results", results.len() - limit);
    }
}

fn cmd_resolve(
    gravity: &SemanticGravity,
    dep_bridge: &mut Option<DependencyBridge>,
    path: &str,
    limit: usize,
) {
    println!("=== Call-Site Teleportation for '{}' ===", path);

    // Show local usages (the "bridge")
    let local_usages = gravity.get_external_usages(path);
    if !local_usages.is_empty() {
        println!(
            "\nLocal usages in your project ({} sites):",
            local_usages.len()
        );

        // Sort by complexity
        let mut sorted_usages: Vec<_> = local_usages.iter().collect();
        sorted_usages.sort_by(|a, b| b.complexity.cmp(&a.complexity));

        for (i, usage) in sorted_usages.iter().take(limit).enumerate() {
            let complexity_label = match usage.complexity {
                0..=2 => "simple",
                3..=5 => "moderate",
                _ => "complex",
            };
            println!(
                "  {}. {}:{} in {}() [{}]",
                i + 1,
                usage.file.display(),
                usage.line,
                usage.caller_context,
                complexity_label
            );
        }

        if let Some(most_complex) = gravity.get_most_complex_usage(path) {
            println!(
                "\n  Most complex usage: {}:{} in {}()",
                most_complex.file.display(),
                most_complex.line,
                most_complex.caller_context
            );
        }
    } else {
        println!("  No local usages found for '{}'", path);
    }

    // Show registry location
    if let Some(bridge) = dep_bridge {
        match bridge.resolve_path(path) {
            Some(resolved) => {
                println!("\nRegistry source:");
                println!("  {}", resolved);
                println!("  Path: {}", resolved.registry_path.display());
            }
            None => {
                println!("\n  Could not resolve in registry");
            }
        }
    }
}

fn cmd_deps(dep_bridge: &mut Option<DependencyBridge>, limit: usize) {
    println!("=== Dependencies ===\n");

    let Some(bridge) = dep_bridge else {
        eprintln!("Could not initialize dependency bridge");
        return;
    };

    match bridge.load_dependencies() {
        Ok(deps) => {
            println!("Found {} external dependencies:\n", deps.len());
            for (name, dep) in deps.iter().take(limit) {
                let status = if dep.registry_path.is_some() {
                    "+"
                } else {
                    "?"
                };
                println!("  {} {} v{}", status, name, dep.version);
            }
            if deps.len() > limit {
                println!("\n  ... and {} more", deps.len() - limit);
            }
            println!("\n  + = resolved in registry, ? = not found locally");
        }
        Err(e) => {
            eprintln!("Error loading dependencies: {}", e);
        }
    }
}

/// Interactive analysis session (for future REPL mode)
#[allow(dead_code)]
struct AnalysisSession {
    gravity: SemanticGravity,
    dep_bridge: Option<DependencyBridge>,
    project_root: PathBuf,
}

#[allow(dead_code)]
impl AnalysisSession {
    fn new(project_root: PathBuf) -> Result<Self, Box<dyn std::error::Error>> {
        let mut gravity = SemanticGravity::new();
        gravity.analyze_project(&project_root)?;

        let dep_bridge = DependencyBridge::new(&project_root).ok();

        Ok(Self {
            gravity,
            dep_bridge,
            project_root,
        })
    }

    /// Search for items by name
    fn search(&self, query: &str) -> Vec<cargomap::WorkSiteScore> {
        self.gravity.search(query)
    }

    /// Get all implementations for a type
    fn get_impls(&self, type_name: &str) -> Vec<&cargomap::ParsedItem> {
        self.gravity.get_impls_for_type(type_name)
    }

    /// Find where a function is called
    fn find_callers(&self, fn_name: &str) -> Vec<&cargomap::CallSite> {
        self.gravity.find_call_sites(fn_name)
    }

    /// Resolve an external crate path
    fn resolve_external(&mut self, path: &str) -> Option<cargomap::dependency::ResolvedPath> {
        self.dep_bridge.as_mut()?.resolve_path(path)
    }

    /// Get local usages of an external symbol
    fn get_local_usages(&self, path: &str) -> Vec<&cargomap::ExternalReference> {
        self.gravity.get_external_usages(path)
    }

    /// Get the project summary
    fn summary(&self) -> cargomap::gravity::ProjectSummary {
        self.gravity.summarize()
    }
}