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;
pub const RUBY_COMPAT_VERSION: &str = "3.4.0";
pub const RUBY_ENGINE: &str = "rubylang";
pub const RUBY_ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn ruby_platform() -> String {
format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS)
}
pub fn version_banner() -> String {
format!(
"ruby {} (rubylang {}) [{}]",
RUBY_COMPAT_VERSION,
RUBY_ENGINE_VERSION,
ruby_platform()
)
}
pub const DEFAULT_WARN_LEVEL: u8 = 1;
pub struct RunConfig {
pub argv: Vec<String>,
pub includes: Vec<String>,
pub requires: Vec<String>,
pub script_name: String,
pub warn_level: u8,
pub debug: bool,
pub frozen_string_literal: bool,
pub frozen_string_literal_switched: bool,
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,
}
}
}
fn verbose_for_level(level: u8) -> Value {
match level {
0 => Value::Undef,
1 => Value::Bool(false),
_ => Value::Bool(true),
}
}
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);
}
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);
compiler::set_chilled_string_literals(
comment.is_none() && compiler::default_chilled_string_literals(),
);
let stmts = parser::parse(src)?;
compiler::compile(&stmts, false)
}
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; }
let Some(rest) = t.strip_prefix('#') else {
break; };
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
}
pub fn compile_debug(src: &str) -> Result<compiler::Program, String> {
let stmts = parser::parse(src)?;
compiler::compile(&stmts, true)
}
pub fn eval_str(src: &str) -> Result<Value, String> {
eval_str_cfg(src, &RunConfig::default())
}
pub fn eval_str_cfg(src: &str, cfg: &RunConfig) -> Result<Value, String> {
host::reset_host();
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()
};
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))?,
))
})
}
pub fn eval_str_captured(src: &str, globals: &[(&str, &str)]) -> (Result<Value, String>, String) {
eval_captured(src, globals, host::StdinSource::Process)
}
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"));
seed_verbosity(&RunConfig::default());
run_prelude()?;
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)
}
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
"#;
fn run_prelude() -> Result<(), String> {
run_compiled(compile(PRELUDE)?)?;
builtins::install_native_constants();
Ok(())
}
fn run_requires(requires: &[String]) -> Result<(), String> {
if requires.is_empty() {
return Ok(());
}
let src: String = requires
.iter()
.map(|lib| format!("require {lib:?}\n"))
.collect();
run_compiled(compile(&src)?).map(|_| ())
}
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);
}
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
}
pub fn run_compiled(prog: compiler::Program) -> Result<Value, String> {
host::run_main(load_merged(prog))
}
pub fn eval_file(path: &str) -> Result<Value, String> {
eval_file_cfg(path, &RunConfig::default())
}
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}"))?;
host::reset_host();
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);
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 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))?,
))
})
}
fn syntax_report(cfg: &RunConfig, script: &str, msg: String) -> String {
if cfg.report_syntax_errors {
format!("{script}: {msg} (SyntaxError)")
} else {
msg
}
}
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
}
pub fn eval_to_string(src: &str) -> Result<String, String> {
let v = eval_str(src)?;
Ok(host::with_host(|h| h.inspect(&v)))
}