rubylang 0.1.18

Ruby as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a RubyHost heap — the first compiled standalone Ruby runtime
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
//! Command-line interface for the `ruby` binary.
//!
//! `ruby(1)` has an option grammar clap cannot model faithfully — `-e` is
//! repeatable and switches off the program-file slot (the first non-switch token
//! then becomes `ARGV[0]`), short switches bundle (`-ne`, `-wc`), value switches
//! glue their argument (`-Idir`, `-rlib`), and everything after the program file
//! (or after `--`) is `ARGV`, not more switches. So this is a hand-rolled parser
//! that mirrors MRI's `proc_options`, plus rubylang's own long options
//! (`--repl`/`--lsp`/`--dap`/`--build`/`--dump-*`/`--disasm`).

/// The parsed command line. Boolean rubylang extensions keep their old names so
/// `main.rs` dispatch is unchanged; the MRI-compat fields are new.
#[derive(Debug, Default)]
pub struct Cli {
    // ---- MRI program selection --------------------------------------------
    /// `-e SRC` snippets, in order (MRI joins repeated `-e` with newlines).
    pub eval: Vec<String>,
    /// `-r LIB` libraries to `require` before the program runs.
    pub requires: Vec<String>,
    /// `-I DIR` directories prepended to `$LOAD_PATH`.
    pub includes: Vec<String>,
    /// The program file to run (`None` with `-e`, or when reading stdin).
    pub file: Option<String>,
    /// Arguments passed to the program as `ARGV`.
    pub argv: Vec<String>,

    // ---- MRI switches ------------------------------------------------------
    /// `-c` — check syntax only, print `Syntax OK`, do not run.
    pub check_syntax: bool,
    /// MRI verbosity level: 0 (`-W0`) → `$VERBOSE = nil`, 1 (no switch) →
    /// `false`, ≥2 (`-w`, `-v`, `-W2`…`-W7`, `--verbose`) → `true`. Switches
    /// ASSIGN this rather than raising it, because MRI is last-wins: `-w -W0`
    /// ends at `nil` and `-W0 -w` ends at `true`.
    pub warn_level: u8,
    /// `--enable`/`--disable-frozen-string-literal` (and the `--enable=…`,
    /// `all` and comma-list spellings): what a file with no
    /// `# frozen_string_literal:` comment compiles as. Last switch wins.
    pub frozen_string_literal: bool,
    /// Whether any such switch was given: without one, a file with no comment
    /// chills its literals (Ruby 3.4+).
    pub frozen_string_literal_switched: bool,
    /// `-n` — wrap the program in `while gets; … end`.
    pub loop_n: bool,
    /// `-p` — like `-n` but print `$_` at the end of each iteration.
    pub loop_p: bool,
    /// `-a` — autosplit each line into `$F` (with `-n`/`-p`).
    pub autosplit: bool,
    /// `-l` — chomp the input record separator on each `gets`.
    pub chomp: bool,
    /// `-F PAT` — the `$_.split` pattern for `-a`.
    pub field_sep: Option<String>,
    /// `-S` — search `$PATH` for the program file.
    pub search_path: bool,
    /// `-d`/`--debug` — set `$DEBUG`.
    pub debug: bool,
    /// `-v` — print the version banner, then run any program.
    pub verbose_version: bool,

    // ---- exit-early informational -----------------------------------------
    /// `--version` (or bare `-v` with no program) — print version and exit.
    pub show_version: bool,
    /// `--help`/`-h`.
    pub show_help: bool,

    /// Warnings the parser itself produced (today: `-W:` naming an unknown
    /// warning category). Collected rather than printed so parsing stays pure
    /// and testable; `main` writes them to stderr before the program runs.
    pub warnings: Vec<String>,

    // ---- rubylang extensions (unchanged) ----------------------------------
    pub repl: bool,
    pub lsp: bool,
    pub dap: bool,
    pub build: bool,
    pub native: bool,
    pub dump_bytecode: bool,
    pub dump_tokens: bool,
    pub dump_ast: bool,
    pub disasm: bool,
    /// `--tiers`: run the script, then report which fusevm tiers took its chunks.
    pub tiers: bool,
}

/// The level `-w`, `-v`, `-W` and `--verbose` all select: `$VERBOSE = true`.
const VERBOSE_LEVEL: u8 = 2;

/// The features `--enable` / `--disable` name, in MRI's own order — it prints
/// this list verbatim when it does not recognise one. Only
/// `frozen_string_literal` and `rubyopt` change anything here; the rest are
/// accepted so a command line written for MRI runs unaltered.
const FEATURES: &[&str] = &[
    "gems",
    "error_highlight",
    "did_you_mean",
    "syntax_suggest",
    "rubyopt",
    "frozen_string_literal",
    "yjit",
    "zjit",
];

/// Apply one `--enable`/`--disable` argument, which may be `all`, a single
/// feature, or a comma-separated list. Feature names are spelled with either
/// `_` or `-` (`--enable=frozen-string-literal` and `--enable-frozen_string_literal`
/// both work), so they are normalised before lookup.
///
/// An unrecognised name is a warning listing the known features, not an error:
/// MRI prints both lines and runs the program anyway (exit 0).
fn apply_feature(cli: &mut Cli, arg: &str, on: bool, switch: &str) {
    for raw in arg.split(',') {
        let feature = raw.trim().replace('-', "_");
        if feature == "all" {
            cli.frozen_string_literal = on;
            cli.frozen_string_literal_switched = true;
            // `rubyopt` is deliberately NOT toggled by `all`: it is answered by
            // the pre-scan below, before this parser ever runs.
            continue;
        }
        if !FEATURES.contains(&feature.as_str()) {
            cli.warnings
                .push(format!("warning: unknown argument for --{switch}: '{raw}'"));
            cli.warnings
                .push(format!("warning: features are [{}].", FEATURES.join(", ")));
            continue;
        }
        if feature == "frozen_string_literal" {
            cli.frozen_string_literal = on;
            cli.frozen_string_literal_switched = true;
        }
        // Every other feature is accepted with no effect: rubylang has no
        // RubyGems to disable, no YJIT/ZJIT, and no did_you_mean/error_highlight
        // machinery for the switch to turn off.
    }
}

/// Does this command line ask for `RUBYOPT` to be ignored?
///
/// This has to be answered before the ordinary parse, because it decides
/// whether `RUBYOPT` contributes any switches at all — so it reads the raw
/// argument vector rather than a parsed `Cli`. Only the disabling spellings
/// matter; `rubyopt` is on unless something turns it off.
fn rubyopt_disabled(args: &[String]) -> bool {
    args.iter().any(|a| {
        let Some(long) = a.strip_prefix("--disable") else {
            return false;
        };
        let arg = match long.strip_prefix(['-', '=']) {
            Some(rest) => rest,
            None => return false,
        };
        arg.split(',')
            .any(|f| matches!(f.trim().replace('-', "_").as_str(), "rubyopt" | "all"))
    })
}

// The warning categories `-W:` and `-W:no-` accept are MRI's (the list
// `Warning.categories` answers). An unrecognised one is a warning, not an
// error, and leaves the level alone. Verified against MRI 4.0.6: `-W:foo`
// prints `warning: unknown warning category: 'foo'` and runs.
use crate::host::WARNING_CATEGORIES;

/// Short switches MRI accepts inside `RUBYOPT`. Every other switch is rejected
/// there even though it is valid on the command line, because `RUBYOPT` is
/// ambient: a stray `-e` in the environment would silently replace the program.
/// MRI's `proc_options` marks the rest `noenvopt`. Verified against MRI 4.0.6 —
/// `-a`/`-n`/`-p`/`-l`/`-c`/`-S`/`-x`/`-0`/`-e` all answer
/// `invalid switch in RUBYOPT`, while these nine run.
const ENV_SHORT: &str = "IdvwWrKUE";

/// Short switches in [`ENV_SHORT`] that swallow the rest of their token (a
/// value, or `-W`'s level digit / `:category`), so the characters after them
/// are an argument and must not be checked as further switches.
const ENV_SHORT_TAKES_REST: &str = "IrEW";

/// `--long` switches MRI accepts inside `RUBYOPT`, beyond the `--enable-*` /
/// `--disable-*` families. `--version` and `--help` are rejected there.
const ENV_LONG: &[&str] = &["verbose", "debug"];

/// Split `RUBYOPT` into switch tokens, rejecting any MRI would not honour.
///
/// The tokens are returned rather than applied so they can be placed *before*
/// the real command line, which is where MRI puts them: an explicit `-W0` on
/// the command line overrides a `-w` from the environment, not the reverse.
pub fn split_env_options(rubyopt: &str) -> Result<Vec<String>, String> {
    let bad = |tok: &str| format!("invalid switch in RUBYOPT: {tok}");
    let mut out = Vec::new();
    for tok in rubyopt.split_whitespace() {
        if let Some(long) = tok.strip_prefix("--") {
            let name = long.split_once('=').map_or(long, |(n, _)| n);
            let ok = ENV_LONG.contains(&name)
                || name.starts_with("enable-")
                || name.starts_with("disable-");
            if !ok {
                return Err(bad(tok));
            }
        } else if let Some(short) = tok.strip_prefix('-') {
            if short.is_empty() {
                return Err(bad(tok));
            }
            for c in short.chars() {
                if !ENV_SHORT.contains(c) {
                    return Err(bad(&format!("-{c}")));
                }
                if ENV_SHORT_TAKES_REST.contains(c) {
                    break;
                }
            }
        } else {
            // A bare word in RUBYOPT would be a program file or an argument;
            // neither can come from the environment.
            return Err(bad(tok));
        }
        out.push(tok.to_string());
    }
    Ok(out)
}

/// Parse the real process arguments (skipping `argv[0]`), with any `RUBYOPT`
/// switches applied first.
pub fn parse() -> Result<Cli, String> {
    let argv: Vec<String> = std::env::args().skip(1).collect();
    // `--disable-rubyopt` decides whether RUBYOPT is read at all, so it has to
    // be seen before the switches RUBYOPT would contribute.
    let use_env = !rubyopt_disabled(&argv);
    let mut args = match std::env::var("RUBYOPT") {
        Ok(opt) if use_env => split_env_options(&opt)?,
        _ => Vec::new(),
    };
    args.extend(argv);
    parse_args(args)
}

/// Parse an explicit argument vector (testable, no `argv[0]`).
pub fn parse_args(args: Vec<String>) -> Result<Cli, String> {
    let mut cli = Cli {
        warn_level: crate::DEFAULT_WARN_LEVEL,
        ..Cli::default()
    };
    let mut it = args.into_iter().peekable();

    // Phase 1: switches, until the first non-switch token, `--`, `-`, or a token
    // consumed as the program file.
    while let Some(tok) = it.peek() {
        if tok == "--" {
            it.next();
            break;
        }
        if tok == "-" {
            // A bare `-` means read the program from stdin; it is the "file".
            it.next();
            cli.file = Some("-".to_string());
            break;
        }
        if let Some(long) = tok.strip_prefix("--") {
            let long = long.to_string();
            it.next();
            apply_long(&mut cli, &long)?;
            continue;
        }
        if let Some(short) = tok.strip_prefix('-') {
            if short.is_empty() {
                break;
            }
            let short = short.to_string();
            it.next();
            // A short cluster may consume the next token (for `-e`/`-I`/`-r`/`-F`
            // with a detached argument). Switch scanning continues even after
            // `-e` — MRI keeps parsing switches (more `-e`/`-r`/…) until the first
            // non-switch token, which then becomes ARGV.
            apply_short_cluster(&mut cli, &short, &mut it)?;
            continue;
        }
        // First non-switch token. With `-e` there is no program file, so it (and
        // the rest) is ARGV; otherwise it is the program file.
        if cli.eval.is_empty() {
            cli.file = Some(it.next().unwrap());
        }
        break;
    }

    // With `-e`, the program is the snippets and there is no file; everything
    // left (after `--` or the first non-switch token) is ARGV.
    if !cli.eval.is_empty() {
        cli.argv = it.collect();
        return Ok(cli);
    }
    if cli.file.is_none() {
        // `--` with a following file, or a program file after long switches.
        if let Some(next) = it.next() {
            cli.file = Some(next);
        }
    }
    cli.argv = it.collect();
    Ok(cli)
}

/// A `--long` option (rubylang extensions plus a few MRI long forms).
fn apply_long(cli: &mut Cli, long: &str) -> Result<(), String> {
    // `--name=value` split (`--enable=…`/`--disable=…`, and `--dump=`).
    let (name, val) = long.split_once('=').unwrap_or((long, ""));
    // Feature switches come in four spellings: `--enable=X`, `--disable=X`,
    // `--enable-X`, `--disable-X`. The first two arrive with the feature in
    // `val`, the last two with it glued to the switch name.
    for (prefix, on) in [("enable", true), ("disable", false)] {
        if name == prefix {
            apply_feature(cli, val, on, prefix);
            return Ok(());
        }
        if let Some(feature) = name.strip_prefix(prefix).and_then(|r| r.strip_prefix('-')) {
            apply_feature(cli, feature, on, prefix);
            return Ok(());
        }
    }
    match name {
        "version" => cli.show_version = true,
        "help" => cli.show_help = true,
        "repl" => cli.repl = true,
        "lsp" => cli.lsp = true,
        "dap" => cli.dap = true,
        "build" => cli.build = true,
        "native" => cli.native = true,
        "dump-bytecode" => cli.dump_bytecode = true,
        "dump-tokens" => cli.dump_tokens = true,
        "dump-ast" => cli.dump_ast = true,
        "disasm" => cli.disasm = true,
        "tiers" => cli.tiers = true,
        // Accepted for compat, no effect: no external encodings to select.
        "dump" => {}
        "debug" => cli.debug = true,
        "verbose" => cli.warn_level = VERBOSE_LEVEL,
        "copyright" => cli.show_version = true,
        other => return Err(format!("invalid option --{other}")),
    }
    Ok(())
}

/// A bundled short-switch token (already stripped of its leading `-`). Value
/// switches (`-e`/`-I`/`-r`/`-F`/`-C`/`-E`) consume the glued remainder or the
/// next token and end the cluster.
fn apply_short_cluster(
    cli: &mut Cli,
    cluster: &str,
    it: &mut std::iter::Peekable<std::vec::IntoIter<String>>,
) -> Result<(), String> {
    let bytes: Vec<char> = cluster.chars().collect();
    let mut i = 0;
    while i < bytes.len() {
        let c = bytes[i];
        // The remainder of this token, after the current flag char.
        let rest: String = bytes[i + 1..].iter().collect();
        // For a value flag, the argument is the glued remainder or the next token.
        let take_arg = |rest: &str, it: &mut std::iter::Peekable<std::vec::IntoIter<String>>| {
            if !rest.is_empty() {
                Some(rest.to_string())
            } else {
                it.next()
            }
        };
        match c {
            'e' => {
                let arg =
                    take_arg(&rest, it).ok_or_else(|| "no code specified for -e".to_string())?;
                cli.eval.push(arg);
                return Ok(());
            }
            'I' => {
                let arg =
                    take_arg(&rest, it).ok_or_else(|| "missing argument for -I".to_string())?;
                cli.includes.push(arg);
                return Ok(());
            }
            'r' => {
                let arg =
                    take_arg(&rest, it).ok_or_else(|| "missing argument for -r".to_string())?;
                cli.requires.push(arg);
                return Ok(());
            }
            'F' => {
                let arg =
                    take_arg(&rest, it).ok_or_else(|| "missing argument for -F".to_string())?;
                cli.field_sep = Some(arg);
                cli.autosplit = true;
                return Ok(());
            }
            'c' => cli.check_syntax = true,
            // `-w` is `$VERBOSE = true`, i.e. level 2 — the same state `-W2`
            // names. It is an assignment, not a raise: `-w -W0` ends at `nil`.
            'w' => cli.warn_level = VERBOSE_LEVEL,
            'W' => {
                // `-W:category` selects a warning category instead of a level.
                // The category runs to the end of the token.
                if bytes.get(i + 1) == Some(&':') {
                    let cat: String = bytes[i + 2..].iter().collect();
                    if !WARNING_CATEGORIES.contains(&cat.trim_start_matches("no-")) {
                        cli.warnings
                            .push(format!("warning: unknown warning category: '{cat}'"));
                    }
                    return Ok(());
                }
                // `-W`, `-W0`…`-W7`. MRI scans the level with `scan_oct`, so 8
                // and 9 are NOT digits here: the `W` takes its default level and
                // the stray digit is re-read as its own (invalid) switch.
                match bytes.get(i + 1).and_then(|d| d.to_digit(8)) {
                    Some(n) => {
                        cli.warn_level = n as u8;
                        i += 1;
                    }
                    None => cli.warn_level = VERBOSE_LEVEL,
                }
            }
            'n' => cli.loop_n = true,
            'p' => cli.loop_p = true,
            'a' => cli.autosplit = true,
            'l' => cli.chomp = true,
            'S' => cli.search_path = true,
            'd' => cli.debug = true,
            // `-v` prints the banner AND runs verbosely — it is `--verbose` with
            // a version line, not a bare informational switch.
            'v' => {
                cli.verbose_version = true;
                cli.warn_level = VERBOSE_LEVEL;
            }
            'h' => cli.show_help = true,
            // `-0`, `-K`, `-U`, `-T`, `-x` are accepted but inert: rubylang is
            // UTF-8 only, untainted, and has no `$/` override yet.
            '0' | 'K' | 'U' | 'T' | 'x' => {}
            'C' | 'E' => {
                // Value flags accepted for compat; argument consumed, ignored.
                let _ = take_arg(&rest, it);
                return Ok(());
            }
            other => return Err(format!("invalid option -{other}")),
        }
        i += 1;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::DEFAULT_WARN_LEVEL;

    fn p(args: &[&str]) -> Cli {
        parse_args(args.iter().map(|s| s.to_string()).collect()).unwrap()
    }

    #[test]
    fn eval_takes_argv_not_file() {
        // `-e` switches off the program-file slot: trailing tokens are ARGV.
        let c = p(&["-e", "p ARGV", "one", "two"]);
        assert_eq!(c.eval, ["p ARGV"]);
        assert_eq!(c.file, None);
        assert_eq!(c.argv, ["one", "two"]);
    }

    #[test]
    fn multiple_e_snippets_kept_in_order() {
        let c = p(&["-e", "x=1", "-e", "p x"]);
        assert_eq!(c.eval, ["x=1", "p x"]);
        assert!(c.argv.is_empty());
    }

    #[test]
    fn double_dash_ends_options() {
        let c = p(&["-e", "p ARGV", "--", "-x", "-y"]);
        assert_eq!(c.argv, ["-x", "-y"]);
    }

    #[test]
    fn glued_and_detached_value_switches() {
        let c = p(&["-Ilib", "-I", "vendor", "-rfoo", "-r", "bar", "-e", "0"]);
        assert_eq!(c.includes, ["lib", "vendor"]);
        assert_eq!(c.requires, ["foo", "bar"]);
    }

    #[test]
    fn bundled_boolean_switches() {
        // Both flags in the cluster take effect. `-w` is the verbose level, not
        // level 1: MRI 4.0.6 answers `true` for `ruby -w -e 'p $VERBOSE'`, and
        // level 1 is `false`.
        let c = p(&["-wc", "-e", "0"]);
        assert_eq!(c.warn_level, VERBOSE_LEVEL);
        assert!(c.check_syntax);
    }

    #[test]
    fn bundled_flag_then_e_takes_next_token() {
        // `-ne 'code'` == `-n -e 'code'`; the `-e` arg is the next token.
        let c = p(&["-ne", "p 1"]);
        assert!(c.loop_n);
        assert_eq!(c.eval, ["p 1"]);
    }

    #[test]
    fn warning_level_digit() {
        assert_eq!(p(&["-W0", "-e", "0"]).warn_level, 0);
        assert_eq!(p(&["-W2", "-e", "0"]).warn_level, 2);
        assert_eq!(p(&["-W", "-e", "0"]).warn_level, 2);
    }

    #[test]
    fn no_switch_is_level_one_not_zero() {
        // The state MRI starts in is `$VERBOSE = false` (level 1). Level 0 is
        // `nil` and is reachable only by asking: a derived `Default` would make
        // "no switch" and `-W0` the same state.
        assert_eq!(p(&["-e", "0"]).warn_level, DEFAULT_WARN_LEVEL);
        assert_eq!(DEFAULT_WARN_LEVEL, 1);
        assert_ne!(
            p(&["-e", "0"]).warn_level,
            p(&["-W0", "-e", "0"]).warn_level
        );
    }

    #[test]
    fn verbose_switches_all_reach_the_same_level() {
        for args in [
            vec!["-w", "-e", "0"],
            vec!["-v", "-e", "0"],
            vec!["--verbose", "-e", "0"],
            vec!["-W", "-e", "0"],
            vec!["-W2", "-e", "0"],
        ] {
            assert_eq!(p(&args).warn_level, VERBOSE_LEVEL, "{args:?}");
        }
        // `-v` also still asks for the banner.
        assert!(p(&["-v", "-e", "0"]).verbose_version);
    }

    #[test]
    fn warning_level_is_last_wins_not_highest() {
        // MRI 4.0.6: `-w -W0` → nil, `-W0 -w` → true, `-w -W1` → false. A `max`
        // would make all three `true`.
        assert_eq!(p(&["-w", "-W0", "-e", "0"]).warn_level, 0);
        assert_eq!(p(&["-W0", "-w", "-e", "0"]).warn_level, VERBOSE_LEVEL);
        assert_eq!(p(&["-w", "-W1", "-e", "0"]).warn_level, 1);
        assert_eq!(p(&["-W2", "-W0", "-e", "0"]).warn_level, 0);
    }

    #[test]
    fn warning_level_digit_is_octal() {
        // MRI scans the `-W` level with `scan_oct`, so 0..=7 are levels…
        for n in 0..=7u8 {
            assert_eq!(p(&[&format!("-W{n}"), "-e", "0"]).warn_level, n);
        }
        // …and 8/9 are not digits at all: `-W` takes its default and the stray
        // character is re-read as its own switch, which is invalid.
        for bad in ["-W8", "-W9"] {
            assert!(
                parse_args(vec![bad.to_string(), "-e".into(), "0".into()]).is_err(),
                "{bad} should be rejected"
            );
        }
    }

    #[test]
    fn warning_category_switch_does_not_change_the_level() {
        let c = p(&["-W:no-deprecated", "-e", "0"]);
        assert_eq!(c.warn_level, DEFAULT_WARN_LEVEL);
        assert!(c.warnings.is_empty());
        // An unknown category warns but still runs.
        let c = p(&["-W:bogus", "-e", "0"]);
        assert_eq!(c.warn_level, DEFAULT_WARN_LEVEL);
        assert_eq!(c.warnings, ["warning: unknown warning category: 'bogus'"]);
    }

    #[test]
    fn rubyopt_accepts_only_the_switches_mri_allows() {
        // Verified against MRI 4.0.6 by setting RUBYOPT and reading the result.
        for ok in [
            "-w", "-W0", "-v", "-d", "-I/tmp", "-rjson", "-K", "-U", "-E:UTF-8",
        ] {
            assert!(split_env_options(ok).is_ok(), "{ok} should be allowed");
        }
        for bad in ["-a", "-n", "-p", "-l", "-c", "-S", "-x", "-0", "-e"] {
            let err = split_env_options(bad).unwrap_err();
            assert_eq!(err, format!("invalid switch in RUBYOPT: {bad}"));
        }
        // Long switches: the enable/disable families and these two only.
        for ok in [
            "--verbose",
            "--debug",
            "--disable-gems",
            "--enable-frozen-string-literal",
        ] {
            assert!(split_env_options(ok).is_ok(), "{ok} should be allowed");
        }
        for bad in ["--version", "--help"] {
            assert!(split_env_options(bad).is_err(), "{bad} should be rejected");
        }
        // A bare word could only be a program file; the environment cannot name one.
        assert!(split_env_options("script.rb").is_err());
    }

    #[test]
    fn rubyopt_switches_lose_to_the_command_line() {
        // MRI applies RUBYOPT first, so an explicit switch overrides it:
        // `RUBYOPT=-w ruby -W0 -e 'p $VERBOSE'` prints nil.
        let mut args = split_env_options("-w").unwrap();
        args.extend(["-W0", "-e", "0"].iter().map(|s| s.to_string()));
        assert_eq!(parse_args(args).unwrap().warn_level, 0);
        // …and with nothing overriding it, the environment switch stands.
        let mut args = split_env_options("-w -I/tmp").unwrap();
        args.extend(["-e", "0"].iter().map(|s| s.to_string()));
        let c = parse_args(args).unwrap();
        assert_eq!(c.warn_level, VERBOSE_LEVEL);
        assert_eq!(c.includes, ["/tmp"]);
    }

    #[test]
    fn file_mode_takes_first_positional_then_argv() {
        let c = p(&["script.rb", "a", "b"]);
        assert_eq!(c.file.as_deref(), Some("script.rb"));
        assert_eq!(c.argv, ["a", "b"]);
    }

    #[test]
    fn switches_before_file() {
        let c = p(&["-w", "-Ilib", "script.rb", "arg"]);
        assert_eq!(c.warn_level, VERBOSE_LEVEL);
        assert_eq!(c.includes, ["lib"]);
        assert_eq!(c.file.as_deref(), Some("script.rb"));
        assert_eq!(c.argv, ["arg"]);
    }

    #[test]
    fn bare_dash_is_stdin_program() {
        let c = p(&["-", "arg"]);
        assert_eq!(c.file.as_deref(), Some("-"));
        assert_eq!(c.argv, ["arg"]);
    }

    #[test]
    fn unknown_switch_is_error() {
        assert!(parse_args(vec!["-Z".to_string()]).is_err());
        assert!(parse_args(vec!["--bogus".to_string()]).is_err());
    }

    #[test]
    fn frozen_string_literal_has_four_spellings() {
        // MRI accepts the feature glued to the switch or after an `=`, and
        // spells the name with either `-` or `_`. All four mean the same thing.
        for on in [
            "--enable-frozen-string-literal",
            "--enable=frozen-string-literal",
            "--enable-frozen_string_literal",
            "--enable=frozen_string_literal",
        ] {
            assert!(p(&[on, "-e", "0"]).frozen_string_literal, "{on}");
        }
        for off in [
            "--disable-frozen-string-literal",
            "--disable=frozen-string-literal",
        ] {
            assert!(!p(&[off, "-e", "0"]).frozen_string_literal, "{off}");
        }
        // `all` reaches it, and a comma list is applied item by item.
        assert!(p(&["--enable=all", "-e", "0"]).frozen_string_literal);
        assert!(p(&["--enable-all", "-e", "0"]).frozen_string_literal);
        assert!(!p(&["--disable=all", "-e", "0"]).frozen_string_literal);
        assert!(p(&["--enable=frozen-string-literal,gems", "-e", "0"]).frozen_string_literal);
    }

    #[test]
    fn the_last_feature_switch_wins() {
        let on = "--enable-frozen-string-literal";
        let off = "--disable-frozen-string-literal";
        assert!(!p(&[on, off, "-e", "0"]).frozen_string_literal);
        assert!(p(&[off, on, "-e", "0"]).frozen_string_literal);
        // …including when the earlier one arrived via `all`.
        assert!(!p(&["--enable=all", off, "-e", "0"]).frozen_string_literal);
    }

    #[test]
    fn an_unknown_feature_warns_and_lists_the_known_ones() {
        // MRI prints two lines and still runs the program, so this must not be
        // an error. The second line is the feature list verbatim.
        let c = p(&["--enable=fsl", "-e", "0"]);
        assert_eq!(
            c.warnings,
            [
                "warning: unknown argument for --enable: 'fsl'".to_string(),
                format!("warning: features are [{}].", FEATURES.join(", ")),
            ]
        );
        // The switch name in the message follows the switch that was used.
        let c = p(&["--disable=nope", "-e", "0"]);
        assert!(c.warnings[0].contains("for --disable: 'nope'"));
        // A known feature we do not act on is silent, not a warning.
        assert!(p(&["--disable-gems", "-e", "0"]).warnings.is_empty());
        assert!(p(&["--enable=yjit", "-e", "0"]).warnings.is_empty());
    }

    #[test]
    fn disable_rubyopt_is_read_from_the_raw_argument_vector() {
        // It decides whether RUBYOPT contributes switches at all, so it cannot
        // be answered from a parsed `Cli` that RUBYOPT already fed into.
        let v = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
        assert!(rubyopt_disabled(&v(&["--disable-rubyopt", "-e", "0"])));
        assert!(rubyopt_disabled(&v(&["--disable=rubyopt", "-e", "0"])));
        assert!(rubyopt_disabled(&v(&["--disable=all", "-e", "0"])));
        assert!(rubyopt_disabled(&v(&["--disable=gems,rubyopt", "-e", "0"])));
        assert!(!rubyopt_disabled(&v(&["--enable-rubyopt", "-e", "0"])));
        assert!(!rubyopt_disabled(&v(&["--disable-gems", "-e", "0"])));
        assert!(!rubyopt_disabled(&v(&["-e", "0"])));
    }

    #[test]
    fn long_extensions_still_parse() {
        assert!(p(&["--repl"]).repl);
        assert!(p(&["--version"]).show_version);
        assert!(p(&["--dump-ast", "x.rb"]).dump_ast);
    }
}