cuke-dedup 0.13.0

Static analysis for duplicate and reusable Cucumber step definitions
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
//! Source-order local bindings for handler identity; names never establish framework trust.
use super::{descendants, literal_string, text};
use std::cell::OnceCell;
use std::collections::{BTreeMap, BTreeSet};
use tree_sitter::Node;

#[derive(Default)]
pub(super) struct Bindings {
    pub names: BTreeMap<usize, String>,
    pub captures: BTreeSet<String>,
    /// A capture whose identity holds only inside its file.
    pub lexical: bool,
    pub calls: BTreeSet<usize>,
    pub uncertain: bool,
    /// Lambda literals assigned to handler locals: syntax, not behaviour.
    pub elided: BTreeSet<usize>,
    /// Zero-argument invocations whose single declaration executes in place.
    pub expansions: BTreeMap<usize, usize>,
    /// Invocations of parameterized declared lambdas; the body's values stay unproven.
    pub unresolved_invocations: BTreeSet<usize>,
}

const WALLS: [&str; 5] = [
    "method",
    "singleton_method",
    "class",
    "module",
    "singleton_class",
];

/// Blocks and lambdas open a scope that still closes over the enclosing locals.
fn scope_node(node: Node<'_>) -> bool {
    matches!(node.kind(), "block" | "do_block" | "lambda")
}

/// The statements a block, lambda or method scope executes.
fn scope_body(scope: Node<'_>) -> Option<Node<'_>> {
    let body = scope.child_by_field_name("body")?;
    if scope.kind() == "lambda" {
        body.child_by_field_name("body")
    } else {
        Some(body)
    }
}

/// Names a scope binds through its parameters, including `|; locals|`.
fn parameter_names(scope: Node<'_>, source: &str) -> BTreeSet<String> {
    scope
        .child_by_field_name("parameters")
        .map(binding_nodes)
        .unwrap_or_default()
        .iter()
        .map(|name| text(*name, source).to_owned())
        .collect()
}

/// Immutable literals whose token text is the value.
fn scalar_literal(node: Node<'_>) -> bool {
    matches!(
        node.kind(),
        "integer" | "float" | "simple_symbol" | "true" | "false" | "nil"
    )
}

/// Decoded text of a string literal without interpolation.
fn string_literal(node: Node<'_>, source: &str) -> Option<String> {
    (node.kind() == "string"
        && !descendants(node)
            .iter()
            .any(|part| part.kind() == "interpolation"))
    .then(|| literal_string(text(node, source)))
    .flatten()
}

/// A `->`, `lambda` or `proc` literal; the returned node owns the whole callable syntax.
pub(super) fn callable_literal<'a>(node: Node<'a>, source: &str) -> Option<Node<'a>> {
    if node.kind() == "lambda" {
        return Some(node);
    }
    (node.kind() == "call"
        && node.child_by_field_name("receiver").is_none()
        && node.child_by_field_name("arguments").is_none()
        && node.child_by_field_name("block").is_some()
        && node
            .child_by_field_name("method")
            .is_some_and(|method| matches!(text(method, source), "lambda" | "proc")))
    .then_some(node)
}

/// Whether a lambda literal declares parameters; their values are never substituted.
pub(super) fn callable_parameterized(callable: Node<'_>) -> bool {
    let owner = if callable.kind() == "lambda" {
        Some(callable)
    } else {
        callable.child_by_field_name("block")
    };
    owner.is_some_and(|owner| {
        owner
            .child_by_field_name("parameters")
            .is_some_and(|parameters| parameters.named_child_count() != 0)
    })
}

/// Named children in source order.
pub(super) fn named_children(node: Node<'_>) -> Vec<Node<'_>> {
    let mut cursor = node.walk();
    node.named_children(&mut cursor).collect()
}

/// Named children that carry syntax; comments are extras and never count.
pub(super) fn semantic_children(node: Node<'_>) -> Vec<Node<'_>> {
    named_children(node)
        .into_iter()
        .filter(|child| !child.is_extra())
        .collect()
}

/// Unwraps transparent parentheses around a single expression.
pub(super) fn unparenthesized(mut node: Node<'_>) -> Node<'_> {
    while node.kind() == "parenthesized_statements" {
        match semantic_children(node).as_slice() {
            [inner] => node = *inner,
            _ => break,
        }
    }
    node
}

/// Declared callable literals by node id; their bodies are syntax until an invocation expands them.
pub(super) fn declared_callables<'a>(
    block: Node<'a>,
    bindings: &Bindings,
) -> BTreeMap<usize, Node<'a>> {
    descendants(block)
        .into_iter()
        .filter(|node| bindings.elided.contains(&node.id()))
        .map(|node| (node.id(), node))
        .collect()
}

/// Statements of the declaration a proven invocation runs, one level deep.
pub(super) fn expansion_statements<'a>(
    bindings: &Bindings,
    declared: &BTreeMap<usize, Node<'a>>,
    call: Node<'a>,
    expanded: bool,
) -> Option<Vec<Node<'a>>> {
    bindings
        .expansions
        .get(&call.id())
        .filter(|_| !expanded)
        .and_then(|callable| declared.get(callable).copied())
        .and_then(callable_body)
        .map(named_children)
}

/// The statements a declared callable runs when invoked.
pub(super) fn callable_body(callable: Node<'_>) -> Option<Node<'_>> {
    if callable.kind() == "lambda" {
        scope_body(callable)
    } else {
        callable
            .child_by_field_name("block")
            .and_then(|block| block.child_by_field_name("body"))
    }
}

/// The block, lambda or method that directly owns a node.
fn nearest_scope(node: Node<'_>) -> Option<Node<'_>> {
    std::iter::successors(node.parent(), |node| node.parent())
        .find(|node| scope_node(*node) || WALLS.contains(&node.kind()))
}

/// A `.call(...)` or `.()` dispatch on the binding, through transparent parentheses.
fn invocation<'a>(read: Node<'a>, source: &str) -> Option<(Node<'a>, usize)> {
    let mut value = read;
    while let Some(parent) = value.parent().filter(|node| {
        node.kind() == "parenthesized_statements" && semantic_children(*node).len() == 1
    }) {
        value = parent;
    }
    let call = value.parent().filter(|call| {
        call.kind() == "call"
            && call.child_by_field_name("receiver") == Some(value)
            && call.child_by_field_name("block").is_none()
            && call
                .child_by_field_name("method")
                .is_none_or(|method| text(method, source) == "call")
    })?;
    let arity = call
        .child_by_field_name("arguments")
        .map_or(0, |arguments| {
            let mut cursor = arguments.walk();
            arguments
                .named_children(&mut cursor)
                .filter(|node| !node.is_extra())
                .count()
        });
    Some((call, arity))
}

/// Whether the leading comment block enables `frozen_string_literal`.
fn frozen_string_literals(root: Node<'_>, source: &str) -> bool {
    let mut cursor = root.walk();
    let leading: Vec<_> = root
        .children(&mut cursor)
        .take_while(|node| node.kind() == "comment")
        .collect();
    leading.iter().any(|comment| {
        let body = text(*comment, source).trim_start_matches('#').trim();
        body.strip_prefix("frozen_string_literal:")
            .is_some_and(|value| value.trim().eq_ignore_ascii_case("true"))
    })
}

/// Values of constants assigned exactly once at program level with an immutable literal.
fn file_constants(root: Node<'_>, source: &str) -> BTreeMap<String, String> {
    let nodes = descendants(root);
    if nodes.iter().any(|node| {
        node.kind() == "call"
            && node.child_by_field_name("method").is_some_and(|method| {
                matches!(
                    text(method, source),
                    "const_set" | "remove_const" | "const_missing"
                )
            })
    }) {
        return BTreeMap::new();
    }
    let frozen = frozen_string_literals(root, source);
    let mut writes = BTreeMap::<String, Vec<Node<'_>>>::new();
    for node in &nodes {
        if !matches!(node.kind(), "assignment" | "operator_assignment") {
            continue;
        }
        // Every assignment has a target; a bare constant is the write itself, anything else
        // (qualified or destructured) poisons each constant it names.
        let targets = node
            .child_by_field_name("left")
            .into_iter()
            .flat_map(|left| {
                if left.kind() == "constant" {
                    vec![left]
                } else {
                    descendants(left)
                        .into_iter()
                        .filter(|part| part.kind() == "constant")
                        .collect()
                }
            });
        for target in targets {
            writes
                .entry(text(target, source).to_owned())
                .or_default()
                .push(*node);
        }
    }
    writes
        .into_iter()
        .filter_map(|(name, writes)| {
            let [write] = writes.as_slice() else {
                return None;
            };
            if write.kind() != "assignment"
                || write.parent() != Some(root)
                || write
                    .child_by_field_name("left")
                    .is_none_or(|left| left.kind() != "constant")
            {
                return None;
            }
            constant_value(write.child_by_field_name("right")?, source, frozen)
                .map(|value| (name, value))
        })
        .collect()
}

/// Fingerprint value of an immutable constant initializer; strings need `.freeze` or the pragma.
fn constant_value(right: Node<'_>, source: &str, frozen: bool) -> Option<String> {
    if scalar_literal(right) {
        return Some(format!("const:{}:{}", right.kind(), text(right, source)));
    }
    let string = if right.kind() == "string" {
        frozen.then(|| string_literal(right, source)).flatten()
    } else {
        (right.kind() == "call"
            && right.child_by_field_name("arguments").is_none()
            && right.child_by_field_name("block").is_none()
            && right
                .child_by_field_name("method")
                .is_some_and(|method| text(method, source) == "freeze"))
        .then(|| string_literal(right.child_by_field_name("receiver")?, source))
        .flatten()
    };
    string.map(|value| format!("const:string:{value}"))
}

/// Whether a constant node reads a value rather than naming a method, scope or target.
fn constant_read(node: Node<'_>) -> bool {
    node.parent().is_none_or(|parent| {
        !(matches!(
            parent.kind(),
            "scope_resolution" | "class" | "module" | "singleton_class"
        ) || (parent.kind() == "call" && parent.child_by_field_name("method") == Some(node))
            || (matches!(parent.kind(), "assignment" | "operator_assignment")
                && parent.child_by_field_name("left") == Some(node)))
    })
}

/// Syntax that binds locals without an assignment and is not modelled: `for` and pattern
/// variables, `rescue => e`, and a regex literal with a named group on the left of `=~`.
/// A bare `rescue`, a regex on the right, an interpolated regex or a regex held in a variable
/// binds nothing (ruby 4.0: `"a" =~ /(?<y>a)/; y` is a NameError).
fn binds_locals(node: Node<'_>, source: &str) -> bool {
    match node.kind() {
        "for" | "in_clause" | "match_pattern" | "test_pattern" => true,
        "rescue" => node.child_by_field_name("variable").is_some(),
        "binary" => {
            node.child_by_field_name("operator")
                .is_some_and(|n| text(n, source) == "=~")
                && node.child_by_field_name("left").is_some_and(|left| {
                    left.kind() == "regex"
                        && !descendants(left)
                            .iter()
                            .any(|part| part.kind() == "interpolation")
                        && named_group(text(left, source))
                })
        }
        _ => false, // fail-closed: assignments are tracked separately; no other syntax binds a local
    }
}

/// `(?<name>...)` or `(?'name'...)` as live regex syntax; escaped text, character classes,
/// and lookbehind `(?<=`/`(?<!` bind nothing.
fn named_group(pattern: &str) -> bool {
    let chars: Vec<char> = pattern.chars().collect();
    let mut index = 0;
    let mut in_class = false;
    while index < chars.len() {
        match chars[index] {
            '\\' => index += 1,
            '[' => in_class = true,
            ']' => in_class = false,
            '(' if !in_class && chars.get(index + 1) == Some(&'?') => {
                let opener = chars.get(index + 2);
                if opener == Some(&'\'')
                    || (opener == Some(&'<')
                        && chars
                            .get(index + 3)
                            .is_some_and(|c| c.is_ascii_alphabetic() || *c == '_'))
                {
                    return true;
                }
            }
            _ => {} // fail-closed: only an unescaped `(?` outside a class can open a named group
        }
        index += 1;
    }
    false
}

/// Locals assigned in `scope` before `before`, outside nested scopes; flags unresolved syntax.
fn locals_before(
    scope: Node<'_>,
    before: Node<'_>,
    source: &str,
    uncertain: &mut bool,
) -> BTreeSet<String> {
    let locals = RootLocals::walk(scope, before.start_byte(), source);
    *uncertain |= locals.first_uncertain.is_some();
    locals
        .assignments
        .into_iter()
        .flat_map(|(_, names)| names)
        .collect()
}

/// File-level binding facts shared by every handler in one parsed file, computed on first use.
///
/// Recomputing them per handler made extraction quadratic in the number of handlers per file.
pub(super) struct RootScope<'a> {
    root: Node<'a>,
    source: &'a str,
    constants: OnceCell<BTreeMap<String, String>>,
    locals: OnceCell<RootLocals>,
}

/// Program-level assignments and local-binding syntax in source order, outside nested scopes.
struct RootLocals {
    /// Start byte and target names of each program-level assignment.
    assignments: Vec<(usize, Vec<String>)>,
    /// Start byte of the first program-level node that binds locals without an assignment.
    first_uncertain: Option<usize>,
}

impl<'a> RootScope<'a> {
    /// Wraps the `program` root of `source`; nothing is computed until a handler asks.
    pub(super) fn new(root: Node<'a>, source: &'a str) -> Self {
        Self {
            root,
            source,
            constants: OnceCell::new(),
            locals: OnceCell::new(),
        }
    }

    /// The file's constants, as `file_constants` computes them.
    fn constants(&self) -> &BTreeMap<String, String> {
        self.constants
            .get_or_init(|| file_constants(self.root, self.source))
    }

    /// Program-level locals assigned before `before`, equal to `locals_before(root, before)`.
    ///
    /// That walk visits exactly the nodes reachable from the root without entering a block,
    /// lambda or wall that start before `before`, and whether a node is entered depends only on
    /// its kind; so the visit set is one source-ordered list cut at `before`.
    fn locals_before(&self, before: Node<'_>, uncertain: &mut bool) -> BTreeSet<String> {
        let locals = self
            .locals
            .get_or_init(|| RootLocals::walk(self.root, usize::MAX, self.source));
        let limit = before.start_byte();
        *uncertain |= locals.first_uncertain.is_some_and(|start| start < limit);
        locals
            .assignments
            .iter()
            .take_while(|(start, _)| *start < limit)
            .flat_map(|(_, names)| names.iter().cloned())
            .collect()
    }
}

impl RootLocals {
    /// Walks `scope` without entering nested scopes or walls, skipping nodes at or after `limit`.
    fn walk(scope: Node<'_>, limit: usize, source: &str) -> Self {
        let mut assignments = Vec::new();
        let mut first_uncertain = None::<usize>;
        let mut pending = vec![scope];
        while let Some(node) = pending.pop() {
            if node.start_byte() >= limit
                || (node != scope && (scope_node(node) || WALLS.contains(&node.kind())))
            {
                continue;
            }
            if binds_locals(node, source) {
                first_uncertain = Some(
                    first_uncertain.map_or(node.start_byte(), |start| start.min(node.start_byte())),
                );
            }
            match node.kind() {
                "assignment" | "operator_assignment" => assignments.push((
                    node.start_byte(),
                    node.child_by_field_name("left")
                        .map(binding_nodes)
                        .unwrap_or_default()
                        .iter()
                        .map(|name| text(*name, source).to_owned())
                        .collect(),
                )),
                _ => {} // fail-closed: binding syntax without an assignment is reported by binds_locals
            }
            let mut cursor = node.walk();
            pending.extend(node.named_children(&mut cursor));
        }
        assignments.sort_by_key(|(start, _)| *start);
        Self {
            assignments,
            first_uncertain,
        }
    }
}

impl Bindings {
    /// Tracks parser-order bindings while keeping unresolved reflection and implicit parameters uncertain.
    pub fn collect(block: Node<'_>, scope: &RootScope<'_>, source: &str) -> Self {
        Self::collect_with_origins(block, scope, source, &BTreeMap::new(), &BTreeSet::new())
    }

    /// Resolves handler bindings with source-proven captures and lexical shadowing.
    pub(super) fn collect_with_origins(
        block: Node<'_>,
        file: &RootScope<'_>,
        source: &str,
        captures: &BTreeMap<String, String>,
        dispatch: &BTreeSet<(usize, usize)>,
    ) -> Self {
        let mut result = Self::default();
        // Ruby def opens a new local scope; it does not close over the file's locals.
        let closure = block.kind() != "method";
        let outer = if closure {
            file.locals_before(block, &mut result.uncertain)
        } else {
            BTreeSet::new()
        };
        // Enclosing block and lambda scopes up to the nearest scope wall; a lambda's own body
        // block is folded into the lambda.
        let enclosing: Vec<_> = std::iter::successors(block.parent(), |node| node.parent())
            .take(if closure { usize::MAX } else { 0 })
            .take_while(|node| !WALLS.contains(&node.kind()))
            .filter(|node| {
                scope_node(*node)
                    && !node
                        .parent()
                        .is_some_and(|parent| parent.kind() == "lambda")
            })
            .collect();
        // Fingerprinted blocks are top-level or inside executed lambdas, so constant lookup
        // never crosses a class or module body; `def` handlers keep names.
        let constants = if closure {
            file.constants().clone()
        } else {
            BTreeMap::new()
        };
        let mut scopes = vec![outer
            .into_iter()
            .map(|name| (name.clone(), format!("capture:{name}")))
            .collect::<BTreeMap<_, _>>()];
        let mut enclosing_scopes = Vec::new();
        for scope in enclosing.iter().rev() {
            // An assignment creates a scope-local only when no outer local already owns the
            // name; parameters and block-locals rebind it regardless.
            let visible: BTreeSet<_> = scopes.iter().flat_map(BTreeMap::keys).cloned().collect();
            let parameters = parameter_names(*scope, source);
            let mut names = parameters.clone();
            // The handler sits inside this scope, so the scope has a body.
            names.extend(
                scope_body(*scope)
                    .map_or_else(BTreeSet::new, |body| {
                        locals_before(body, block, source, &mut result.uncertain)
                    })
                    .into_iter()
                    .filter(|name| !visible.contains(name)),
            );
            scopes.push(
                names
                    .iter()
                    .map(|name| (name.clone(), format!("scope:{}:{name}", scope.start_byte())))
                    .collect(),
            );
            enclosing_scopes.push((*scope, parameters));
        }
        let mut writes = BTreeMap::<String, Vec<Node<'_>>>::new();
        let mut reads = BTreeMap::<String, Vec<Node<'_>>>::new();
        let mut next = 0;
        let mut pending = vec![(block, false)];
        while let Some((node, closing)) = pending.pop() {
            let scope = scope_node(node) || (node == block && node.kind() == "method");
            if closing {
                if scope {
                    scopes.pop();
                }
                continue;
            }
            if scope {
                scopes.push(BTreeMap::new());
                if let Some(parameters) = node.child_by_field_name("parameters") {
                    for name in binding_nodes(parameters) {
                        let key = format!("local:{next}");
                        next += 1;
                        scopes
                            .last_mut()
                            .unwrap()
                            .insert(text(name, source).to_owned(), key.clone());
                        result.names.insert(name.id(), key);
                    }
                }
            }
            if binds_locals(node, source)
                || (node.kind() == "pair" && node.child_by_field_name("value").is_none())
            {
                result.uncertain = true;
            }
            if matches!(node.kind(), "assignment" | "operator_assignment") {
                if let Some(left) = node.child_by_field_name("left") {
                    for name in binding_nodes(left) {
                        let spelling = text(name, source);
                        let key = scopes
                            .iter()
                            .rev()
                            .find_map(|s| s.get(spelling))
                            .cloned()
                            .unwrap_or_else(|| {
                                let key = format!("local:{next}");
                                next += 1;
                                scopes
                                    .last_mut()
                                    .unwrap()
                                    .insert(spelling.to_owned(), key.clone());
                                key
                            });
                        writes.entry(key.clone()).or_default().push(node);
                        result.names.insert(name.id(), key);
                    }
                }
            }
            if node.kind() == "constant" && constant_read(node) {
                if let Some(value) = constants.get(text(node, source)) {
                    result.names.insert(node.id(), value.clone());
                }
            }
            if node.kind() == "identifier" {
                let spelling = text(node, source);
                let method = node.parent().is_some_and(|p| {
                    p.kind() == "call" && p.child_by_field_name("method") == Some(node)
                });
                if !method {
                    if let Some(key) = scopes.iter().rev().find_map(|s| s.get(spelling)) {
                        if !result.names.contains_key(&node.id()) {
                            reads.entry(key.clone()).or_default().push(node);
                        }
                        result.names.insert(node.id(), key.clone());
                        if let Some(name) = key.strip_prefix("capture:") {
                            result.captures.insert(name.to_owned());
                            // A resolved alias keeps its spelling and adds its owner, so two
                            // files binding one name to different providers stay distinct.
                            match captures.get(name) {
                                Some(owner) => {
                                    result.captures.insert(owner.clone());
                                }
                                None => result.lexical = true,
                            }
                        } else if key.starts_with("scope:") {
                            result.captures.insert(key.clone());
                            result.lexical = true;
                        }
                    } else {
                        result.calls.insert(node.id());
                    }
                }
                if (method || result.calls.contains(&node.id()))
                    && !node.parent().is_some_and(|call| {
                        dispatch.contains(&(call.start_byte(), call.end_byte()))
                    })
                    && matches!(
                        spelling,
                        "caller"
                            | "caller_locations"
                            | "source_location"
                            | "binding"
                            | "eval"
                            | "local_variables"
                            | "local_variable_get"
                            | "local_variable_set"
                            | "method"
                            | "public_method"
                            | "send"
                            | "public_send"
                            | "__send__"
                            | "instance_eval"
                    )
                {
                    result.uncertain = true;
                }
                if spelling
                    .strip_prefix('_')
                    .is_some_and(|n| n.parse::<u8>().is_ok_and(|n| (1..=9).contains(&n)))
                {
                    result.uncertain = true;
                }
                if spelling == "it" && result.calls.contains(&node.id()) {
                    result.uncertain = true;
                }
                if matches!(spelling, "__FILE__" | "__dir__") {
                    result.captures.insert("<source-file>".to_owned());
                    result.lexical = true;
                }
            }
            pending.push((node, true));
            let mut cursor = node.walk();
            let mut children: Vec<_> = node.named_children(&mut cursor).collect();
            // Ruby's lexical declarations follow source order, even for modifier expressions.
            children.sort_by_key(Node::start_byte);
            pending.extend(children.into_iter().rev().map(|n| (n, false)));
        }
        let unresolved = result
            .captures
            .iter()
            .filter(|name| {
                !name.starts_with("scope:")
                    && !name.starts_with("ruby:callable:")
                    && !captures.contains_key(*name)
            })
            .cloned()
            .collect();
        result.uncertain |=
            !stable_captures(block, file.root, source, &unresolved, &BTreeSet::new());
        for (scope, parameters) in enclosing_scopes {
            let prefix = format!("scope:{}:", scope.start_byte());
            let names = result
                .captures
                .iter()
                .filter_map(|name| name.strip_prefix(prefix.as_str()))
                .map(str::to_owned)
                .collect();
            result.uncertain |= !stable_captures(block, scope, source, &names, &parameters);
        }
        result.declare_callables(block, source, &writes, &reads);
        result
    }

    /// Classifies handler locals holding lambda literals; unmodeled uses keep deferred identity.
    fn declare_callables(
        &mut self,
        block: Node<'_>,
        source: &str,
        writes: &BTreeMap<String, Vec<Node<'_>>>,
        reads: &BTreeMap<String, Vec<Node<'_>>>,
    ) {
        for (key, writes) in writes {
            if !key.starts_with("local:") {
                continue;
            }
            // Only a plain `name = <lambda>` write declares a callable; destructuring and
            // operator assignment keep the binding's existing deferred identity.
            let Some(callables) = writes
                .iter()
                .map(|write| {
                    (write.kind() == "assignment"
                        && write
                            .child_by_field_name("left")
                            .is_some_and(|left| left.kind() == "identifier"))
                    .then(|| write.child_by_field_name("right"))
                    .flatten()
                    .and_then(|right| callable_literal(right, source))
                })
                .collect::<Option<Vec<_>>>()
            else {
                continue;
            };
            let Some(invocations) = reads
                .get(key)
                .map(|reads| {
                    reads
                        .iter()
                        .map(|read| invocation(*read, source))
                        .collect::<Option<Vec<_>>>()
                })
                .unwrap_or_else(|| Some(Vec::new()))
            else {
                continue;
            };
            let parameterized = callables
                .iter()
                .any(|callable| callable_parameterized(*callable));
            if callables
                .iter()
                .any(|callable| callable_parameterized(*callable) != parameterized)
                || invocations
                    .iter()
                    .any(|(_, arity)| (*arity != 0) != parameterized)
            {
                continue;
            }
            self.elided.extend(callables.iter().map(Node::id));
            if parameterized {
                self.unresolved_invocations
                    .extend(invocations.iter().map(|(call, _)| call.id()));
                continue;
            }
            // One declaration owned by the handler scope runs at every later invocation, in
            // any expression position; inside a nested block the expansion is deferred.
            // Declarations inside nested scopes and reassigned declarations stay syntax.
            if let ([write], [callable]) = (writes.as_slice(), callables.as_slice()) {
                if nearest_scope(*write) == Some(block) {
                    for (call, _) in invocations {
                        if call.start_byte() >= write.end_byte() {
                            self.expansions.insert(call.id(), callable.id());
                        }
                    }
                }
            }
        }
    }
}

/// Lexical identity alone cannot close mutable factories, property aliases or escaped values.
///
/// `scope` is the program or an enclosing block whose body initializes the captures;
/// `parameters` are the scope's own parameters, stable without a write.
fn stable_captures(
    handler: Node<'_>,
    scope: Node<'_>,
    source: &str,
    captures: &BTreeSet<String>,
    parameters: &BTreeSet<String>,
) -> bool {
    if captures.is_empty() {
        return true;
    }
    let body = if scope.kind() == "program" {
        Some(scope)
    } else {
        scope_body(scope)
    };
    let mut initialized = BTreeSet::new();
    let mut immutable = BTreeSet::new();
    let mut reads = BTreeSet::new();
    let mut unsafe_names = BTreeSet::new();
    let mut shadows: Vec<BTreeSet<String>> = Vec::new();
    let mut pending = vec![(scope, false)];
    while let Some((node, closing)) = pending.pop() {
        if closing {
            shadows.pop();
            continue;
        }
        if node != scope {
            if WALLS.contains(&node.kind()) {
                continue;
            }
            if scope_node(node) {
                let rebound = parameter_names(node, source);
                let deferred = node == handler
                    || node.parent().is_some_and(|parent| {
                        parent.kind() == "call"
                            && parent
                                .child_by_field_name("method")
                                .is_some_and(|name| super::registration(text(name, source)))
                    });
                if deferred {
                    shadows.push(rebound);
                    deferred_writes(node, source, captures, &mut shadows, &mut unsafe_names);
                    shadows.pop();
                    continue;
                }
                shadows.push(rebound);
                pending.push((node, true));
            }
        }
        if node.kind() == "identifier"
            && captures.contains(text(node, source))
            && !shadows
                .iter()
                .any(|names| names.contains(text(node, source)))
        {
            let name = text(node, source);
            let assignment = node.parent().filter(|n| {
                n.kind() == "assignment"
                    && n.parent() == body
                    && n.child_by_field_name("left") == Some(node)
            });
            let right = assignment.and_then(|n| n.child_by_field_name("right"));
            let literal = right.is_some_and(|n| {
                scalar_literal(n)
                    || string_literal(n, source).is_some()
                    || callable_literal(n, source).is_some()
            });
            if assignment.is_some() {
                if right.is_some_and(|n| n.kind() != "string") {
                    immutable.insert(name.to_owned());
                }
                if !literal || !initialized.insert(name.to_owned()) {
                    unsafe_names.insert(name.to_owned());
                }
            } else if node.parent().is_some_and(|parent| {
                matches!(parent.kind(), "assignment" | "operator_assignment")
                    && parent.child_by_field_name("left") == Some(node)
            }) {
                unsafe_names.insert(name.to_owned());
            } else {
                reads.insert(name.to_owned());
            }
        }
        let mut cursor = node.walk();
        pending.extend(node.named_children(&mut cursor).map(|child| (child, false)));
    }
    captures.iter().all(|name| {
        name == "<source-file>"
            || (!unsafe_names.contains(name)
                && if initialized.contains(name) {
                    !reads.contains(name) || immutable.contains(name)
                } else {
                    parameters.contains(name)
                })
    })
}

/// Writes inside a deferred body reach a capture unless a nearer scope rebinds the name.
fn deferred_writes(
    body: Node<'_>,
    source: &str,
    captures: &BTreeSet<String>,
    shadows: &mut Vec<BTreeSet<String>>,
    unsafe_names: &mut BTreeSet<String>,
) {
    let mut pending = vec![(body, false)];
    while let Some((node, closing)) = pending.pop() {
        if closing {
            shadows.pop();
            continue;
        }
        if node != body {
            if WALLS.contains(&node.kind()) {
                continue;
            }
            if scope_node(node) {
                shadows.push(parameter_names(node, source));
                pending.push((node, true));
            }
        }
        if matches!(node.kind(), "assignment" | "operator_assignment") {
            unsafe_names.extend(
                node.child_by_field_name("left")
                    .map(binding_nodes)
                    .unwrap_or_default()
                    .iter()
                    .map(|n| text(*n, source).to_owned())
                    .filter(|name| {
                        captures.contains(name) && !shadows.iter().any(|names| names.contains(name))
                    }),
            );
        }
        let mut cursor = node.walk();
        pending.extend(node.named_children(&mut cursor).map(|child| (child, false)));
    }
}

/// Collects binding targets without renaming property receivers, keys, or method names.
fn binding_nodes(node: Node<'_>) -> Vec<Node<'_>> {
    let mut names = Vec::new();
    let mut pending = vec![node];
    while let Some(node) = pending.pop() {
        match node.kind() {
            "identifier" => names.push(node),
            "left_assignment_list"
            | "destructured_left_assignment"
            | "rest_assignment"
            | "block_parameters"
            | "lambda_parameters"
            | "method_parameters"
            | "destructured_parameter" => {
                let mut cursor = node.walk();
                pending.extend(node.named_children(&mut cursor));
            }
            "block_parameter" | "splat_parameter" | "hash_splat_parameter" => {
                pending.extend(node.child_by_field_name("name"));
            }
            _ => {}
        }
    }
    names.sort_by_key(Node::start_byte);
    names
}

#[cfg(test)]
mod tests {
    use super::super::load_phase::tests::parse;
    use super::*;

    /// Asserts the per-file index answers every handler-shaped node exactly as the root walk does.
    fn assert_index_matches_walk(source: &str, label: &str) -> usize {
        let tree = parse(source);
        let root = tree.root_node();
        let scope = RootScope::new(root, source);
        let mut checked = 0;
        for node in descendants(root) {
            if !matches!(node.kind(), "block" | "do_block" | "lambda" | "method") {
                continue;
            }
            let (mut indexed, mut walked) = (false, false);
            assert_eq!(
                scope.locals_before(node, &mut indexed),
                locals_before(root, node, source, &mut walked),
                "{label}: names"
            );
            assert_eq!(indexed, walked, "{label}: uncertain");
            checked += 1;
        }
        assert_eq!(
            scope.constants(),
            &file_constants(root, source),
            "{label}: constants"
        );
        checked
    }

    /// The index equals the walk for every assignment form, nested scope, enclosing block and
    /// local-binding syntax, before and after each handler.
    #[test]
    fn root_index_matches_the_walk_on_the_matrix() {
        let source = r#"
LIMIT = 5
first, *rest = [1, 2, 3]
total = 0
total += 1
Given('first') { work(total) }
if ready
  inside_if = 1
end
begin
  inside_begin = 2
rescue => error
  handled = error
end
def helper
  hidden_in_def = 3
end
class Holder
  hidden_in_class = 4
end
module Space
  hidden_in_module = 5
end
class << self
  hidden_in_singleton = 6
end
[1].each { |item| hidden_in_block = item }
3.times do |index|
  inside_loop = index
  Given("loop #{index}") { work(inside_loop) }
end
callable = -> { hidden_in_lambda = 7 }
When('middle') do
  work(callable, inside_if)
end
for element in [1]
  looped = element
end
case value
in { name: }
  matched = name
end
/(?<group>x)/ =~ text
after = 8
Then('last') { work(after) }
def step_method
  Given('in method') { work }
end
"#;
        assert!(assert_index_matches_walk(source, "matrix") >= 10);
    }

    /// The index equals the walk for every handler-shaped node in every Ruby fixture.
    #[test]
    fn root_index_matches_the_walk_on_every_ruby_fixture() {
        let mut files = Vec::new();
        let mut pending =
            vec![std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fixtures")];
        while let Some(directory) = pending.pop() {
            for entry in std::fs::read_dir(directory).unwrap() {
                let path = entry.unwrap().path();
                if path.is_dir() {
                    pending.push(path);
                } else if path.extension().is_some_and(|extension| extension == "rb") {
                    files.push(path);
                }
            }
        }
        files.sort();
        assert!(files.len() > 100, "Ruby fixtures not found");
        let checked: usize = files
            .iter()
            .map(|path| {
                let source = std::fs::read_to_string(path).unwrap();
                assert_index_matches_walk(&source, &path.display().to_string())
            })
            .sum();
        assert!(checked > 100);
    }
}