Modifications
This commit is contained in:
+114
-133
@@ -1,19 +1,3 @@
|
||||
//! Step 1 of declass: rewrite how a class is built, in prototype form.
|
||||
//!
|
||||
//! A class-build cluster (declass_algo.txt, step 1):
|
||||
//!
|
||||
//! push_const8 #ctor ; define_class @Name
|
||||
//! ( fclosure8 #m ; define_method @meth )*
|
||||
//! ( fclosure8 #fields ; set_home_object ; put_loc ; drop )?
|
||||
//!
|
||||
//! becomes `fclosure8 #ctor` followed, per method, by
|
||||
//! `get_field "prototype" ; put_field @meth`; the field-initialiser tail is
|
||||
//! dropped. Detection (`find_class_seqs`) records the ranges; replacement
|
||||
//! (`ClassSequence::emit_prototype`) reads operands out of each matched range.
|
||||
//!
|
||||
//! Derived classes (`extends`) are unsupported and panic: prototype form would
|
||||
//! have to flatten the parent's prototype in and lower `super`.
|
||||
|
||||
use std::range::Range;
|
||||
|
||||
use crate::{
|
||||
@@ -21,81 +5,124 @@ use crate::{
|
||||
regify::{RegFn, RegInstr},
|
||||
};
|
||||
|
||||
use super::FieldInit;
|
||||
pub fn find_class_seqs(reg_fn: &RegFn) -> Vec<ClassSequence> {
|
||||
let mut ins = reg_fn.code.as_slice();
|
||||
let mut seqs = vec![];
|
||||
let mut offset = 0;
|
||||
|
||||
/// Read each constructor <-> field-initialiser link off the class builds, as
|
||||
/// fn ids. Run before `rewrite`, which drops the instructions carrying them.
|
||||
pub(super) fn field_init_links(fns: &[RegFn]) -> Vec<FieldInit> {
|
||||
let mut links = vec![];
|
||||
for f in fns {
|
||||
for seq in find_class_seqs(&f.code) {
|
||||
if let Some(link) = seq.field_init(&f.code, &f.cpool) {
|
||||
links.push(link);
|
||||
while !ins.is_empty() {
|
||||
let seq = match_class_seq(ins); // Try to match a class decl sequence
|
||||
|
||||
match seq {
|
||||
// Found class sequence, store it and advance `ins`
|
||||
Ok((rest, num_methods)) => {
|
||||
let consumed = ins.len() - rest.len(); // How many instrs were consumed
|
||||
let seq_instr = &ins[..consumed]; // The class seq's instrs
|
||||
|
||||
seqs.push(ClassSequence {
|
||||
range: Range {
|
||||
start: offset,
|
||||
end: offset + consumed,
|
||||
},
|
||||
num_methods,
|
||||
ctor_fn: fn_id(®_fn.cpool, as_const(seq_instr[0].imm)),
|
||||
field_init_fn: find_field_init_fn(seq_instr, num_methods, ®_fn.cpool),
|
||||
});
|
||||
|
||||
offset += consumed;
|
||||
ins = rest;
|
||||
}
|
||||
}
|
||||
}
|
||||
links
|
||||
}
|
||||
|
||||
/// Rewrite every class build in one function to prototype form.
|
||||
pub(super) fn rewrite(mut reg_fn: RegFn) -> RegFn {
|
||||
let seqs = find_class_seqs(®_fn.code);
|
||||
// Move the code out of reg_fn so we can consume it while still calling
|
||||
// reg_fn.fresh_val(); the empty Vec left behind costs nothing.
|
||||
let code = std::mem::take(&mut reg_fn.code);
|
||||
let total = code.len();
|
||||
|
||||
let mut out = Vec::with_capacity(total);
|
||||
let mut instrs = code.into_iter();
|
||||
let mut seqs = seqs.iter();
|
||||
let mut next_seq = seqs.next();
|
||||
let mut pos = 0;
|
||||
|
||||
while pos < total {
|
||||
match next_seq {
|
||||
Some(seq) if seq.range.start == pos => {
|
||||
let adv = seq.range.end - seq.range.start;
|
||||
let matched: Vec<RegInstr> = instrs.by_ref().take(adv).collect();
|
||||
seq.emit_prototype(&mut reg_fn, &mut out, &matched);
|
||||
pos += adv;
|
||||
next_seq = seqs.next();
|
||||
}
|
||||
_ => {
|
||||
out.push(instrs.next().unwrap());
|
||||
pos += 1;
|
||||
// Did not find sequence, advance `ins` by 1 and try again
|
||||
Err(rest) => {
|
||||
let consumed = ins.len() - rest.len(); // Handle partial consumption
|
||||
let consumed = consumed.max(1);
|
||||
offset += consumed;
|
||||
ins = &ins[consumed..];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
reg_fn.code = out;
|
||||
reg_fn
|
||||
seqs
|
||||
}
|
||||
|
||||
struct ClassSequence {
|
||||
range: Range<usize>,
|
||||
pub fn rewrite_class_to_proto(reg_fn: &mut RegFn, class_seqs: &[ClassSequence]) {
|
||||
// The prototype form is never longer than the class build it replaces, so
|
||||
// it drops straight over it and every instr outside a class seq stays put.
|
||||
// The code moves out only so fresh_val() can borrow reg_fn beside it.
|
||||
let mut code = std::mem::take(&mut reg_fn.code);
|
||||
let mut buf = vec![]; // Reused across seqs, so it allocates once
|
||||
|
||||
for seq in class_seqs {
|
||||
seq.emit_prototype(&code[seq.range], &mut || reg_fn.fresh_val(), &mut buf);
|
||||
code[seq.range].swap_with_slice(&mut buf);
|
||||
}
|
||||
|
||||
reg_fn.code = code;
|
||||
}
|
||||
|
||||
pub struct ClassSequence {
|
||||
pub range: Range<usize>,
|
||||
pub num_methods: usize,
|
||||
pub ctor_fn: usize, // Fn id of the class ctor
|
||||
pub field_init_fn: Option<usize>, // Fn id of the field init, if any
|
||||
}
|
||||
|
||||
/// The field initialiser's fn id, if the class has a field-initialiser tail.
|
||||
fn find_field_init_fn(
|
||||
matched: &[RegInstr],
|
||||
num_methods: usize,
|
||||
cpool: &[JsValue],
|
||||
) -> Option<usize> {
|
||||
let tail = 2 + 2 * num_methods; // The ctor and its methods, before the tail
|
||||
|
||||
if matched.len() == tail {
|
||||
return None; // No field-initialiser tail
|
||||
}
|
||||
|
||||
Some(fn_id(cpool, as_const(matched[tail].imm)))
|
||||
}
|
||||
|
||||
impl ClassSequence {
|
||||
/// Emit the prototype form, reading operands straight out of `matched` --
|
||||
/// the class sequence's own instructions.
|
||||
fn emit_prototype(&self, reg_fn: &mut RegFn, out: &mut Vec<RegInstr>, matched: &[RegInstr]) {
|
||||
/// Emit the prototype form into the scratchpad `buf`, reading operands
|
||||
/// straight out of `matched` -- this class sequence's own instructions.
|
||||
/// `buf` comes back padded with nops to exactly the length of the class
|
||||
/// build, so the caller can drop it over the original in place.
|
||||
fn emit_prototype<F>(&self, matched: &[RegInstr], fresh_val: &mut F, buf: &mut Vec<RegInstr>)
|
||||
where
|
||||
F: FnMut() -> usize,
|
||||
{
|
||||
buf.clear();
|
||||
|
||||
// push_const8 #ctor ; define_class -> fclosure8 #ctor (constructor kept)
|
||||
let (ctor_const, ctor_val) = self.ctor(matched);
|
||||
out.push(fclosure8(ctor_const, ctor_val));
|
||||
buf.push(fclosure8(ctor_const, ctor_val));
|
||||
|
||||
// each ( fclosure8 #m ; define_method @meth ) -> get_field + put_field
|
||||
for k in 0..self.num_methods {
|
||||
let (method_const, method_val, meth) = self.method(matched, k);
|
||||
out.push(fclosure8(method_const, method_val));
|
||||
let proto = reg_fn.fresh_val();
|
||||
out.push(get_field(proto_atom(), proto, ctor_val));
|
||||
out.push(put_field(ImmOperand::Atom(meth), method_val, proto));
|
||||
// A class with no methods has no prototype to read
|
||||
if self.num_methods > 0 {
|
||||
// The prototype cannot change between the put_fields below, so read
|
||||
// it once for the whole class instead of once per method
|
||||
let proto = fresh_val();
|
||||
buf.push(get_field(proto_atom(), proto, ctor_val));
|
||||
|
||||
// each ( fclosure8 #m ; define_method @meth ) -> fclosure8 + put_field
|
||||
for k in 0..self.num_methods {
|
||||
let (method_const, method_val, meth) = self.method(matched, k);
|
||||
buf.push(fclosure8(method_const, method_val));
|
||||
buf.push(put_field(ImmOperand::Atom(meth), method_val, proto));
|
||||
}
|
||||
}
|
||||
// the fclosure8 #fields ; set_home_object ; put_loc ; drop tail is dropped.
|
||||
|
||||
// 2 + 2n emitted against the 2 + 2n matched, less the 4-instr field
|
||||
// initialiser tail, so the emission always fits. Nop pads the slack; it
|
||||
// pops and pushes nothing, so it cannot disturb the value flow.
|
||||
let len = self.range.end - self.range.start;
|
||||
debug_assert!(buf.len() <= len, "class rewrite outgrew its range");
|
||||
buf.resize_with(len, nop);
|
||||
}
|
||||
|
||||
/// The constructor's constant and value: push_const8 #ctor ; define_class.
|
||||
/// The constructor's constant and register ID it was written to
|
||||
/// push_const8 #ctor ; define_class.
|
||||
fn ctor(&self, matched: &[RegInstr]) -> (u32, usize) {
|
||||
(as_const(matched[0].imm), matched[1].dsts[0])
|
||||
}
|
||||
@@ -111,64 +138,22 @@ impl ClassSequence {
|
||||
atom_of(define_method.imm),
|
||||
)
|
||||
}
|
||||
|
||||
/// The constructor and field-initialiser fn ids, if the class has a
|
||||
/// field-initialiser tail. `code` is the whole enclosing function, so the
|
||||
/// range indexes it directly.
|
||||
fn field_init(&self, code: &[RegInstr], cpool: &[JsValue]) -> Option<FieldInit> {
|
||||
let base = 2 + 2 * self.num_methods; // constructor + methods, before the tail
|
||||
if self.range.end - self.range.start == base {
|
||||
return None; // no field-initialiser tail
|
||||
}
|
||||
let ctor_const = as_const(code[self.range.start].imm);
|
||||
let fields_const = as_const(code[self.range.start + base].imm);
|
||||
Some(FieldInit {
|
||||
ctor: fn_id(cpool, ctor_const),
|
||||
fields: fn_id(cpool, fields_const),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn find_class_seqs(mut ins: &[RegInstr]) -> Vec<ClassSequence> {
|
||||
let mut seqs = vec![];
|
||||
let mut offset = 0;
|
||||
|
||||
while !ins.is_empty() {
|
||||
match match_class_seq(ins) {
|
||||
Ok((rest, num_methods)) => {
|
||||
let adv = ins.len() - rest.len();
|
||||
|
||||
seqs.push(ClassSequence {
|
||||
range: Range {
|
||||
start: offset,
|
||||
end: offset + adv,
|
||||
},
|
||||
num_methods,
|
||||
});
|
||||
|
||||
offset += adv;
|
||||
ins = rest;
|
||||
}
|
||||
Err(_) => {
|
||||
offset += 1;
|
||||
ins = &ins[1..];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
seqs
|
||||
}
|
||||
|
||||
// ── the grammar, as matchers over the instruction stream ───────────────────
|
||||
// ─────────────────────────── Class Sequence Grammar ─────────────────────────────────────
|
||||
// push_const8 #ctor ; define_class @Name <-- Class decl header
|
||||
// ( fclosure8 #method ; define_method @meth )* <-- Methods
|
||||
// ( fclosure8 #fields ; set_home_object ; put_loc ; drop )? <-- Field initializer stuff
|
||||
//
|
||||
// match fns return Ok(advanced_instrs) or Err(original_instrs)
|
||||
|
||||
fn match_class_seq(ins: &[RegInstr]) -> Result<(&[RegInstr], usize), &[RegInstr]> {
|
||||
let ins = match_one(ins, |i| i.op == OpCode::PushConst8)?;
|
||||
|
||||
// A class build is `push_const8 ; define_class`. Derived classes (`extends`)
|
||||
// are unsupported: prototype form would have to flatten the parent's
|
||||
// prototype in and lower `super`, neither of which is implemented.
|
||||
if let Some(i) = ins.first() {
|
||||
if i.op == OpCode::DefineClass && is_derived(i) {
|
||||
let is_derived_class = matches!(i.imm, ImmOperand::AtomU8 { arg, .. } if arg & 1 == 1);
|
||||
|
||||
if i.op == OpCode::DefineClass && is_derived_class {
|
||||
panic!("declass: derived classes (extends) are not supported");
|
||||
}
|
||||
}
|
||||
@@ -180,15 +165,7 @@ fn match_class_seq(ins: &[RegInstr]) -> Result<(&[RegInstr], usize), &[RegInstr]
|
||||
Ok((ins, num_methods))
|
||||
}
|
||||
|
||||
/// A derived class: `define_class` with the derived flag set.
|
||||
fn is_derived(i: &RegInstr) -> bool {
|
||||
matches!(i.imm, ImmOperand::AtomU8 { arg, .. } if arg & 1 == 1)
|
||||
}
|
||||
|
||||
// TODO: accessors are not handled. A getter/setter is a `define_method` with a
|
||||
// non-zero kind in `arg`; this matcher takes it for an ordinary method, so it
|
||||
// is wrongly lowered to a `put_field` (a data property) instead of an accessor
|
||||
// property. It should instead make the whole class pass through untouched.
|
||||
// TODO: accessors are not handled
|
||||
fn match_method_seq(ins: &[RegInstr]) -> Result<&[RegInstr], &[RegInstr]> {
|
||||
let ins = match_one(ins, |i| i.op == OpCode::Fclosure8)?;
|
||||
let ins = match_one(ins, |i| i.op == OpCode::DefineMethod)?;
|
||||
@@ -215,7 +192,7 @@ fn match_field_init_seq(ins: &[RegInstr]) -> Result<&[RegInstr], &[RegInstr]> {
|
||||
Ok(ins)
|
||||
}
|
||||
|
||||
// ── matcher primitives ─────────────────────────────────────────────────────
|
||||
// ───────────────────────────── Matcher Primitives ───────────────────────────────────────
|
||||
|
||||
fn match_one(i: &[RegInstr], f: impl Fn(&RegInstr) -> bool) -> Result<&[RegInstr], &[RegInstr]> {
|
||||
match i.first() {
|
||||
@@ -250,6 +227,10 @@ fn match_opt<'a>(
|
||||
|
||||
// ── emitted instructions ───────────────────────────────────────────────────
|
||||
|
||||
fn nop() -> RegInstr {
|
||||
RegInstr::new(OpCode::Nop, ImmOperand::None, vec![], vec![])
|
||||
}
|
||||
|
||||
fn fclosure8(const_index: u32, dst: usize) -> RegInstr {
|
||||
RegInstr::new(
|
||||
OpCode::Fclosure8,
|
||||
|
||||
Reference in New Issue
Block a user