mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
perf(codemode): make a namespace path a small heap object, spelled out only when a call needs it
This commit is contained in:
parent
fb3bec4ad9
commit
f679776772
7 changed files with 119 additions and 87 deletions
|
|
@ -1054,9 +1054,8 @@ fn resume_wait(vm: &mut Vm, state: Id, outcome: Result<Value, Value>) -> Result<
|
|||
let (callee, args) = (item(vm, 2), list(vm, item(vm, 3)));
|
||||
let r = match &vm.heap[callee.as_obj().unwrap_or(0) as usize].kind {
|
||||
// A namespace function is called through its namespace, which costs the reference nothing.
|
||||
Kind::Namespace(ns) => {
|
||||
let ns = ns.clone();
|
||||
crate::host::call_namespace(vm, &ns, &args, callee)
|
||||
Kind::Namespace(_) => {
|
||||
crate::host::call_namespace(vm, callee.as_obj().unwrap_or(0), &args, callee)
|
||||
}
|
||||
_ => {
|
||||
let r = vm.call(&callee, Value::Undef, &args);
|
||||
|
|
@ -1115,8 +1114,8 @@ fn parks_with(vm: &mut Vm) -> Option<u32> {
|
|||
|
||||
#[cold]
|
||||
fn cant_wait(vm: &mut Vm, callee: Value) -> Value {
|
||||
let name = match callee.as_obj().map(|id| &vm.heap[id as usize].kind) {
|
||||
Some(Kind::Namespace(ns)) => ns.label.clone(),
|
||||
let name = match callee.as_obj() {
|
||||
Some(id) if vm.is_namespace(id) => vm.ns_label(&vm.ns_path(id)),
|
||||
_ => crate::host::function_name(vm, &callee),
|
||||
};
|
||||
let msg = format!(
|
||||
|
|
|
|||
|
|
@ -311,7 +311,8 @@ pub struct RunHost<'rt> {
|
|||
pub(crate) modules_loaded: FxHashMap<String, Value>,
|
||||
pub(crate) namespaces: FxHashMap<String, Value>,
|
||||
/// The host namespaces among the globals, by the label of the global they are, with where they are.
|
||||
pub(crate) host_namespaces: FxHashMap<Rc<str>, (Namespace, Vec<String>)>,
|
||||
/// The host namespaces among the globals, by the atom of the label of the global they are, with where they are.
|
||||
pub(crate) host_namespaces: FxHashMap<Atom, (Namespace, Vec<String>)>,
|
||||
/// Counts the points where the reference hands queued calls to the host, for streaming responses.
|
||||
pub(crate) epoch: crate::streaming::Epoch,
|
||||
/// The VM's fuel counters, which it checks only when its step budget runs out.
|
||||
|
|
@ -716,9 +717,10 @@ fn failure_value(
|
|||
|
||||
/// Calls the function a namespace path names, as the reference's `callNamespace`: `resolve` gives the function, or
|
||||
/// the failure the call throws.
|
||||
pub fn call_namespace(vm: &mut Vm, ns: &Rc<NsRef>, args: &[Value], callee: Value) -> Res {
|
||||
pub fn call_namespace(vm: &mut Vm, id: Id, args: &[Value], callee: Value) -> Res {
|
||||
let ns = vm.ns_path(id);
|
||||
let Some((namespace, _)) = vm.host.host_namespaces.get(&ns.root) else {
|
||||
let message = format!("The namespace {} is not available.", ns.root);
|
||||
let message = format!("The namespace {} is not available.", vm.atoms.text(ns.root));
|
||||
return Err(vm.type_error(&message));
|
||||
};
|
||||
let resolve = namespace.resolve.clone();
|
||||
|
|
@ -744,7 +746,7 @@ pub fn call_namespace(vm: &mut Vm, ns: &Rc<NsRef>, args: &[Value], callee: Value
|
|||
.map(|(_, global)| global.iter().chain(ns.keys.iter()).cloned().collect()),
|
||||
};
|
||||
let target = Target {
|
||||
label: ns.label.clone(),
|
||||
label: vm.ns_label(&ns),
|
||||
path,
|
||||
owner: None,
|
||||
};
|
||||
|
|
@ -1440,11 +1442,14 @@ fn from_host(
|
|||
HostValue::Durable(f) => wrap(vm, Callee::Durable(f.clone()), label, place, None),
|
||||
HostValue::Namespace(ns) => match &place.global {
|
||||
Some(global) => {
|
||||
let root: Rc<str> = Rc::from(label);
|
||||
let name = vm.atoms.intern(label);
|
||||
vm.host
|
||||
.host_namespaces
|
||||
.insert(root.clone(), (ns.clone(), global.clone()));
|
||||
vm.ns_ref(NsRef::new(root, Box::new([])))
|
||||
.insert(name, (ns.clone(), global.clone()));
|
||||
vm.ns_ref(NsPath {
|
||||
parent: NsPath::ROOT,
|
||||
name,
|
||||
})
|
||||
}
|
||||
None => {
|
||||
let msg = format!("{label} produced a namespace, which the program cannot hold.");
|
||||
|
|
@ -2013,10 +2018,14 @@ fn import_native(vm: &mut Vm, _this: Value, args: &[Value], _callee: Id) -> Res
|
|||
|
||||
/// The names directly under a namespace path, as the reference's `namespaceKeys` lists them, or what listing them
|
||||
/// threw.
|
||||
pub(crate) fn namespace_keys(vm: &mut Vm, ns: &Rc<NsRef>) -> Result<Vec<String>, Value> {
|
||||
pub(crate) fn namespace_keys(vm: &mut Vm, id: Id) -> Result<Vec<String>, Value> {
|
||||
let ns = vm.ns_path(id);
|
||||
let Some((namespace, _)) = vm.host.host_namespaces.get(&ns.root).cloned() else {
|
||||
let message = format!("The namespace {} is not available.", ns.root);
|
||||
let message = format!("The namespace {} is not available.", vm.atoms.text(ns.root));
|
||||
return Err(vm.type_error(&message));
|
||||
};
|
||||
(namespace.keys)(&ns.keys).map_err(|thrown| thrown_value(vm, &thrown, &ns.label))
|
||||
(namespace.keys)(&ns.keys).map_err(|thrown| {
|
||||
let label = vm.ns_label(&ns);
|
||||
thrown_value(vm, &thrown, &label)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -102,50 +102,45 @@ impl Props {
|
|||
}
|
||||
}
|
||||
|
||||
/// A path into a host namespace among the globals: the global it is under, and the names read below it.
|
||||
#[derive(Debug)]
|
||||
/// A path into a host namespace among the globals, as a small heap object: the path it was read from (`parent`) and
|
||||
/// the name read (`name`); a namespace global itself has no parent, and its name is the global's label. Each read makes
|
||||
/// a new one, as the reference's `HostNamespace` does; its whole path and label are built only when a call or a
|
||||
/// message needs them (`Vm::ns_path`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct NsPath {
|
||||
pub parent: u32,
|
||||
pub name: crate::strings::Atom,
|
||||
}
|
||||
|
||||
impl NsPath {
|
||||
/// The `parent` of a namespace global.
|
||||
pub const ROOT: u32 = u32::MAX;
|
||||
|
||||
pub fn is_root(&self) -> bool {
|
||||
self.parent == Self::ROOT
|
||||
}
|
||||
}
|
||||
|
||||
/// A namespace path spelled out: the global it is under, by its label's atom, and the names below it.
|
||||
pub struct NsRef {
|
||||
/// The global the namespace is, which names it in messages.
|
||||
pub root: Rc<str>,
|
||||
/// The names read below it, as the host's `keys` and `resolve` get them.
|
||||
pub keys: Box<[String]>,
|
||||
/// How the program names the path in errors, as the reference's `member` writes it: `api.issues.list`,
|
||||
/// `api["x-y"]`.
|
||||
pub label: String,
|
||||
pub root: crate::strings::Atom,
|
||||
pub keys: Vec<String>,
|
||||
}
|
||||
|
||||
impl NsRef {
|
||||
pub fn new(root: Rc<str>, keys: Box<[String]>) -> Self {
|
||||
let label = keys
|
||||
.iter()
|
||||
.fold(root.to_string(), |at, key| member(&at, key));
|
||||
Self { root, keys, label }
|
||||
}
|
||||
|
||||
/// The path one name below this one.
|
||||
pub fn child(&self, key: &str) -> Self {
|
||||
let mut keys = Vec::with_capacity(self.keys.len() + 1);
|
||||
keys.extend(self.keys.iter().cloned());
|
||||
keys.push(key.to_owned());
|
||||
Self {
|
||||
root: self.root.clone(),
|
||||
keys: keys.into(),
|
||||
label: member(&self.label, key),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `base.key`, or `base["key"]` when the key is not an identifier, as the reference's `member` writes a label.
|
||||
pub fn member(base: &str, key: &str) -> String {
|
||||
/// Appends `.key`, or `["key"]` when the key is not an identifier, to a label, as the reference's `member` writes it.
|
||||
pub fn push_member(out: &mut String, key: &str) {
|
||||
let mut chars = key.chars();
|
||||
let ident = chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_' || c == '$')
|
||||
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
|
||||
if ident {
|
||||
format!("{base}.{key}")
|
||||
out.push('.');
|
||||
out.push_str(key);
|
||||
} else {
|
||||
format!("{base}[{}]", serde_json::Value::String(key.to_owned()))
|
||||
out.push('[');
|
||||
out.push_str(&serde_json::Value::String(key.to_owned()).to_string());
|
||||
out.push(']');
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -359,7 +354,7 @@ pub enum Kind {
|
|||
pos: u32,
|
||||
},
|
||||
/// A path into a host namespace among the globals, the reference's `HostNamespace`.
|
||||
Namespace(Rc<NsRef>),
|
||||
Namespace(NsPath),
|
||||
/// Shared state of a promise's resolve/reject pair: the promise, and whether either already ran.
|
||||
Resolvers {
|
||||
promise: Id,
|
||||
|
|
@ -446,7 +441,7 @@ impl Obj {
|
|||
pub fn is_callable(&self) -> bool {
|
||||
match &self.kind {
|
||||
Kind::Closure(_) | Kind::Native { .. } | Kind::Bound(_) => true,
|
||||
Kind::Namespace(n) => !n.keys.is_empty(),
|
||||
Kind::Namespace(n) => !n.is_root(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,5 @@
|
|||
//! Property access, conversions, operators and iteration on program values.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::builtins::exotic;
|
||||
use crate::bytecode::{ITER_FOR_OF, Site};
|
||||
use crate::iteration::{BY_CLOSE, BY_COUNTED, BY_RESUME, BY_UNCOUNTED};
|
||||
|
|
@ -168,13 +166,15 @@ impl<'rt> Vm<'rt> {
|
|||
Kind::Map(m) | Kind::Set(m) if cur == id && key == self.names.size => {
|
||||
return Value::Num(m.live as f64);
|
||||
}
|
||||
Kind::Namespace(ns) if cur == id => {
|
||||
Kind::Namespace(_) if cur == id => {
|
||||
// `then` is a path like any other; a namespace is never a thenable (`resolve_promise`).
|
||||
if key <= SYM_ASYNC_ITERATOR {
|
||||
return Value::Undef;
|
||||
}
|
||||
let child = ns.child(self.atoms.text(key));
|
||||
return self.ns_ref(child);
|
||||
return self.ns_ref(NsPath {
|
||||
parent: id,
|
||||
name: key,
|
||||
});
|
||||
}
|
||||
// A Map's or Set's only own accessor is `size`, above.
|
||||
Kind::Map(_) | Kind::Set(_) => {}
|
||||
|
|
@ -1135,19 +1135,17 @@ impl<'rt> Vm<'rt> {
|
|||
|
||||
/// The names under a namespace path, for `Object.keys` and `for...in`, or what listing them threw.
|
||||
pub(crate) fn namespace_names(&mut self, id: Id) -> Result<Vec<Atom>, Value> {
|
||||
let Kind::Namespace(ns) = &self.heap[id as usize].kind else {
|
||||
if !self.is_namespace(id) {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let names = crate::host::namespace_keys(self, &ns.clone())?;
|
||||
}
|
||||
let names = crate::host::namespace_keys(self, id)?;
|
||||
Ok(names.iter().map(|c| self.atoms.intern(c)).collect())
|
||||
}
|
||||
|
||||
/// The global a namespace path is under, which names it in messages.
|
||||
pub(crate) fn namespace_root(&self, id: Id) -> Rc<str> {
|
||||
match &self.heap[id as usize].kind {
|
||||
Kind::Namespace(ns) => ns.root.clone(),
|
||||
_ => Rc::from(""),
|
||||
}
|
||||
pub(crate) fn namespace_root(&self, id: Id) -> String {
|
||||
let root = self.ns_path(id).root;
|
||||
self.atoms.text(root).to_owned()
|
||||
}
|
||||
|
||||
#[inline(never)]
|
||||
|
|
|
|||
|
|
@ -119,7 +119,6 @@ impl Walk<'_> {
|
|||
match &o.kind {
|
||||
Kind::Ordinary
|
||||
| Kind::Error(_)
|
||||
| Kind::Namespace(_)
|
||||
| Kind::RegExp(_)
|
||||
| Kind::Date(_)
|
||||
| Kind::Bytes(_)
|
||||
|
|
@ -127,6 +126,11 @@ impl Walk<'_> {
|
|||
| Kind::Headers(_)
|
||||
| Kind::StrIter { .. }
|
||||
| Kind::Live(_) => {}
|
||||
Kind::Namespace(ns) => {
|
||||
if !ns.is_root() {
|
||||
self.id(ns.parent);
|
||||
}
|
||||
}
|
||||
Kind::Array(items) | Kind::Arguments(items) => self.vals(items.iter()),
|
||||
Kind::ListIter { items, .. } => self.vals(items.iter()),
|
||||
Kind::Closure(c) => self.val(&c.this),
|
||||
|
|
|
|||
|
|
@ -591,7 +591,7 @@ impl Enc<'_, '_> {
|
|||
Kind::StrIter { s, pos } => json!(["si", s, pos]),
|
||||
Kind::Cross(c) => cross(c),
|
||||
Kind::ListIter { items, pos } => json!(["li", vals(items), pos]),
|
||||
Kind::Namespace(ns) => json!(["t", ns.root.as_ref(), ns.keys]),
|
||||
Kind::Namespace(ns) => json!(["t", (!ns.is_root()).then_some(ns.parent), ns.name]),
|
||||
Kind::Resolvers { promise, done } => json!(["r", promise, done]),
|
||||
Kind::Combinator(c) => {
|
||||
let kind = match c.kind {
|
||||
|
|
@ -1665,15 +1665,13 @@ impl Dec<'_> {
|
|||
items: self.vals(f(1)?)?.into(),
|
||||
pos: u32_(f(2)?)?,
|
||||
},
|
||||
"t" => Kind::Namespace(Rc::new(NsRef::new(
|
||||
Rc::from(string(f(1)?)?.as_str()),
|
||||
f(2)?
|
||||
.as_array()
|
||||
.ok_or_else(|| invalid("a namespace path is not a list."))?
|
||||
.iter()
|
||||
.map(string)
|
||||
.collect::<R<_>>()?,
|
||||
))),
|
||||
"t" => Kind::Namespace(NsPath {
|
||||
parent: match f(1)? {
|
||||
J::Null => NsPath::ROOT,
|
||||
p => self.id(p)?,
|
||||
},
|
||||
name: u32_(f(2)?)?,
|
||||
}),
|
||||
"r" => Kind::Resolvers {
|
||||
promise: self.id(f(1)?)?,
|
||||
done: boolean(f(2)?)?,
|
||||
|
|
|
|||
|
|
@ -1010,13 +1010,12 @@ impl<'rt> Vm<'rt> {
|
|||
all.extend_from_slice(args);
|
||||
self.call(&target, bthis, &all)
|
||||
}
|
||||
Kind::Namespace(ns) if ns.keys.is_empty() => {
|
||||
let message = format!("{} is not a function.", ns.root);
|
||||
Kind::Namespace(ns) if ns.is_root() => {
|
||||
let message = format!("{} is not a function.", self.atoms.text(ns.name));
|
||||
Err(self.type_error(&message))
|
||||
}
|
||||
Kind::Namespace(ns) => {
|
||||
let ns = ns.clone();
|
||||
let r = crate::host::call_namespace(self, &ns, args, *f);
|
||||
Kind::Namespace(_) => {
|
||||
let r = crate::host::call_namespace(self, id, args, *f);
|
||||
if self.entered {
|
||||
return self.drive_entered(false);
|
||||
}
|
||||
|
|
@ -1355,18 +1354,17 @@ impl<'rt> Vm<'rt> {
|
|||
self.call_op(argc + n)
|
||||
}
|
||||
// The namespace itself is not a function.
|
||||
Kind::Namespace(ns) if ns.keys.is_empty() => {
|
||||
Kind::Namespace(ns) if ns.is_root() => {
|
||||
self.stack.truncate(fpos);
|
||||
let message = format!("{} is not a function.", ns.root);
|
||||
let message = format!("{} is not a function.", self.atoms.text(ns.name));
|
||||
let e = self.type_error(&message);
|
||||
Err(self.at_site(e, crate::bytecode::Site::Object))
|
||||
}
|
||||
Kind::Namespace(ns) => {
|
||||
let ns = ns.clone();
|
||||
Kind::Namespace(_) => {
|
||||
let callee = self.stack[fpos].get();
|
||||
let args: Vec<Value> = self.stack.drain(fpos + 2..).map(Slot::get).collect();
|
||||
self.stack.truncate(fpos);
|
||||
let r = crate::host::call_namespace(self, &ns, &args, callee)?;
|
||||
let r = crate::host::call_namespace(self, id, &args, callee)?;
|
||||
// A call that waits for promises in its arguments runs in a native frame (see `cross.rs`).
|
||||
if std::mem::take(&mut self.entered) {
|
||||
self.host.meter.bytecode = false;
|
||||
|
|
@ -1494,9 +1492,40 @@ impl<'rt> Vm<'rt> {
|
|||
}
|
||||
|
||||
/// A namespace path as a value: a new reference each time the run reads one, as in the reference.
|
||||
pub fn ns_ref(&mut self, path: crate::object::NsRef) -> Value {
|
||||
pub fn ns_ref(&mut self, path: crate::object::NsPath) -> Value {
|
||||
let proto = self.realm.function_proto;
|
||||
Value::Obj(self.alloc(Obj::new(Some(proto), Kind::Namespace(Rc::new(path)))))
|
||||
Value::Obj(self.alloc(Obj::new(Some(proto), Kind::Namespace(path))))
|
||||
}
|
||||
|
||||
/// The namespace path the reference `id` names, spelled out from its global down.
|
||||
pub(crate) fn ns_path(&self, id: Id) -> crate::object::NsRef {
|
||||
let mut keys = Vec::new();
|
||||
let mut at = id;
|
||||
let root = loop {
|
||||
match &self.heap[at as usize].kind {
|
||||
Kind::Namespace(ns) if ns.is_root() => break ns.name,
|
||||
Kind::Namespace(ns) => {
|
||||
keys.push(self.atoms.text(ns.name).to_owned());
|
||||
at = ns.parent;
|
||||
}
|
||||
_ => break 0,
|
||||
}
|
||||
};
|
||||
keys.reverse();
|
||||
crate::object::NsRef { root, keys }
|
||||
}
|
||||
|
||||
/// How the program names a namespace path in errors, as the reference's `member` writes it: `api.issues.list`,
|
||||
/// `api["x-y"]`.
|
||||
pub(crate) fn ns_label(&self, ns: &crate::object::NsRef) -> String {
|
||||
let root = self.atoms.text(ns.root);
|
||||
let mut out =
|
||||
String::with_capacity(root.len() + ns.keys.iter().map(|k| k.len() + 1).sum::<usize>());
|
||||
out.push_str(root);
|
||||
for key in &ns.keys {
|
||||
crate::object::push_member(&mut out, key);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------- exceptions ----------
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue