code-analyze 0.1.1

Analyze code structure and relationships using tree-sitter
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
// Copyright 2024 Block, Inc. (original code from https://github.com/block/goose)
// Copyright 2025 utapyngo (modifications)
// SPDX-License-Identifier: Apache-2.0

use super::types::{
    AnalysisMode, AnalysisResult, CallChain, EntryType, FocusedAnalysisData, ReferenceType,
};
use crate::lang;
use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

fn safe_truncate(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_chars.saturating_sub(3)).collect();
        format!("{}...", truncated)
    }
}

pub struct Formatter;

impl Formatter {
    /// Format analysis result based on mode
    pub fn format_analysis_result(
        path: &Path,
        result: &AnalysisResult,
        mode: &AnalysisMode,
    ) -> String {
        match mode {
            AnalysisMode::Structure => Self::format_structure_overview(path, result),
            AnalysisMode::Semantic => Self::format_semantic_result(path, result),
            AnalysisMode::Focused => String::new(),
        }
    }

    /// Format structure overview (compact format)
    pub fn format_structure_overview(path: &Path, result: &AnalysisResult) -> String {
        let mut output = String::new();

        output.push_str(&format!("{} [{}L", path.display(), result.line_count));

        if result.function_count > 0 {
            output.push_str(&format!(", {}F", result.function_count));
        }

        if result.class_count > 0 {
            output.push_str(&format!(", {}C", result.class_count));
        }

        output.push(']');

        if let Some(main_line) = result.main_line {
            output.push_str(&format!(" main:{}", main_line));
        }

        output.push('\n');
        output
    }

    /// Format semantic analysis result (dense matrix format)
    pub fn format_semantic_result(path: &Path, result: &AnalysisResult) -> String {
        let mut output = format!(
            "FILE: {} [{}L, {}F, {}C]\n\n",
            path.display(),
            result.line_count,
            result.function_count,
            result.class_count
        );

        if !result.classes.is_empty() {
            output.push_str("C: ");
            let class_strs: Vec<String> = result
                .classes
                .iter()
                .map(|c| format!("{}:{}", c.name, c.line))
                .collect();
            output.push_str(&class_strs.join(" "));
            output.push_str("\n\n");
        }

        if !result.functions.is_empty() {
            output.push_str("F: ");

            let mut call_counts: HashMap<String, usize> = HashMap::new();
            for call in &result.calls {
                *call_counts.entry(call.callee_name.clone()).or_insert(0) += 1;
            }

            let func_strs: Vec<String> = result
                .functions
                .iter()
                .map(|f| {
                    let count = call_counts.get(&f.name).unwrap_or(&0);
                    if *count > 3 {
                        format!("{}:{}•{}", f.name, f.line, count)
                    } else {
                        format!("{}:{}", f.name, f.line)
                    }
                })
                .collect();

            let mut line_len = 3; // "F: "
            for (i, func_str) in func_strs.iter().enumerate() {
                if i > 0 && line_len + func_str.len() + 1 > 100 {
                    output.push_str("\n   ");
                    line_len = 3;
                }
                if i > 0 {
                    output.push(' ');
                    line_len += 1;
                }
                output.push_str(func_str);
                line_len += func_str.len();
            }
            output.push_str("\n\n");
        }

        if !result.imports.is_empty() {
            output.push_str("I: ");

            let mut grouped_imports: HashMap<String, Vec<String>> = HashMap::new();
            for import in &result.imports {
                let group = if import.starts_with("use ") {
                    import.split("::").next().unwrap_or("use").to_string()
                } else if import.starts_with("import ") {
                    import
                        .split_whitespace()
                        .nth(1)
                        .unwrap_or("import")
                        .to_string()
                } else if import.starts_with("from ") {
                    import
                        .split_whitespace()
                        .nth(1)
                        .unwrap_or("from")
                        .to_string()
                } else {
                    import.split_whitespace().next().unwrap_or("").to_string()
                };
                grouped_imports
                    .entry(group)
                    .or_default()
                    .push(import.clone());
            }

            let import_summary: Vec<String> = grouped_imports
                .iter()
                .map(|(group, imports)| {
                    if imports.len() > 1 {
                        format!("{}({})", group, imports.len())
                    } else {
                        safe_truncate(&imports[0], 40)
                    }
                })
                .collect();

            output.push_str(&import_summary.join("; "));
            output.push('\n');
        }

        if !result.references.is_empty() {
            Self::append_references(&mut output, result);
        }

        output
    }

    fn append_references(output: &mut String, result: &AnalysisResult) {
        let mut method_defs = Vec::new();
        let mut type_inst = Vec::new();
        let mut field_types = Vec::new();
        let mut var_types = Vec::new();
        let mut param_types = Vec::new();

        for ref_info in &result.references {
            match ref_info.ref_type {
                ReferenceType::MethodDefinition => method_defs.push(ref_info),
                ReferenceType::TypeInstantiation => type_inst.push(ref_info),
                ReferenceType::FieldType => field_types.push(ref_info),
                ReferenceType::VariableType => var_types.push(ref_info),
                ReferenceType::ParameterType => param_types.push(ref_info),
                ReferenceType::Call | ReferenceType::Definition | ReferenceType::Import => {}
            }
        }

        if method_defs.is_empty()
            && type_inst.is_empty()
            && field_types.is_empty()
            && var_types.is_empty()
            && param_types.is_empty()
        {
            return;
        }

        output.push_str("\nR: ");

        let mut sections = Vec::new();

        if !method_defs.is_empty() {
            let mut method_strs: Vec<String> = method_defs
                .iter()
                .map(|r| {
                    if let Some(type_name) = &r.associated_type {
                        format!("{}({})", r.symbol, type_name)
                    } else {
                        r.symbol.clone()
                    }
                })
                .collect();
            method_strs.sort();
            method_strs.dedup();
            sections.push(format!("methods[{}]", method_strs.join(" ")));
        }

        if !type_inst.is_empty() {
            let mut type_names: Vec<String> = type_inst.iter().map(|r| r.symbol.clone()).collect();
            type_names.sort();
            type_names.dedup();
            sections.push(format!("types[{}]", type_names.join(" ")));
        }

        if !field_types.is_empty() {
            let mut field_type_names: Vec<String> =
                field_types.iter().map(|r| r.symbol.clone()).collect();
            field_type_names.sort();
            field_type_names.dedup();
            sections.push(format!("fields[{}]", field_type_names.join(" ")));
        }

        if !var_types.is_empty() {
            let mut var_type_names: Vec<String> =
                var_types.iter().map(|r| r.symbol.clone()).collect();
            var_type_names.sort();
            var_type_names.dedup();
            sections.push(format!("vars[{}]", var_type_names.join(" ")));
        }

        if !param_types.is_empty() {
            let mut param_type_names: Vec<String> =
                param_types.iter().map(|r| r.symbol.clone()).collect();
            param_type_names.sort();
            param_type_names.dedup();
            sections.push(format!("params[{}]", param_type_names.join(" ")));
        }

        output.push_str(&sections.join("; "));
        output.push('\n');
    }

    /// Format directory structure with summary
    pub fn format_directory_structure(
        base_path: &Path,
        results: &[(PathBuf, EntryType)],
        max_depth: u32,
    ) -> String {
        let mut output = String::new();

        Self::append_summary(&mut output, results, max_depth);

        output.push_str("\nPATH [LOC, FUNCTIONS, CLASSES] <FLAGS>\n");

        Self::append_tree_structure(&mut output, base_path, results);

        output
    }

    fn append_summary(output: &mut String, results: &[(PathBuf, EntryType)], max_depth: u32) {
        let files: Vec<&AnalysisResult> = results
            .iter()
            .map(|(_, entry)| {
                let EntryType::File(result) = entry;
                result
            })
            .collect();

        let total_files = files.len();
        let total_lines: usize = files.iter().map(|r| r.line_count).sum();
        let total_functions: usize = files.iter().map(|r| r.function_count).sum();
        let total_classes: usize = files.iter().map(|r| r.class_count).sum();

        output.push_str("SUMMARY:\n");
        if max_depth == 0 {
            output.push_str(&format!(
                "Shown: {} files, {}L, {}F, {}C (unlimited depth)\n",
                total_files, total_lines, total_functions, total_classes
            ));
        } else {
            output.push_str(&format!(
                "Shown: {} files, {}L, {}F, {}C (max_depth={})\n",
                total_files, total_lines, total_functions, total_classes, max_depth
            ));
        }

        Self::append_language_stats(output, results, total_lines);
    }

    fn append_language_stats(
        output: &mut String,
        results: &[(PathBuf, EntryType)],
        total_lines: usize,
    ) {
        let mut language_lines: HashMap<String, usize> = HashMap::new();
        for (path, entry) in results {
            let EntryType::File(result) = entry;
            let lang_id = lang::get_language_identifier(path);
            if !lang_id.is_empty() && result.line_count > 0 {
                *language_lines.entry(lang_id.to_string()).or_insert(0) += result.line_count;
            }
        }

        if !language_lines.is_empty() && total_lines > 0 {
            let mut languages: Vec<_> = language_lines.iter().collect();
            languages.sort_by(|a, b| b.1.cmp(a.1));

            let lang_str: Vec<String> = languages
                .iter()
                .map(|(lang_name, lines)| {
                    let percentage = (**lines as f64 / total_lines as f64 * 100.0) as u32;
                    format!("{} ({}%)", lang_name, percentage)
                })
                .collect();

            output.push_str(&format!("Languages: {}\n", lang_str.join(", ")));
        }
    }

    fn append_tree_structure(
        output: &mut String,
        base_path: &Path,
        results: &[(PathBuf, EntryType)],
    ) {
        let mut sorted_results = results.to_vec();
        sorted_results.sort_by(|a, b| a.0.cmp(&b.0));

        let mut printed_dirs = HashSet::new();

        for (path, entry) in sorted_results {
            Self::format_tree_entry(output, base_path, &path, &entry, &mut printed_dirs);
        }
    }

    fn format_tree_entry(
        output: &mut String,
        base_path: &Path,
        path: &Path,
        entry: &EntryType,
        printed_dirs: &mut HashSet<PathBuf>,
    ) {
        let relative_path = path.strip_prefix(base_path).unwrap_or(path);

        let components: Vec<_> = relative_path.components().collect();
        if components.is_empty() {
            return;
        }

        for i in 0..components.len().saturating_sub(1) {
            let parent_path: PathBuf = components[..=i].iter().collect();
            if !printed_dirs.contains(&parent_path) {
                let indent = "  ".repeat(i);
                let dir_name = components[i].as_os_str().to_string_lossy();
                output.push_str(&format!("{}{}/\n", indent, dir_name));
                printed_dirs.insert(parent_path);
            }
        }

        let indent_level = components.len().saturating_sub(1);
        let indent = "  ".repeat(indent_level);

        let name = components
            .last()
            .map(|c| c.as_os_str().to_string_lossy().to_string())
            .unwrap_or_else(|| relative_path.display().to_string());

        Self::format_entry_line(output, &indent, &name, entry);
    }

    fn format_entry_line(output: &mut String, indent: &str, name: &str, entry: &EntryType) {
        match entry {
            EntryType::File(result) => {
                output.push_str(&format!("{}{} [{}L", indent, name, result.line_count));
                if result.function_count > 0 {
                    output.push_str(&format!(", {}F", result.function_count));
                }
                if result.class_count > 0 {
                    output.push_str(&format!(", {}C", result.class_count));
                }
                output.push(']');
                if let Some(main_line) = result.main_line {
                    output.push_str(&format!(" main:{}", main_line));
                }
                output.push('\n');
            }
        }
    }

    /// Format focused analysis output with call chains
    pub fn format_focused_output(focus_data: &FocusedAnalysisData) -> String {
        let mut output = format!("FOCUSED ANALYSIS: {}\n\n", focus_data.focus_symbol);

        let (file_map, sorted_files) = Self::build_file_aliases(
            focus_data.definitions,
            focus_data.incoming_chains,
            focus_data.outgoing_chains,
        );

        Self::append_definitions(
            &mut output,
            focus_data.definitions,
            &file_map,
            focus_data.focus_symbol,
        );

        Self::append_call_chains(
            &mut output,
            focus_data.incoming_chains,
            &file_map,
            focus_data.follow_depth,
            true,
        );

        Self::append_call_chains(
            &mut output,
            focus_data.outgoing_chains,
            &file_map,
            focus_data.follow_depth,
            false,
        );

        Self::append_statistics(
            &mut output,
            focus_data.files_analyzed,
            focus_data.definitions,
            focus_data.incoming_chains,
            focus_data.outgoing_chains,
            focus_data.follow_depth,
        );

        Self::append_file_legend(
            &mut output,
            &file_map,
            &sorted_files,
            focus_data.definitions,
            focus_data.incoming_chains,
            focus_data.outgoing_chains,
        );

        if focus_data.definitions.is_empty()
            && focus_data.incoming_chains.is_empty()
            && focus_data.outgoing_chains.is_empty()
        {
            output = format!(
                "Symbol '{}' not found in any analyzed files.\n",
                focus_data.focus_symbol
            );
        }

        output
    }

    fn build_file_aliases(
        definitions: &[(PathBuf, usize)],
        incoming_chains: &[CallChain],
        outgoing_chains: &[CallChain],
    ) -> (HashMap<PathBuf, String>, Vec<PathBuf>) {
        let mut all_files = HashSet::new();

        for (file, _) in definitions {
            all_files.insert(file.clone());
        }

        for chain in incoming_chains.iter().chain(outgoing_chains.iter()) {
            for (file, _, _, _) in &chain.path {
                all_files.insert(file.clone());
            }
        }

        let mut sorted_files: Vec<_> = all_files.into_iter().collect();
        sorted_files.sort();

        let mut file_map = HashMap::new();
        for (index, file) in sorted_files.iter().enumerate() {
            let alias = if sorted_files.len() == 1 {
                file.file_name()
                    .and_then(|n| n.to_str())
                    .unwrap_or("unknown")
                    .to_string()
            } else {
                format!("F{}", index + 1)
            };
            file_map.insert(file.clone(), alias);
        }

        (file_map, sorted_files)
    }

    fn append_definitions(
        output: &mut String,
        definitions: &[(PathBuf, usize)],
        file_map: &HashMap<PathBuf, String>,
        focus_symbol: &str,
    ) {
        if !definitions.is_empty() {
            output.push_str("DEFINITIONS:\n");
            for (file, line) in definitions {
                let alias = file_map.get(file).cloned().unwrap_or_else(|| {
                    file.file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("unknown")
                        .to_string()
                });
                output.push_str(&format!("{}:{} - {}\n", alias, line, focus_symbol));
            }
            output.push('\n');
        }
    }

    fn append_call_chains(
        output: &mut String,
        chains: &[CallChain],
        file_map: &HashMap<PathBuf, String>,
        follow_depth: u32,
        is_incoming: bool,
    ) {
        if !chains.is_empty() {
            let chain_type = if is_incoming { "INCOMING" } else { "OUTGOING" };
            output.push_str(&format!(
                "{} CALL CHAINS (depth={}):\n",
                chain_type, follow_depth
            ));

            let mut unique_chains = HashSet::new();
            for chain in chains {
                let chain_str = Self::format_chain_path(&chain.path, file_map);
                unique_chains.insert(chain_str);
            }

            let mut sorted_chains: Vec<_> = unique_chains.into_iter().collect();
            sorted_chains.sort();

            for chain in sorted_chains {
                output.push_str(&format!("{}\n", chain));
            }
            output.push('\n');
        }
    }

    fn format_chain_path(
        path: &[(PathBuf, usize, String, String)],
        file_map: &HashMap<PathBuf, String>,
    ) -> String {
        path.iter()
            .map(|(file, line, from, to)| {
                let alias = file_map.get(file).cloned().unwrap_or_else(|| {
                    file.file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("unknown")
                        .to_string()
                });
                format!("{}:{} ({} -> {})", alias, line, from, to)
            })
            .collect::<Vec<_>>()
            .join(" -> ")
    }

    fn append_statistics(
        output: &mut String,
        files_analyzed: &[PathBuf],
        definitions: &[(PathBuf, usize)],
        incoming_chains: &[CallChain],
        outgoing_chains: &[CallChain],
        follow_depth: u32,
    ) {
        output.push_str("STATISTICS:\n");
        output.push_str(&format!("  Files analyzed: {}\n", files_analyzed.len()));
        output.push_str(&format!("  Definitions found: {}\n", definitions.len()));
        output.push_str(&format!("  Incoming chains: {}\n", incoming_chains.len()));
        output.push_str(&format!("  Outgoing chains: {}\n", outgoing_chains.len()));
        output.push_str(&format!("  Follow depth: {}\n", follow_depth));
    }

    fn append_file_legend(
        output: &mut String,
        file_map: &HashMap<PathBuf, String>,
        sorted_files: &[PathBuf],
        definitions: &[(PathBuf, usize)],
        incoming_chains: &[CallChain],
        outgoing_chains: &[CallChain],
    ) {
        if !file_map.is_empty()
            && (sorted_files.len() > 1
                || !incoming_chains.is_empty()
                || !outgoing_chains.is_empty()
                || !definitions.is_empty())
        {
            output.push_str("\nFILES:\n");
            let mut legend_entries: Vec<_> = file_map.iter().collect();
            legend_entries.sort_by_key(|(_, alias)| alias.as_str());

            for (file_path, alias) in legend_entries {
                if sorted_files.len() == 1
                    && alias == file_path.file_name().and_then(|n| n.to_str()).unwrap_or("")
                {
                    continue;
                }
                output.push_str(&format!("  {}: {}\n", alias, file_path.display()));
            }
        }
    }

    /// Filter output by focus symbol
    pub fn filter_by_focus(output: &str, focus: &str) -> String {
        let mut filtered = String::new();
        let mut include_section = false;

        for line in output.lines() {
            if line.starts_with("##") {
                include_section = false;
            }

            if line.contains(focus) {
                include_section = true;
                if let Some(header_line) = output
                    .lines()
                    .rev()
                    .find(|l| l.starts_with("##") && l.get(3..).is_some_and(|s| line.contains(s)))
                    && !filtered.contains(header_line)
                {
                    filtered.push_str(header_line);
                    filtered.push('\n');
                }
            }

            if include_section || line.starts_with('#') {
                filtered.push_str(line);
                filtered.push('\n');
            }
        }

        if filtered.is_empty() {
            format!("No results found for symbol: {}", focus)
        } else {
            filtered
        }
    }
}