code2graph 0.0.0-beta.4

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
// SPDX-License-Identifier: Apache-2.0

//! Lua extractor — one tree-sitter pass yielding definitions and references.
//!
//! Definitions: global functions, local functions, table-dot methods
//! (`function M.foo()`), table-colon methods (`function M:bar()`), local
//! variable declarations (plain locals, function-valued locals, and table
//! constructors treated as modules). Identity is file-path-derived (Lua has no
//! namespace declaration).
//!
//! References: free calls, dot/colon member calls, and `require()` calls
//! (emitted as an `Import` reference rather than a `Call`).
//!
//! Emits neutral [`FileFacts`] — no storage entries, no source bodies.
//!
//! The core extraction logic is shared with the Luau extractor via
//! `extract_lua_family`, which is parameterized by [`Language`] and grammar.

use tree_sitter::{Node, Parser};

use crate::error::{CodegraphError, Result};
use crate::graph::types::{
    Binding, BindingKind, ByteSpan, FileFacts, RefRole, Reference, Scope, ScopeId, ScopeKind,
    Symbol, SymbolKind, Visibility,
};
use crate::lang::Language;
use crate::symbol::Descriptor;

use super::{
    ExtractCtx, Extractor, MIN_REF_LEN, attach_reference_scopes, collect_call_references,
    definition_bindings, field_text, import_bindings, innermost_scope, make_symbol, node_span,
    node_text, one_line_signature, push_binding, push_import_ref, push_ref, push_scope,
};

/// Tree-sitter query capturing call-callee identifiers.
///
/// Pattern 1: free call `foo()` — identifier directly as `name`.
/// Pattern 2: dot call `a.bar()` — dot_index_expression; table as `@qualifier`,
///            field as `@callee`.
/// Pattern 3: colon call `a:qux()` — method_index_expression; table as
///            `@qualifier`, method as `@callee`.
const CALL_QUERY: &str = r#"
[
  (function_call name: (identifier) @callee)
  (function_call name: (dot_index_expression table: (identifier) @qualifier field: (identifier) @callee))
  (function_call name: (method_index_expression table: (identifier) @qualifier method: (identifier) @callee))
]
"#;

/// Extracts Lua symbols and references.
pub struct LuaExtractor;

impl Extractor for LuaExtractor {
    fn lang(&self) -> Language {
        Language::Lua
    }

    fn extract(&self, source: &str, file: &str) -> Result<FileFacts> {
        extract_lua_family(source, file, Language::Lua, crate::grammar::lua())
    }
}

/// Shared extraction pass for the Lua language family (Lua and Luau).
///
/// Parameterized by `lang` (determines SCIP scheme tag and `FileFacts.lang`)
/// and `grammar` (the tree-sitter grammar to use). `LuaExtractor` and
/// `LuauExtractor` are thin wrappers that call this function.
pub(crate) fn extract_lua_family(
    source: &str,
    file: &str,
    lang: Language,
    grammar: tree_sitter::Language,
) -> Result<FileFacts> {
    let mut parser = Parser::new();
    parser
        .set_language(&grammar)
        .map_err(|_| CodegraphError::Parse {
            path: file.to_owned(),
        })?;
    let tree = parser
        .parse(source, None)
        .ok_or_else(|| CodegraphError::Parse {
            path: file.to_owned(),
        })?;

    let root = tree.root_node();
    let bytes = source.as_bytes();
    let namespaces = lua_namespaces(file);
    let ctx = ExtractCtx { bytes, file, lang };

    let defs = collect_symbols(&root, &ctx, &namespaces);
    let def_bindings = definition_bindings(&defs);
    let mut symbols = defs;
    let mod_sym = super::module_symbol(lang, &namespaces, file, source.len());
    let module_id = mod_sym.id.to_scip_string();
    symbols.push(mod_sym);

    // Collect all calls; we'll filter `require` out separately.
    let mut references = collect_call_references(&root, &grammar, CALL_QUERY, lang, bytes, file)?;
    // Remove `require` from plain call refs — we re-emit them as Import refs.
    references.retain(|r| r.name != "require");

    collect_require_imports(&root, bytes, file, &mut references, &module_id);
    collect_read_references(&root, bytes, file, &mut references);
    collect_write_references(&root, bytes, file, &mut references);

    let scopes = collect_scopes(&root, source.len());
    attach_reference_scopes(&mut references, &scopes);
    let mut bindings = collect_bindings(&root, bytes, &scopes);
    bindings.extend(def_bindings);
    bindings.extend(import_bindings(&references, &scopes));

    Ok(FileFacts {
        file: file.to_owned(),
        lang: lang.as_str().to_owned(),
        symbols,
        references,
        scopes,
        bindings,
        ffi_exports: Vec::new(),
    })
}

// ── Namespace derivation ─────────────────────────────────────────────────────

/// Derive namespace descriptors purely from the file path.
///
/// Lua/Luau have no namespace/package declaration — identity is file-based. We
/// strip `.lua`/`.luau`, strip leading `src/`, `lua/`, or `luau/` (common
/// source roots), then split on `/`.
///
/// `src/util.lua`        → `["util"]`
/// `lua/http/client.lua` → `["http", "client"]`
/// `src/m.luau`          → `["m"]`
fn lua_namespaces(file: &str) -> Vec<String> {
    let p = file
        .strip_suffix(".luau")
        .or_else(|| file.strip_suffix(".lua"))
        .unwrap_or(file);
    let p = p
        .strip_prefix("luau/")
        .or_else(|| p.strip_prefix("lua/"))
        .or_else(|| p.strip_prefix("src/"))
        .unwrap_or(p);
    p.split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect()
}

// ── Symbol collection ────────────────────────────────────────────────────────

fn collect_symbols(root: &Node, ctx: &ExtractCtx, namespaces: &[String]) -> Vec<Symbol> {
    let ns_descriptors: Vec<Descriptor> = namespaces
        .iter()
        .cloned()
        .map(Descriptor::Namespace)
        .collect();
    let mut out = Vec::new();
    collect_chunk(root, ctx, &ns_descriptors, &mut out);
    out
}

/// Walk the `chunk` node and collect top-level definitions.
///
/// Lua's top-level construct is a `chunk` whose children include:
/// - `function_declaration` nodes (global and table-dot/colon methods)
/// - `local_declaration` with a `function_declaration` value (local function)
/// - `variable_declaration` / assignment with a `function_definition` or
///   `table_constructor` value (local `x = function()` / `local M = {}`)
///
/// Luau additionally has `type_definition` nodes (`type X = …` / `export type
/// X = …`). These never appear in plain Lua source, so the arm is a no-op for
/// Lua and active for Luau.
fn collect_chunk(node: &Node, ctx: &ExtractCtx, prefix: &[Descriptor], out: &mut Vec<Symbol>) {
    // Iterate ALL children (field-labeled `local_declaration` children are
    // returned here too, with their node kind — e.g. a local function still has
    // kind `function_declaration`).
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        match child.kind() {
            "function_declaration" => {
                collect_function_declaration(&child, ctx, prefix, out);
            }
            "variable_declaration" => {
                collect_variable_declaration(&child, ctx, prefix, out);
            }
            "assignment_statement" => {
                collect_assignment(&child, ctx, prefix, out);
            }
            // Luau: `type Point = { x: number, y: number }` or `export type Point = …`
            // The `name` field is present regardless of the `export` prefix.
            "type_definition" => {
                collect_type_definition(&child, ctx, prefix, out);
            }
            _ => {}
        }
    }
}

/// Emit a symbol for a `function_declaration`.
///
/// Covers:
/// - `function foo() end` → Function `foo` under the file prefix.
/// - `function M.baz() end` → Method `baz` under Type `M`.
/// - `function M:qux() end` → Method `qux` under Type `M`.
fn collect_function_declaration(
    node: &Node,
    ctx: &ExtractCtx,
    prefix: &[Descriptor],
    out: &mut Vec<Symbol>,
) {
    let name_node = match node.child_by_field_name("name") {
        Some(n) => n,
        None => return,
    };

    match name_node.kind() {
        "identifier" => {
            // Global function: `function foo() end`
            let name = node_text(&name_node, ctx.bytes).to_owned();
            let mut descriptors = prefix.to_vec();
            descriptors.push(Descriptor::Method {
                name: name.clone(),
                disambiguator: String::new(),
            });
            let sig = one_line_signature(node_text(node, ctx.bytes), &['{', '(']);
            out.push(make_symbol(
                ctx,
                node,
                name,
                SymbolKind::Function,
                Visibility::Unknown,
                descriptors,
                sig,
            ));
        }
        "dot_index_expression" | "method_index_expression" => {
            // `function M.baz()` or `function M:qux()`
            let table_field = if name_node.kind() == "dot_index_expression" {
                ("table", "field")
            } else {
                ("table", "method")
            };
            let table = match field_text(&name_node, table_field.0, ctx.bytes) {
                Some(t) => t,
                None => return,
            };
            let method = match field_text(&name_node, table_field.1, ctx.bytes) {
                Some(m) => m,
                None => return,
            };
            let mut descriptors = prefix.to_vec();
            descriptors.push(Descriptor::Type(table));
            descriptors.push(Descriptor::Method {
                name: method.clone(),
                disambiguator: String::new(),
            });
            let sig = one_line_signature(node_text(node, ctx.bytes), &['{', '(']);
            out.push(make_symbol(
                ctx,
                node,
                method,
                SymbolKind::Method,
                Visibility::Unknown,
                descriptors,
                sig,
            ));
        }
        _ => {}
    }
}

/// Handle `variable_declaration` — covers `local x = 1`, `local f = function()`,
/// `local M = {}`.
fn collect_variable_declaration(
    node: &Node,
    ctx: &ExtractCtx,
    prefix: &[Descriptor],
    out: &mut Vec<Symbol>,
) {
    // `variable_declaration` wraps an `assignment_statement` that carries the
    // `variable_list`/`expression_list`; delegate to the shared handler.
    let mut cursor = node.walk();
    for child in node.children(&mut cursor) {
        if child.kind() == "assignment_statement" {
            collect_assignment(&child, ctx, prefix, out);
        }
    }
}

/// Handle bare `assignment_statement` (e.g. `local M = {}`; or top-level `x = 1`).
fn collect_assignment(node: &Node, ctx: &ExtractCtx, prefix: &[Descriptor], out: &mut Vec<Symbol>) {
    let names: Vec<Node> = node
        .children(&mut node.walk())
        .find(|c| c.kind() == "variable_list")
        .map(|vl| {
            vl.children(&mut vl.walk())
                .filter(|c| c.kind() == "identifier")
                .collect()
        })
        .unwrap_or_default();

    let values: Vec<Node> = node
        .children(&mut node.walk())
        .find(|c| c.kind() == "expression_list")
        .map(|el| {
            el.children(&mut el.walk())
                .filter(|c| !matches!(c.kind(), "," | " "))
                .collect()
        })
        .unwrap_or_default();

    for (i, name_node) in names.iter().enumerate() {
        let name = node_text(name_node, ctx.bytes).to_owned();
        let value_opt = values.get(i);
        emit_local_symbol(name, value_opt, node, ctx, prefix, out);
    }
}

/// Emit a symbol for a named local or assignment, choosing kind from the value.
fn emit_local_symbol(
    name: String,
    value_opt: Option<&Node>,
    decl_node: &Node,
    ctx: &ExtractCtx,
    prefix: &[Descriptor],
    out: &mut Vec<Symbol>,
) {
    let (kind, descriptor) = match value_opt.map(|v| v.kind()) {
        Some("function_definition") => (
            SymbolKind::Function,
            Descriptor::Method {
                name: name.clone(),
                disambiguator: String::new(),
            },
        ),
        Some("table_constructor") => (SymbolKind::Module, Descriptor::Type(name.clone())),
        _ => (SymbolKind::Static, Descriptor::Term(name.clone())),
    };

    let mut descriptors = prefix.to_vec();
    descriptors.push(descriptor);
    let sig = one_line_signature(node_text(decl_node, ctx.bytes), &['{', '=']);
    out.push(make_symbol(
        ctx,
        decl_node,
        name,
        kind,
        Visibility::Unknown,
        descriptors.clone(),
        sig,
    ));

    // If it's a table constructor, descend into its fields.
    if let Some(val) = value_opt {
        if val.kind() == "table_constructor" {
            collect_table_fields(val, &descriptors, ctx, out);
        }
    }
}

/// Walk a `table_constructor` emitting methods and static fields.
fn collect_table_fields(
    node: &Node,
    type_prefix: &[Descriptor],
    ctx: &ExtractCtx,
    out: &mut Vec<Symbol>,
) {
    for child in node.children(&mut node.walk()) {
        if child.kind() != "field" {
            continue;
        }
        // field: name: (identifier) value: <expr>
        let Some(fname) = field_text(&child, "name", ctx.bytes) else {
            continue;
        };
        let value_kind = child.child_by_field_name("value").map_or("", |v| v.kind());

        let (kind, descriptor) = if value_kind == "function_definition" {
            (
                SymbolKind::Method,
                Descriptor::Method {
                    name: fname.clone(),
                    disambiguator: String::new(),
                },
            )
        } else {
            (SymbolKind::Static, Descriptor::Term(fname.clone()))
        };

        let mut descriptors = type_prefix.to_vec();
        descriptors.push(descriptor);
        let sig = one_line_signature(node_text(&child, ctx.bytes), &['{', '=']);
        out.push(make_symbol(
            ctx,
            &child,
            fname,
            kind,
            Visibility::Unknown,
            descriptors,
            sig,
        ));
    }
}

/// Emit a [`SymbolKind::TypeAlias`] for a Luau `type_definition` node.
///
/// Handles both `type X = …` and `export type X = …` — the `name` field is
/// present in both forms so no special-casing is needed for the `export`
/// keyword.  This node never appears in plain Lua source, so calling this
/// function for Lua is a no-op.
fn collect_type_definition(
    node: &Node,
    ctx: &ExtractCtx,
    prefix: &[Descriptor],
    out: &mut Vec<Symbol>,
) {
    let Some(name_node) = node.child_by_field_name("name") else {
        return;
    };
    let name = node_text(&name_node, ctx.bytes).to_owned();
    let mut descriptors = prefix.to_vec();
    descriptors.push(Descriptor::Type(name.clone()));
    let sig = one_line_signature(node_text(node, ctx.bytes), &['=']);
    out.push(make_symbol(
        ctx,
        node,
        name,
        SymbolKind::TypeAlias,
        Visibility::Unknown,
        descriptors,
        sig,
    ));
}

// ── Require imports ──────────────────────────────────────────────────────────

/// Walk the tree and emit [`RefRole::Import`] references for every `require(…)` call.
///
/// `require('pkg.sub')` produces an import reference whose `name` is the leaf
/// segment (`sub`) and whose `from_path` is the full dotted path (`pkg.sub`).
///
/// Luau / Roblox: `require(script.Parent.Mod)` passes a `dot_index_expression`
/// chain instead of a string. We handle it by extracting the full dotted text
/// of that expression; the leaf (last `.`-segment) becomes the `name`. This is
/// additive and a no-op for plain Lua (Lua require is always a string literal).
fn collect_require_imports(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
) {
    if node.kind() == "function_call" {
        if let Some(name_node) = node.child_by_field_name("name") {
            if name_node.kind() == "identifier" && node_text(&name_node, bytes) == "require" {
                if let Some(args) = node.child_by_field_name("arguments") {
                    // Case 1: string literal require('pkg.sub')
                    if let Some(from_path) = extract_string_arg(&args, bytes) {
                        let leaf = from_path.rsplit('.').next().unwrap_or(&from_path);
                        if leaf.len() >= MIN_REF_LEN {
                            push_import_ref(out, leaf, &name_node, file, module_id, &from_path);
                        }
                    }
                    // Case 2: dot-expression require(script.Parent.Mod) — Roblox/Luau style.
                    else if let Some(from_path) = extract_dot_expr_arg(&args, bytes) {
                        let leaf = from_path.rsplit('.').next().unwrap_or(&from_path);
                        if leaf.len() >= MIN_REF_LEN {
                            push_import_ref(out, leaf, &name_node, file, module_id, &from_path);
                        }
                    }
                }
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_require_imports(&child, bytes, file, out, module_id);
    }
}

/// Extract the first `dot_index_expression` argument text from an `arguments`
/// node, e.g. `script.Parent.Mod` from `require(script.Parent.Mod)`.
///
/// Returns the raw text of the expression node, which will contain `.`-separated
/// identifiers.
fn extract_dot_expr_arg(args: &Node, bytes: &[u8]) -> Option<String> {
    for child in args.children(&mut args.walk()) {
        if child.kind() == "dot_index_expression" {
            return Some(node_text(&child, bytes).to_owned());
        }
    }
    None
}

/// Extract the first string content from an `arguments` node.
fn extract_string_arg(args: &Node, bytes: &[u8]) -> Option<String> {
    for child in args.children(&mut args.walk()) {
        if child.kind() == "string" {
            // Find string_content child.
            for inner in child.children(&mut child.walk()) {
                if inner.kind() == "string_content" {
                    return Some(node_text(&inner, bytes).to_owned());
                }
            }
            // Fallback: strip surrounding quotes from the string node text.
            let raw = node_text(&child, bytes);
            let stripped = raw
                .strip_prefix('\'')
                .and_then(|s| s.strip_suffix('\''))
                .or_else(|| raw.strip_prefix('"').and_then(|s| s.strip_suffix('"')))
                .unwrap_or(raw);
            if !stripped.is_empty() {
                return Some(stripped.to_owned());
            }
        }
    }
    None
}

// ── Read / write references ──────────────────────────────────────────────────

/// Returns `true` when `node` (an `identifier`) sits in a position already
/// captured by another collector — a call callee, a definition/parameter name,
/// an assignment/local-declaration target, a member-access leaf, or a
/// table-constructor field key — and so must NOT also be emitted as a Read.
///
/// The base table of a member access (`a` in `a.b` / `a:b()`) is a genuine read
/// of `a` and is intentionally *not* skipped — only the leaf field/method name is.
fn is_non_read_position(node: &Node) -> bool {
    let parent = match node.parent() {
        Some(p) => p,
        None => return true,
    };
    match parent.kind() {
        // Free-call callee: `foo()` — the `name` field of a `function_call`.
        "function_call" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Member access `a.b` / `a:b` — skip the leaf field/method name only.
        "dot_index_expression" => parent.child_by_field_name("field").as_ref() == Some(node),
        "method_index_expression" => parent.child_by_field_name("method").as_ref() == Some(node),
        // Assignment / local-declaration targets live in the `variable_list`
        // (writes are emitted separately; locals are bindings).
        "variable_list" => true,
        // Function / closure parameter binding sites.
        "parameters" => true,
        // Definition name: `function foo()` (dotted/colon names nest under an
        // index expression and are handled by the arms above).
        "function_declaration" => parent.child_by_field_name("name").as_ref() == Some(node),
        // Table-constructor field key `{ key = value }` — a field definition; the
        // value identifier is still reached and kept as a read.
        "field" => parent.child_by_field_name("name").as_ref() == Some(node),
        _ => false,
    }
}

/// Recursively walk `node` and emit [`RefRole::Read`] references for bare
/// `identifier` nodes used in value positions. Applies [`MIN_REF_LEN`].
///
/// Skips positions handled by other collectors (call callees, definition and
/// parameter names, assignment / local-declaration targets, member-access leaf
/// names, table-field keys) via [`is_non_read_position`].
fn collect_read_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "identifier" {
        let name = node_text(node, bytes);
        if name.len() >= MIN_REF_LEN && !is_non_read_position(node) {
            push_ref(out, name, node, file, RefRole::Read);
        }
        // identifiers have no meaningful children; return early.
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_read_references(&child, bytes, file, out);
    }
}

/// Recursively walk `node` and emit [`RefRole::Write`] references for the
/// bare-identifier targets of an `assignment_statement` (e.g. `x = 5`,
/// `count = count + 1`).
///
/// A `local x = …` declaration is *not* a write — its `assignment_statement`
/// nests under a `variable_declaration`/`local_declaration` wrapper and is
/// excluded. Member / index targets (`obj.field = …`, `t[i] = …`) are not
/// covered in v1 — only bare `identifier` targets. Applies [`MIN_REF_LEN`].
fn collect_write_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "assignment_statement"
        && !matches!(
            node.parent().map(|p| p.kind()),
            Some("variable_declaration") | Some("local_declaration")
        )
    {
        if let Some(vl) = node
            .children(&mut node.walk())
            .find(|c| c.kind() == "variable_list")
        {
            for target in vl.children(&mut vl.walk()) {
                if target.kind() == "identifier" {
                    let name = node_text(&target, bytes);
                    if name.len() >= MIN_REF_LEN {
                        push_ref(out, name, &target, file, RefRole::Write);
                    }
                }
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_write_references(&child, bytes, file, out);
    }
}

// ── Scope tree ───────────────────────────────────────────────────────────────

fn collect_scopes(root: &Node, source_len: usize) -> Vec<Scope> {
    let mut scopes = Vec::new();
    push_scope(
        &mut scopes,
        None,
        ByteSpan {
            start: 0,
            end: source_len,
        },
        ScopeKind::Module,
    );
    for child in root.children(&mut root.walk()) {
        scope_dfs(&child, 0, &mut scopes);
    }
    scopes
}

fn scope_dfs(node: &Node, parent_id: ScopeId, scopes: &mut Vec<Scope>) {
    match node.kind() {
        "function_declaration" | "function_definition" => {
            let fn_id = push_scope(
                scopes,
                Some(parent_id),
                node_span(node),
                ScopeKind::Function,
            );
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, fn_id, scopes);
                }
            }
        }
        "block" => {
            let block_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Block);
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, block_id, scopes);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, parent_id, scopes);
            }
        }
    }
}

// ── Bindings ─────────────────────────────────────────────────────────────────

fn collect_bindings(root: &Node, bytes: &[u8], scopes: &[Scope]) -> Vec<Binding> {
    let mut out = Vec::new();
    collect_bindings_dfs(root, bytes, scopes, &mut out);
    out
}

fn collect_bindings_dfs(node: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    match node.kind() {
        "function_declaration" | "function_definition" => {
            // Collect parameters.
            if let Some(params) = node.child_by_field_name("parameters") {
                for child in params.named_children(&mut params.walk()) {
                    if child.kind() == "identifier" {
                        let name = node_text(&child, bytes).to_owned();
                        let intro = child.start_byte();
                        if name.len() >= MIN_REF_LEN && innermost_scope(intro, scopes) != Some(0) {
                            push_binding(out, name, intro, BindingKind::Param, scopes);
                        }
                    }
                }
            }
        }
        "local_declaration" => {
            // local x = …
            let mut cur1 = node.walk();
            for inner in node.children(&mut cur1) {
                if inner.kind() == "variable_declaration" {
                    let mut cur2 = inner.walk();
                    let vl_opt = inner
                        .children(&mut cur2)
                        .find(|c| c.kind() == "variable_list");
                    if let Some(vl) = vl_opt {
                        let mut cur3 = vl.walk();
                        for id in vl.children(&mut cur3) {
                            if id.kind() == "identifier" {
                                let name = node_text(&id, bytes).to_owned();
                                let intro = id.start_byte();
                                if name.len() >= MIN_REF_LEN
                                    && innermost_scope(intro, scopes) != Some(0)
                                {
                                    push_binding(out, name, intro, BindingKind::Local, scopes);
                                }
                            }
                        }
                    }
                }
            }
        }
        _ => {}
    }
    for child in node.children(&mut node.walk()) {
        collect_bindings_dfs(&child, bytes, scopes, out);
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::types::RefRole;

    fn extract(src: &str, file: &str) -> FileFacts {
        LuaExtractor.extract(src, file).unwrap()
    }

    fn by_name(facts: &FileFacts, name: &str) -> Option<Symbol> {
        facts.symbols.iter().find(|s| s.name == name).cloned()
    }

    // ── Definitions ──────────────────────────────────────────────────────────

    #[test]
    fn global_function_is_extracted() {
        // File `src/util.lua` → namespace = ["util"]
        // foo → descriptors: [Namespace("util"), Method { name: "foo" }]
        // SCIP: "codegraph . . . util/foo()."
        let src = "function foo() end";
        let facts = extract(src, "src/util.lua");

        let foo = by_name(&facts, "foo").unwrap();
        assert_eq!(foo.kind, SymbolKind::Function);
        // Verify SCIP string contains the function descriptor rendering.
        let scip = foo.id.to_scip_string();
        assert!(
            scip.contains("util") && scip.contains("foo"),
            "unexpected SCIP string: {scip}"
        );
        assert_eq!(facts.lang, "lua");
    }

    #[test]
    fn table_dot_method_is_extracted_as_method_under_type() {
        let src = "function M.baz(x) end";
        let facts = extract(src, "src/util.lua");

        let baz = by_name(&facts, "baz").unwrap();
        assert_eq!(baz.kind, SymbolKind::Method);
        // SCIP should encode M as a Type descriptor and baz as Method.
        let scip = baz.id.to_scip_string();
        assert!(
            scip.contains("M#") && scip.contains("baz"),
            "unexpected SCIP string: {scip}"
        );
    }

    #[test]
    fn table_colon_method_is_extracted_as_method_under_type() {
        let src = "function M:qux() end";
        let facts = extract(src, "src/util.lua");

        let qux = by_name(&facts, "qux").unwrap();
        assert_eq!(qux.kind, SymbolKind::Method);
        let scip = qux.id.to_scip_string();
        assert!(
            scip.contains("M#") && scip.contains("qux"),
            "unexpected SCIP string: {scip}"
        );
    }

    #[test]
    fn local_function_is_extracted_as_function() {
        let src = "local function bar() end";
        let facts = extract(src, "src/util.lua");

        let bar = by_name(&facts, "bar").unwrap();
        assert_eq!(bar.kind, SymbolKind::Function);
    }

    #[test]
    fn local_table_is_extracted_as_module() {
        let src = "local M = {}";
        let facts = extract(src, "src/util.lua");

        let m = by_name(&facts, "M").unwrap();
        assert_eq!(m.kind, SymbolKind::Module);
    }

    // ── References ───────────────────────────────────────────────────────────

    #[test]
    fn free_call_is_captured_as_call_ref() {
        let src = "function run() foo() end";
        let facts = extract(src, "src/util.lua");

        let call_ref = facts.references.iter().find(|r| r.name == "foo").unwrap();
        assert_eq!(call_ref.role, RefRole::Call);
    }

    #[test]
    fn member_call_captures_qualifier() {
        let src = "function run() a.bar() end";
        let facts = extract(src, "src/util.lua");

        let bar_ref = facts
            .references
            .iter()
            .find(|r| r.name == "bar")
            .expect("expected Call ref for 'bar'");
        assert_eq!(bar_ref.role, RefRole::Call);
        assert_eq!(
            bar_ref.qualifier.as_deref(),
            Some("a"),
            "expected qualifier 'a' on the bar call ref"
        );
    }

    #[test]
    fn require_produces_import_reference() {
        let src = "local sub = require('pkg.sub')";
        let facts = extract(src, "src/util.lua");

        let import_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import)
            .expect("expected an Import ref from require");
        // Leaf name is `sub` (last `.`-segment)
        assert_eq!(import_ref.name, "sub");
        assert!(
            import_ref
                .from_path
                .as_deref()
                .is_some_and(|p| p.contains("pkg.sub")),
            "from_path should contain 'pkg.sub', got {:?}",
            import_ref.from_path
        );
    }

    #[test]
    fn require_is_not_emitted_as_plain_call() {
        let src = "local sub = require('pkg.sub')";
        let facts = extract(src, "src/util.lua");

        let require_calls: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call && r.name == "require")
            .collect();
        assert!(
            require_calls.is_empty(),
            "require should not appear as a Call ref"
        );
    }

    // ── Read / write references ──────────────────────────────────────────────

    fn has_ref(facts: &FileFacts, role: RefRole, name: &str) -> bool {
        facts
            .references
            .iter()
            .any(|r| r.role == role && r.name == name)
    }

    #[test]
    fn reassignment_emits_write_and_reads() {
        // `count = count + bonus` is a re-assignment (not a `local`): the LHS is a
        // Write; both RHS identifiers are Reads.
        let src = "function run() local count = 0 count = count + bonus end";
        let facts = extract(src, "src/util.lua");

        assert!(
            has_ref(&facts, RefRole::Write, "count"),
            "expected a Write ref for the assignment target 'count'"
        );
        assert!(
            has_ref(&facts, RefRole::Read, "bonus"),
            "expected a Read ref for 'bonus' on the RHS"
        );
        assert!(
            has_ref(&facts, RefRole::Read, "count"),
            "expected a Read ref for the RHS use of 'count'"
        );
    }

    #[test]
    fn local_declaration_is_not_a_write() {
        // `local total = compute()` introduces a binding — not a Write.
        let src = "function run() local total = compute() end";
        let facts = extract(src, "src/util.lua");

        assert!(
            !has_ref(&facts, RefRole::Write, "total"),
            "a `local` declaration must not emit a Write ref"
        );
        // The declared name is a binding, not a Read either.
        assert!(
            !has_ref(&facts, RefRole::Read, "total"),
            "the declared name must not be emitted as a Read"
        );
    }

    #[test]
    fn read_of_global_in_call_arg() {
        // `config` is read as an argument; `print` is the call callee, not a Read.
        let src = "function run() print(config) end";
        let facts = extract(src, "src/util.lua");

        assert!(
            has_ref(&facts, RefRole::Read, "config"),
            "expected a Read ref for the argument 'config'"
        );
        assert!(
            !has_ref(&facts, RefRole::Read, "print"),
            "a call callee must not also be a Read ref"
        );
    }

    #[test]
    fn member_access_base_is_read_leaf_is_not() {
        // `value = source.field` — `source` (base) is a Read; `field` (leaf) is not.
        let src = "function run() value = source.field end";
        let facts = extract(src, "src/util.lua");

        assert!(
            has_ref(&facts, RefRole::Read, "source"),
            "the base of a member access should be a Read ref"
        );
        assert!(
            !has_ref(&facts, RefRole::Read, "field"),
            "the leaf of a member access must not be a Read ref"
        );
    }
}