patchloom 0.11.0

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
use super::*;
use crate::ast::rewrite::replace_function_signature;

#[test]
fn check_no_overlapping_spans_ok() {
    // Non-overlapping spans should pass
    let spans = vec![(0, 3), (4, 7), (8, 10)];
    let names = vec!["a", "b", "c"];
    check_no_overlapping_spans(&spans, &names).unwrap();
}

#[test]
fn check_no_overlapping_spans_adjacent_ok() {
    // Adjacent (touching but not overlapping) spans should pass
    let spans = vec![(0, 3), (3, 6), (6, 9)];
    let names = vec!["a", "b", "c"];
    check_no_overlapping_spans(&spans, &names).unwrap();
}

#[test]
fn check_no_overlapping_spans_detects_overlap() {
    // Overlapping spans should error
    let spans = vec![(0, 5), (3, 8)];
    let names = vec!["foo", "bar"];
    let err = check_no_overlapping_spans(&spans, &names).unwrap_err();
    let msg = err.to_string();
    assert!(msg.contains("overlapping"), "error: {msg}");
    assert!(
        msg.contains("foo"),
        "error should mention first symbol: {msg}"
    );
    assert!(
        msg.contains("bar"),
        "error should mention second symbol: {msg}"
    );
}

#[test]
fn check_no_overlapping_spans_detects_containment() {
    // One span fully inside another should error
    let spans = vec![(0, 10), (2, 5)];
    let names = vec!["outer", "inner"];
    let err = check_no_overlapping_spans(&spans, &names).unwrap_err();
    assert!(err.to_string().contains("overlapping"));
}

#[test]
fn check_no_overlapping_spans_single_ok() {
    // Single span should always pass
    let spans = vec![(0, 5)];
    let names = vec!["only"];
    check_no_overlapping_spans(&spans, &names).unwrap();
}

#[test]
fn check_no_overlapping_spans_empty_ok() {
    check_no_overlapping_spans(&[], &[]).unwrap();
}

#[test]
fn extract_rust_symbols() {
    let source = r#"
struct Foo {
    x: i32,
}

fn bar() -> i32 {
    42
}

impl Foo {
    fn baz(&self) -> i32 {
        self.x
    }
}
"#;
    let symbols = extract_symbols(source, Language::Rust);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Foo"));
    assert!(names.contains(&"bar"));
    // impl Foo should contain baz as a child
    let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
    assert_eq!(impl_sym.name, "Foo");
    assert_eq!(impl_sym.children.len(), 1);
    assert_eq!(impl_sym.children[0].name, "baz");
}

#[test]
fn rust_impl_trait_extracts_type_not_trait() {
    // Regression: `impl Display for Foo` returned "Display" (the trait)
    // because child_text_by_kind found the first type_identifier.
    // The fix uses child_by_field_name("type") to get the target type.
    let source = r#"
use std::fmt;

struct Foo;

impl fmt::Display for Foo {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Foo")
    }
}
"#;
    let symbols = extract_symbols(source, Language::Rust);
    let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
    assert_eq!(
        impl_sym.name, "Foo",
        "impl target should be Foo, not the trait"
    );
}

#[test]
fn rust_impl_without_trait() {
    // Inherent impl (no trait) should still extract the type name.
    let source = "struct Bar;\nimpl Bar { fn go(&self) {} }\n";
    let symbols = extract_symbols(source, Language::Rust);
    let impl_sym = symbols.iter().find(|s| s.kind == SymbolKind::Impl).unwrap();
    assert_eq!(impl_sym.name, "Bar");
}

#[test]
fn extract_python_symbols() {
    let source = r#"
class MyClass:
    def method(self):
        pass

def standalone():
    pass
"#;
    let symbols = extract_symbols(source, Language::Python);
    let class = symbols.iter().find(|s| s.name == "MyClass").unwrap();
    assert_eq!(class.kind, SymbolKind::Class);
    assert_eq!(class.children.len(), 1);
    assert_eq!(class.children[0].name, "method");
    assert_eq!(class.children[0].kind, SymbolKind::Method);

    let func = symbols.iter().find(|s| s.name == "standalone").unwrap();
    assert_eq!(func.kind, SymbolKind::Function);
}

#[test]
fn extract_python_decorated_method() {
    // Regression: decorated methods have an extra `decorated_definition`
    // wrapper, so the grandparent check for `class_definition` failed.
    let source = "class Foo:\n    @staticmethod\n    def bar():\n        pass\n";
    let symbols = extract_symbols(source, Language::Python);
    let class = symbols.iter().find(|s| s.name == "Foo").unwrap();
    assert_eq!(class.children.len(), 1);
    assert_eq!(class.children[0].name, "bar");
    assert_eq!(
        class.children[0].kind,
        SymbolKind::Method,
        "decorated method should be classified as Method, not Function"
    );
}

#[test]
fn extract_go_symbols() {
    let source = r#"
package main

func main() {
    fmt.Println("hello")
}

type Config struct {
    Host string
}
"#;
    let symbols = extract_symbols(source, Language::Go);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"main"));
    assert!(names.contains(&"Config"));
}

#[test]
fn go_grouped_type_declaration() {
    // Regression: grouped `type (...)` blocks only returned the first type_spec.
    // The fix matches `type_spec` instead of `type_declaration` so visit_node
    // recurses into each spec independently.
    let source = "package main\n\ntype (\n\tPoint struct{ X, Y int }\n\tReader interface{ Read([]byte) (int, error) }\n\tAlias = int\n)\n";
    let symbols = extract_symbols(source, Language::Go);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Point"), "missing Point, got {:?}", names);
    assert!(names.contains(&"Reader"), "missing Reader, got {:?}", names);
    assert!(names.contains(&"Alias"), "missing Alias, got {:?}", names);
    let point = symbols.iter().find(|s| s.name == "Point").unwrap();
    assert_eq!(point.kind, SymbolKind::Struct);
    let reader = symbols.iter().find(|s| s.name == "Reader").unwrap();
    assert_eq!(reader.kind, SymbolKind::Interface);
}

#[test]
fn find_symbol_qualified() {
    let source = r#"
impl Server {
    fn start(&self) {}
    fn stop(&self) {}
}
"#;
    let symbols = extract_symbols(source, Language::Rust);
    let found = find_symbol(&symbols, "Server::start").expect("should find Server::start");
    assert_eq!(found.name, "start");
}

#[test]
fn find_symbol_unqualified_searches_children() {
    let source = r#"
impl Server {
    fn start(&self) {}
}
"#;
    let symbols = extract_symbols(source, Language::Rust);
    find_symbol(&symbols, "start").expect("should find 'start' via unqualified search");
}

/// find_symbol should recurse into deeply nested children, not just
/// one level (#1111 item 5).
#[test]
fn find_symbol_deeply_nested() {
    // Build a 3-level hierarchy: mod > struct > method
    let inner = SymbolDef {
        name: "deep_method".into(),
        kind: SymbolKind::Method,
        start_line: 3,
        end_line: 4,
        signature: "fn deep_method()".into(),
        children: Vec::new(),
        depth: 2,
    };
    let mid = SymbolDef {
        name: "MidStruct".into(),
        kind: SymbolKind::Struct,
        start_line: 2,
        end_line: 5,
        signature: "struct MidStruct".into(),
        children: vec![inner],
        depth: 1,
    };
    let outer = SymbolDef {
        name: "outer_mod".into(),
        kind: SymbolKind::Module,
        start_line: 1,
        end_line: 6,
        signature: "mod outer_mod".into(),
        children: vec![mid],
        depth: 0,
    };
    let symbols = vec![outer];

    // Unqualified search should find a deeply nested symbol
    find_symbol(&symbols, "deep_method").expect("should find deeply nested symbol");

    // Qualified search with multiple :: should work recursively
    find_symbol(&symbols, "outer_mod::MidStruct").expect("should find qualified nested symbol");
}

/// Regression: when a struct and its impl block share the same name,
/// find_symbol must try all parents with a matching name, not just the
/// first. The struct has no children, so `Point::new` should resolve
/// via the impl block's children.
#[test]
fn find_symbol_qualified_skips_struct_to_impl() {
    let source = r#"
struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Self {
        Self { x, y }
    }
}
"#;
    let symbols = extract_symbols(source, Language::Rust);
    let found = find_symbol(&symbols, "Point::new").expect("should find Point::new via impl");
    assert_eq!(found.name, "new");
}

#[test]
fn symbol_kind_from_str() {
    assert_eq!(
        SymbolKind::from_str_loose("function"),
        Some(SymbolKind::Function)
    );
    assert_eq!(SymbolKind::from_str_loose("fn"), Some(SymbolKind::Function));
    assert_eq!(
        SymbolKind::from_str_loose("struct"),
        Some(SymbolKind::Struct)
    );
    assert_eq!(SymbolKind::from_str_loose("CONST"), Some(SymbolKind::Const));
    assert_eq!(SymbolKind::from_str_loose("unknown"), None);
}

#[test]
fn unknown_language_returns_empty() {
    assert!(extract_symbols("anything", Language::Unknown).is_empty());
}

#[test]
fn signature_truncates_at_brace() {
    let source = "fn hello(x: i32) {\n    x + 1\n}\n";
    let symbols = extract_symbols(source, Language::Rust);
    assert_eq!(symbols[0].signature, "fn hello(x: i32)");
}

#[test]
fn replace_function_signature_basic() {
    let src = "fn old(a: i32) -> i32 { a }\nfn other() {}";
    let res = replace_function_signature(src, "old", "pub fn new(b: u32) -> u32");
    let out = res.expect("replace_function_signature should succeed for matching name");
    assert!(out.contains("pub fn new(b: u32) -> u32"));
    assert!(out.contains("fn other"));
    assert!(!out.contains("fn old"));
    // Regression: body must be preserved (was deleted when using "body"
    // node kind instead of "block").
    assert!(
        out.contains("{ a }"),
        "function body should be preserved: {out}"
    );
}

#[test]
fn extract_typescript_symbols() {
    let source = r#"
class Foo {
    greet(name: string): string {
        return `Hello, ${name}`;
    }

    farewell(): void {
        console.log("bye");
    }
}

function bar(x: number): number {
    return x * 2;
}

interface Baz {
    id: number;
    name: string;
}

enum Status {
    Active,
    Inactive,
    Pending,
}

const MAX_RETRIES = 5;
"#;
    let symbols = extract_symbols(source, Language::TypeScript);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Foo"), "should find class Foo");
    assert!(names.contains(&"bar"), "should find function bar");
    assert!(names.contains(&"Baz"), "should find interface Baz");
    assert!(names.contains(&"Status"), "should find enum Status");
    assert!(
        names.contains(&"MAX_RETRIES"),
        "should find const MAX_RETRIES"
    );

    // Class Foo should have methods as children
    let class_foo = symbols.iter().find(|s| s.name == "Foo").unwrap();
    assert_eq!(class_foo.kind, SymbolKind::Class);
    let child_names: Vec<&str> = class_foo.children.iter().map(|c| c.name.as_str()).collect();
    assert!(
        child_names.contains(&"greet"),
        "Foo should contain method greet"
    );
    assert!(
        child_names.contains(&"farewell"),
        "Foo should contain method farewell"
    );

    // Interface
    let iface = symbols.iter().find(|s| s.name == "Baz").unwrap();
    assert_eq!(iface.kind, SymbolKind::Interface);

    // Enum
    let status = symbols.iter().find(|s| s.name == "Status").unwrap();
    assert_eq!(status.kind, SymbolKind::Enum);
}

/// Multi-declarator `const a = 1, b = 2, c = 3;` should emit one symbol
/// per declarator, not just the first one (#1104).
#[test]
fn extract_typescript_multi_declarator_const() {
    let source = "const a = 1, b = 2, c = 3;\n";
    let symbols = extract_symbols(source, Language::TypeScript);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"a"), "should find const a: {names:?}");
    assert!(names.contains(&"b"), "should find const b: {names:?}");
    assert!(names.contains(&"c"), "should find const c: {names:?}");
    assert_eq!(
        symbols.len(),
        3,
        "exactly 3 symbols for 3 declarators: {names:?}"
    );
}

/// `let` and `var` declarators should NOT be extracted (only `const`).
#[test]
fn extract_typescript_let_var_not_extracted() {
    let source = "let x = 1, y = 2;\nvar z = 3;\n";
    let symbols = extract_symbols(source, Language::TypeScript);
    assert!(
        symbols.is_empty(),
        "let/var should not produce symbols: {:?}",
        symbols.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

#[test]
fn extract_java_symbols() {
    let source = r#"
public class Foo {
    private int count;

    public void bar() {
        System.out.println("hello");
    }

    public int getCount() {
        return count;
    }
}

interface Baz {
    void process();
    String getName();
}

enum Status {
    ACTIVE,
    INACTIVE,
    PENDING
}
"#;
    let symbols = extract_symbols(source, Language::Java);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Foo"), "should find class Foo");
    assert!(names.contains(&"Baz"), "should find interface Baz");
    assert!(names.contains(&"Status"), "should find enum Status");

    // Class Foo should have method children
    let class_foo = symbols.iter().find(|s| s.name == "Foo").unwrap();
    assert_eq!(class_foo.kind, SymbolKind::Class);
    let child_names: Vec<&str> = class_foo.children.iter().map(|c| c.name.as_str()).collect();
    assert!(
        child_names.contains(&"bar"),
        "Foo should contain method bar"
    );
    assert!(
        child_names.contains(&"getCount"),
        "Foo should contain method getCount"
    );

    // Interface
    let iface = symbols.iter().find(|s| s.name == "Baz").unwrap();
    assert_eq!(iface.kind, SymbolKind::Interface);

    // Enum
    let status = symbols.iter().find(|s| s.name == "Status").unwrap();
    assert_eq!(status.kind, SymbolKind::Enum);
}

#[test]
fn extract_c_symbols() {
    let source = r#"
#include <stdio.h>

void foo(int x) {
    printf("%d\n", x);
}

int calculate(int a, int b) {
    return a + b;
}

struct Bar {
    int x;
    int y;
    char name[64];
};

enum Color {
    RED,
    GREEN,
    BLUE
};
"#;
    let symbols = extract_symbols(source, Language::C);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"foo"), "should find function foo");
    assert!(
        names.contains(&"calculate"),
        "should find function calculate"
    );
    assert!(names.contains(&"Bar"), "should find struct Bar");
    assert!(names.contains(&"Color"), "should find enum Color");

    // Check kinds
    let foo_sym = symbols.iter().find(|s| s.name == "foo").unwrap();
    assert_eq!(foo_sym.kind, SymbolKind::Function);

    let bar_sym = symbols.iter().find(|s| s.name == "Bar").unwrap();
    assert_eq!(bar_sym.kind, SymbolKind::Struct);

    let color_sym = symbols.iter().find(|s| s.name == "Color").unwrap();
    assert_eq!(color_sym.kind, SymbolKind::Enum);
}

/// Regression: C functions returning pointer types (e.g. `int *func()`,
/// `void *func()`, `Foo *func()`) were either missing from `ast list`
/// or mislabeled with the return type name. The root cause was that
/// `extract_generic` checked direct `type_identifier` children (the
/// return type) before checking declarator children (the function name),
/// and the declarator recursion was only one level deep while pointer
/// declarators nest two levels: `pointer_declarator -> function_declarator
/// -> identifier`.
#[test]
fn extract_c_pointer_returning_functions() {
    let source = r#"
int *pointer_func(void) { return 0; }
void *void_ptr_func(void) { return 0; }
char *string_func(void) { return "hello"; }

typedef struct Foo { int x; } Foo;
Foo *foo_create(void) { return 0; }
"#;
    let symbols = extract_symbols(source, Language::C);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"pointer_func"),
        "should find int* function: {names:?}"
    );
    assert!(
        names.contains(&"void_ptr_func"),
        "should find void* function: {names:?}"
    );
    assert!(
        names.contains(&"string_func"),
        "should find char* function: {names:?}"
    );
    assert!(
        names.contains(&"foo_create"),
        "should find Foo* function (not mislabeled as 'Foo'): {names:?}"
    );

    // Verify they are classified as functions, not structs/types
    for fname in &["pointer_func", "void_ptr_func", "string_func", "foo_create"] {
        let sym = symbols.iter().find(|s| s.name == *fname).unwrap();
        assert_eq!(
            sym.kind,
            SymbolKind::Function,
            "{fname} should be Function, got {:?}",
            sym.kind
        );
    }
}

#[test]
fn extract_cpp_symbols() {
    let source = r#"
#include <iostream>
#include <string>

class Engine {
public:
    void start() {
        std::cout << "started" << std::endl;
    }

    int getSpeed() const {
        return speed;
    }

private:
    int speed;
};

namespace utils {
    int helper(int x) {
        return x + 1;
    }
}

struct Point {
    double x;
    double y;
};
"#;
    let symbols = extract_symbols(source, Language::Cpp);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(names.contains(&"Engine"), "should find class Engine");
    assert!(names.contains(&"Point"), "should find struct Point");
    // Namespace may or may not be detected depending on grammar; check class details
    let engine = symbols.iter().find(|s| s.name == "Engine").unwrap();
    assert_eq!(engine.kind, SymbolKind::Class);
}

#[test]
fn extract_cpp_qualified_method() {
    let source = "void MyClass::process(int x) {\n    // body\n}\n";
    let symbols = extract_symbols(source, Language::Cpp);
    let names: Vec<&str> = symbols.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"process"),
        "should find qualified method process, got: {names:?}"
    );
}

// ── full_symbol_span tests ────────────────────────────────────

#[test]
fn full_span_no_attributes() {
    let source = "fn foo() {\n    42\n}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = &symbols[0];
    let (start, end) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(start, sym.start_line);
    assert_eq!(end, sym.end_line);
}

#[test]
fn full_span_single_attribute() {
    let source = "#[test]\nfn foo() {\n    42\n}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = &symbols[0];
    assert_eq!(sym.start_line, 2); // tree-sitter sees fn on line 2
    let (start, end) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(start, 1); // includes #[test]
    assert_eq!(end, sym.end_line);
}

#[test]
fn full_span_stacked_attributes() {
    let source = "#[test]\n#[cfg(unix)]\nfn foo() {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = &symbols[0];
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(start, 1); // includes both attributes
}

#[test]
fn full_span_doc_comment() {
    let source = "/// This is a doc comment.\n/// Second line.\nfn foo() {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = &symbols[0];
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(start, 1);
}

#[test]
fn full_span_mixed_attrs_and_docs() {
    let source = "/// A doc comment.\n#[test]\n#[cfg(unix)]\nfn foo() {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = &symbols[0];
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(start, 1);
}

#[test]
fn full_span_python_decorator() {
    let source = "@staticmethod\ndef foo():\n    pass\n";
    let symbols = extract_symbols(source, Language::Python);
    let sym = &symbols[0];
    let (start, _) = full_symbol_span(source, sym, Language::Python);
    assert_eq!(start, 1);
}

// Regression: multi-line Python decorators with continuation lines
// were truncated because only lines starting with '@' matched (#1103).
#[test]
fn full_span_python_multiline_decorator() {
    let source = "\
@decorator(
    arg1,
    arg2
)
def foo():
    pass
";
    let symbols = extract_symbols(source, Language::Python);
    let sym = symbols.iter().find(|s| s.name == "foo").unwrap();
    let (start, _) = full_symbol_span(source, sym, Language::Python);
    assert_eq!(
        start, 1,
        "multiline @decorator(...) should be included in foo's span"
    );
}

#[test]
fn full_span_python_stacked_multiline_decorator() {
    let source = "\
@first_decorator
@second_decorator(
    option=True
)
def bar():
    pass
";
    let symbols = extract_symbols(source, Language::Python);
    let sym = symbols.iter().find(|s| s.name == "bar").unwrap();
    let (start, _) = full_symbol_span(source, sym, Language::Python);
    assert_eq!(
        start, 1,
        "both decorators (including multiline) should be included"
    );
}

// Regression: //! inner doc comments belong to the module, not the
// following symbol. full_symbol_span must not absorb them.
#[test]
fn full_span_excludes_inner_doc_comments() {
    let source = "//! Module-level doc.\nstruct Config {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = symbols.iter().find(|s| s.name == "Config").unwrap();
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(
        start, 2,
        "inner doc comment //! should not be included in Config's span"
    );
}

#[test]
fn full_span_stops_at_unrelated_code() {
    let source = "fn bar() {}\n\n#[test]\nfn foo() {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let foo = symbols.iter().find(|s| s.name == "foo").unwrap();
    let (start, _) = full_symbol_span(source, foo, Language::Rust);
    assert_eq!(start, 3); // #[test] on line 3, not line 1
}

// Regression: multiline Rust attributes like #[cfg_attr(\n  ...\n)]
// were not recognized by the backward walk because is_annotation_line
// only matches lines starting with #[.  The fix uses bracket depth
// tracking to find the opening #[ from interior/closing lines.
#[test]
fn full_span_multiline_rust_attribute() {
    let source = "\
#[cfg_attr(
    feature = \"serde\",
    derive(Serialize, Deserialize)
)]
struct Config {
    name: String,
}
";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = symbols.iter().find(|s| s.name == "Config").unwrap();
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(
        start, 1,
        "multiline #[cfg_attr(...)] should be included in Config's span"
    );
}

#[test]
fn full_span_multiline_attribute_with_stacked_single() {
    let source = "\
#[derive(Debug)]
#[cfg_attr(
    feature = \"serde\",
    derive(Serialize)
)]
pub struct Foo {}
";
    let symbols = extract_symbols(source, Language::Rust);
    let sym = symbols.iter().find(|s| s.name == "Foo").unwrap();
    let (start, _) = full_symbol_span(source, sym, Language::Rust);
    assert_eq!(
        start, 1,
        "both #[derive(Debug)] and the multiline #[cfg_attr] should be included"
    );
}

#[test]
fn extract_symbol_text_basic() {
    let source = "#[test]\nfn foo() {\n    42\n}\n\nfn bar() {}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let foo = symbols.iter().find(|s| s.name == "foo").unwrap();
    let text = extract_symbol_text(source, foo, Language::Rust);
    assert!(text.contains("#[test]"));
    assert!(text.contains("fn foo()"));
    assert!(!text.contains("fn bar"));
}

// Regression: extract_symbol_text used a global line-ending heuristic
// that produced wrong byte offsets on files with mixed \r\n and \n endings.
#[test]
fn extract_symbol_text_mixed_line_endings() {
    // First line uses \r\n, rest use \n.
    let source = "fn first() {}\r\nfn second() {\n    42\n}\n";
    let symbols = extract_symbols(source, Language::Rust);
    let second = symbols.iter().find(|s| s.name == "second").unwrap();
    let text = extract_symbol_text(source, second, Language::Rust);
    assert!(
        text.contains("fn second()"),
        "should contain fn second(): {text:?}"
    );
    assert!(
        !text.contains("fn first()"),
        "should not contain fn first(): {text:?}"
    );
}

#[test]
fn extract_symbol_text_crlf() {
    // CRLF line endings: str::lines() strips \r\n but each line's
    // byte offset must account for 2-byte endings, not 1.
    let source = "fn first() {}\r\nfn second() {\r\n    42\r\n}\r\n";
    let symbols = extract_symbols(source, Language::Rust);
    let second = symbols.iter().find(|s| s.name == "second").unwrap();
    let text = extract_symbol_text(source, second, Language::Rust);
    assert!(
        text.contains("fn second()"),
        "extracted text should contain 'fn second()', got: {:?}",
        text
    );
    assert!(
        !text.contains("fn first()"),
        "extracted text should not contain 'fn first()', got: {:?}",
        text
    );
}

#[test]
fn go_receiver_methods_grouped_under_struct() {
    let source = "\
package main

type Server struct {
\tHost string
}

func NewServer() *Server { return nil }

func (s *Server) Start() error { return nil }

func (s *Server) Stop() {}
";
    let syms = extract_symbols(source, Language::Go);
    let server = syms.iter().find(|s| s.name == "Server").unwrap();
    assert_eq!(server.kind, SymbolKind::Struct);
    assert_eq!(
        server.children.len(),
        2,
        "Server should have 2 method children, got: {:?}",
        server.children.iter().map(|c| &c.name).collect::<Vec<_>>()
    );
    assert!(server.children.iter().any(|c| c.name == "Start"));
    assert!(server.children.iter().any(|c| c.name == "Stop"));
    // NewServer is a free function, not a method
    assert!(
        syms.iter()
            .any(|s| s.name == "NewServer" && s.kind == SymbolKind::Function)
    );
}

#[test]
fn go_qualified_name_lookup_works() {
    let source = "\
package main

type Dog struct{}
func (d *Dog) Speak() string { return \"woof\" }

type Cat struct{}
func (c *Cat) Speak() string { return \"meow\" }
";
    let syms = extract_symbols(source, Language::Go);
    // Qualified lookup should disambiguate
    let dog_speak = find_symbol(&syms, "Dog::Speak").expect("Dog::Speak should be found");
    assert!(dog_speak.signature.contains("Dog"));

    let cat_speak = find_symbol(&syms, "Cat::Speak").expect("Cat::Speak should be found");
    assert!(cat_speak.signature.contains("Cat"));
}

#[test]
fn go_value_receiver_grouped() {
    let source = "\
package main

type Counter struct{ n int }

func (c Counter) Count() int { return c.n }
";
    let syms = extract_symbols(source, Language::Go);
    let counter = syms.iter().find(|s| s.name == "Counter").unwrap();
    assert_eq!(counter.children.len(), 1);
    assert_eq!(counter.children[0].name, "Count");
}

#[test]
fn go_method_without_matching_struct_stays_top_level() {
    // Receiver type not defined in this file
    let source = "\
package main

func (e *External) DoWork() {}
";
    let syms = extract_symbols(source, Language::Go);
    assert!(
        syms.iter()
            .any(|s| s.name == "DoWork" && s.kind == SymbolKind::Method),
        "orphan method should stay top-level"
    );
}