brokk-bifrost-ruby 0.9.2

Ruby language knowledge for brokk-bifrost: declarations, require/autoload and Zeitwerk visibility, mixin and dispatch-mode facts, and usage-graph resolution
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
use crate::imports::parse_ruby_require_call;
use crate::mixins::{encode_mixin_relation, encode_superclass_relation, raw_mixin_specs_for_type};
use brokk_bifrost_core::analyzer::fq_name::{FqName, SegmentId, SegmentKind, segment_interner};
use brokk_bifrost_core::analyzer::model::{
    CodeUnitType, DispatchExtensibility, RubyMethodDispatchMode, SignatureMetadata,
};
use brokk_bifrost_core::analyzer::parsed_file::ParsedFile;
use brokk_bifrost_core::analyzer::structural::materialization::{
    GenerationKind, MaterializationRecord,
};
use brokk_bifrost_core::analyzer::tree_walk::{WalkControl, node_range, walk_named_tree_preorder};
use brokk_bifrost_core::analyzer::{CodeUnit, ProjectFile};
use brokk_bifrost_core::hash::HashSet;
use tree_sitter::{Node, Parser, Tree};

/// Intern one qualified-name segment in the process-global interner.
fn ruby_segment(text: &str, kind: SegmentKind) -> SegmentId {
    segment_interner().intern(text, kind)
}

/// Build the structured type/namespace chain for a sequence of Ruby class/
/// module name segments (already atomic AST-derived strings — see
/// [`extract_name_segments`], which walks `scope_resolution` nodes rather than
/// splitting `A::B` text). Ruby's `package_name` is always empty and its legacy
/// `short_name` joins EVERY namespace segment with a literal `$` (see this
/// module's doc comment on [`RubyVisitor`]): `module A; class B` yields `A$B`.
/// [`SegmentKind::Nested`] is the tag whose join renders a leading
/// `$` regardless of the previous segment's kind, and the very first segment of
/// a qualified name never gets a leading separator at all (there is no
/// preceding segment) — so tagging every namespace segment `Companion`
/// reproduces the `$`-joined chain exactly, including its first element.
fn ruby_type_chain_fq(segments: &[String]) -> FqName {
    let mut fq = FqName::new();
    for segment in segments {
        fq.push(ruby_segment(segment, SegmentKind::Nested));
    }
    fq
}

/// Extends a type/namespace chain with one trailing `Member` segment — the
/// structured counterpart of [`member_short_name`], which appends `.name`
/// after the `$`-joined chain.
fn ruby_member_fq(type_segments: &[String], name: &str) -> FqName {
    ruby_type_chain_fq(type_segments).with_pushed(ruby_segment(name, SegmentKind::Member))
}

/// Parses Ruby source into a tree-sitter tree, or `None` if parsing fails.
pub fn parse_ruby_tree(source: &str) -> Option<Tree> {
    let mut parser = Parser::new();
    parser
        .set_language(&tree_sitter_ruby::LANGUAGE.into())
        .expect("failed to load ruby parser");
    parser.parse(source, None)
}

/// Reads the source text backing a tree-sitter node.
pub fn ruby_node_text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
    brokk_bifrost_core::analyzer::common::node_source_text(node, source)
}

/// Walks a Ruby file and emits its declarations into `parsed`.
///
/// Ruby symbol identity follows the shared `CodeUnit` scheme used by every
/// bifrost analyzer: `package_name` is empty, nested namespaces/types are joined
/// in `short_name` with `$`, and a type's members are appended after a `.`. So
/// `module A; class B; def c` yields `A$B` (class) and `A$B.c` (method), which
/// `CodeUnit::identifier` resolves back to `B` and `c`.
pub struct RubyVisitor<'a> {
    pub file: &'a ProjectFile,
    pub source: &'a str,
    pub parsed: &'a mut ParsedFile,
}

/// A pending traversal step: visit `node` as a statement within the enclosing
/// type's `segments`/`parent` context. The visitor uses an explicit stack of
/// these instead of native recursion so deeply nested input cannot overflow the
/// call stack (per AGENTS.md, and mirroring the Python visitor).
struct RubyWork<'tree> {
    node: Node<'tree>,
    segments: Vec<String>,
    parent: Option<CodeUnit>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RubyFieldScope {
    Instance,
    ClassVariable,
    SingletonClass,
}

/// Pushes a node's named children as statement work items. Children are pushed
/// in reverse so the stack pops them in source order.
fn push_named_children<'tree>(
    node: Node<'tree>,
    segments: &[String],
    parent: Option<&CodeUnit>,
    stack: &mut Vec<RubyWork<'tree>>,
) {
    let mut cursor = node.walk();
    let children: Vec<_> = node.named_children(&mut cursor).collect();
    for child in children.into_iter().rev() {
        stack.push(RubyWork {
            node: child,
            segments: segments.to_vec(),
            parent: parent.cloned(),
        });
    }
}

impl RubyVisitor<'_> {
    pub fn visit_program(&mut self, root: Node<'_>) {
        let mut stack = Vec::new();
        push_named_children(root, &[], None, &mut stack);
        while let Some(work) = stack.pop() {
            self.visit_statement(work.node, &work.segments, work.parent.as_ref(), &mut stack);
        }
    }

    fn visit_statement<'tree>(
        &mut self,
        node: Node<'tree>,
        segments: &[String],
        parent: Option<&CodeUnit>,
        stack: &mut Vec<RubyWork<'tree>>,
    ) {
        match node.kind() {
            "class" => self.visit_class_like(node, segments, parent, false, stack),
            "module" => self.visit_class_like(node, segments, parent, true, stack),
            "singleton_class" => {
                // `class << self` — its methods belong to the enclosing type.
                if let Some(body) = node.child_by_field_name("body") {
                    push_named_children(body, segments, parent, stack);
                }
            }
            "method" | "singleton_method" => self.visit_method(node, segments, parent),
            "assignment" | "operator_assignment" => {
                self.visit_assignment(node, segments, parent, None)
            }
            "call" => self.visit_call(node, segments, parent),
            kind if is_descendable_container(kind) => {
                push_named_children(node, segments, parent, stack);
            }
            _ => {}
        }
    }

    fn visit_class_like<'tree>(
        &mut self,
        node: Node<'tree>,
        segments: &[String],
        parent: Option<&CodeUnit>,
        is_module: bool,
        stack: &mut Vec<RubyWork<'tree>>,
    ) {
        let Some(name_node) = node.child_by_field_name("name") else {
            return;
        };
        let name_segments = extract_name_segments(name_node, self.source);
        if name_segments.is_empty() {
            return;
        }

        let mut new_segments = segments.to_vec();
        new_segments.extend(name_segments);
        let short_name = new_segments.join("$");

        let kind = if is_module {
            CodeUnitType::Module
        } else {
            CodeUnitType::Class
        };
        let code_unit = CodeUnit::new_fq(
            self.file.clone(),
            kind,
            String::new(),
            short_name,
            ruby_type_chain_fq(&new_segments),
        );
        self.parsed
            .replace_code_unit(code_unit.clone(), node, self.source, parent.cloned(), None);
        self.parsed
            .add_signature(code_unit.clone(), first_line(node, self.source));

        let mut owner_relations = extract_ruby_supertypes(node, self.source)
            .into_iter()
            .map(|target| {
                let encoded = encode_superclass_relation(&target);
                (target, encoded)
            })
            .collect::<Vec<_>>();
        owner_relations.extend(raw_mixin_specs_for_type(node, self.source).into_iter().map(
            |spec| {
                let encoded = encode_mixin_relation(&spec);
                (spec.raw_target, encoded)
            },
        ));
        if !owner_relations.is_empty() {
            self.parsed.set_raw_supertypes(
                code_unit.clone(),
                owner_relations
                    .iter()
                    .map(|(target, _)| target.clone())
                    .collect(),
            );
            self.parsed.set_supertype_lookup_paths(
                code_unit.clone(),
                owner_relations
                    .into_iter()
                    .map(|(_, encoded)| encoded)
                    .collect(),
            );
        }

        self.visit_scope_field_assignments(
            node,
            &new_segments,
            Some(&code_unit),
            RubyFieldScope::SingletonClass,
        );
        if let Some(body) = node.child_by_field_name("body") {
            push_named_children(body, &new_segments, Some(&code_unit), stack);
        }
    }

    fn visit_method(&mut self, node: Node<'_>, segments: &[String], parent: Option<&CodeUnit>) {
        let Some(name_node) = node.child_by_field_name("name") else {
            return;
        };
        let name = ruby_node_text(name_node, self.source).trim();
        if name.is_empty() {
            return;
        }
        let short_name = member_short_name(segments, name);
        let signature = node
            .child_by_field_name("parameters")
            .map(|params| ruby_node_text(params, self.source).trim().to_string());
        let code_unit = CodeUnit::with_signature_and_fq(
            self.file.clone(),
            CodeUnitType::Function,
            String::new(),
            short_name,
            signature,
            false,
            ruby_member_fq(segments, name),
        );
        self.parsed
            .replace_code_unit(code_unit.clone(), node, self.source, parent.cloned(), None);
        self.parsed.set_ruby_method_dispatch_mode(
            code_unit.clone(),
            ruby_method_dispatch_mode(node, self.source),
        );
        self.parsed.add_signature_with_metadata(
            code_unit,
            ruby_signature_metadata(first_line(node, self.source), node, self.source),
        );
        // Method bodies are otherwise leaves for declaration purposes, but Ruby
        // instance/class variables are declarations even when first assigned in
        // methods.
        self.visit_scope_field_assignments(node, segments, parent, ruby_method_field_scope(node));
    }

    fn visit_assignment(
        &mut self,
        node: Node<'_>,
        segments: &[String],
        parent: Option<&CodeUnit>,
        field_scope: Option<RubyFieldScope>,
    ) {
        let Some(left) = node.child_by_field_name("left") else {
            return;
        };
        if let Some(field_scope) = ruby_field_scope_for_assignment_left(left, segments, field_scope)
        {
            self.visit_variable_field_assignment(node, left, segments, parent, field_scope);
            return;
        }
        // Only constant assignments are declarations; locals are lowercase.
        if !matches!(left.kind(), "constant" | "scope_resolution") {
            return;
        }
        let name_path = extract_name_path(left, self.source);
        if name_path.segments.is_empty() {
            return;
        }
        let short_name = assignment_constant_short_name(segments, &name_path);
        let code_unit = CodeUnit::new_fq(
            self.file.clone(),
            CodeUnitType::Field,
            String::new(),
            short_name,
            assignment_constant_fq(segments, &name_path),
        );
        self.parsed
            .replace_code_unit(code_unit.clone(), node, self.source, parent.cloned(), None);
        self.parsed.add_signature(
            code_unit,
            ruby_node_text(node, self.source).trim().to_string(),
        );
    }

    fn visit_scope_field_assignments(
        &mut self,
        node: Node<'_>,
        segments: &[String],
        parent: Option<&CodeUnit>,
        field_scope: RubyFieldScope,
    ) {
        let mut stack = vec![node];
        while let Some(current) = stack.pop() {
            if current != node
                && matches!(
                    current.kind(),
                    "class" | "module" | "method" | "singleton_method" | "singleton_class"
                )
            {
                continue;
            }
            if matches!(current.kind(), "assignment" | "operator_assignment") {
                self.visit_assignment(current, segments, parent, Some(field_scope));
                continue;
            }
            for index in (0..current.named_child_count()).rev() {
                if let Some(child) = current.named_child(index) {
                    stack.push(child);
                }
            }
        }
    }

    fn visit_variable_field_assignment(
        &mut self,
        node: Node<'_>,
        left: Node<'_>,
        segments: &[String],
        parent: Option<&CodeUnit>,
        field_scope: RubyFieldScope,
    ) {
        let Some(short_name) = ruby_field_short_name(segments, left, self.source, field_scope)
        else {
            return;
        };
        let fq = ruby_field_fq(segments, left, self.source, field_scope).unwrap_or_default();
        let code_unit = CodeUnit::new_fq(
            self.file.clone(),
            CodeUnitType::Field,
            String::new(),
            short_name,
            fq,
        );
        if self
            .parsed
            .first_range_start(&code_unit)
            .is_some_and(|start| start <= node.start_byte())
        {
            return;
        }
        self.parsed
            .replace_code_unit(code_unit.clone(), node, self.source, parent.cloned(), None);
        self.parsed.add_signature(
            code_unit,
            ruby_node_text(node, self.source).trim().to_string(),
        );
    }

    fn visit_call(&mut self, node: Node<'_>, segments: &[String], parent: Option<&CodeUnit>) {
        let Some(method) = node.child_by_field_name("method") else {
            return;
        };
        let method_name = ruby_node_text(method, self.source).trim();
        match method_name {
            "require" | "require_relative" | "load" | "autoload" => {
                if let Some(info) = parse_ruby_require_call(node, self.source) {
                    self.parsed.imports.push(info);
                }
            }
            "attr_accessor" | "attr_reader" | "attr_writer" => {
                self.visit_attr_macro(node, method_name, segments, parent);
            }
            "alias_method" => {
                self.visit_alias_method(node, segments, parent);
            }
            _ => {}
        }
    }

    fn visit_attr_macro(
        &mut self,
        node: Node<'_>,
        method_name: &str,
        segments: &[String],
        parent: Option<&CodeUnit>,
    ) {
        // `attr_accessor` and friends only declare members inside a type body.
        let Some(parent) = parent else {
            return;
        };
        let Some(arguments) = node.child_by_field_name("arguments") else {
            return;
        };
        let mut cursor = arguments.walk();
        let mut dynamic_argument_seen = false;
        for arg in arguments.named_children(&mut cursor) {
            let Some(name) = literal_symbol_or_string_name(arg, self.source) else {
                // A non-literal argument generates *something* the analyzer
                // cannot name. The site record is what keeps the generated
                // set explicitly unknown rather than silently empty.
                dynamic_argument_seen = true;
                continue;
            };
            let member_name = attr_field_member_name(node, &name);
            let field_name = format!("@{name}");
            let code_unit = CodeUnit::new_fq(
                self.file.clone(),
                CodeUnitType::Field,
                String::new(),
                member_short_name(segments, &member_name),
                ruby_scoped_field_fq(segments, &field_name, method_is_singleton_context(node)),
            );
            self.parsed.replace_code_unit(
                code_unit.clone(),
                node,
                self.source,
                Some(parent.clone()),
                None,
            );
            self.parsed
                .record_materialization(MaterializationRecord::GeneratedDeclaration {
                    site: node_range(node),
                    argument: node_range(arg),
                    kind: GenerationKind::AccessorMacro,
                    unit: code_unit.clone(),
                });
            self.parsed.add_signature(
                code_unit,
                ruby_node_text(node, self.source).trim().to_string(),
            );
            if matches!(method_name, "attr_accessor" | "attr_reader") {
                self.add_member_function(
                    node,
                    arg,
                    segments,
                    parent,
                    &name,
                    GenerationKind::AccessorMacro,
                );
            }
            if matches!(method_name, "attr_accessor" | "attr_writer") {
                self.add_member_function(
                    node,
                    arg,
                    segments,
                    parent,
                    &format!("{name}="),
                    GenerationKind::AccessorMacro,
                );
            }
        }
        if dynamic_argument_seen {
            self.parsed
                .record_materialization(MaterializationRecord::DynamicGenerationSite {
                    site: node_range(node),
                    kind: GenerationKind::AccessorMacro,
                });
        }
    }

    fn visit_alias_method(
        &mut self,
        node: Node<'_>,
        segments: &[String],
        parent: Option<&CodeUnit>,
    ) {
        let Some(parent) = parent else {
            return;
        };
        let Some(arguments) = node.child_by_field_name("arguments") else {
            return;
        };
        let mut cursor = arguments.walk();
        let Some(alias_arg) = arguments.named_children(&mut cursor).next() else {
            return;
        };
        let Some(alias_name) = literal_symbol_or_string_name(alias_arg, self.source) else {
            // A dynamic alias name generates a method the analyzer cannot
            // name; record the site so the generated set stays explicitly
            // unknown.
            self.parsed
                .record_materialization(MaterializationRecord::DynamicGenerationSite {
                    site: node_range(node),
                    kind: GenerationKind::AliasMacro,
                });
            return;
        };
        self.add_member_function(
            node,
            alias_arg,
            segments,
            parent,
            &alias_name,
            GenerationKind::AliasMacro,
        );
    }

    fn add_member_function(
        &mut self,
        signature_node: Node<'_>,
        range_node: Node<'_>,
        segments: &[String],
        parent: &CodeUnit,
        name: &str,
        generation: GenerationKind,
    ) {
        let code_unit = CodeUnit::new_fq(
            self.file.clone(),
            CodeUnitType::Function,
            String::new(),
            member_short_name(segments, name),
            ruby_member_fq(segments, name),
        );
        self.parsed.replace_code_unit(
            code_unit.clone(),
            range_node,
            self.source,
            Some(parent.clone()),
            None,
        );
        self.parsed
            .record_materialization(MaterializationRecord::GeneratedDeclaration {
                site: node_range(signature_node),
                argument: node_range(range_node),
                kind: generation,
                unit: code_unit.clone(),
            });
        self.parsed.set_ruby_method_dispatch_mode(
            code_unit.clone(),
            ruby_method_dispatch_mode(signature_node, self.source),
        );
        self.parsed.add_signature(
            code_unit,
            ruby_node_text(signature_node, self.source)
                .trim()
                .to_string(),
        );
    }
}

/// Builds a member's `short_name` from its enclosing type segments and own name.
fn member_short_name(segments: &[String], name: &str) -> String {
    if segments.is_empty() {
        name.to_string()
    } else {
        format!("{}.{}", segments.join("$"), name)
    }
}

fn attr_field_member_name(node: Node<'_>, name: &str) -> String {
    if method_is_singleton_context(node) {
        format!("$singleton.@{name}")
    } else {
        format!("@{name}")
    }
}

pub fn ruby_variable_field_name(node: Node<'_>, source: &str) -> Option<String> {
    if !matches!(node.kind(), "instance_variable" | "class_variable") {
        return None;
    }
    let name = ruby_node_text(node, source).trim();
    (!name.is_empty()).then(|| name.to_string())
}

/// The rendered member tail shared by [`ruby_field_short_name`] and
/// [`ruby_field_fq`]. Singleton-scoped fields retain the established
/// `$singleton.@field` spelling, while [`ruby_field_fq`] records `$singleton`
/// and the field itself as distinct scope/member segments.
fn ruby_field_member_name(node: Node<'_>, source: &str, scope: RubyFieldScope) -> Option<String> {
    let name = ruby_variable_field_name(node, source)?;
    Some(match scope {
        RubyFieldScope::Instance | RubyFieldScope::ClassVariable => name,
        RubyFieldScope::SingletonClass => format!("$singleton.{name}"),
    })
}

pub fn ruby_field_short_name(
    segments: &[String],
    node: Node<'_>,
    source: &str,
    scope: RubyFieldScope,
) -> Option<String> {
    if segments.is_empty() {
        return None;
    }
    let member = ruby_field_member_name(node, source, scope)?;
    Some(member_short_name(segments, &member))
}

/// The structured counterpart of [`ruby_field_short_name`].
fn ruby_field_fq(
    segments: &[String],
    node: Node<'_>,
    source: &str,
    scope: RubyFieldScope,
) -> Option<FqName> {
    if segments.is_empty() {
        return None;
    }
    let name = ruby_variable_field_name(node, source)?;
    Some(ruby_scoped_field_fq(
        segments,
        &name,
        scope == RubyFieldScope::SingletonClass,
    ))
}

/// Builds the structured identity for a Ruby field. `$singleton` is a real
/// synthetic owner scope, not part of the terminal field identifier.
fn ruby_scoped_field_fq(segments: &[String], name: &str, singleton: bool) -> FqName {
    let mut fq = ruby_type_chain_fq(segments);
    if singleton {
        fq.push(ruby_segment("$singleton", SegmentKind::Package));
    }
    fq.push(ruby_segment(name, SegmentKind::Member));
    fq
}

pub fn ruby_field_scope_for_assignment_left(
    left: Node<'_>,
    segments: &[String],
    current_scope: Option<RubyFieldScope>,
) -> Option<RubyFieldScope> {
    if segments.is_empty() {
        return None;
    }
    match left.kind() {
        "class_variable" => Some(RubyFieldScope::ClassVariable),
        "instance_variable" => Some(current_scope.unwrap_or(RubyFieldScope::SingletonClass)),
        _ => None,
    }
}

fn ruby_method_field_scope(node: Node<'_>) -> RubyFieldScope {
    if method_is_singleton_context(node) {
        RubyFieldScope::SingletonClass
    } else {
        RubyFieldScope::Instance
    }
}

fn ruby_method_dispatch_mode(node: Node<'_>, source: &str) -> RubyMethodDispatchMode {
    if module_function_applies_to_method(node, source) {
        RubyMethodDispatchMode::ModuleFunction
    } else if method_is_singleton_context(node) {
        RubyMethodDispatchMode::Singleton
    } else {
        RubyMethodDispatchMode::Instance
    }
}

fn method_is_singleton_context(node: Node<'_>) -> bool {
    if node.kind() == "singleton_method" {
        return true;
    }
    let mut parent = node.parent();
    while let Some(current) = parent {
        if current.kind() == "singleton_class" {
            return true;
        }
        if matches!(current.kind(), "class" | "module") {
            break;
        }
        parent = current.parent();
    }
    false
}

fn module_function_applies_to_method(node: Node<'_>, source: &str) -> bool {
    if node.kind() != "method" {
        return false;
    }
    let Some(name_node) = node.child_by_field_name("name") else {
        return false;
    };
    let method_name = ruby_node_text(name_node, source).trim();
    let Some(module) = enclosing_module_for_module_function(node) else {
        return false;
    };
    let Some(body) = module.child_by_field_name("body") else {
        return false;
    };

    let mut bare_module_function_active = false;
    let mut stack = vec![body];
    while let Some(current) = stack.pop() {
        if current != body
            && matches!(
                current.kind(),
                "class" | "module" | "method" | "singleton_method"
            )
        {
            continue;
        }
        if current.kind() == "identifier"
            && current.start_byte() < node.start_byte()
            && ruby_node_text(current, source).trim() == "module_function"
        {
            bare_module_function_active = true;
            continue;
        }
        if current.kind() == "call"
            && let Some(method) = current.child_by_field_name("method")
            && ruby_node_text(method, source).trim() == "module_function"
        {
            let mut names = module_function_names(current, source);
            if names.next().is_none() {
                if current.start_byte() < node.start_byte() {
                    bare_module_function_active = true;
                }
            } else if module_function_names(current, source).any(|name| name == method_name) {
                return true;
            }
            continue;
        }
        for index in (0..current.named_child_count()).rev() {
            if let Some(child) = current.named_child(index) {
                stack.push(child);
            }
        }
    }
    bare_module_function_active
}

fn enclosing_module_for_module_function(node: Node<'_>) -> Option<Node<'_>> {
    let mut parent = node.parent();
    while let Some(current) = parent {
        match current.kind() {
            "module" => return Some(current),
            "class" => return None,
            _ => parent = current.parent(),
        }
    }
    None
}

fn module_function_names<'a>(node: Node<'_>, source: &'a str) -> impl Iterator<Item = String> + 'a {
    let mut names = Vec::new();
    if let Some(arguments) = node.child_by_field_name("arguments") {
        let mut cursor = arguments.walk();
        for arg in arguments.named_children(&mut cursor) {
            if let Some(name) = literal_symbol_or_string_name(arg, source) {
                names.push(name);
            }
        }
    }
    names.into_iter()
}

fn assignment_constant_short_name(lexical_segments: &[String], name_path: &RubyNamePath) -> String {
    let Some((name, owner_segments)) = name_path.segments.split_last() else {
        return String::new();
    };
    if owner_segments.is_empty() {
        return member_short_name(lexical_segments, name);
    }
    if name_path.absolute || owner_segments.len() > 1 || lexical_segments.is_empty() {
        return member_short_name(owner_segments, name);
    }

    let mut resolved_owner = Vec::new();
    resolved_owner.extend_from_slice(lexical_segments);
    resolved_owner.extend_from_slice(owner_segments);
    member_short_name(&resolved_owner, name)
}

/// The structured counterpart of [`assignment_constant_short_name`] — mirrors
/// its branches exactly, building an [`FqName`] from the same owner segments
/// instead of a `$`-joined string. The owner segments come from the constant
/// reference's own AST-derived name path (`extract_name_path`), which may name
/// a different (re-opened) namespace than the lexically enclosing one, so this
/// builds a fresh chain rather than extending a `parent` `CodeUnit`'s `fq`.
fn assignment_constant_fq(lexical_segments: &[String], name_path: &RubyNamePath) -> FqName {
    let Some((name, owner_segments)) = name_path.segments.split_last() else {
        return FqName::new();
    };
    if owner_segments.is_empty() {
        return ruby_member_fq(lexical_segments, name);
    }
    if name_path.absolute || owner_segments.len() > 1 || lexical_segments.is_empty() {
        return ruby_member_fq(owner_segments, name);
    }

    let mut resolved_owner = Vec::new();
    resolved_owner.extend_from_slice(lexical_segments);
    resolved_owner.extend_from_slice(owner_segments);
    ruby_member_fq(&resolved_owner, name)
}

pub struct RubyNamePath {
    pub segments: Vec<String>,
    pub absolute: bool,
}

/// Extracts the namespace segments from a class/module name node by walking the
/// AST (not by string-splitting `::`). A plain `(constant)` yields one segment;
/// a `(scope_resolution)` like `A::B` walks its `scope` and `name` fields to
/// yield `["A", "B"]`.
pub fn extract_name_segments(name_node: Node<'_>, source: &str) -> Vec<String> {
    extract_name_path(name_node, source).segments
}

pub fn extract_name_path(name_node: Node<'_>, source: &str) -> RubyNamePath {
    match name_node.kind() {
        "scope_resolution" => {
            let mut path = name_node
                .child_by_field_name("scope")
                .map(|scope| extract_name_path(scope, source))
                .unwrap_or_else(|| RubyNamePath {
                    segments: Vec::new(),
                    absolute: true,
                });
            if let Some(name) = name_node.child_by_field_name("name") {
                path.segments.extend(extract_name_segments(name, source));
            }
            path
        }
        _ => {
            let text = ruby_node_text(name_node, source).trim();
            let segments = if text.is_empty() {
                Vec::new()
            } else {
                vec![text.to_string()]
            };
            RubyNamePath {
                segments,
                absolute: false,
            }
        }
    }
}

/// Renders a `constant`/`scope_resolution` reference node into the internal
/// `$`-joined name used as a `CodeUnit` key (e.g. `A::B` -> `A$B`).
pub fn qualified_internal_name(node: Node<'_>, source: &str) -> Option<String> {
    let segments = extract_name_segments(node, source);
    (!segments.is_empty()).then(|| segments.join("$"))
}

/// Collects a class/module's true superclass. Ruby mixins are intentionally not
/// type hierarchy ancestors; they are modeled separately for method lookup.
fn extract_ruby_supertypes(node: Node<'_>, source: &str) -> Vec<String> {
    let mut supertypes = Vec::new();

    if let Some(superclass) = node.child_by_field_name("superclass") {
        let mut cursor = superclass.walk();
        if let Some(expr) = superclass.named_children(&mut cursor).next()
            && let Some(name) = qualified_internal_name(expr, source)
        {
            supertypes.push(name);
        }
    }

    supertypes
}

/// Extracts the bare name from a literal `attr_*`/`alias_method` argument,
/// which is usually a symbol (`:name`) or string (`"name"`).
fn literal_symbol_or_string_name(node: Node<'_>, source: &str) -> Option<String> {
    if !matches!(node.kind(), "simple_symbol" | "string") {
        return None;
    }
    let text = ruby_node_text(node, source).trim();
    let stripped = text
        .strip_prefix(':')
        .unwrap_or(text)
        .trim_matches(['"', '\'']);
    (!stripped.is_empty()).then(|| stripped.to_string())
}

/// First non-blank line of a node's source, used as a one-line signature.
fn first_line(node: Node<'_>, source: &str) -> String {
    ruby_node_text(node, source)
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty())
        .unwrap_or_default()
        .to_string()
}

fn ruby_signature_metadata(signature: String, node: Node<'_>, source: &str) -> SignatureMetadata {
    let Some(parameters_node) = node.child_by_field_name("parameters") else {
        return SignatureMetadata::new(signature, Vec::new())
            .with_dispatch_extensibility(DispatchExtensibility::Open);
    };
    let mut cursor = parameters_node.walk();
    let labels = parameters_node
        .named_children(&mut cursor)
        .filter_map(|child| ruby_parameter_label_node(child))
        .map(|label_node| ruby_node_text(label_node, source).trim().to_string())
        .filter(|label| !label.is_empty())
        .collect();
    SignatureMetadata::with_parameter_labels(signature, labels)
        .with_dispatch_extensibility(DispatchExtensibility::Open)
}

fn ruby_parameter_label_node(node: Node<'_>) -> Option<Node<'_>> {
    match node.kind() {
        "identifier" => Some(node),
        "optional_parameter"
        | "keyword_parameter"
        | "splat_parameter"
        | "hash_splat_parameter"
        | "block_parameter" => node
            .child_by_field_name("name")
            .or_else(|| first_identifier_descendant(node)),
        _ => None,
    }
}

fn first_identifier_descendant(node: Node<'_>) -> Option<Node<'_>> {
    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        if current.kind() == "identifier" {
            return Some(current);
        }
        for index in (0..current.named_child_count()).rev() {
            if let Some(child) = current.named_child(index) {
                stack.push(child);
            }
        }
    }
    None
}

/// Container node kinds the visitor recurses through to find conditionally
/// declared symbols (e.g. a `def` inside an `if`). Excludes `method`/
/// `singleton_method`, whose bodies are treated as leaves.
pub fn is_descendable_container(kind: &str) -> bool {
    matches!(
        kind,
        "if" | "unless"
            | "elsif"
            | "else"
            | "while"
            | "until"
            | "for"
            | "case"
            | "case_match"
            | "when"
            | "in_clause"
            | "begin"
            | "body_statement"
            | "do"
            | "do_block"
            | "block"
            | "then"
            | "ensure"
            | "rescue"
            | "parenthesized_statements"
            | "begin_block"
            | "end_block"
    )
}

pub fn collect_ruby_identifiers(node: Node<'_>, source: &str, identifiers: &mut HashSet<String>) {
    walk_named_tree_preorder(node, true, |node| {
        if matches!(node.kind(), "identifier" | "constant") {
            let text = ruby_node_text(node, source).trim();
            if !text.is_empty() {
                identifiers.insert(text.to_string());
            }
        }
        WalkControl::Continue
    });
}