codanna 0.9.19

Code Intelligence for Large Language Models
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
//! Benchmark command - parser performance testing.

use std::path::PathBuf;
use std::time::Instant;

use crate::display::tables::create_benchmark_table;
use crate::display::theme::Theme;
use crate::parsing::{
    CSharpParser, GoParser, LanguageParser, LuaParser, PhpParser, PythonParser, RustParser,
    TypeScriptParser,
};
use crate::types::{FileId, SymbolCounter};
use console::style;

/// Run parser performance benchmarks
pub fn run(language: &str, custom_file: Option<PathBuf>) {
    // Print styled header
    if Theme::should_disable_colors() {
        println!("\n=== Codanna Parser Benchmarks ===\n");
    } else {
        println!(
            "\n{}\n",
            style("=== Codanna Parser Benchmarks ===").cyan().bold()
        );
    }

    match language.to_lowercase().as_str() {
        "rust" => benchmark_rust_parser(custom_file),
        "python" => benchmark_python_parser(custom_file),
        "php" => benchmark_php_parser(custom_file),
        "typescript" | "ts" => benchmark_typescript_parser(custom_file),
        "go" => benchmark_go_parser(custom_file),
        "lua" => benchmark_lua_parser(custom_file),
        "csharp" | "c#" | "cs" => benchmark_csharp_parser(custom_file),
        "all" => {
            benchmark_csharp_parser(None);
            println!();
            benchmark_go_parser(None);
            println!();
            benchmark_lua_parser(None);
            println!();
            benchmark_php_parser(None);
            println!();
            benchmark_python_parser(None);
            println!();
            benchmark_rust_parser(None);
            println!();
            benchmark_typescript_parser(None);
        }
        _ => {
            eprintln!("Unknown language: {language}");
            eprintln!("Available languages: csharp, go, lua, php, python, rust, typescript, all");
            std::process::exit(1);
        }
    }

    // Print target info with styling
    if Theme::should_disable_colors() {
        println!("\nTarget: >10,000 symbols/second");
    } else {
        println!(
            "\n{}: {}",
            style("Target").dim(),
            style(">10,000 symbols/second").dim()
        );
    }
}

fn benchmark_rust_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_rust_benchmark_code(), None)
    };

    let mut parser = RustParser::new().expect("Failed to create Rust parser");
    benchmark_parser("Rust", &mut parser, &code, file_path);
}

fn benchmark_python_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else if std::path::Path::new("tests/python_comprehensive_features.py").exists() {
        match std::fs::read_to_string("tests/python_comprehensive_features.py") {
            Ok(content) => (content, None),
            Err(e) => {
                eprintln!("Warning: Failed to read test file: {e}");
                eprintln!("Generating benchmark code instead...");
                (generate_python_benchmark_code(), None)
            }
        }
    } else {
        (generate_python_benchmark_code(), None)
    };

    let mut parser = PythonParser::new().expect("Failed to create Python parser");
    benchmark_parser("Python", &mut parser, &code, file_path);
}

fn benchmark_php_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_php_benchmark_code(), None)
    };

    let mut parser = PhpParser::new().expect("Failed to create PHP parser");
    benchmark_parser("PHP", &mut parser, &code, file_path);
}

fn benchmark_typescript_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_typescript_benchmark_code(), None)
    };

    let mut parser = TypeScriptParser::new().expect("Failed to create TypeScript parser");
    benchmark_parser("TypeScript", &mut parser, &code, file_path);
}

fn benchmark_go_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_go_benchmark_code(), None)
    };

    let mut parser = GoParser::new().expect("Failed to create Go parser");
    benchmark_parser("Go", &mut parser, &code, file_path);
}

fn benchmark_lua_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_lua_benchmark_code(), None)
    };

    let mut parser = LuaParser::new().expect("Failed to create Lua parser");
    benchmark_parser("Lua", &mut parser, &code, file_path);
}

fn benchmark_csharp_parser(custom_file: Option<PathBuf>) {
    let (code, file_path) = if let Some(path) = custom_file {
        let content = std::fs::read_to_string(&path).unwrap_or_else(|e| {
            eprintln!("Failed to read {}: {e}", path.display());
            std::process::exit(1);
        });
        (content, Some(path))
    } else {
        (generate_csharp_benchmark_code(), None)
    };

    let mut parser = CSharpParser::new().expect("Failed to create C# parser");
    benchmark_parser("C#", &mut parser, &code, file_path);
}

fn benchmark_parser(
    language: &str,
    parser: &mut dyn LanguageParser,
    code: &str,
    file_path: Option<PathBuf>,
) {
    let file_id = FileId::new(1).expect("Failed to create file ID");
    let mut counter = SymbolCounter::new();

    // Warm up
    let _ = parser.parse(code, file_id, &mut counter);

    // Measure parsing performance (average of 3 runs)
    let mut total_duration = std::time::Duration::ZERO;
    let mut symbols_count = 0;

    for _ in 0..3 {
        counter = SymbolCounter::new();
        let start = Instant::now();
        let symbols = parser.parse(code, file_id, &mut counter);
        total_duration += start.elapsed();
        symbols_count = symbols.len();
    }

    let avg_duration = total_duration / 3;
    let rate = symbols_count as f64 / avg_duration.as_secs_f64();

    let table = create_benchmark_table(
        language,
        file_path
            .as_ref()
            .map(|p| p.to_str().unwrap_or("<invalid path>")),
        symbols_count,
        avg_duration,
        rate,
    );

    println!("\n{table}");

    // Verify zero-cost abstractions (silently)
    let calls = parser.find_calls(code);
    if !calls.is_empty() {
        let (caller, _callee, _) = &calls[0];
        let caller_ptr = caller.as_ptr();
        let code_ptr = code.as_ptr();
        let within_bounds =
            caller_ptr >= code_ptr && caller_ptr < unsafe { code_ptr.add(code.len()) };

        if !within_bounds {
            println!("\nWarning: String allocation detected!");
        }
    }
}

fn generate_rust_benchmark_code() -> String {
    let mut code = String::from("//! Rust benchmark file\n\n");

    // Generate 500 functions
    for i in 0..500 {
        code.push_str(&format!(
            r#"/// Function {i} documentation
fn function_{i}(param1: i32, param2: &str) -> bool {{
    let result = param1 * 2;
    result > 0
}}

"#
        ));
    }

    // Generate 50 structs with methods
    for i in 0..50 {
        code.push_str(&format!(
            r#"/// Struct {i} documentation
struct Struct{i} {{
    value: i32,
}}

impl Struct{i} {{
    fn new(value: i32) -> Self {{
        Self {{ value }}
    }}

    fn method_a(&self) -> i32 {{
        self.value * 2
    }}
}}

"#
        ));
    }

    code
}

fn generate_python_benchmark_code() -> String {
    let mut code = String::from("\"\"\"Python benchmark file\"\"\"\n\n");

    // Generate 500 functions
    for i in 0..500 {
        code.push_str(&format!(
            r#"def function_{i}(param1: int, param2: str = 'default') -> bool:
    """Function {i} documentation."""
    result = param1 * 2
    return result > 0

"#
        ));
    }

    // Generate 50 classes
    for i in 0..50 {
        code.push_str(&format!(
            r#"class Class_{i}:
    """Class {i} documentation."""

    def __init__(self, value: int):
        self.value = value

    def method_a(self) -> int:
        return self.value * 2

"#
        ));
    }

    code
}

fn generate_php_benchmark_code() -> String {
    let mut code = String::from("<?php\n/**\n * PHP benchmark file\n */\n\n");

    // Generate 500 functions
    for i in 0..500 {
        code.push_str(&format!(
            r#"/**
 * Function {i} documentation
 */
function function_{i}(int $param1, string $param2 = 'default'): bool {{
    $result = $param1 * 2;
    return $result > 0;
}}

"#
        ));
    }

    // Generate 50 classes with methods
    for i in 0..50 {
        code.push_str(&format!(
            r#"/**
 * Class {i} documentation
 */
class Class_{i} {{
    private int $value;

    public function __construct(int $value) {{
        $this->value = $value;
    }}

    public function methodA(): int {{
        return $this->value * 2;
    }}

    public function methodB(string $param): string {{
        return strtoupper($param);
    }}
}}

"#
        ));
    }

    // Generate 25 interfaces
    for i in 0..25 {
        code.push_str(&format!(
            r#"interface Interface_{i} {{
    public function method_{i}(): void;
}}

"#
        ));
    }

    // Generate 25 traits
    for i in 0..25 {
        code.push_str(&format!(
            r#"trait Trait_{i} {{
    public function traitMethod_{i}(): string {{
        return 'trait_{i}';
    }}
}}

"#
        ));
    }

    code.push_str("?>");
    code
}

fn generate_typescript_benchmark_code() -> String {
    let mut code = String::from("// TypeScript benchmark file\n\n");

    // Generate 500 functions with various TypeScript features
    for i in 0..500 {
        code.push_str(&format!(
            r#"/**
 * Function {i} documentation
 * @param param1 The first parameter
 * @param param2 The second parameter
 * @returns A boolean result
 */
export function function_{i}(param1: number, param2: string = 'default'): boolean {{
    const result = param1 > 0 && param2.length > 0;
    return result;
}}

"#
        ));
    }

    // Generate 50 interfaces
    for i in 0..50 {
        code.push_str(&format!(
            r#"/**
 * Interface {i} for data structure
 */
export interface Interface_{i} {{
    id: number;
    name: string;
    optional?: boolean;
    readonly immutable: string;
    method(param: string): void;
}}

"#
        ));
    }

    // Generate 50 classes with methods
    for i in 0..50 {
        code.push_str(&format!(
            r#"/**
 * Class {i} implementation
 */
export class Class_{i} implements Interface_{i} {{
    public id: number;
    public name: string;
    public optional?: boolean;
    public readonly immutable: string;
    private _internal: number;
    protected _protected: string;

    constructor(id: number, name: string) {{
        this.id = id;
        this.name = name;
        this.immutable = 'fixed';
        this._internal = 0;
        this._protected = 'protected';
    }}

    public method(param: string): void {{
        console.log(param);
    }}

    private privateMethod(): number {{
        return this._internal;
    }}

    protected protectedMethod(): string {{
        return this._protected;
    }}

    static staticMethod(): void {{
        console.log('static');
    }}
}}

"#
        ));
    }

    // Generate 50 type aliases
    for i in 0..50 {
        code.push_str(&format!(
            r#"/**
 * Type alias {i}
 */
export type TypeAlias_{i} = string | number | boolean;

type ComplexType_{i} = {{
    field1: TypeAlias_{i};
    field2: Interface_{i};
    field3: (param: string) => void;
}};

"#
        ));
    }

    // Generate 50 enums
    for i in 0..50 {
        code.push_str(&format!(
            r#"/**
 * Enum {i} definition
 */
export enum Enum_{i} {{
    First = 0,
    Second = 1,
    Third = 'three',
    Fourth = 'four'
}}

"#
        ));
    }

    // Add some arrow functions and const declarations
    for i in 0..50 {
        code.push_str(&format!(
            r#"export const arrowFunction_{i} = (x: number, y: number): number => x + y;

export const constant_{i}: string = 'constant value';

let variable_{i}: number = {i};

"#
        ));
    }

    code
}

fn generate_go_benchmark_code() -> String {
    let mut code =
        String::from("// Go benchmark file\n\npackage bench\n\nimport (\n\t\"fmt\"\n)\n\n");

    // Generate 500 free functions
    for i in 0..500 {
        code.push_str(&format!(
            r#"// Function {i} documentation
func Function_{i}(param1 int, param2 string) bool {{
    result := param1 * 2
    return result > 0 && len(param2) > 0
}}

"#
        ));
    }

    // Generate 50 structs with methods and interface satisfaction
    for i in 0..50 {
        code.push_str(&format!(
            r#"// Struct {i} documentation
type Struct{i} struct {{
    Value int
}}

func NewStruct{i}(v int) *Struct{i} {{
    return &Struct{i}{{Value: v}}
}}

func (s *Struct{i}) MethodA() int {{
    return s.Value * 2
}}

func (s *Struct{i}) Do(param string) int {{
    fmt.Println(param)
    return len(param) + s.Value
}}

"#
        ));
    }

    // Generate 25 interfaces
    for i in 0..25 {
        code.push_str(&format!(
            r#"// Interface {i} documentation
type Interface_{i} interface {{
    Do(param string) int
}}

"#
        ));
    }

    // A small main-like entry to keep parser busy with calls/selectors
    code.push_str(
        r#"// Entry point (not used, just for call patterns)
func main() {
    s := NewStruct0(42)
    _ = s.MethodA()
    _ = s.Do("hello")
    ok := Function_0(1, "x")
    if ok {
        fmt.Println("ok")
    }
}
"#,
    );

    code
}

fn generate_lua_benchmark_code() -> String {
    let mut code = String::from("-- Lua benchmark file\n\nlocal M = {}\n\n");

    // Generate 500 functions
    for i in 0..500 {
        code.push_str(&format!(
            r#"--- Function {i} documentation
--- @param param1 number The first parameter
--- @param param2 string The second parameter
--- @return boolean
function M.function_{i}(param1, param2)
    local result = param1 * 2
    return result > 0 and #param2 > 0
end

"#
        ));
    }

    // Generate 50 "classes" (table-based OOP)
    for i in 0..50 {
        code.push_str(&format!(
            r#"--- Class {i} documentation
local Class{i} = {{}}
Class{i}.__index = Class{i}

function Class{i}:new(value)
    local instance = setmetatable({{}}, self)
    instance.value = value
    return instance
end

function Class{i}:methodA()
    return self.value * 2
end

function Class{i}:methodB(param)
    return string.upper(param)
end

M.Class{i} = Class{i}

"#
        ));
    }

    // Generate 25 local helper functions
    for i in 0..25 {
        code.push_str(&format!(
            r#"local function _helper_{i}(data)
    return data * {i}
end

"#
        ));
    }

    // Generate some module-level variables and constants
    for i in 0..25 {
        code.push_str(&format!(
            r#"local CONSTANT_{i} = {i}
local variable_{i} = "value_{i}"

"#
        ));
    }

    code.push_str("return M\n");
    code
}

fn generate_csharp_benchmark_code() -> String {
    let mut code = String::from(
        "// C# benchmark file\n\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace BenchmarkNamespace\n{\n",
    );

    // Generate 500 static classes with methods
    for i in 0..500 {
        code.push_str(&format!(
            r#"    /// <summary>
    /// Static class {i} documentation
    /// </summary>
    public static class StaticClass{i}
    {{
        public static int Method{i}(int param)
        {{
            return param * 2;
        }}

        public static string Process{i}(string input)
        {{
            return input.ToUpper();
        }}
    }}

"#
        ));
    }

    // Generate 50 classes with properties/fields/constructors
    for i in 0..50 {
        code.push_str(&format!(
            r#"    /// <summary>
    /// Class {i} documentation
    /// </summary>
    public class Class{i}
    {{
        private int _value;

        public int Value {{ get; set; }}
        public string Name {{ get; set; }}

        public Class{i}(int value, string name)
        {{
            _value = value;
            Value = value;
            Name = name;
        }}

        public int Calculate()
        {{
            return _value * 2;
        }}

        public void Process(string input)
        {{
            Console.WriteLine(input);
        }}
    }}

"#
        ));
    }

    // Generate 25 interfaces
    for i in 0..25 {
        code.push_str(&format!(
            r#"    /// <summary>
    /// Interface {i} documentation
    /// </summary>
    public interface IInterface{i}
    {{
        void Process(string input);
        int Calculate();
    }}

"#
        ));
    }

    // Program class with Main method
    code.push_str(
        r#"    /// <summary>
    /// Entry point class
    /// </summary>
    class Program
    {
        static void Main(string[] args)
        {
            var obj = new Class0(42, "test");
            var result = obj.Calculate();
            obj.Process("hello");

            var staticResult = StaticClass0.Method0(10);
            var processed = StaticClass0.Process0("world");

            Console.WriteLine($"Result: {result}, Static: {staticResult}, Processed: {processed}");
        }
    }
}
"#,
    );

    code
}