cuke-dedup 0.14.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
use super::regex_expression;

/// Verify Ruby fingerprints retain value and callee differences while normalizing superficial formatting and local renames.
#[test]
fn handler_fingerprints_preserve_superficial_value_and_callee_boundaries() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let file = SourceFile {
        path: "steps.rb".into(),
        language: SourceLanguage::Ruby,
    };
    let extract = |source: &str| {
        super::RUBY_ADAPTER
            .extract(source, &file)
            .unwrap()
            .definitions
    };

    let definitions = extract(
        "Given('commented') { # note\n work() }\nGiven('plain') { work() }\nGiven('delimited') do work() end",
    );
    assert!(definitions
        .iter()
        .all(|definition| definition.handler.exact.len() == definition.handler.normalized.len()));
    assert_ne!(definitions[0].handler.exact, definitions[1].handler.exact);
    assert_eq!(
        definitions[0].handler.normalized,
        definitions[1].handler.normalized
    );
    assert_ne!(definitions[1].handler.exact, definitions[2].handler.exact);
    assert_eq!(
        definitions[1].handler.normalized,
        definitions[2].handler.normalized
    );

    let renamed =
        extract("Given('first') { |z, a| z.goto(a) }\nGiven('second') { |b, y| b.goto(y) }");
    assert_eq!(
        renamed[0].handler.alpha_normalized,
        renamed[1].handler.alpha_normalized
    );
    assert_eq!(
        renamed[0].handler.behavior_signature,
        renamed[1].handler.behavior_signature
    );

    let literals = extract(
        "Given('save') { page.locator('#save') }\nGiven('saves') { page.locator('#saves') }",
    );
    assert_ne!(
        literals[0].handler.alpha_normalized,
        literals[1].handler.alpha_normalized
    );
    assert_eq!(
        literals[0].handler.structural,
        literals[1].handler.structural
    );

    let calls = extract(
        "Given('direct') { page.click('#save') }\nGiven('fluent') { page.locator('#save').click }\nGiven('factory') { browser().click('#save') }\nGiven('callback') { |perform| perform.call }",
    );
    for (definition, expected) in calls.iter().zip([
        "page.#click",
        "page.#click",
        "browser.#click",
        "local:0.#call",
    ]) {
        assert!(
            definition
                .handler
                .behavior_signature
                .iter()
                .any(|event| event.contains(expected)),
            "{expected}: {:?}",
            definition.handler.behavior_signature
        );
    }

    let structural = extract(
        "Given('strip') { 'value'.strip }\nGiven('upcase') { 'value'.upcase }\nGiven('user') { render(\"#{user.name}\") }\nGiven('order') { render(\"#{order.id}\") }",
    );
    assert_ne!(
        structural[0].handler.behavior_signature,
        structural[1].handler.behavior_signature
    );
    assert_ne!(
        structural[2].handler.structural,
        structural[3].handler.structural
    );

    let forged = extract(
        "Given('two') { combine('m', 'n') }\nGiven('one') { combine(\"m') }, (string n\") }",
    );
    assert_ne!(
        forged[0].handler.alpha_normalized,
        forged[1].handler.alpha_normalized
    );

    let long = format!("{{\r\n# {}\r\nwork()\r\n}}", "#\r\n界".repeat(900));
    for handler_source in ["{\r\n# note\r\nwork()\r\n}".to_owned(), long] {
        let source = format!("Given('work') {handler_source}");
        let definition = &extract(&source)[0];
        let legacy_snippet_bytes = handler_source
            .chars()
            .take(2_000)
            .map(char::len_utf8)
            .sum::<usize>();
        assert_eq!(
            definition.handler.exact.len() + definition.handler.source_snippet.len(),
            definition.handler.normalized.len() + legacy_snippet_bytes,
            "{handler_source:?}"
        );
    }
}

/// Verify safe local registration aliases preserve final findings while uncertain or escaping aliases gain no trust.
#[test]
fn local_registration_aliases_preserve_final_findings_without_granting_unknown_trust() {
    use crate::model::Rule;
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let dir = tempfile::tempdir().unwrap();
    let file = SourceFile {
        path: dir.path().join("steps.rb"),
        language: SourceLanguage::Ruby,
    };
    let config = crate::config::Config::load(dir.path(), Default::default()).unwrap();
    let direct = "Given('same') { first() }; Given('same') { second() }";
    for keyword in ["Given", "When", "Then", "And", "But"] {
        for (prefix, calls, definitions, complete, duplicate) in [
            ("", direct, 2, true, true),
            (
                "given = method(:Given);",
                "given.call('same') { first() }; given.call('same') { second() }",
                2,
                true,
                true,
            ),
            (
                "given = method('Given');",
                "given.call('same') { first() }; Given('same') { second() }",
                2,
                true,
                true,
            ),
            (
                "given = method(:Given); other = method(:Then);",
                "given.call('same') { first() }; other.call('same') { second() }",
                2,
                true,
                true,
            ),
            ("given = method(:Given);", direct, 2, true, true),
            (
                "given = method(:Given);",
                "given.call('alpha') { first() }; given.call('omega') { second() }",
                2,
                true,
                false,
            ),
            (
                "given = method(:Given); given = foreign;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); consume(given);",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); copy = given;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given.call('early') { first() }; given = method(:Given);",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); def nested(given); given.call('same') { first() }; end;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); if enabled; given.call('same') { first() }; end;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given);",
                "Given('same') { given.call('same') { first() } }",
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); given.call = replacement;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given); given ||= replacement;",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given);",
                "given.call('same') { eval(dynamic) }",
                1,
                false,
                false,
            ),
            (
                "given = ->(text, &handler) { :ignored };",
                "given.call('same') { first() }; given.call('same') { second() }",
                0,
                true,
                false,
            ),
            ("given = foreign.method(:Given);", direct, 0, false, false),
            ("given = method(:untrusted);", direct, 0, false, false),
            (
                "def method(name); foreign; end; given = method(:Given);",
                direct,
                0,
                false,
                false,
            ),
            (
                "class Method; def call(*args); :ignored; end; end; given = method(:Given);",
                direct,
                0,
                false,
                false,
            ),
            (
                "given = method(:Given);",
                "given.call(dynamic) { first() }",
                0,
                false,
                false,
            ),
            (
                "given = method(:Given);",
                "given.call('same', &handler)",
                0,
                false,
                false,
            ),
        ] {
            let source = format!("{prefix}\n{calls}").replace("Given", keyword);
            let extraction = super::RUBY_ADAPTER.extract(&source, &file).unwrap();
            assert_eq!(extraction.definitions.len(), definitions, "{source}");
            assert_eq!(
                extraction.diagnostics.is_empty(),
                complete,
                "{source}: {:?}",
                extraction.diagnostics
            );
            let result = crate::analysis::analyze_with_step_usage(
                extraction.definitions,
                vec![],
                &config,
                &extraction.indirect_usage.unwrap(),
            )
            .unwrap()
            .result;
            assert_eq!(
                result
                    .findings
                    .iter()
                    .any(|f| f.rule == Rule::DuplicateMatcher),
                duplicate,
                "{source}"
            );
            assert!(
                !result.findings.iter().any(|f| matches!(
                    f.rule,
                    Rule::DuplicateHandler | Rule::ParameterizationCandidate
                )),
                "{source}"
            );
        }
        let source = format!("given = method(:{keyword})\ngiven.call('alpha') {{ work() }}\ngiven.call('omega') {{ work() }}");
        let extraction = super::RUBY_ADAPTER.extract(&source, &file).unwrap();
        assert!(extraction.diagnostics.is_empty());
        assert_eq!(
            extraction
                .definitions
                .iter()
                .map(|d| (d.registration.as_str(), d.location.line))
                .collect::<Vec<_>>(),
            [(keyword, 2), (keyword, 3)]
        );
        let outcome = crate::analysis::analyze_with_step_usage(
            extraction.definitions,
            vec![],
            &config,
            &extraction.indirect_usage.unwrap(),
        )
        .unwrap();
        assert!(outcome.incomplete.is_empty());
        assert!(outcome
            .result
            .findings
            .iter()
            .any(|f| f.rule == Rule::DuplicateHandler));
    }
}

/// Verify unresolved dependencies expose unknown usage through direct adapter extraction without dropping local definitions.
#[test]
fn unresolved_dependency_usage_is_exposed_by_the_direct_adapter_api() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let extraction = super::RUBY_ADAPTER
        .extract(
            "require 'external/provider'; Given('local') { work() }",
            &SourceFile {
                path: "steps.rb".into(),
                language: SourceLanguage::Ruby,
            },
        )
        .unwrap();
    assert_eq!(extraction.definitions.len(), 1);
    assert!(extraction.indirect_usage.unwrap().unknown);
}

/// Verify Ruby regex translation retains line anchors and ASCII classes while rejecting unsupported flags and constructs.
#[test]
fn ruby_regex_subset_preserves_line_anchors_and_ascii_digits() {
    for (pattern, input, matches) in [
        ("^value$", "other\nvalue\nlast", true),
        (r"\Avalue\z", "other\nvalue\nlast", false),
        (r"\d+", "12", true),
        (r"\d+", "12", false),
        (r"value\/path", "value/path", true),
        (r"\A\w+\z", "alpha_19", true),
        (r"\A\w+\z", "日本", false),
        (r"\A\s\z", "\u{b}", true),
        (r"\A\s\z", "\u{c}", true),
        (r"\A\s\z", "\u{a0}", false),
    ] {
        let regex = regex::Regex::new(&regex_expression(pattern, "").unwrap()).unwrap();
        assert_eq!(regex.is_match(input), matches, "{pattern} {input}");
    }
    for (pattern, flags) in [
        ("a++a", ""),
        ("a*+a", ""),
        ("a?+a", ""),
        ("a{1,2}+a", ""),
        ("value.*", "i"),
        ("value", "x"),
        ("(?=value)", ""),
        ("(?<bad!>value)", ""),
        ("(", ""),
        ("[[:alpha:]]", ""),
        (r"(x)\1", ""),
    ] {
        assert!(
            regex_expression(pattern, flags).is_none(),
            "{pattern}/{flags}"
        );
    }
}

/// Verify public analysis rejects mixed Ruby and JavaScript definitions in either order.
#[test]
fn public_analysis_rejects_mixed_languages_in_either_order() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let dir = tempfile::tempdir().unwrap();
    let ruby = super::RUBY_ADAPTER
        .extract(
            "Given('same') { work() }",
            &SourceFile {
                path: dir.path().join("steps.rb"),
                language: SourceLanguage::Ruby,
            },
        )
        .unwrap()
        .definitions
        .remove(0);
    let js = crate::typescript::extract(
        "Given('same', () => work())",
        &SourceFile {
            path: dir.path().join("steps.js"),
            language: SourceLanguage::JavaScript,
        },
    )
    .unwrap()
    .remove(0);
    let config = crate::config::Config::load(dir.path(), Default::default()).unwrap();
    for pair in [vec![ruby.clone(), js.clone()], vec![js, ruby]] {
        let error = crate::analysis::analyze(pair, vec![], &config).unwrap_err();
        assert!(error.to_string().contains("separate analysis runs"));
    }
}

/// Verify escaped ASCII punctuation remains literal both inside and outside Ruby regex character classes.
#[test]
fn ruby_ascii_punctuation_identity_escapes_remain_literal() {
    for punctuation in (0x21_u8..=0x7e)
        .map(char::from)
        .filter(char::is_ascii_punctuation)
    {
        for pattern in [
            format!(r"\A\{punctuation}\z"),
            format!(r"\A[\{punctuation}]\z"),
        ] {
            let converted = regex_expression(&pattern, "").unwrap();
            let regex = regex::Regex::new(&converted).unwrap();
            assert!(
                regex.is_match(&punctuation.to_string()),
                "{pattern}: {converted}"
            );
            assert!(!regex.is_match("a"), "{pattern}: {converted}");
        }
    }
}

/// Verify unresolved owner effects report incompleteness even without neighboring registrations.
#[test]
fn unresolved_owner_effects_are_reported_without_adjacent_registrations() {
    use crate::source_adapter::{
        ExtractionDiagnosticKind, SourceAdapter, SourceFile, SourceLanguage,
    };
    for source in [
        "module Ghost::Helpers; end",
        "autoload :Loader, 'provider'",
        "def Given(x); :local; end",
    ] {
        let extraction = super::RUBY_ADAPTER
            .extract(
                source,
                &SourceFile {
                    path: "support.rb".into(),
                    language: SourceLanguage::Ruby,
                },
            )
            .unwrap();
        assert!(extraction.definitions.is_empty());
        assert!(
            extraction
                .diagnostics
                .iter()
                .any(|diagnostic| diagnostic.kind == ExtractionDiagnosticKind::Incomplete),
            "{source}: {:?}",
            extraction.diagnostics
        );
    }
}

/// Verify static parameter-type metadata is extracted without running transformers and built-in name collisions produce diagnostics.
#[test]
fn parameter_type_metadata_is_available_without_running_a_transformer() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let file = SourceFile {
        path: "support.rb".into(),
        language: SourceLanguage::Ruby,
    };
    for source in [
        "ParameterType(name: 'channel', regexp: /stdout/, transformer: ->(value) { value })",
        "ParameterType({:name => 'channel', :regexp => /stdout/, :transformer => proc { |value| value }})",
        "ParameterType( # explanation\n {name: 'channel', # comment\n regexp: [ /stdout/ # element\n ], transformer: ->(value) { value }})",
    ] {
        let extraction = super::RUBY_ADAPTER.extract(source, &file).unwrap();
        assert!(extraction.diagnostics.is_empty(), "{source}: {:?}", extraction.diagnostics);
        assert_eq!(extraction.parameter_types.len(), 1);
        assert_eq!(extraction.parameter_types[0].name.as_deref(), Some("channel"));
        let pattern = extraction.parameter_types[0].expression.as_ref().unwrap();
        let matcher = regex::Regex::new(pattern).unwrap();
        assert!(matcher.is_match("stdout"));
        assert!(!matcher.is_match("other"));
    }
    let extraction = super::RUBY_ADAPTER
        .extract(
            "ParameterType(name: 'int', regexp: /stdout/, transformer: ->(value) { value })",
            &file,
        )
        .unwrap();
    assert!(!extraction.diagnostics.is_empty());
}

/// Verify parameter-type regexps accept every `%r` delimiter through the shared literal splitter,
/// including a nested pair and an escaped delimiter, and that an unterminated literal is rejected.
#[test]
fn parameter_type_regexps_accept_percent_r_delimiters() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let file = SourceFile {
        path: "support.rb".into(),
        language: SourceLanguage::Ruby,
    };
    for (literal, hit, miss) in [
        ("%r!std(out)!", "stdout", "std"),
        ("%r(std(out))", "stdout", "std"),
        ("%r[std[o]ut]", "stdout", "stu"),
        ("%r<std<out>>", "std<out>", "stdout"),
        ("%r{std{1}}", "std", "stdd"),
        ("%r|std\\|out|", "std|out", "stdout"),
        ("%r-std\\-out-", "std-out", "stdout"),
    ] {
        let source = format!(
            "ParameterType(name: 'channel', regexp: {literal}, transformer: ->(value) {{ value }})"
        );
        let extraction = super::RUBY_ADAPTER.extract(&source, &file).unwrap();
        assert!(
            extraction.diagnostics.is_empty(),
            "{literal}: {:?}",
            extraction.diagnostics
        );
        let pattern = extraction.parameter_types[0].expression.as_ref().unwrap();
        let matcher = regex::Regex::new(&format!("^(?:{pattern})$")).unwrap();
        assert!(matcher.is_match(hit), "{literal} hit");
        assert!(!matcher.is_match(miss), "{literal} miss");
    }
    let unterminated =
        "ParameterType(name: 'channel', regexp: %r(std(out), transformer: ->(value) { value })";
    let extraction = super::RUBY_ADAPTER.extract(unterminated, &file).unwrap();
    assert!(!extraction.diagnostics.is_empty());
}

/// Ruby string literals decode only when complete and valid; truncated quotes and invalid escapes
/// yield no value.
#[test]
fn malformed_ruby_literal_boundaries_preserve_valid_values() {
    for (raw, expected) in [
        ("", None),
        ("'", None),
        ("\"", None),
        ("'value", None),
        ("''", Some("")),
        ("\"\"", Some("")),
        ("'value'", Some("value")),
        ("\"value\"", Some("value")),
        ("'日本'", Some("日本")),
        (r#""\u{1f600 41}""#, Some("😀A")),
        (r#""\u{}""#, Some("")),
        (r#""\u{ 41 }""#, Some("A")),
        (r#""\u0041""#, Some("A")),
        (r#""\uD800""#, None),
        (r#""\u{110000}""#, None),
        (r#""\u{0000041}""#, None),
        (r#""\u12""#, None),
        (r#""\u{41""#, None),
        ("\"\\u{41\n42}\"", None),
        ("\"a\\nb\"", Some("a\nb")),
    ] {
        assert_eq!(super::literal_string(raw).as_deref(), expected, "{raw:?}");
    }
}

/// Verify Ruby definitions and diagnostics each retain their source order.
#[test]
fn ruby_review_extraction_is_in_source_order() {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let extraction = super::RUBY_ADAPTER.extract(
        "Given('first') { work() }\nGiven(dynamic) { work() }\nThen('last') { finish() }\nThen(other) { finish() }",
        &SourceFile { path: "steps.rb".into(), language: SourceLanguage::Ruby },
    ).unwrap();
    assert_eq!(
        extraction
            .definitions
            .iter()
            .map(|d| d.location.line)
            .collect::<Vec<_>>(),
        [1, 3]
    );
    assert_eq!(
        extraction
            .diagnostics
            .iter()
            .map(|d| d.location.line)
            .collect::<Vec<_>>(),
        [2, 4]
    );
}

/// Whether `router.Given(arguments)`, with an optional brace block and trailing source lines, may
/// register, together with the tree-sitter kind of its first argument.
fn receiver_call(arguments: &str, block: bool, tail: &str) -> (bool, String) {
    let block = if block { " { }" } else { "" };
    let source = format!("router.Given({arguments}){block}\n{tail}");
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_ruby::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(&source, None).unwrap();
    let call = super::descendants(tree.root_node())
        .into_iter()
        .find(|node| {
            node.kind() == "call"
                && node
                    .child_by_field_name("method")
                    .is_some_and(|method| super::text(method, &source) == "Given")
        })
        .unwrap();
    let first = call
        .child_by_field_name("arguments")
        .and_then(|arguments| {
            super::bindings::semantic_children(arguments)
                .first()
                .copied()
        })
        .map_or_else(String::new, |node| node.kind().to_owned());
    (super::may_register(call, &source), first)
}

/// Every expression kind tree-sitter-ruby allows in an argument list is classified by the value
/// Ruby gives it. Each row states the kind its sample parses to and whether the call may register
/// as the first argument with a block, the second argument without one, and the second with one.
/// Rows with a fixed value class (pattern 100, handler 011, `nil`/`false` 001, other 000) were
/// checked against a cucumber-ruby registrar stub; unknown values (111) fail closed.
#[test]
fn receiver_registration_follows_the_value_of_every_argument_kind() {
    let rows: &[(&str, &str, &str, &str)] = &[
        ("string", "'a'", "", "100"),
        ("chained_string", "'a' 'b'", "", "100"),
        ("character", "?a", "", "100"),
        ("regex", "/a/", "", "100"),
        ("heredoc_beginning", "<<~T", "x\nT\n", "100"),
        ("heredoc_beginning", "<<~`T`", "ls\nT\n", "111"),
        ("identifier", "__FILE__", "", "100"),
        ("simple_symbol", ":a", "", "011"),
        ("delimited_symbol", ":\"a\"", "", "011"),
        ("lambda", "-> {}", "", "011"),
        ("method", "def m1; end", "", "011"),
        ("singleton_method", "def self.m2; end", "", "011"),
        ("nil", "nil", "", "001"),
        ("false", "false", "", "001"),
        ("test_pattern", "1 in String", "", "001"),
        ("true", "true", "", "000"),
        ("integer", "1", "", "000"),
        ("unary", "-1", "", "000"),
        ("unary", "+1.5", "", "000"),
        ("float", "1.5", "", "000"),
        ("rational", "1r", "", "000"),
        ("complex", "1i", "", "000"),
        ("array", "[1]", "", "000"),
        ("string_array", "%w[a]", "", "000"),
        ("symbol_array", "%i[a]", "", "000"),
        ("hash", "{}", "", "000"),
        ("range", "1..2", "", "000"),
        ("identifier", "__LINE__", "", "000"),
        ("identifier", "__ENCODING__", "", "000"),
        ("assignment", "y = :s", "", "011"),
        ("parenthesized_statements", "(1; :s)", "", "011"),
        ("parenthesized_statements", "()", "", "001"),
        // A jump is a void value expression Ruby rejects as an argument, so the file never loads;
        // tree-sitter parses it, and it stays unknown.
        ("break", "break", "", "111"),
        ("next", "next", "", "111"),
        ("redo", "redo", "", "111"),
        ("retry", "retry", "", "111"),
        ("return", "return", "", "111"),
        // Values only runtime decides.
        ("unary", "- 1", "", "111"),
        ("unary", "!x", "", "111"),
        ("unary", "defined?(x)", "", "111"),
        ("subshell", "`true`", "", "111"),
        ("identifier", "x", "", "111"),
        ("constant", "String", "", "111"),
        ("scope_resolution", "Object::String", "", "111"),
        ("self", "self", "", "111"),
        ("instance_variable", "@i", "", "111"),
        ("class_variable", "@@c", "", "111"),
        ("global_variable", "$g", "", "111"),
        ("call", "foo.to_s", "", "111"),
        ("element_reference", "a[0]", "", "111"),
        ("binary", "'a' + 'b'", "", "111"),
        ("operator_assignment", "x += 'b'", "", "111"),
        ("conditional", "true ? 'a' : 'b'", "", "111"),
        ("if", "if true then 'a' end", "", "111"),
        ("unless", "unless false then 'a' end", "", "111"),
        ("case", "case 1 when 1 then 'a' end", "", "111"),
        ("case_match", "case 1\nin 1 then 'a'\nend", "", "111"),
        ("while", "while false do end", "", "111"),
        ("until", "until true do end", "", "111"),
        ("for", "for i in [] do end", "", "111"),
        ("begin", "begin; 'a'; end", "", "111"),
        ("class", "class C1; 'a'; end", "", "111"),
        ("module", "module M1; 'a'; end", "", "111"),
        ("singleton_class", "class << self; 'a'; end", "", "111"),
        ("super", "super", "", "111"),
        ("yield", "yield", "", "111"),
        // `match_pattern` is reachable only in parentheses (bare `1 => q` is a hash pair) and is a
        // void value expression Ruby rejects as an argument; it stays unknown.
        ("parenthesized_statements", "(1 => q)", "", "111"),
    ];
    for (kind, expression, tail, expected) in rows {
        let (first, parsed) = receiver_call(expression, true, tail);
        let (second, _) = receiver_call(&format!("'x', {expression}"), false, tail);
        let (second_block, _) = receiver_call(&format!("'x', {expression}"), true, tail);
        assert_eq!(parsed, *kind, "{expression}");
        let actual: String = [first, second, second_block]
            .iter()
            .map(|registers| if *registers { '1' } else { '0' })
            .collect();
        assert_eq!(actual, *expected, "{kind}: {expression}");
    }
}

/// Keyword pairs and a non-empty `**hash` are one trailing Hash argument, a block argument other
/// than `&nil` is a possible handler, and each splat or `...` supplies any number of arguments
/// (a literal array splat supplies its elements). Every row was checked against a cucumber-ruby
/// registrar stub; `*a` with an unknown array may register and fails closed.
#[test]
fn receiver_registration_counts_keywords_blocks_and_splats() {
    for (arguments, block, expected) in [
        ("'x', key: 1", true, false),
        ("'x', :s, key: 1", false, true),
        ("'x', nil, {}, key: 1", true, false),
        ("'x', **{}", true, true),
        ("'x', **{key: 1}", true, false),
        ("'x', **opts", true, true),
        ("'x', **nil", true, true),
        ("'x', **({})", true, true),
        ("'x', **({key: 1})", true, false),
        ("'x', **{**{}}", true, true),
        ("'x', **{**{key: 1}}", true, false),
        ("'x', **{**h}", true, true),
        ("*['x', key: 1]", true, false),
        ("*['x', :s, key: 1]", false, true),
        ("*['x', *a]", true, true),
        ("*(['x', :s])", false, true),
        ("*(['x', 1])", false, false),
        ("*['x', **h]", true, true),
        ("*['x', **h]", false, false),
        ("*['x', **{key: 1}]", true, false),
        // A pattern test is false at runtime when the value does not match, and the block registers.
        ("'x', (x in Integer)", true, true),
        ("'x', &nil", false, false),
        ("'x', &(nil)", false, false),
        ("'x', &()", false, false),
        ("'x', &(1; nil)", false, false),
        ("'x', &((nil))", false, false),
        ("'x', &(1; false)", false, true),
        ("'x', &false", false, true),
        ("'x', &handler", false, true),
        ("*nil", true, false),
        ("*()", true, false),
        ("*(1; nil)", true, false),
        ("*[]", true, false),
        ("*['x', :s]", false, true),
        ("*['x', 1]", false, false),
        ("*a", true, true),
        ("'x', *a, 1, 2, 3", true, false),
        ("*a, 'x', 'y'", true, false),
        ("'x', *a, :s, *a, {}", false, true),
    ] {
        assert_eq!(
            receiver_call(arguments, block, "").0,
            expected,
            "{arguments}"
        );
    }
}

/// Extract one Ruby registration and return its matcher, flags and whether analysis stayed complete.
fn extract_matcher(literal: &str) -> (Vec<(String, String)>, bool) {
    use crate::source_adapter::{SourceAdapter, SourceFile, SourceLanguage};
    let file = SourceFile {
        path: "steps.rb".into(),
        language: SourceLanguage::Ruby,
    };
    let extraction = super::RUBY_ADAPTER
        .extract(&format!("Given({literal}) {{ work() }}"), &file)
        .unwrap();
    (
        extraction
            .definitions
            .into_iter()
            .map(|d| (d.matcher, d.matcher_flags))
            .collect(),
        extraction.diagnostics.is_empty(),
    )
}

/// Verify every `%r` delimiter registers like `/…/`: bracket pairs nest by depth, an escaped
/// delimiter or backslash does not end the literal, and each row's matcher is Ruby 4.0's
/// `source` with the same match results.
#[test]
fn percent_r_delimiters_register_with_nesting_and_escapes() {
    // (literal, matcher, text Ruby matches, text Ruby does not match)
    for (literal, matcher, hit, miss) in [
        ("/a.c/", "a.c", "abc", "ac"),
        ("%r{a.c}", "a.c", "abc", "ac"),
        ("%r!a.c!", "a.c", "abc", "ac"),
        ("%r(a.c)", "a.c", "abc", "ac"),
        ("%r[a.c]", "a.c", "abc", "ac"),
        ("%r<a.c>", "a.c", "abc", "ac"),
        ("%r|a.c|", "a.c", "abc", "ac"),
        // Nested pairs close at depth zero, not at the first closer.
        ("%r(a(b)c)", "a(b)c", "abc", "ac"),
        ("%r[a[b]c]", "a[b]c", "abc", "ac"),
        ("%r<a<b>c>", "a<b>c", "a<b>c", "abc"),
        ("%r{a{2}c}", "a{2}c", "aac", "ac"),
        // An escaped bracket neither opens nor closes a level.
        (r"%r(a\(b)", r"a\(b", "a(b", "ab"),
        (r"%r(a\)b)", r"a\)b", "a)b", "ab"),
        (r"%r[a\]b]", r"a\]b", "a]b", "ab"),
        (r"%r<a\>b>", r"a\>b", "a>b", "ab"),
        (r"%r{a\}b}", r"a\}b", "a}b", "ab"),
        // An escaped non-bracket delimiter stays inside. Ruby drops its backslash unless the
        // character is regex syntax, which changes `[a\-z]` into the range `[a-z]`.
        (r"%r!a\!b!", "a!b", "a!b", "ab"),
        (r"/a\/b/", "a/b", "a/b", "ab"),
        // `/` is not the terminator here, so its backslash stays.
        (r"%r!a\/b!", r"a\/b", "a/b", "ab"),
        (r"%r,a\,b,", "a,b", "a,b", "ab"),
        (r"%r-\A[a\-z]\z-", r"\A[a-z]\z", "b", "-"),
        (r"%r|a\|b|", r"a\|b", "a|b", "a"),
        (r"%r^a\^b^", r"a\^b", "a^b", "ab"),
        (r"%r.a\.b.", r"a\.b", "a.b", "axb"),
        (r"%r?a\?b?", r"a\?b", "a?b", "ab"),
        (r"%r*a\*b*", r"a\*b", "a*b", "ab"),
        (r"%r+a\+b+", r"a\+b", "a+b", "ab"),
        (r"%r$a\$b$", r"a\$b", "a$b", "ab"),
        (r"%r)a\)b)", r"a\)b", "a)b", "ab"),
        (r"%r]a\]b]", r"a\]b", "a]b", "ab"),
        (r"%r}a\}b}", r"a\}b", "a}b", "ab"),
        (r"%r>a\>b>", r"a\>b", "a>b", "ab"),
        // An escaped backslash does not escape the delimiter after it.
        (r"%r(a\\b)", r"a\\b", r"a\b", "ab"),
        (r"%r!a\\!", r"a\\", r"a\", "a"),
        ("%r(a\nb)", "a\nb", "a\nb", "ab"),
    ] {
        let (definitions, complete) = extract_matcher(literal);
        assert!(complete, "{literal}");
        assert_eq!(
            definitions,
            [(matcher.to_owned(), String::new())],
            "{literal}"
        );
        let regex = regex::Regex::new(&regex_expression(matcher, "").unwrap()).unwrap();
        assert!(regex.is_match(hit), "{literal} hit");
        assert!(!regex.is_match(miss), "{literal} miss");
    }
    // Ruby 4.0 accepts every ASCII punctuation character as a symmetric delimiter, including
    // closing brackets, and drops the backslash of an escaped delimiter except for the regex
    // syntax characters (probe: `ruby -e 'p %r<c>a\<c>b<c>.source'`). tree-sitter-ruby 0.23
    // cannot parse `%r=`, and `\` as a delimiter is not modeled; both stay incomplete.
    let dropped = "!\"#%&',-/:;@_`~";
    for delimiter in ('!'..='~').filter(|c| c.is_ascii_punctuation() && !"([{<".contains(*c)) {
        let modeled = !"=\\".contains(delimiter);
        let (plain, escaped) = (
            format!("%r{delimiter}abc{delimiter}i"),
            format!("%r{delimiter}a\\{delimiter}b{delimiter}"),
        );
        let expect = |matcher: String, flags: &str| {
            if modeled {
                (vec![(matcher, flags.to_owned())], true)
            } else {
                (vec![], false)
            }
        };
        assert_eq!(
            extract_matcher(&plain),
            expect("abc".into(), "i"),
            "{plain}"
        );
        let source = if dropped.contains(delimiter) {
            format!("a{delimiter}b")
        } else {
            format!("a\\{delimiter}b")
        };
        assert_eq!(extract_matcher(&escaped), expect(source, ""), "{escaped}");
    }
}

/// Verify flags are collected after the closing delimiter for every form, and that literals
/// Ruby rejects or this adapter does not model stay incomplete instead of registering.
#[test]
fn percent_r_flags_and_unmodeled_literals_fail_closed() {
    for (raw, expected) in [
        ("/a/", Some(("a", ""))),
        ("/a/mi", Some(("a", "im"))),
        ("%r{a}iim", Some(("a", "im"))),
        ("%r!a!xm", Some(("a", "mx"))),
        ("%r(a)n", Some(("a", "n"))),
        ("%r a ", None),
        (r"%r\a\", None),
        // Unterminated, escaped closer, bare prefix, alphanumeric delimiter and other `%` literals.
        ("%r(a", None),
        ("%r(a(b)", None),
        ("%r!a", None),
        (r"%r(a\)", None),
        ("%r", None),
        ("%ra", None),
        ("%R(a)", None),
        ("%w(a)", None),
        ("(a)", None),
    ] {
        assert_eq!(
            super::regex_literal(raw),
            expected.map(|(pattern, flags)| (pattern.to_owned(), flags.to_owned())),
            "{raw}"
        );
    }
    // Control: the same registration is complete with a supported delimiter and incomplete when
    // tree-sitter-ruby reports a syntax error (invalid Ruby, or a valid whitespace or `=`
    // delimiter it cannot parse), the matcher interpolates, or a flag is unsupported.
    assert!(extract_matcher("%r(a)").1);
    for literal in [
        "%r|a|b|",
        "%r a ",
        r"%r\a\",
        "%r(a",
        "%r(a#{x})",
        "%r!a#{x}!",
        "/a#{x}/",
        "%r(a)z",
    ] {
        assert!(!extract_matcher(literal).1, "{literal}");
    }
}