cuke-dedup 0.12.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
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
//! Conservative, opt-in extraction of direct Cucumber-Ruby registrations.

pub(crate) mod semantics;

use crate::model::{Framework, MatcherKind, SourceLocation, StepDefinition};
use crate::source_adapter::{
    AdapterSessionState, Extraction, ExtractionDiagnostic, ExtractionDiagnosticKind as Kind,
    ExtractionDiagnosticLevel as Level, SourceAdapter, SourceExtractionSession, SourceFile,
    SourceFinalization, SourceLanguage, SourceUncertainty, StatefulSourceAdapter, UncertaintyCause,
    UncertaintyScope,
};
use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
use tree_sitter::Node;

mod assertions;
mod bindings;
pub(crate) mod config;
mod dependencies;
mod handler;
mod load_phase;
mod ownership;
mod parameters;
mod providers;
mod registration_aliases;
mod registration_wrappers;
mod step_keywords;

pub(crate) struct RubyAdapter;
pub(crate) static RUBY_ADAPTER: RubyAdapter = RubyAdapter;
pub(crate) struct RubySession {
    effects: ownership::RegistrationEffects,
    providers: providers::Providers,
    assertions: assertions::AssertionProviders,
    assertion_modules: Vec<String>,
    /// Set when provider proofs are unavailable because the selection exceeds the proof budget.
    proof_sources_exceeded: bool,
    /// Ruby files prepared for the session and those actually extracted; a prepared file that was
    /// never extracted (unreadable, or skipped by a caller) still loads, so the suite is open.
    prepared: std::collections::BTreeSet<PathBuf>,
    extracted: std::collections::BTreeSet<PathBuf>,
}
impl AdapterSessionState for RubySession {
    /// Resolves configured Ruby provider paths with the same rule discovery applies to loads.
    fn initialize(root: Option<&Path>, _: &[String], assertion_modules: &[String]) -> Self {
        let mut configured = assertion_modules.to_vec();
        if let Some(root) = root {
            // A configured module names a load request, resolved exactly as discovery resolves one.
            for module in assertion_modules {
                if let Some(path) = dependencies::request_target(&[root.to_owned()], module) {
                    configured.push(path.to_string_lossy().into_owned());
                }
            }
        }
        Self {
            effects: Default::default(),
            providers: Default::default(),
            assertions: Default::default(),
            assertion_modules: configured,
            proof_sources_exceeded: false,
            prepared: Default::default(),
            extracted: Default::default(),
        }
    }
}
impl StatefulSourceAdapter for RubyAdapter {
    type State = RubySession;
    fn discover_dependencies(
        config: &crate::config::Config,
        excludes: &globset::GlobSet,
        files: &mut crate::discovery::DiscoveredFiles,
    ) {
        dependencies::resolve(config, excludes, files);
    }
}

impl SourceAdapter for RubyAdapter {
    fn name(&self) -> &'static str {
        "cucumber-ruby"
    }
    fn language(&self) -> SourceLanguage {
        SourceLanguage::Ruby
    }
    fn extract(&self, source: &str, file: &SourceFile) -> Result<Extraction> {
        let (mut extraction, _) = extract(source, file)?;
        mark_unresolved_dependency_usage(&mut extraction);
        Ok(extraction)
    }
    fn discover_by_default(&self) -> bool {
        false
    }
    fn supports_indirect_usage(&self) -> bool {
        true
    }
    fn resolve_parameter_types(
        &self,
        declarations: Vec<crate::source_adapter::SourceParameterType>,
        configured: &std::collections::BTreeMap<String, String>,
    ) -> (std::collections::BTreeMap<String, String>, Vec<String>) {
        parameters::merge(declarations, configured)
    }
    /// Loads provider and assertion proofs, recording when the selection exceeds their budget.
    fn prepare_session(
        &self,
        files: &[SourceFile],
        session: &mut SourceExtractionSession,
    ) -> Result<()> {
        let source_budget = (
            crate::resource_limits::MAX_REGISTRATION_MODULES,
            crate::resource_limits::MAX_REGISTRATION_MODULE_BYTES,
        );
        let (units, exceeded) = match providers::load_proof_sources(files, source_budget)? {
            providers::ProofSources::Loaded(units) => (Some(units), false),
            providers::ProofSources::OverBudget => (None, true),
            providers::ProofSources::Untrusted => (None, false),
        };
        let edges = session.dependency_edges();
        let state = session.state::<RubySession>()?;
        state.proof_sources_exceeded = exceeded;
        state.prepared = files
            .iter()
            .filter(|file| file.language == SourceLanguage::Ruby)
            .map(|file| file.path.clone())
            .collect();
        if let Some(units) = units {
            let (providers, assertions) = providers::Providers::from_units_with_assertions(
                &units,
                &edges,
                &state.assertion_modules,
            );
            state.providers = providers;
            state.assertions = assertions;
        } else {
            state.providers = Default::default();
            state.assertions = if state.assertion_modules.is_empty() {
                Default::default()
            } else {
                assertions::AssertionProviders::unavailable()
            };
        }
        Ok(())
    }
    /// Reports suite-wide Ruby uncertainties, naming the proof limit when it caused them.
    fn finalize_session(
        &self,
        session: &mut SourceExtractionSession,
    ) -> Result<SourceFinalization> {
        let mut result = SourceFinalization::default();
        let state = session.state::<RubySession>()?;
        result
            .advisories
            .extend_from_slice(state.assertions.advisories());
        let limit = state
            .proof_sources_exceeded
            .then(proof_limit_reason)
            .unwrap_or_default();
        if state.assertions.incomplete() {
            result.uncertainties.push(SourceUncertainty::new(
                UncertaintyScope::Registry(SourceLanguage::Ruby),
                UncertaintyCause::Source,
                format!("Ruby assertion-provider provenance is incomplete{limit}"),
            ));
        }
        if !state.prepared.is_subset(&state.extracted) {
            state.effects.open_load_phase();
        }
        // A call contained in an instance method runs during load once the suite's load phase is
        // open, exactly like any other unresolved effect.
        let escaped = state.effects.escaped_call().map(|site| {
            format!(
                "Ruby call at {}:{}:{} that may redefine the DSL or dispatch dynamically can run during load because the suite's load-time code is not limited to registrations, literal loads and plain class definitions",
                site.path.display(),
                site.line,
                site.column
            )
        });
        let cause = escaped
            .as_ref()
            .map(|reason| format!("; {reason}"))
            .unwrap_or_default();
        let invalidated = state.effects.invalidated() || escaped.is_some();
        if state.providers.work_exhausted() {
            result.uncertainties.push(SourceUncertainty::new(
                UncertaintyScope::Registry(SourceLanguage::Ruby),
                if invalidated {
                    UncertaintyCause::Registration
                } else {
                    UncertaintyCause::Source
                },
                if invalidated {
                    format!("Ruby registration source proof exceeded its work limit; DSL redefinition or metaprogramming also prevents trusted registration extraction{cause}")
                } else {
                    "Ruby registration source proof exceeded its work limit".to_owned()
                },
            ));
        } else if invalidated {
            result.uncertainties.push(SourceUncertainty::new(
                UncertaintyScope::Registry(SourceLanguage::Ruby),
                UncertaintyCause::Registration,
                format!("Ruby DSL redefinition or metaprogramming prevents trusted registration extraction across the selected suite{limit}{cause}"),
            ));
        }
        Ok(result)
    }
    /// Extracts one file, keeping dependency diagnostics for unfollowed loads and their reasons.
    fn extract_with_session(
        &self,
        source: &str,
        file: &SourceFile,
        session: &mut SourceExtractionSession,
    ) -> Result<Extraction> {
        let prepared = prepare_nuls(source);
        let source = prepared.as_ref();
        let assertions = session
            .state::<RubySession>()?
            .assertions
            .get(&file.path, source);
        let proof = session
            .state::<RubySession>()?
            .providers
            .get(&file.path, source);
        let (mut extraction, mut invalidated) =
            extract_with_proof(source, file, proof, assertions.as_ref(), true)?;
        extraction.diagnostics.retain(|diagnostic| {
            diagnostic.kind != Kind::Dependency
                || !session.dependency_resolved(&diagnostic.location)
        });
        for diagnostic in &mut extraction.diagnostics {
            if let Some(reason) = (diagnostic.kind == Kind::Dependency)
                .then(|| session.dependency_gap(&diagnostic.location))
                .flatten()
            {
                diagnostic.message = format!("Ruby source dependency was not followed: {reason}");
            }
        }
        mark_unresolved_dependency_usage(&mut extraction);
        // An unresolved top-level load runs unanalyzed code during load, so the suite's load phase
        // is not closed. Loads inside handlers or methods run only when those do.
        if extraction.diagnostics.iter().any(|diagnostic| {
            diagnostic.kind == Kind::Dependency && invalidated.load_require(&diagnostic.location)
        }) {
            invalidated.open_load_phase();
        }
        let state = session.state::<RubySession>()?;
        state.extracted.insert(file.path.clone());
        state.effects.extend(invalidated);
        Ok(extraction)
    }
}

/// The clause naming the provider-proof budget, appended to a suite-wide uncertainty.
fn proof_limit_reason() -> String {
    format!(
        ": provider proofs are unavailable because the selected and loaded Ruby files exceed the {}-file / {} proof limit",
        dependencies::grouped(crate::resource_limits::MAX_REGISTRATION_MODULES),
        dependencies::byte_limit(crate::resource_limits::MAX_REGISTRATION_MODULE_BYTES)
    )
}

fn mark_unresolved_dependency_usage(extraction: &mut Extraction) {
    if extraction
        .diagnostics
        .iter()
        .any(|diagnostic| diagnostic.kind == Kind::Dependency)
    {
        // Unknown providers may delegate to any local step. Only resolved source edges can
        // discharge this uncertainty, without clearing independent dynamic usage signals.
        extraction
            .indirect_usage
            .get_or_insert_with(Default::default)
            .unknown = true;
    }
}

/// Extracts one source without a session; no call is contained without suite finalization.
fn extract(
    source: &str,
    file: &SourceFile,
) -> Result<(Extraction, ownership::RegistrationEffects)> {
    // Without a session nothing finalizes the suite, so no call can be contained.
    let prepared = prepare_nuls(source);
    extract_with_proof(prepared.as_ref(), file, None, None, false)
}

/// Match Ruby's lexical NUL boundary without executing the source. NUL inside a Ruby comment is
/// ignored; NUL inside literal data is retained; executable interpolation stops the source.
fn prepare_nuls(source: &str) -> std::borrow::Cow<'_, str> {
    if !source.contains('\0') {
        return std::borrow::Cow::Borrowed(source);
    }
    // A space has the same byte width and lets tree-sitter classify comments and quoted data
    // without its special NUL error recovery changing the enclosing lexical node.
    let probe = source.replace('\0', " ");
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&tree_sitter_ruby::LANGUAGE.into())
        .expect("statically linked Ruby grammar is compatible with tree-sitter");
    let tree = parser
        .parse(&probe, None)
        .expect("Ruby parser with no timeout or cancellation returns a tree");
    let mut prepared = source.to_owned();
    for (byte, _) in source.match_indices('\0') {
        let mut node = tree.root_node().descendant_for_byte_range(byte, byte + 1);
        let mut kind = None;
        while let Some(current) = node {
            if matches!(
                current.kind(),
                "comment"
                    | "string"
                    | "delimited_symbol"
                    | "bare_string"
                    | "bare_symbol"
                    | "string_array"
                    | "symbol_array"
                    | "regex"
                    | "heredoc_body"
                    | "interpolation"
            ) {
                kind = Some(current.kind());
                break;
            }
            node = current.parent();
        }
        match kind {
            Some("comment") => prepared.replace_range(byte..byte + 1, " "),
            // tree-sitter rejects NUL inside bare array elements. Keep their one-byte extent and
            // token boundary; array values are opaque to registration extraction.
            Some("bare_string" | "bare_symbol" | "string_array" | "symbol_array") => {
                prepared.replace_range(byte..byte + 1, "x");
            }
            Some("string" | "delimited_symbol" | "regex" | "heredoc_body") => {}
            _ => {
                prepared.truncate(byte);
                break;
            }
        }
    }
    std::borrow::Cow::Owned(prepared)
}

/// Extracts registrations using source-owned provider and assertion evidence.
fn extract_with_proof(
    source: &str,
    file: &SourceFile,
    proof: Option<&providers::Proof>,
    assertions: Option<&assertions::AssertionBindings>,
    finalized: bool,
) -> Result<(Extraction, ownership::RegistrationEffects)> {
    if file.language != SourceLanguage::Ruby {
        bail!(
            "cucumber-ruby adapter cannot parse {:?} source {}",
            file.language,
            file.path.display()
        );
    }
    let mut parser = tree_sitter::Parser::new();
    parser.set_language(&tree_sitter_ruby::LANGUAGE.into())?;
    let tree = parser
        .parse(source, None)
        .context("Ruby parser produced no tree")?;
    let root = tree.root_node();
    let syntax_error = syntax_error(root, source);
    let syntax_valid = syntax_error.is_none();
    let proof = proof.filter(|_| syntax_valid);
    let assertions = assertions.filter(|_| syntax_valid);
    let nodes = descendants(root);
    let lines: Vec<_> = source.lines().collect();
    let mut aliases = if syntax_valid {
        registration_aliases::RegistrationAliases::collect(root, source)
    } else {
        Default::default()
    };
    if let Some(proof) = proof {
        aliases.extend_provider(root, proof);
    }
    let wrappers = if syntax_valid {
        registration_wrappers::RegistrationWrappers::collect(root, source, &aliases)
    } else {
        Default::default()
    };
    let mut result = Extraction {
        indirect_usage: Some(indirect_usage(&nodes, source, &aliases, proof)),
        ..Extraction::default()
    };
    if let Some(cause) = syntax_error {
        result.diagnostics.push(diagnostic(
            file,
            cause,
            source,
            Kind::Unparseable,
            "Ruby source contains syntax errors; extraction is incomplete",
        ));
    }
    result.parameter_types = parameters::collect(&nodes, source, file);
    let mut effects = ownership::RegistrationEffects::collect(
        file, finalized, root, source, &aliases, &wrappers, proof,
    );
    if let Some(declaration) = result
        .parameter_types
        .iter()
        .find(|declaration| parameters::invalidates_registry(declaration))
    {
        effects.invalidate(nodes.iter().copied().find(|node| {
            node.kind() == "call" && location(file, *node, source) == declaration.location
        }));
    }
    let replaced = effects.invalidated();
    if replaced {
        let cause = effects
            .invalidation_site()
            .and_then(|(start, end)| root.descendant_for_byte_range(start, end))
            .unwrap_or(root);
        result.diagnostics.push(diagnostic(
            file,
            cause,
            source,
            Kind::Incomplete,
            "Ruby registration ownership or executable source effects are unresolved",
        ));
    }
    for (node, name) in named_calls(&nodes, source) {
        if proof.is_some_and(|p| p.unresolved_calls.contains(&node.start_byte())) {
            result
                .indirect_usage
                .get_or_insert_with(Default::default)
                .unknown = true;
            result.diagnostics.push(diagnostic(
                file,
                node,
                source,
                Kind::Incomplete,
                "Ruby constant provider callable has unresolved registration provenance",
            ));
        }
        if wrappers.forwarding(node)
            || proof.is_some_and(|p| p.forwarding.contains(&node.start_byte()))
        {
            continue;
        }
        let alias = aliases.registration(node);
        let name = alias
            .or_else(|| wrappers.registration(node))
            .unwrap_or(name);
        // A loader call without operands loads nothing (Ruby raises ArgumentError), so it can
        // neither resolve nor leave a dependency unresolved.
        if matches!(name, "require" | "require_relative" | "load" | "autoload")
            && has_operands(node)
        {
            result.diagnostics.push(diagnostic(
                file,
                node,
                source,
                Kind::Dependency,
                "Ruby source dependency is unresolved",
            ));
        }
        if let Some(receiver) = node
            .child_by_field_name("receiver")
            .filter(|_| alias.is_none())
        {
            // Any receiver may evaluate to main (`def me = self`, a local rebound through `binding`
            // or `binding_of_caller`), whose DSL registers.
            if registration(name) && may_register(node, source) {
                let message = if is_self_receiver(receiver) {
                    "Ruby self-qualified registration is outside direct-call extraction support"
                } else {
                    "Ruby registration through a receiver is not resolved; definitions may be missing"
                };
                result
                    .diagnostics
                    .push(diagnostic(file, node, source, Kind::Incomplete, message));
            }
            continue;
        }
        if matches!(
            name,
            "eval" | "send" | "public_send" | "define_method" | "alias_method"
        ) {
            result.diagnostics.push(diagnostic(file, node, source, Kind::Incomplete,
                    "Ruby dependency, dynamic dispatch or parameter type is not resolved; definitions may be missing"));
        }
        if name == "ParameterType"
            && result.parameter_types.iter().any(|declaration| {
                declaration.location == location(file, node, source)
                    && (declaration.expression.is_none()
                        || parameters::invalidates_registry(declaration))
            })
        {
            result.diagnostics.push(diagnostic(
                file,
                node,
                source,
                Kind::Incomplete,
                "Ruby parameter type declaration is not statically resolved",
            ));
        }
        if !registration(name) {
            continue;
        }
        if node
            .parent()
            .is_some_and(|parent| parent.kind() != "program")
            && !may_register(node, source)
            && node.child_by_field_name("block").is_none()
        {
            // A call without a possible handler cannot add a step. An attached block still
            // indicates an attempted registration with potentially unsupported arguments.
            continue;
        }
        if replaced
            || (node
                .parent()
                .is_none_or(|parent| parent.kind() != "program")
                && !proof.is_some_and(|p| p.executed.contains(&node.start_byte())))
        {
            result.diagnostics.push(diagnostic(
                file,
                node,
                source,
                Kind::Incomplete,
                "Ruby registration is redefined or not a direct top-level call",
            ));
            continue;
        }
        let Some((matcher, matcher_kind, flags, block)) = registration_parts(
            node,
            source,
            proof.is_some_and(|p| p.handlers.contains_key(&node.start_byte())),
        ) else {
            result.diagnostics.push(diagnostic(
                file,
                node,
                source,
                Kind::Incomplete,
                "Ruby registration requires a static matcher and a statically resolved handler",
            ));
            continue;
        };
        let translated_regex = if matcher_kind == MatcherKind::RegularExpression {
            match regex_expression_result(&matcher, &flags) {
                Ok(expression) => Some(expression),
                Err(RegexConversionError::Unsupported) => {
                    result.diagnostics.push(diagnostic(
                        file,
                        node,
                        source,
                        Kind::Incomplete,
                        "Ruby regular expression is outside the supported static matching subset",
                    ));
                    None
                }
                Err(RegexConversionError::CompiledTooBig) => {
                    result.diagnostics.push(diagnostic(
                        file,
                        node,
                        source,
                        Kind::Incomplete,
                        "Ruby regular expression exceeds the regex resource limit",
                    ));
                    None
                }
                // Shared matcher compilation reports the raw-pattern limit at its location.
                Err(RegexConversionError::PatternTooLong) => None,
            }
        } else {
            None
        };
        let handler = proof
            .and_then(|p| p.handlers.get(&node.start_byte()))
            .cloned()
            .unwrap_or_else(|| handler::fingerprint(block, root, source, assertions));
        if !handler.comparable
            && !proof.is_some_and(|proof| proof.comparison_rejections.contains(&node.start_byte()))
            && !assertions
                .is_some_and(|assertions| assertions.rejected_comparison(block, root, source))
        {
            result.diagnostics.push(diagnostic(
                file,
                block,
                source,
                Kind::Incomplete,
                "Ruby handler comparison has unresolved syntax, captures or receiver identity",
            ));
        }
        let comparison = if matcher_kind == MatcherKind::CucumberExpression {
            crate::matcher::normalize_cucumber_expression(&matcher)
        } else {
            // Translation preserves Ruby capture arity. Flags have their own comparison
            // partition, so strip only the generated outer flag group from this key.
            translated_regex
                .map(|expression| {
                    expression[expression.find(':').unwrap() + 1..expression.len() - 1].to_owned()
                })
                .unwrap_or_else(|| matcher.clone())
        };
        result.definitions.push(StepDefinition {
            normalized_matcher: comparison,
            matcher,
            matcher_kind,
            matcher_flags: flags,
            handler,
            framework: Framework::CucumberRuby,
            registration: name.to_owned(),
            location: location(file, node, source),
            inline_suppressions: crate::source_adapter::suppression::inline_suppressions(
                node.start_position().row,
                "#",
                &lines,
                file,
                &mut result.diagnostics,
            ),
        });
    }
    result
        .definitions
        .sort_by_key(|item| (item.location.line, item.location.column));
    result
        .diagnostics
        .sort_by_key(|item| (item.location.line, item.location.column));
    Ok((result, effects))
}

/// What an argument evaluates to, as far as Cucumber-Ruby's registrar can tell: a step pattern
/// (String or Regexp), a handler (Symbol or Proc), `nil`/`false`, another known type, or a value
/// only runtime decides.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ArgumentValue {
    Pattern,
    Handler,
    Falsy,
    Other,
    Unknown,
}

/// The value class of one argument node. Every `argument_list` expression kind of tree-sitter-ruby
/// not listed here is `Unknown`; the listed classes were checked with `ruby -e`.
fn argument_value(node: Node<'_>, source: &str) -> ArgumentValue {
    match node.kind() {
        // `(a; b)` is the last statement, `()` is nil.
        "parenthesized_statements" => bindings::semantic_children(node)
            .last()
            .map_or(ArgumentValue::Falsy, |last| argument_value(*last, source)),
        "assignment" => node
            .child_by_field_name("right")
            .map_or(ArgumentValue::Unknown, |right| {
                argument_value(right, source)
            }),
        "string" | "chained_string" | "character" | "regex" => ArgumentValue::Pattern,
        // A backtick heredoc calls the redefinable backtick method.
        "heredoc_beginning" if !text(node, source).contains('`') => ArgumentValue::Pattern,
        // `def` returns its name as a Symbol.
        "simple_symbol" | "delimited_symbol" | "lambda" | "method" | "singleton_method" => {
            ArgumentValue::Handler
        }
        "nil" | "false" | "test_pattern" => ArgumentValue::Falsy,
        "true" | "integer" | "float" | "rational" | "complex" | "array" | "string_array"
        | "symbol_array" | "hash" | "range" => ArgumentValue::Other,
        // A sign written directly before a number is part of the literal; `- 1` is a call.
        "unary"
            if node.child_by_field_name("operand").is_some_and(|operand| {
                matches!(operand.kind(), "integer" | "float" | "rational" | "complex")
                    && node.child(0).is_some_and(|sign| {
                        matches!(sign.kind(), "-" | "+") && sign.end_byte() == operand.start_byte()
                    })
            }) =>
        {
            ArgumentValue::Other
        }
        // tree-sitter parses these reserved keywords as identifiers; Ruby never binds them.
        "identifier" => match text(node, source) {
            "__FILE__" => ArgumentValue::Pattern,
            "__LINE__" | "__ENCODING__" => ArgumentValue::Other,
            _ => ArgumentValue::Unknown, // fail-closed: a local or method may hold anything.
        },
        _ => ArgumentValue::Unknown, // fail-closed: runtime decides the value.
    }
}

/// Whether a `**` operand is a literal empty Hash (`Some(true)`), a literal non-empty one
/// (`Some(false)`), or unknown. Parentheses are transparent, and a literal Hash is non-empty when it
/// has a pair or a non-empty nested `**` literal. `**nil` passes nothing, which "unknown" already
/// allows.
fn literal_hash_empty(node: Node<'_>) -> Option<bool> {
    let node = bindings::unparenthesized(node);
    match node.kind() {
        "hash" => {
            let mut empty = Some(true);
            for entry in bindings::semantic_children(node) {
                empty = if entry.kind() == "hash_splat_argument" {
                    either_non_empty(empty, entry.named_child(0).and_then(literal_hash_empty))
                } else {
                    Some(false) // a pair
                };
            }
            empty
        }
        _ => None, // fail-closed: runtime decides whether the Hash is empty.
    }
}

/// Whether an expression is `nil` by its syntax: `nil`, `()`, or parentheses whose last statement
/// is one of those (`(1; nil)`).
fn evaluates_to_nil(node: Node<'_>) -> bool {
    match node.kind() {
        "nil" => true,
        "parenthesized_statements" => bindings::semantic_children(node)
            .last()
            .is_none_or(|last| evaluates_to_nil(*last)),
        _ => false, // fail-closed: any other operand may be non-nil, so it may pass a block.
    }
}

/// Combines two emptiness answers: non-empty if either is, unknown if either is, else empty.
fn either_non_empty(left: Option<bool>, right: Option<bool>) -> Option<bool> {
    match (left, right) {
        (Some(false), _) | (_, Some(false)) => Some(false),
        (Some(true), Some(true)) => Some(true),
        _ => None, // fail-closed: either side may be non-empty at runtime.
    }
}

/// One positional argument: a known value, zero or one known value, or a splat or `...`
/// supplying any number of values.
#[derive(Clone, Copy)]
enum Positional {
    Fixed(ArgumentValue),
    /// Zero or one value of a known class, as an unknown `**hash` entry adds nothing or a Hash.
    Optional(ArgumentValue),
    Variadic,
}

/// Whether a step-keyword call can register. Cucumber-Ruby keywords take
/// `(pattern, symbol = nil, options = {}, &proc)`: the pattern must be a String or Regexp, and
/// `symbol || proc` must be a Symbol or a Proc. Keyword pairs and a non-empty `**hash` are one
/// trailing Hash argument; each splat or `...` supplies any number of arguments, so every
/// argument list within three arguments is tried, and the call can register when one of them
/// has a possible pattern and either a possible handler second or, with that argument absent,
/// `nil` or `false`, a possible block.
fn may_register(call: Node<'_>, source: &str) -> bool {
    let arguments = call
        .child_by_field_name("arguments")
        .map(bindings::semantic_children)
        .unwrap_or_default();
    let mut positional = Vec::new();
    // `None`: no keyword Hash; `Some(false)`: maybe one; `Some(true)`: always one.
    let mut keywords: Option<bool> = None;
    let mut block = call.child_by_field_name("block").is_some();
    for argument in &arguments {
        match argument.kind() {
            "pair" => keywords = Some(true),
            "hash_splat_argument" => match argument.named_child(0).and_then(literal_hash_empty) {
                Some(true) => {}
                Some(false) => keywords = Some(true),
                None => keywords = Some(keywords.unwrap_or(false)),
            },
            "block_argument" => {
                block |= argument
                    .named_child(0)
                    .is_none_or(|value| !evaluates_to_nil(value));
            }
            "forward_argument" => {
                block = true;
                keywords = Some(keywords.unwrap_or(false));
                positional.push(Positional::Variadic);
            }
            "splat_argument" => match argument.named_child(0).map(bindings::unparenthesized) {
                Some(value) if evaluates_to_nil(value) => {}
                // A literal array supplies its elements; its keyword pairs are one trailing Hash.
                Some(value) if value.kind() == "array" => {
                    let mut hash = Some(true);
                    for element in bindings::semantic_children(value) {
                        match element.kind() {
                            "pair" => hash = Some(false),
                            "hash_splat_argument" => {
                                hash = either_non_empty(
                                    hash,
                                    element.named_child(0).and_then(literal_hash_empty),
                                );
                            }
                            "splat_argument" => positional.push(Positional::Variadic),
                            _ => {
                                positional.push(Positional::Fixed(argument_value(element, source)))
                            }
                        }
                    }
                    match hash {
                        Some(true) => {}
                        Some(false) => positional.push(Positional::Fixed(ArgumentValue::Other)),
                        // A Hash that may be empty is zero or one more argument, never another value.
                        None => positional.push(Positional::Optional(ArgumentValue::Other)),
                    }
                }
                _ => positional.push(Positional::Variadic),
            },
            _ => positional.push(Positional::Fixed(argument_value(*argument, source))),
        }
    }
    // Distinct argument lists within the three-argument cap; `None` is a value a splat supplied.
    let mut expansions: Vec<Vec<Option<ArgumentValue>>> = vec![Vec::new()];
    for item in &positional {
        let mut next: Vec<Vec<Option<ArgumentValue>>> = Vec::new();
        for prefix in &expansions {
            let choices: Vec<Vec<Option<ArgumentValue>>> = match item {
                Positional::Fixed(value) => vec![vec![Some(*value)]],
                Positional::Optional(value) => vec![Vec::new(), vec![Some(*value)]],
                Positional::Variadic => (0..=3).map(|width| vec![None; width]).collect(),
            };
            for choice in choices {
                let mut slots = prefix.clone();
                slots.extend(choice);
                if slots.len() <= 3 && !next.contains(&slots) {
                    next.push(slots);
                }
            }
        }
        expansions = next;
    }
    let hashes: &[bool] = match keywords {
        None => &[false],
        Some(false) => &[false, true],
        Some(true) => &[true],
    };
    expansions.iter().any(|slots| {
        hashes.iter().any(|&hash| {
            let mut slots = slots.clone();
            if hash {
                slots.push(Some(ArgumentValue::Other));
            }
            let pattern = slots.first().is_some_and(|first| {
                matches!(
                    first,
                    None | Some(ArgumentValue::Pattern | ArgumentValue::Unknown)
                )
            });
            let proc = match slots.get(1) {
                Some(None | Some(ArgumentValue::Handler | ArgumentValue::Unknown)) => true,
                Some(Some(ArgumentValue::Pattern | ArgumentValue::Other)) => false,
                // `nil`, `false` or absent: the block is the handler.
                Some(Some(ArgumentValue::Falsy)) | None => block,
            };
            slots.len() <= 3 && pattern && proc
        })
    })
}

/// Whether a call passes any argument, ignoring comments inside the parentheses.
fn has_operands(call: Node<'_>) -> bool {
    call.child_by_field_name("arguments")
        .is_some_and(|arguments| {
            // A block argument passes no operand either: `load(&blk)` still raises.
            bindings::semantic_children(arguments)
                .iter()
                .any(|argument| argument.kind() != "block_argument")
        })
}

fn is_self_receiver(mut node: Node<'_>) -> bool {
    while node.kind() == "parenthesized_statements" {
        let mut cursor = node.walk();
        let Some(value) = node
            .named_children(&mut cursor)
            .filter(|n| n.kind() != "comment")
            .last()
        else {
            return false;
        };
        node = value;
    }
    node.kind() == "self"
}

fn named_calls<'a>(
    nodes: &'a [Node<'a>],
    source: &'a str,
) -> impl Iterator<Item = (Node<'a>, &'a str)> {
    nodes.iter().copied().filter_map(move |node| {
        if node.kind() != "call" {
            return None;
        }
        let method = node.child_by_field_name("method")?;
        Some((node, text(method, source)))
    })
}

fn indirect_usage(
    nodes: &[Node<'_>],
    source: &str,
    aliases: &registration_aliases::RegistrationAliases,
    proof: Option<&providers::Proof>,
) -> crate::source_adapter::IndirectStepUsage {
    let mut usage = crate::source_adapter::IndirectStepUsage {
        unknown: nodes.iter().any(|n| {
            n.has_error()
                || matches!(n.kind(), "method" | "singleton_method")
                    && n.child_by_field_name("name")
                        .is_some_and(|name| matches!(text(name, source), "step" | "steps"))
        }),
        ..Default::default()
    };
    for (node, name) in named_calls(nodes, source) {
        if aliases.capture(node)
            || proof.is_some_and(|p| p.isolated_calls.contains(&node.start_byte()))
        {
            continue;
        }
        if matches!(
            name,
            "send"
                | "public_send"
                | "__send__"
                | "method"
                | "public_method"
                | "eval"
                | "instance_eval"
                | "class_eval"
                | "module_eval"
        ) {
            usage.unknown = true;
        }
        if !matches!(name, "step" | "steps") {
            continue;
        }
        let argument = node
            .child_by_field_name("arguments")
            .and_then(|args| args.named_child(0));
        let literal = argument
            .filter(|arg| {
                arg.kind() == "string"
                    && !descendants(*arg)
                        .iter()
                        .any(|n| n.kind() == "interpolation")
            })
            .and_then(|arg| literal_string(text(arg, source)));
        if name == "step"
            && node
                .child_by_field_name("receiver")
                .is_none_or(|receiver| receiver.kind() == "self")
        {
            if let Some(value) = literal {
                usage.texts.insert(value);
                continue;
            }
        }
        usage.unknown = true;
    }
    usage
}

fn static_method_name(node: Node<'_>, source: &str) -> Option<String> {
    match node.kind() {
        "simple_symbol" => text(node, source).strip_prefix(':').map(str::to_owned),
        "string"
            if !descendants(node)
                .iter()
                .any(|n| n.kind() == "interpolation") =>
        {
            literal_string(text(node, source))
        }
        _ => None,
    }
}

fn method_table_mutator(name: &str) -> bool {
    matches!(
        name,
        "define_method"
            | "define_singleton_method"
            | "alias_method"
            | "undef_method"
            | "remove_method"
    )
}

/// Method names whose redefinition or table mutation can redirect registration or deferral.
fn protected_method(name: &str) -> bool {
    deferring_dsl_method(name)
        || method_table_mutator(name)
        || matches!(
            name,
            "ParameterType"
                | "World"
                | "lambda"
                | "proc"
                | "method"
                | "public_method"
                | "call"
                | "to_proc"
                | "method_missing"
                | "require"
                | "require_relative"
                | "autoload"
                | "send"
                | "public_send"
                | "__send__"
                | "step"
                | "steps"
        )
}

fn may_replace_dsl(node: Node<'_>, source: &str) -> bool {
    let Some(method) = node.child_by_field_name("method") else {
        return false;
    };
    let mut name = text(method, source).to_owned();
    let mut cursor = node.walk();
    let args: Vec<_> = node
        .child_by_field_name("arguments")
        .map(|args| args.named_children(&mut cursor).collect())
        .unwrap_or_default();
    let mut args = args.into_iter();
    let mut dispatched = false;
    while matches!(name.as_str(), "send" | "public_send" | "__send__") {
        dispatched = true;
        let Some(target) = args.next().and_then(|arg| static_method_name(arg, source)) else {
            return true;
        };
        name = target;
    }
    if matches!(name.as_str(), "undef_method" | "remove_method") {
        return args.any(|arg| {
            static_method_name(arg, source).is_none_or(|target| protected_method(&target))
        });
    }
    if method_table_mutator(name.as_str()) {
        return args
            .next()
            .and_then(|arg| static_method_name(arg, source))
            .is_none_or(|target| protected_method(&target));
    }
    (dispatched && protected_method(&name))
        || matches!(
            name.as_str(),
            "autoload"
                | "eval"
                | "class_eval"
                | "module_eval"
                | "instance_eval"
                | "method"
                | "public_method"
                | "include"
                | "extend"
                | "prepend"
                | "const_get"
                | "const_set"
                | "remove_const"
        )
}

/// Whether `node` sits in a block that runs only during scenarios: a step handler, a scenario hook
/// block, or a `ParameterType` transformer.
fn inside_deferred_body(
    node: Node<'_>,
    source: &str,
    aliases: &registration_aliases::RegistrationAliases,
    wrappers: &registration_wrappers::RegistrationWrappers,
) -> bool {
    let mut parent = node.parent();
    while let Some(block) = parent {
        parent = block.parent();
        if !matches!(block.kind(), "block" | "do_block") {
            continue;
        }
        let Some(call) = block.parent() else { continue };
        if call.kind() == "call" && call.child_by_field_name("block") == Some(block) {
            let method = call.child_by_field_name("method").map(|n| text(n, source));
            // Step handlers and scenario hook blocks run only during scenarios.
            if call.parent().is_some_and(|p| p.kind() == "program")
                && (aliases.registration(call).is_some()
                    || wrappers.registration(call).is_some()
                    || (call.child_by_field_name("receiver").is_none()
                        && method.is_some_and(deferring_dsl_method)))
            {
                return true;
            }
            if call.child_by_field_name("receiver").is_some()
                || call
                    .child_by_field_name("arguments")
                    .is_some_and(|a| a.named_child_count() != 0)
                || !matches!(method, Some("lambda" | "proc"))
            {
                continue;
            }
        } else if call.kind() != "lambda" {
            continue;
        }
        let Some(pair) = call.parent().filter(|p| p.kind() == "pair") else {
            continue;
        };
        if pair.child_by_field_name("value") != Some(call)
            || !pair.child_by_field_name("key").is_some_and(|key| {
                key.kind() == "hash_key_symbol" && text(key, source) == "transformer"
            })
        {
            continue;
        }
        let registration = pair
            .parent()
            .filter(|p| p.kind() == "argument_list")
            .and_then(|p| p.parent());
        if registration.is_some_and(|r| {
            r.kind() == "call"
                && r.parent().is_some_and(|p| p.kind() == "program")
                && r.child_by_field_name("receiver").is_none()
                && r.child_by_field_name("method")
                    .is_some_and(|m| text(m, source) == "ParameterType")
        }) {
            return true;
        }
    }
    false
}

/// Cucumber-Ruby aliases every dialect's step keywords onto `register_rb_step_definition`
/// regardless of the feature-file language, so each one is a registrar in every step file.
/// DSL methods whose block runs only during scenarios: step keywords and scenario hooks. The same
/// names are protected against redefinition, so a block is deferred only while its method is the
/// runner's own.
fn deferring_dsl_method(name: &str) -> bool {
    registration(name) || load_phase::scenario_hook(name)
}

fn registration(name: &str) -> bool {
    name == "register_rb_step_definition"
        || step_keywords::STEP_KEYWORDS.binary_search(&name).is_ok()
}

fn text<'a>(node: Node<'_>, source: &'a str) -> &'a str {
    &source[node.byte_range()]
}

fn descendants(root: Node<'_>) -> Vec<Node<'_>> {
    let mut result = Vec::new();
    let mut pending = vec![root];
    while let Some(node) = pending.pop() {
        result.push(node);
        let mut cursor = node.walk();
        pending.extend(node.named_children(&mut cursor));
    }
    result
}

/// Returns the first syntax boundary Ruby rejects but tree-sitter may recover through.
fn syntax_error<'a>(root: Node<'a>, source: &str) -> Option<Node<'a>> {
    let mut nodes = Vec::new();
    let mut pending = vec![root];
    while let Some(node) = pending.pop() {
        nodes.push(node);
        let mut cursor = node.walk();
        pending.extend(node.children(&mut cursor));
    }
    let supplemental: Vec<_> = nodes
        .iter()
        .copied()
        .filter(|node| {
            (node.kind() == "identifier"
                && node.parent() == Some(root)
                && text(*node, source) == "end")
                || (node.kind() == "escape_sequence" && invalid_unicode_escape(text(*node, source)))
        })
        .collect();
    nodes
        .into_iter()
        .filter(|node| node.is_error() || node.is_missing())
        .chain(supplemental.iter().copied())
        .min_by_key(|node| (node.start_byte(), node.end_byte()))
}

/// Rejects Unicode escapes whose contents are not Ruby Unicode scalar values.
fn invalid_unicode_escape(raw: &str) -> bool {
    let Some(raw) = raw.strip_prefix("\\u") else {
        return false;
    };
    let mut chars = raw.chars().peekable();
    unicode_escape(&mut chars).is_none() || chars.next().is_some()
}

fn registration_parts<'a>(
    node: Node<'a>,
    source: &str,
    resolved_handler: bool,
) -> Option<(String, MatcherKind, String, Node<'a>)> {
    let args = node.child_by_field_name("arguments")?;
    if args.named_child_count() != 1
        && !(resolved_handler
            && args.named_child_count() == 2
            && node.child_by_field_name("block").is_none()
            && args
                .named_child(1)
                .is_some_and(|n| n.kind() == "block_argument"))
    {
        return None;
    }
    let matcher = args.named_child(0)?;
    let block = node
        .child_by_field_name("block")
        .or_else(|| resolved_handler.then(|| args.named_child(1)).flatten())?;
    if matcher.has_error() || block.has_error() {
        return None;
    }
    if descendants(matcher)
        .iter()
        .any(|node| node.kind() == "interpolation")
    {
        return None;
    }
    let raw = text(matcher, source);
    match matcher.kind() {
        "string" => Some((
            literal_string(raw)?,
            MatcherKind::CucumberExpression,
            String::new(),
            block,
        )),
        "regex" => {
            let (pattern, flags) = regex_literal(raw)?;
            Some((pattern, MatcherKind::RegularExpression, flags, block))
        }
        _ => None,
    }
}

fn regex_literal(raw: &str) -> Option<(String, String)> {
    let (start, delimiter) = if raw.starts_with('/') {
        (1, '/')
    } else if raw.starts_with("%r{") {
        (3, '}')
    } else {
        return None;
    };
    let end = raw.rfind(delimiter)?;
    (end >= start).then(|| {
        let flags = raw[end + 1..]
            .chars()
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .collect();
        (raw[start..end].to_owned(), flags)
    })
}

fn literal_string(raw: &str) -> Option<String> {
    let quote = raw.chars().next()?;
    if raw.len() < 2 || !matches!(quote, '\'' | '"') || !raw.ends_with(quote) {
        return None;
    }
    let mut chars = raw[1..raw.len() - 1].chars().peekable();
    let mut value = String::new();
    while let Some(ch) = chars.next() {
        if ch != '\\' {
            value.push(ch);
            continue;
        }
        let escaped = chars.next()?;
        match escaped {
            '\\' => value.push('\\'),
            c if c == quote => value.push(c),
            'n' if quote == '"' => value.push('\n'),
            'r' if quote == '"' => value.push('\r'),
            't' if quote == '"' => value.push('\t'),
            'u' if quote == '"' => value.push_str(&unicode_escape(&mut chars)?),
            c if quote == '\'' => {
                value.push('\\');
                value.push(c);
            }
            _ => return None,
        }
    }
    Some(value)
}

/// Decodes Unicode scalar escapes; Ruby does not use UTF-16 surrogate pairs.
fn unicode_escape(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Option<String> {
    let braced = chars.peek() == Some(&'{');
    let mut digits = String::new();
    if braced {
        chars.next();
        loop {
            let ch = chars.next()?;
            if ch == '}' {
                break;
            }
            if ch == '\n' {
                return None;
            }
            digits.push(ch);
        }
    } else {
        for _ in 0..4 {
            digits.push(chars.next()?);
        }
        if !digits.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
    }
    let mut decoded = String::new();
    for scalar in digits.split_ascii_whitespace() {
        if scalar.len() > 6 || !scalar.chars().all(|c| c.is_ascii_hexdigit()) {
            return None;
        }
        decoded.push(char::from_u32(u32::from_str_radix(scalar, 16).ok()?)?);
    }
    Some(decoded)
}

/// Full Unicode folds can consume multiple literal ASCII letters in Ruby, unlike Rust regex.
fn compatible_ignorecase_literal(pattern: &str) -> bool {
    let folded = pattern.to_ascii_lowercase();
    pattern.is_ascii()
        && !pattern.chars().any(|c| r"\.[](){}*+?|".contains(c))
        && !["ss", "ff", "fi", "fl", "st"]
            .iter()
            .any(|fold| folded.contains(fold))
}

/// Ruby line anchors are multiline by default; unsupported constructs never reach JS conversion.
pub(crate) fn regex_expression(pattern: &str, flags: &str) -> Option<String> {
    regex_expression_result(pattern, flags).ok()
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum RegexConversionError {
    PatternTooLong,
    CompiledTooBig,
    Unsupported,
}

fn regex_expression_result(pattern: &str, flags: &str) -> Result<String, RegexConversionError> {
    if pattern.len() > crate::resource_limits::MAX_REGEX_PATTERN_BYTES {
        return Err(RegexConversionError::PatternTooLong);
    }
    if flags
        .chars()
        .any(|flag| !matches!(flag, 'm' | 'i' | 'u' | 'n'))
        || (flags.contains('n') && (!pattern.is_ascii() || flags.contains('u')))
        || (flags.contains('i') && !compatible_ignorecase_literal(pattern))
        || pattern.contains("[[:")
        || pattern.contains("&&")
        || ["++", "*+", "?+", "}+"]
            .iter()
            .any(|operator| pattern.contains(operator))
    {
        return Err(RegexConversionError::Unsupported);
    }
    let mut result = String::from(if flags.contains('m') { "(?ms:" } else { "(?m:" });
    if flags.contains('i') {
        result.insert(2, 'i');
    }
    let mut chars = pattern.chars().peekable();
    let mut class_depth = 0;
    let mut first_class_member = false;
    let mut class_negated = false;
    let mut capture_names = std::collections::BTreeSet::new();
    let mut ordinary_captures = Vec::new();
    while let Some(ch) = chars.next() {
        let in_class = class_depth > 0;
        if ch == '{' && !in_class {
            if let Some(bound) =
                repetition_bound(&mut chars).ok_or(RegexConversionError::Unsupported)?
            {
                result.push('{');
                result.push_str(&bound);
                result.push('}');
            } else {
                result.push_str(r"\{");
            }
            continue;
        }
        if ch == '}' && !in_class {
            result.push_str(r"\}");
            continue;
        }
        if ch == '[' {
            class_depth += 1;
            first_class_member = true;
            class_negated = false;
        } else if in_class {
            if ch == ']' && !first_class_member {
                class_depth -= 1;
            } else if ch == '^' && first_class_member && !class_negated {
                class_negated = true;
            } else {
                first_class_member = false;
            }
        }

        if ch == '(' && !in_class {
            if chars.peek() != Some(&'?') {
                ordinary_captures.push(result.len() + 1);
            } else {
                chars.next();
                match chars.next().ok_or(RegexConversionError::Unsupported)? {
                    ':' => result.push_str("(?:"),
                    'm' if chars.next() == Some(':') => result.push_str("(?s:"),
                    delimiter @ ('<' | '\'') => {
                        let end = if delimiter == '<' { '>' } else { '\'' };
                        let mut name = String::new();
                        loop {
                            let member = chars.next().ok_or(RegexConversionError::Unsupported)?;
                            if member == end {
                                break;
                            }
                            if !(member.is_ascii_alphabetic()
                                || member == '_'
                                || (!name.is_empty() && member.is_ascii_digit()))
                            {
                                return Err(RegexConversionError::Unsupported);
                            }
                            name.push(member);
                        }
                        if name.is_empty() || !capture_names.insert(name) {
                            return Err(RegexConversionError::Unsupported);
                        }
                        result.push('(');
                    }
                    _ => return Err(RegexConversionError::Unsupported),
                }
                continue;
            }
        }
        if ch != '\\' {
            result.push(ch);
            continue;
        }
        let escaped = chars.next().ok_or(RegexConversionError::Unsupported)?;
        match escaped {
            'd' => result.push_str("[0-9]"),
            'D' => result.push_str("[^0-9]"),
            'w' => result.push_str("[A-Za-z0-9_]"),
            'W' => result.push_str("[^A-Za-z0-9_]"),
            's' => result.push_str(r"[ \t\r\n\x0c\x0b]"),
            'S' => result.push_str(r"[^ \t\r\n\x0c\x0b]"),
            'A' | 'z' | 'n' | 'r' | 't' | '\\' | '.' | '*' | '+' | '?' | '(' | ')' | '[' | ']'
            | '{' | '}' | '^' | '$' | '|' => {
                result.push('\\');
                result.push(escaped);
            }
            c if c.is_ascii_punctuation() || c == ' ' => {
                result.push_str(&regex::escape(&c.to_string()));
            }
            _ => return Err(RegexConversionError::Unsupported),
        }
    }
    // Ruby suppresses ordinary captures whenever the expression has a named capture.
    // Copy each segment once: inserting at every offset is quadratic for large patterns.
    if !capture_names.is_empty() {
        let mut rewritten = String::with_capacity(result.len() + ordinary_captures.len() * 2);
        let mut start = 0;
        for position in ordinary_captures {
            rewritten.push_str(&result[start..position]);
            rewritten.push_str("?:");
            start = position;
        }
        rewritten.push_str(&result[start..]);
        result = rewritten;
    }
    result.push(')');
    match crate::resource_limits::compile_regex(&result) {
        Ok(_) => Ok(result),
        Err(regex::Error::CompiledTooBig(_)) => Err(RegexConversionError::CompiledTooBig),
        Err(_) => Err(RegexConversionError::Unsupported),
    }
}

// Consume only Ruby repetition syntax. Other braces are literal; excessively long numeric
// bounds stay unsupported rather than spending unbounded work or treating a bound as text.
fn repetition_bound(
    chars: &mut std::iter::Peekable<std::str::Chars<'_>>,
) -> Option<Option<String>> {
    let mut probe = chars.clone();
    let mut bound = String::new();
    while let Some(ch) = probe.peek().copied() {
        if ch == '}' {
            let parts: Vec<_> = bound.split(',').collect();
            let valid = match parts.as_slice() {
                [count] => !count.is_empty(),
                [minimum, maximum] => !minimum.is_empty() || !maximum.is_empty(),
                _ => false,
            };
            if !valid {
                return Some(None);
            }
            probe.next();
            *chars = probe;
            if bound.starts_with(',') {
                bound.insert(0, '0');
            }
            return Some(Some(bound));
        }
        if !ch.is_ascii_digit() && ch != ',' {
            return Some(None);
        }
        if bound.len() >= 32 {
            return None;
        }
        bound.push(ch);
        probe.next();
    }
    Some(None)
}

fn location(file: &SourceFile, node: Node<'_>, source: &str) -> SourceLocation {
    let column = |byte: usize| {
        source[..byte]
            .rsplit('\n')
            .next()
            .unwrap_or("")
            .chars()
            .count()
            + 1
    };
    SourceLocation::new(
        &file.path,
        node.start_position().row + 1,
        column(node.start_byte()),
        node.end_position().row + 1,
        column(node.end_byte()),
    )
}

fn diagnostic(
    file: &SourceFile,
    node: Node<'_>,
    source: &str,
    kind: Kind,
    message: &str,
) -> ExtractionDiagnostic {
    ExtractionDiagnostic::with_kind(kind, Level::Warning, location(file, node, source), message)
}

#[cfg(test)]
mod tests;