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
use crate::declarations::{RubyFieldScope, extract_name_path};
use crate::graph::RubyGraphSource;
use crate::graph_support::{RubySemanticFacts, RubySource};
use crate::mixins::{ruby_forward_mixin_specs, ruby_forward_superclass_targets};
use brokk_bifrost_core::analyzer::model::RubyMethodDispatchMode;
use brokk_bifrost_core::analyzer::type_relations::TypeRelationKind;
use brokk_bifrost_core::analyzer::{BoundedDefinitionLookup, CodeUnit, ProjectFile};
use brokk_bifrost_core::hash::{HashMap, HashSet};
use std::cell::RefCell;
use tree_sitter::Node;

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RubyTargetKind {
    TypeOrConstant,
    Method,
    Field(RubyFieldScope),
}

pub struct RubyTargetSpec {
    pub target: CodeUnit,
    pub kind: RubyTargetKind,
    pub member_name: String,
    pub field_owner: Option<String>,
}

pub struct RubyFieldTarget {
    pub owner: String,
    pub scope: RubyFieldScope,
    pub member: String,
}

impl RubyTargetSpec {
    pub fn from_target(
        graph: &RubyGraphSource<'_>,
        ruby: &dyn RubySource,
        target: &CodeUnit,
    ) -> Option<Self> {
        if target.is_field()
            && let Some(field) = ruby_field_target(target)
        {
            return Some(Self {
                target: target.clone(),
                kind: RubyTargetKind::Field(field.scope),
                member_name: field.member,
                field_owner: Some(field.owner),
            });
        }
        if target.is_class() || target.is_module() || target.is_field() {
            return Some(Self {
                target: target.clone(),
                kind: RubyTargetKind::TypeOrConstant,
                member_name: target.identifier().to_string(),
                field_owner: None,
            });
        }
        if target.is_function() {
            let class_side_declaration = matches!(
                ruby.method_dispatch_mode(target),
                RubyMethodDispatchMode::Singleton | RubyMethodDispatchMode::ModuleFunction
            );
            if graph.index.parent_of(target).is_none() && class_side_declaration {
                return None;
            }
            return Some(Self {
                target: target.clone(),
                kind: RubyTargetKind::Method,
                member_name: target.identifier().to_string(),
                field_owner: None,
            });
        }
        None
    }
}

pub fn ruby_field_target(target: &CodeUnit) -> Option<RubyFieldTarget> {
    let member = target.identifier();
    // fqname-M4: `owner` below is compared against a package-less class-name
    // reference-text `owner` parsed at a field-reference site (see
    // `field_reference_matches_target`); `fq.parent()`/`default_parent_fq_name`
    // would render the package-qualified owner, a different string that would
    // never match there.
    let short_name = target.short_name();
    if member.starts_with("@@") {
        let owner = short_name.strip_suffix(&format!(".{member}"))?;
        return (!owner.is_empty()).then(|| RubyFieldTarget {
            owner: owner.to_string(),
            scope: RubyFieldScope::ClassVariable,
            member: member.to_string(),
        });
    }
    if member.starts_with('@') {
        let singleton_suffix = format!(".$singleton.{member}");
        if let Some(owner) = short_name.strip_suffix(&singleton_suffix) {
            return (!owner.is_empty()).then(|| RubyFieldTarget {
                owner: owner.to_string(),
                scope: RubyFieldScope::SingletonClass,
                member: member.to_string(),
            });
        }
        let owner = short_name.strip_suffix(&format!(".{member}"))?;
        return (!owner.is_empty()).then(|| RubyFieldTarget {
            owner: owner.to_string(),
            scope: RubyFieldScope::Instance,
            member: member.to_string(),
        });
    }
    None
}

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ReceiverMode {
    Instance,
    Class,
    TopLevel,
}

#[derive(Clone, Copy)]
pub enum ExplicitReceiverLookup {
    Bare,
    ReceiverOnly,
}

#[derive(Clone)]
pub struct ReceiverType {
    pub owner_fq_name: String,
    pub mode: ReceiverMode,
}

pub struct RubySemanticIndex<'a> {
    pub graph: RubyGraphSource<'a>,
    pub ruby: &'a dyn RubySource,
    facts: Option<&'a RubySemanticFacts>,
    target: Option<CodeUnit>,
    forward_owner_facts: RefCell<HashMap<String, RubyForwardOwnerFacts>>,
    pub factory_return_cache: RefCell<HashMap<FactoryInferenceKey, Option<String>>>,
}

#[derive(Clone, Default)]
struct RubyForwardOwnerFacts {
    ancestors: Vec<String>,
    included: Vec<String>,
    prepended: Vec<String>,
    extended: Vec<String>,
}

impl<'a> RubySemanticIndex<'a> {
    pub fn build(
        graph: RubyGraphSource<'a>,
        ruby: &'a dyn RubySource,
        spec: &RubyTargetSpec,
    ) -> Self {
        Self::build_with_target(graph, ruby, Some(spec.target.clone()))
    }

    pub fn build_for_lookup(graph: RubyGraphSource<'a>, ruby: &'a dyn RubySource) -> Self {
        Self::build_with_target(graph, ruby, None)
    }

    fn build_with_target(
        graph: RubyGraphSource<'a>,
        ruby: &'a dyn RubySource,
        target: Option<CodeUnit>,
    ) -> Self {
        Self {
            graph,
            ruby,
            facts: target.as_ref().map(|_| ruby.semantic_facts()),
            target,
            forward_owner_facts: RefCell::new(HashMap::default()),
            factory_return_cache: RefCell::new(HashMap::default()),
        }
    }

    pub fn visible_files_from(&self, file: &ProjectFile) -> HashSet<ProjectFile> {
        let mut visible = HashSet::default();
        visible.insert(file.clone());
        if let Some(zeitwerk_files) =
            crate::imports::ruby_zeitwerk_visible_files_for(self.ruby, file)
        {
            visible.extend(zeitwerk_files.iter().cloned());
        }
        let mut stack = crate::imports::ruby_required_files(self.ruby, file);
        while let Some(next) = stack.pop() {
            if !visible.insert(next.clone()) {
                continue;
            }
            stack.extend(crate::imports::ruby_required_files(self.ruby, &next));
        }
        visible
    }

    /// Follows only explicit project-local `require` edges and fails closed
    /// when the dependency closure is too broad for a latency-sensitive caller.
    ///
    /// Diagnostics use this instead of the navigation-oriented visibility
    /// closure. Callers that want convention-derived Zeitwerk visibility must
    /// continue using [`Self::visible_files_from`].
    pub fn visible_files_from_bounded(
        &self,
        file: &ProjectFile,
        max_files: usize,
    ) -> Option<HashSet<ProjectFile>> {
        let mut visible = HashSet::default();
        visible.insert(file.clone());
        let mut stack = crate::imports::ruby_required_files(self.ruby, file);
        while let Some(next) = stack.pop() {
            if !visible.insert(next.clone()) {
                continue;
            }
            if visible.len() > max_files {
                return None;
            }
            stack.extend(crate::imports::ruby_required_files(self.ruby, &next));
        }
        Some(visible)
    }

    pub fn resolve_constant(
        &self,
        file: &ProjectFile,
        visible_files: &HashSet<ProjectFile>,
        lexical_stack: &[String],
        node: Node<'_>,
        source: &str,
    ) -> Option<CodeUnit> {
        let path = extract_name_path(node, source);
        self.resolve_constant_path(
            file,
            visible_files,
            lexical_stack,
            &path.segments,
            path.absolute,
            true,
        )
    }

    /// Resolves only indexed declarations in the supplied project-local
    /// visibility closure. This avoids initializing the workspace-wide
    /// `autoload` index for conservative, latency-sensitive diagnostics.
    pub fn resolve_project_local_constant(
        &self,
        file: &ProjectFile,
        visible_files: &HashSet<ProjectFile>,
        lexical_stack: &[String],
        node: Node<'_>,
        source: &str,
    ) -> Option<CodeUnit> {
        let path = extract_name_path(node, source);
        self.resolve_constant_path(
            file,
            visible_files,
            lexical_stack,
            &path.segments,
            path.absolute,
            false,
        )
    }

    /// Whether the workspace declares the constant path `node` spells anywhere
    /// at all, ignoring which files the referencing file can reach.
    ///
    /// [`Self::resolve_constant`] answers the navigation question -- can this
    /// file reach the declaration -- and a cross-workspace boundary claim must
    /// not be built on it. A project file that declares the constant without
    /// being required is still a workspace declaration, and reporting the
    /// reference as leaving the workspace would be false. This is the weaker,
    /// visibility-blind question such a claim has to ask first.
    pub fn declares_constant_anywhere(
        &self,
        lexical_stack: &[String],
        node: Node<'_>,
        source: &str,
    ) -> bool {
        let path = extract_name_path(node, source);
        let Some(candidates) =
            constant_lookup_candidates(lexical_stack, &path.segments, path.absolute)
        else {
            return false;
        };
        candidates
            .iter()
            .any(|candidate| self.graph.index.definitions(candidate).next().is_some())
    }

    pub fn resolve_constant_name(
        &self,
        file: &ProjectFile,
        visible_files: &HashSet<ProjectFile>,
        lexical_stack: &[String],
        name: &str,
    ) -> Option<CodeUnit> {
        self.resolve_constant_path(
            file,
            visible_files,
            lexical_stack,
            &[name.to_string()],
            false,
            true,
        )
    }

    fn resolve_constant_path(
        &self,
        file: &ProjectFile,
        visible_files: &HashSet<ProjectFile>,
        lexical_stack: &[String],
        segments: &[String],
        absolute: bool,
        include_autoload: bool,
    ) -> Option<CodeUnit> {
        let candidates = constant_lookup_candidates(lexical_stack, segments, absolute)?;

        candidates.into_iter().find_map(|candidate| {
            let autoload_files = if include_autoload {
                crate::imports::ruby_autoload_visible_files_for_constant(self.ruby, &candidate)
            } else {
                HashSet::default()
            };
            self.graph.index.definitions(&candidate).find(|unit| {
                visible_files.contains(unit.source())
                    || unit.source() == file
                    || autoload_files.contains(unit.source())
            })
        })
    }

    pub fn target_matches_constant(&self, unit: &CodeUnit) -> bool {
        self.target
            .as_ref()
            .is_some_and(|target| unit == target || unit.fq_name() == target.fq_name())
    }

    pub fn resolve_method_candidates(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
    ) -> Vec<CodeUnit> {
        self.method_candidates(support, visible_files, receiver, member, None)
    }

    /// [`Self::resolve_method_candidates`], reporting where the group it
    /// returns was found (#1477).
    ///
    /// The lookup returns the first non-empty group it reaches, so one owner
    /// and one edge describe every candidate in that group. A caller that does
    /// not ask keeps the plain entry point and pays nothing.
    pub fn resolve_method_candidates_traced(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
        find: &mut Option<RubyMethodFind>,
    ) -> Vec<CodeUnit> {
        self.method_candidates(support, visible_files, receiver, member, Some(find))
    }

    fn method_candidates(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
        mut find: Option<&mut Option<RubyMethodFind>>,
    ) -> Vec<CodeUnit> {
        let visible_files: Vec<ProjectFile> = visible_files.iter().cloned().collect();
        let mut seen = HashSet::default();
        let mut push_owner = |owner: &str, mode: RubyMethodLookupMode, out: &mut Vec<CodeUnit>| {
            for unit in support.fqn_direct_children(owner) {
                if unit.is_function()
                    && unit.identifier() == member
                    && visible_files.contains(unit.source())
                    && ruby_method_lookup_mode_matches(self.ruby, &unit, mode)
                    && seen.insert(unit.clone())
                {
                    out.push(unit);
                }
            }
        };

        match receiver.mode {
            ReceiverMode::TopLevel => {
                self.resolve_top_level_method_candidates(support, &visible_files, member)
            }
            ReceiverMode::Instance => {
                for owner in self.forward_receiver_owner_lookup_order(
                    support,
                    &visible_files,
                    &receiver.owner_fq_name,
                ) {
                    let mut prepended = Vec::new();
                    let mut prepended_from = None;
                    for mixin in self
                        .mixin_owners(
                            support,
                            &visible_files,
                            &owner,
                            TypeRelationKind::MixinPrepend,
                        )
                        .into_iter()
                        .rev()
                    {
                        push_owner(&mixin, RubyMethodLookupMode::InstanceMethod, &mut prepended);
                        if !prepended.is_empty() {
                            prepended_from = Some(mixin);
                            break;
                        }
                    }
                    if !prepended.is_empty() {
                        record_find(
                            &mut find,
                            &owner,
                            prepended_from,
                            Some(TypeRelationKind::MixinPrepend),
                            false,
                        );
                        return prepended;
                    }

                    let mut direct = Vec::new();
                    push_owner(&owner, RubyMethodLookupMode::InstanceMethod, &mut direct);
                    if !direct.is_empty() {
                        record_find(&mut find, &owner, None, None, false);
                        return direct;
                    }

                    let mut included = Vec::new();
                    let mut included_from = None;
                    for mixin in self
                        .mixin_owners(
                            support,
                            &visible_files,
                            &owner,
                            TypeRelationKind::MixinInclude,
                        )
                        .into_iter()
                        .rev()
                    {
                        push_owner(&mixin, RubyMethodLookupMode::InstanceMethod, &mut included);
                        if !included.is_empty() {
                            included_from = Some(mixin);
                            break;
                        }
                    }
                    if !included.is_empty() {
                        record_find(
                            &mut find,
                            &owner,
                            included_from,
                            Some(TypeRelationKind::MixinInclude),
                            false,
                        );
                        return included;
                    }
                }
                Vec::new()
            }
            ReceiverMode::Class => {
                for owner in self.forward_receiver_owner_lookup_order(
                    support,
                    &visible_files,
                    &receiver.owner_fq_name,
                ) {
                    let mut direct = Vec::new();
                    push_owner(&owner, RubyMethodLookupMode::SingletonMethod, &mut direct);
                    if !direct.is_empty() {
                        record_find(&mut find, &owner, None, None, true);
                        return direct;
                    }

                    let mut extended = Vec::new();
                    let mut extended_from = None;
                    for mixin in self
                        .mixin_owners(
                            support,
                            &visible_files,
                            &owner,
                            TypeRelationKind::MixinExtend,
                        )
                        .into_iter()
                        .rev()
                    {
                        push_owner(&mixin, RubyMethodLookupMode::InstanceMethod, &mut extended);
                        if !extended.is_empty() {
                            extended_from = Some(mixin);
                            break;
                        }
                    }
                    if !extended.is_empty() {
                        record_find(
                            &mut find,
                            &owner,
                            extended_from,
                            Some(TypeRelationKind::MixinExtend),
                            true,
                        );
                        return extended;
                    }
                }
                Vec::new()
            }
        }
    }

    pub fn resolve_bare_method_candidates(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
    ) -> Vec<CodeUnit> {
        self.bare_method_candidates(support, visible_files, receiver, member, None)
    }

    /// [`Self::resolve_bare_method_candidates`], reporting where the group it
    /// returns was found (#1477).
    ///
    /// A bare name that falls through to the top-level scope reports no find:
    /// a top-level method belongs to no owner, so there is nothing to
    /// attribute it to.
    pub fn resolve_bare_method_candidates_traced(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
        find: &mut Option<RubyMethodFind>,
    ) -> Vec<CodeUnit> {
        self.bare_method_candidates(support, visible_files, receiver, member, Some(find))
    }

    fn bare_method_candidates(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &HashSet<ProjectFile>,
        receiver: &ReceiverType,
        member: &str,
        find: Option<&mut Option<RubyMethodFind>>,
    ) -> Vec<CodeUnit> {
        let candidates = self.method_candidates(support, visible_files, receiver, member, find);
        if !candidates.is_empty() || receiver.mode == ReceiverMode::TopLevel {
            return candidates;
        }
        let visible_files: Vec<ProjectFile> = visible_files.iter().cloned().collect();
        self.resolve_top_level_method_candidates(support, &visible_files, member)
    }

    /// The direct ancestors of `owner`: the exact edges
    /// [`Self::forward_ancestor_lookup_order`] walks, before it flattens them
    /// into a lookup order that no longer says which owner reached which.
    pub fn direct_ancestor_owners(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
    ) -> Vec<String> {
        if let Some(facts) = self.facts {
            let mut direct: Vec<String> = facts
                .ancestors
                .get(owner)
                .map(|items| items.iter().cloned().collect())
                .unwrap_or_default();
            direct.sort();
            return direct;
        }
        self.forward_owner_facts(support, visible_files, owner)
            .ancestors
    }

    /// The mixins `owner` composes in through `kind`, in the order the method
    /// lookup considers them.
    pub fn mixin_owners_of(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
        kind: TypeRelationKind,
    ) -> Vec<String> {
        self.mixin_owners(support, visible_files, owner, kind)
    }

    /// The class or module declaration `owner` names, as the lookup resolves
    /// it: an indexed class or module of that exact fq name, visible from the
    /// referencing file.
    pub fn owner_unit(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
    ) -> Option<CodeUnit> {
        support.fqn(owner).into_iter().find(|unit| {
            (unit.is_class() || unit.is_module())
                && unit.fq_name() == owner
                && visible_files.contains(unit.source())
        })
    }

    fn resolve_top_level_method_candidates(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        member: &str,
    ) -> Vec<CodeUnit> {
        support
            .file_identifier_in_files(visible_files, member)
            .into_iter()
            .filter(|unit| {
                unit.is_function()
                    && unit.identifier() == member
                    && self.graph.index.parent_of(unit).is_none()
                    && !ruby_method_lookup_mode_matches(
                        self.ruby,
                        unit,
                        RubyMethodLookupMode::SingletonMethod,
                    )
            })
            .collect()
    }

    fn mixin_owners(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
        kind: TypeRelationKind,
    ) -> Vec<String> {
        if let Some(facts) = self.facts {
            let index = match kind {
                TypeRelationKind::MixinInclude => &facts.mixin_included_owners,
                TypeRelationKind::MixinPrepend => &facts.mixin_prepended_owners,
                TypeRelationKind::MixinExtend => &facts.mixin_class_owners,
                _ => return Vec::new(),
            };
            return index.get(owner).cloned().unwrap_or_default();
        }
        let facts = self.forward_owner_facts(support, visible_files, owner);
        match kind {
            TypeRelationKind::MixinInclude => facts.included,
            TypeRelationKind::MixinPrepend => facts.prepended,
            TypeRelationKind::MixinExtend => facts.extended,
            _ => Vec::new(),
        }
    }

    pub fn ancestor_lookup_order(&self, owner: &str) -> Vec<String> {
        let Some(facts) = self.facts else {
            return Vec::new();
        };
        let mut out = Vec::new();
        let mut visited = HashSet::default();
        let mut stack: Vec<String> = facts
            .ancestors
            .get(owner)
            .map(|items| items.iter().cloned().collect())
            .unwrap_or_default();
        while let Some(candidate) = stack.pop() {
            if !visited.insert(candidate.clone()) {
                continue;
            }
            out.push(candidate.clone());
            if let Some(next) = facts.ancestors.get(&candidate) {
                stack.extend(next.iter().cloned());
            }
        }
        out
    }

    pub fn forward_ancestor_lookup_order(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
    ) -> Vec<String> {
        if self.facts.is_some() {
            return self.ancestor_lookup_order(owner);
        }
        let mut out = Vec::new();
        let mut visited = HashSet::default();
        let mut stack = self
            .forward_owner_facts(support, visible_files, owner)
            .ancestors;
        stack.reverse();
        while let Some(candidate) = stack.pop() {
            if !visited.insert(candidate.clone()) {
                continue;
            }
            out.push(candidate.clone());
            let mut next = self
                .forward_owner_facts(support, visible_files, &candidate)
                .ancestors;
            next.reverse();
            stack.extend(next);
        }
        out
    }

    fn forward_receiver_owner_lookup_order(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
    ) -> Vec<String> {
        let mut owners = vec![owner.to_string()];
        owners.extend(self.forward_ancestor_lookup_order(support, visible_files, owner));
        owners
    }

    fn forward_owner_facts(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        owner: &str,
    ) -> RubyForwardOwnerFacts {
        if let Some(cached) = self.forward_owner_facts.borrow().get(owner) {
            return cached.clone();
        }
        let Some(owner_unit) = self.owner_unit(support, visible_files, owner) else {
            self.forward_owner_facts
                .borrow_mut()
                .insert(owner.to_string(), RubyForwardOwnerFacts::default());
            return RubyForwardOwnerFacts::default();
        };

        let specs = ruby_forward_mixin_specs(self.ruby, &owner_unit);
        let mixin_names: HashSet<String> =
            specs.iter().map(|spec| spec.raw_target.clone()).collect();
        let mut facts = RubyForwardOwnerFacts::default();
        for spec in specs {
            let Some(target) =
                self.resolve_forward_owner_name(support, visible_files, owner, &spec.raw_target)
            else {
                continue;
            };
            match spec.kind {
                TypeRelationKind::MixinInclude => facts.included.push(target),
                TypeRelationKind::MixinPrepend => facts.prepended.push(target),
                TypeRelationKind::MixinExtend => facts.extended.push(target),
                _ => {}
            }
        }
        for raw in ruby_forward_superclass_targets(self.ruby, &owner_unit) {
            if mixin_names.contains(&raw) {
                continue;
            }
            if let Some(target) =
                self.resolve_forward_owner_name(support, visible_files, owner, &raw)
            {
                facts.ancestors.push(target);
            }
        }
        facts.ancestors.dedup();
        facts.included.dedup();
        facts.prepended.dedup();
        facts.extended.dedup();
        self.forward_owner_facts
            .borrow_mut()
            .insert(owner.to_string(), facts.clone());
        facts
    }

    fn resolve_forward_owner_name(
        &self,
        support: &dyn BoundedDefinitionLookup,
        visible_files: &[ProjectFile],
        lexical_owner: &str,
        raw: &str,
    ) -> Option<String> {
        let mut candidate_names = vec![raw.to_string()];
        let mut prefix = lexical_owner;
        // fqname-M4: walks the `$`-joined lexical-owner *string* (not a CodeUnit) to enumerate
        // enclosing-scope candidate names; fq not threaded to this string-keyed support probe
        while let Some((parent, _)) = prefix.rsplit_once('$') {
            candidate_names.push(format!("{parent}${raw}"));
            prefix = parent;
        }
        for candidate in candidate_names {
            let mut matches = support.fqn(&candidate);
            matches.retain(|unit| {
                (unit.is_class() || unit.is_module()) && visible_files.contains(unit.source())
            });
            matches.sort();
            matches.dedup();
            if matches.len() == 1 {
                return Some(matches.remove(0).fq_name());
            }
        }

        let identifier = raw.rsplit('$').next().unwrap_or(raw); // fqname-M4: leaf of a `$`-joined reference string (no CodeUnit here)
        let mut matches = support.file_identifier_in_files(visible_files, identifier);
        matches.retain(|unit| {
            (unit.is_class() || unit.is_module()) && unit.identifier() == identifier
        });
        matches.sort();
        matches.dedup();
        (matches.len() == 1).then(|| matches.remove(0).fq_name())
    }
}

/// Where a method lookup found the group of candidates it returned (#1477).
///
/// The lookup walks the receiver's ancestor order and returns the first
/// non-empty group it reaches, so exactly one owner and one edge describe
/// every candidate in that group.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RubyMethodFind {
    /// The owner in the receiver's ancestor lookup order the group was
    /// reached from.
    pub reached_from: String,
    /// The owner that declares the group: `reached_from` itself, or the module
    /// `mixin` names.
    pub owner: String,
    /// The mixin edge from `reached_from` to `owner`, absent when the group
    /// was declared by `reached_from` itself.
    pub mixin: Option<TypeRelationKind>,
    /// Whether the lookup was on the owner's class side.
    pub class_side: bool,
}

/// Record one find, when the caller asked for one. Every argument is a fact
/// the branch that calls this has just decided; nothing here re-derives one.
fn record_find(
    find: &mut Option<&mut Option<RubyMethodFind>>,
    reached_from: &str,
    mixin_owner: Option<String>,
    mixin: Option<TypeRelationKind>,
    class_side: bool,
) {
    let Some(slot) = find.as_deref_mut() else {
        return;
    };
    debug_assert_eq!(
        mixin_owner.is_some(),
        mixin.is_some(),
        "a mixin edge and the module it reaches are recorded together"
    );
    *slot = Some(RubyMethodFind {
        owner: mixin_owner.unwrap_or_else(|| reached_from.to_owned()),
        reached_from: reached_from.to_owned(),
        mixin,
        class_side,
    });
}

#[derive(Clone, Copy)]
pub enum RubyMethodLookupMode {
    InstanceMethod,
    SingletonMethod,
}

#[derive(Clone, Eq, Hash, PartialEq)]
pub struct FactoryInferenceKey {
    pub method: CodeUnit,
    pub invocation_owner_fq_name: String,
}

pub struct FactoryInferenceFrame {
    pub method: CodeUnit,
    pub invocation_owner_fq_name: String,
}

pub enum FactoryMethodOutcome {
    Owner(String),
    Chain(Vec<FactoryInferenceFrame>),
    Unknown,
}

pub fn ruby_method_lookup_mode_matches(
    ruby: &dyn RubySource,
    unit: &CodeUnit,
    mode: RubyMethodLookupMode,
) -> bool {
    matches!(
        (ruby.method_dispatch_mode(unit), mode),
        (
            RubyMethodDispatchMode::Instance,
            RubyMethodLookupMode::InstanceMethod
        ) | (
            RubyMethodDispatchMode::Singleton,
            RubyMethodLookupMode::SingletonMethod
        ) | (RubyMethodDispatchMode::ModuleFunction, _)
    )
}

fn constant_lookup_candidates(
    lexical_stack: &[String],
    segments: &[String],
    absolute: bool,
) -> Option<Vec<String>> {
    if segments.is_empty() {
        return None;
    }

    let name = segments.join("$");
    let mut candidates = Vec::new();
    if !absolute {
        for owner in lexical_stack.iter().rev() {
            candidates.push(format!("{owner}${name}"));
        }
    }
    candidates.push(name);

    let Some((constant_name, owner_segments)) = segments.split_last() else {
        return Some(candidates);
    };
    if owner_segments.is_empty() {
        if !absolute {
            for owner in lexical_stack.iter().rev() {
                candidates.push(format!("{owner}.{constant_name}"));
            }
        }
        return Some(candidates);
    }

    let owner_name = owner_segments.join("$");
    if !absolute {
        for owner in lexical_stack.iter().rev() {
            candidates.push(format!("{owner}${owner_name}.{constant_name}"));
        }
    }
    candidates.push(format!("{owner_name}.{constant_name}"));

    Some(candidates)
}