Skip to main content

aptu_coder_core/
analyze.rs

1// SPDX-FileCopyrightText: 2026 aptu-coder contributors
2// SPDX-License-Identifier: Apache-2.0
3//! Main analysis engine for extracting code structure from files and directories.
4//!
5//! Implements the four MCP tools: `analyze_directory` (Overview), `analyze_file` (`FileDetails`),
6//! `analyze_symbol` (call graph), and `analyze_module` (lightweight index). Handles parallel processing and cancellation.
7
8use crate::formatter::{format_file_details, format_structure};
9use crate::graph::InternalCallChain;
10use crate::lang::{language_for_extension, supported_languages};
11use crate::parser::{ElementExtractor, SemanticExtractor};
12use crate::test_detection::is_test_file;
13use crate::traversal::{WalkEntry, walk_directory};
14use crate::types::{AnalysisMode, FileInfo, SemanticAnalysis, SymbolMatchMode};
15use rayon::prelude::*;
16#[cfg(feature = "schemars")]
17use schemars::JsonSchema;
18use serde::{Deserialize, Serialize};
19use std::path::{Path, PathBuf};
20use std::sync::Arc;
21use std::sync::atomic::{AtomicUsize, Ordering};
22use std::time::Instant;
23use thiserror::Error;
24use tokio_util::sync::CancellationToken;
25use tracing::instrument;
26
27pub const MAX_FILE_SIZE_BYTES: u64 = 10_000_000;
28
29#[derive(Debug, Error)]
30#[non_exhaustive]
31pub enum AnalyzeError {
32    #[error("Traversal error: {0}")]
33    Traversal(#[from] crate::traversal::TraversalError),
34    #[error("Parser error: {0}")]
35    Parser(#[from] crate::parser::ParserError),
36    #[error("Graph error: {0}")]
37    Graph(#[from] crate::graph::GraphError),
38    #[error("Formatter error: {0}")]
39    Formatter(#[from] crate::formatter::FormatterError),
40    #[error("Analysis cancelled")]
41    Cancelled,
42    #[error("unsupported language: {0}")]
43    UnsupportedLanguage(String),
44    #[error("I/O error: {0}")]
45    Io(#[from] std::io::Error),
46    #[error("invalid range: start ({start}) > end ({end}); file has {total} lines")]
47    InvalidRange {
48        start: usize,
49        end: usize,
50        total: usize,
51    },
52    #[error("path is a directory, not a file: {0}")]
53    NotAFile(PathBuf),
54    #[error(
55        "file has {total_lines} lines; provide start_line and end_line, or call analyze_module first to locate the range"
56    )]
57    RangelessLargeFile { total_lines: usize },
58    #[error("parse timeout exceeded for {path}: {micros} microseconds")]
59    ParseTimeout { path: PathBuf, micros: u64 },
60}
61
62/// Result of directory analysis containing both formatted output and file data.
63#[derive(Debug, Clone, Serialize, Deserialize)]
64#[cfg_attr(feature = "schemars", derive(JsonSchema))]
65#[non_exhaustive]
66pub struct AnalysisOutput {
67    #[cfg_attr(
68        feature = "schemars",
69        schemars(description = "Formatted text representation of the analysis")
70    )]
71    pub formatted: String,
72    #[cfg_attr(
73        feature = "schemars",
74        schemars(description = "List of files analyzed in the directory")
75    )]
76    pub files: Vec<FileInfo>,
77    /// Walk entries used internally for summary generation; not serialized.
78    #[serde(skip)]
79    #[serde(default)]
80    #[cfg_attr(feature = "schemars", schemars(skip))]
81    pub entries: Vec<WalkEntry>,
82    /// Subtree file counts computed from an unbounded walk; used by `format_summary`; not serialized.
83    #[serde(skip)]
84    #[serde(default)]
85    #[cfg_attr(feature = "schemars", schemars(skip))]
86    pub subtree_counts: Option<Vec<(std::path::PathBuf, usize)>>,
87    #[serde(skip_serializing_if = "Option::is_none")]
88    #[cfg_attr(
89        feature = "schemars",
90        schemars(
91            description = "Opaque cursor token for the next page of results (absent when no more results)"
92        )
93    )]
94    pub next_cursor: Option<String>,
95}
96
97/// Result of file-level semantic analysis.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99#[cfg_attr(feature = "schemars", derive(JsonSchema))]
100#[non_exhaustive]
101pub struct FileAnalysisOutput {
102    #[cfg_attr(
103        feature = "schemars",
104        schemars(description = "Formatted text representation of the analysis")
105    )]
106    pub formatted: String,
107    #[cfg_attr(
108        feature = "schemars",
109        schemars(description = "Semantic analysis data including functions, classes, and imports")
110    )]
111    pub semantic: SemanticAnalysis,
112    #[cfg_attr(
113        feature = "schemars",
114        schemars(description = "Total line count of the analyzed file")
115    )]
116    #[cfg_attr(
117        feature = "schemars",
118        schemars(schema_with = "crate::schema_helpers::integer_schema")
119    )]
120    pub line_count: usize,
121    #[serde(skip_serializing_if = "Option::is_none")]
122    #[cfg_attr(
123        feature = "schemars",
124        schemars(
125            description = "Opaque cursor token for the next page of results (absent when no more results)"
126        )
127    )]
128    pub next_cursor: Option<String>,
129    #[serde(skip_serializing_if = "Option::is_none")]
130    #[cfg_attr(
131        feature = "schemars",
132        schemars(
133            description = "True when the file extension is not supported; semantic fields are empty and formatted contains a raw preview"
134        )
135    )]
136    pub unsupported: Option<bool>,
137}
138
139impl FileAnalysisOutput {
140    /// Create a new `FileAnalysisOutput`.
141    #[must_use]
142    pub fn new(
143        formatted: String,
144        semantic: SemanticAnalysis,
145        line_count: usize,
146        next_cursor: Option<String>,
147    ) -> Self {
148        Self {
149            formatted,
150            semantic,
151            line_count,
152            next_cursor,
153            unsupported: None,
154        }
155    }
156}
157/// Reason a file was skipped during eligibility check.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159enum SkipReason {
160    Oversized,
161    Unreadable,
162}
163
164/// Check if a file is eligible for analysis based on size and readability.
165///
166/// Returns `Ok(content)` when the file should be analyzed, `Err(reason)` to skip it.
167fn check_file_eligibility(entry: &WalkEntry) -> Result<String, SkipReason> {
168    // Check file size before reading
169    if entry.path.metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
170        tracing::debug!("skipping large file: {}", entry.path.display());
171        return Err(SkipReason::Oversized);
172    }
173
174    // Try to read file content; skip binary or unreadable files
175    std::fs::read_to_string(&entry.path).map_err(|_| SkipReason::Unreadable)
176}
177
178/// Process a single file entry and extract its analysis data.
179fn process_file_entry(entry: &WalkEntry, source: &str) -> FileInfo {
180    let path_str = entry.path.display().to_string();
181    let line_count = source.lines().count();
182
183    // Detect language from extension
184    let ext = entry.path.extension().and_then(|e| e.to_str());
185
186    // Detect language and extract counts
187    let (language, function_count, class_count) = if let Some(ext_str) = ext
188        && let Some(lang) = language_for_extension(ext_str)
189    {
190        let lang_str = lang.to_string();
191        match ElementExtractor::extract_with_depth(source, &lang_str) {
192            Ok((func_count, class_count)) => (lang_str, func_count, class_count),
193            Err(_) => (lang_str, 0, 0),
194        }
195    } else {
196        (
197            ext.map(|e| e.to_lowercase())
198                .unwrap_or_else(|| "unknown".to_string()),
199            0,
200            0,
201        )
202    };
203
204    let is_test = is_test_file(&entry.path);
205
206    FileInfo {
207        path: path_str,
208        line_count,
209        function_count,
210        class_count,
211        language,
212        is_test,
213    }
214}
215
216/// Analyze a single file entry in parallel context.
217fn analyze_single_file(
218    entry: &WalkEntry,
219    progress: &Arc<AtomicUsize>,
220    ct: &CancellationToken,
221) -> Option<FileInfo> {
222    // Check cancellation per file
223    if ct.is_cancelled() {
224        return None;
225    }
226
227    // Check file eligibility; progress accounting happens on all exit paths below
228    let source = match check_file_eligibility(entry) {
229        Ok(content) => content,
230        Err(_) => {
231            progress.fetch_add(1, Ordering::Relaxed);
232            return None;
233        }
234    };
235
236    let file_info = process_file_entry(entry, &source);
237    progress.fetch_add(1, Ordering::Relaxed);
238
239    Some(file_info)
240}
241
242/// Initialize analysis context and collect file entries.
243fn init_analysis_context(entries: &[WalkEntry]) -> Vec<&WalkEntry> {
244    entries
245        .iter()
246        .filter(|e| !e.is_dir && !e.is_symlink)
247        .collect()
248}
249
250/// Build the final analysis output from results.
251fn build_analysis_output(
252    entries: Vec<WalkEntry>,
253    analysis_results: Vec<FileInfo>,
254) -> AnalysisOutput {
255    let formatted = format_structure(&entries, &analysis_results, None);
256    AnalysisOutput {
257        formatted,
258        files: analysis_results,
259        entries,
260        next_cursor: None,
261        subtree_counts: None,
262    }
263}
264
265/// Run parallel analysis on file entries and log completion.
266fn run_parallel_analysis(
267    file_entries: &[&WalkEntry],
268    progress: &Arc<AtomicUsize>,
269    ct: &CancellationToken,
270) -> Result<Vec<FileInfo>, AnalyzeError> {
271    let start = Instant::now();
272    tracing::debug!(file_count = file_entries.len(), "analysis start");
273
274    let _parse_span = tracing::info_span!("ast.parse_batch", count = file_entries.len()).entered();
275
276    // Parallel analysis of files
277    let analysis_results: Vec<FileInfo> = file_entries
278        .par_iter()
279        .filter_map(|entry| analyze_single_file(entry, progress, ct))
280        .collect();
281
282    // Check if cancelled after parallel processing
283    if ct.is_cancelled() {
284        return Err(AnalyzeError::Cancelled);
285    }
286
287    tracing::debug!(
288        file_count = file_entries.len(),
289        duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
290        "analysis complete"
291    );
292
293    Ok(analysis_results)
294}
295
296#[instrument(skip_all, fields(path = %root.display()))]
297// public API; callers expect owned semantics
298#[allow(clippy::needless_pass_by_value)]
299pub fn analyze_directory_with_progress(
300    root: &Path,
301    entries: Vec<WalkEntry>,
302    progress: Arc<AtomicUsize>,
303    ct: CancellationToken,
304) -> Result<AnalysisOutput, AnalyzeError> {
305    // Check if already cancelled
306    if ct.is_cancelled() {
307        return Err(AnalyzeError::Cancelled);
308    }
309
310    tracing::debug!(root = %root.display(), "analysis start");
311
312    let file_entries = init_analysis_context(&entries);
313    let analysis_results = run_parallel_analysis(&file_entries, &progress, &ct)?;
314
315    let _format_span = tracing::info_span!("output.format").entered();
316
317    // Build and return output
318    Ok(build_analysis_output(entries, analysis_results))
319}
320
321/// Analyze a directory structure and return formatted output and file data.
322#[instrument(skip_all, fields(path = %root.display()))]
323pub fn analyze_directory(
324    root: &Path,
325    max_depth: Option<u32>,
326) -> Result<AnalysisOutput, AnalyzeError> {
327    let entries = walk_directory(root, max_depth)?;
328    let counter = Arc::new(AtomicUsize::new(0));
329    let ct = CancellationToken::new();
330    analyze_directory_with_progress(root, entries, counter, ct)
331}
332
333/// Determine analysis mode based on parameters and path.
334#[must_use]
335pub fn determine_mode(path: &str, focus: Option<&str>) -> AnalysisMode {
336    if focus.is_some() {
337        return AnalysisMode::SymbolFocus;
338    }
339
340    let path_obj = Path::new(path);
341    if path_obj.is_dir() {
342        AnalysisMode::Overview
343    } else {
344        AnalysisMode::FileDetails
345    }
346}
347
348/// Analyze a single file and return semantic analysis with formatted output.
349#[instrument(skip_all, fields(path))]
350pub fn analyze_file(
351    path: &str,
352    ast_recursion_limit: Option<usize>,
353) -> Result<FileAnalysisOutput, AnalyzeError> {
354    let start = Instant::now();
355
356    // Check file size before reading
357    if Path::new(path).metadata().map(|m| m.len()).unwrap_or(0) > MAX_FILE_SIZE_BYTES {
358        tracing::debug!("skipping large file: {}", path);
359        return Err(AnalyzeError::Parser(
360            crate::parser::ParserError::ParseError("file too large".to_string()),
361        ));
362    }
363
364    let source = std::fs::read_to_string(path)
365        .map_err(|e| AnalyzeError::Parser(crate::parser::ParserError::ParseError(e.to_string())))?;
366
367    let line_count = source.lines().count();
368
369    // Detect language from extension
370    let ext = Path::new(path)
371        .extension()
372        .and_then(|e| e.to_str())
373        .and_then(language_for_extension)
374        .map_or_else(|| "unknown".to_string(), std::string::ToString::to_string);
375
376    // Extract semantic information
377    let mut semantic = SemanticExtractor::extract(&source, &ext, ast_recursion_limit, None)?;
378
379    // Populate the file path on references now that the path is known
380    for r in &mut semantic.references {
381        r.location = path.to_string();
382    }
383
384    // Resolve Python wildcard imports
385    if ext == "python" {
386        resolve_wildcard_imports(Path::new(path), &mut semantic.imports);
387    }
388
389    // Detect if this is a test file
390    let is_test = is_test_file(Path::new(path));
391
392    // Extract parent directory for relative path display
393    let parent_dir = Path::new(path).parent();
394
395    // Format output
396    let formatted = format_file_details(path, &semantic, line_count, is_test, parent_dir);
397
398    tracing::debug!(path = %path, language = %ext, functions = semantic.functions.len(), classes = semantic.classes.len(), imports = semantic.imports.len(), duration_ms = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX), "file analysis complete");
399
400    Ok(FileAnalysisOutput::new(
401        formatted, semantic, line_count, None,
402    ))
403}
404
405/// Analyze source code from a string buffer without filesystem access.
406///
407/// This function analyzes in-memory source code by language identifier. The `language`
408/// parameter can be either a language name (e.g., `"rust"`, `"python"`, `"go"`) or a file
409/// extension (e.g., `"rs"`, `"py"`).
410///
411/// Accepted language identifiers depend on compiled features. Use [`supported_languages()`] to
412/// discover the available language names at runtime, and [`language_for_extension()`] to resolve
413/// a file extension to its supported language identifier.
414///
415/// # Arguments
416///
417/// * `source` - The source code to analyze
418/// * `language` - The language identifier (language name or extension)
419/// * `ast_recursion_limit` - Optional limit for AST traversal depth
420///
421/// # Returns
422///
423/// - `Ok(FileAnalysisOutput)` on success
424/// - `Err(AnalyzeError::UnsupportedLanguage)` if the language is not recognized
425/// - `Err(AnalyzeError::Parser)` if parsing fails
426///
427/// # Notes
428///
429/// - Python wildcard import resolution is skipped for in-memory analysis (no filesystem path available)
430/// - The formatted output uses the standard file-details formatter, so it includes a `FILE:` header with an empty path
431#[inline]
432pub fn analyze_str(
433    source: &str,
434    language: &str,
435    ast_recursion_limit: Option<usize>,
436) -> Result<FileAnalysisOutput, AnalyzeError> {
437    // Resolve language: first try as a file extension, then as a language name
438    // (case-insensitive match against supported_languages()).
439    let lang = language_for_extension(language).or_else(|| {
440        let lower = language.to_ascii_lowercase();
441        supported_languages()
442            .iter()
443            .find(|&&name| name == lower)
444            .copied()
445    });
446    let lang = lang.ok_or_else(|| AnalyzeError::UnsupportedLanguage(language.to_string()))?;
447
448    // Extract semantic information
449    let mut semantic = SemanticExtractor::extract(source, lang, ast_recursion_limit, None)?;
450
451    // Populate a stable in-memory sentinel on all reference locations
452    for r in &mut semantic.references {
453        r.location = "<memory>".to_string();
454    }
455
456    // Count lines in the source
457    let line_count = source.lines().count();
458
459    // Format output with empty path (no filesystem access)
460    let formatted = format_file_details("", &semantic, line_count, false, None);
461
462    Ok(FileAnalysisOutput::new(
463        formatted, semantic, line_count, None,
464    ))
465}
466
467/// Single entry in a call chain (depth-1 direct caller or callee).
468#[non_exhaustive]
469#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
470#[cfg_attr(feature = "schemars", derive(JsonSchema))]
471pub struct CallChainEntry {
472    #[cfg_attr(
473        feature = "schemars",
474        schemars(description = "Symbol name of the caller or callee")
475    )]
476    pub symbol: String,
477    #[cfg_attr(
478        feature = "schemars",
479        schemars(description = "File path relative to the repository root")
480    )]
481    pub file: String,
482    #[cfg_attr(
483        feature = "schemars",
484        schemars(
485            description = "Line number of the definition or call site (1-indexed)",
486            schema_with = "crate::schema_helpers::integer_schema"
487        )
488    )]
489    pub line: usize,
490}
491
492/// Result of focused symbol analysis.
493#[derive(Debug, Clone, Serialize, Deserialize)]
494#[cfg_attr(feature = "schemars", derive(JsonSchema))]
495#[non_exhaustive]
496pub struct FocusedAnalysisOutput {
497    #[cfg_attr(
498        feature = "schemars",
499        schemars(description = "Formatted text representation of the call graph analysis")
500    )]
501    pub formatted: String,
502    #[serde(skip_serializing_if = "Option::is_none")]
503    #[cfg_attr(
504        feature = "schemars",
505        schemars(
506            description = "Opaque cursor token for the next page of results (absent when no more results)"
507        )
508    )]
509    pub next_cursor: Option<String>,
510    /// Production caller chains (partitioned from incoming chains, excluding test callers).
511    /// Not serialized; used for pagination in lib.rs.
512    #[serde(default)]
513    #[cfg_attr(feature = "schemars", schemars(skip))]
514    pub prod_chains: Vec<InternalCallChain>,
515    /// Test caller chains. Not serialized; used for pagination summary in lib.rs.
516    #[serde(default)]
517    #[cfg_attr(feature = "schemars", schemars(skip))]
518    pub test_chains: Vec<InternalCallChain>,
519    /// Outgoing (callee) chains. Not serialized; used for pagination in lib.rs.
520    #[serde(default)]
521    #[cfg_attr(feature = "schemars", schemars(skip))]
522    pub outgoing_chains: Vec<InternalCallChain>,
523    /// Number of definitions for the symbol. Not serialized; used for pagination headers.
524    #[serde(default)]
525    #[cfg_attr(feature = "schemars", schemars(skip))]
526    pub def_count: usize,
527    /// Total unique callers before `impl_only` filter. Not serialized; used for FILTER header.
528    #[serde(default)]
529    #[cfg_attr(feature = "schemars", schemars(skip))]
530    pub unfiltered_caller_count: usize,
531    /// Unique callers after `impl_only` filter. Not serialized; used for FILTER header.
532    #[serde(default)]
533    #[cfg_attr(feature = "schemars", schemars(skip))]
534    pub impl_trait_caller_count: usize,
535    /// Direct (depth-1) production callers. `follow_depth` does not affect this field.
536    #[serde(skip_serializing_if = "Option::is_none")]
537    pub callers: Option<Vec<CallChainEntry>>,
538    /// Direct (depth-1) test callers. `follow_depth` does not affect this field.
539    #[serde(skip_serializing_if = "Option::is_none")]
540    pub test_callers: Option<Vec<CallChainEntry>>,
541    /// Direct (depth-1) callees. `follow_depth` does not affect this field.
542    #[serde(skip_serializing_if = "Option::is_none")]
543    pub callees: Option<Vec<CallChainEntry>>,
544    /// Definition and use sites for the symbol.
545    #[serde(default)]
546    pub def_use_sites: Vec<crate::types::DefUseSite>,
547    /// Cache tier for this result: `"l1_memory"`, `"l2_disk"`, or `"miss"`.
548    /// Populated by the MCP handler after cache lookup.
549    ///
550    /// This field is `None` in the following cases:
551    /// - `import_lookup=true` responses: the import-lookup path does not consult the call
552    ///   graph cache, so no tier is recorded.
553    /// - Non-symbol analysis modes (directory and file tools): `FocusedAnalysisOutput` is
554    ///   not produced by those handlers, and the field is therefore absent.
555    /// - Any `FocusedAnalysisOutput` constructed outside the `handle_focused_mode` return
556    ///   path (e.g. legacy cached entries that pre-date this field).
557    #[serde(skip_serializing_if = "Option::is_none")]
558    #[cfg_attr(
559        feature = "schemars",
560        schemars(description = "Cache tier for this result: l1_memory, l2_disk, or miss")
561    )]
562    pub cache_tier: Option<String>,
563}
564
565/// Parameters for focused symbol analysis. Groups high-arity parameters to keep
566/// function signatures under clippy's default 7-argument threshold.
567#[derive(Clone)]
568pub struct FocusedAnalysisConfig {
569    pub focus: String,
570    pub match_mode: SymbolMatchMode,
571    pub follow_depth: u32,
572    pub max_depth: Option<u32>,
573    pub ast_recursion_limit: Option<usize>,
574    pub use_summary: bool,
575    pub impl_only: Option<bool>,
576    pub def_use: bool,
577    pub parse_timeout_micros: Option<u64>,
578}
579
580#[cfg(test)]
581pub(crate) use crate::analyze_focused::chains_to_entries;
582pub(crate) use crate::analyze_focused::resolve_wildcard_imports;
583pub use crate::analyze_focused::{
584    analyze_focused, analyze_focused_with_progress, analyze_focused_with_progress_with_entries,
585    analyze_import_lookup, analyze_module_file,
586};
587/// Read a file and return its raw content with line numbers for a specified range.
588#[cfg(test)]
589mod tests {
590    use super::*;
591    use crate::formatter::format_focused_paginated;
592    use crate::graph::InternalCallChain;
593    use crate::pagination::{PaginationMode, decode_cursor, paginate_slice};
594    use std::fs;
595    use std::path::PathBuf;
596    use tempfile::TempDir;
597
598    #[test]
599    fn analyze_str_rust_happy_path() {
600        let source = "fn hello() -> i32 { 42 }";
601        let result = analyze_str(source, "rs", None);
602        assert!(result.is_ok());
603    }
604
605    #[test]
606    fn analyze_str_python_happy_path() {
607        let source = "def greet(name):\n    return f'Hello {name}'";
608        let result = analyze_str(source, "py", None);
609        assert!(result.is_ok());
610    }
611
612    #[test]
613    fn analyze_str_rust_by_language_name() {
614        let source = "fn hello() -> i32 { 42 }";
615        let result = analyze_str(source, "rust", None);
616        assert!(result.is_ok());
617    }
618
619    #[test]
620    fn analyze_str_python_by_language_name() {
621        let source = "def greet(name):\n    return f'Hello {name}'";
622        let result = analyze_str(source, "python", None);
623        assert!(result.is_ok());
624    }
625
626    #[test]
627    fn analyze_str_rust_mixed_case() {
628        let source = "fn hello() -> i32 { 42 }";
629        let result = analyze_str(source, "RuSt", None);
630        assert!(result.is_ok());
631    }
632
633    #[test]
634    fn analyze_str_python_mixed_case() {
635        let source = "def greet(name):\n    return f'Hello {name}'";
636        let result = analyze_str(source, "PyThOn", None);
637        assert!(result.is_ok());
638    }
639
640    #[test]
641    fn analyze_str_unsupported_language() {
642        let result = analyze_str("code", "brainfuck", None);
643        assert!(
644            matches!(result, Err(AnalyzeError::UnsupportedLanguage(lang)) if lang == "brainfuck")
645        );
646    }
647
648    #[test]
649    fn test_symbol_focus_callers_pagination_first_page() {
650        let temp_dir = TempDir::new().unwrap();
651
652        // Create a file with many callers of `target`
653        let mut code = String::from("fn target() {}\n");
654        for i in 0..15 {
655            code.push_str(&format!("fn caller_{:02}() {{ target(); }}\n", i));
656        }
657        fs::write(temp_dir.path().join("lib.rs"), &code).unwrap();
658
659        // Act
660        let output = analyze_focused(temp_dir.path(), "target", 1, None, None).unwrap();
661
662        // Paginate prod callers with page_size=5
663        let paginated = paginate_slice(&output.prod_chains, 0, 5, PaginationMode::Callers)
664            .expect("paginate failed");
665        assert!(
666            paginated.total >= 5,
667            "should have enough callers to paginate"
668        );
669        assert!(
670            paginated.next_cursor.is_some(),
671            "should have next_cursor for page 1"
672        );
673
674        // Verify cursor encodes callers mode
675        assert_eq!(paginated.items.len(), 5);
676    }
677
678    #[test]
679    fn test_symbol_focus_callers_pagination_second_page() {
680        let temp_dir = TempDir::new().unwrap();
681
682        let mut code = String::from("fn target() {}\n");
683        for i in 0..12 {
684            code.push_str(&format!("fn caller_{:02}() {{ target(); }}\n", i));
685        }
686        fs::write(temp_dir.path().join("lib.rs"), &code).unwrap();
687
688        let output = analyze_focused(temp_dir.path(), "target", 1, None, None).unwrap();
689        let total_prod = output.prod_chains.len();
690
691        if total_prod > 5 {
692            // Get page 1 cursor
693            let p1 = paginate_slice(&output.prod_chains, 0, 5, PaginationMode::Callers)
694                .expect("paginate failed");
695            assert!(p1.next_cursor.is_some());
696
697            let cursor_str = p1.next_cursor.unwrap();
698            let cursor_data = decode_cursor(&cursor_str).expect("decode failed");
699
700            // Get page 2
701            let p2 = paginate_slice(
702                &output.prod_chains,
703                cursor_data.offset,
704                5,
705                PaginationMode::Callers,
706            )
707            .expect("paginate failed");
708
709            // Format paginated output
710            let formatted = format_focused_paginated(
711                &p2.items,
712                total_prod,
713                PaginationMode::Callers,
714                "target",
715                &output.prod_chains,
716                &output.test_chains,
717                &output.outgoing_chains,
718                output.def_count,
719                cursor_data.offset,
720                Some(temp_dir.path()),
721                true,
722            );
723
724            // Assert: header shows correct range for page 2
725            let expected_start = cursor_data.offset + 1;
726            assert!(
727                formatted.contains(&format!("CALLERS ({}", expected_start)),
728                "header should show page 2 range, got: {}",
729                formatted
730            );
731        }
732    }
733
734    #[test]
735    fn test_chains_to_entries_empty_returns_none() {
736        // Arrange
737        let chains: Vec<InternalCallChain> = vec![];
738
739        // Act
740        let result = chains_to_entries(&chains, None);
741
742        // Assert
743        assert!(result.is_none());
744    }
745
746    #[test]
747    fn test_chains_to_entries_with_data_returns_entries() {
748        // Arrange
749        let chains = vec![
750            InternalCallChain {
751                chain: vec![("caller1".to_string(), PathBuf::from("/root/lib.rs"), 10)],
752            },
753            InternalCallChain {
754                chain: vec![("caller2".to_string(), PathBuf::from("/root/other.rs"), 20)],
755            },
756        ];
757        let root = PathBuf::from("/root");
758
759        // Act
760        let result = chains_to_entries(&chains, Some(root.as_path()));
761
762        // Assert
763        assert!(result.is_some());
764        let entries = result.unwrap();
765        assert_eq!(entries.len(), 2);
766        assert_eq!(entries[0].symbol, "caller1");
767        assert_eq!(entries[0].file, "lib.rs");
768        assert_eq!(entries[0].line, 10);
769        assert_eq!(entries[1].symbol, "caller2");
770        assert_eq!(entries[1].file, "other.rs");
771        assert_eq!(entries[1].line, 20);
772    }
773
774    #[test]
775    fn test_symbol_focus_callees_pagination() {
776        let temp_dir = TempDir::new().unwrap();
777
778        // target calls many functions
779        let mut code = String::from("fn target() {\n");
780        for i in 0..10 {
781            code.push_str(&format!("    callee_{:02}();\n", i));
782        }
783        code.push_str("}\n");
784        for i in 0..10 {
785            code.push_str(&format!("fn callee_{:02}() {{}}\n", i));
786        }
787        fs::write(temp_dir.path().join("lib.rs"), &code).unwrap();
788
789        let output = analyze_focused(temp_dir.path(), "target", 1, None, None).unwrap();
790        let total_callees = output.outgoing_chains.len();
791
792        if total_callees > 3 {
793            let paginated = paginate_slice(&output.outgoing_chains, 0, 3, PaginationMode::Callees)
794                .expect("paginate failed");
795
796            let formatted = format_focused_paginated(
797                &paginated.items,
798                total_callees,
799                PaginationMode::Callees,
800                "target",
801                &output.prod_chains,
802                &output.test_chains,
803                &output.outgoing_chains,
804                output.def_count,
805                0,
806                Some(temp_dir.path()),
807                true,
808            );
809
810            assert!(
811                formatted.contains(&format!(
812                    "CALLEES (1-{} of {})",
813                    paginated.items.len(),
814                    total_callees
815                )),
816                "header should show callees range, got: {}",
817                formatted
818            );
819        }
820    }
821
822    #[test]
823    fn test_symbol_focus_empty_prod_callers() {
824        let temp_dir = TempDir::new().unwrap();
825
826        // target is only called from test functions
827        let code = r#"
828fn target() {}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833    #[test]
834    fn test_something() { target(); }
835}
836"#;
837        fs::write(temp_dir.path().join("lib.rs"), code).unwrap();
838
839        let output = analyze_focused(temp_dir.path(), "target", 1, None, None).unwrap();
840
841        // prod_chains may be empty; pagination should handle it gracefully
842        let paginated = paginate_slice(&output.prod_chains, 0, 100, PaginationMode::Callers)
843            .expect("paginate failed");
844        assert_eq!(paginated.items.len(), output.prod_chains.len());
845        assert!(
846            paginated.next_cursor.is_none(),
847            "no next_cursor for empty or single-page prod_chains"
848        );
849    }
850
851    #[test]
852    fn test_impl_only_filter_header_correct_counts() {
853        let temp_dir = TempDir::new().unwrap();
854
855        // Create a Rust fixture with:
856        // - A trait definition
857        // - An impl Trait for SomeType block that calls the focus symbol
858        // - A regular (non-trait-impl) function that also calls the focus symbol
859        let code = r#"
860trait MyTrait {
861    fn focus_symbol();
862}
863
864struct SomeType;
865
866impl MyTrait for SomeType {
867    fn focus_symbol() {}
868}
869
870fn impl_caller() {
871    SomeType::focus_symbol();
872}
873
874fn regular_caller() {
875    SomeType::focus_symbol();
876}
877"#;
878        fs::write(temp_dir.path().join("lib.rs"), code).unwrap();
879
880        // Call analyze_focused with impl_only=Some(true)
881        let params = FocusedAnalysisConfig {
882            focus: "focus_symbol".to_string(),
883            match_mode: SymbolMatchMode::Insensitive,
884            follow_depth: 1,
885            max_depth: None,
886            ast_recursion_limit: None,
887            use_summary: false,
888            impl_only: Some(true),
889            def_use: false,
890            parse_timeout_micros: None,
891        };
892        let output = analyze_focused_with_progress(
893            temp_dir.path(),
894            &params,
895            Arc::new(AtomicUsize::new(0)),
896            CancellationToken::new(),
897        )
898        .unwrap();
899
900        // Assert the result contains "FILTER: impl_only=true"
901        assert!(
902            output.formatted.contains("FILTER: impl_only=true"),
903            "formatted output should contain FILTER header for impl_only=true, got: {}",
904            output.formatted
905        );
906
907        // Assert the retained count N < total count M
908        assert!(
909            output.impl_trait_caller_count < output.unfiltered_caller_count,
910            "impl_trait_caller_count ({}) should be less than unfiltered_caller_count ({})",
911            output.impl_trait_caller_count,
912            output.unfiltered_caller_count
913        );
914
915        // Assert format is "FILTER: impl_only=true (N of M callers shown)"
916        let filter_line = output
917            .formatted
918            .lines()
919            .find(|line| line.contains("FILTER: impl_only=true"))
920            .expect("should find FILTER line");
921        assert!(
922            filter_line.contains(&format!(
923                "({} of {} callers shown)",
924                output.impl_trait_caller_count, output.unfiltered_caller_count
925            )),
926            "FILTER line should show correct N of M counts, got: {}",
927            filter_line
928        );
929    }
930
931    #[test]
932    fn test_callers_count_matches_formatted_output() {
933        let temp_dir = TempDir::new().unwrap();
934
935        // Create a file with multiple callers of `target`
936        let code = r#"
937fn target() {}
938fn caller_a() { target(); }
939fn caller_b() { target(); }
940fn caller_c() { target(); }
941"#;
942        fs::write(temp_dir.path().join("lib.rs"), code).unwrap();
943
944        // Analyze the symbol
945        let output = analyze_focused(temp_dir.path(), "target", 1, None, None).unwrap();
946
947        // Extract CALLERS count from formatted output
948        let formatted = &output.formatted;
949        let callers_count_from_output = formatted
950            .lines()
951            .find(|line| line.contains("FOCUS:"))
952            .and_then(|line| {
953                line.split(',')
954                    .find(|part| part.contains("callers"))
955                    .and_then(|part| {
956                        part.trim()
957                            .split_whitespace()
958                            .next()
959                            .and_then(|s| s.parse::<usize>().ok())
960                    })
961            })
962            .expect("should find CALLERS count in formatted output");
963
964        // Compute expected count from prod_chains (unique first-caller names)
965        let expected_callers_count = output
966            .prod_chains
967            .iter()
968            .filter_map(|chain| chain.chain.first().map(|(name, _, _)| name))
969            .collect::<std::collections::HashSet<_>>()
970            .len();
971
972        assert_eq!(
973            callers_count_from_output, expected_callers_count,
974            "CALLERS count in formatted output should match unique-first-caller count in prod_chains"
975        );
976    }
977
978    #[test]
979    fn test_def_use_focused_analysis() {
980        let temp_dir = TempDir::new().unwrap();
981        fs::write(
982            temp_dir.path().join("lib.rs"),
983            "fn example() {\n    let x = 10;\n    x += 1;\n    println!(\"{}\", x);\n    let y = x + 1;\n}\n",
984        )
985        .unwrap();
986
987        let entries = walk_directory(temp_dir.path(), None).unwrap();
988        let counter = Arc::new(AtomicUsize::new(0));
989        let ct = CancellationToken::new();
990        let params = FocusedAnalysisConfig {
991            focus: "x".to_string(),
992            match_mode: SymbolMatchMode::Exact,
993            follow_depth: 1,
994            max_depth: None,
995            ast_recursion_limit: None,
996            use_summary: false,
997            impl_only: None,
998            def_use: true,
999            parse_timeout_micros: None,
1000        };
1001
1002        let output = analyze_focused_with_progress_with_entries(
1003            temp_dir.path(),
1004            &params,
1005            &counter,
1006            &ct,
1007            &entries,
1008        )
1009        .expect("def_use analysis should succeed");
1010
1011        assert!(
1012            !output.def_use_sites.is_empty(),
1013            "should find def-use sites for x"
1014        );
1015        assert!(
1016            output
1017                .def_use_sites
1018                .iter()
1019                .any(|s| s.kind == crate::types::DefUseKind::Write),
1020            "should have at least one Write site",
1021        );
1022        // No location appears as both write and read
1023        let write_locs: std::collections::HashSet<_> = output
1024            .def_use_sites
1025            .iter()
1026            .filter(|s| {
1027                matches!(
1028                    s.kind,
1029                    crate::types::DefUseKind::Write | crate::types::DefUseKind::WriteRead
1030                )
1031            })
1032            .map(|s| (&s.file, s.line, s.column))
1033            .collect();
1034        assert!(
1035            output
1036                .def_use_sites
1037                .iter()
1038                .filter(|s| s.kind == crate::types::DefUseKind::Read)
1039                .all(|s| !write_locs.contains(&(&s.file, s.line, s.column))),
1040            "no location should appear as both write and read",
1041        );
1042        assert!(
1043            output.formatted.contains("DEF-USE SITES"),
1044            "formatted output should contain DEF-USE SITES"
1045        );
1046    }
1047
1048    fn make_temp_file(content: &str) -> tempfile::NamedTempFile {
1049        let mut f = tempfile::NamedTempFile::new().unwrap();
1050        use std::io::Write;
1051        f.write_all(content.as_bytes()).unwrap();
1052        f.flush().unwrap();
1053        f
1054    }
1055}