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
//! rubylang — Ruby as a fusevm frontend.
//!
//! Pipeline: `lexer` → `parser` builds a Ruby AST → `compiler` lowers it to a
//! `fusevm::Chunk` (plus a table of method/block sub-chunks) → fusevm executes
//! it, calling back into the `host` (through registered builtins and the strict
//! numeric hook) for every Ruby-specific operation. There is no bespoke VM or
//! JIT here — execution and codegen live in fusevm.

pub mod aot;
pub mod arity_table;
pub mod ast;
pub mod banner;
pub mod builtins;
pub mod bundle;
pub mod cache;
pub mod cli;
pub mod compiler;
pub mod dap;
pub mod embed;
pub mod encoding_table;
pub mod erb;
pub mod host;
pub mod intercepts;
pub mod lexer;
pub mod lsp;
pub mod oracle;
pub mod parser;
pub mod pp;
pub mod private_builtins;
pub mod random;
pub mod repl;
pub mod rstr;
pub mod rtime;
pub mod rust_ffi;
pub mod tiers;
pub mod unicode_tables;

pub use embed::run_program;
pub use fusevm::Value;

/// The MRI language level rubylang targets — the value reported as `RUBY_VERSION`
/// and in `ruby --version`. Gems test this against `required_ruby_version`.
pub const RUBY_COMPAT_VERSION: &str = "3.4.0";
/// `RUBY_ENGINE` — rubylang is its own engine (like `jruby`/`truffleruby`), so
/// engine-sniffing code can tell it apart from MRI.
pub const RUBY_ENGINE: &str = "rubylang";
/// `RUBY_ENGINE_VERSION` — this crate's own version.
pub const RUBY_ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// The `RUBY_PLATFORM` string, built from the host arch/OS.
pub fn ruby_platform() -> String {
    format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
}

/// The `ruby --version` / `-v` banner. Starts with `ruby <X.Y.Z>` so tools that
/// parse the version line (rbenv/chruby/bundler) read the compat level, then
/// names the real engine so nothing is misrepresented as MRI.
pub fn version_banner() -> String {
    format!(
        "ruby {} (rubylang {}) [{}]",
        RUBY_COMPAT_VERSION,
        RUBY_ENGINE_VERSION,
        ruby_platform()
    )
}

/// The warning level of an interpreter started with no `-w`/`-W`/`-v` switch.
///
/// MRI's default is level 1 — `$VERBOSE` is `false`, not `nil`. Level 0 is
/// reachable only by asking for it with `-W0`, so "no switch given" and `-W0`
/// are *different* states and cannot share the zero value a derived `Default`
/// would hand out. Verified against MRI 4.0.6:
///
/// ```text
/// $ /opt/homebrew/opt/ruby/bin/ruby     -e 'p $VERBOSE'   # false
/// $ /opt/homebrew/opt/ruby/bin/ruby -W0 -e 'p $VERBOSE'   # nil
/// ```
pub const DEFAULT_WARN_LEVEL: u8 = 1;

/// Program-invocation configuration threaded in from the command line: `ARGV`,
/// `-I` load-path prepends, `-r` requires, and the `$0` script name.
pub struct RunConfig {
    pub argv: Vec<String>,
    pub includes: Vec<String>,
    pub requires: Vec<String>,
    pub script_name: String,
    /// MRI verbosity level: 0 → `$VERBOSE = nil`, 1 → `false`, ≥2 → `true`.
    /// Defaults to [`DEFAULT_WARN_LEVEL`], never to 0.
    pub warn_level: u8,
    /// `-d`/`--debug` → `$DEBUG`.
    pub debug: bool,
    /// `--enable`/`--disable-frozen-string-literal`: what a file with no
    /// `# frozen_string_literal:` comment compiles as. MRI's default is off.
    pub frozen_string_literal: bool,
    /// Whether an `--enable`/`--disable-frozen-string-literal` switch was
    /// given at all. Without one, a file with no comment chills its literals.
    pub frozen_string_literal_switched: bool,
    /// Report a script that does not parse the way the `ruby` command does —
    /// `<script>: <message> (SyntaxError)` — rather than as the bare parser
    /// message an embedder gets.
    pub report_syntax_errors: bool,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            argv: Vec::new(),
            includes: Vec::new(),
            requires: Vec::new(),
            script_name: String::new(),
            warn_level: DEFAULT_WARN_LEVEL,
            debug: false,
            frozen_string_literal: false,
            frozen_string_literal_switched: false,
            report_syntax_errors: false,
        }
    }
}

/// `$VERBOSE` for a warning level: `-W0` silences to `nil`, level 1 (the
/// default) is `false`, and `-w`/`-v`/`-W2` and above are `true`. MRI scans the
/// `-W` digit as OCTAL, so levels up to 7 are reachable and all of 2..=7 mean
/// `true`.
fn verbose_for_level(level: u8) -> Value {
    // Ruby `nil` is `Value::Undef` in this runtime.
    match level {
        0 => Value::Undef,
        1 => Value::Bool(false),
        _ => Value::Bool(true),
    }
}

/// Seed `$VERBOSE`/`$DEBUG` from the warning level and debug flag, and install
/// the invocation-wide frozen-string-literal default. Called by every run entry
/// point before anything compiles, since `compile` reads that default.
fn seed_verbosity(cfg: &RunConfig) {
    let verbose = verbose_for_level(cfg.warn_level);
    host::with_host(|h| {
        h.set_global("VERBOSE", verbose);
        h.set_global("DEBUG", Value::Bool(cfg.debug));
    });
    host::reset_warning_categories(cfg.warn_level);
    compiler::set_default_frozen_string_literals(cfg.frozen_string_literal);
    compiler::set_default_chilled_string_literals(!cfg.frozen_string_literal_switched);
}

/// Compile a source string to a runnable program.
///
/// A `# frozen_string_literal:` magic comment always wins; the
/// `--enable`/`--disable-frozen-string-literal` switch only decides what a file
/// WITHOUT one compiles as. Verified against MRI 4.0.6: with
/// `--enable-frozen-string-literal`, a file whose comment says `false` still
/// gets unfrozen literals.
pub fn compile(src: &str) -> Result<compiler::Program, String> {
    let comment = frozen_string_literal_comment(src);
    let frozen = comment.unwrap_or_else(compiler::default_frozen_string_literals);
    compiler::set_frozen_string_literals(frozen);
    // Ruby 3.4+: with neither a comment nor a switch, literals are chilled.
    compiler::set_chilled_string_literals(
        comment.is_none() && compiler::default_chilled_string_literals(),
    );
    let stmts = parser::parse(src)?;
    compiler::compile(&stmts, false)
}

/// Read a `# frozen_string_literal:` magic comment: `Some(true)`/`Some(false)`
/// when the file states one, `None` when it does not.
///
/// MRI honours the comment only in the leading comment block (after an optional
/// shebang) and stops at the first line of code. The distinction between
/// `Some(false)` and `None` is load-bearing, because only the former overrides
/// the command-line switch. A value that is neither `true` nor `false` is not a
/// setting at all — MRI ignores it and the switch still applies:
///
/// ```text
/// $ cat bogus.rb
/// # frozen_string_literal: bogus
/// p "x".frozen?
/// $ /opt/homebrew/opt/ruby/bin/ruby                                bogus.rb  # false
/// $ /opt/homebrew/opt/ruby/bin/ruby --enable-frozen-string-literal bogus.rb  # true
/// ```
fn frozen_string_literal_comment(src: &str) -> Option<bool> {
    for (i, line) in src.lines().enumerate() {
        let t = line.trim();
        if t.is_empty() {
            continue;
        }
        if i == 0 && t.starts_with("#!") {
            continue; // shebang
        }
        let Some(rest) = t.strip_prefix('#') else {
            break; // first non-comment line ends the magic-comment region
        };
        // Accept `# frozen_string_literal: true` and `-*- … -*-` emacs form.
        if let Some(after) = rest.split("frozen_string_literal:").nth(1) {
            let value = after.trim_start().trim_end_matches("-*-").trim();
            return match value {
                v if v.starts_with("true") => Some(true),
                v if v.starts_with("false") => Some(false),
                _ => None,
            };
        }
    }
    None
}

/// Compile with per-statement DAP line markers enabled (`ruby --dap`).
pub fn compile_debug(src: &str) -> Result<compiler::Program, String> {
    let stmts = parser::parse(src)?;
    compiler::compile(&stmts, true)
}

/// Parse, compile, load, and run a Ruby source string on a fresh host; return
/// the value of the last top-level expression. `$LOAD_PATH`/`$LOADED_FEATURES`
/// and the `require` file-dir stack are seeded with the current directory so a
/// `require`/`require_relative` from a `-e` one-liner resolves against it.
pub fn eval_str(src: &str) -> Result<Value, String> {
    eval_str_cfg(src, &RunConfig::default())
}

/// `eval_str` with command-line configuration: seeds `-I` includes, `ARGV`/`$0`,
/// runs `-r` requires, then the one-liner. `$0`/`__FILE__` default to `-e`.
pub fn eval_str_cfg(src: &str, cfg: &RunConfig) -> Result<Value, String> {
    // Install a fresh per-run VM BEFORE taking the GVL: `reset_host` swaps the
    // thread's current VM, which must not happen while a guard into the old one
    // is live (see the invariant on `gvl_enter`).
    host::reset_host();
    // Hold the GVL for the whole run so heap access stays exclusive and any
    // `Thread` spawned inside contends on the same lock (MRI's model).
    host::with_gvl(|| {
        let cwd = std::env::current_dir().unwrap_or_default();
        host::with_host(|h| h.init_load_path(&cwd.to_string_lossy()));
        host::with_host(|h| h.prepend_load_path(&cfg.includes));
        host::push_file_dir(cwd);
        let name = if cfg.script_name.is_empty() {
            "-e".to_string()
        } else {
            cfg.script_name.clone()
        };
        // A `-e` one-liner has no script file; MRI reports `__FILE__` as "-e".
        host::push_file_path(name.clone());
        host::with_host(|h| h.set_program_args(&cfg.argv, &name));
        seed_verbosity(cfg);
        run_prelude()?;
        run_requires(&cfg.requires)?;
        end_program(run_compiled(
            compile(src).map_err(|e| syntax_report(cfg, &name, e))?,
        ))
    })
}

/// Run Ruby source on a fresh host with `globals` bound and the program's
/// output captured in-process, returning the program's outcome alongside
/// everything it wrote.
///
/// This is the entry point for an embedder rather than for the `ruby` binary,
/// and it exists because [`eval_str`] cannot serve one: it resets the host
/// first, which wipes any global installed beforehand, and it lets `puts` reach
/// the real stdout, which corrupts a host that owns the terminal. Both are
/// fixed here — the globals are seeded *after* the reset, and every write the
/// program makes lands in the returned string.
///
/// Globals are given as text (bound as local-scope names, so `stdin` reads as
/// an ordinary variable) and interned as real `String` objects here. They are
/// deliberately not `Value`: strings live on this host's heap as `RObj::Str`,
/// so a `Value::Str` a caller builds is not a Ruby string and answers no
/// methods.
///
/// The outcome and the output are returned separately (rather than the output
/// only on success) because a program that prints and *then* raises produced
/// both, and an embedder generally wants to show both.
///
/// ```no_run
/// let (result, out) = rubylang::eval_str_captured("puts stdin.upcase", &[("stdin", "hi")]);
/// assert!(result.is_ok());
/// assert_eq!(out, "HI\n");
/// ```
pub fn eval_str_captured(src: &str, globals: &[(&str, &str)]) -> (Result<Value, String>, String) {
    eval_captured(src, globals, host::StdinSource::Process)
}

/// [`eval_str_captured`] with the program's standard input read from `stdin`.
pub(crate) fn eval_captured(
    src: &str,
    globals: &[(&str, &str)],
    stdin: host::StdinSource,
) -> (Result<Value, String>, String) {
    host::reset_host();
    host::with_host(|h| h.stdin = stdin);
    let result = host::with_gvl(|| {
        let cwd = std::env::current_dir().unwrap_or_default();
        host::with_host(|h| h.init_load_path(&cwd.to_string_lossy()));
        host::push_file_dir(cwd);
        host::push_file_path("-e".to_string());
        host::with_host(|h| h.set_program_args(&[], "-e"));
        // An embedded program sees the same default verbosity a command-line one
        // does; without this `$VERBOSE` would read `nil` here and `false` there.
        seed_verbosity(&RunConfig::default());
        run_prelude()?;
        // Seeded after the prelude: it runs ordinary Ruby, and a local set
        // before it would not survive into the program's scope.
        host::with_host(|h| {
            for (name, text) in globals {
                let value = h.new_string(text.to_string());
                h.set_local(name, value);
            }
            h.begin_capture();
        });
        run_compiled(compile(src)?)
    });
    let output = host::with_host(|h| h.end_capture());
    (result, output)
}

/// Core classes that MRI provides in C but rubylang defines in Ruby, run on the
/// fresh host before any user code. `ObjectSpace::WeakMap` is a weak-key hash in
/// MRI; here it is an ordinary hash (no weak semantics), which is enough for the
/// callers that use it as a registry/set (activesupport DescendantsTracker).
const PRELUDE: &str = r#"
# Real Ruby always has rubygems loaded, so Gem::Version is universally available
# (rack-test, bundler, and countless gems assume it at load time without a
# require). Preload the bundled definition here.
require "rubygems/version"

# `Thread::Backtrace::Location` — the class of the objects `caller_locations`
# returns natively; declared here so it exists as a constant (activesupport's
# SyntaxErrorProxy does `DelegateClass(Thread::Backtrace::Location)`, which reads
# its public_instance_methods).
class Thread
  class Backtrace
    class Location
      def path; @path; end
      def lineno; @lineno; end
      def label; @label; end
      def base_label; @base_label || @label; end
      def absolute_path; @absolute_path; end
      def to_s; @path.to_s + ":" + @lineno.to_s + ":in '" + @label.to_s + "'"; end
      def inspect; to_s.inspect; end
    end
  end
end

module Process
  # clock_gettime clock ids; `Process.clock_gettime` maps each to the host's own
  # POSIX clock (realtime, monotonic, process/thread CPU time, monotonic raw).
  CLOCK_REALTIME = 0
  CLOCK_MONOTONIC = 1
  CLOCK_PROCESS_CPUTIME_ID = 2
  CLOCK_THREAD_CPUTIME_ID = 3
  CLOCK_MONOTONIC_RAW = 4

  # `$?` after `system` / backticks. Built natively (`set_last_status`) with the
  # raw wait status in `@__status`; the readers decode it as process.c does.
  class Status
    def pid; @__pid; end
    def to_i; @__status; end
    def exited?; @__status & 0x7f == 0; end
    def exitstatus; exited? ? (@__status >> 8) & 0xff : nil; end
    def success?; exited? ? exitstatus == 0 : nil; end
    def stopped?; @__status & 0xff == 0x7f; end
    def stopsig; stopped? ? (@__status >> 8) & 0xff : nil; end
    def signaled?; !exited? && !stopped?; end
    def termsig; signaled? ? @__status & 0x7f : nil; end
    def coredump?; signaled? && @__status & 0x80 != 0; end
    def ==(other); equal?(other) || @__status == other; end
    def to_s; @__message; end
    def inspect; '#<Process::Status: ' + @__message + ">"; end
  end
end

module RbConfig
  CONFIG = {
    "host_os" => "linux-gnu",
    "arch" => "x86_64-linux",
    "ruby_version" => "3.4.0",
    "MAJOR" => "3",
    "MINOR" => "4",
    "TEENY" => "0",
    "ruby_install_name" => "ruby",
    "RUBY_INSTALL_NAME" => "ruby",
    "UNICODE_VERSION" => "15.0.0",
    "UNICODE_EMOJI_VERSION" => "15.0",
    "bindir" => "/usr/bin",
    "rubylibdir" => "/usr/lib/ruby",
    "EXEEXT" => "",
  }
end

class IO
  SEEK_SET = 0
  SEEK_CUR = 1
  SEEK_END = 2
end

class File
  # The module IO includes (so File inherits it); only its platform-neutral
  # members are modelled.
  module Constants
    FNM_NOESCAPE = 1
    FNM_PATHNAME = 2
    FNM_DOTMATCH = 4
    FNM_CASEFOLD = 8
    FNM_EXTGLOB = 16
    FNM_SYSCASE = 0
    FNM_SHORTNAME = 0
    NULL = "/dev/null"
  end
  SEPARATOR = "/"
  ALT_SEPARATOR = nil
  PATH_SEPARATOR = ":"
  Separator = "/"
  # MRI reaches these through `File < IO`; File here does not inherit IO's.
  SEEK_SET = 0
  SEEK_CUR = 1
  SEEK_END = 2
  FNM_NOESCAPE = 1
  FNM_PATHNAME = 2
  FNM_DOTMATCH = 4
  FNM_CASEFOLD = 8
  FNM_EXTGLOB = 16
  FNM_SYSCASE = 0
  FNM_SHORTNAME = 0
end

class Regexp
  IGNORECASE = 1
  EXTENDED = 2
  MULTILINE = 4
  FIXEDENCODING = 16
  NOENCODING = 32
end

class ObjectSpace::WeakMap
  def initialize; @__wm = {}; end
  def [](k); @__wm[k]; end
  def []=(k, v); @__wm[k] = v; end
  def delete(k); @__wm.delete(k); end
  def key?(k); @__wm.key?(k); end
  def include?(k); @__wm.key?(k); end
  def member?(k); @__wm.key?(k); end
  def each(&b); @__wm.each(&b); end
  def each_key(&b); @__wm.each_key(&b); end
  def each_value(&b); @__wm.each_value(&b); end
  def each_pair(&b); @__wm.each_pair(&b); end
  def keys; @__wm.keys; end
  def values; @__wm.values; end
  def size; @__wm.size; end
  def length; @__wm.size; end
end
"#;

/// Compile and run [`PRELUDE`] on the current host. Silent and fast; runs once per
/// fresh VM before requires and the program.
fn run_prelude() -> Result<(), String> {
    run_compiled(compile(PRELUDE)?)?;
    builtins::install_native_constants();
    Ok(())
}

/// Run each `-r LIB` on the current host before the program. Requires share the
/// program's host (globals, classes), matching MRI's `-r`.
fn run_requires(requires: &[String]) -> Result<(), String> {
    if requires.is_empty() {
        return Ok(());
    }
    // `{lib:?}` quotes+escapes the name into a Ruby string literal for `require`.
    let src: String = requires
        .iter()
        .map(|lib| format!("require {lib:?}\n"))
        .collect();
    run_compiled(compile(&src)?).map(|_| ())
}

/// The script has finished — normally or with an uncaught exception — so run
/// its `at_exit` handlers before the caller reports the outcome. When a
/// handler decided the exit status (`exit` inside it, or a raise), the process
/// ends here with that status, after printing the script's own uncaught error.
fn end_program(r: Result<Value, String>) -> Result<Value, String> {
    let Some(code) = host::run_at_exit_handlers() else {
        return r;
    };
    if let Err(e) = &r {
        eprintln!("{e}");
    }
    use std::io::Write;
    let _ = std::io::stdout().flush();
    std::process::exit(code);
}

/// Merge an already-compiled program onto the current host: rebase its
/// proc/begin ids above what is already loaded (so ids never collide — see
/// `compiler::rebase_program`), install its methods/classes/begins/procs, and
/// return the (rebased) main chunk for the caller to run. Shared by the initial
/// script run, each REPL line, and every `require`/`load`.
pub fn load_merged(mut prog: compiler::Program) -> fusevm::Chunk {
    let (proc_off, begin_off) = host::with_host(|h| h.program_offsets());
    compiler::rebase_program(&mut prog, proc_off, begin_off);
    compiler::assign_regex_sites(&mut prog);
    let compiler::Program {
        main,
        methods,
        classes,
        begins,
        procs,
    } = prog;
    host::with_host(|h| h.load_program(methods, classes, begins, procs));
    main
}

/// Run an already-compiled program on the current host (rebasing + merging it
/// first, then running its main chunk at the top level).
pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
    host::run_main(load_merged(prog))
}

/// Read and run a `.rb` file. Seeds `$LOAD_PATH`/`$LOADED_FEATURES` and the
/// `require` file-dir stack with the script's own directory (MRI seeds the
/// running script's dir), so `require`/`require_relative` resolve against it.
pub fn eval_file(path: &str) -> Result<Value, String> {
    eval_file_cfg(path, &RunConfig::default())
}

/// `eval_file` with command-line configuration (`-I`/`-r`/`ARGV`/`$0`).
pub fn eval_file_cfg(path: &str, cfg: &RunConfig) -> Result<Value, String> {
    let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
    // Fresh per-run VM before the GVL (see `eval_str_cfg`).
    host::reset_host();
    // Hold the GVL for the whole run (see `eval_str_cfg`).
    host::with_gvl(|| {
        let abs = std::fs::canonicalize(path).unwrap_or_else(|_| std::path::PathBuf::from(path));
        let dir = abs
            .parent()
            .map(|p| p.to_path_buf())
            .unwrap_or_else(|| std::path::PathBuf::from("."));
        host::with_host(|h| h.init_load_path(&dir.to_string_lossy()));
        host::with_host(|h| h.prepend_load_path(&cfg.includes));
        host::push_file_dir(dir);
        // `__FILE__` for the top-level script is the path exactly as given on the
        // command line (MRI does not canonicalize it). `$0` is the same path.
        host::push_file_path(path.to_string());
        host::with_host(|h| h.set_program_args(&cfg.argv, path));
        seed_verbosity(cfg);
        run_prelude()?;
        run_requires(&cfg.requires)?;
        // If `ruby --build FILE` warmed the cache, the stored program is the whole
        // bundled app (every statically-required file inlined). Run it directly —
        // it skips lex/parse/lower AND needs none of the required source files on
        // disk. `cache::load` returns `None` (falls back to a fresh compile +
        // runtime `require`) on a miss or a changed bundled file.
        if let Some(prog) = cache::load_file(&abs.to_string_lossy(), &src) {
            return end_program(run_compiled(prog));
        }
        end_program(run_compiled(
            compile(&src).map_err(|e| syntax_report(cfg, path, e))?,
        ))
    })
}

/// How a script that does not parse is reported: MRI names the script and ends
/// the line with the exception class (`-e: … (SyntaxError)`), which is what
/// says the run failed with a SyntaxError rather than some other error.
fn syntax_report(cfg: &RunConfig, script: &str, msg: String) -> String {
    if cfg.report_syntax_errors {
        format!("{script}: {msg} (SyntaxError)")
    } else {
        msg
    }
}

/// Read and run a `.rb` file under the DAP debugger: compile with per-statement
/// line markers and run with the debug hook installed (`ruby --dap`).
pub fn eval_file_debug(path: &str) -> Result<Value, String> {
    let src = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
    let prog = compile_debug(&src)?;
    host::reset_host();
    host::set_debug_mode(true);
    let r = run_compiled(prog);
    host::set_debug_mode(false);
    r
}

/// Evaluate `src` and return the `inspect` form of the last expression's value.
/// The convenience entry point for tests and `--eval`-style checks.
pub fn eval_to_string(src: &str) -> Result<String, String> {
    let v = eval_str(src)?;
    Ok(host::with_host(|h| h.inspect(&v)))
}