use crate::ast::*;
use crate::host::{ops, BeginDef, ClassDef, MethodDef, ProcDef, RescueDef, Visibility};
use fusevm::{Chunk, ChunkBuilder, Op, Value};
use std::sync::Arc;
pub const ATTR_WRITER_PARAM: &str = "__attr_value__";
thread_local! {
static FROZEN_STR_LITERALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
static CHILLED_STR_LITERALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn chilled_string_literals() -> bool {
CHILLED_STR_LITERALS.with(|c| c.get())
}
pub fn set_chilled_string_literals(on: bool) {
CHILLED_STR_LITERALS.with(|c| c.set(on));
}
static DEFAULT_CHILLED_STR_LITERALS: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(true);
pub fn default_chilled_string_literals() -> bool {
DEFAULT_CHILLED_STR_LITERALS.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn set_default_chilled_string_literals(on: bool) {
DEFAULT_CHILLED_STR_LITERALS.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub fn frozen_string_literals() -> bool {
FROZEN_STR_LITERALS.with(|c| c.get())
}
pub fn set_frozen_string_literals(on: bool) {
FROZEN_STR_LITERALS.with(|c| c.set(on));
}
static DEFAULT_FROZEN_STR_LITERALS: std::sync::atomic::AtomicBool =
std::sync::atomic::AtomicBool::new(false);
pub fn default_frozen_string_literals() -> bool {
DEFAULT_FROZEN_STR_LITERALS.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn set_default_frozen_string_literals(on: bool) {
DEFAULT_FROZEN_STR_LITERALS.store(on, std::sync::atomic::Ordering::Relaxed);
}
pub struct Program {
pub main: Chunk,
pub methods: Vec<(String, MethodDef)>,
pub classes: Vec<(String, ClassDef)>,
pub begins: Vec<BeginDef>,
pub procs: Vec<ProcDef>,
}
struct LoopCtx {
start: usize,
body_start: usize,
breaks: Vec<usize>,
nexts: Vec<usize>,
redos: Vec<usize>,
}
#[derive(Default)]
pub struct Compiler {
methods: Vec<(String, MethodDef)>,
classes: Vec<(String, ClassDef)>,
begins: Vec<BeginDef>,
procs: Vec<ProcDef>,
loops: Vec<LoopCtx>,
redo_ok: bool,
tmp: usize,
debug: bool,
nesting: Vec<String>,
block_depth: u32,
cur_line: u32,
scope_locals: Vec<std::collections::HashSet<String>>,
cur_method: Vec<String>,
slot_scopes: Vec<std::collections::HashMap<String, u16>>,
}
static SYNTH_CTR: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn next_synth_id() -> u64 {
SYNTH_CTR.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
fn utf8_encoding_const() -> Expr {
Expr::Call {
recv: Some(Box::new(Expr::Var(VarKind::Const, "Encoding".into()))),
name: "UTF_8".into(),
args: Vec::new(),
block: None,
}
}
pub fn synth_ids_used() -> u64 {
SYNTH_CTR.load(std::sync::atomic::Ordering::Relaxed)
}
pub fn advance_synth_ids(base: u64) {
SYNTH_CTR.fetch_max(base, std::sync::atomic::Ordering::Relaxed);
}
const INTROSPECT_CALLS: &[&str] = &[
"eval",
"binding",
"local_variables",
"instance_eval",
"instance_exec",
"class_eval",
"module_eval",
"class_exec",
"module_exec",
];
fn slot_scan(body: &[Stmt]) -> (std::collections::HashSet<String>, bool) {
let mut caps = std::collections::HashSet::new();
let mut disq = false;
for s in body {
slot_scan_expr(&s.expr, &mut caps, &mut disq, false);
}
(caps, disq)
}
fn regex_literal_local_names(source: &str, flags: &str) -> Vec<String> {
if source.contains("#{") || crate::parser::has_sigil_interp(source) {
return Vec::new();
}
let mut names: Vec<String> = Vec::new();
for name in crate::host::regex_group_names(source, flags) {
let mut chars = name.chars();
let local_start = chars
.next()
.is_some_and(|c| c == '_' || c.is_ascii_lowercase() || !c.is_ascii());
let local_rest = chars.all(|c| c == '_' || c.is_ascii_alphanumeric() || !c.is_ascii());
if local_start
&& local_rest
&& !crate::lexer::KEYWORDS.contains(&name.as_str())
&& !names.contains(&name)
{
names.push(name);
}
}
names
}
fn regex_interp_expr(source: &str) -> Option<Expr> {
if !(source.contains("#{") || crate::parser::has_sigil_interp(source)) {
return None;
}
crate::parser::scan_interp(source).ok().map(Expr::Str)
}
fn slot_scan_block(b: &Block, caps: &mut std::collections::HashSet<String>, disq: &mut bool) {
for s in &b.body {
slot_scan_expr(&s.expr, caps, disq, true);
}
}
fn slot_scan_body(
body: &[Stmt],
caps: &mut std::collections::HashSet<String>,
disq: &mut bool,
in_closure: bool,
) {
for s in body {
slot_scan_expr(&s.expr, caps, disq, in_closure);
}
}
fn slot_scan_expr(
e: &Expr,
caps: &mut std::collections::HashSet<String>,
disq: &mut bool,
in_closure: bool,
) {
match e {
Expr::Regex(src, _) => {
if let Some(x) = regex_interp_expr(src) {
slot_scan_expr(&x, caps, disq, in_closure);
}
}
Expr::Var(VarKind::Local, n) => {
if in_closure {
caps.insert(n.clone());
}
}
Expr::Nil
| Expr::True
| Expr::False
| Expr::Int(_)
| Expr::Float(_)
| Expr::Symbol(_)
| Expr::SelfExpr
| Expr::Retry
| Expr::Redo
| Expr::Var(_, _) => {}
Expr::Str(parts) => {
for p in parts {
if let StrPart::Interp(x) = p {
slot_scan_expr(x, caps, disq, in_closure);
}
}
}
Expr::Array(xs) => {
for x in xs {
slot_scan_expr(x, caps, disq, in_closure);
}
}
Expr::Hash(kvs) => {
for (k, v) in kvs {
slot_scan_expr(k, caps, disq, in_closure);
slot_scan_expr(v, caps, disq, in_closure);
}
}
Expr::KwArgs(inner) => slot_scan_expr(inner, caps, disq, in_closure),
Expr::Range { lo, hi, .. } => {
if let Some(x) = lo {
slot_scan_expr(x, caps, disq, in_closure);
}
if let Some(x) = hi {
slot_scan_expr(x, caps, disq, in_closure);
}
}
Expr::Assign(t, v) => {
slot_scan_expr(t, caps, disq, in_closure);
slot_scan_expr(v, caps, disq, in_closure);
}
Expr::MultiAssign { targets, values } => {
if !in_closure {
*disq = true;
}
for t in targets {
slot_scan_expr(t, caps, disq, in_closure);
}
for v in values {
slot_scan_expr(v, caps, disq, in_closure);
}
}
Expr::Unary(_, x) => slot_scan_expr(x, caps, disq, in_closure),
Expr::Binary(_, a, b) => {
slot_scan_expr(a, caps, disq, in_closure);
slot_scan_expr(b, caps, disq, in_closure);
}
Expr::If {
cond,
then,
elifs,
els,
} => {
slot_scan_expr(cond, caps, disq, in_closure);
slot_scan_body(then, caps, disq, in_closure);
for (c, b) in elifs {
slot_scan_expr(c, caps, disq, in_closure);
slot_scan_body(b, caps, disq, in_closure);
}
if let Some(b) = els {
slot_scan_body(b, caps, disq, in_closure);
}
}
Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
slot_scan_expr(cond, caps, disq, in_closure);
slot_scan_body(body, caps, disq, in_closure);
}
Expr::For { iter, body, .. } => {
if !in_closure {
*disq = true;
}
slot_scan_expr(iter, caps, disq, in_closure);
slot_scan_body(body, caps, disq, in_closure);
}
Expr::Case {
subject,
whens,
els,
} => {
slot_scan_expr(subject, caps, disq, in_closure);
for (pats, b) in whens {
for p in pats {
slot_scan_expr(p, caps, disq, in_closure);
}
slot_scan_body(b, caps, disq, in_closure);
}
if let Some(b) = els {
slot_scan_body(b, caps, disq, in_closure);
}
}
Expr::CaseIn { subject, els, .. } => {
if !in_closure {
*disq = true;
}
slot_scan_expr(subject, caps, disq, in_closure);
if let Some(b) = els {
slot_scan_body(b, caps, disq, in_closure);
}
}
Expr::Call {
recv,
name,
args,
block,
} => {
if INTROSPECT_CALLS.contains(&name.as_str()) {
*disq = true;
}
if let Some(r) = recv {
slot_scan_expr(r, caps, disq, in_closure);
}
for a in args {
slot_scan_expr(a, caps, disq, in_closure);
}
if let Some(b) = block {
slot_scan_block(b, caps, disq);
}
}
Expr::Index(r, idxs) => {
slot_scan_expr(r, caps, disq, in_closure);
for i in idxs {
slot_scan_expr(i, caps, disq, in_closure);
}
}
Expr::BlockPass(x) | Expr::Splat(x) => slot_scan_expr(x, caps, disq, in_closure),
Expr::Def {
singleton_recv: Some(recv),
..
} => slot_scan_expr(recv, caps, disq, in_closure),
Expr::Def { .. }
| Expr::Class { .. }
| Expr::Module { .. }
| Expr::SingletonClass { .. } => {}
Expr::Begin {
body,
rescues,
ensure,
} => {
slot_scan_body(body, caps, disq, true);
for r in rescues {
if let Some(s) = &r.splat {
slot_scan_expr(s, caps, disq, true);
}
slot_scan_body(&r.body, caps, disq, true);
}
if let Some(en) = ensure {
slot_scan_body(en, caps, disq, true);
}
}
Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
if let Some(x) = o {
slot_scan_expr(x, caps, disq, in_closure);
}
}
Expr::Yield(xs) => {
for x in xs {
slot_scan_expr(x, caps, disq, in_closure);
}
}
Expr::Defined(inner) => {
if let Expr::Var(VarKind::Local, _) = &**inner {
*disq = true;
}
slot_scan_expr(inner, caps, disq, in_closure);
}
Expr::Super { args, block } => {
if let Some(a) = args {
for x in a {
slot_scan_expr(x, caps, disq, in_closure);
}
}
if let Some(b) = block {
slot_scan_block(b, caps, disq);
}
}
Expr::Lambda(b) => slot_scan_block(b, caps, disq),
}
}
fn scope_plain_assigns(body: &[Stmt]) -> Vec<String> {
let mut out = Vec::new();
for s in body {
collect_plain_assigns(&s.expr, &mut out);
}
out
}
fn for_body_locals(body: &[Stmt]) -> Vec<String> {
let mut out = Vec::new();
for s in body {
for_locals_expr(&s.expr, &mut out);
}
out
}
fn push_local(name: &str, out: &mut Vec<String>) {
if !out.iter().any(|x| x == name) {
out.push(name.to_string());
}
}
fn masgn_ary(value: Expr) -> Expr {
Expr::Call {
recv: None,
name: "__masgn_ary".into(),
args: vec![value],
block: None,
}
}
fn for_locals_target(t: &Expr, out: &mut Vec<String>) {
match t {
Expr::Var(VarKind::Local, n) => push_local(n, out),
Expr::Splat(inner) => for_locals_target(inner, out),
Expr::Array(items) => items.iter().for_each(|i| for_locals_target(i, out)),
_ => {}
}
}
fn for_locals_pattern(p: &Pattern, out: &mut Vec<String>) {
match p {
Pattern::Bind(n) => push_local(n, out),
Pattern::Splat(Some(n)) => push_local(n, out),
Pattern::As(inner, n) => {
for_locals_pattern(inner, out);
push_local(n, out);
}
Pattern::Array(ps) | Pattern::Or(ps) => ps.iter().for_each(|p| for_locals_pattern(p, out)),
Pattern::Hash(fields, _) => {
for (key, sub) in fields {
match sub {
None => push_local(key, out),
Some(p) => for_locals_pattern(p, out),
}
}
}
Pattern::Const(_, Some(inner)) => for_locals_pattern(inner, out),
_ => {}
}
}
fn for_locals_body(body: &[Stmt], out: &mut Vec<String>) {
for s in body {
for_locals_expr(&s.expr, out);
}
}
fn for_locals_expr(e: &Expr, out: &mut Vec<String>) {
match e {
Expr::Regex(src, _) => {
if let Some(x) = regex_interp_expr(src) {
for_locals_expr(&x, out);
}
}
Expr::Assign(t, v) => {
for_locals_target(t, out);
for_locals_expr(v, out);
}
Expr::MultiAssign { targets, values } => {
targets.iter().for_each(|t| for_locals_target(t, out));
values.iter().for_each(|v| for_locals_expr(v, out));
}
Expr::If {
cond,
then,
elifs,
els,
} => {
for_locals_expr(cond, out);
for_locals_body(then, out);
for (c, b) in elifs {
for_locals_expr(c, out);
for_locals_body(b, out);
}
if let Some(b) = els {
for_locals_body(b, out);
}
}
Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
for_locals_expr(cond, out);
for_locals_body(body, out);
}
Expr::For { var, iter, body } => {
push_local(var, out);
for_locals_expr(iter, out);
for_locals_body(body, out);
}
Expr::Case {
subject,
whens,
els,
} => {
for_locals_expr(subject, out);
for (tests, b) in whens {
tests.iter().for_each(|t| for_locals_expr(t, out));
for_locals_body(b, out);
}
if let Some(b) = els {
for_locals_body(b, out);
}
}
Expr::CaseIn {
subject,
clauses,
els,
} => {
for_locals_expr(subject, out);
for c in clauses {
for_locals_pattern(&c.pattern, out);
if let Some(g) = &c.guard {
for_locals_expr(g, out);
}
for_locals_body(&c.body, out);
}
if let Some(b) = els {
for_locals_body(b, out);
}
}
Expr::Begin {
body,
rescues,
ensure,
} => {
for_locals_body(body, out);
for r in rescues {
for_locals_body(&r.body, out);
}
if let Some(b) = ensure {
for_locals_body(b, out);
}
}
Expr::Call { recv, args, .. } => {
if let Some(r) = recv {
for_locals_expr(r, out);
}
args.iter().for_each(|a| for_locals_expr(a, out));
}
Expr::Binary(_, l, r) => {
for_locals_expr(l, out);
for_locals_expr(r, out);
}
Expr::Unary(_, x) | Expr::Splat(x) | Expr::BlockPass(x) | Expr::Defined(x) => {
for_locals_expr(x, out)
}
Expr::Index(r, idx) => {
for_locals_expr(r, out);
idx.iter().for_each(|i| for_locals_expr(i, out));
}
Expr::Array(xs) | Expr::Yield(xs) => xs.iter().for_each(|x| for_locals_expr(x, out)),
Expr::Hash(pairs) => {
for (k, v) in pairs {
for_locals_expr(k, out);
for_locals_expr(v, out);
}
}
Expr::KwArgs(inner) => for_locals_expr(inner, out),
Expr::Range { lo, hi, .. } => {
if let Some(x) = lo {
for_locals_expr(x, out);
}
if let Some(x) = hi {
for_locals_expr(x, out);
}
}
Expr::Str(parts) => {
for p in parts {
if let StrPart::Interp(x) = p {
for_locals_expr(x, out);
}
}
}
Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
if let Some(x) = o {
for_locals_expr(x, out);
}
}
Expr::Super { args: Some(a), .. } => a.iter().for_each(|x| for_locals_expr(x, out)),
_ => {}
}
}
fn collect_plain_assigns(e: &Expr, out: &mut Vec<String>) {
match e {
Expr::Regex(src, _) => {
if let Some(x) = regex_interp_expr(src) {
collect_plain_assigns(&x, out);
}
}
Expr::Assign(t, v) => {
if let Expr::Var(VarKind::Local, n) = &**t {
if !out.iter().any(|x| x == n) {
out.push(n.clone());
}
}
collect_plain_assigns(v, out);
}
Expr::Nil
| Expr::True
| Expr::False
| Expr::Int(_)
| Expr::Float(_)
| Expr::Symbol(_)
| Expr::SelfExpr
| Expr::Retry
| Expr::Redo
| Expr::Var(_, _) => {}
Expr::Str(parts) => {
for p in parts {
if let StrPart::Interp(x) = p {
collect_plain_assigns(x, out);
}
}
}
Expr::Array(xs) => xs.iter().for_each(|x| collect_plain_assigns(x, out)),
Expr::Hash(kvs) => kvs.iter().for_each(|(k, v)| {
collect_plain_assigns(k, out);
collect_plain_assigns(v, out);
}),
Expr::KwArgs(inner) => collect_plain_assigns(inner, out),
Expr::Range { lo, hi, .. } => {
if let Some(x) = lo {
collect_plain_assigns(x, out);
}
if let Some(x) = hi {
collect_plain_assigns(x, out);
}
}
Expr::MultiAssign { values, .. } => {
values.iter().for_each(|v| collect_plain_assigns(v, out))
}
Expr::Unary(_, x) | Expr::BlockPass(x) | Expr::Splat(x) => collect_plain_assigns(x, out),
Expr::Binary(_, a, b) => {
collect_plain_assigns(a, out);
collect_plain_assigns(b, out);
}
Expr::If {
cond,
then,
elifs,
els,
} => {
collect_plain_assigns(cond, out);
then.iter()
.for_each(|s| collect_plain_assigns(&s.expr, out));
for (c, b) in elifs {
collect_plain_assigns(c, out);
b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
}
if let Some(b) = els {
b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
}
}
Expr::While { cond, body } | Expr::DoWhile { cond, body } => {
collect_plain_assigns(cond, out);
body.iter()
.for_each(|s| collect_plain_assigns(&s.expr, out));
}
Expr::For { iter, body, .. } => {
collect_plain_assigns(iter, out);
body.iter()
.for_each(|s| collect_plain_assigns(&s.expr, out));
}
Expr::Case {
subject,
whens,
els,
} => {
collect_plain_assigns(subject, out);
for (pats, b) in whens {
pats.iter().for_each(|p| collect_plain_assigns(p, out));
b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
}
if let Some(b) = els {
b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
}
}
Expr::CaseIn { subject, els, .. } => {
collect_plain_assigns(subject, out);
if let Some(b) = els {
b.iter().for_each(|s| collect_plain_assigns(&s.expr, out));
}
}
Expr::Call { recv, args, .. } => {
if let Some(r) = recv {
collect_plain_assigns(r, out);
}
args.iter().for_each(|a| collect_plain_assigns(a, out));
}
Expr::Index(r, idxs) => {
collect_plain_assigns(r, out);
idxs.iter().for_each(|i| collect_plain_assigns(i, out));
}
Expr::Def { .. }
| Expr::Class { .. }
| Expr::Module { .. }
| Expr::SingletonClass { .. }
| Expr::Lambda(_)
| Expr::Begin { .. } => {}
Expr::Return(o) | Expr::Break(o) | Expr::Next(o) => {
if let Some(x) = o {
collect_plain_assigns(x, out);
}
}
Expr::Yield(xs) => xs.iter().for_each(|x| collect_plain_assigns(x, out)),
Expr::Defined(inner) => collect_plain_assigns(inner, out),
Expr::Super { args, .. } => {
if let Some(a) = args {
a.iter().for_each(|x| collect_plain_assigns(x, out));
}
}
}
}
pub fn compile(stmts: &[Stmt], debug: bool) -> Result<Program, String> {
let mut c = Compiler {
debug,
..Default::default()
};
let mut b = ChunkBuilder::new();
c.scope_locals.push(std::collections::HashSet::new());
c.enter_slot_scope(&std::collections::HashSet::new(), stmts);
c.compile_seq(&mut b, stmts)?;
c.exit_slot_scope();
c.scope_locals.pop();
Ok(Program {
main: b.build(),
methods: c.methods,
classes: c.classes,
begins: c.begins,
procs: c.procs,
})
}
pub fn rebase_program(prog: &mut Program, proc_off: usize, begin_off: usize) {
if proc_off == 0 && begin_off == 0 {
return;
}
rebase_chunk(&mut prog.main, proc_off, begin_off);
for (_, m) in &mut prog.methods {
rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
}
for (_, c) in &mut prog.classes {
for (_, m) in &mut c.methods {
rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
}
for (_, m) in &mut c.class_methods {
rebase_chunk(Arc::make_mut(&mut m.chunk), proc_off, begin_off);
}
}
for p in &mut prog.procs {
rebase_chunk(&mut p.chunk, proc_off, begin_off);
}
for bd in &mut prog.begins {
bd.body += proc_off;
if let Some(e) = &mut bd.ensure {
*e += proc_off;
}
for r in &mut bd.rescues {
r.body += proc_off;
if let Some(s) = &mut r.splat {
*s += proc_off;
}
}
}
}
fn rebase_chunk(chunk: &mut Chunk, proc_off: usize, begin_off: usize) {
let mut changed = false;
for i in 1..chunk.ops.len() {
if let Op::CallBuiltin(id, 1) = chunk.ops[i] {
let off = if id == ops::MKPROC || id == ops::MKLAMBDA {
proc_off
} else if id == ops::BEGIN {
begin_off
} else {
continue;
};
if off == 0 {
continue;
}
if let Op::LoadInt(v) = &mut chunk.ops[i - 1] {
*v += off as i64;
changed = true;
}
}
}
for sub in &mut chunk.sub_chunks {
rebase_chunk(sub, proc_off, begin_off);
}
if changed {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
chunk.ops.hash(&mut h);
chunk.constants.hash(&mut h);
chunk.op_hash = h.finish();
}
}
const REGEX_SITE_STATIC: i64 = -1;
const REGEX_SITE_ONCE: i64 = -2;
static NEXT_REGEX_SITE: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
pub fn assign_regex_sites(prog: &mut Program) {
assign_chunk_regex_sites(&mut prog.main);
for (_, m) in &mut prog.methods {
assign_chunk_regex_sites(Arc::make_mut(&mut m.chunk));
}
for (_, c) in &mut prog.classes {
for (_, m) in c.methods.iter_mut().chain(c.class_methods.iter_mut()) {
assign_chunk_regex_sites(Arc::make_mut(&mut m.chunk));
}
}
for p in &mut prog.procs {
assign_chunk_regex_sites(&mut p.chunk);
}
}
fn assign_chunk_regex_sites(chunk: &mut Chunk) {
use std::sync::atomic::Ordering;
let mut open_once = Vec::new();
let mut changed = false;
for i in 1..chunk.ops.len() {
let Op::CallBuiltin(id, argc) = chunk.ops[i] else {
continue;
};
let Op::LoadInt(site) = &mut chunk.ops[i - 1] else {
continue;
};
let fresh = || NEXT_REGEX_SITE.fetch_add(1, Ordering::Relaxed);
match (id, argc, *site) {
(ops::REGEX_ONCE, 1, REGEX_SITE_ONCE) => {
let n = fresh();
open_once.push(n);
*site = n;
}
(ops::MKREGEX, 3, REGEX_SITE_ONCE) => match open_once.pop() {
Some(n) => *site = n,
None => continue,
},
(ops::MKREGEX, 3, REGEX_SITE_STATIC) => *site = fresh(),
_ => continue,
}
changed = true;
}
for sub in &mut chunk.sub_chunks {
assign_chunk_regex_sites(sub);
}
if changed {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut h = DefaultHasher::new();
chunk.ops.hash(&mut h);
chunk.constants.hash(&mut h);
chunk.op_hash = h.finish();
}
}
pub fn compile_at(stmts: &[Stmt], proc_base: usize, begin_base: usize) -> Result<Program, String> {
let mut c = Compiler {
procs: (0..proc_base).map(|_| dummy_proc()).collect(),
begins: (0..begin_base)
.map(|_| BeginDef {
body: 0,
rescues: vec![],
ensure: None,
})
.collect(),
..Default::default()
};
let mut b = ChunkBuilder::new();
c.slot_scopes.push(std::collections::HashMap::new());
c.compile_seq(&mut b, stmts)?;
c.slot_scopes.pop();
Ok(Program {
main: b.build(),
methods: c.methods,
classes: c.classes,
begins: c.begins.split_off(begin_base),
procs: c.procs.split_off(proc_base),
})
}
pub fn block_own_locals(arity: &crate::ast::BlockArity) -> impl Iterator<Item = String> + '_ {
arity
.kwnames
.iter()
.chain(&arity.kwsplat)
.chain(&arity.locals)
.cloned()
}
fn dummy_proc() -> ProcDef {
ProcDef {
params: vec![],
splat: None,
chunk: ChunkBuilder::new().build(),
arity: crate::ast::BlockArity::default(),
block_depth: 1,
line: 0,
file: None,
}
}
impl Compiler {
fn compile_seq(&mut self, b: &mut ChunkBuilder, body: &[Stmt]) -> Result<(), String> {
if body.is_empty() {
b.emit(Op::LoadUndef, 0);
return Ok(());
}
for (i, s) in body.iter().enumerate() {
if s.line != 0 {
self.cur_line = s.line;
}
if self.debug && s.line != 0 {
b.emit(Op::Extended(crate::host::ext::DBG_LINE, 0), s.line);
}
self.compile_expr(b, &s.expr).map_err(|e| {
if s.line != 0 && !e.starts_with("line ") {
format!("line {}: {e}", s.line)
} else {
e
}
})?;
if i + 1 < body.len() {
b.emit(Op::Pop, 0);
}
}
Ok(())
}
fn stash_method(&mut self, params: &[Param], body: &[Stmt]) -> Result<String, String> {
let def = self.compile_method(params, body)?;
let synth = format!("__def{}__", next_synth_id());
self.methods.push((synth.clone(), def));
Ok(synth)
}
fn compile_method(&mut self, params: &[Param], body: &[Stmt]) -> Result<MethodDef, String> {
self.compile_method_named("", params, body)
}
fn collect_default_locals(e: &Expr, out: &mut Vec<String>) {
match e {
Expr::Assign(target, value) => {
if let Expr::Var(VarKind::Local, n) = &**target {
if !out.contains(n) {
out.push(n.clone());
}
}
Self::collect_default_locals(value, out);
}
Expr::MultiAssign { targets, values } => {
for t in targets {
match t {
Expr::Var(VarKind::Local, n) => {
if !out.contains(n) {
out.push(n.clone());
}
}
Expr::Array(inner) => Self::collect_default_locals(
&Expr::MultiAssign {
targets: inner.clone(),
values: Vec::new(),
},
out,
),
_ => {}
}
}
for v in values {
Self::collect_default_locals(v, out);
}
}
Expr::Binary(_, l, r) => {
Self::collect_default_locals(l, out);
Self::collect_default_locals(r, out);
}
Expr::Unary(_, x) | Expr::Splat(x) => Self::collect_default_locals(x, out),
Expr::Index(r, idx) => {
Self::collect_default_locals(r, out);
for i in idx {
Self::collect_default_locals(i, out);
}
}
Expr::Array(items) => {
for i in items {
Self::collect_default_locals(i, out);
}
}
Expr::Call { recv, args, .. } => {
if let Some(r) = recv {
Self::collect_default_locals(r, out);
}
for a in args {
Self::collect_default_locals(a, out);
}
}
_ => {}
}
}
fn compile_method_named(
&mut self,
name: &str,
params: &[Param],
body: &[Stmt],
) -> Result<MethodDef, String> {
let saved = std::mem::take(&mut self.loops);
let saved_redo = std::mem::take(&mut self.redo_ok);
let saved_line = self.cur_line;
let param_locals: std::collections::HashSet<String> =
params.iter().map(|p| p.name.clone()).collect();
self.scope_locals.push(param_locals);
self.cur_method.push(name.to_string());
let mut b = ChunkBuilder::new();
let mut default_locals: Vec<String> = Vec::new();
for p in params {
if let Some(default) = &p.default {
Self::collect_default_locals(default, &mut default_locals);
}
}
let n_slot_params = self.enter_method_slot_scope(params, &default_locals, body);
for lname in &default_locals {
if params.iter().any(|p| &p.name == lname) {
continue;
}
if let Some(scope) = self.scope_locals.last_mut() {
scope.insert(lname.clone());
}
self.kstr(&mut b, lname);
self.compile_expr(&mut b, &Expr::Nil)?;
b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
b.emit(Op::Pop, 0);
}
for p in params {
if let Some(default) = &p.default {
self.kstr(&mut b, &p.name);
b.emit(Op::CallBuiltin(ops::DEFINED, 1), 0);
let skip = b.emit(Op::JumpIfTrue(0), 0);
self.compile_assign(&mut b, &Expr::Var(VarKind::Local, p.name.clone()), default)?;
b.emit(Op::Pop, 0);
let here = b.current_pos();
b.patch_jump(skip, here);
}
}
self.compile_seq(&mut b, body)?;
self.exit_slot_scope();
self.scope_locals.pop();
self.cur_method.pop();
self.loops = saved;
self.redo_ok = saved_redo;
self.cur_line = saved_line;
let pnames: Vec<String> = params
.iter()
.filter(|p| !p.keyword && !p.kwsplat && !p.block)
.map(|p| p.name.clone())
.collect();
let blockparam = params.iter().find(|p| p.block).map(|p| p.name.clone());
let kwparams: Vec<String> = params
.iter()
.filter(|p| p.keyword)
.map(|p| p.name.clone())
.collect();
let kwsplat = params.iter().find(|p| p.kwsplat).map(|p| p.name.clone());
let splat = params
.iter()
.filter(|p| !p.keyword && !p.kwsplat && !p.block)
.position(|p| p.splat);
let req = params
.iter()
.filter(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_none())
.count() as u16;
let opt = params
.iter()
.filter(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_some())
.count() as u16;
let positional: Vec<_> = params
.iter()
.filter(|p| !p.keyword && !p.kwsplat && !p.block)
.collect();
let post = positional
.iter()
.rposition(|p| p.splat || p.default.is_some())
.map_or(0, |last| positional.len() - last - 1) as u16;
let kwreq: Vec<String> = params
.iter()
.filter(|p| p.keyword && p.default.is_none())
.map(|p| p.name.clone())
.collect();
Ok(MethodDef {
chunk_id: crate::host::next_method_chunk_id(),
params: pnames,
splat,
kwparams,
kwsplat,
blockparam,
req,
opt,
post,
kwreq,
chunk: Arc::new(b.build()),
slot_params: n_slot_params,
line: saved_line,
file: None,
})
}
fn compile_body_chunk(&mut self, body: &[Stmt]) -> Result<Chunk, String> {
let saved = std::mem::take(&mut self.loops);
let saved_line = self.cur_line;
let mut b = ChunkBuilder::new();
self.slot_scopes.push(std::collections::HashMap::new());
self.compile_seq(&mut b, body)?;
self.slot_scopes.pop();
self.loops = saved;
self.cur_line = saved_line;
Ok(b.build())
}
fn compile_expr(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<(), String> {
match e {
Expr::Call {
recv: None,
name,
args,
..
} if name == "__LINE__" && args.is_empty() => {
b.emit(Op::LoadInt(self.cur_line as i64), 0);
return Ok(());
}
Expr::Var(VarKind::Local, name) if name == "__LINE__" => {
b.emit(Op::LoadInt(self.cur_line as i64), 0);
return Ok(());
}
Expr::Call {
recv: None,
name,
args,
block: None,
} if name == "__ENCODING__" && args.is_empty() => {
return self.compile_expr(b, &utf8_encoding_const());
}
Expr::Var(VarKind::Local, name) if name == "__ENCODING__" => {
return self.compile_expr(b, &utf8_encoding_const());
}
_ => {}
}
match e {
Expr::Nil => {
b.emit(Op::LoadUndef, 0);
}
Expr::True => {
b.emit(Op::LoadTrue, 0);
}
Expr::False => {
b.emit(Op::LoadFalse, 0);
}
Expr::Int(n) => {
b.emit(Op::LoadInt(*n), 0);
}
Expr::Float(f) => {
b.emit(Op::LoadFloat(*f), 0);
}
Expr::Str(parts) if parts.iter().any(|p| matches!(p, StrPart::Bytes(_))) => {
let all_literal = parts.iter().all(|p| !matches!(p, StrPart::Interp(_)));
let mut kinds = String::from(match (all_literal, frozen_string_literals()) {
(true, true) => "F",
(true, false) if chilled_string_literals() => "C",
_ => "-",
});
for p in parts {
kinds.push(match p {
StrPart::Lit(_) => 'L',
StrPart::Bytes(_) => 'B',
StrPart::Interp(_) => 'I',
});
}
self.kstr(b, &kinds);
for p in parts {
match p {
StrPart::Lit(s) => self.kstr(b, s),
StrPart::Bytes(bytes) => {
self.kstr(b, &bytes.iter().map(|&x| char::from(x)).collect::<String>())
}
StrPart::Interp(e) => self.compile_expr(b, e)?,
}
}
b.emit(Op::CallBuiltin(ops::MKBSTR, argc(parts.len() + 1)?), 0);
}
Expr::Str(parts) => {
for p in parts {
match p {
StrPart::Lit(s) => self.kstr(b, s),
StrPart::Interp(e) => self.compile_expr(b, e)?,
StrPart::Bytes(_) => unreachable!("lowered by the arm above"),
}
}
let all_literal = parts.iter().all(|p| matches!(p, StrPart::Lit(_)));
let op = match (all_literal, frozen_string_literals()) {
(true, true) => ops::MKSTRF,
(true, false) if chilled_string_literals() => ops::MKSTRC,
_ => ops::MKSTR,
};
b.emit(Op::CallBuiltin(op, parts.len() as u8), 0);
}
Expr::Symbol(s) => {
self.kstr(b, s);
b.emit(Op::CallBuiltin(ops::MKSYM, 1), 0);
}
Expr::Array(items) => {
if items.iter().any(|it| matches!(it, Expr::Splat(_))) {
self.compile_spread(b, items)?;
} else if items.len() <= 255 {
for it in items {
self.compile_expr(b, it)?;
}
b.emit(Op::CallBuiltin(ops::MKARRAY, items.len() as u8), 0);
} else {
let mut nchunks = 0usize;
for chunk in items.chunks(255) {
for it in chunk {
self.compile_expr(b, it)?;
}
b.emit(Op::CallBuiltin(ops::MKARRAY, chunk.len() as u8), 0);
nchunks += 1;
}
b.emit(Op::CallBuiltin(ops::MKARGS, argc(nchunks)?), 0);
}
}
Expr::Splat(e) => {
self.compile_expr(b, e)?;
}
Expr::BlockPass(_) => {
return Err("block-pass used outside call position".into());
}
Expr::Lambda(block) => {
let id = self.compile_proc(block)?;
b.emit(Op::LoadInt(id as i64), 0);
b.emit(Op::CallBuiltin(ops::MKLAMBDA, 1), 0);
}
Expr::Regex(source, flags) => {
let interp = source.contains("#{") || crate::parser::has_sigil_interp(source);
let once = interp && flags.contains('o');
let mut skip = None;
if once {
b.emit(Op::LoadInt(REGEX_SITE_ONCE), 0);
b.emit(Op::CallBuiltin(ops::REGEX_ONCE, 1), 0);
b.emit(Op::Dup, 0);
b.emit(Op::RubyTruthy, 0);
skip = Some(b.emit(Op::JumpIfTrue(0), 0));
b.emit(Op::Pop, 0);
}
if interp {
let parts = crate::parser::scan_interp(source)?;
self.compile_expr(b, &Expr::Str(parts))?;
} else {
self.kstr(b, source);
}
self.kstr(b, flags);
let site = match (interp, once) {
(false, _) => REGEX_SITE_STATIC,
(true, true) => REGEX_SITE_ONCE,
(true, false) => 0,
};
b.emit(Op::LoadInt(site), 0);
b.emit(Op::CallBuiltin(ops::MKREGEX, 3), 0);
if let Some(j) = skip {
let end = b.current_pos();
b.patch_jump(j, end);
}
}
Expr::KwArgs(inner) => {
self.compile_expr(b, inner)?;
b.emit(Op::CallBuiltin(ops::MARK_KWARGS, 1), 0);
}
Expr::Hash(pairs) => {
if pairs.len() * 2 <= 255 {
for (k, v) in pairs {
self.compile_expr(b, k)?;
self.compile_expr(b, v)?;
}
b.emit(Op::CallBuiltin(ops::MKHASH, (pairs.len() * 2) as u8), 0);
} else {
let mut nchunks = 0usize;
for chunk in pairs.chunks(127) {
for (k, v) in chunk {
self.compile_expr(b, k)?;
self.compile_expr(b, v)?;
}
b.emit(Op::CallBuiltin(ops::MKHASH, (chunk.len() * 2) as u8), 0);
nchunks += 1;
}
b.emit(Op::CallBuiltin(ops::MKHASH_MERGE, argc(nchunks)?), 0);
}
}
Expr::Range { lo, hi, exclusive } => {
match lo {
Some(e) => self.compile_expr(b, e)?,
None => {
b.emit(Op::LoadInt(crate::host::RANGE_BEGINLESS), 0);
}
}
match hi {
Some(e) => self.compile_expr(b, e)?,
None => {
b.emit(Op::LoadInt(crate::host::RANGE_ENDLESS), 0);
}
}
b.emit(
if *exclusive {
Op::LoadTrue
} else {
Op::LoadFalse
},
0,
);
b.emit(Op::CallBuiltin(ops::MKRANGE, 3), 0);
}
Expr::Var(VarKind::Local, name)
if self.cur_method.last().map(String::as_str) == Some(name.as_str())
&& !self.scope_locals.last().is_some_and(|s| s.contains(name)) =>
{
self.compile_call(b, &None, name, &[], &None)?;
}
Expr::Var(kind, name) => self.compile_var_read(b, *kind, name),
Expr::Assign(target, value) => self.compile_assign(b, target, value)?,
Expr::MultiAssign { targets, values } => {
self.compile_multi_assign(b, targets, values)?
}
Expr::Unary(op, e) => self.compile_unary(b, *op, e)?,
Expr::Binary(op, l, r) => self.compile_binary(b, *op, l, r)?,
Expr::If {
cond,
then,
elifs,
els,
} => self.compile_if(b, cond, then, elifs, els)?,
Expr::While { cond, body } => self.compile_while(b, cond, body)?,
Expr::DoWhile { cond, body } => self.compile_do_while(b, cond, body)?,
Expr::For { var, iter, body } => self.compile_for(b, var, iter, body)?,
Expr::Case {
subject,
whens,
els,
} => self.compile_case(b, subject, whens, els)?,
Expr::CaseIn {
subject,
clauses,
els,
} => self.compile_case_in(b, subject, clauses, els)?,
Expr::Call {
recv,
name,
args,
block,
} => self.compile_call(b, recv, name, args, block)?,
Expr::Index(recv, idx) => {
if idx.iter().any(|i| matches!(i, Expr::Splat(_))) {
self.compile_expr(b, recv)?;
self.kstr(b, "[]");
self.compile_spread(b, idx)?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
} else {
self.compile_expr(b, recv)?;
for i in idx {
self.compile_expr(b, i)?;
}
b.emit(
Op::CallBuiltin(ops::INDEX_GET, argc(1 + idx.len())?),
self.cur_line,
);
}
}
Expr::Def {
name,
params,
body,
singleton,
singleton_recv,
} => {
match singleton_recv {
Some(recv) => {
let synth = self.stash_method(params, body)?;
self.compile_expr(b, recv)?;
self.kstr(b, name);
self.kstr(b, &synth);
b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
}
None if *singleton => {
let synth = self.stash_method(params, body)?;
self.compile_expr(b, &Expr::SelfExpr)?;
self.kstr(b, name);
self.kstr(b, &synth);
b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
}
None => {
let def = self.compile_method_named(name, params, body)?;
let synth = format!("__def{}__", next_synth_id());
self.methods.push((name.clone(), def.clone()));
self.methods.push((synth.clone(), def));
self.kstr(b, name);
self.kstr(b, &synth);
b.emit(Op::CallBuiltin(ops::DEFINE_METHOD_DYN, 2), 0);
}
}
}
Expr::Class {
name,
superclass,
body,
} => self.compile_class(b, name, superclass, body, false)?,
Expr::Module { name, body } => self.compile_class(b, name, &None, body, true)?,
Expr::SingletonClass { recv, body } => {
let mut nondefs: Vec<Stmt> = Vec::new();
for s in body {
if let Expr::Def {
name, params, body, ..
} = &s.expr
{
let synth = self.stash_method(params, body)?;
match recv {
Some(r) => self.compile_expr(b, r)?,
None => {
b.emit(Op::CallBuiltin(ops::GETSELF, 0), 0);
}
}
self.kstr(b, name);
self.kstr(b, &synth);
b.emit(Op::CallBuiltin(ops::DEFINE_SINGLETON, 3), self.cur_line);
b.emit(Op::Pop, 0);
} else {
nondefs.push(s.clone());
}
}
if !nondefs.is_empty() {
let recv_expr = match recv {
Some(r) => (**r).clone(),
None => Expr::SelfExpr,
};
let call = Expr::Call {
recv: Some(Box::new(Expr::Call {
recv: Some(Box::new(recv_expr)),
name: "singleton_class".into(),
args: Vec::new(),
block: None,
})),
name: "class_eval".into(),
args: Vec::new(),
block: Some(Block {
params: Vec::new(),
splat: None,
body: nondefs,
arity: None,
line: 0,
}),
};
self.compile_expr(b, &call)?;
b.emit(Op::Pop, 0);
}
b.emit(Op::LoadUndef, 0);
}
Expr::SelfExpr => {
b.emit(Op::CallBuiltin(ops::GETSELF, 0), 0);
}
Expr::Begin {
body,
rescues,
ensure,
} => self.compile_begin(b, body, rescues, ensure)?,
Expr::Return(e) => self.compile_flow(b, e, ops::SIG_RETURN, FlowKind::Return)?,
Expr::Break(e) => self.compile_flow(b, e, ops::SIG_BREAK, FlowKind::Break)?,
Expr::Next(e) => self.compile_flow(b, e, ops::SIG_NEXT, FlowKind::Next)?,
Expr::Retry => {
b.emit(Op::LoadUndef, 0);
b.emit(Op::CallBuiltin(ops::SIG_RETRY, 1), 0);
}
Expr::Redo => {
if self.loops.is_empty() {
if !self.redo_ok {
return Err("Invalid redo (SyntaxError)".into());
}
b.emit(Op::LoadUndef, 0); b.emit(Op::CallBuiltin(ops::SIG_REDO, 1), 0);
} else {
let j = b.emit(Op::Jump(0), 0);
self.loops.last_mut().unwrap().redos.push(j);
b.emit(Op::LoadUndef, 0); }
}
Expr::Yield(args) => {
for a in args {
self.compile_expr(b, a)?;
}
b.emit(
Op::CallBuiltin(ops::YIELD, argc(args.len())?),
self.cur_line,
);
}
Expr::Defined(operand) => self.compile_defined(b, operand)?,
Expr::Super { args, block } => {
let pass_expr = block.as_ref().and_then(block_pass_expr);
let proc_id = match (&pass_expr, block) {
(Some(_), _) => None,
(None, Some(bl)) => Some(self.compile_proc(bl)?),
(None, None) => None,
};
let has_block = pass_expr.is_some() || proc_id.is_some();
let emit_block = |s: &mut Self, b: &mut ChunkBuilder| -> Result<(), String> {
match (&pass_expr, proc_id) {
(Some(e), _) => s.compile_expr(b, e),
(None, Some(id)) => {
b.emit(Op::LoadInt(id as i64), 0);
b.emit(Op::CallBuiltin(ops::MKPROC, 1), 0);
Ok(())
}
(None, None) => Ok(()),
}
};
match (args, has_block) {
(Some(args), false) => {
for a in args {
self.compile_expr(b, a)?;
}
b.emit(
Op::CallBuiltin(ops::SUPER, argc(args.len())?),
self.cur_line,
);
}
(None, false) => {
b.emit(Op::CallBuiltin(ops::SUPER_FWD, 0), self.cur_line);
}
(Some(args), true) => {
for a in args {
self.compile_expr(b, a)?;
}
emit_block(self, b)?;
b.emit(
Op::CallBuiltin(ops::SUPER_BLK, argc(args.len() + 1)?),
self.cur_line,
);
}
(None, true) => {
emit_block(self, b)?;
b.emit(Op::CallBuiltin(ops::SUPER_FWD_BLK, 1), self.cur_line);
}
}
}
}
Ok(())
}
fn qualify(&self, name: &str) -> String {
match self.nesting.last() {
Some(ns) => format!("{ns}::{name}"),
None => name.to_string(),
}
}
fn resolve_class_name(&self, written: &str) -> String {
if let Some(abs) = written.strip_prefix("::") {
return abs.to_string();
}
for ns in self.nesting.iter().rev() {
let cand = format!("{ns}::{written}");
if self.classes.iter().any(|(n, _)| *n == cand) {
return cand;
}
}
written.to_string()
}
fn const_candidates(&self, name: &str) -> String {
if let Some(abs) = name.strip_prefix("::") {
return abs.to_string();
}
if self.nesting.is_empty() {
return name.to_string();
}
let mut cands: Vec<String> = self
.nesting
.iter()
.rev()
.map(|ns| format!("{ns}::{name}"))
.collect();
cands.push(name.to_string());
cands.join("\u{1f}")
}
fn enter_slot_scope(&mut self, params: &std::collections::HashSet<String>, body: &[Stmt]) {
let (caps, disq) = slot_scan(body);
let mut slots = std::collections::HashMap::new();
if !disq {
let mut idx = 0u16;
for name in scope_plain_assigns(body) {
if params.contains(&name) || caps.contains(&name) {
continue;
}
slots.insert(name, idx);
idx += 1;
}
}
self.slot_scopes.push(slots);
}
fn exit_slot_scope(&mut self) {
self.slot_scopes.pop();
}
fn enter_method_slot_scope(
&mut self,
params: &[Param],
default_locals: &[String],
body: &[Stmt],
) -> u16 {
let (caps, disq) = slot_scan(body);
let simple = !disq
&& !params.is_empty()
&& default_locals.is_empty()
&& params
.iter()
.all(|p| !p.keyword && !p.kwsplat && !p.block && !p.splat && p.default.is_none())
&& params.iter().all(|p| !caps.contains(&p.name));
if !simple {
let mut host_bound: std::collections::HashSet<String> =
params.iter().map(|p| p.name.clone()).collect();
host_bound.extend(default_locals.iter().cloned());
self.enter_slot_scope(&host_bound, body);
return 0;
}
let mut slots = std::collections::HashMap::new();
let mut idx = 0u16;
for p in params {
slots.insert(p.name.clone(), idx);
idx += 1;
}
let n_params = idx;
for name in scope_plain_assigns(body) {
if slots.contains_key(&name) || caps.contains(&name) {
continue;
}
slots.insert(name, idx);
idx += 1;
}
self.slot_scopes.push(slots);
n_params
}
fn local_slot(&self, name: &str) -> Option<u16> {
self.slot_scopes.last().and_then(|m| m.get(name)).copied()
}
fn compile_var_read(&mut self, b: &mut ChunkBuilder, kind: VarKind, name: &str) {
if let VarKind::Const = kind {
let encoded = self.const_candidates(name);
self.kstr(b, &encoded);
b.emit(Op::CallBuiltin(ops::GETCONST, 1), self.cur_line);
return;
}
if let VarKind::Local = kind {
if let Some(slot) = self.local_slot(name) {
b.emit(Op::GetSlot(slot), self.cur_line);
return;
}
}
let op = match kind {
VarKind::Local if self.scope_locals.last().is_some_and(|s| s.contains(name)) => {
ops::GETLOCAL_DECLARED
}
VarKind::Local => ops::GETLOCAL,
VarKind::Instance => ops::GETIVAR,
VarKind::Class => ops::GETCVAR,
VarKind::Global => ops::GETGVAR,
VarKind::Const => ops::GETCONST,
};
self.kstr(b, name);
b.emit(Op::CallBuiltin(op, 1), self.cur_line);
}
fn compile_assign(
&mut self,
b: &mut ChunkBuilder,
target: &Expr,
value: &Expr,
) -> Result<(), String> {
match target {
Expr::Var(kind, name) => {
if let VarKind::Local = kind {
if let Some(scope) = self.scope_locals.last_mut() {
scope.insert(name.clone());
}
if let Some(slot) = self.local_slot(name) {
self.compile_expr(b, value)?;
b.emit(Op::Dup, 0);
b.emit(Op::SetSlot(slot), 0);
return Ok(());
}
}
let op = match kind {
VarKind::Local => ops::SETLOCAL,
VarKind::Instance => ops::SETIVAR,
VarKind::Class => ops::SETCVAR,
VarKind::Global => ops::SETGVAR,
VarKind::Const => ops::SETCONST,
};
let stored = if let VarKind::Const = kind {
self.qualify(name)
} else {
name.to_string()
};
self.kstr(b, &stored);
self.compile_expr(b, value)?;
b.emit(Op::CallBuiltin(op, 2), 0);
}
Expr::Index(recv, idx) => {
if idx.iter().any(|i| {
matches!(i, Expr::KwArgs(_))
|| matches!(i, Expr::Splat(inner) if matches!(**inner, Expr::KwArgs(_)))
}) {
return Err(format!(
"line {}: keywords are not allowed in index assignment expressions",
self.cur_line
));
}
let tr = self.eval_to_temp(b, recv)?;
if idx.iter().any(|i| matches!(i, Expr::Splat(_))) {
let mut spread = Vec::with_capacity(idx.len() + 1);
for i in idx {
spread.push(match i {
Expr::Splat(inner) => Expr::Splat(Box::new(Expr::Var(
VarKind::Local,
self.eval_to_temp(b, inner)?,
))),
_ => Expr::Var(VarKind::Local, self.eval_to_temp(b, i)?),
});
}
let tv = self.eval_to_temp(b, value)?;
spread.push(Expr::Var(VarKind::Local, tv.clone()));
self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
self.kstr(b, "[]=");
self.compile_spread(b, &spread)?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
b.emit(Op::Pop, 0);
self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
return Ok(());
}
let tis = idx
.iter()
.map(|i| self.eval_to_temp(b, i))
.collect::<Result<Vec<_>, _>>()?;
let tv = self.eval_to_temp(b, value)?;
self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
for ti in &tis {
self.compile_expr(b, &Expr::Var(VarKind::Local, ti.clone()))?;
}
self.compile_expr(b, &Expr::Var(VarKind::Local, tv.clone()))?;
b.emit(
Op::CallBuiltin(ops::INDEX_SET, argc(2 + idx.len())?),
self.cur_line,
);
b.emit(Op::Pop, 0);
self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
}
Expr::Call {
recv: Some(r),
name,
args,
block: None,
} if args.is_empty()
&& name.chars().next().is_some_and(|c| c.is_uppercase())
&& const_path_name(r).is_some() =>
{
let qualified = format!("{}::{name}", const_path_name(r).unwrap());
self.kstr(b, &qualified);
self.compile_expr(b, value)?;
b.emit(Op::CallBuiltin(ops::SETCONST, 2), 0);
}
Expr::Call {
recv: Some(r),
name,
args,
block: None,
} if args.is_empty() => {
let tr = self.eval_to_temp(b, r)?;
let tv = self.eval_to_temp(b, value)?;
self.compile_expr(b, &Expr::Var(VarKind::Local, tr))?;
self.kstr(b, &format!("{name}="));
self.compile_expr(b, &Expr::Var(VarKind::Local, tv.clone()))?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
b.emit(Op::Pop, 0);
self.compile_expr(b, &Expr::Var(VarKind::Local, tv))?;
}
_ => return Err("invalid assignment target".into()),
}
Ok(())
}
fn eval_to_temp(&mut self, b: &mut ChunkBuilder, e: &Expr) -> Result<String, String> {
self.tmp += 1;
let name = format!("__asgn{}__", self.tmp);
self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), e)?;
b.emit(Op::Pop, 0);
Ok(name)
}
fn compile_multi_assign(
&mut self,
b: &mut ChunkBuilder,
targets: &[Expr],
values: &[Expr],
) -> Result<(), String> {
let mut names = Vec::new();
targets
.iter()
.for_each(|t| for_locals_target(t, &mut names));
if let Some(scope) = self.scope_locals.last_mut() {
scope.extend(names);
}
let rhs = match values {
[Expr::Splat(e)] => Expr::Call {
recv: None,
name: "Array".into(),
args: vec![e.as_ref().clone()],
block: None,
},
[one] => masgn_ary(one.clone()),
_ => Expr::Array(values.to_vec()),
};
self.compile_destructure(b, targets, &rhs, 0)
}
fn compile_destructure(
&mut self,
b: &mut ChunkBuilder,
targets: &[Expr],
rhs: &Expr,
depth: usize,
) -> Result<(), String> {
let tmp = if depth == 0 {
"__massign__".to_string()
} else {
format!("__massign{depth}__")
};
self.compile_assign(b, &Expr::Var(VarKind::Local, tmp.clone()), rhs)?;
b.emit(Op::Pop, 0);
let tmp_var = || Expr::Var(VarKind::Local, tmp.clone());
let splat_at = targets.iter().position(|t| matches!(t, Expr::Splat(_)));
for (i, t) in targets.iter().enumerate() {
let (target, value): (&Expr, Expr) = match (splat_at, t) {
(Some(si), Expr::Splat(inner)) if i == si => {
let after = targets.len() - si - 1;
let len_expr = Expr::Binary(
BinOp::Sub,
Box::new(Expr::Binary(
BinOp::Sub,
Box::new(Expr::Call {
recv: Some(Box::new(tmp_var())),
name: "length".into(),
args: vec![],
block: None,
}),
Box::new(Expr::Int(after as i64)),
)),
Box::new(Expr::Int(si as i64)),
);
let slice =
Expr::Index(Box::new(tmp_var()), vec![Expr::Int(si as i64), len_expr]);
(inner.as_ref(), slice)
}
(Some(si), t) if i > si => {
let from_end = targets.len() - i; let idx = Expr::Binary(
BinOp::Sub,
Box::new(Expr::Call {
recv: Some(Box::new(tmp_var())),
name: "length".into(),
args: vec![],
block: None,
}),
Box::new(Expr::Int(from_end as i64)),
);
(t, Expr::Index(Box::new(tmp_var()), vec![idx]))
}
(_, t) => (
t,
Expr::Index(Box::new(tmp_var()), vec![Expr::Int(i as i64)]),
),
};
match target {
Expr::Array(inner) => {
self.compile_destructure(b, inner, &masgn_ary(value), depth + 1)?
}
_ => self.compile_assign(b, target, &value)?,
}
b.emit(Op::Pop, 0);
}
self.compile_var_read(b, VarKind::Local, &tmp);
Ok(())
}
fn compile_unary(&mut self, b: &mut ChunkBuilder, op: UnOp, e: &Expr) -> Result<(), String> {
self.compile_expr(b, e)?;
match op {
UnOp::Neg => {
b.emit(Op::Negate, 0);
}
UnOp::Not => {
b.emit(Op::RubyTruthy, 0);
b.emit(Op::LogNot, 0);
}
UnOp::BitNot => {
b.emit(Op::CallBuiltin(ops::BITNOT, 1), self.cur_line);
}
}
Ok(())
}
fn compile_named_capture_match(
&mut self,
b: &mut ChunkBuilder,
l: &Expr,
r: &Expr,
names: &[String],
) -> Result<(), String> {
self.compile_expr(b, l)?;
self.kstr(b, "=~");
self.compile_expr(b, r)?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
let last_match = || Expr::Var(VarKind::Global, "~".into());
for name in names {
let group = Expr::Binary(
BinOp::And,
Box::new(last_match()),
Box::new(Expr::Index(
Box::new(last_match()),
vec![Expr::Symbol(name.clone())],
)),
);
self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), &group)?;
b.emit(Op::Pop, 0);
}
Ok(())
}
fn compile_binary(
&mut self,
b: &mut ChunkBuilder,
op: BinOp,
l: &Expr,
r: &Expr,
) -> Result<(), String> {
if op == BinOp::Match {
if let Expr::Regex(source, flags) = l {
let names = regex_literal_local_names(source, flags);
if !names.is_empty() {
return self.compile_named_capture_match(b, l, r, &names);
}
}
}
if op == BinOp::And || op == BinOp::Or {
self.compile_expr(b, l)?;
b.emit(Op::Dup, 0);
b.emit(Op::RubyTruthy, 0);
let jmp = if op == BinOp::And {
b.emit(Op::JumpIfFalse(0), 0)
} else {
b.emit(Op::JumpIfTrue(0), 0)
};
b.emit(Op::Pop, 0);
self.compile_expr(b, r)?;
let end = b.current_pos();
b.patch_jump(jmp, end);
return Ok(());
}
if matches!(
op,
BinOp::Pow
| BinOp::Div
| BinOp::Mod
| BinOp::Shl
| BinOp::Shr
| BinOp::Cmp
| BinOp::CaseEq
| BinOp::Match
| BinOp::NMatch
| BinOp::BitAnd
| BinOp::BitOr
| BinOp::BitXor
) {
let name = match op {
BinOp::Pow => "**",
BinOp::Div => "/",
BinOp::Mod => "%",
BinOp::Shl => "<<",
BinOp::Shr => ">>",
BinOp::Cmp => "<=>",
BinOp::CaseEq => "===",
BinOp::BitAnd => "&",
BinOp::BitOr => "|",
BinOp::BitXor => "^",
_ => "=~", };
self.compile_expr(b, l)?;
self.kstr(b, name);
self.compile_expr(b, r)?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
if op == BinOp::NMatch {
b.emit(Op::RubyTruthy, 0);
b.emit(Op::LogNot, 0);
}
return Ok(());
}
self.compile_expr(b, l)?;
self.compile_expr(b, r)?;
let native = match op {
BinOp::Add => Op::Add,
BinOp::Sub => Op::Sub,
BinOp::Mul => Op::Mul,
BinOp::Div => Op::Div,
BinOp::Mod => Op::Mod,
BinOp::Pow => Op::Pow,
BinOp::Eq => Op::NumEq,
BinOp::Ne => Op::NumNe,
BinOp::Lt => Op::NumLt,
BinOp::Gt => Op::NumGt,
BinOp::Le => Op::NumLe,
BinOp::Ge => Op::NumGe,
BinOp::Cmp => Op::Spaceship,
BinOp::BitAnd => Op::BitAnd,
BinOp::BitOr => Op::BitOr,
BinOp::BitXor => Op::BitXor,
BinOp::Shl => Op::Shl,
BinOp::Shr => Op::Shr,
BinOp::And | BinOp::Or | BinOp::Match | BinOp::NMatch | BinOp::CaseEq => unreachable!(),
};
b.emit(native, self.cur_line);
Ok(())
}
fn compile_cond(&mut self, b: &mut ChunkBuilder, cond: &Expr) -> Result<(), String> {
self.compile_expr(b, cond)?;
b.emit(Op::RubyTruthy, 0);
Ok(())
}
fn compile_if(
&mut self,
b: &mut ChunkBuilder,
cond: &Expr,
then: &[Stmt],
elifs: &[(Expr, Vec<Stmt>)],
els: &Option<Vec<Stmt>>,
) -> Result<(), String> {
let mut end_jumps = Vec::new();
self.compile_cond(b, cond)?;
let mut skip = b.emit(Op::JumpIfFalse(0), 0);
self.compile_seq(b, then)?;
end_jumps.push(b.emit(Op::Jump(0), 0));
for (c, body) in elifs {
let here = b.current_pos();
b.patch_jump(skip, here);
self.compile_cond(b, c)?;
skip = b.emit(Op::JumpIfFalse(0), 0);
self.compile_seq(b, body)?;
end_jumps.push(b.emit(Op::Jump(0), 0));
}
let else_pos = b.current_pos();
b.patch_jump(skip, else_pos);
match els {
Some(body) => self.compile_seq(b, body)?,
None => {
b.emit(Op::LoadUndef, 0);
}
}
let end = b.current_pos();
for j in end_jumps {
b.patch_jump(j, end);
}
Ok(())
}
fn compile_while(
&mut self,
b: &mut ChunkBuilder,
cond: &Expr,
body: &[Stmt],
) -> Result<(), String> {
let start = b.current_pos();
self.loops.push(LoopCtx {
start,
body_start: start,
breaks: vec![],
nexts: vec![],
redos: vec![],
});
self.compile_cond(b, cond)?;
let exit = b.emit(Op::JumpIfFalse(0), 0);
self.loops.last_mut().unwrap().body_start = b.current_pos();
self.compile_seq(b, body)?;
b.emit(Op::Pop, 0); b.emit(Op::Jump(start), 0);
b.patch_jump(exit, b.current_pos());
b.emit(Op::LoadUndef, 0);
let end = b.current_pos();
let ctx = self.loops.pop().unwrap();
for j in ctx.breaks {
b.patch_jump(j, end);
}
for j in ctx.nexts {
b.patch_jump(j, ctx.start);
}
for j in ctx.redos {
b.patch_jump(j, ctx.body_start);
}
Ok(())
}
fn compile_do_while(
&mut self,
b: &mut ChunkBuilder,
cond: &Expr,
body: &[Stmt],
) -> Result<(), String> {
let body_start = b.current_pos();
self.loops.push(LoopCtx {
start: body_start,
body_start,
breaks: vec![],
nexts: vec![],
redos: vec![],
});
self.compile_seq(b, body)?;
b.emit(Op::Pop, 0); let cond_pos = b.current_pos();
self.compile_cond(b, cond)?;
b.emit(Op::JumpIfTrue(body_start), 0);
b.emit(Op::LoadUndef, 0);
let end = b.current_pos();
let ctx = self.loops.pop().unwrap();
for j in ctx.breaks {
b.patch_jump(j, end);
}
for j in ctx.nexts {
b.patch_jump(j, cond_pos);
}
for j in ctx.redos {
b.patch_jump(j, ctx.body_start);
}
Ok(())
}
fn compile_for(
&mut self,
b: &mut ChunkBuilder,
var: &str,
iter: &Expr,
body: &[Stmt],
) -> Result<(), String> {
self.tmp += 1;
let hidden = format!("__for{}__", self.tmp);
let mut declare = vec![var.to_string()];
for n in for_body_locals(body) {
if n != var && !n.starts_with("__") {
declare.push(n);
}
}
for name in &declare {
self.kstr(b, name);
b.emit(Op::CallBuiltin(ops::DEFINED, 1), 0);
let skip = b.emit(Op::JumpIfTrue(0), 0);
self.compile_assign(b, &Expr::Var(VarKind::Local, name.clone()), &Expr::Nil)?;
b.emit(Op::Pop, 0);
b.patch_jump(skip, b.current_pos());
}
let mut inner = vec![Stmt::from(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, var.to_string())),
Box::new(Expr::Var(VarKind::Local, hidden.clone())),
))];
inner.extend(body.iter().cloned());
let block = Block {
params: vec![hidden],
splat: None,
body: inner,
arity: None,
line: 0,
};
let call = Expr::Call {
recv: Some(Box::new(iter.clone())),
name: "each".into(),
args: vec![],
block: Some(block),
};
self.compile_expr(b, &call)
}
fn compile_case_in(
&mut self,
b: &mut ChunkBuilder,
subject: &Expr,
clauses: &[InClause],
els: &Option<Vec<Stmt>>,
) -> Result<(), String> {
self.tmp += 1;
let tmp = format!("__casein{}__", self.tmp);
let subj = Expr::Var(VarKind::Local, tmp.clone());
self.compile_assign(b, &subj, subject)?;
b.emit(Op::Pop, 0);
let reason =
(clauses.len() == 1 && els.is_none()).then(|| format!("__pmreason{}__", self.tmp));
if let Some(var) = &reason {
self.compile_assign(b, &Expr::Var(VarKind::Local, var.clone()), &Expr::Nil)?;
b.emit(Op::Pop, 0);
}
let mut end_jumps = Vec::new();
for clause in clauses {
PM_REASON.with(|r| *r.borrow_mut() = reason.clone());
let (test, binds) = lower_pattern(&clause.pattern, &subj);
PM_REASON.with(|r| *r.borrow_mut() = None);
self.compile_cond(b, &test)?;
let next = b.emit(Op::JumpIfFalse(0), 0);
for bind in &binds {
self.compile_expr(b, bind)?;
b.emit(Op::Pop, 0);
}
let guard_next = if let Some(g) = &clause.guard {
let g = match &reason {
Some(var) => {
PM_REASON.with(|r| *r.borrow_mut() = Some(var.clone()));
let checked = pm_check(g.clone(), "guard", vec![]);
PM_REASON.with(|r| *r.borrow_mut() = None);
checked
}
None => g.clone(),
};
self.compile_cond(b, &g)?;
Some(b.emit(Op::JumpIfFalse(0), 0))
} else {
None
};
self.compile_seq(b, &clause.body)?;
end_jumps.push(b.emit(Op::Jump(0), 0));
let here = b.current_pos();
b.patch_jump(next, here);
if let Some(j) = guard_next {
b.patch_jump(j, here);
}
}
match els {
Some(body) => self.compile_seq(b, body)?,
None => {
self.compile_expr(b, &subj)?;
match &reason {
Some(var) => {
self.compile_expr(b, &Expr::Var(VarKind::Local, var.clone()))?;
b.emit(Op::CallBuiltin(ops::NO_MATCH, 2), 0);
}
None => {
b.emit(Op::CallBuiltin(ops::NO_MATCH, 1), 0);
}
}
}
}
let end = b.current_pos();
for j in end_jumps {
b.patch_jump(j, end);
}
Ok(())
}
fn compile_case(
&mut self,
b: &mut ChunkBuilder,
subject: &Expr,
whens: &[(Vec<Expr>, Vec<Stmt>)],
els: &Option<Vec<Stmt>>,
) -> Result<(), String> {
let tmp = "__case__";
self.kstr(b, tmp);
self.compile_expr(b, subject)?;
b.emit(Op::CallBuiltin(ops::SETLOCAL, 2), 0);
b.emit(Op::Pop, 0);
let mut end_jumps = Vec::new();
for (labels, body) in whens {
let mut into_body = Vec::new();
for label in labels {
if let Expr::Splat(inner) = label {
let any = Expr::Call {
recv: Some(inner.clone()),
name: "any?".into(),
args: Vec::new(),
block: Some(Block {
params: vec!["__e".into()],
splat: None,
body: vec![Expr::Call {
recv: Some(Box::new(Expr::Var(VarKind::Local, "__e".into()))),
name: "===".into(),
args: vec![Expr::Var(VarKind::Local, tmp.into())],
block: None,
}
.into()],
arity: None,
line: 0,
}),
};
self.compile_expr(b, &any)?;
b.emit(Op::RubyTruthy, 0);
into_body.push(b.emit(Op::JumpIfTrue(0), 0));
continue;
}
self.compile_expr(b, label)?;
self.kstr(b, "===");
self.compile_var_read(b, VarKind::Local, tmp);
b.emit(Op::CallBuiltin(ops::CALL_METHOD, 3), self.cur_line);
b.emit(Op::RubyTruthy, 0);
into_body.push(b.emit(Op::JumpIfTrue(0), 0));
}
let skip = b.emit(Op::Jump(0), 0);
let body_pos = b.current_pos();
for j in into_body {
b.patch_jump(j, body_pos);
}
self.compile_seq(b, body)?;
end_jumps.push(b.emit(Op::Jump(0), 0));
let after = b.current_pos();
b.patch_jump(skip, after);
}
match els {
Some(body) => self.compile_seq(b, body)?,
None => {
b.emit(Op::LoadUndef, 0);
}
}
let end = b.current_pos();
for j in end_jumps {
b.patch_jump(j, end);
}
Ok(())
}
fn compile_call(
&mut self,
b: &mut ChunkBuilder,
recv: &Option<Box<Expr>>,
name: &str,
args: &[Expr],
block: &Option<Block>,
) -> Result<(), String> {
if recv.is_none() && name == METHOD_HOOK_CALL {
for a in args {
self.compile_expr(b, a)?;
}
b.emit(
Op::CallBuiltin(ops::METHOD_HOOK, argc(args.len())?),
self.cur_line,
);
return Ok(());
}
let pass_expr = block.as_ref().and_then(block_pass_expr);
let proc_id = match (&pass_expr, block) {
(Some(_), _) => None,
(None, Some(bl)) => Some(self.compile_proc(bl)?),
(None, None) => None,
};
let emit_block = |s: &mut Self, b: &mut ChunkBuilder| -> Result<(), String> {
match (&pass_expr, proc_id) {
(Some(e), _) => s.compile_expr(b, e),
(None, Some(id)) => {
b.emit(Op::LoadInt(id as i64), 0);
b.emit(Op::CallBuiltin(ops::MKPROC, 1), 0);
Ok(())
}
(None, None) => Ok(()),
}
};
let has_block = pass_expr.is_some() || proc_id.is_some();
if args.iter().any(|a| matches!(a, Expr::Splat(_))) {
if let Some(r) = recv {
self.compile_expr(b, r)?;
}
self.kstr(b, name);
self.compile_spread(b, args)?;
match (recv.is_some(), has_block) {
(true, true) => {
emit_block(self, b)?;
b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR_BLK, 4), self.cur_line);
}
(true, false) => {
b.emit(Op::CallBuiltin(ops::CALL_METHOD_ARR, 3), self.cur_line);
}
(false, true) => {
emit_block(self, b)?;
b.emit(Op::CallBuiltin(ops::CALL_ARR_BLK, 3), self.cur_line);
}
(false, false) => {
b.emit(Op::CallBuiltin(ops::CALL_ARR, 2), self.cur_line);
}
}
return Ok(());
}
match recv {
Some(r) => {
self.compile_expr(b, r)?;
self.kstr(b, name);
for a in args {
self.compile_expr(b, a)?;
}
if has_block {
emit_block(self, b)?;
b.emit(
Op::CallBuiltin(ops::CALL_METHOD_BLK, argc(3 + args.len())?),
self.cur_line,
);
} else {
b.emit(
Op::CallBuiltin(ops::CALL_METHOD, argc(2 + args.len())?),
self.cur_line,
);
}
}
None => {
self.kstr(b, name);
for a in args {
self.compile_expr(b, a)?;
}
if has_block {
emit_block(self, b)?;
b.emit(
Op::CallBuiltin(ops::CALL_BLK, argc(2 + args.len())?),
self.cur_line,
);
} else {
b.emit(
Op::CallBuiltin(ops::CALL, argc(1 + args.len())?),
self.cur_line,
);
}
}
}
Ok(())
}
fn compile_proc(&mut self, block: &Block) -> Result<usize, String> {
let saved_redo = std::mem::replace(&mut self.redo_ok, true);
self.block_depth += 1;
let r = self.compile_proc_body_arity(
&block.body,
&block.params,
block.splat,
block.arity.clone(),
block.line,
);
self.block_depth -= 1;
self.redo_ok = saved_redo;
r
}
fn compile_spread(&mut self, b: &mut ChunkBuilder, items: &[Expr]) -> Result<(), String> {
for it in items {
match it {
Expr::Splat(e) if matches!(**e, Expr::KwArgs(_)) => {
self.compile_expr(b, e)?;
b.emit(Op::CallBuiltin(ops::KWSPLAT_ARGS, 1), 0);
}
Expr::Splat(e) => self.compile_expr(b, e)?,
other => {
self.compile_expr(b, other)?;
b.emit(Op::CallBuiltin(ops::MKARRAY, 1), 0);
}
}
}
b.emit(Op::CallBuiltin(ops::MKARGS, argc(items.len())?), 0);
Ok(())
}
fn compile_proc_body(
&mut self,
body: &[Stmt],
params: &[String],
splat: Option<usize>,
) -> Result<usize, String> {
self.compile_proc_body_arity(body, params, splat, None, 0)
}
fn compile_proc_body_arity(
&mut self,
body: &[Stmt],
params: &[String],
splat: Option<usize>,
arity: Option<crate::ast::BlockArity>,
line: u32,
) -> Result<usize, String> {
let arity = arity.unwrap_or_else(|| crate::ast::BlockArity {
req: params.len().saturating_sub(splat.is_some() as usize) as u16,
..Default::default()
});
let mut frame = self.scope_locals.last().cloned().unwrap_or_default();
frame.extend(params.iter().cloned());
frame.extend(block_own_locals(&arity));
self.scope_locals.push(frame);
let block_depth = self.block_depth.max(1);
let chunk = self.compile_body_chunk(body);
self.scope_locals.pop();
let chunk = chunk?;
let id = self.procs.len();
self.procs.push(ProcDef {
params: params.to_vec(),
splat,
chunk,
arity,
block_depth,
line,
file: None,
});
Ok(id)
}
fn compile_class(
&mut self,
b: &mut ChunkBuilder,
name: &str,
superclass: &Option<String>,
body: &[Stmt],
is_module: bool,
) -> Result<(), String> {
let qname = self.qualify(name);
let resolved_super = superclass.as_ref().map(|s| self.resolve_class_name(s));
self.nesting.push(qname.clone());
let mut methods: indexmap::IndexMap<String, MethodDef> = indexmap::IndexMap::new();
let mut class_methods: indexmap::IndexMap<String, MethodDef> = indexmap::IndexMap::new();
let includes: Vec<String> = Vec::new();
let mut prepends: Vec<String> = Vec::new();
let mut extends: Vec<String> = Vec::new();
let mut init_body: Vec<Stmt> = Vec::new();
let mut module_function_mode = false;
let mut vis_mode = Visibility::Public;
let mut visibility: indexmap::IndexMap<String, Visibility> = indexmap::IndexMap::new();
let record_vis = |name: &str, vis: Visibility, map: &mut indexmap::IndexMap<_, _>| {
if vis == Visibility::Public {
map.shift_remove(name);
} else {
map.insert(name.to_string(), vis);
}
};
for stmt in body {
match &stmt.expr {
Expr::Def {
singleton_recv: Some(_),
..
} => init_body.push(stmt.clone()),
Expr::Def {
name,
params,
body,
singleton,
singleton_recv: None,
} => {
self.cur_line = stmt.line;
let def = self.compile_method_named(name, params, body)?;
if *singleton {
class_methods.insert(name.clone(), def);
} else {
if module_function_mode {
class_methods.insert(name.clone(), def.clone());
}
record_vis(name, vis_mode, &mut visibility);
methods.insert(name.clone(), def);
}
}
Expr::Call {
recv: None,
name: m,
args,
..
} if matches!(
m.as_str(),
"private" | "public" | "protected" | "module_function"
) && args.len() == 1
&& matches!(
&args[0],
Expr::Def {
singleton_recv: None,
..
}
) =>
{
let Expr::Def {
name,
params,
body,
singleton,
..
} = &args[0]
else {
unreachable!("guarded by the match arm above")
};
self.cur_line = stmt.line;
let def = self.compile_method_named(name, params, body)?;
if *singleton {
class_methods.insert(name.clone(), def);
} else {
if module_function_mode || m == "module_function" {
class_methods.insert(name.clone(), def.clone());
}
record_vis(
name,
match m.as_str() {
"private" | "module_function" => Visibility::Private,
"protected" => Visibility::Protected,
_ => Visibility::Public,
},
&mut visibility,
);
methods.insert(name.clone(), def);
}
}
Expr::Var(VarKind::Local, v)
if matches!(v.as_str(), "private" | "protected" | "public") =>
{
vis_mode = match v.as_str() {
"private" => Visibility::Private,
"protected" => Visibility::Protected,
_ => Visibility::Public,
};
}
Expr::Call {
recv: None,
name: m,
args,
..
} if matches!(m.as_str(), "private" | "protected" | "public")
&& !args.is_empty()
&& args.iter().all(|a| matches!(a, Expr::Symbol(_))) =>
{
let vis = match m.as_str() {
"private" => Visibility::Private,
"protected" => Visibility::Protected,
_ => Visibility::Public,
};
for a in args {
let Expr::Symbol(s) = a else {
unreachable!("guarded by the match arm above")
};
record_vis(s, vis, &mut visibility);
}
}
Expr::Var(VarKind::Local, v) if v == "module_function" => {
module_function_mode = true;
init_body.push(stmt.clone());
}
Expr::Call {
recv: None,
name: m,
args,
..
} if m == "module_function" => {
if args.is_empty() {
module_function_mode = true;
init_body.push(stmt.clone());
} else {
for a in args {
if let Some(field) = sym_name(a) {
if let Some(def) = methods.get(&field) {
class_methods.insert(field.clone(), def.clone());
}
record_vis(&field, Visibility::Private, &mut visibility);
}
}
}
}
Expr::Call {
recv: None,
name: m,
args,
..
} if matches!(m.as_str(), "attr_accessor" | "attr_reader" | "attr_writer") => {
self.cur_line = stmt.line;
for a in args {
if let Some(field) = sym_name(a) {
if m != "attr_writer" {
methods.insert(field.clone(), self.build_getter(&field));
record_vis(&field, vis_mode, &mut visibility);
}
if m != "attr_reader" {
let setter = format!("{field}=");
methods.insert(setter.clone(), self.build_setter(&field));
record_vis(&setter, vis_mode, &mut visibility);
}
}
}
}
Expr::Call {
recv: None,
name: m,
args,
..
} if m == "define_method" && vis_mode != Visibility::Public => {
if let Some(field) = args.first().and_then(sym_name) {
record_vis(&field, vis_mode, &mut visibility);
}
init_body.push(stmt.clone());
}
Expr::Call {
recv: None,
name: m,
args,
..
} if m == "include" => {
init_body.push(stmt.clone());
}
Expr::Call {
recv: None,
name: m,
args,
..
} if m == "prepend" => {
for a in args {
if let Some(module) = const_path_name(a) {
prepends.push(self.resolve_class_name(&module));
}
}
init_body.push(stmt.clone());
}
Expr::Call {
recv: None,
name: m,
args,
..
} if m == "extend" => {
for a in args {
if let Some(module) = const_path_name(a) {
extends.push(self.resolve_class_name(&module));
} else if matches!(a, Expr::SelfExpr) {
extends.push(qname.clone());
}
}
init_body.push(stmt.clone());
}
Expr::SingletonClass { recv: None, body } => {
let mut sc_nondefs: Vec<Stmt> = Vec::new();
for s in body {
match &s.expr {
Expr::Def {
name, params, body, ..
} => {
class_methods
.insert(name.clone(), self.compile_method(params, body)?);
}
Expr::Call {
recv: None,
name: m,
args,
..
} if matches!(
m.as_str(),
"attr_accessor" | "attr_reader" | "attr_writer"
) =>
{
for a in args {
if let Some(field) = sym_name(a) {
if m != "attr_writer" {
class_methods
.insert(field.clone(), self.build_getter(&field));
}
if m != "attr_reader" {
class_methods.insert(
format!("{field}="),
self.build_setter(&field),
);
}
}
}
}
_ => sc_nondefs.push(s.clone()),
}
}
if !sc_nondefs.is_empty() {
init_body.push(
Expr::Call {
recv: Some(Box::new(Expr::Call {
recv: Some(Box::new(Expr::SelfExpr)),
name: "singleton_class".into(),
args: Vec::new(),
block: None,
})),
name: "class_eval".into(),
args: Vec::new(),
block: Some(Block {
params: Vec::new(),
splat: None,
body: sc_nondefs,
arity: None,
line: 0,
}),
}
.into(),
);
}
}
Expr::SingletonClass { recv: Some(_), .. } => init_body.push(stmt.clone()),
_ => init_body.push(stmt.clone()),
}
let (inst, sing) = hoisted_method_names(stmt);
for (hook, names) in [("method_added", inst), ("singleton_method_added", sing)] {
if !names.is_empty() {
init_body.push(method_hook_stmt(hook, names, stmt.line));
}
}
}
let body_name = format!("__class_body__{}", next_synth_id());
if !init_body.is_empty() {
class_methods.insert(body_name.clone(), self.compile_method(&[], &init_body)?);
}
self.nesting.pop();
self.classes.push((
qname.clone(),
ClassDef {
superclass: resolved_super.clone(),
methods,
includes,
prepends,
extends,
class_methods,
visibility,
class_visibility: Default::default(),
is_module,
},
));
if let Some(sc) = superclass {
let encoded = self.const_candidates(sc);
self.kstr(b, &encoded);
b.emit(Op::CallBuiltin(ops::GETCONST, 1), self.cur_line);
b.emit(Op::Pop, 0);
}
if let Some(sc) = &resolved_super {
self.emit_hook(b, sc, "inherited", &qname);
}
let value_from_body = body.last().is_some_and(|s| init_body.last() == Some(s));
if !init_body.is_empty() {
self.kstr(b, &qname);
b.emit(Op::CallBuiltin(ops::GETCONST, 1), 0);
self.kstr(b, &body_name);
b.emit(Op::CallBuiltin(ops::CALL_METHOD, 2), self.cur_line);
if value_from_body {
return Ok(());
}
b.emit(Op::Pop, 0);
}
match body.last().map(|s| &s.expr) {
Some(Expr::Def {
name,
singleton_recv: None,
..
}) => self.compile_expr(b, &Expr::Symbol(name.clone()))?,
_ => {
b.emit(Op::LoadUndef, 0);
}
}
Ok(())
}
fn emit_hook(&mut self, b: &mut ChunkBuilder, module: &str, hook: &str, target: &str) {
self.kstr(b, module);
self.kstr(b, hook);
self.kstr(b, target);
b.emit(Op::CallBuiltin(ops::FIRE_HOOK, 3), 0);
b.emit(Op::Pop, 0);
}
fn build_getter(&mut self, field: &str) -> MethodDef {
let mut b = ChunkBuilder::new();
let idx = b.add_constant(Value::Str(Arc::new(field.to_string())));
b.emit(Op::LoadConst(idx), 0);
b.emit(Op::CallBuiltin(ops::GETIVAR, 1), 0);
MethodDef {
chunk_id: crate::host::next_method_chunk_id(),
params: vec![],
splat: None,
kwparams: vec![],
kwsplat: None,
blockparam: None,
req: 0,
opt: 0,
post: 0,
kwreq: vec![],
chunk: Arc::new(b.build()),
slot_params: 0,
line: self.cur_line,
file: None,
}
}
fn build_setter(&mut self, field: &str) -> MethodDef {
let mut b = ChunkBuilder::new();
let fidx = b.add_constant(Value::Str(Arc::new(field.to_string())));
b.emit(Op::LoadConst(fidx), 0);
let vidx = b.add_constant(Value::Str(Arc::new(ATTR_WRITER_PARAM.to_string())));
b.emit(Op::LoadConst(vidx), 0);
b.emit(Op::CallBuiltin(ops::GETLOCAL, 1), 0);
b.emit(Op::CallBuiltin(ops::SETIVAR, 2), 0);
MethodDef {
chunk_id: crate::host::next_method_chunk_id(),
params: vec![ATTR_WRITER_PARAM.to_string()],
splat: None,
kwparams: vec![],
kwsplat: None,
blockparam: None,
req: 1,
opt: 0,
post: 0,
kwreq: vec![],
chunk: Arc::new(b.build()),
slot_params: 0,
line: self.cur_line,
file: None,
}
}
fn compile_begin(
&mut self,
b: &mut ChunkBuilder,
body: &[Stmt],
rescues: &[Rescue],
ensure: &Option<Vec<Stmt>>,
) -> Result<(), String> {
let saved_redo = self.redo_ok;
if !self.loops.is_empty() {
self.redo_ok = true;
}
let body_id = self.compile_proc_body(body, &[], None)?;
let mut rdefs = Vec::new();
for r in rescues {
let rid = self.compile_proc_body(&r.body, &[], None)?;
let splat = match &r.splat {
Some(e) => Some(self.compile_proc_body(
std::slice::from_ref(&Stmt::from(e.clone())),
&[],
None,
)?),
None => None,
};
rdefs.push(RescueDef {
classes: r.classes.clone(),
splat,
body: rid,
});
}
let ensure_id = match ensure {
Some(e) => Some(self.compile_proc_body(e, &[], None)?),
None => None,
};
self.redo_ok = saved_redo;
let begin_id = self.begins.len();
self.begins.push(BeginDef {
body: body_id,
rescues: rdefs,
ensure: ensure_id,
});
b.emit(Op::LoadInt(begin_id as i64), 0);
let op = if self.loops.is_empty() {
ops::BEGIN
} else {
ops::BEGIN_IN_LOOP
};
b.emit(Op::CallBuiltin(op, 1), 0);
self.emit_loop_signal_handoff(b);
Ok(())
}
fn emit_loop_signal_handoff(&mut self, b: &mut ChunkBuilder) {
if self.loops.is_empty() {
return;
}
b.emit(Op::CallBuiltin(ops::TAKE_LOOP_NEXT, 0), 0);
let no_next = b.emit(Op::JumpIfFalse(0), 0);
b.emit(Op::Pop, 0);
let next_jump = b.emit(Op::Jump(0), 0);
b.patch_jump(no_next, b.current_pos());
b.emit(Op::CallBuiltin(ops::PEEK_LOOP_BREAK, 0), 0);
let no_break = b.emit(Op::JumpIfFalse(0), 0);
b.emit(Op::Pop, 0);
b.emit(Op::CallBuiltin(ops::TAKE_LOOP_BREAK, 0), 0);
let break_jump = b.emit(Op::Jump(0), 0);
b.patch_jump(no_break, b.current_pos());
b.emit(Op::CallBuiltin(ops::TAKE_LOOP_REDO, 0), 0);
let no_redo = b.emit(Op::JumpIfFalse(0), 0);
b.emit(Op::Pop, 0);
let redo_jump = b.emit(Op::Jump(0), 0);
b.patch_jump(no_redo, b.current_pos());
let ctx = self.loops.last_mut().unwrap();
ctx.nexts.push(next_jump);
ctx.breaks.push(break_jump);
ctx.redos.push(redo_jump);
}
fn compile_flow(
&mut self,
b: &mut ChunkBuilder,
e: &Option<Box<Expr>>,
sig_op: u16,
kind: FlowKind,
) -> Result<(), String> {
let in_loop = !self.loops.is_empty();
match e {
Some(e) => self.compile_expr(b, e)?,
None => {
b.emit(Op::LoadUndef, 0);
}
}
if in_loop && matches!(kind, FlowKind::Break | FlowKind::Next) {
if matches!(kind, FlowKind::Next) {
b.emit(Op::Pop, 0);
}
let j = b.emit(Op::Jump(0), 0);
let ctx = self.loops.last_mut().unwrap();
match kind {
FlowKind::Break => ctx.breaks.push(j),
FlowKind::Next => ctx.nexts.push(j),
_ => {}
}
b.emit(Op::LoadUndef, 0); } else {
b.emit(Op::CallBuiltin(sig_op, 1), 0);
}
Ok(())
}
fn kstr(&mut self, b: &mut ChunkBuilder, s: &str) {
let idx = b.add_constant(Value::Str(Arc::new(s.to_string())));
b.emit(Op::LoadConst(idx), 0);
}
fn compile_defined(&mut self, b: &mut ChunkBuilder, operand: &Expr) -> Result<(), String> {
let lit = |c: &mut Self, b: &mut ChunkBuilder, s: &str| {
c.kstr(b, s);
b.emit(Op::CallBuiltin(ops::MKSTR, 1), 0);
};
let check = |c: &mut Self, b: &mut ChunkBuilder, kind: &str, name: &str| {
c.kstr(b, kind);
c.kstr(b, name);
b.emit(Op::CallBuiltin(ops::DEFINED_DESC, 2), 0);
};
match operand {
Expr::Nil => lit(self, b, "nil"),
Expr::True => lit(self, b, "true"),
Expr::False => lit(self, b, "false"),
Expr::SelfExpr => lit(self, b, "self"),
Expr::Assign(..) | Expr::MultiAssign { .. } => lit(self, b, "assignment"),
Expr::Var(VarKind::Const, n) => check(self, b, "const", n),
Expr::Var(VarKind::Instance, n) => check(self, b, "ivar", n),
Expr::Var(VarKind::Global, n) => check(self, b, "gvar", n),
Expr::Var(VarKind::Class, n) => check(self, b, "cvar", n),
Expr::Var(VarKind::Local, n) => check(self, b, "local", n),
Expr::Yield(_) => check(self, b, "yield", ""),
Expr::Super { .. } => check(self, b, "super", ""),
Expr::Call { .. } if const_path_name(operand).is_some() => {
let path = const_path_name(operand).unwrap();
check(self, b, "const", &path);
}
Expr::Call {
recv: None,
name,
args,
block: None,
} if args.is_empty() => check(self, b, "local", name),
Expr::Call { .. } | Expr::Binary(..) | Expr::Unary(..) | Expr::Index(..) => {
lit(self, b, "method")
}
_ => lit(self, b, "expression"),
}
Ok(())
}
}
enum FlowKind {
Return,
Break,
Next,
}
fn block_pass_expr(block: &Block) -> Option<&Expr> {
match block.body.as_slice() {
[stmt] => match &stmt.expr {
Expr::BlockPass(e) => Some(e),
_ => None,
},
_ => None,
}
}
const METHOD_HOOK_CALL: &str = "<method-hook>";
fn method_hook_stmt(hook: &str, names: Vec<String>, line: u32) -> Stmt {
let mut args = vec![Expr::Str(vec![StrPart::Lit(hook.to_string())])];
args.extend(names.into_iter().map(Expr::Symbol));
Stmt {
expr: Expr::Call {
recv: None,
name: METHOD_HOOK_CALL.to_string(),
args,
block: None,
},
line,
}
}
fn hoisted_method_names(stmt: &Stmt) -> (Vec<String>, Vec<String>) {
fn attrs(m: &str, args: &[Expr], out: &mut Vec<String>) {
for field in args.iter().filter_map(sym_name) {
if m != "attr_writer" {
out.push(field.clone());
}
if m != "attr_reader" {
out.push(format!("{field}="));
}
}
}
fn is_attr(m: &str) -> bool {
matches!(m, "attr_accessor" | "attr_reader" | "attr_writer")
}
let mut inst = Vec::new();
let mut sing = Vec::new();
let mut def_of = |e: &Expr| {
if let Expr::Def {
name,
singleton,
singleton_recv: None,
..
} = e
{
if *singleton {
sing.push(name.clone());
} else {
inst.push(name.clone());
}
}
};
match &stmt.expr {
e @ Expr::Def { .. } => def_of(e),
Expr::Call {
recv: None,
name: m,
args,
..
} if matches!(
m.as_str(),
"private" | "public" | "protected" | "module_function"
) && args.len() == 1 =>
{
def_of(&args[0])
}
Expr::Call {
recv: None,
name: m,
args,
..
} if is_attr(m) => attrs(m, args, &mut inst),
Expr::SingletonClass { recv: None, body } => {
for s in body {
match &s.expr {
Expr::Def { name, .. } => sing.push(name.clone()),
Expr::Call {
recv: None,
name: m,
args,
..
} if is_attr(m) => attrs(m, args, &mut sing),
_ => {}
}
}
}
_ => {}
}
(inst, sing)
}
fn sym_name(e: &Expr) -> Option<String> {
match e {
Expr::Symbol(s) => Some(s.clone()),
Expr::Str(parts) => match parts.as_slice() {
[StrPart::Lit(s)] => Some(s.clone()),
_ => None,
},
_ => None,
}
}
fn const_path_name(e: &Expr) -> Option<String> {
match e {
Expr::Var(VarKind::Const, n) => Some(n.strip_prefix("::").unwrap_or(n).to_string()),
Expr::Call {
recv: Some(r),
name,
args,
block,
} if args.is_empty()
&& block.is_none()
&& name.chars().next().is_some_and(|c| c.is_uppercase()) =>
{
Some(format!("{}::{}", const_path_name(r)?, name))
}
_ => None,
}
}
fn argc(n: usize) -> Result<u8, String> {
u8::try_from(n).map_err(|_| format!("too many arguments/elements ({n} > 255)"))
}
fn pcall(recv: Expr, name: &str, args: Vec<Expr>) -> Expr {
Expr::Call {
recv: Some(Box::new(recv)),
name: name.to_string(),
args,
block: None,
}
}
fn pand(a: Expr, b: Expr) -> Expr {
Expr::Binary(BinOp::And, Box::new(a), Box::new(b))
}
thread_local! {
static PM_REASON: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
}
fn pm_check(test: Expr, kind: &str, details: Vec<Expr>) -> Expr {
let Some(var) = PM_REASON.with(|r| r.borrow().clone()) else {
return test;
};
let mut items = vec![Expr::Symbol(kind.to_string())];
items.extend(details);
let record = Expr::Assign(
Box::new(Expr::Var(VarKind::Local, var)),
Box::new(Expr::Array(items)),
);
Expr::Binary(
BinOp::Or,
Box::new(test),
Box::new(pand(record, Expr::False)),
)
}
fn eqq_check(pattern: &Expr, subj: &Expr) -> Expr {
pm_check(
pcall(pattern.clone(), "===", vec![subj.clone()]),
"eqq",
vec![pattern.clone(), subj.clone()],
)
}
fn pindex(subj: &Expr, i: i64) -> Expr {
Expr::Index(Box::new(subj.clone()), vec![Expr::Int(i)])
}
fn pindex_expr(subj: &Expr, idx: Expr) -> Expr {
Expr::Index(Box::new(subj.clone()), vec![idx])
}
fn padd(e: Expr, n: i64) -> Expr {
Expr::Binary(BinOp::Add, Box::new(e), Box::new(Expr::Int(n)))
}
fn psub(e: Expr, n: i64) -> Expr {
Expr::Binary(BinOp::Sub, Box::new(e), Box::new(Expr::Int(n)))
}
static FIND_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn lower_pattern(pat: &Pattern, subj: &Expr) -> (Expr, Vec<Expr>) {
match pat {
Pattern::Value(v) => (eqq_check(v, subj), vec![]),
Pattern::Pin(e) => (eqq_check(e, subj), vec![]),
Pattern::Bind(name) if name == "_" => (Expr::True, vec![]),
Pattern::Bind(name) => (
Expr::True,
vec![Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(subj.clone()),
)],
),
Pattern::Const(name, None) => (
eqq_check(&Expr::Var(VarKind::Const, name.clone()), subj),
vec![],
),
Pattern::Const(name, Some(inner)) => {
let type_test = eqq_check(&Expr::Var(VarKind::Const, name.clone()), subj);
let (t, binds) = match inner.as_ref() {
Pattern::Hash(..) => lower_pattern(inner, subj),
_ => lower_pattern(inner, &pcall(subj.clone(), "deconstruct", vec![])),
};
(pand(type_test, t), binds)
}
Pattern::As(inner, name) => {
let (t, mut binds) = lower_pattern(inner, subj);
binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(subj.clone()),
));
(t, binds)
}
Pattern::Or(alts) => {
let test = alts
.iter()
.map(|p| lower_pattern(p, subj).0)
.reduce(|a, c| Expr::Binary(BinOp::Or, Box::new(a), Box::new(c)))
.unwrap_or(Expr::False);
(test, vec![])
}
Pattern::Splat(_) => (Expr::True, vec![]), Pattern::Array(elems) => lower_array_pattern(elems, subj),
Pattern::Hash(pairs, rest) => lower_hash_pattern(pairs, rest, subj),
}
}
fn lower_array_pattern(elems: &[Pattern], subj: &Expr) -> (Expr, Vec<Expr>) {
if elems.len() >= 3
&& matches!(elems.first(), Some(Pattern::Splat(_)))
&& matches!(elems.last(), Some(Pattern::Splat(_)))
&& !elems[1..elems.len() - 1]
.iter()
.any(|p| matches!(p, Pattern::Splat(_)))
{
return lower_find_pattern(elems, subj);
}
let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let d = Expr::Var(VarKind::Local, format!("__decon{uid}__"));
let gate = pm_check(
pcall(
subj.clone(),
"respond_to?",
vec![Expr::Symbol("deconstruct".into())],
),
"deconstruct",
vec![subj.clone()],
);
let assign_d = Expr::Assign(
Box::new(d.clone()),
Box::new(pcall(subj.clone(), "deconstruct", vec![])),
);
let splat_at = elems.iter().position(|p| matches!(p, Pattern::Splat(_)));
let len = || pcall(d.clone(), "length", vec![]);
let mut test = pand(gate, assign_d);
let mut binds = Vec::new();
match splat_at {
None => {
test = pand(
test,
pm_check(
Expr::Binary(
BinOp::Eq,
Box::new(len()),
Box::new(Expr::Int(elems.len() as i64)),
),
"length",
vec![
d.clone(),
len(),
Expr::Str(vec![StrPart::Lit(elems.len().to_string())]),
],
),
);
for (i, p) in elems.iter().enumerate() {
let (t, bs) = lower_pattern(p, &pindex(&d, i as i64));
test = pand(test, t);
binds.extend(bs);
}
}
Some(s) => {
let pre = &elems[..s];
let post = &elems[s + 1..];
let min = (pre.len() + post.len()) as i64;
test = pand(
test,
pm_check(
Expr::Binary(BinOp::Ge, Box::new(len()), Box::new(Expr::Int(min))),
"length",
vec![
d.clone(),
len(),
Expr::Str(vec![StrPart::Lit(format!("{min}+"))]),
],
),
);
for (i, p) in pre.iter().enumerate() {
let (t, bs) = lower_pattern(p, &pindex(&d, i as i64));
test = pand(test, t);
binds.extend(bs);
}
if let Pattern::Splat(Some(name)) = &elems[s] {
let count = Expr::Binary(
BinOp::Sub,
Box::new(Expr::Binary(
BinOp::Sub,
Box::new(len()),
Box::new(Expr::Int(pre.len() as i64)),
)),
Box::new(Expr::Int(post.len() as i64)),
);
let slice = Expr::Index(
Box::new(d.clone()),
vec![Expr::Int(pre.len() as i64), count],
);
binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(slice),
));
}
for (j, p) in post.iter().enumerate() {
let idx = -(post.len() as i64) + j as i64;
let (t, bs) = lower_pattern(p, &pindex(&d, idx));
test = pand(test, t);
binds.extend(bs);
}
}
}
(test, binds)
}
fn lower_find_pattern(elems: &[Pattern], subj: &Expr) -> (Expr, Vec<Expr>) {
let pre = &elems[0];
let post = &elems[elems.len() - 1];
let mids = &elems[1..elems.len() - 1];
let k = mids.len() as i64;
let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let d = Expr::Var(VarKind::Local, format!("__findd{uid}__"));
let idx = Expr::Var(VarKind::Local, format!("__find_i{uid}__"));
let s_name = format!("__find_s{uid}__");
let s = Expr::Var(VarKind::Local, s_name.clone());
let len = || pcall(d.clone(), "length", vec![]);
let reason = PM_REASON.with(|r| r.borrow_mut().take());
let pred = mids
.iter()
.enumerate()
.map(|(j, m)| lower_pattern(m, &pindex_expr(&d, padd(s.clone(), j as i64))).0)
.reduce(pand)
.unwrap_or(Expr::True);
PM_REASON.with(|r| *r.borrow_mut() = reason);
let scan = Expr::If {
cond: Box::new(pand(pcall(idx.clone(), "nil?", vec![]), pred)),
then: vec![Expr::Assign(Box::new(idx.clone()), Box::new(s.clone())).into()],
elifs: vec![],
els: None,
};
let range = Expr::Range {
lo: Some(Box::new(Expr::Int(0))),
hi: Some(Box::new(psub(len(), k))),
exclusive: false,
};
let each = Expr::Call {
recv: Some(Box::new(range)),
name: "each".into(),
args: vec![],
block: Some(Block {
params: vec![s_name],
splat: None,
body: vec![scan.into()],
arity: None,
line: 0,
}),
};
let found = Expr::Begin {
body: vec![
Expr::Assign(Box::new(idx.clone()), Box::new(Expr::Nil)).into(),
each.into(),
Expr::Binary(BinOp::Ne, Box::new(idx.clone()), Box::new(Expr::Nil)).into(),
],
rescues: vec![],
ensure: None,
};
let gate = pm_check(
pcall(
subj.clone(),
"respond_to?",
vec![Expr::Symbol("deconstruct".into())],
),
"deconstruct",
vec![subj.clone()],
);
let assign_d = Expr::Assign(
Box::new(d.clone()),
Box::new(pcall(subj.clone(), "deconstruct", vec![])),
);
let found = pm_check(found, "find", vec![d.clone()]);
let long_enough = pm_check(
Expr::Binary(BinOp::Ge, Box::new(len()), Box::new(Expr::Int(k))),
"length",
vec![
d.clone(),
len(),
Expr::Str(vec![StrPart::Lit(format!("{k}+"))]),
],
);
let test = pand(gate, pand(assign_d, pand(long_enough, found)));
let mut binds = Vec::new();
if let Pattern::Splat(Some(name)) = pre {
binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(Expr::Index(
Box::new(d.clone()),
vec![Expr::Int(0), idx.clone()],
)),
));
}
for (j, m) in mids.iter().enumerate() {
binds.extend(lower_pattern(m, &pindex_expr(&d, padd(idx.clone(), j as i64))).1);
}
if let Pattern::Splat(Some(name)) = post {
let start = padd(idx.clone(), k);
let count = Expr::Binary(BinOp::Sub, Box::new(len()), Box::new(start.clone()));
binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(Expr::Index(Box::new(d.clone()), vec![start, count])),
));
}
(test, binds)
}
fn lower_hash_pattern(
pairs: &[(String, Option<Pattern>)],
rest: &HashRest,
subj: &Expr,
) -> (Expr, Vec<Expr>) {
let uid = FIND_UID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dh = Expr::Var(VarKind::Local, format!("__deconk{uid}__"));
let keys_arg = if matches!(rest, HashRest::None) && !pairs.is_empty() {
Expr::Array(pairs.iter().map(|(k, _)| Expr::Symbol(k.clone())).collect())
} else {
Expr::Nil
};
let gate = pm_check(
pcall(
subj.clone(),
"respond_to?",
vec![Expr::Symbol("deconstruct_keys".into())],
),
"deconstruct_keys",
vec![subj.clone()],
);
let assign_dh = Expr::Assign(
Box::new(dh.clone()),
Box::new(pcall(subj.clone(), "deconstruct_keys", vec![keys_arg])),
);
let mut test = pand(gate, assign_dh);
let mut binds = Vec::new();
for (key, sub) in pairs {
let at = Expr::Index(Box::new(dh.clone()), vec![Expr::Symbol(key.clone())]);
test = pand(
test,
pm_check(
pcall(dh.clone(), "key?", vec![Expr::Symbol(key.clone())]),
"key",
vec![Expr::Symbol(key.clone()), dh.clone()],
),
);
match sub {
None => binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, key.clone())),
Box::new(at),
)),
Some(p) => {
let (t, bs) = lower_pattern(p, &at);
test = pand(test, t);
binds.extend(bs);
}
}
}
if let HashRest::Splat(Some(name)) = rest {
let except_args = pairs
.iter()
.map(|(k, _)| Expr::Symbol(k.clone()))
.collect::<Vec<_>>();
binds.push(Expr::Assign(
Box::new(Expr::Var(VarKind::Local, name.clone())),
Box::new(pcall(dh.clone(), "except", except_args)),
));
}
let exact =
matches!(rest, HashRest::Nil) || (matches!(rest, HashRest::None) && pairs.is_empty());
if exact {
let (kind, detail) = if pairs.is_empty() {
("empty", dh.clone())
} else {
let keys = pairs.iter().map(|(k, _)| Expr::Symbol(k.clone())).collect();
("rest", pcall(dh.clone(), "except", keys))
};
test = pand(
test,
pm_check(
Expr::Binary(
BinOp::Eq,
Box::new(pcall(dh.clone(), "length", vec![])),
Box::new(Expr::Int(pairs.len() as i64)),
),
kind,
vec![detail],
),
);
}
(test, binds)
}