Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 50 additions & 1 deletion rust/crates/psychoscript/src/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,53 @@ use crate::object::*;
use crate::value::{Id, Value};
use crate::vm::{NativeFn, Res, Vm};

/// The fresh runtime, made once for the process: what `Vm::new_scratch` and `Vm::setup` make before any program or
/// host global, which is the same for every run. A run copies it instead of making it again, which was most of what
/// a short program cost. Its strings come first in every run's (`Strings::fresh`), so its atoms and string ids are
/// the same in all of them.
pub(crate) struct Image {
pub atoms: crate::strings::Strings,
pub heap: crate::collector::Heap,
pub realm: crate::vm::Realm,
pub names: crate::vm::Names,
pub global_map: rustc_hash::FxHashMap<Atom, Value>,
pub char_strs: Vec<crate::strings::StrId>,
}

impl Image {
/// Whether `atoms` started as this image's: its strings and atoms are the first of them.
pub fn seeds(&self, atoms: &crate::strings::Strings) -> bool {
let (bufs, count) = self.atoms.counts();
let (have_bufs, have) = atoms.counts();
have_bufs >= bufs
&& have >= count
&& atoms.lookup("length") == Some(self.names.length)
&& atoms.lookup("buffer") == Some(self.names.buffer)
}
}

pub(crate) fn image() -> &'static Image {
static IMAGE: std::sync::OnceLock<Image> = std::sync::OnceLock::new();
IMAGE.get_or_init(|| {
let mut vm = Vm::new_scratch(
crate::host::RunHost::bare(),
crate::Limits::default(),
crate::strings::Strings::new(),
);
vm.setup();
Image {
atoms: std::mem::replace(&mut vm.atoms, crate::strings::Strings::new()),
heap: vm.heap.clone_base(),
realm: vm.realm.clone(),
names: vm.names.clone(),
global_map: std::mem::take(&mut vm.global_map),
char_strs: std::mem::take(&mut vm.char_strs),
}
})
}

/// Prototypes of the standard-library kinds beyond the core ones in `Realm`.
#[derive(Default)]
#[derive(Clone, Default)]
pub struct StdProtos {
pub regexp: Id,
pub date: Id,
Expand Down Expand Up @@ -342,7 +387,11 @@ impl Vm {
Value::Obj(id)
}

/// Makes the fresh runtime's built-ins, unless the VM was made with them (`Vm::new` from the image).
pub fn setup(&mut self) {
if !self.heap.is_empty() {
return;
}
let object_proto = self.alloc(Obj::new(None, Kind::Ordinary));
self.realm.object_proto = object_proto;
// Function.prototype is itself a function that accepts anything and returns undefined, as in JS.
Expand Down
10 changes: 10 additions & 0 deletions rust/crates/psychoscript/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,16 @@ impl Heap {
}
}

/// A copy of a fresh runtime's heap, which holds only what `Obj::clone_base` copies, with room for a small
/// program's own objects.
pub(crate) fn clone_base(&self) -> Heap {
let mut heap = Heap::with_capacity(self.len() + 34);
for o in self.iter() {
heap.push(o.clone_base());
}
heap
}

/// The bytes of storage object `i` (`Kind::Storage`), past the barrier: bytes hold no references, so writing them
/// changes nothing marking must see.
#[inline(always)]
Expand Down
7 changes: 6 additions & 1 deletion rust/crates/psychoscript/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R<Program> {
bigints: c.bigints,
globals: c.globals,
templates: c.templates,
names_constructor: c.atoms.lookup("constructor").is_some(),
names_constructor: c.names_constructor,
})
}

Expand Down Expand Up @@ -1205,6 +1205,9 @@ struct Compiler<'a, 's> {
readonly: FxHashSet<SymbolId>,
/// The name `await` names were renamed to for parsing (see `rename_await_names`), which compiles as `await`.
await_alias: Option<String>,
/// The program names `constructor` as a key or a binding (`Program::names_constructor`). Its strings start as
/// the image's, which hold the name already, so they do not say.
names_constructor: bool,
/// Parameters of a function with parameter expressions, which are in their TDZ until bound in order.
param_tdz: FxHashSet<SymbolId>,
/// Function scopes whose `arguments` is read, and whether an arrow inside reads it.
Expand Down Expand Up @@ -1256,6 +1259,7 @@ impl<'a, 's> Compiler<'a, 's> {
switch_scopes: FxHashSet::default(),
readonly: FxHashSet::default(),
await_alias: None,
names_constructor: false,
param_tdz: FxHashSet::default(),
args_owner: FxHashMap::default(),
unbound: FxHashSet::default(),
Expand Down Expand Up @@ -1462,6 +1466,7 @@ impl<'a, 's> Compiler<'a, 's> {

fn atom(&mut self, s: &str) -> Atom {
let s = self.real_name(s);
self.names_constructor |= s == "constructor";
self.atoms.intern(s)
}

Expand Down
33 changes: 33 additions & 0 deletions rust/crates/psychoscript/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,39 @@ impl Obj {
}
}

/// A copy of an object of the fresh runtime, whose kinds are the few with nothing a run owns alone.
pub(crate) fn clone_base(&self) -> Obj {
let kind = match &self.kind {
Kind::Ordinary => Kind::Ordinary,
Kind::Array(items) => Kind::Array(items.clone()),
Kind::Native {
f,
data,
name,
length,
ctor,
} => Kind::Native {
f: *f,
data: *data,
name: *name,
length: *length,
ctor: *ctor,
},
Kind::Accessor(a) => Kind::Accessor(a.clone()),
Kind::Namespace(n) => Kind::Namespace(*n),
Kind::Error(None) => Kind::Error(None),
Kind::Date(t) => Kind::Date(*t),
_ => unreachable!("a fresh runtime makes no object of this kind"),
};
Obj {
proto: self.proto,
props: self.props.clone(),
kind,
flags: self.flags,
visit: 0,
}
}

pub fn is_callable(&self) -> bool {
match &self.kind {
Kind::Closure(_) | Kind::Native { .. } | Kind::Bound(_) => true,
Expand Down
6 changes: 3 additions & 3 deletions rust/crates/psychoscript/src/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl<'a> From<&'a Compiled> for Code<'a> {

/// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything.
pub fn compile_program(code: &str) -> Result<Compiled, Diagnostic> {
let mut atoms = Strings::new();
let mut atoms = Strings::fresh();
let program = compile(code, &mut atoms).map_err(|e| compile_diagnostic(code, e))?;
Ok(Compiled(Arc::new(CompiledProgram {
code: Arc::from(code),
Expand Down Expand Up @@ -166,7 +166,7 @@ pub fn start(
let (code, mut program, atoms) = match code {
Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()),
Code::Source(code) => {
let mut atoms = Strings::new();
let mut atoms = Strings::fresh();
match compile(code, &mut atoms) {
Ok(p) => (Arc::from(code), p, atoms),
Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))),
Expand Down Expand Up @@ -211,7 +211,7 @@ pub fn start_for_resume(
restored: crate::snapshot::Restored,
) -> Result<Resumed, crate::snapshot::SnapshotError> {
let code = restored.code;
let mut atoms = Strings::new();
let mut atoms = Strings::fresh();
let mut program = compile(&code, &mut atoms).map_err(|_| {
crate::snapshot::SnapshotError::new(
"Source main does not compile in this build, so it can't resume.",
Expand Down
8 changes: 4 additions & 4 deletions rust/crates/psychoscript/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ use crate::vm::{
use crate::{DiagnosticKind, Json, Limits};

/// Bumped whenever the shape of saved state changes.
pub const FORMAT: u64 = 2;
pub const FORMAT: u64 = 3;

/// A run's saved state: plain JSON, with a `header` that says where it can resume. A state changed since it was saved
/// is refused, by a hash of it in the header; the hash guards against damage, not forgery, so resume only states your
Expand Down Expand Up @@ -120,7 +120,7 @@ fn natives() -> &'static Natives {
let mut vm = Vm::new(
host::RunHost::bare(),
Limits::default(),
crate::strings::Strings::new(),
crate::strings::Strings::fresh(),
);
vm.setup();
let base = vm.heap.len();
Expand Down Expand Up @@ -391,7 +391,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result<Snapshot, Refusal> {
};
let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?;
let base = vm.snapshot_base;
let program = crate::run::compile(c.code, &mut crate::strings::Strings::new())
let program = crate::run::compile(c.code, &mut crate::strings::Strings::fresh())
.map_err(|e| Refusal::Other(e.message))?;
let limits = *vm.limits;
let metadata = vm.host.run.metadata();
Expand Down Expand Up @@ -947,7 +947,7 @@ fn hex_bytes(s: &str) -> R<Vec<u8>> {

/// Each object of a fresh run's base, encoded, to see which ones the run changed.
fn baseline(vm: &Vm, code: &str) -> R<Vec<J>> {
let mut atoms = crate::strings::Strings::new();
let mut atoms = crate::strings::Strings::fresh();
let program =
crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?;
let h = &vm.host;
Expand Down
34 changes: 30 additions & 4 deletions rust/crates/psychoscript/src/strings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,13 +222,15 @@ pub struct StrRef<'a> {
impl Strings {
pub fn new() -> Self {
let mut s = Strings {
bufs: Vec::new(),
// Sized for what a fresh runtime makes (about 380 strings, 250 of them atoms), so setting one up grows none
// of these.
bufs: Vec::with_capacity(448),
grow: Vec::new(),
arena: NO_GROW,
wtf: Vec::new(),
map: FxHashMap::default(),
atom_str: Vec::new(),
atom_index: Vec::new(),
map: FxHashMap::with_capacity_and_hasher(448, Default::default()),
atom_str: Vec::with_capacity(320),
atom_index: Vec::with_capacity(320),
gc_limit: crate::collector::first_limit(),
gc: Default::default(),
};
Expand All @@ -245,6 +247,30 @@ impl Strings {
s
}

/// The strings a compile starts from: the fresh runtime's (`builtins::image`), so they have the same ids in
/// every run and a run's VM is a copy of the image.
pub fn fresh() -> Self {
let image = &crate::builtins::image().atoms;
// Copied with room for a short program's own strings and names: a plain copy has none, and its first push
// would double it.
fn roomy<T: Clone>(from: &[T], room: usize) -> Vec<T> {
let mut v = Vec::with_capacity(from.len() + room);
v.extend_from_slice(from);
v
}
Strings {
bufs: roomy(&image.bufs, 64),
grow: image.grow.clone(),
arena: image.arena,
wtf: image.wtf.clone(),
map: image.map.clone(),
atom_str: roomy(&image.atom_str, 32),
atom_index: roomy(&image.atom_index, 32),
gc_limit: image.gc_limit,
gc: image.gc.clone(),
}
}

#[inline]
pub fn alloc(&mut self, s: String) -> StrId {
let ascii = s.is_ascii();
Expand Down
2 changes: 1 addition & 1 deletion rust/crates/psychoscript/src/test262.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ fn diagnostic(kind: DiagnosticKind, message: String) -> Diagnostic {
fn run_here(code: &str, timeout_ms: u64) -> Run {
let probe = 0u8;
DONE.with(|d| *d.borrow_mut() = None);
let mut atoms = Strings::new();
let mut atoms = Strings::fresh();
let program = match compiler::compile(code, &mut atoms) {
Ok(p) => p,
Err(e) => {
Expand Down
47 changes: 42 additions & 5 deletions rust/crates/psychoscript/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ pub enum Job {
},
}

#[derive(Clone)]
pub struct Names {
pub length: Atom,
pub name: Atom,
Expand All @@ -197,7 +198,7 @@ pub struct Names {
pub buffer: Atom,
}

#[derive(Default)]
#[derive(Clone, Default)]
pub struct Realm {
pub object_proto: Id,
pub function_proto: Id,
Expand Down Expand Up @@ -359,7 +360,29 @@ pub struct Vm {
}

impl Vm {
/// A VM with the fresh runtime's built-ins in it. One whose strings start as the image's (`Strings::fresh`, which
/// every compile starts from) copies the image, made once for the process; any other is set up from scratch by
/// `setup`, as the image itself is.
pub fn new(host: crate::host::RunHost, limits: Limits, atoms: Strings) -> Self {
let image = crate::builtins::image();
if !image.seeds(&atoms) {
return Self::new_scratch(host, limits, atoms);
}
let mut vm = Self::bare(
host,
limits,
atoms,
image.names.clone(),
image.char_strs.clone(),
);
vm.heap = image.heap.clone_base();
vm.realm = image.realm.clone();
vm.global_map = image.global_map.clone();
vm
}

/// A VM with no built-ins yet, its names interned here.
pub(crate) fn new_scratch(host: crate::host::RunHost, limits: Limits, atoms: Strings) -> Self {
let mut atoms = atoms;
let names = Names {
length: atoms.intern_static("length"),
Expand All @@ -385,18 +408,32 @@ impl Vm {
byte_offset: atoms.intern_static("byteOffset"),
buffer: atoms.intern_static("buffer"),
};
let char_strs = (0u8..128)
.map(|c| atoms.alloc((c as char).to_string()))
// Static text, as the built-in names are: a copy of the image's strings then allocates none of them.
const ASCII: &str = "\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f";
let char_strs = (0..128)
.map(|c| atoms.alloc_static(&ASCII[c..c + 1]))
.collect();
Self::bare(host, limits, atoms, names, char_strs)
}

fn bare(
host: crate::host::RunHost,
limits: Limits,
atoms: Strings,
names: Names,
char_strs: Vec<StrId>,
) -> Self {
let seed = crate::time::SystemTime::now()
.duration_since(crate::time::UNIX_EPOCH)
.map(|d| d.as_nanos() as u64)
.unwrap_or(0x9e3779b97f4a7c15);
Vm {
heap: Heap::with_capacity(1024),
// Room for what a fresh runtime makes (about 290 objects) and a small program's own: a waiting run keeps
// this, so it is not sized for a large one, which grows it.
heap: Heap::with_capacity(320),
cells: Vec::new(),
atoms,
stack: Vec::with_capacity(1024),
stack: Vec::with_capacity(128),
frames: Vec::with_capacity(64),
spare_frames: Vec::new(),
handlers: Vec::new(),
Expand Down