Broken site based impl
This commit is contained in:
+318
-262
@@ -1,28 +1,30 @@
|
||||
//! Infers a type for every value (see `docs/model.md`, section 3)
|
||||
|
||||
pub mod sites;
|
||||
pub mod types;
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use crate::{
|
||||
libqjs::parse::{AtomRef, JsValue, opcodes::OpCode},
|
||||
native,
|
||||
native::{self, ProtoOf},
|
||||
regify::RegFn,
|
||||
transform::{FIRST_ARG, THIS_ARG},
|
||||
};
|
||||
|
||||
use types::{Code, Heap, Number, Site, Type};
|
||||
use sites::{Code, CtxId, LENGTH_FIELD, Place, Protos, SiteId, SiteTable};
|
||||
use types::{BaseType, EMPTY_STRING, Type, is_function, loose_eq, strict_eq, test, truthiness, typeof_name};
|
||||
|
||||
const LENGTH_FIELD: AtomRef = AtomRef::Predefined(51); // length
|
||||
const EMPTY_STRING: AtomRef = AtomRef::Predefined(48); // ""
|
||||
|
||||
/// One walk of a fn with one tuple of arg types (see `docs/model.md`,
|
||||
/// section 3.4)
|
||||
/// section 3.5)
|
||||
#[derive(Debug)]
|
||||
pub struct Variant {
|
||||
pub fn_id: usize,
|
||||
/// One for each of the fn's params (see `TypeCache::variant()`)
|
||||
pub arg_types: Vec<Type>,
|
||||
/// The context of the sites that it makes (see `SiteTable::context()`)
|
||||
pub ctx: CtxId,
|
||||
/// The walk in the current round, once it is done
|
||||
pub result: Option<InferResult>,
|
||||
/// What it returned in the rounds so far, which is what a call of it gives
|
||||
@@ -48,9 +50,9 @@ pub struct TypeCache {
|
||||
by_args: Vec<HashMap<Vec<Type>, usize>>,
|
||||
/// Scratch for a call's arg types
|
||||
key: Vec<Type>,
|
||||
pub heap: Heap,
|
||||
pub site_table: SiteTable,
|
||||
/// The prototype of each primitive kind, as the stdlib links it, by kind
|
||||
pub protos: [Type; 3],
|
||||
pub protos: Protos,
|
||||
/// Goes up when a variant's return or a proto changes (see `infer_types()`)
|
||||
changes: usize,
|
||||
}
|
||||
@@ -62,8 +64,9 @@ impl TypeCache {
|
||||
/// arg's kind crosses a call, not a known value, else every literal passed
|
||||
/// would make a new variant
|
||||
pub fn variant(&mut self, fn_id: usize, arg_types: &[Type], fns: &[RegFn]) -> usize {
|
||||
let site_table = &mut self.site_table;
|
||||
self.key.clear();
|
||||
self.key.extend(params(fn_id, arg_types, fns));
|
||||
self.key.extend(params(fn_id, arg_types, fns).map(|ty| site_table.widen(&ty)));
|
||||
|
||||
if let Some(&v) = self.by_args[fn_id].get(&self.key[..]) {
|
||||
return v;
|
||||
@@ -74,8 +77,9 @@ impl TypeCache {
|
||||
self.variants.push(Variant {
|
||||
fn_id,
|
||||
arg_types: self.key.clone(),
|
||||
ctx: self.site_table.context(&self.key),
|
||||
result: None,
|
||||
ret: Type::EMPTY,
|
||||
ret: Type::Unknown,
|
||||
walking: false,
|
||||
});
|
||||
|
||||
@@ -84,10 +88,47 @@ impl TypeCache {
|
||||
|
||||
/// The variant for a call that infer walked
|
||||
pub fn find(&self, fn_id: usize, arg_types: &[Type], fns: &[RegFn]) -> usize {
|
||||
let key: Vec<Type> = params(fn_id, arg_types, fns).collect();
|
||||
let site_table = &self.site_table;
|
||||
let key: Vec<Type> = params(fn_id, arg_types, fns).map(|ty| site_table.widened(&ty)).collect();
|
||||
self.by_args[fn_id][&key]
|
||||
}
|
||||
|
||||
/// The join of `f` over the members of `ty` (see `SiteTable::members()`).
|
||||
/// The lists of sums only grow, so a member stays where it is while `f`
|
||||
/// adds sums
|
||||
fn map(&mut self, ty: Type, mut f: impl FnMut(&mut Self, Type) -> Type) -> Type {
|
||||
let mut out = Type::Unknown;
|
||||
|
||||
for i in 0..self.site_table.members(&ty).len() {
|
||||
let member = self.site_table.members(&ty)[i];
|
||||
let ty = f(self, member);
|
||||
out = self.site_table.join(&out, &ty);
|
||||
}
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// The join of `f` over each pair of members of `a` and `b`
|
||||
fn map2(&mut self, a: Type, b: Type, mut f: impl FnMut(&mut Self, Type, Type) -> Type) -> Type {
|
||||
self.map(a, |cache, a| cache.map(b, |cache, b| f(cache, a, b)))
|
||||
}
|
||||
|
||||
/// What `f` gives for every member of `ty`, if all members give the same
|
||||
fn agree<T: PartialEq>(&self, ty: &Type, f: impl Fn(&Type) -> Option<T>) -> Option<T> {
|
||||
let mut members = self.site_table.members(ty).iter().map(f);
|
||||
let first = members.next()??;
|
||||
members.all(|t| t.as_ref() == Some(&first)).then_some(first)
|
||||
}
|
||||
|
||||
/// What `f` gives for every pair of members of `a` and `b`, if all pairs
|
||||
/// give the same
|
||||
fn agree2<T: PartialEq>(&self, a: &Type, b: &Type, f: impl Fn(&Type, &Type) -> Option<T>) -> Option<T> {
|
||||
let members = |t| self.site_table.members(t).iter();
|
||||
let mut pairs = members(a).flat_map(|x| members(b).map(move |y| (x, y))).map(|(x, y)| f(x, y));
|
||||
let first = pairs.next()??;
|
||||
pairs.all(|t| t.as_ref() == Some(&first)).then_some(first)
|
||||
}
|
||||
|
||||
/// Infer a call of `fn_id`, walking it unless an identical call was
|
||||
/// already walked in this round. Gives what it returns
|
||||
fn call(&mut self, fn_id: usize, arg_types: &[Type], fns: &[RegFn]) -> Type {
|
||||
@@ -104,7 +145,7 @@ impl TypeCache {
|
||||
let ret = res.ret_type;
|
||||
|
||||
let last = self.variants[v].ret;
|
||||
let joined = self.heap.join(&last, &ret);
|
||||
let joined = self.site_table.join(&last, &ret);
|
||||
self.changes += (joined != last) as usize;
|
||||
|
||||
let variant = &mut self.variants[v];
|
||||
@@ -116,9 +157,73 @@ impl TypeCache {
|
||||
}
|
||||
|
||||
/// The type of each of fn `fn_id`'s params, for a call with args of these
|
||||
/// types (see `TypeCache::variant()`)
|
||||
/// types, before known values are dropped (see `TypeCache::variant()`)
|
||||
fn params<'a>(fn_id: usize, arg_types: &'a [Type], fns: &[RegFn]) -> impl Iterator<Item = Type> + 'a {
|
||||
(0..fns[fn_id].arg_count).map(|i| arg_types.get(i).map_or(Type::UNDEFINED, Type::widen))
|
||||
(0..fns[fn_id].arg_count).map(|i| arg_types.get(i).copied().unwrap_or(Type::Undefined))
|
||||
}
|
||||
|
||||
/// A call of `code` with operands of these types (see the call rule in
|
||||
/// `walk_fn()`). Gives what it returns
|
||||
fn call_code(cache: &mut TypeCache, code: Code, arg_types: &[Type], fns: &[RegFn]) -> Type {
|
||||
let args = &arg_types[FIRST_ARG as usize..];
|
||||
|
||||
match code {
|
||||
Code::Fn(fn_id) => cache.call(fn_id, arg_types, fns),
|
||||
Code::Native(id) => native::ret_type(id, args, &cache.site_table),
|
||||
Code::ProtoLink(kind) => {
|
||||
let linked = cache.protos[kind as usize];
|
||||
let joined = cache.site_table.join(&linked, args.first().unwrap_or(&Type::Undefined));
|
||||
cache.changes += (joined != linked) as usize;
|
||||
cache.protos[kind as usize] = joined;
|
||||
Type::Undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A call of a callee of type `Any`, with operands of these types: a call of
|
||||
/// any fn object in an `Any`, with every operand an `Any`, except that the
|
||||
/// callee is its own env. That is the variant that emit's dispatch on `Any`
|
||||
/// calls (see `call_any_variant()`). Gives an `Any`
|
||||
fn call_any(cache: &mut TypeCache, arg_types: &mut [Type], fns: &[RegFn]) -> Type {
|
||||
for ty in arg_types.iter_mut() {
|
||||
*ty = cache.site_table.to_any(ty);
|
||||
}
|
||||
|
||||
for site in 0..cache.site_table.sites.len() as SiteId {
|
||||
let Some(code) = cache.site_table.site(site).code().filter(|_| cache.site_table.site(site).in_any) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
arg_types[0] = Type::Obj(site);
|
||||
let ret = call_code(cache, code, arg_types, fns);
|
||||
cache.site_table.to_any(&ret);
|
||||
}
|
||||
|
||||
Type::Any
|
||||
}
|
||||
|
||||
/// The site that `place` makes in context `ctx`, made if it is new
|
||||
fn site_at(cache: &mut TypeCache, place: Place, ctx: CtxId) -> SiteId {
|
||||
let place = cache.site_table.place_id(place);
|
||||
cache.site_table.site_at(place, ctx)
|
||||
}
|
||||
|
||||
/// An array index must be a number. Any other key is a computed field name,
|
||||
/// which is not supported
|
||||
fn check_index(cache: &TypeCache, index: &Type) {
|
||||
for member in cache.site_table.members(index) {
|
||||
if !matches!(member, Type::Int | Type::Float) {
|
||||
unimplemented!("`a[k]` with a key of type {member:?}: computed field names");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The operand types of the variant that a call on `Any`, with `n_args`
|
||||
/// args, runs for a fn object of `site`
|
||||
pub fn call_any_variant(site: SiteId, n_args: usize) -> Vec<Type> {
|
||||
let mut arg_types = vec![Type::Any; FIRST_ARG as usize + n_args];
|
||||
arg_types[0] = Type::Obj(site);
|
||||
arg_types
|
||||
}
|
||||
|
||||
/// Walk every variant from the entry, in rounds, until a round changes
|
||||
@@ -130,20 +235,20 @@ pub fn infer_types(fns: &[RegFn]) -> TypeCache {
|
||||
variants: vec![],
|
||||
by_args: fns.iter().map(|_| HashMap::new()).collect(),
|
||||
key: vec![],
|
||||
heap: Heap::new(fns),
|
||||
protos: [Type::EMPTY; 3],
|
||||
site_table: SiteTable::new(fns),
|
||||
protos: [Type::Unknown; ProtoOf::ALL.len()],
|
||||
changes: 0,
|
||||
};
|
||||
|
||||
loop {
|
||||
let before = (cache.heap.version, cache.changes);
|
||||
let before = (cache.site_table.version, cache.changes);
|
||||
cache.variants.iter_mut().for_each(|v| v.result = None);
|
||||
|
||||
// The synthetic program entry is appended last by `flatten`. It is
|
||||
// called by the host with no args
|
||||
cache.call(fns.len() - 1, &[], fns);
|
||||
|
||||
if before == (cache.heap.version, cache.changes) {
|
||||
if before == (cache.site_table.version, cache.changes) {
|
||||
return cache;
|
||||
}
|
||||
}
|
||||
@@ -152,11 +257,11 @@ pub fn infer_types(fns: &[RegFn]) -> TypeCache {
|
||||
fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferResult {
|
||||
use OpCode::*;
|
||||
|
||||
let fn_id = cache.variants[variant].fn_id;
|
||||
let (fn_id, ctx) = (cache.variants[variant].fn_id, cache.variants[variant].ctx);
|
||||
let f = ®_fns[fn_id];
|
||||
let mut val_types = vec![Type::EMPTY; f.val_count];
|
||||
let mut instr_types = vec![Type::EMPTY; f.code.len()];
|
||||
let mut ret_type = Type::EMPTY;
|
||||
let mut val_types = vec![Type::Unknown; f.val_count];
|
||||
let mut instr_types = vec![Type::Unknown; f.code.len()];
|
||||
let mut ret_type = Type::Unknown;
|
||||
|
||||
// arg `i` is value id `var_count + i` (see regify)
|
||||
// Init them with the arg types passed in
|
||||
@@ -170,13 +275,13 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
|
||||
// Scratch for calls, kept across instrs
|
||||
let mut arg_types: Vec<Type> = vec![];
|
||||
let mut codes: Vec<Code> = vec![];
|
||||
|
||||
// Walk instrs till nothing changes. A return only changes `ret_type` once
|
||||
// its block is reachable, and a field read only gives more once the heap
|
||||
// changes, so the values, the blocks and the heap are enough to watch
|
||||
// its block is reachable, and a field read only gives more once the site
|
||||
// table changes, so the values, the blocks and the site table are enough
|
||||
// to watch
|
||||
loop {
|
||||
let version = cache.heap.version;
|
||||
let version = cache.site_table.version;
|
||||
let mut changed = false;
|
||||
|
||||
for (block_idx, block) in f.blocks.iter().enumerate() {
|
||||
@@ -190,9 +295,9 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
for (offset, instr) in code.enumerate() {
|
||||
let is_ret = matches!(instr.op, Return | ReturnAsync | ReturnUndef);
|
||||
|
||||
// A rule with an empty operand gives an empty result: no value
|
||||
// has reached the instr yet
|
||||
let waits = instr.args.iter().any(|&v| val_types[v].is_empty());
|
||||
// A rule with an `Unknown` operand gives `Unknown`: no value has
|
||||
// reached the instr yet
|
||||
let waits = instr.args.iter().any(|&v| val_types[v] == Type::Unknown);
|
||||
|
||||
if (instr.dsts.is_empty() && !is_ret) || waits {
|
||||
continue;
|
||||
@@ -205,162 +310,231 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
let ty = match instr.op {
|
||||
// ────────────────────────────────────────── Literals ───────────────────────────────────────────────────────
|
||||
PushMinus1 | Push0 | Push1 | Push2 | Push3 | Push4 | Push5 | Push6 | Push7
|
||||
| PushI8 | PushI16 | PushI32 => Type::number(Number::Int),
|
||||
| PushI8 | PushI16 | PushI32 => Type::Int,
|
||||
|
||||
PushTrue => Type::bool(Some(true)),
|
||||
PushFalse => Type::bool(Some(false)),
|
||||
PushAtomValue => Type::string(Some(instr.imm.atom())),
|
||||
PushEmptyString => Type::string(Some(EMPTY_STRING)),
|
||||
PushTrue => Type::Bool(Some(true)),
|
||||
PushFalse => Type::Bool(Some(false)),
|
||||
PushAtomValue => Type::Str(Some(instr.imm.atom())),
|
||||
PushEmptyString => Type::Str(Some(EMPTY_STRING)),
|
||||
|
||||
PushConst | PushConst8 => match f.cpool[instr.imm.const_idx()] {
|
||||
JsValue::Int(_) => Type::number(Number::Int),
|
||||
JsValue::Float(_) => Type::number(Number::Float),
|
||||
JsValue::String(_) => Type::string(None),
|
||||
JsValue::BoolTrue => Type::bool(Some(true)),
|
||||
JsValue::BoolFalse => Type::bool(Some(false)),
|
||||
JsValue::Undefined => Type::UNDEFINED,
|
||||
JsValue::NativeFn(id) => cache.heap.create(cache.heap.builtin(Site::Native(id))),
|
||||
JsValue::ProtoLink(kind) => cache.heap.create(cache.heap.builtin(Site::ProtoLink(kind))),
|
||||
JsValue::Int(_) => Type::Int,
|
||||
JsValue::Float(_) => Type::Float,
|
||||
JsValue::String(_) => Type::Str(None),
|
||||
JsValue::BoolTrue => Type::Bool(Some(true)),
|
||||
JsValue::BoolFalse => Type::Bool(Some(false)),
|
||||
JsValue::Undefined => Type::Undefined,
|
||||
JsValue::NativeFn(id) => cache.site_table.create(cache.site_table.builtin(Place::Native(id))),
|
||||
JsValue::ProtoLink(kind) => cache.site_table.create(cache.site_table.builtin(Place::ProtoLink(kind))),
|
||||
_ => unreachable!(),
|
||||
},
|
||||
|
||||
Undefined => Type::UNDEFINED,
|
||||
Null => Type::NULL,
|
||||
Undefined => Type::Undefined,
|
||||
Null => Type::Null,
|
||||
|
||||
// ──────────────────────────────────────── Arithmetic ───────────────────────────────────────────────────────
|
||||
// `+` concatenates if either side becomes a string, which
|
||||
// only a string or an object can
|
||||
Add => {
|
||||
let (l, r) = (arg(1), arg(0));
|
||||
let is_string = |t: Type| t.is_only(Type::string(None));
|
||||
let can_be_string = |t: Type| t.string.is_some() || t.object.is_some();
|
||||
|
||||
if is_number(l) && is_number(r) {
|
||||
Type::number(l.number.max(r.number).unwrap())
|
||||
} else if is_string(l) || is_string(r) {
|
||||
Type::string(None)
|
||||
} else if can_be_string(l) || can_be_string(r) {
|
||||
Type { string: Some(None), ..Type::number(Number::Float) }
|
||||
} else {
|
||||
Type::number(Number::Float)
|
||||
}
|
||||
}
|
||||
// a string or an object does. Else it adds numbers
|
||||
Add => cache.map2(arg(1), arg(0), |_, l, r| match (l, r) {
|
||||
(Type::Any, _) | (_, Type::Any) => Type::Any,
|
||||
(l, r) if [l, r].iter().any(|t| matches!(t, Type::Str(_) | Type::Obj(_))) => Type::Str(None),
|
||||
(Type::Int, Type::Int) => Type::Int,
|
||||
_ => Type::Float,
|
||||
}),
|
||||
// Any other operator converts its operands to numbers
|
||||
Sub | Mul | Mod | Pow => match (arg(1), arg(0)) {
|
||||
(l, r) if is_int(l) && is_int(r) => Type::number(Number::Int),
|
||||
_ => Type::number(Number::Float),
|
||||
},
|
||||
Neg | Plus | Inc | Dec | PostInc | PostDec => match arg(0) {
|
||||
t if is_int(t) => Type::number(Number::Int),
|
||||
_ => Type::number(Number::Float),
|
||||
},
|
||||
Div => Type::number(Number::Float),
|
||||
Sub | Mul | Mod | Pow => cache.map2(arg(1), arg(0), |_, l, r| match (l, r) {
|
||||
(Type::Int, Type::Int) => Type::Int,
|
||||
_ => Type::Float,
|
||||
}),
|
||||
Neg | Plus | Inc | Dec | PostInc | PostDec => cache.map(arg(0), |_, t| match t {
|
||||
Type::Int => Type::Int,
|
||||
_ => Type::Float,
|
||||
}),
|
||||
Div => Type::Float,
|
||||
// Bitwise NOT gives an int32
|
||||
Not => Type::number(Number::Int),
|
||||
Not => Type::Int,
|
||||
|
||||
Lt | Lte | Gt | Gte => Type::bool(None),
|
||||
Lt | Lte | Gt | Gte => Type::Bool(None),
|
||||
|
||||
// ─────────────────────────────── Conditions the types may decide ──────────────────────────────────────────
|
||||
// A known value lets infer skip the branch that cannot run
|
||||
// (see `reachable` below)
|
||||
// An identity test of two objects (see `docs/model.md`, section 5)
|
||||
StrictEq | StrictNeq | Eq | Neq if arg(0).object.is_some() && arg(1).object.is_some() => {
|
||||
for obj in [arg(0).object, arg(1).object].into_iter().flatten() {
|
||||
cache.heap.mark(obj, |shape| &mut shape.compared);
|
||||
StrictEq | StrictNeq | Eq | Neq => {
|
||||
let (a, b) = (arg(0), arg(1));
|
||||
|
||||
// An identity test of an object with what can be an
|
||||
// object (see `docs/model.md`, section 5)
|
||||
let members = |t: &Type| cache.site_table.members(t).to_vec();
|
||||
let (a_members, b_members) = (members(&a), members(&b));
|
||||
let can_be_object = |ms: &[Type]| ms.iter().any(|t| matches!(t, Type::Obj(_) | Type::Any));
|
||||
|
||||
if can_be_object(&a_members) && can_be_object(&b_members) {
|
||||
for t in a_members.iter().chain(&b_members) {
|
||||
if let Type::Obj(site) = t {
|
||||
cache.site_table.mark(*site, |shape| &mut shape.compared);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Type::bool(None)
|
||||
let eq = match instr.op {
|
||||
StrictEq | StrictNeq => cache.agree2(&a, &b, strict_eq),
|
||||
_ => cache.agree2(&a, &b, loose_eq),
|
||||
};
|
||||
|
||||
Type::Bool(eq.map(|eq| eq == matches!(instr.op, StrictEq | Eq)))
|
||||
}
|
||||
StrictEq => Type::bool(strict_eq(&arg(0), &arg(1))),
|
||||
StrictNeq => Type::bool(strict_eq(&arg(0), &arg(1)).map(|eq| !eq)),
|
||||
Eq => Type::bool(loose_eq(&arg(0), &arg(1))),
|
||||
Neq => Type::bool(loose_eq(&arg(0), &arg(1)).map(|eq| !eq)),
|
||||
Lnot => Type::bool(truthiness(&arg(0)).map(|t| !t)),
|
||||
Typeof => typeof_of(&arg(0), &cache.heap),
|
||||
IsUndefined | TypeofIsUndefined => Type::bool(test(&arg(0), Type::UNDEFINED)),
|
||||
IsNull => Type::bool(test(&arg(0), Type::NULL)),
|
||||
IsUndefinedOrNull => Type::bool(test(&arg(0), Type { null: true, ..Type::UNDEFINED })),
|
||||
TypeofIsFunction => Type::bool(is_function(&arg(0), &cache.heap)),
|
||||
Lnot => Type::Bool(cache.agree(&arg(0), truthiness).map(|t| !t)),
|
||||
Typeof => match cache.agree(&arg(0), |t| typeof_name(t, &cache.site_table)) {
|
||||
Some(name) => Type::Str(Some(AtomRef::Predefined(name))),
|
||||
None => Type::Str(None),
|
||||
},
|
||||
IsUndefined | TypeofIsUndefined => Type::Bool(cache.agree(&arg(0), |t| test(t, &[BaseType::Undefined]))),
|
||||
IsNull => Type::Bool(cache.agree(&arg(0), |t| test(t, &[BaseType::Null]))),
|
||||
IsUndefinedOrNull => Type::Bool(cache.agree(&arg(0), |t| test(t, &[BaseType::Undefined, BaseType::Null]))),
|
||||
TypeofIsFunction => Type::Bool(cache.agree(&arg(0), |t| is_function(t, &cache.site_table))),
|
||||
|
||||
// ─────────────────────────────────────── Value Movers ──────────────────────────────────────────────────────
|
||||
SetLoc | SetName => arg(0),
|
||||
|
||||
// ───────────────────────────────────────── Objects ─────────────────────────────────────────────────────────
|
||||
Object | Fclosure | Fclosure8 => cache.heap.create(cache.heap.site_at(fn_id, idx).unwrap()),
|
||||
// The write goes into the object's shape, which every value
|
||||
// that holds the object sees. A primitive has no fields to
|
||||
// write, and undefined and null throw
|
||||
DefineField | PutField => {
|
||||
if let Some(obj) = arg(1).object {
|
||||
cache.heap.write(obj, instr.imm.atom(), &arg(0));
|
||||
Object | Fclosure | Fclosure8 => {
|
||||
let site = site_at(cache, Place::Op { fn_id, instr: idx }, ctx);
|
||||
cache.site_table.create(site)
|
||||
}
|
||||
// The elements are its operands, last first
|
||||
ArrayFrom => {
|
||||
let site = site_at(cache, Place::Op { fn_id, instr: idx }, ctx);
|
||||
|
||||
if !cache.heap.is_creation_write(fn_id, idx) {
|
||||
cache.heap.mark(obj, |shape| &mut shape.written);
|
||||
}
|
||||
for &v in &instr.args {
|
||||
cache.site_table.write_elem(site, &val_types[v]);
|
||||
}
|
||||
|
||||
cache.heap.canon(&arg(1))
|
||||
cache.site_table.create(site)
|
||||
}
|
||||
GetField => cache.heap.read_value(&arg(0), instr.imm.atom(), &cache.protos),
|
||||
// `a[i]` and `a[i] = x`, on arrays, and `s[i]` on strings:
|
||||
// an index is a number. Other objects need computed field
|
||||
// names, which are not supported. A string cannot be
|
||||
// written (module code is strict), and undefined and null
|
||||
// throw
|
||||
GetArrayEl => {
|
||||
let index = arg(0);
|
||||
|
||||
cache.map(arg(1), |cache, obj| match obj {
|
||||
Type::Obj(site) if cache.site_table.site(site).is_array() => {
|
||||
check_index(cache, &index);
|
||||
cache.site_table.read_elem(site)
|
||||
}
|
||||
Type::Str(_) => {
|
||||
check_index(cache, &index);
|
||||
cache.site_table.join(&Type::Str(None), &Type::Undefined)
|
||||
}
|
||||
Type::Undefined | Type::Null => Type::Unknown,
|
||||
obj => unimplemented!("`o[k]` on {obj:?}: computed field names"),
|
||||
})
|
||||
}
|
||||
PutArrayEl => {
|
||||
let (value, index) = (arg(0), arg(1));
|
||||
|
||||
cache.map(arg(2), |cache, obj| {
|
||||
match obj {
|
||||
Type::Obj(site) if cache.site_table.site(site).is_array() => {
|
||||
check_index(cache, &index);
|
||||
cache.site_table.write_elem(site, &value);
|
||||
cache.site_table.mark(site, |s| &mut s.written);
|
||||
}
|
||||
Type::Undefined | Type::Null | Type::Str(_) => {}
|
||||
obj => unimplemented!("`o[k] = v` on {obj:?}: computed field names"),
|
||||
}
|
||||
|
||||
Type::Unknown
|
||||
});
|
||||
|
||||
arg(2)
|
||||
}
|
||||
// A key stays as it is: a number is an index
|
||||
ToPropkey => arg(0),
|
||||
// The write goes into the fields of the object's site, which
|
||||
// every value that holds an object of the site sees. A write
|
||||
// on `Any` can reach any object in an `Any`. A primitive has
|
||||
// no fields to write, and undefined and null throw
|
||||
DefineField | PutField => {
|
||||
let (field, value) = (instr.imm.atom(), arg(0));
|
||||
// A define_field builds the object before it goes
|
||||
// anywhere (see regify)
|
||||
let creation = instr.op == DefineField;
|
||||
|
||||
cache.map(arg(1), |cache, obj| {
|
||||
match obj {
|
||||
Type::Obj(site) => {
|
||||
cache.site_table.write(site, field, &value);
|
||||
|
||||
if !creation {
|
||||
cache.site_table.mark(site, |shape| &mut shape.written);
|
||||
}
|
||||
}
|
||||
Type::Any => {
|
||||
for site in 0..cache.site_table.sites.len() as SiteId {
|
||||
if cache.site_table.site(site).in_any {
|
||||
cache.site_table.write(site, field, &value);
|
||||
cache.site_table.mark(site, |shape| &mut shape.written);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Type::Unknown
|
||||
});
|
||||
|
||||
arg(1)
|
||||
}
|
||||
GetField => cache.site_table.read_value(&arg(0), instr.imm.atom(), &cache.protos),
|
||||
// A string's length is its own. Anything else reads a
|
||||
// `length` field
|
||||
GetLength => {
|
||||
let others = Type { string: None, ..arg(0) };
|
||||
let read = cache.heap.read_value(&others, LENGTH_FIELD, &cache.protos);
|
||||
let own = Type { number: arg(0).string.map(|_| Number::Int), ..Type::EMPTY };
|
||||
cache.heap.join(&read, &own)
|
||||
}
|
||||
GetLength => cache.map(arg(0), |cache, obj| match obj {
|
||||
Type::Str(_) => Type::Int,
|
||||
obj => cache.site_table.read_value(&obj, LENGTH_FIELD, &cache.protos),
|
||||
}),
|
||||
|
||||
// ───────────────────────────────────── Function Calls ──────────────────────────────────────────────────────
|
||||
// Operands are the callee's params: the callee (its env),
|
||||
// `this`, then the args (see regify). The call runs one of
|
||||
// the callee's fns. A callee that is not a fn throws, so it
|
||||
// gives nothing
|
||||
// `this`, then the args (see regify). A callee that is not
|
||||
// a fn throws, so it gives nothing
|
||||
// The callee's env is the fn object itself, so a call of
|
||||
// each member of a sum passes that member as the env
|
||||
Call | CallMethod | CallConstructor => {
|
||||
arg_types.clear();
|
||||
arg_types.extend(instr.args.iter().map(|&v| val_types[v]));
|
||||
let args = &arg_types[FIRST_ARG as usize..];
|
||||
let this = arg(THIS_ARG as usize);
|
||||
|
||||
codes.clear();
|
||||
let ret = cache.map(arg(0), |cache, callee| {
|
||||
arg_types.clear();
|
||||
arg_types.extend(instr.args.iter().map(|&v| val_types[v]));
|
||||
arg_types[0] = callee;
|
||||
|
||||
if let Some(callee) = arg_types[0].object {
|
||||
codes.extend(&cache.heap.shape(callee).code);
|
||||
}
|
||||
|
||||
let mut ret = Type::EMPTY;
|
||||
|
||||
for &code in &codes {
|
||||
let ty = match code {
|
||||
Code::Fn(fn_id) => cache.call(fn_id, &arg_types, reg_fns),
|
||||
Code::Native(id) => native::ret_type(id, args),
|
||||
Code::ProtoLink(kind) => {
|
||||
let linked = cache.protos[kind as usize];
|
||||
let joined = cache.heap.join(&linked, &args[0]);
|
||||
cache.changes += (joined != linked) as usize;
|
||||
cache.protos[kind as usize] = joined;
|
||||
Type::UNDEFINED
|
||||
}
|
||||
};
|
||||
|
||||
ret = cache.heap.join(&ret, &ty);
|
||||
}
|
||||
match callee {
|
||||
Type::Obj(site) => match cache.site_table.site(site).code() {
|
||||
Some(code) => call_code(cache, code, &arg_types, reg_fns),
|
||||
None => Type::Unknown,
|
||||
},
|
||||
Type::Any => call_any(cache, &mut arg_types, reg_fns),
|
||||
_ => Type::Unknown,
|
||||
}
|
||||
});
|
||||
|
||||
// `new` gives what the constructor returns if that is an
|
||||
// object, else the new object itself, `this`
|
||||
let others = Type { object: None, ..ret };
|
||||
|
||||
match instr.op {
|
||||
CallConstructor if !others.is_empty() => {
|
||||
let this = val_types[instr.args[THIS_ARG as usize]];
|
||||
cache.heap.join(&Type { object: ret.object, ..Type::EMPTY }, &this)
|
||||
}
|
||||
CallConstructor => cache.map(ret, |cache, ret| match ret {
|
||||
Type::Obj(_) => ret,
|
||||
Type::Any => cache.site_table.join(&ret, &this),
|
||||
_ => this,
|
||||
}),
|
||||
_ => ret,
|
||||
}
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────── Returns ──────────────────────────────────────────────────────────
|
||||
Return | ReturnAsync => arg(0),
|
||||
ReturnUndef => Type::UNDEFINED,
|
||||
ReturnUndef => Type::Undefined,
|
||||
|
||||
_ => unreachable!("{instr:?}"),
|
||||
};
|
||||
@@ -368,16 +542,16 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
// Postfix copies come after the block's own instrs, and have no
|
||||
// entry: a copy gives the type of what it copies
|
||||
if idx < block.end {
|
||||
instr_types[idx] = cache.heap.join(&instr_types[idx], &ty);
|
||||
instr_types[idx] = cache.site_table.join(&instr_types[idx], &ty);
|
||||
}
|
||||
|
||||
if is_ret {
|
||||
ret_type = cache.heap.join(&ret_type, &ty);
|
||||
ret_type = cache.site_table.join(&ret_type, &ty);
|
||||
continue;
|
||||
}
|
||||
|
||||
for &dst in &instr.dsts {
|
||||
let joined = cache.heap.join(&val_types[dst], &ty);
|
||||
let joined = cache.site_table.join(&val_types[dst], &ty);
|
||||
changed |= joined != val_types[dst];
|
||||
val_types[dst] = joined;
|
||||
}
|
||||
@@ -390,8 +564,8 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
let jumps = match f.code[block.start..block.end].last() {
|
||||
Some(last) if matches!(last.op, IfFalse | IfFalse8 | IfTrue | IfTrue8) => {
|
||||
match val_types[last.args[0]] {
|
||||
cond if cond.is_empty() => continue,
|
||||
cond => truthiness(&cond).map(|t| t == matches!(last.op, IfTrue | IfTrue8)),
|
||||
Type::Unknown => continue,
|
||||
cond => cache.agree(&cond, truthiness).map(|t| t == matches!(last.op, IfTrue | IfTrue8)),
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
@@ -406,17 +580,11 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
}
|
||||
} // block
|
||||
|
||||
if !changed && cache.heap.version == version {
|
||||
if !changed && cache.site_table.version == version {
|
||||
break;
|
||||
}
|
||||
} // loop
|
||||
|
||||
// A type names the site its shape was kept under at the time: make it the
|
||||
// one now
|
||||
for ty in val_types.iter_mut().chain(&mut instr_types).chain([&mut ret_type]) {
|
||||
*ty = cache.heap.canon(ty);
|
||||
}
|
||||
|
||||
InferResult {
|
||||
val_types,
|
||||
instr_types,
|
||||
@@ -425,115 +593,3 @@ fn walk_fn(variant: usize, reg_fns: &[RegFn], cache: &mut TypeCache) -> InferRes
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every value of type `ty` is a number
|
||||
fn is_number(ty: Type) -> bool {
|
||||
ty.is_only(Type::number(Number::Int))
|
||||
}
|
||||
|
||||
/// Whether every value of type `ty` is an int32
|
||||
fn is_int(ty: Type) -> bool {
|
||||
ty == Type::number(Number::Int)
|
||||
}
|
||||
|
||||
/// The type, if every value of it is one value that its kind and refinement
|
||||
/// tell
|
||||
fn single(ty: &Type) -> Option<Type> {
|
||||
let one = match ty.kinds() {
|
||||
[true, false, false, false, false, false] | [false, true, false, false, false, false] => true,
|
||||
[false, false, true, false, false, false] => ty.bool.flatten().is_some(),
|
||||
[false, false, false, false, true, false] => ty.string.flatten().is_some(),
|
||||
_ => false,
|
||||
};
|
||||
|
||||
one.then_some(*ty)
|
||||
}
|
||||
|
||||
/// Whether `a === b`, if the types decide it
|
||||
fn strict_eq(a: &Type, b: &Type) -> Option<bool> {
|
||||
let disjoint = !a.kinds().iter().zip(b.kinds()).any(|(x, y)| *x && y);
|
||||
|
||||
match (single(a), single(b)) {
|
||||
_ if disjoint => Some(false),
|
||||
(Some(x), Some(y)) => Some(x == y),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a == b`, if the types decide it. Undefined and null are equal to
|
||||
/// each other and to nothing else. Two values of one kind compare as `===`
|
||||
/// does
|
||||
fn loose_eq(a: &Type, b: &Type) -> Option<bool> {
|
||||
let nullish = |t: &Type| t.has_nullish() && t.non_nullish().is_empty();
|
||||
|
||||
match (a, b) {
|
||||
_ if nullish(a) && nullish(b) => Some(true),
|
||||
_ if (nullish(a) && !b.has_nullish()) || (!a.has_nullish() && nullish(b)) => Some(false),
|
||||
_ if a.kinds() == b.kinds() && single(a).is_some() => strict_eq(a, b),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every value of type `ty` is of a kind in `kinds`: true if every
|
||||
/// value is, false if none is, `None` if the type does not decide it
|
||||
fn test(ty: &Type, kinds: Type) -> Option<bool> {
|
||||
let [inside, outside] = [true, false].map(|want| {
|
||||
ty.kinds().iter().zip(kinds.kinds()).any(|(has, of)| *has && of == want)
|
||||
});
|
||||
|
||||
match (inside, outside) {
|
||||
(true, false) => Some(true),
|
||||
(false, true) => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether every value of type `ty` is a fn, if the type decides it
|
||||
fn is_function(ty: &Type, heap: &Heap) -> Option<bool> {
|
||||
let shape = ty.object.map(|site| heap.shape(site));
|
||||
let fns = shape.is_some_and(|shape| !shape.code.is_empty());
|
||||
let others = ty.kinds()[..5].contains(&true) || shape.is_some_and(|shape| shape.plain);
|
||||
|
||||
match (fns, others) {
|
||||
(true, false) => Some(true),
|
||||
(false, _) => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a value of type `ty` is truthy, if the type decides it
|
||||
fn truthiness(ty: &Type) -> Option<bool> {
|
||||
let truthy = [
|
||||
ty.undefined.then_some(Some(false)),
|
||||
ty.null.then_some(Some(false)),
|
||||
ty.bool,
|
||||
ty.number.map(|_| None),
|
||||
ty.string.map(|s| s.map(|atom| atom != EMPTY_STRING)),
|
||||
ty.object.map(|_| Some(true)),
|
||||
];
|
||||
|
||||
let mut kinds = truthy.into_iter().flatten();
|
||||
let first = kinds.next()?;
|
||||
kinds.all(|t| t == first).then_some(first).flatten()
|
||||
}
|
||||
|
||||
/// What `typeof` gives for a value of type `ty`
|
||||
fn typeof_of(ty: &Type, heap: &Heap) -> Type {
|
||||
let shape = ty.object.map(|site| heap.shape(site));
|
||||
|
||||
let names = [
|
||||
ty.undefined.then_some(73), // "undefined"
|
||||
ty.null.then_some(77), // "object"
|
||||
ty.bool.map(|_| 75), // "boolean"
|
||||
ty.number.map(|_| 74), // "number"
|
||||
ty.string.map(|_| 76), // "string"
|
||||
shape.filter(|shape| shape.plain).map(|_| 77), // "object"
|
||||
shape.filter(|shape| !shape.code.is_empty()).map(|_| 27), // "function"
|
||||
];
|
||||
|
||||
let mut names = names.into_iter().flatten();
|
||||
|
||||
match names.next() {
|
||||
Some(name) if names.all(|n| n == name) => Type::string(Some(AtomRef::Predefined(name))),
|
||||
_ => Type::string(None),
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user