mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-26 04:51:52 +00:00
Scripts: #include and the other preprocessor lines run, and $.evalFile runs a file
Before a script runs, `script.run` reads its preprocessor lines (`#` or `//@` at the start of a line, outside strings and comments): - `#include` and `//@include` put another file's text in place of the line, looked for beside the including file, then in each `#includepath` folder, then in each `JSINCLUDE` folder. A later `#includepath` replaces the list. - `#script` names the run unless `name` is given; `#target` takes any value; `#strict off` is taken. `#strict on`, `#targetengine` and `#engine` are refused as unsupported, and any other `#name` as unknown. `$.evalFile(path, timeout?)` runs a file in the same global environment and returns its last value, `$.fileName` is the file being run and `$.includePath` the include folders. A script run from a file reads these files only in its folder and the folders below it. Paths with a `..` name, links or junctions that lead out, device names, streams and network paths are refused; a script given as text reads none. A run reads at most 64 files 16 levels deep, 32 MiB of source in all and 1,024 paths looked up. An error in an included or evaluated file is reported at that file's line and column, and the report's new `file` field names it. Docs: docs/mcp.md (script.run, Script Console), docs/target-app-parity.md.
This commit is contained in:
@@ -472,7 +472,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
|
||||
Ok(p) => p,
|
||||
Err(e) => return Err(interp.throw(ErrorType::Syntax, &e.message)),
|
||||
};
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() });
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: interp.source_tag });
|
||||
let code = match compile_constructed_function(&program, &source) {
|
||||
Ok(Some(code)) => code,
|
||||
Ok(None) => return Err(interp.throw(ErrorType::Syntax, "the parameters or body do not form one function")),
|
||||
@@ -501,7 +501,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) ->
|
||||
return Ok(Value::String(Str::from_units(units.to_vec())));
|
||||
}
|
||||
Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Host { name, .. } | Func::Data { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { name, .. }) => format!("function {name}() {{ [native code] }}"),
|
||||
Some(Func::Bound { .. }) => "function () { [native code] }".to_string(),
|
||||
None => return Err(interp.type_error("Function.prototype.toString was called on a value that is not a function")),
|
||||
};
|
||||
|
||||
@@ -171,6 +171,8 @@ pub(crate) struct Handler {
|
||||
pub(crate) struct Source {
|
||||
pub(crate) lines: LineTable,
|
||||
pub(crate) text: Rc<[u16]>,
|
||||
/// Which source this is, as [`crate::Realm::error_source`] gives it.
|
||||
pub(crate) tag: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
|
||||
@@ -176,13 +176,15 @@ pub(crate) enum NativeKind {
|
||||
/// What a function object runs. `Bound` is a function made by `Function.prototype.bind` (section
|
||||
/// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given.
|
||||
/// `Data` is a host function given [`crate::Data`]; with `text`, each argument arrives as the
|
||||
/// string `String(value)` gives.
|
||||
/// string `String(value)` gives. `Eval` is a host function that gives source to run as global code
|
||||
/// ([`crate::HostItem::Evaluator`]); `end` is called when that code ends.
|
||||
#[derive(Clone)]
|
||||
pub(crate) enum Func {
|
||||
Closure { code: Rc<Code>, env: EnvId },
|
||||
Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str },
|
||||
Host { f: Rc<HostFn>, name: Rc<str> },
|
||||
Data { f: DataFn, name: Rc<str>, text: bool },
|
||||
Eval { f: DataFn, end: Rc<dyn Fn()>, name: Rc<str> },
|
||||
Bound { target: ObjId, this: Value, args: Rc<[Value]> },
|
||||
}
|
||||
|
||||
|
||||
+62
-7
@@ -55,6 +55,8 @@ pub enum HostError {
|
||||
Type(String),
|
||||
/// Thrown to the script as a `RangeError`.
|
||||
Range(String),
|
||||
/// Thrown to the script as a `SyntaxError`.
|
||||
Syntax(String),
|
||||
/// Ends the run with [`LimitKind::Host`] and this message. The script cannot catch it.
|
||||
Abort(String),
|
||||
}
|
||||
@@ -74,6 +76,16 @@ pub enum HostItem {
|
||||
Getter(HostFunction),
|
||||
/// A frozen object with these members.
|
||||
Object(Vec<(String, HostItem)>),
|
||||
/// A function whose host function gives JavaScript source as a string, which then runs as
|
||||
/// global code in the realm, as an indirect `eval` runs it, with the run's fuel and limits:
|
||||
/// the call gives that code's completion value, and its declarations become globals. A result
|
||||
/// that is not a string is the call's result. `end` is called when the source has run,
|
||||
/// normally or not. Each source given has the next tag of [`crate::Realm::error_source`],
|
||||
/// from 1.
|
||||
Evaluator {
|
||||
source: HostFunction,
|
||||
end: Rc<dyn Fn()>,
|
||||
},
|
||||
}
|
||||
|
||||
enum Step {
|
||||
@@ -280,6 +292,39 @@ impl Interp {
|
||||
/// Calls host function `f`: reads its arguments (with `text`, each as the string `String(value)`
|
||||
/// gives), runs it, and gives its result to the script.
|
||||
pub(crate) fn call_data(&mut self, f: &crate::heap::DataFn, name: &Rc<str>, args: &[Value], text: bool) -> JsResult<Value> {
|
||||
let data = self.read_args(name, args, text)?;
|
||||
match f(data) {
|
||||
Ok(d) => self.write_data(d, 0, false),
|
||||
Err(e) => Err(self.host_error(e)?),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls evaluator `f` ([`HostItem::Evaluator`]): reads its arguments, runs it, and runs the
|
||||
/// source it gives as global code, as an indirect `eval` does, giving that code's completion
|
||||
/// value. A result that is not a string is given to the script as it is. `end` is called once
|
||||
/// the source has run, normally or not.
|
||||
pub(crate) fn call_evaluator(&mut self, f: &crate::heap::DataFn, end: &Rc<dyn Fn()>, name: &Rc<str>, args: &[Value]) -> JsResult<Value> {
|
||||
let data = self.read_args(name, args, false)?;
|
||||
let source = match f(data) {
|
||||
Ok(Data::String(source)) => source,
|
||||
Ok(d) => return self.write_data(d, 0, false),
|
||||
Err(e) => return Err(self.host_error(e)?),
|
||||
};
|
||||
self.evaluated = self.evaluated.saturating_add(1);
|
||||
let tag = std::mem::replace(&mut self.source_tag, self.evaluated);
|
||||
let code = self.encode_source(&source).and_then(|units| self.compile_source(&units, false, crate::bytecode::CodeKind::Eval));
|
||||
self.source_tag = tag;
|
||||
let r = match code {
|
||||
Ok(code) => self.run_global(code, true),
|
||||
Err(e) => Err(self.compile_error_to_abrupt(e)),
|
||||
};
|
||||
end();
|
||||
r
|
||||
}
|
||||
|
||||
/// The arguments of host function `name` as [`Data`] (with `text`, each as the string
|
||||
/// `String(value)` gives).
|
||||
fn read_args(&mut self, name: &Rc<str>, args: &[Value], text: bool) -> JsResult<Vec<Data>> {
|
||||
let mut reading = Reading { limits: self.data_limits, bytes: 0, entries: 0, ancestors: Vec::new(), path: Vec::new(), function: name.clone() };
|
||||
let mut data = Vec::with_capacity(args.len());
|
||||
// A conversion can run the script's own `toString`, which may collect garbage.
|
||||
@@ -302,15 +347,20 @@ impl Interp {
|
||||
}
|
||||
self.temp_roots.truncate(mark);
|
||||
read?;
|
||||
match f(data) {
|
||||
Ok(d) => self.write_data(d, 0, false),
|
||||
Err(HostError::Abort(message)) => {
|
||||
Ok(data)
|
||||
}
|
||||
|
||||
/// What host error `e` throws, or the limit it ends the run with.
|
||||
fn host_error(&mut self, e: HostError) -> JsResult<Abrupt> {
|
||||
match e {
|
||||
HostError::Abort(message) => {
|
||||
self.host_abort = Some(message);
|
||||
Err(Abrupt::Limit(LimitKind::Host))
|
||||
Ok(Abrupt::Limit(LimitKind::Host))
|
||||
}
|
||||
Err(HostError::Error(message)) => Err(self.throw_host(ErrorType::Error, &message)?),
|
||||
Err(HostError::Type(message)) => Err(self.throw_host(ErrorType::Type, &message)?),
|
||||
Err(HostError::Range(message)) => Err(self.throw_host(ErrorType::Range, &message)?),
|
||||
HostError::Error(message) => self.throw_host(ErrorType::Error, &message),
|
||||
HostError::Type(message) => self.throw_host(ErrorType::Type, &message),
|
||||
HostError::Range(message) => self.throw_host(ErrorType::Range, &message),
|
||||
HostError::Syntax(message) => self.throw_host(ErrorType::Syntax, &message),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,6 +411,11 @@ impl Interp {
|
||||
HostItem::TextFunction(f) => Prop::Data { value: Value::Object(self.host_function(f, &full, true)), flags: ENUMERABLE },
|
||||
HostItem::Getter(f) => Prop::Accessor { get: Some(self.host_function(f, &full, false)), set: None, flags: ENUMERABLE },
|
||||
HostItem::Object(items) => Prop::Data { value: Value::Object(self.host_object(&full, items)?), flags: ENUMERABLE },
|
||||
HostItem::Evaluator { source, end } => {
|
||||
let proto = self.intrinsics.function_proto;
|
||||
let f = self.heap.alloc_object(Object::new(Class::Function(Func::Eval { f: source, end, name: full.into() }), Some(proto)));
|
||||
Prop::Data { value: Value::Object(f), flags: ENUMERABLE }
|
||||
}
|
||||
};
|
||||
self.define(o, key(&name), prop)
|
||||
}
|
||||
|
||||
+11
-1
@@ -185,6 +185,12 @@ pub(crate) struct Interp {
|
||||
pub(crate) host_abort: Option<String>,
|
||||
/// How much a value passed to or from a host function may carry.
|
||||
pub(crate) data_limits: crate::DataLimits,
|
||||
/// The tag the source compiled next gets ([`crate::Realm::error_source`]).
|
||||
pub(crate) source_tag: u32,
|
||||
/// The sources [`crate::HostItem::Evaluator`] functions have given in this realm.
|
||||
pub(crate) evaluated: u32,
|
||||
/// The tag of the source the last run's error was raised in.
|
||||
pub(crate) error_tag: u32,
|
||||
}
|
||||
|
||||
/// The bytes all live [`HeldBytes`] hold, and the bytes dropped holders released that the heap's
|
||||
@@ -376,6 +382,9 @@ impl Interp {
|
||||
pause: Rc::default(),
|
||||
host_abort: None,
|
||||
data_limits: crate::DataLimits::default(),
|
||||
source_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
evaluated: 0,
|
||||
error_tag: crate::realm::UNKNOWN_SOURCE,
|
||||
};
|
||||
crate::builtins::install(&mut interp);
|
||||
interp.fuel = limits.fuel;
|
||||
@@ -1851,6 +1860,7 @@ impl Interp {
|
||||
// keeps itself reachable.
|
||||
return Ok(Prepared::Done(self.call_data(&f, &name, &args, text)?));
|
||||
}
|
||||
Func::Eval { f, end, name } => return Ok(Prepared::Done(self.call_evaluator(&f, &end, &name, &args)?)),
|
||||
Func::Host { f: host, .. } => {
|
||||
let js_args: Vec<crate::JsValue> = args.iter().map(|v| self.to_js_value(v)).collect();
|
||||
return match host(&js_args) {
|
||||
@@ -2123,7 +2133,7 @@ impl Interp {
|
||||
let remaining = self.options.max_source_units.saturating_sub(self.source_units.saturating_sub(units.len()));
|
||||
let options = Options { strict, max_source_units: remaining, ..self.options.clone() };
|
||||
let program = crate::parse_utf16(units, &options).map_err(CompileError::Syntax)?;
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into() });
|
||||
let source = Rc::new(Source { lines: program.lines.clone(), text: units.into(), tag: self.source_tag });
|
||||
compile_program(&program, &source, kind).map_err(|e| match e {
|
||||
CompileFail::Syntax(s) => CompileError::Syntax(s),
|
||||
CompileFail::Internal(m) => CompileError::Internal(m),
|
||||
|
||||
@@ -774,7 +774,7 @@ fn deep_nesting_compiles_on_a_small_stack() {
|
||||
// ---- the verifier ----
|
||||
|
||||
fn code(ops: Vec<Op>) -> Code {
|
||||
let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::<u16>::new()) });
|
||||
let source = Rc::new(Source { lines: crate::LineTable::new(&[]), text: Rc::from(Vec::<u16>::new()), tag: 0 });
|
||||
Code {
|
||||
positions: vec![0; ops.len()],
|
||||
ops,
|
||||
|
||||
@@ -69,7 +69,7 @@ pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
pub use host::{Data, DataLimits, HostError, HostFunction, HostItem};
|
||||
pub use lexer::{Goal, Lexer};
|
||||
pub use number::to_string as number_to_string;
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind};
|
||||
pub use realm::{Interrupt, JsValue, LimitKind, Limits, MAX_UNBROKEN_FUEL, Progress, Realm, RunError, RunErrorKind, UNKNOWN_SOURCE};
|
||||
pub use token::{Directive, DirectiveName, Keyword, Punct, Span, Token, TokenKind};
|
||||
|
||||
/// How a script is read.
|
||||
|
||||
+23
-3
@@ -58,6 +58,10 @@ pub enum LimitKind {
|
||||
Host,
|
||||
}
|
||||
|
||||
/// The tag [`Realm::error_source`] gives for a source that is neither the realm's script nor an
|
||||
/// evaluator's: code that `eval` or `Function` compiled, or an error with no place.
|
||||
pub const UNKNOWN_SOURCE: u32 = u32::MAX;
|
||||
|
||||
/// The fuel [`Realm::advance`] lets a slice spend, past the slice it was asked for, in a nested run
|
||||
/// it cannot pause.
|
||||
pub const MAX_UNBROKEN_FUEL: u64 = 200_000_000;
|
||||
@@ -218,10 +222,17 @@ impl Realm {
|
||||
interp.throw_site = None;
|
||||
interp.last_thrown = Value::Undefined;
|
||||
interp.host_abort = None;
|
||||
interp.error_tag = UNKNOWN_SOURCE;
|
||||
let strict = interp.options.strict;
|
||||
match interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global)) {
|
||||
interp.source_tag = 0;
|
||||
let code = interp.encode_source(source).and_then(|units| interp.compile_source(&units, strict, CodeKind::Global));
|
||||
interp.source_tag = UNKNOWN_SOURCE;
|
||||
match code {
|
||||
Ok(code) => Ok(code),
|
||||
Err(CompileError::Syntax(e)) => Err(e.into()),
|
||||
Err(CompileError::Syntax(e)) => {
|
||||
interp.error_tag = 0;
|
||||
Err(e.into())
|
||||
}
|
||||
Err(CompileError::Internal(m)) => Err(RunError { kind: RunErrorKind::Internal, message: m, line: 0, column: 0 }),
|
||||
}
|
||||
}
|
||||
@@ -229,7 +240,9 @@ impl Realm {
|
||||
/// The end of a run: its completion value or error, with the interpreter's stacks emptied.
|
||||
fn outcome(&mut self, result: Result<Value, Abrupt>) -> Result<JsValue, RunError> {
|
||||
let interp = &mut self.interp;
|
||||
let (line, column) = interp.throw_site.take().map_or((0, 0), |(code, pc)| code.line_column(pc));
|
||||
let site = interp.throw_site.take();
|
||||
interp.error_tag = site.as_ref().map_or(UNKNOWN_SOURCE, |(code, _)| code.source.tag);
|
||||
let (line, column) = site.map_or((0, 0), |(code, pc)| code.line_column(pc));
|
||||
interp.stack.clear();
|
||||
interp.frames.clear();
|
||||
interp.temp_roots.clear();
|
||||
@@ -299,6 +312,13 @@ impl Realm {
|
||||
self.interp.interrupt = interrupt.0.clone();
|
||||
}
|
||||
|
||||
/// Which source the last error's `line` and `column` are in: 0 for the script given to
|
||||
/// [`Realm::run`] or [`Realm::start`], `n` for the `n`th source a
|
||||
/// [`crate::HostItem::Evaluator`] gave in this realm, and [`UNKNOWN_SOURCE`] otherwise.
|
||||
pub fn error_source(&self) -> u32 {
|
||||
self.interp.error_tag
|
||||
}
|
||||
|
||||
/// Fuel the run has left.
|
||||
pub fn fuel_left(&self) -> u64 {
|
||||
self.interp.fuel
|
||||
|
||||
Reference in New Issue
Block a user