Initial type inference impl

This commit is contained in:
2026-09-08 18:52:47 +00:00
parent be53d3a5e5
commit 51bcac6225
5 changed files with 615 additions and 286 deletions
+310
View File
@@ -0,0 +1,310 @@
use crate::{
parse::{AtomRef, ImmOperand, JsValue, opcodes::OpCode},
regify::RegInstr,
};
#[derive(Debug, Clone, PartialEq)]
pub enum Type {
Unknown,
Undefined,
Bool,
Int,
Float,
Empty,
/// A named function, by flat fn id.
Fn(usize),
ReturnOf((usize, Vec<Type>)),
Any,
}
#[derive(Debug)]
pub enum CodeKind {
Code(Vec<RegInstr>),
DefineField(AtomRef),
PutField(AtomRef),
}
#[derive(Debug)]
pub struct Signature {
pub args: Vec<Type>,
pub ret: Type,
}
#[derive(Debug)]
pub struct InferFn {
pub name: String,
pub cpool: Vec<JsValue>,
pub code: CodeKind,
pub sigs: Vec<Signature>,
/// One entry per value id, so a value's type is `types[v]`. regify keeps
/// the first `var_count` ids for the locals, so a local's type lives there
/// too and `put_loc` / `get_loc` just copy between the two.
pub types: Vec<Type>,
}
/// The lattice, joining what a value already holds with what it is being
/// given. Unknown is the bottom and gives way to anything; Any is the top and
/// swallows everything; two types that disagree can only be described by Any.
pub fn join(a: &Type, b: &Type) -> Type {
match (a, b) {
(Type::Unknown, t) | (t, Type::Unknown) => t.clone(),
(Type::Any, _) | (_, Type::Any) => Type::Any,
(a, b) if a == b => a.clone(),
_ => Type::Any,
}
}
/// Walk a function's code once, giving every value a type, and hand back what
/// the function returns. A call is followed down into its callee.
pub fn infer(fn_id: usize, fns: &mut Vec<InferFn>) -> Type {
// The caller left this function's argument types here before recursing.
let args = match fns[fn_id].sigs.first() {
Some(sig) => sig.args.clone(),
None => vec![],
};
// The two field writers have no body: their result IS the shape term that
// names them, built from the types they were handed.
let code = match &fns[fn_id].code {
CodeKind::DefineField(_) | CodeKind::PutField(_) => return Type::ReturnOf((fn_id, args)),
// An empty body means this function's code is out on the stack, so we
// have come back round a cycle. Unknown is the bottom, and a later
// round raises it.
CodeKind::Code(c) if c.is_empty() => return Type::Unknown,
CodeKind::Code(_) => {
let taken = std::mem::replace(&mut fns[fn_id].code, CodeKind::Code(vec![]));
let CodeKind::Code(code) = taken else {
unreachable!()
};
code
}
};
if fns[fn_id].sigs.is_empty() {
fns[fn_id].sigs.push(Signature {
args: vec![],
ret: Type::Unknown,
});
}
// The types move out too, so a callee can be inferred through `fns` while
// this function is still being walked. Both go back at the end.
let mut types = std::mem::take(&mut fns[fn_id].types);
let mut ret = Type::Unknown;
for instr in &code {
// regify does not rename locals, so a load just names the local's value
// again. It must not write to it, or it would wipe what is stored there.
let load = matches!(
instr.op,
OpCode::GetLoc0
| OpCode::GetLoc1
| OpCode::GetLoc2
| OpCode::GetLoc3
| OpCode::GetLoc0Loc1
| OpCode::GetLoc
| OpCode::GetLoc8
| OpCode::GetLocCheck
);
let ty = match instr.op {
// ── literals ────────────────────────────────────────────────
OpCode::PushMinus1
| OpCode::Push0
| OpCode::Push1
| OpCode::Push2
| OpCode::Push3
| OpCode::Push4
| OpCode::Push5
| OpCode::Push6
| OpCode::Push7
| OpCode::PushI8
| OpCode::PushI16
| OpCode::PushI32 => Type::Int,
OpCode::PushTrue | OpCode::PushFalse => Type::Bool,
OpCode::Undefined => Type::Undefined,
OpCode::Object => Type::Empty,
OpCode::PushConst | OpCode::PushConst8 | OpCode::Fclosure | OpCode::Fclosure8 => {
match instr.imm {
ImmOperand::Const(k) => match fns[fn_id].cpool.get(k as usize) {
Some(JsValue::Int(_)) => Type::Int,
Some(JsValue::Float(_)) => Type::Float,
Some(JsValue::BoolTrue) | Some(JsValue::BoolFalse) => Type::Bool,
Some(JsValue::Undefined) => Type::Undefined,
Some(&JsValue::FnById(id)) => Type::Fn(id),
_ => Type::Any,
},
_ => Type::Any,
}
}
// ── field reads ─────────────────────────────────────────────
// Walk the shape term from the outside in: the newest write of the
// field wins, which is what makes a later write shadow an earlier.
OpCode::GetField => {
let field = match instr.imm {
ImmOperand::Atom(a) => a,
_ => AtomRef::TaggedInt(u32::MAX),
};
let mut ty = types[instr.args[0]].clone();
loop {
let (id, args) = match ty {
Type::ReturnOf((id, args)) if args.len() == 2 => (id, args),
Type::Empty => break Type::Undefined, // No fields at all
_ => break Type::Any,
};
match &fns[id].code {
CodeKind::DefineField(a) | CodeKind::PutField(a) if *a == field => {
break args[1].clone();
}
CodeKind::DefineField(_) | CodeKind::PutField(_) => ty = args[0].clone(),
CodeKind::Code(_) => break Type::Any, // Not a shape we built
}
}
}
// ── arithmetic ──────────────────────────────────────────────
// A float anywhere makes the result a float; anything else can be
// a string concatenation or an object coercion, so it is Any.
OpCode::Add | OpCode::Sub | OpCode::Mul | OpCode::Div | OpCode::Mod | OpCode::Pow => {
match (&types[instr.args[0]], &types[instr.args[1]]) {
(Type::Int, Type::Int) => Type::Int,
(Type::Float, Type::Float)
| (Type::Int, Type::Float)
| (Type::Float, Type::Int) => Type::Float,
_ => Type::Any,
}
}
OpCode::Neg | OpCode::Plus | OpCode::Inc | OpCode::Dec => match types[instr.args[0]] {
Type::Int => Type::Int,
Type::Float => Type::Float,
_ => Type::Any,
},
OpCode::Lt
| OpCode::Lte
| OpCode::Gt
| OpCode::Gte
| OpCode::Eq
| OpCode::Neq
| OpCode::StrictEq
| OpCode::StrictNeq
| OpCode::Not => Type::Bool,
// ── calls ───────────────────────────────────────────────────
// demutate names a lifted callee in the immediate. Anything else
// is a callee off the stack, which this does not resolve yet.
OpCode::Call | OpCode::Call0 | OpCode::Call1 | OpCode::Call2 | OpCode::Call3 => {
// demutate names its callee in the immediate; every other call
// takes it off the stack, where it is deepest and so comes last.
// Reversing the rest puts them back in written order.
let (callee, args) = match instr.imm {
ImmOperand::Const(k) => match fns[fn_id].cpool.get(k as usize) {
Some(&JsValue::FnById(id)) => (Some(id), &instr.args[..]),
_ => (None, &instr.args[..]),
},
_ => match instr.args.last().map(|a| &types[*a]) {
Some(&Type::Fn(id)) => (Some(id), &instr.args[..instr.args.len() - 1]),
_ => (None, &instr.args[..]),
},
};
match callee {
Some(callee) => {
let args = args.iter().rev().map(|a| types[*a].clone()).collect();
fns[callee].sigs = vec![Signature {
args,
ret: Type::Unknown,
}];
infer(callee, fns)
}
None => Type::Any,
}
}
// ── arguments ───────────────────────────────────────────────
OpCode::GetArg0 => args.first().cloned().unwrap_or(Type::Undefined),
OpCode::GetArg1 => args.get(1).cloned().unwrap_or(Type::Undefined),
OpCode::GetArg2 => args.get(2).cloned().unwrap_or(Type::Undefined),
OpCode::GetArg3 => args.get(3).cloned().unwrap_or(Type::Undefined),
OpCode::GetArg => match instr.imm {
ImmOperand::Arg(k) => args.get(k as usize).cloned().unwrap_or(Type::Undefined),
_ => Type::Any,
},
// ── value movers ────────────────────────────────────────────
// These hand the value straight back, so the type goes through.
// dup pushes it twice, which the assignment below spreads over
// both destinations.
// A store into a local is one of these too: the local IS the
// destination value, so the type simply moves across.
OpCode::SetName
| OpCode::SetNameComputed
| OpCode::SetHomeObject
| OpCode::Dup
| OpCode::PutLoc0
| OpCode::PutLoc1
| OpCode::PutLoc2
| OpCode::PutLoc3
| OpCode::PutLoc
| OpCode::PutLoc8
| OpCode::PutLocCheck
| OpCode::PutLocCheckInit
| OpCode::SetLoc0
| OpCode::SetLoc1
| OpCode::SetLoc2
| OpCode::SetLoc3
| OpCode::SetLoc
| OpCode::SetLoc8 => types[instr.args[0]].clone(),
OpCode::SetLocUninitialized => Type::Unknown,
// ── returns ─────────────────────────────────────────────────
OpCode::Return => {
ret = join(&ret, &types[instr.args[0]]);
Type::Unknown
}
OpCode::ReturnUndef => {
ret = join(&ret, &Type::Undefined);
Type::Unknown
}
// ── everything else ─────────────────────────────────────────
_ => Type::Any,
};
// Assigning follows the algebra rather than overwriting. A local keeps
// one value id, so both arms of a branch write it, and the join is what
// stops the second simply winning.
//
// IMPRECISE, and it needs a CFG to fix: joining EVERY write treats a
// plain reassignment like a branch, so `let x = 1; x = 2.5` gives Any
// where Float is right. Only a merge point should join; an
// unconditional store should replace. A linear walk cannot tell the two
// apart. It also walks a loop body once, with the types from before the
// loop, instead of iterating it.
//
// Both need the jump targets, and `ImmOperand::Label` still holds a
// BYTE offset (parse.rs resolves it against pc), which means nothing
// once the code is a list of instructions.
if !load {
for &dst in &instr.dsts {
types[dst] = join(&types[dst], &ty);
}
}
}
fns[fn_id].types = types;
fns[fn_id].code = CodeKind::Code(code);
fns[fn_id].sigs[0].ret = ret.clone();
ret
}