mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-25 18:04:15 +00:00
Merge pull request #9079 from dotCooCoo/feat/js-es2015-block-arrow-template
Scripts: .js scripts run let, const, arrows, templates, default and rest parameters and spread
This commit is contained in:
@@ -217,6 +217,15 @@ pub(crate) struct Files {
|
||||
levels: usize,
|
||||
/// The files `$.evalFile` is running, the script first.
|
||||
frames: Vec<Frame>,
|
||||
/// The run reads ECMAScript 2015 ([`es2015_script`]): its files are parsed that way.
|
||||
es2015: bool,
|
||||
}
|
||||
|
||||
/// A script at `path` runs with [`vectorcraft_js::Options::es2015`] when its file name ends in
|
||||
/// `.js` (in any letter case); a `.jsx` script, any other file and a script given as text run as
|
||||
/// ECMAScript 5.1 with the ExtendScript extensions.
|
||||
pub(crate) fn es2015_script(path: Option<&str>) -> bool {
|
||||
path.and_then(|p| Path::new(p).extension()).is_some_and(|e| e.eq_ignore_ascii_case("js"))
|
||||
}
|
||||
|
||||
/// The output being built: its UTF-16 text, the line it is on, the units since that line began,
|
||||
@@ -311,9 +320,15 @@ impl Files {
|
||||
chain: real.into_iter().collect(),
|
||||
levels: 0,
|
||||
frames: vec![Frame { shown: Arc::from(path.unwrap_or_default()), dir }],
|
||||
es2015: es2015_script(path),
|
||||
}
|
||||
}
|
||||
|
||||
/// The options a file of this run is parsed with, preprocessor lines aside.
|
||||
pub(crate) fn options(&self) -> Options {
|
||||
Options { max_source_units: MAX_TOTAL_BYTES, es2015: self.es2015, ..Options::default() }
|
||||
}
|
||||
|
||||
/// The `JSINCLUDE` folders of this process: absolute folders separated by `;`.
|
||||
pub(crate) fn jsinclude_env() -> Vec<PathBuf> {
|
||||
#[cfg(test)]
|
||||
@@ -456,7 +471,7 @@ impl Files {
|
||||
return Ok(());
|
||||
}
|
||||
let fail = |kind, message: String, line, column| Failure { kind, message, index, file: shown.clone(), line, column };
|
||||
let options = Options { preprocessor_lines: true, max_source_units: MAX_TOTAL_BYTES, ..Options::default() };
|
||||
let options = Options { preprocessor_lines: true, ..self.options() };
|
||||
let program = vectorcraft_js::parse_utf16(&units, &options).map_err(|e| fail(FailKind::Syntax, e.message, e.line, e.column))?;
|
||||
let mut cursor = 0usize;
|
||||
for d in &program.directives {
|
||||
|
||||
@@ -1514,7 +1514,7 @@ fn eval_file(host: &Host, args: Vec<Data>) -> std::result::Result<Data, HostErro
|
||||
if f.line > 0 { host.placed(error, f.file, f.line, f.column) } else { error }
|
||||
})?;
|
||||
// A file without preprocessor lines is parsed here first, so its syntax error names its place.
|
||||
let options = vectorcraft_js::Options { max_source_units: include::MAX_TOTAL_BYTES, ..vectorcraft_js::Options::default() };
|
||||
let options = host.files.borrow().options();
|
||||
if let Err(e) = vectorcraft_js::parse(&expanded.source, &options) {
|
||||
host.files.borrow_mut().end_eval();
|
||||
let (_, file, line, column) = expanded.map.locate(e.line, e.column);
|
||||
@@ -2006,11 +2006,16 @@ impl Session {
|
||||
// A realm made here gets the script extensions, `$` and the dialogs; a kept one has them
|
||||
// from its first run, and they act for the run that calls them.
|
||||
let fresh = realm.is_none();
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), ..Options::default() };
|
||||
// A `.js` script reads ECMAScript 2015; `eval`, `Function`, includes and `$.evalFile` read
|
||||
// code the way the script does.
|
||||
let es2015 = include::es2015_script(request.file.as_deref());
|
||||
let options = Options { max_source_units: include::MAX_TOTAL_BYTES.saturating_mul(2), es2015, ..Options::default() };
|
||||
let strict = options.strict;
|
||||
// A kept engine reads each run's code the way that run's script does.
|
||||
let mut realm = match realm {
|
||||
Some(mut realm) => {
|
||||
realm.set_limits(limits);
|
||||
realm.set_es2015(es2015);
|
||||
realm
|
||||
}
|
||||
None => {
|
||||
|
||||
@@ -297,6 +297,40 @@ fn files_are_checked_before_they_are_read() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_js_script_reads_ecmascript_2015_and_a_jsx_script_does_not() {
|
||||
let dir = fresh_folder("es2015");
|
||||
let write = |name: &str, text: &str| {
|
||||
let p = dir.join(name);
|
||||
std::fs::write(&p, text).unwrap();
|
||||
p.to_string_lossy().into_owned()
|
||||
};
|
||||
let mut s = two_docs();
|
||||
let path = |p: &str| json!({"path": p});
|
||||
write("lib.jsxinc", "const k = 2;\nvar twice = n => n * k;\n");
|
||||
write("more.jsx", "let m = `m${k}`;\nm;\n");
|
||||
let modern = "#include \"lib.jsxinc\"\nlet x = [1, ...[2]];\nvc.log(`${twice(x[1])}`);\nvc.log(eval('let e = 5; e'));\nvc.log(new Function('a = 6', 'return a')());\nvc.log($.evalFile(File($.fileName).parent + '/more.jsx'));\n";
|
||||
let r = s.execute("script.run", &path(&write("modern.js", modern))).unwrap();
|
||||
assert_eq!(r["log"], json!(["4", 5, 6, "m2"]), "{r}");
|
||||
let upper = s.execute("script.run", &path(&write("UPPER.JS", "let u = 1; vc.log(u);"))).unwrap();
|
||||
assert_eq!(upper["log"], json!([1]), "{upper}");
|
||||
for (name, text) in [("legacy.jsx", "let x = 1;"), ("arrow.jsx", "var f = () => 1;"), ("template.jsx", "vc.log(`t`);")] {
|
||||
let e = s.execute("script.run", &path(&write(name, text))).unwrap_err().to_string();
|
||||
assert!(e.contains("SyntaxError"), "{name}: {e}");
|
||||
}
|
||||
// Script text given without a file keeps the ExtendScript language.
|
||||
assert!(run(&mut s, "const c = 1;").unwrap_err().to_string().contains("SyntaxError"));
|
||||
// A named engine reads each run the way that run's script does.
|
||||
s.execute("script.run", &path(&write("first.jsx", "#targetengine kept\nvar kept = 1;"))).unwrap();
|
||||
let modern = s.execute("script.run", &path(&write("second.js", "#targetengine kept\nlet k2 = kept + 1;\nvc.log(k2);"))).unwrap();
|
||||
assert_eq!(modern["log"], json!([2]), "{modern}");
|
||||
let legacy = s.execute("script.run", &path(&write("third.jsx", "#targetengine kept\nvc.log(k2);\nconst c = 1;")));
|
||||
assert!(legacy.unwrap_err().to_string().contains("SyntaxError"));
|
||||
let legacy = s.execute("script.run", &path(&write("fourth.jsx", "#targetengine kept\nvc.log(k2 + kept);"))).unwrap();
|
||||
assert_eq!(legacy["log"], json!([3]), "{legacy}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A new empty folder for test `name`.
|
||||
fn fresh_folder(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id()));
|
||||
|
||||
@@ -200,6 +200,40 @@ pub enum Expr {
|
||||
object: ExprId,
|
||||
predicate: ExprId,
|
||||
},
|
||||
/// An arrow function.
|
||||
Arrow(FunctionId),
|
||||
/// A template literal: its pieces (one more than its substitutions) and its substitutions,
|
||||
/// in source order.
|
||||
Template {
|
||||
quasis: Vec<TemplatePiece>,
|
||||
exprs: Vec<ExprId>,
|
||||
},
|
||||
/// A tagged template (`` tag`a${b}c` ``): `tag` called with the template object and the
|
||||
/// substitutions.
|
||||
TaggedTemplate {
|
||||
tag: ExprId,
|
||||
quasis: Vec<TemplatePiece>,
|
||||
exprs: Vec<ExprId>,
|
||||
},
|
||||
/// `...expression` in an array literal or an argument list, and as the last of an arrow
|
||||
/// function's parenthesized parameters while they are read.
|
||||
Spread(ExprId),
|
||||
}
|
||||
|
||||
/// A piece of a template literal's text between its substitutions.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct TemplatePiece {
|
||||
/// The text with its escapes read.
|
||||
pub cooked: Vec<u16>,
|
||||
/// The text as written.
|
||||
pub raw: Vec<u16>,
|
||||
}
|
||||
|
||||
/// Which lexical declaration a name has.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LexKind {
|
||||
Let,
|
||||
Const,
|
||||
}
|
||||
|
||||
/// A piece of an XML literal, in source order.
|
||||
@@ -247,12 +281,17 @@ pub enum ForInTarget {
|
||||
/// `for (var x in o)`, with the declaration's initializer if it has one.
|
||||
Var(VarDecl),
|
||||
Expr(ExprId),
|
||||
/// `for (let x in o)` or `for (const x in o)`: a new binding for each name.
|
||||
Lexical(LexKind, Name),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ForInit {
|
||||
Var(Vec<VarDecl>),
|
||||
Expr(ExprId),
|
||||
/// `let` or `const` declarations, in a scope of the loop's own with a new copy of each `let`
|
||||
/// binding for each iteration.
|
||||
Lexical(LexKind, Vec<VarDecl>),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
@@ -272,6 +311,8 @@ pub struct CatchClause {
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum Stmt {
|
||||
Var(Vec<VarDecl>),
|
||||
/// `let` or `const` declarations (a `const` always has an initializer).
|
||||
Lexical(LexKind, Vec<VarDecl>),
|
||||
FunctionDecl(FunctionId),
|
||||
Expr(ExprId),
|
||||
Block(Vec<StmtId>),
|
||||
@@ -334,13 +375,20 @@ pub enum FunctionKind {
|
||||
Expression,
|
||||
Getter,
|
||||
Setter,
|
||||
/// An arrow function; one with an expression body has a body of one `return` statement.
|
||||
Arrow,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Function {
|
||||
pub kind: FunctionKind,
|
||||
pub name: Option<Name>,
|
||||
/// The parameters before a rest parameter.
|
||||
pub params: Vec<Name>,
|
||||
/// Each parameter's default value, in the order of `params` (empty when none has one).
|
||||
pub defaults: Vec<Option<ExprId>>,
|
||||
/// The rest parameter (`...name`).
|
||||
pub rest: Option<Name>,
|
||||
pub body: Vec<StmtId>,
|
||||
/// The function's code is strict mode code: its own directive prologue holds `"use strict"`,
|
||||
/// or the code around it is strict.
|
||||
@@ -348,6 +396,13 @@ pub struct Function {
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
impl Function {
|
||||
/// The parameters are plain names: no default value and no rest parameter.
|
||||
pub fn simple_params(&self) -> bool {
|
||||
self.rest.is_none() && self.defaults.iter().all(Option::is_none)
|
||||
}
|
||||
}
|
||||
|
||||
/// The arenas of a parsed script.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct Ast {
|
||||
@@ -412,6 +467,8 @@ pub struct Program {
|
||||
/// Its preprocessor lines, in source order.
|
||||
pub directives: Vec<crate::token::Directive>,
|
||||
pub(crate) lines: crate::LineTable,
|
||||
/// It was read with [`crate::Options::es2015`].
|
||||
pub(crate) es2015: bool,
|
||||
}
|
||||
|
||||
impl Program {
|
||||
|
||||
@@ -503,7 +503,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe
|
||||
Err(CompileFail::Internal(m)) => return Err(Abrupt::Internal(m)),
|
||||
};
|
||||
interp.charge_code(&code, 0)?;
|
||||
let env = interp.global_env;
|
||||
let env = interp.global_scope();
|
||||
interp.make_closure(code, env).map(Value::Object)
|
||||
}
|
||||
|
||||
|
||||
@@ -178,6 +178,49 @@ pub(crate) enum Op {
|
||||
ForEachValue(u32),
|
||||
/// `value` → nothing: sets the default XML namespace of the running code.
|
||||
SetDefaultNamespace,
|
||||
/// Enters a block's environment: the `let` and `const` names of `scopes[i]`, not yet
|
||||
/// initialized, and its function declarations.
|
||||
PushBlock(u32),
|
||||
/// Replaces the current environment with a copy of it, for a `for` loop's next iteration.
|
||||
CopyEnv,
|
||||
/// `value` → nothing: initializes the nearest binding of `names[i]`, a `let`, a `const` or
|
||||
/// a parameter of a function with default or rest parameters.
|
||||
InitVar(u32),
|
||||
/// Pushes the value of the parameter `names[i]` of the running function, initialized or not.
|
||||
LoadParam(u32),
|
||||
/// Ends the parameters of a function with default or rest parameters: enters the environment
|
||||
/// of its body's variables and function declarations, and of its `let` and `const` names.
|
||||
BodyEnv,
|
||||
/// `value` → nothing: assigns the function declared in a block outside strict mode code to
|
||||
/// the variable `names[i]` of the running code (ECMA-262 2015 Annex B.3.3).
|
||||
AnnexB(u32),
|
||||
/// `array value` → `array`, with the elements of the value appended (spread).
|
||||
ArraySpread,
|
||||
/// `function this array` → result: a call with the array's elements as its arguments, a
|
||||
/// direct eval when `eval` is true and the function is the global `eval`.
|
||||
CallSpread(bool),
|
||||
/// `function array` → the new object, constructed with the array's elements as arguments.
|
||||
NewSpread,
|
||||
/// `value` → its string (a template literal's substitution).
|
||||
ToStr,
|
||||
/// Pushes the template object of `templates[i]`, the same object for each evaluation.
|
||||
TemplateObject(u32),
|
||||
}
|
||||
|
||||
/// The names a block declares, entered with [`Op::PushBlock`].
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct BlockScope {
|
||||
/// The `let` and `const` names, each with whether it is a `const`.
|
||||
pub(crate) lets: Vec<(Key, bool)>,
|
||||
/// The function declarations: their names and indices in `functions`.
|
||||
pub(crate) funcs: Vec<(Key, u32)>,
|
||||
}
|
||||
|
||||
/// A tagged template's strings: as read and as written.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Template {
|
||||
pub(crate) cooked: Vec<Str>,
|
||||
pub(crate) raw: Vec<Str>,
|
||||
}
|
||||
|
||||
/// What code is: a function body, a script, or eval code.
|
||||
@@ -239,6 +282,23 @@ pub(crate) struct Code {
|
||||
pub(crate) source: Rc<Source>,
|
||||
/// Where the function's text starts and ends in the source.
|
||||
pub(crate) span: (u32, u32),
|
||||
/// The block scopes [`Op::PushBlock`] enters.
|
||||
pub(crate) scopes: Vec<BlockScope>,
|
||||
/// The scope of the `let` and `const` names at the top of the body, script or eval code.
|
||||
pub(crate) top_scope: Option<u32>,
|
||||
/// The tagged templates [`Op::TemplateObject`] makes objects of.
|
||||
pub(crate) templates: Vec<Template>,
|
||||
/// The rest parameter's name.
|
||||
pub(crate) rest: Option<Key>,
|
||||
/// The function's `length`: its parameters before the first with a default value.
|
||||
pub(crate) length: u32,
|
||||
/// The code is an arrow function's.
|
||||
pub(crate) arrow: bool,
|
||||
/// The code reads `this` or calls `eval`, itself or in an arrow function inside it.
|
||||
pub(crate) uses_this: bool,
|
||||
/// The function has default or rest parameters: its parameters start uninitialized, its
|
||||
/// code initializes them and then enters its body with [`Op::BodyEnv`].
|
||||
pub(crate) param_init: bool,
|
||||
}
|
||||
|
||||
impl Code {
|
||||
@@ -315,6 +375,12 @@ fn effect(op: Op, finally_tables: &[Vec<u32>]) -> Result<Effect, String> {
|
||||
Op::XmlScopeRef => e(1, 2),
|
||||
Op::ForEachValue(n) => e(n + 2, n + 3),
|
||||
Op::SetDefaultNamespace => e(1, 0),
|
||||
Op::PushBlock(_) | Op::CopyEnv | Op::BodyEnv => e(0, 0),
|
||||
Op::InitVar(_) | Op::AnnexB(_) => e(1, 0),
|
||||
Op::LoadParam(_) | Op::TemplateObject(_) => e(0, 1),
|
||||
Op::ArraySpread | Op::NewSpread => e(2, 1),
|
||||
Op::CallSpread(_) => e(3, 1),
|
||||
Op::ToStr => e(1, 1),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -341,8 +407,13 @@ fn check_indices(op: Op, code: &Code) -> Result<(), String> {
|
||||
| Op::InitProp(i)
|
||||
| Op::InitGetter(i)
|
||||
| Op::InitSetter(i)
|
||||
| Op::PushCatch(i) => check(i, code.names.len(), "name"),
|
||||
| Op::PushCatch(i)
|
||||
| Op::InitVar(i)
|
||||
| Op::LoadParam(i)
|
||||
| Op::AnnexB(i) => check(i, code.names.len(), "name"),
|
||||
Op::Closure(i) => check(i, code.functions.len(), "function"),
|
||||
Op::PushBlock(i) => check(i, code.scopes.len(), "scope"),
|
||||
Op::TemplateObject(i) => check(i, code.templates.len(), "template"),
|
||||
Op::RegExp(i) => check(i, code.regexps.len(), "regular expression"),
|
||||
_ => Ok(()),
|
||||
}
|
||||
@@ -363,9 +434,15 @@ pub(crate) fn verify(code: &Code) -> Result<u32, String> {
|
||||
return Err("a function declaration without a name".into());
|
||||
}
|
||||
}
|
||||
if code.fun_decls.iter().any(|(_, i)| *i as usize >= code.functions.len()) {
|
||||
if code.fun_decls.iter().chain(code.scopes.iter().flat_map(|s| &s.funcs)).any(|(_, i)| *i as usize >= code.functions.len()) {
|
||||
return Err("function declaration index out of range".into());
|
||||
}
|
||||
if code.top_scope.is_some_and(|i| i as usize >= code.scopes.len()) {
|
||||
return Err("top scope out of range".into());
|
||||
}
|
||||
if code.templates.iter().any(|t| t.cooked.len() != t.raw.len()) {
|
||||
return Err("a template whose strings do not match".into());
|
||||
}
|
||||
let mut depth: Vec<Option<u32>> = vec![None; len];
|
||||
let mut work: Vec<(u32, u32)> = vec![(0, 0)];
|
||||
for h in &code.handlers {
|
||||
|
||||
+533
-61
@@ -17,10 +17,10 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::ast::{
|
||||
AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LogicalOp, PropertyValue, Stmt, StmtId, UnaryOp, UpdateOp,
|
||||
VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, Expr, ExprId, ForInTarget, ForInit, FunctionId, FunctionKind, LexKind, LogicalOp, PropertyValue, Stmt, StmtId,
|
||||
TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
use crate::bytecode::{Code, CodeKind, Handler, Op, Source, fallthrough_effect, verify};
|
||||
use crate::bytecode::{BlockScope, Code, CodeKind, Handler, Op, Source, Template, fallthrough_effect, verify};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::heap::Key;
|
||||
use crate::value::Str;
|
||||
@@ -88,6 +88,17 @@ struct FnCompiler<'a> {
|
||||
contexts: Vec<Ctx>,
|
||||
uses_arguments: bool,
|
||||
recursion: u32,
|
||||
/// The code was read with [`crate::Options::es2015`]: blocks have scopes of their own.
|
||||
es2015: bool,
|
||||
scopes: Vec<BlockScope>,
|
||||
templates: Vec<Template>,
|
||||
uses_this: bool,
|
||||
/// The function declarations at the top of the body, which are var-scoped.
|
||||
top_funcs: HashSet<StmtId>,
|
||||
/// The function declarations a block scope instantiates.
|
||||
block_funcs: HashSet<StmtId>,
|
||||
/// The function declarations in blocks whose names are also var-scoped (Annex B.3.3).
|
||||
annex: HashSet<StmtId>,
|
||||
}
|
||||
|
||||
/// The `var` names and function declarations a body hoists.
|
||||
@@ -128,6 +139,13 @@ impl<'a> FnCompiler<'a> {
|
||||
contexts: Vec::new(),
|
||||
uses_arguments: false,
|
||||
recursion,
|
||||
es2015: false,
|
||||
scopes: Vec::new(),
|
||||
templates: Vec::new(),
|
||||
uses_this: false,
|
||||
top_funcs: HashSet::new(),
|
||||
block_funcs: HashSet::new(),
|
||||
annex: HashSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -222,59 +240,106 @@ impl<'a> FnCompiler<'a> {
|
||||
|
||||
/// Collects the `var` names and function declarations of a body, outside nested functions,
|
||||
/// in source order, and compiles the functions.
|
||||
fn hoist(&mut self, body: &[StmtId]) -> CResult<Hoisted> {
|
||||
/// With [`crate::Options::es2015`], only the function declarations at the top of the body are
|
||||
/// hoisted; one in a block is instantiated when the block is entered, and outside strict mode
|
||||
/// code its name is also a variable (Annex B.3.3) unless that clashes with a parameter or with
|
||||
/// a `let` or a `const` of the body or of a block or loop around the declaration, or with a
|
||||
/// function of a block around the one that holds it.
|
||||
fn hoist(&mut self, body: &[StmtId], params: &[Key]) -> CResult<Hoisted> {
|
||||
let mut out = Hoisted::default();
|
||||
let mut seen = HashSet::new();
|
||||
let mut work: Vec<StmtId> = body.iter().rev().copied().collect();
|
||||
let mut add_var = |out: &mut Hoisted, d: &VarDecl| {
|
||||
let k = key_of(&d.name.name);
|
||||
// The `let` and `const` names and the block functions of each statement list and loop the
|
||||
// walk enters, with the index of the one around it; the body's are first, and its
|
||||
// functions are var-scoped.
|
||||
let mut scopes: Vec<(Option<usize>, HashSet<Key>, HashSet<Key>)> = vec![(None, self.lexical_names(body), HashSet::new())];
|
||||
let mut work: Vec<(StmtId, bool, usize)> = body.iter().rev().map(|&s| (s, false, 0)).collect();
|
||||
let mut add_var = |out: &mut Hoisted, k: Key| {
|
||||
if seen.insert(k.clone()) {
|
||||
out.vars.push(k);
|
||||
}
|
||||
};
|
||||
while let Some(id) = work.pop() {
|
||||
let mut annex: Vec<(Key, usize, StmtId)> = Vec::new();
|
||||
while let Some((id, nested, scope)) = work.pop() {
|
||||
let Some(stmt) = self.ast.stmt(id) else { return internal("statement out of range") };
|
||||
let inner = self.es2015;
|
||||
let mut enter = |names: HashSet<Key>, funcs: HashSet<Key>| {
|
||||
scopes.push((Some(scope), names, funcs));
|
||||
scopes.len() - 1
|
||||
};
|
||||
match stmt {
|
||||
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, d)),
|
||||
Stmt::Var(decls) => decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name))),
|
||||
Stmt::Lexical(..) => {}
|
||||
Stmt::FunctionDecl(fid) => {
|
||||
let Some(name) = self.ast.function(*fid).and_then(|f| f.name.as_ref()) else {
|
||||
return internal("function declaration without a name");
|
||||
};
|
||||
let k = key_of(&name.name);
|
||||
let i = self.function(*fid)?;
|
||||
out.fun_decls.push((k, i));
|
||||
}
|
||||
Stmt::Block(list) => work.extend(list.iter().rev()),
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
work.extend(alternate.iter());
|
||||
work.push(*consequent);
|
||||
}
|
||||
Stmt::DoWhile { body, .. } | Stmt::While { body, .. } | Stmt::With { body, .. } | Stmt::Labeled { body, .. } => work.push(*body),
|
||||
Stmt::For { init, body, .. } => {
|
||||
work.push(*body);
|
||||
if let Some(ForInit::Var(decls)) = init {
|
||||
decls.iter().for_each(|d| add_var(&mut out, d));
|
||||
if self.es2015 && nested {
|
||||
if !self.strict {
|
||||
annex.push((k, scope, id));
|
||||
}
|
||||
} else {
|
||||
let i = self.function(*fid)?;
|
||||
out.fun_decls.push((k, i));
|
||||
self.top_funcs.insert(id);
|
||||
}
|
||||
}
|
||||
Stmt::Block(list) => {
|
||||
let s = enter(self.lexical_names(list), self.block_function_names(list));
|
||||
work.extend(list.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::If { consequent, alternate, .. } => {
|
||||
// A function declaration standing alone as a branch is in a block of its own
|
||||
// (Annex B.3.4).
|
||||
for &branch in alternate.iter().chain(std::iter::once(consequent)) {
|
||||
let alone = matches!(self.ast.stmt(branch), Some(Stmt::FunctionDecl(_)));
|
||||
let s = if alone { enter(HashSet::new(), HashSet::new()) } else { scope };
|
||||
work.push((branch, nested || inner, s));
|
||||
}
|
||||
}
|
||||
Stmt::Labeled { body, .. } => work.push((*body, nested, scope)),
|
||||
Stmt::DoWhile { body, .. } | Stmt::While { body, .. } | Stmt::With { body, .. } => work.push((*body, nested || inner, scope)),
|
||||
Stmt::For { init, body, .. } => {
|
||||
let s = match init {
|
||||
Some(ForInit::Var(decls)) => {
|
||||
decls.iter().for_each(|d| add_var(&mut out, key_of(&d.name.name)));
|
||||
scope
|
||||
}
|
||||
Some(ForInit::Lexical(_, decls)) => enter(decls.iter().map(|d| key_of(&d.name.name)).collect(), HashSet::new()),
|
||||
_ => scope,
|
||||
};
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::ForIn { target, body, .. } => {
|
||||
work.push(*body);
|
||||
if let ForInTarget::Var(d) = target {
|
||||
add_var(&mut out, d);
|
||||
}
|
||||
let s = match target {
|
||||
ForInTarget::Var(d) => {
|
||||
add_var(&mut out, key_of(&d.name.name));
|
||||
scope
|
||||
}
|
||||
ForInTarget::Lexical(_, name) => enter(HashSet::from([key_of(&name.name)]), HashSet::new()),
|
||||
ForInTarget::Expr(_) => scope,
|
||||
};
|
||||
work.push((*body, nested || inner, s));
|
||||
}
|
||||
Stmt::Switch { cases, .. } => {
|
||||
let names = cases.iter().flat_map(|c| self.lexical_names(&c.body)).collect();
|
||||
let funcs = cases.iter().flat_map(|c| self.block_function_names(&c.body)).collect();
|
||||
let s = enter(names, funcs);
|
||||
for case in cases.iter().rev() {
|
||||
work.extend(case.body.iter().rev());
|
||||
work.extend(case.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
}
|
||||
Stmt::Try { block, handler, finalizer } => {
|
||||
if let Some(f) = finalizer {
|
||||
work.extend(f.iter().rev());
|
||||
let s = enter(self.lexical_names(f), self.block_function_names(f));
|
||||
work.extend(f.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
if let Some(h) = handler {
|
||||
work.extend(h.body.iter().rev());
|
||||
let s = enter(self.lexical_names(&h.body), self.block_function_names(&h.body));
|
||||
work.extend(h.body.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
work.extend(block.iter().rev());
|
||||
let s = enter(self.lexical_names(block), self.block_function_names(block));
|
||||
work.extend(block.iter().rev().map(|&st| (st, nested || inner, s)));
|
||||
}
|
||||
Stmt::Expr(_)
|
||||
| Stmt::Empty
|
||||
@@ -286,12 +351,124 @@ impl<'a> FnCompiler<'a> {
|
||||
| Stmt::DefaultXmlNamespace(_) => {}
|
||||
}
|
||||
}
|
||||
for (k, scope, id) in annex {
|
||||
let mut cur = Some(scope);
|
||||
let mut clash = params.contains(&k) || *k == *key_of("arguments");
|
||||
// The functions of the declaration's own block are judged with it (Annex B.3.3.4);
|
||||
// those of the blocks around it clash.
|
||||
let mut own = true;
|
||||
while let Some((outer, names, funcs)) = cur.and_then(|i| scopes.get(i)).filter(|_| !clash) {
|
||||
clash = names.contains(&k) || (!own && funcs.contains(&k));
|
||||
own = false;
|
||||
cur = *outer;
|
||||
}
|
||||
if !clash {
|
||||
self.annex.insert(id);
|
||||
add_var(&mut out, k);
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The `let` and `const` names a statement list declares.
|
||||
fn lexical_names(&self, list: &[StmtId]) -> HashSet<Key> {
|
||||
list.iter()
|
||||
.filter_map(|&s| match self.ast.stmt(s) {
|
||||
Some(Stmt::Lexical(_, decls)) => Some(decls.iter().map(|d| key_of(&d.name.name))),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The function declaration a statement is, or the one at the end of its chain of labels,
|
||||
/// with the statement that holds it.
|
||||
fn declared_function(&self, mut s: StmtId) -> Option<(StmtId, FunctionId)> {
|
||||
loop {
|
||||
match self.ast.stmt(s)? {
|
||||
Stmt::FunctionDecl(fid) => return Some((s, *fid)),
|
||||
Stmt::Labeled { body, .. } => s = *body,
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The names of the function declarations a statement list holds, labelled ones included.
|
||||
fn block_function_names(&self, list: &[StmtId]) -> HashSet<Key> {
|
||||
list.iter()
|
||||
.filter_map(|&s| self.declared_function(s))
|
||||
.filter_map(|(_, fid)| self.ast.function(fid).and_then(|f| f.name.as_ref()))
|
||||
.map(|name| key_of(&name.name))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The scope a statement list declares with [`crate::Options::es2015`]: its `let` and
|
||||
/// `const` names, and (`functions`) its function declarations, labelled ones included. `None`
|
||||
/// when it declares none.
|
||||
fn list_scope(&mut self, list: &[StmtId], functions: bool) -> CResult<Option<u32>> {
|
||||
if !self.es2015 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut scope = BlockScope::default();
|
||||
for &s in list {
|
||||
if let Some(Stmt::Lexical(kind, decls)) = self.ast.stmt(s) {
|
||||
scope.lets.extend(decls.iter().map(|d| (key_of(&d.name.name), *kind == LexKind::Const)));
|
||||
continue;
|
||||
}
|
||||
let Some((decl, fid)) = self.declared_function(s).filter(|(decl, _)| functions && !self.top_funcs.contains(decl)) else { continue };
|
||||
let Some(name) = self.ast.function(fid).and_then(|f| f.name.as_ref()) else {
|
||||
return internal("function declaration without a name");
|
||||
};
|
||||
let k = key_of(&name.name);
|
||||
let i = self.function(fid)?;
|
||||
scope.funcs.push((k, i));
|
||||
self.block_funcs.insert(decl);
|
||||
}
|
||||
if scope.lets.is_empty() && scope.funcs.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(self.push_scope(scope)))
|
||||
}
|
||||
|
||||
fn push_scope(&mut self, scope: BlockScope) -> u32 {
|
||||
self.scopes.push(scope);
|
||||
len_u32(self.scopes.len() - 1)
|
||||
}
|
||||
|
||||
/// A block's statements, in an environment of their own when they declare `let`, `const` or
|
||||
/// (with [`crate::Options::es2015`]) functions.
|
||||
fn block(&mut self, list: &[StmtId]) -> CResult<()> {
|
||||
let Some(scope) = self.list_scope(list, true)? else { return self.stmts(list) };
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
self.stmts(list)?;
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `let` or `const` declarations: each binding initialized with its value or `undefined`.
|
||||
fn lexical_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
|
||||
for d in decls {
|
||||
match d.init {
|
||||
Some(init) => self.expr(init)?,
|
||||
None => self.emit(Op::Undefined),
|
||||
}
|
||||
self.at(d.name.span.start);
|
||||
let n = self.var_name(&d.name.name);
|
||||
self.emit(Op::InitVar(n));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Compiles a nested function and returns its index in the function table.
|
||||
fn function(&mut self, fid: FunctionId) -> CResult<u32> {
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true)?;
|
||||
let code = compile_function(self.ast, fid, self.source, self.recursion, true, self.es2015)?;
|
||||
// An arrow function reads the `this` and `arguments` of the code around it.
|
||||
if code.arrow {
|
||||
self.uses_this |= code.uses_this;
|
||||
self.uses_arguments |= code.uses_arguments;
|
||||
}
|
||||
self.functions.push(code);
|
||||
Ok(u32::try_from(self.functions.len() - 1).unwrap_or(u32::MAX))
|
||||
}
|
||||
@@ -319,13 +496,15 @@ impl<'a> FnCompiler<'a> {
|
||||
self.at(self.ast.stmt_span(id).start);
|
||||
match stmt {
|
||||
Stmt::Var(decls) => self.var_decls(decls),
|
||||
Stmt::FunctionDecl(_) | Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Lexical(_, decls) => self.lexical_decls(decls),
|
||||
Stmt::FunctionDecl(fid) => self.function_decl(id, *fid),
|
||||
Stmt::Empty | Stmt::Debugger => Ok(()),
|
||||
Stmt::Expr(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(if self.kind == CodeKind::Function { Op::Pop } else { Op::SetCompletion });
|
||||
Ok(())
|
||||
}
|
||||
Stmt::Block(list) => self.stmts(list),
|
||||
Stmt::Block(list) => self.block(list),
|
||||
Stmt::If { .. } => self.if_chain(id),
|
||||
Stmt::DoWhile { .. } | Stmt::While { .. } | Stmt::For { .. } | Stmt::ForIn { .. } => self.loop_stmt(id, Vec::new()),
|
||||
Stmt::Continue(label) => self.jump_stmt(label.as_ref().map(|l| l.name.as_str()), true),
|
||||
@@ -363,6 +542,29 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A function declaration where it stands. One at the top of the body was instantiated on
|
||||
/// entry, and one in a block when the block was entered; outside strict mode code, one in a
|
||||
/// block (or standing alone as an `if` branch) is also assigned to its variable here
|
||||
/// (Annex B.3.3 and B.3.4).
|
||||
fn function_decl(&mut self, id: StmtId, fid: FunctionId) -> CResult<()> {
|
||||
if !self.es2015 || self.top_funcs.contains(&id) {
|
||||
return Ok(());
|
||||
}
|
||||
let Some(name) = self.ast.function(fid).and_then(|f| f.name.as_ref()) else { return internal("function declaration without a name") };
|
||||
if !self.annex.contains(&id) {
|
||||
return Ok(());
|
||||
}
|
||||
let n = self.name_key(key_of(&name.name));
|
||||
if self.block_funcs.contains(&id) {
|
||||
self.emit(Op::GetVar(n));
|
||||
} else {
|
||||
let i = self.function(fid)?;
|
||||
self.emit(Op::Closure(i));
|
||||
}
|
||||
self.emit(Op::AnnexB(n));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn var_decls(&mut self, decls: &[VarDecl]) -> CResult<()> {
|
||||
for d in decls {
|
||||
if let Some(init) = d.init {
|
||||
@@ -385,7 +587,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.expr(*test)?;
|
||||
let otherwise = self.new_label();
|
||||
self.jump(Op::JumpIfFalse, otherwise);
|
||||
self.stmt(*consequent)?;
|
||||
self.branch(*consequent)?;
|
||||
let Some(alt) = *alternate else {
|
||||
self.bind(otherwise);
|
||||
break;
|
||||
@@ -396,7 +598,7 @@ impl<'a> FnCompiler<'a> {
|
||||
if matches!(self.ast.stmt(alt), Some(Stmt::If { .. })) {
|
||||
cur = alt;
|
||||
} else {
|
||||
self.stmt(alt)?;
|
||||
self.branch(alt)?;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -404,6 +606,15 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An `if` branch. With [`crate::Options::es2015`], a function declaration standing alone as
|
||||
/// the branch is in a block of its own (Annex B.3.4).
|
||||
fn branch(&mut self, id: StmtId) -> CResult<()> {
|
||||
if self.es2015 && matches!(self.ast.stmt(id), Some(Stmt::FunctionDecl(_))) {
|
||||
return self.block(&[id]);
|
||||
}
|
||||
self.stmt(id)
|
||||
}
|
||||
|
||||
fn labeled(&mut self, id: StmtId) -> CResult<()> {
|
||||
let mut labels = Vec::new();
|
||||
let mut cur = id;
|
||||
@@ -456,9 +667,13 @@ impl<'a> FnCompiler<'a> {
|
||||
self.expr(*test)?;
|
||||
self.jump(Op::JumpIfTrue, top);
|
||||
}
|
||||
Some(Stmt::For { init: Some(ForInit::Lexical(kind, decls)), test, update, body }) => {
|
||||
return self.for_lexical(*kind, decls, *test, *update, *body, labels, brk, cont);
|
||||
}
|
||||
Some(Stmt::For { init, test, update, body }) => {
|
||||
match init {
|
||||
Some(ForInit::Var(decls)) => self.var_decls(decls)?,
|
||||
Some(ForInit::Lexical(..)) => return internal("lexical for loop"),
|
||||
Some(ForInit::Expr(e)) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(Op::Pop);
|
||||
@@ -486,7 +701,105 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `for (let …; test; update) body` or `for (const …; …)`: the declarations in a scope of the
|
||||
/// loop's own, copied for each iteration of a `let` loop before the update runs, so a closure
|
||||
/// made in one iteration keeps that iteration's bindings (ECMA-262 2015 section 13.7.4.7).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn for_lexical(
|
||||
&mut self,
|
||||
kind: LexKind,
|
||||
decls: &[VarDecl],
|
||||
test: Option<ExprId>,
|
||||
update: Option<ExprId>,
|
||||
body: StmtId,
|
||||
labels: Vec<String>,
|
||||
brk: Label,
|
||||
cont: Label,
|
||||
) -> CResult<()> {
|
||||
let scope = BlockScope { lets: decls.iter().map(|d| (key_of(&d.name.name), kind == LexKind::Const)).collect(), funcs: Vec::new() };
|
||||
let scope = self.push_scope(scope);
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
self.lexical_decls(decls)?;
|
||||
let per_iteration = kind == LexKind::Let;
|
||||
if per_iteration {
|
||||
self.emit(Op::CopyEnv);
|
||||
}
|
||||
let head = self.new_label();
|
||||
self.bind(head);
|
||||
if let Some(t) = test {
|
||||
self.expr(t)?;
|
||||
self.jump(Op::JumpIfFalse, brk);
|
||||
}
|
||||
self.loop_body(body, labels, brk, cont)?;
|
||||
self.bind(cont);
|
||||
if per_iteration {
|
||||
self.emit(Op::CopyEnv);
|
||||
}
|
||||
if let Some(u) = update {
|
||||
self.expr(u)?;
|
||||
self.emit(Op::Pop);
|
||||
}
|
||||
self.jump(Op::Jump, head);
|
||||
self.bind(brk);
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `for (let x in o)`, `for (const x in o)` and `for each` with them: the object read where
|
||||
/// `x` is not yet initialized, then a new binding of `x` for each name.
|
||||
fn for_in_lexical(
|
||||
&mut self,
|
||||
kind: LexKind,
|
||||
name: &crate::ast::Name,
|
||||
object: ExprId,
|
||||
body: StmtId,
|
||||
labels: Vec<String>,
|
||||
each: bool,
|
||||
) -> CResult<()> {
|
||||
let scope = self.push_scope(BlockScope { lets: vec![(key_of(&name.name), kind == LexKind::Const)], funcs: Vec::new() });
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
self.expr(object)?;
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
self.emit(Op::ForInStart);
|
||||
let iter_depth = self.depth;
|
||||
let head = self.new_label();
|
||||
let brk = self.new_label();
|
||||
self.bind(head);
|
||||
self.jump(Op::ForInNext, brk);
|
||||
let outer_env = self.env_depth;
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
self.at(name.span.start);
|
||||
let n = self.var_name(&name.name);
|
||||
if each {
|
||||
// The value initializes the binding; the name under it goes next.
|
||||
self.emit(Op::ForEachValue(0));
|
||||
self.emit(Op::InitVar(n));
|
||||
self.emit(Op::Pop);
|
||||
} else {
|
||||
self.emit(Op::InitVar(n));
|
||||
}
|
||||
self.contexts.push(Ctx::Jump { labels, is_loop: true, plain_break: true, brk, cont: Some(head), depth: self.depth, env_depth: outer_env });
|
||||
let r = self.stmt(body);
|
||||
self.contexts.pop();
|
||||
r?;
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
self.jump(Op::Jump, head);
|
||||
self.bind(brk);
|
||||
self.depth = iter_depth;
|
||||
self.emit(Op::Pop);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn for_in(&mut self, target: &ForInTarget, object: ExprId, body: StmtId, labels: Vec<String>, each: bool) -> CResult<()> {
|
||||
if let ForInTarget::Lexical(kind, name) = target {
|
||||
return self.for_in_lexical(*kind, name, object, body, labels, each);
|
||||
}
|
||||
if let ForInTarget::Var(d) = target {
|
||||
self.var_decls(std::slice::from_ref(d))?;
|
||||
}
|
||||
@@ -507,6 +820,7 @@ impl<'a> FnCompiler<'a> {
|
||||
}
|
||||
ForInTarget::Expr(e) if each => self.store_value_to(*e)?,
|
||||
ForInTarget::Expr(e) => self.store_key_to(*e)?,
|
||||
ForInTarget::Lexical(..) => return internal("lexical for-in loop"),
|
||||
}
|
||||
if each {
|
||||
// The value; the name under it goes next.
|
||||
@@ -607,6 +921,12 @@ impl<'a> FnCompiler<'a> {
|
||||
fn switch_stmt(&mut self, id: StmtId, labels: Vec<String>) -> CResult<()> {
|
||||
let Some(Stmt::Switch { discriminant, cases }) = self.ast.stmt(id) else { return internal("not a switch") };
|
||||
self.expr(*discriminant)?;
|
||||
let all: Vec<StmtId> = cases.iter().flat_map(|c| c.body.iter().copied()).collect();
|
||||
let scope = self.list_scope(&all, true)?;
|
||||
if let Some(scope) = scope {
|
||||
self.emit(Op::PushBlock(scope));
|
||||
self.env_depth += 1;
|
||||
}
|
||||
let d = self.depth;
|
||||
let brk = self.new_label();
|
||||
let case_labels: Vec<Label> = cases.iter().map(|_| self.new_label()).collect();
|
||||
@@ -632,6 +952,10 @@ impl<'a> FnCompiler<'a> {
|
||||
self.contexts.pop();
|
||||
self.bind(brk);
|
||||
self.depth = d;
|
||||
if scope.is_some() {
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
}
|
||||
self.emit(Op::Pop);
|
||||
Ok(())
|
||||
}
|
||||
@@ -746,7 +1070,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.contexts.push(Ctx::Finally { try_depth, env_depth, entry: fin_entry, exits: Vec::new() });
|
||||
}
|
||||
let start = self.pc();
|
||||
self.stmts(block)?;
|
||||
self.block(block)?;
|
||||
if let Some(h) = handler {
|
||||
let after = self.new_label();
|
||||
let catch = self.new_label();
|
||||
@@ -759,7 +1083,7 @@ impl<'a> FnCompiler<'a> {
|
||||
let n = self.var_name(&h.param.name);
|
||||
self.emit(Op::PushCatch(n));
|
||||
self.env_depth += 1;
|
||||
self.stmts(&h.body)?;
|
||||
self.block(&h.body)?;
|
||||
self.emit(Op::PopEnv);
|
||||
self.env_depth -= 1;
|
||||
self.bind(after);
|
||||
@@ -779,7 +1103,7 @@ impl<'a> FnCompiler<'a> {
|
||||
if keeps_completion {
|
||||
self.emit(Op::GetCompletion);
|
||||
}
|
||||
self.stmts(fin)?;
|
||||
self.block(fin)?;
|
||||
if keeps_completion {
|
||||
self.emit(Op::SetCompletion);
|
||||
}
|
||||
@@ -822,7 +1146,10 @@ impl<'a> FnCompiler<'a> {
|
||||
let Some(e) = self.ast.expr(id) else { return internal("expression out of range") };
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
match e {
|
||||
Expr::This => self.emit(Op::This),
|
||||
Expr::This => {
|
||||
self.uses_this = true;
|
||||
self.emit(Op::This);
|
||||
}
|
||||
Expr::Ident(name) => {
|
||||
let n = self.var_name(name);
|
||||
self.emit(Op::GetVar(n));
|
||||
@@ -843,10 +1170,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::NewArray);
|
||||
for el in elements {
|
||||
match el {
|
||||
Some(e) => {
|
||||
self.expr(*e)?;
|
||||
self.emit(Op::ArrayPush);
|
||||
}
|
||||
Some(e) => self.array_element(*e)?,
|
||||
None => self.emit(Op::ArrayHole),
|
||||
}
|
||||
}
|
||||
@@ -857,12 +1181,25 @@ impl<'a> FnCompiler<'a> {
|
||||
self.emit(Op::Closure(i));
|
||||
}
|
||||
Expr::Member { .. } | Expr::Index { .. } | Expr::Call { .. } => self.chain(id)?,
|
||||
Expr::New { callee, args } if self.has_spread(args) => {
|
||||
self.expr(*callee)?;
|
||||
self.spread_args(args)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::NewSpread);
|
||||
}
|
||||
Expr::New { callee, args } => {
|
||||
self.expr(*callee)?;
|
||||
self.args(args)?;
|
||||
self.at(self.ast.expr_span(id).start);
|
||||
self.emit(Op::New(len_u32(args.len())));
|
||||
}
|
||||
Expr::Arrow(fid) => {
|
||||
let i = self.function(*fid)?;
|
||||
self.emit(Op::Closure(i));
|
||||
}
|
||||
Expr::Template { quasis, exprs } => self.template(quasis, exprs)?,
|
||||
Expr::TaggedTemplate { .. } => self.chain(id)?,
|
||||
Expr::Spread(_) => return internal("spread outside an array literal or argument list"),
|
||||
Expr::Update { op, prefix, target } => self.update(*op, *prefix, *target)?,
|
||||
Expr::Unary { .. } => self.unary(id)?,
|
||||
Expr::Binary { .. } | Expr::Logical { .. } => self.binary_chain(id)?,
|
||||
@@ -985,6 +1322,62 @@ impl<'a> FnCompiler<'a> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn has_spread(&self, args: &[ExprId]) -> bool {
|
||||
args.iter().any(|&a| matches!(self.ast.expr(a), Some(Expr::Spread(_))))
|
||||
}
|
||||
|
||||
/// `array` → `array` with the element appended: a value, or a spread's elements.
|
||||
fn array_element(&mut self, e: ExprId) -> CResult<()> {
|
||||
if let Some(Expr::Spread(arg)) = self.ast.expr(e) {
|
||||
self.expr(*arg)?;
|
||||
self.at(self.ast.expr_span(e).start);
|
||||
self.emit(Op::ArraySpread);
|
||||
} else {
|
||||
self.expr(e)?;
|
||||
self.emit(Op::ArrayPush);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pushes an array of the arguments, for a call or `new` with a spread among them.
|
||||
fn spread_args(&mut self, args: &[ExprId]) -> CResult<()> {
|
||||
self.emit(Op::NewArray);
|
||||
for &a in args {
|
||||
self.array_element(a)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A template literal: its pieces joined with the strings of its substitutions.
|
||||
fn template(&mut self, quasis: &[TemplatePiece], exprs: &[ExprId]) -> CResult<()> {
|
||||
let Some((first, rest)) = quasis.split_first() else { return internal("template without pieces") };
|
||||
let i = self.string(&first.cooked);
|
||||
self.emit(Op::String(i));
|
||||
if rest.len() != exprs.len() {
|
||||
return internal("template pieces do not match its substitutions");
|
||||
}
|
||||
for (piece, &e) in rest.iter().zip(exprs) {
|
||||
self.expr(e)?;
|
||||
self.at(self.ast.expr_span(e).start);
|
||||
self.emit(Op::ToStr);
|
||||
self.emit(Op::Binary(BinaryOp::Add));
|
||||
if !piece.cooked.is_empty() {
|
||||
let i = self.string(&piece.cooked);
|
||||
self.emit(Op::String(i));
|
||||
self.emit(Op::Binary(BinaryOp::Add));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds a tagged template's strings to the template table and returns their index.
|
||||
fn template_entry(&mut self, quasis: &[TemplatePiece]) -> u32 {
|
||||
let cooked = quasis.iter().map(|q| Str::from_units(q.cooked.clone())).collect();
|
||||
let raw = quasis.iter().map(|q| Str::from_units(q.raw.clone())).collect();
|
||||
self.templates.push(Template { cooked, raw });
|
||||
len_u32(self.templates.len() - 1)
|
||||
}
|
||||
|
||||
fn object_literal(&mut self, props: &[crate::ast::Property]) -> CResult<()> {
|
||||
self.emit(Op::NewObject);
|
||||
for p in props {
|
||||
@@ -1022,14 +1415,15 @@ impl<'a> FnCompiler<'a> {
|
||||
suffixes.push(cur);
|
||||
cur = self.ast.unparenthesized(*object);
|
||||
}
|
||||
Some(Expr::Call { callee, .. }) => {
|
||||
Some(Expr::Call { callee, .. } | Expr::TaggedTemplate { tag: callee, .. }) => {
|
||||
suffixes.push(cur);
|
||||
cur = self.ast.unparenthesized(*callee);
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
let is_call = |c: &Self, e: Option<&ExprId>| e.is_some_and(|&e| matches!(c.ast.expr(e), Some(Expr::Call { .. })));
|
||||
let is_call =
|
||||
|c: &Self, e: Option<&ExprId>| e.is_some_and(|&e| matches!(c.ast.expr(e), Some(Expr::Call { .. } | Expr::TaggedTemplate { .. })));
|
||||
let first_is_call = is_call(self, suffixes.last());
|
||||
let mut base_has_this = false;
|
||||
let mut eval_call = false;
|
||||
@@ -1068,7 +1462,7 @@ impl<'a> FnCompiler<'a> {
|
||||
self.at(span.start);
|
||||
self.xml_filter(*predicate)?;
|
||||
}
|
||||
Some(Expr::Call { args, .. }) => {
|
||||
Some(call @ (Expr::Call { .. } | Expr::TaggedTemplate { .. })) => {
|
||||
let innermost = j + 1 == count;
|
||||
let has_this = if innermost {
|
||||
base_has_this
|
||||
@@ -1078,14 +1472,37 @@ impl<'a> FnCompiler<'a> {
|
||||
if !has_this {
|
||||
self.emit(Op::Undefined);
|
||||
}
|
||||
self.args(args)?;
|
||||
self.at(span.start);
|
||||
let n = len_u32(args.len());
|
||||
if innermost && eval_call {
|
||||
self.uses_arguments = true;
|
||||
self.emit(Op::CallEval(n));
|
||||
} else {
|
||||
self.emit(Op::Call(n));
|
||||
let eval = match call {
|
||||
Expr::TaggedTemplate { quasis, exprs, .. } => {
|
||||
let t = self.template_entry(quasis);
|
||||
self.at(span.start);
|
||||
self.emit(Op::TemplateObject(t));
|
||||
self.args(exprs)?;
|
||||
self.at(span.start);
|
||||
self.emit(Op::Call(len_u32(exprs.len()).saturating_add(1)));
|
||||
continue;
|
||||
}
|
||||
Expr::Call { args, .. } => {
|
||||
let eval = innermost && eval_call;
|
||||
if eval {
|
||||
self.uses_arguments = true;
|
||||
self.uses_this = true;
|
||||
}
|
||||
if self.has_spread(args) {
|
||||
self.spread_args(args)?;
|
||||
self.at(span.start);
|
||||
self.emit(Op::CallSpread(eval));
|
||||
continue;
|
||||
}
|
||||
self.args(args)?;
|
||||
self.at(span.start);
|
||||
(eval, len_u32(args.len()))
|
||||
}
|
||||
_ => return internal("not a call"),
|
||||
};
|
||||
match eval {
|
||||
(true, n) => self.emit(Op::CallEval(n)),
|
||||
(false, n) => self.emit(Op::Call(n)),
|
||||
}
|
||||
}
|
||||
_ => return internal("not a member or call"),
|
||||
@@ -1379,6 +1796,14 @@ impl<'a> FnCompiler<'a> {
|
||||
uses_arguments: self.uses_arguments,
|
||||
source: self.source.clone(),
|
||||
span: meta.span,
|
||||
scopes: std::mem::take(&mut self.scopes),
|
||||
top_scope: meta.top_scope,
|
||||
templates: std::mem::take(&mut self.templates),
|
||||
rest: meta.rest,
|
||||
length: meta.length,
|
||||
arrow: meta.arrow,
|
||||
uses_this: self.uses_this,
|
||||
param_init: meta.param_init,
|
||||
};
|
||||
code.max_stack = verify(&code).map_err(CompileFail::Internal)?;
|
||||
Ok(Rc::new(code))
|
||||
@@ -1392,6 +1817,11 @@ struct Meta {
|
||||
decl_name: Option<Key>,
|
||||
params: Vec<Key>,
|
||||
span: (u32, u32),
|
||||
top_scope: Option<u32>,
|
||||
rest: Option<Key>,
|
||||
length: u32,
|
||||
arrow: bool,
|
||||
param_init: bool,
|
||||
}
|
||||
|
||||
fn len_u32(n: usize) -> u32 {
|
||||
@@ -1399,23 +1829,63 @@ fn len_u32(n: usize) -> u32 {
|
||||
}
|
||||
|
||||
/// Compiles function `fid` of `ast`. With `bind_name`, a function expression's name is bound
|
||||
/// inside it.
|
||||
pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>, recursion: u32, bind_name: bool) -> CResult<Rc<Code>> {
|
||||
/// inside it. `es2015` is [`crate::Options::es2015`] of the script it is in.
|
||||
pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>, recursion: u32, bind_name: bool, es2015: bool) -> CResult<Rc<Code>> {
|
||||
let Some(f) = ast.function(fid) else { return internal("function out of range") };
|
||||
let mut c = FnCompiler::new(ast, source, CodeKind::Function, f.strict, recursion);
|
||||
c.es2015 = es2015;
|
||||
c.at(f.span.start);
|
||||
c.enter()?;
|
||||
let hoisted = c.hoist(&f.body)?;
|
||||
let params: Vec<Key> = f.params.iter().map(|p| key_of(&p.name)).collect();
|
||||
let rest = f.rest.as_ref().map(|r| key_of(&r.name));
|
||||
let all_params: Vec<Key> = params.iter().chain(&rest).cloned().collect();
|
||||
let hoisted = c.hoist(&f.body, &all_params)?;
|
||||
let top_scope = c.list_scope(&f.body, false)?;
|
||||
let param_init = !f.simple_params();
|
||||
if param_init {
|
||||
// Each parameter is initialized in order, from its argument or, when that is
|
||||
// `undefined`, its default value; then the body's environment is entered.
|
||||
for (i, p) in f.params.iter().enumerate() {
|
||||
c.at(p.span.start);
|
||||
let n = c.var_name(&p.name);
|
||||
c.emit(Op::LoadParam(n));
|
||||
if let Some(Some(default)) = f.defaults.get(i) {
|
||||
let skip = c.new_label();
|
||||
c.emit(Op::Dup);
|
||||
c.emit(Op::Undefined);
|
||||
c.emit(Op::Binary(BinaryOp::StrictEq));
|
||||
c.jump(Op::JumpIfFalse, skip);
|
||||
c.emit(Op::Pop);
|
||||
c.expr(*default)?;
|
||||
c.bind(skip);
|
||||
}
|
||||
c.at(p.span.start);
|
||||
c.emit(Op::InitVar(n));
|
||||
}
|
||||
if let Some(r) = &f.rest {
|
||||
c.at(r.span.start);
|
||||
let n = c.var_name(&r.name);
|
||||
c.emit(Op::LoadParam(n));
|
||||
c.emit(Op::InitVar(n));
|
||||
}
|
||||
c.emit(Op::BodyEnv);
|
||||
}
|
||||
c.stmts(&f.body)?;
|
||||
c.at(f.span.end.saturating_sub(1));
|
||||
c.emit(Op::Undefined);
|
||||
c.emit(Op::Return);
|
||||
let name = f.name.as_ref().map(|n| key_of(&n.name));
|
||||
let length = f.defaults.iter().position(Option::is_some).unwrap_or(params.len());
|
||||
let meta = Meta {
|
||||
decl_name: if f.kind == FunctionKind::Declaration { name.clone() } else { None },
|
||||
self_name: if bind_name && f.kind == FunctionKind::Expression { name } else { None },
|
||||
params: f.params.iter().map(|p| key_of(&p.name)).collect(),
|
||||
params,
|
||||
span: (f.span.start, f.span.end),
|
||||
top_scope,
|
||||
rest,
|
||||
length: len_u32(length),
|
||||
arrow: f.kind == FunctionKind::Arrow,
|
||||
param_init,
|
||||
};
|
||||
c.finish(hoisted, meta)
|
||||
}
|
||||
@@ -1423,11 +1893,13 @@ pub(crate) fn compile_function(ast: &Ast, fid: FunctionId, source: &Rc<Source>,
|
||||
/// Compiles a script (`kind` [`CodeKind::Global`]) or eval code ([`CodeKind::Eval`]).
|
||||
pub(crate) fn compile_program(program: &crate::Program, source: &Rc<Source>, kind: CodeKind) -> CResult<Rc<Code>> {
|
||||
let mut c = FnCompiler::new(&program.ast, source, kind, program.strict, 0);
|
||||
let hoisted = c.hoist(&program.body)?;
|
||||
c.es2015 = program.es2015;
|
||||
let hoisted = c.hoist(&program.body, &[])?;
|
||||
let top_scope = c.list_scope(&program.body, false)?;
|
||||
c.stmts(&program.body)?;
|
||||
c.emit(Op::ReturnCompletion);
|
||||
let end = u32::try_from(source.text.len()).unwrap_or(u32::MAX);
|
||||
c.finish(hoisted, Meta { span: (0, end), ..Meta::default() })
|
||||
c.finish(hoisted, Meta { span: (0, end), top_scope, ..Meta::default() })
|
||||
}
|
||||
|
||||
/// The function of a `Function` constructor's source, `(function anonymous(…) {…})`: the program
|
||||
@@ -1438,5 +1910,5 @@ pub(crate) fn compile_constructed_function(program: &crate::Program, source: &Rc
|
||||
let Some(Stmt::Expr(e)) = program.ast.stmt(*stmt) else { return Ok(None) };
|
||||
let Some(Expr::Paren(inner)) = program.ast.expr(*e) else { return Ok(None) };
|
||||
let Some(Expr::Function(fid)) = program.ast.expr(*inner) else { return Ok(None) };
|
||||
compile_function(&program.ast, *fid, source, 0, false).map(Some)
|
||||
compile_function(&program.ast, *fid, source, 0, false, program.es2015).map(Some)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,935 @@
|
||||
use proptest::prelude::*;
|
||||
|
||||
use crate::{JsValue, LimitKind, Limits, Options, Realm, RunError, RunErrorKind};
|
||||
|
||||
fn es_options() -> Options {
|
||||
Options { es2015: true, ..Options::default() }
|
||||
}
|
||||
|
||||
fn es() -> Realm {
|
||||
Realm::with_options(es_options(), Limits::default())
|
||||
}
|
||||
|
||||
fn run(src: &str) -> JsValue {
|
||||
match es().run(src) {
|
||||
Ok(v) => v,
|
||||
Err(e) => panic!("{src}\n{e:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn truth(src: &str) {
|
||||
assert_eq!(run(src), JsValue::Bool(true), "{src}");
|
||||
}
|
||||
|
||||
fn string(src: &str) -> String {
|
||||
match run(src) {
|
||||
JsValue::String(s) => s,
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The script throws an error whose message starts with `name`.
|
||||
fn throws(src: &str, name: &str) {
|
||||
match es().run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Thrown, message, .. }) => assert!(message.starts_with(name), "{src}: {message}"),
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The script does not parse.
|
||||
fn syntax(src: &str) {
|
||||
match es().run(src) {
|
||||
Err(RunError { kind: RunErrorKind::Syntax, .. }) => {}
|
||||
other => panic!("{src}: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- let and const ----
|
||||
|
||||
#[test]
|
||||
fn let_and_const_are_scoped_to_their_block() {
|
||||
truth("let x = 1; { let x = 2; } x === 1");
|
||||
truth("var r = []; { const c = 3; r.push(c); } r[0] === 3 && typeof c === 'undefined'");
|
||||
truth("function f() { if (true) { let y = 5; } return typeof y; } f() === 'undefined'");
|
||||
truth("let a = 1, b = a + 1; b === 2");
|
||||
truth("switch (0) { case 0: let s = 6; case 1: s += 1; } typeof s === 'undefined'");
|
||||
// The cases share one scope, so a case that skips the declaration finds the binding uninitialized.
|
||||
throws("switch (1) { case 0: let s = 0; break; case 1: s = 7; }", "ReferenceError");
|
||||
truth("try { throw 1 } catch (e) { let e2 = e + 1; } typeof e2 === 'undefined'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_binding_is_unusable_before_its_declaration_runs() {
|
||||
throws("x; let x = 1;", "ReferenceError");
|
||||
throws("{ x = 2; let x; }", "ReferenceError");
|
||||
throws("typeof x; const x = 1;", "ReferenceError");
|
||||
throws("function f() { return v; } f(); let v = 1;", "ReferenceError");
|
||||
throws("let q = q;", "ReferenceError");
|
||||
throws("for (let k in k) {}", "ReferenceError");
|
||||
// A declaration without an initializer initializes to undefined where it stands.
|
||||
truth("let u; u === undefined");
|
||||
// A function that runs after the declaration sees the binding.
|
||||
truth("function g() { return w; } let w = 4; g() === 4");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn assigning_a_const_is_a_type_error_in_any_code() {
|
||||
throws("const c = 1; c = 2;", "TypeError");
|
||||
throws("'use strict'; const c = 1; c = 2;", "TypeError");
|
||||
throws("const c = 1; c++;", "TypeError");
|
||||
throws("const c = 1; c += 1;", "TypeError");
|
||||
throws("for (const i = 0; i < 2; i++) {}", "TypeError");
|
||||
truth("const o = {}; o.x = 1; o.x === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redeclarations_and_bad_declarations_are_syntax_errors() {
|
||||
syntax("let a; let a;");
|
||||
syntax("let a; var a;");
|
||||
syntax("var a; let a;");
|
||||
syntax("const a = 1; function a() {}");
|
||||
syntax("{ let a; { var a; } }");
|
||||
syntax("function f(p) { let p; }");
|
||||
syntax("try {} catch (e) { let e; }");
|
||||
syntax("const c;");
|
||||
syntax("let let = 1;");
|
||||
syntax("let [a] = [1];");
|
||||
syntax("'use strict'; { function f() {} function f() {} }");
|
||||
syntax("for (let x = 1 in {}) {}");
|
||||
syntax("if (1) let x = 1;");
|
||||
// Outside strict mode code `let` is still a name where no declaration can start.
|
||||
truth("var let = 3; let === 3");
|
||||
truth("{ function f() { return 1; } function f() { return 2; } } f() === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_let_loop_gives_each_iteration_its_own_binding() {
|
||||
truth("var fs = []; for (let i = 0; i < 3; i++) { fs.push(function() { return i; }); } fs[0]() === 0 && fs[1]() === 1 && fs[2]() === 2");
|
||||
truth("var fs = []; for (let i = 0; i < 3; i++) { fs.push(() => i); i += 0; } fs.map(function(f) { return f(); }).join() === '0,1,2'");
|
||||
truth("var fs = []; for (let k in {a: 1, b: 2}) { fs.push(function() { return k; }); } fs[0]() === 'a' && fs[1]() === 'b'");
|
||||
truth("var fs = []; for (const k in {a: 1, b: 2}) { fs.push(() => k); } fs[0]() + fs[1]() === 'ab'");
|
||||
// `continue` and `break` leave the iteration's environment.
|
||||
truth("var s = 0; for (let i = 0; i < 5; i++) { if (i === 1) continue; if (i === 3) break; s += i; } s === 2");
|
||||
truth("var s = ''; for (let k in {a: 1, b: 2, c: 3}) { if (k === 'b') continue; s += k; } s === 'ac'");
|
||||
truth("var i = 'outer'; for (let i = 0; i < 1; i++) {} i === 'outer'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_declared_in_blocks_are_scoped_to_the_block() {
|
||||
truth("'use strict'; { function f() { return 1; } } typeof f === 'undefined'");
|
||||
// Outside strict mode code the name is also a variable, assigned when the declaration runs.
|
||||
truth("var before = typeof f; { function f() { return 1; } } before === 'undefined' && f() === 1");
|
||||
truth("{ let x = 2; function g() { return x; } } g() === 2");
|
||||
truth("function h() { if (true) { function inner() { return 'i'; } } return inner(); } h() === 'i'");
|
||||
// Only a `let` or `const` around the declaration, or a parameter, keeps the name from being a variable.
|
||||
truth("function f() { { let g; } { function g() {} } return typeof g; } f() === 'function'");
|
||||
truth("function f() { let g = 1; { function g() {} } return g; } f() === 1");
|
||||
truth("function f() { { let g = 1; { function g() {} } } return typeof g; } f() === 'undefined'");
|
||||
truth("function f() { for (let g = 0; g < 1; g++) { function g() {} } return typeof g; } f() === 'undefined'");
|
||||
truth("function f(g) { { function g() {} } return g; } f(5) === 5");
|
||||
// Each declaration is judged on its own: one inside a `let` of the same name leaves the variable alone.
|
||||
truth("function f() { { function g() { return 1; } } { let g; { function g() { return 2; } } } return g(); } f() === 1");
|
||||
truth("{ function t() { return 1; } } { let t; { function t() { return 2; } } } t() === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_block_function_inside_another_of_its_name_leaves_the_variable_alone() {
|
||||
truth("var f; { function f() { return 'outer'; } { function f() { return 'inner'; } } } f() === 'outer'");
|
||||
truth("function g() { { function f() { return 1; } { function f() { return 2; } } } return f(); } g() === 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_labelled_function_in_a_block_is_made_when_the_block_is_entered() {
|
||||
truth("let f = 0; { var value = f(); label: function f() { return 7; } } value === 7 && f === 0");
|
||||
truth("{ var early = g(); a: b: function g() { return 8; } } early === 8 && g() === 8");
|
||||
truth("label: function top() { return 1; } top() === 1");
|
||||
syntax("let f; label: function f() {}");
|
||||
syntax("label: function f() {} let f;");
|
||||
syntax("{ let f; label: function f() {} }");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_standing_alone_as_an_if_branch_has_a_block_of_its_own() {
|
||||
truth("var f; if (true) function f() { return f; } var saved = f; f = 0; saved() === saved");
|
||||
truth("var g; if (false) ; else function g() { return g; } var kept = g; g = 0; kept() === kept");
|
||||
truth("if (true) function h() { return 3; } h() === 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn global_lexical_bindings_stay_across_runs_and_cannot_be_redeclared() {
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("let kept = 5; const fixed = 1; kept"), Ok(JsValue::Number(5.0)));
|
||||
assert_eq!(realm.run("kept + fixed"), Ok(JsValue::Number(6.0)));
|
||||
assert_eq!(realm.run("this.kept === undefined"), Ok(JsValue::Bool(true)));
|
||||
let again = realm.run("let kept = 6;");
|
||||
assert!(matches!(&again, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{again:?}");
|
||||
let var = realm.run("var fixed;");
|
||||
assert!(matches!(&var, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{var:?}");
|
||||
assert_eq!(realm.run("kept"), Ok(JsValue::Number(5.0)));
|
||||
let restricted = realm.run("let undefined = 1;");
|
||||
assert!(restricted.is_err(), "{restricted:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn functions_from_earlier_runs_see_later_global_lexical_bindings() {
|
||||
let mut realm = Realm::new();
|
||||
let first = realm.run("function read() { return x; } function call(f) { return f(); }");
|
||||
assert!(first.is_ok(), "{first:?}");
|
||||
let made = realm.run("(0, eval)('function viaEval() { return x; }'); var made = new Function('return x');");
|
||||
assert!(made.is_ok(), "{made:?}");
|
||||
realm.set_es2015(true);
|
||||
assert_eq!(realm.run("let x = 7; read() + call(() => x) + viaEval() + made()"), Ok(JsValue::Number(28.0)));
|
||||
realm.set_es2015(false);
|
||||
assert_eq!(realm.run("function later() { return x; } later() + read()"), Ok(JsValue::Number(14.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_eval_declares_on_the_global_object_sees_global_lexical_bindings() {
|
||||
// Without the option, eval code's functions close over its variable environment; on the
|
||||
// global object that is the global scope, which holds the scripts' `let` and `const` names.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("let x = 7; 0"), Ok(JsValue::Number(0.0)));
|
||||
realm.set_es2015(false);
|
||||
// The `with` object's `x` would be read if the function closed over the eval's lexical
|
||||
// environment.
|
||||
assert_eq!(realm.run("with ({ x: 99 }) { eval('function read() { return x; }'); } read()"), Ok(JsValue::Number(7.0)));
|
||||
// In a function, the variable environment is the function's own, which holds its `var x`.
|
||||
let local = "function g() { var x = 8; with ({ x: 99 }) { eval('function inner() { return x; }'); } return inner(); } g()";
|
||||
assert_eq!(realm.run(local), Ok(JsValue::Number(8.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_var_makes_its_own_property_over_an_inherited_one() {
|
||||
// ECMA-262 2015 section 8.1.1.4.17 reads the global object's own property, so `var` makes a
|
||||
// new one even when the global object inherits the name.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("Object.prototype.inherited = 1; Object.prototype.viaEval = 2; 0"), Ok(JsValue::Number(0.0)));
|
||||
let own = "var inherited; (0, eval)('var viaEval'); this.hasOwnProperty('inherited') && inherited === undefined \
|
||||
&& this.hasOwnProperty('viaEval') && viaEval === undefined";
|
||||
assert_eq!(realm.run(own), Ok(JsValue::Bool(true)));
|
||||
// Without the option, the inherited property counts as declared (ECMA-262 5.1 section 10.5).
|
||||
let mut realm = Realm::new();
|
||||
assert_eq!(realm.run("Object.prototype.inherited = 1; 0"), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("var inherited; !this.hasOwnProperty('inherited') && inherited === 1"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_function_that_cannot_be_declared_declares_nothing() {
|
||||
let mut realm = es();
|
||||
let failed = realm.run("let retained = 1; function undefined() {}");
|
||||
assert!(matches!(&failed, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")), "{failed:?}");
|
||||
assert_eq!(realm.run("typeof retained"), Ok(JsValue::String("undefined".into())));
|
||||
assert_eq!(realm.run("let retained = 2; retained"), Ok(JsValue::Number(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_function_is_judged_by_the_global_objects_own_property() {
|
||||
// ECMA-262 2015 sections 8.1.1.4.16 and 8.1.1.4.18 read the global object's own property, so
|
||||
// a fixed property the global object inherits does not stop the declaration.
|
||||
let mut realm = es();
|
||||
let setup = "Object.defineProperty(Object.prototype, 'fixed', { value: 1 }); \
|
||||
Object.defineProperty(Object.prototype, 'getter', { get: function () { return 1; } }); 0";
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("function fixed() { return 2; } function getter() { return 3; } fixed() + getter()"), Ok(JsValue::Number(5.0)));
|
||||
let own = "var d = Object.getOwnPropertyDescriptor(this, 'fixed'); d.writable && d.enumerable && !d.configurable && ({}).fixed === 1";
|
||||
assert_eq!(realm.run(own), Ok(JsValue::Bool(true)));
|
||||
// A global object that is not extensible takes no new function, inherited name or not, and
|
||||
// a function declared next to one it cannot take is not declared either.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run(&format!("{setup}; var kept = 1; Object.preventExtensions(this); 0")), Ok(JsValue::Number(0.0)));
|
||||
for decl in [
|
||||
"function fixed() {}",
|
||||
"function fresh() {}",
|
||||
"(0, eval)('function fixed() {}')",
|
||||
"(0, eval)('function fresh() {}')",
|
||||
"(0, eval)('function kept() {} function fresh() {}')",
|
||||
] {
|
||||
let failed = realm.run(decl);
|
||||
assert!(
|
||||
matches!(&failed, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("TypeError")),
|
||||
"{decl}: {failed:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(realm.run("this.hasOwnProperty('fixed') || this.hasOwnProperty('fresh') || kept !== 1"), Ok(JsValue::Bool(false)));
|
||||
}
|
||||
|
||||
fn is_thrown(result: &Result<JsValue, RunError>, name: &str) -> bool {
|
||||
matches!(result, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with(name))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_var_stops_a_later_let_even_on_a_configurable_property() {
|
||||
// ECMA-262 2015 section 15.1.8 checks the names global `var` declarations made, not only the
|
||||
// property attributes.
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("this.x = 1; this.y = 1; 0"), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("var x; 0"), Ok(JsValue::Number(0.0)));
|
||||
let again = realm.run("let x = 2;");
|
||||
assert!(is_thrown(&again, "SyntaxError"), "{again:?}");
|
||||
// A property no `var` declared still takes a `let`.
|
||||
assert_eq!(realm.run("let y = 2; y"), Ok(JsValue::Number(2.0)));
|
||||
// A variable eval code declared can be deleted, and then its name takes a `let`.
|
||||
assert_eq!(realm.run("(0, eval)('var z = 1'); 0"), Ok(JsValue::Number(0.0)));
|
||||
assert!(is_thrown(&realm.run("let z;"), "SyntaxError"));
|
||||
assert_eq!(realm.run("delete z"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("let z = 3; z"), Ok(JsValue::Number(3.0)));
|
||||
assert_eq!(realm.run("(0, eval)('var w = 1'); delete this.w"), Ok(JsValue::Bool(true)));
|
||||
assert_eq!(realm.run("let w = 4; w"), Ok(JsValue::Number(4.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_global_var_that_cannot_be_declared_declares_nothing() {
|
||||
let mut realm = es();
|
||||
assert_eq!(realm.run("var kept = 1; Object.preventExtensions(this); 0"), Ok(JsValue::Number(0.0)));
|
||||
for decl in ["let x = 1; var y;", "(0, eval)('var y;');", "(0, eval)('let w; var y;');"] {
|
||||
let failed = realm.run(decl);
|
||||
assert!(is_thrown(&failed, "TypeError"), "{decl}: {failed:?}");
|
||||
}
|
||||
assert_eq!(realm.run("this.hasOwnProperty('y')"), Ok(JsValue::Bool(false)));
|
||||
// `x` was not declared, and a `var` the global object already has stays allowed.
|
||||
assert_eq!(realm.run("let x = 2; var kept; x + kept"), Ok(JsValue::Number(3.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eval_code_keeps_its_let_and_const_to_itself() {
|
||||
truth("eval('let e = 1; e') === 1 && typeof e === 'undefined'");
|
||||
truth("function f() { eval('var v = 2; let l = 3;'); return v + typeof l; } f() === '2undefined'");
|
||||
truth("let outer = 4; eval('outer') === 4");
|
||||
truth("(0, eval)('let g = 5; g') === 5");
|
||||
// A variable eval code declares cannot take the name of a `let` or `const` around it.
|
||||
throws("let x; eval('var x;');", "SyntaxError");
|
||||
throws("let x; (0, eval)('var x;');", "SyntaxError");
|
||||
throws("function f() { let y; { eval('var y;'); } } f();", "SyntaxError");
|
||||
throws("{ let z; eval('function z() {}'); }", "SyntaxError");
|
||||
throws("{ function w() {} eval('var w;'); }", "SyntaxError");
|
||||
truth("function f() { let y; return eval(\"'use strict'; var y = 1; y\"); } f() === 1");
|
||||
truth("try { throw 1; } catch (e) { eval('var e = 2;'); } true");
|
||||
truth("function f() { { let v; } eval('var v = 3;'); return v; } f() === 3");
|
||||
// Nor, in a default parameter's value, the name of a parameter; the body can.
|
||||
throws("var n = 0; function f(a = eval('var a = 1')) { n++; } try { f(); } finally { n === 0 || ok; }", "SyntaxError");
|
||||
truth("function f(a = eval('var b = 1; b')) { return a; } f() === 1");
|
||||
truth("function f(a = 0) { eval('var a = 2;'); return a; } f() === 2");
|
||||
// Nothing is declared when the check fails.
|
||||
truth("let a; try { eval('var b; var a;'); } catch (e) {} typeof b === 'undefined'");
|
||||
}
|
||||
|
||||
// ---- arrow functions ----
|
||||
|
||||
#[test]
|
||||
fn arrow_functions_take_this_and_arguments_from_around_them() {
|
||||
truth("var o = { v: 1, f: function() { return () => this.v; } }; o.f()() === 1");
|
||||
truth("var o = { v: 1, f: function() { return () => () => this.v; } }; o.f()()() === 1");
|
||||
truth("function f() { return (() => arguments[0])(); } f(7) === 7");
|
||||
truth("var o = { v: 2, f: function() { var g = () => this.v; return g.call({ v: 3 }); } }; o.f() === 2");
|
||||
truth("var o = { f: function() { return () => eval('this'); } }; o.f()() === o");
|
||||
truth("(() => this)() === this");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_functions_have_expression_and_block_bodies() {
|
||||
truth("var f = x => x * 2; f(4) === 8");
|
||||
truth("var f = (a, b) => a + b; f(1, 2) === 3");
|
||||
truth("var f = () => { return 3; }; f() === 3");
|
||||
truth("var f = () => ({ a: 1 }); f().a === 1");
|
||||
truth("var f = (a = 2, ...r) => a + r.length; f(undefined, 1, 2) === 4");
|
||||
truth("var f = x => y => x + y; f(1)(2) === 3");
|
||||
truth("var t = true ? () => 1 : () => 2; t() === 1");
|
||||
truth("[1, 2, 3].map(x => x + 1).join() === '2,3,4'");
|
||||
truth("var f = (x) => x in { a: 1 }; f('a')");
|
||||
truth("var f = a => {}; f() === undefined");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arrow_functions_cannot_be_constructed() {
|
||||
truth("var f = () => 1; f.prototype === undefined && f.length === 0 && !f.hasOwnProperty('prototype')");
|
||||
throws("var f = () => 1; new f();", "TypeError");
|
||||
throws("var f = () => 1; var b = f.bind(null); new b();", "TypeError");
|
||||
truth("((a, b) => 0).length === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arrow_functions_are_syntax_errors() {
|
||||
syntax("var f = x\n=> x;");
|
||||
syntax("var f = (x, x) => 1;");
|
||||
syntax("var f = (a, ...b, c) => 1;");
|
||||
syntax("var f = ((a)) => 1;");
|
||||
syntax("var f = (a + 1) => 1;");
|
||||
syntax("var f = (...a);");
|
||||
syntax("var f = ();");
|
||||
syntax("'use strict'; var f = eval => 1;");
|
||||
syntax("var f = (a = 1) => { 'use strict'; };");
|
||||
syntax("1 + () => 2;");
|
||||
}
|
||||
|
||||
// ---- template literals ----
|
||||
|
||||
#[test]
|
||||
fn template_literals_join_their_pieces_and_substitutions() {
|
||||
assert_eq!(string("`a${1 + 1}b${'c'}`"), "a2bc");
|
||||
assert_eq!(string("``"), "");
|
||||
assert_eq!(string("`${'x'}`"), "x");
|
||||
assert_eq!(string("var o = { toString: function() { return 'T'; }, valueOf: function() { return 'V'; } }; `${o}`"), "T");
|
||||
assert_eq!(string("`a${`b${'c'}d`}e`"), "abcde");
|
||||
assert_eq!(string("`line\nnext`"), "line\nnext");
|
||||
assert_eq!(string("`cr\r\nlf`"), "cr\nlf");
|
||||
assert_eq!(string("`\\u{41}\\x42\\u0043`"), "ABC");
|
||||
assert_eq!(string("`a\\\nb`"), "ab");
|
||||
assert_eq!(string("`{${1}}`"), "{1}");
|
||||
assert_eq!(string("`$`"), "$");
|
||||
assert_eq!(string("`\\${1}`"), "${1}");
|
||||
// Substitutions run left to right.
|
||||
assert_eq!(string("var s = ''; `${s += 'a'}${s += 'b'}`; s"), "ab");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tagged_templates_get_one_frozen_strings_object_for_each_site() {
|
||||
truth("function tag(s, a, b) { return s.length === 3 && s[0] === 'x' && s[1] === '' && s[2] === 'y' && a === 1 && b === 2; } tag`x${1}${2}y`");
|
||||
truth("function tag(s) { return s.raw[0]; } tag`a\\nb` === 'a\\\\nb'");
|
||||
truth("function tag(s) { return s[0]; } tag`a\\nb` === 'a\\nb'");
|
||||
truth("function tag(s) { return s; } function f() { return tag`k`; } f() === f()");
|
||||
truth("function tag(s) { return s; } tag`k` !== tag`k`");
|
||||
truth(
|
||||
"function tag(s) { return Object.isFrozen(s) && Object.isFrozen(s.raw) && !Object.getOwnPropertyDescriptor(s, 'raw').enumerable; } tag`a${0}b`",
|
||||
);
|
||||
truth("var o = { v: 1, m: function(s) { return this.v; } }; o.m`x` === 1");
|
||||
truth("function tag(s) { return s.raw.join('|'); } tag`a\r\nb${0}\\\r\nc` === 'a\\nb|\\\\\\nc'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_objects_go_once_their_code_cannot_run() {
|
||||
// Each eval makes code with two template sites; once it has run, nothing can run that code.
|
||||
let mut realm = es();
|
||||
let src = "function tag(s) { return s; } for (var i = 0; i < 50; i++) eval('tag`a`; tag`b`;'); 0";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Number(0.0)));
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.interp().template_objects.len(), 0);
|
||||
// While the code can run, both of its sites keep their objects.
|
||||
assert_eq!(realm.run("var sites = function () { return [tag`a`, tag`b`]; }; var first = sites(); 0"), Ok(JsValue::Number(0.0)));
|
||||
realm.collect_garbage();
|
||||
assert_eq!(realm.interp().template_objects.len(), 2);
|
||||
assert_eq!(realm.run("var again = sites(); again[0] === first[0] && again[1] === first[1]"), Ok(JsValue::Bool(true)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_preprocessor_line_does_not_start_after_a_template_that_spans_lines() {
|
||||
let options = Options { es2015: true, preprocessor_lines: true, ..Options::default() };
|
||||
assert!(crate::parse("var t = `${1}\n` #strict on", &options).is_err());
|
||||
let p = crate::parse("var t = `${1}\n`\n#strict on", &options);
|
||||
assert!(p.as_ref().is_ok_and(|p| p.directives.len() == 1), "{p:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_template_literals_are_syntax_errors() {
|
||||
syntax("`abc");
|
||||
syntax("`${1`");
|
||||
syntax("`\\01`");
|
||||
syntax("`\\1`");
|
||||
syntax("`\\xZ`");
|
||||
syntax("`\\u{110000}`");
|
||||
syntax("function t() {} t`\\u`");
|
||||
}
|
||||
|
||||
// ---- default and rest parameters ----
|
||||
|
||||
#[test]
|
||||
fn default_parameters_apply_to_undefined_arguments_in_order() {
|
||||
truth("function f(a, b = a + 1) { return b; } f(1) === 2 && f(1, 5) === 5 && f(1, undefined) === 2 && f(1, null) === null");
|
||||
truth("var n = 0; function f(a = ++n, b = ++n) { return [a, b].join(); } f() === '1,2' && f(9) === '9,3'");
|
||||
throws("function f(a = b, b) {} f();", "ReferenceError");
|
||||
throws("function f(a = a) {} f();", "ReferenceError");
|
||||
truth("function f(a, b = 1, c) {} f.length === 1");
|
||||
truth("function f(a, ...r) {} f.length === 1");
|
||||
// A function with defaults has an arguments object that does not follow the parameters.
|
||||
truth("function f(a = 0) { a = 9; return arguments[0]; } f(1) === 1");
|
||||
truth("function f(a = 0) { arguments[0] = 9; return a; } f(1) === 1");
|
||||
// The body's variables start with the parameter's value and are kept apart from it.
|
||||
truth("function f(a = 1) { var a; return a; } f() === 1");
|
||||
truth("function f(a = 1, g = () => a) { var a = 2; return g(); } f() === 1");
|
||||
truth("var x = 'outer'; function f(a = () => x) { var x = 'inner'; return a(); } f() === 'outer'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rest_parameters_collect_the_remaining_arguments() {
|
||||
truth("function f(a, ...r) { return Array.isArray(r) && r.length === 2 && r[0] === 2 && r[1] === 3; } f(1, 2, 3)");
|
||||
truth("function f(...r) { return r.length; } f() === 0");
|
||||
truth("function f(...r) { r.push(1); return r.length; } f(0) === 2");
|
||||
syntax("function f(...r, a) {}");
|
||||
syntax("function f(...r = []) {}");
|
||||
syntax("function f(a, a = 1) {}");
|
||||
syntax("function f(...a) { 'use strict'; }");
|
||||
// Already strict mode code too.
|
||||
syntax("'use strict'; function f(a = 1) { 'use strict'; }");
|
||||
syntax("'use strict'; var f = (...a) => { 'use strict'; };");
|
||||
syntax("var o = { set s(...v) {} };");
|
||||
}
|
||||
|
||||
// ---- spread ----
|
||||
|
||||
#[test]
|
||||
fn spread_expands_arrays_strings_and_array_like_objects() {
|
||||
truth("var a = [1, 2]; var b = [0, ...a, 3]; b.join() === '0,1,2,3' && b.length === 4");
|
||||
truth("var b = [...'a\\uD83D\\uDE00b']; b.length === 3 && b[1] === '\\uD83D\\uDE00'");
|
||||
truth("var b = [...{ length: 2, 0: 'x', 1: 'y' }]; b.join() === 'x,y'");
|
||||
// A negative, NaN or fractional length is read as ToLength reads it.
|
||||
truth("[...{ length: -1, 0: 'x' }].length === 0 && [...{ length: NaN }].length === 0");
|
||||
truth("var b = [...{ length: 1.9, 0: 'x', 1: 'y' }]; b.join() === 'x'");
|
||||
truth("function f() { return arguments.length; } f(...{ length: -4294967295, 0: 1 }) === 0");
|
||||
truth("var b = [...[1, , 3]]; b.length === 3 && 1 in b && b[1] === undefined");
|
||||
truth("var b = [, ...[1]]; b.length === 2 && !(0 in b)");
|
||||
truth("function f() { return arguments.length; } f(...[1, 2], 3, ...[]) === 3");
|
||||
truth("function f(a, b) { return a + b; } f(...[1, 2]) === 3");
|
||||
truth("var o = { v: 1, m: function(x) { return this.v + x; } }; o.m(...[1]) === 2");
|
||||
truth("function C(a, b) { this.s = a + b; } new C(...[1, 2]).s === 3");
|
||||
truth("Math.max(...[1, 5, 2]) === 5");
|
||||
truth("var s = ''; function f() {} f((s += 'a', 0), ...(s += 'b', []), (s += 'c', 0)); s === 'abc'");
|
||||
truth("function f() { return arguments; } var a = f(...'ab'); a[0] === 'a' && a[1] === 'b'");
|
||||
truth("eval(...['1 + 1']) === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_reads_a_string_object_by_code_point() {
|
||||
truth("var b = [...new String('a\\uD83D\\uDE00')]; b.length === 2 && b[0] === 'a' && b[1] === '\\uD83D\\uDE00'");
|
||||
truth("function f() { return arguments.length; } f(...new String('\\uD83D\\uDE00\\uD83D\\uDE00')) === 2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_reads_an_array_s_length_again_before_each_element() {
|
||||
let shrink = "var a = [1, 2]; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 'v'; } }); \
|
||||
var b = [...a]; b.length === 1 && b[0] === 'v'";
|
||||
truth(shrink);
|
||||
let grow = "var a = [1]; Object.defineProperty(a, 0, { get: function () { a.push(2); return 'v'; } }); \
|
||||
var b = [...a]; b.join() === 'v,2'";
|
||||
truth(grow);
|
||||
// An object that is not an array keeps the length it had when spread began.
|
||||
truth("var o = { length: 2, get 0() { o.length = 1; return 'v'; }, 1: 'w' }; [...o].join() === 'v,w'");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_s_spread_is_checked_against_the_elements_it_reads() {
|
||||
// The array starts at the longest length, and its first element's getter shrinks it, so
|
||||
// only one element is read and the result fits.
|
||||
let shrink = "var a = []; a.length = 4294967295; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 7; } }); \
|
||||
var b = [...a]; b.length === 1 && b[0] === 7";
|
||||
truth(shrink);
|
||||
let then_more = "var a = []; a.length = 4294967295; Object.defineProperty(a, 0, { get: function () { a.length = 1; return 7; } }); \
|
||||
var b = [...a, ...[1, 2]]; b.join() === '7,1,2'";
|
||||
truth(then_more);
|
||||
// An array no getter reads is checked when spread begins, without reading its elements.
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
|
||||
let long = realm.run("var a = []; a.length = 4294967295; [...a]");
|
||||
assert!(is_thrown(&long, "RangeError"), "{long:?}");
|
||||
// An object that is not an array is still checked against the length it has when spread
|
||||
// begins.
|
||||
throws("[0, ...{ length: 4294967295 }];", "RangeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_setter_without_a_getter_does_not_delay_the_spread_s_check() {
|
||||
// A setter does not run when the elements are read, so the array is still checked when
|
||||
// spread begins, on its own and on its prototype.
|
||||
for setter in ["a", "Array.prototype"] {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
|
||||
let src = format!("var a = []; a.length = 4294967295; Object.defineProperty({setter}, 0, {{ set: function () {{}} }}); [...a]");
|
||||
let long = realm.run(&src);
|
||||
assert!(is_thrown(&long, "RangeError"), "{setter}: {long:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn looking_for_index_getters_takes_fuel_for_each_property() {
|
||||
// Each attempt to spread the long array looks at every one of its 10,000 elements, so each
|
||||
// takes at least that much fuel.
|
||||
let fuel = 10_000_000;
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel, ..Limits::default() });
|
||||
let setup = "var a = []; for (var i = 0; i < 10000; i++) a[i] = i; a.length = 4294967295; 0";
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
|
||||
let attempt = "var ok = false; try { [...a]; } catch (e) { ok = e instanceof RangeError; } ok";
|
||||
assert_eq!(realm.run(attempt), Ok(JsValue::Bool(true)));
|
||||
let used = fuel - realm.interp().fuel;
|
||||
assert!(used >= 10_000, "{used}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_counts_each_index_name_against_the_heap() {
|
||||
// The elements' properties, with their index names and a string's characters, fit in the
|
||||
// heap or the run ends with the heap limit, at every limit in the range.
|
||||
for spread in ["[...a]", "[...s]"] {
|
||||
let setup = "var a = Array(4000); var s = new Array(4001).join('x'); 0";
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let base = measure.interp().heap.bytes;
|
||||
for extra in (0..640usize).map(|k| k * 1024) {
|
||||
let heap_bytes = base + extra;
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
if realm.run(setup).is_err() {
|
||||
continue;
|
||||
}
|
||||
match realm.run(&format!("var b = {spread}; b.length")) {
|
||||
Ok(v) => assert_eq!(v, JsValue::Number(4000.0), "{spread} at {heap_bytes}"),
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread} at {heap_bytes}: {e:?}"),
|
||||
}
|
||||
// A collection counts what is live, without the bytes the spread held while it ran.
|
||||
realm.interp().collect_garbage();
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{spread}: {} > {heap_bytes}", realm.interp().heap.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreading_other_values_is_a_type_error() {
|
||||
throws("[...1];", "TypeError");
|
||||
throws("[...null];", "TypeError");
|
||||
throws("[...undefined];", "TypeError");
|
||||
throws("[...{}];", "TypeError");
|
||||
throws("Math.max(...true);", "TypeError");
|
||||
throws("new Array(...{ a: 1 });", "TypeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spread_and_templates_stay_within_the_limits() {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 10_000, ..Limits::default() });
|
||||
let e = realm.run("[...{ length: 4294967294 }]").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Fuel), "{e:?}");
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: 4 << 20, ..Limits::default() });
|
||||
let e = realm.run("var s = 'x'; for (var i = 0; i < 22; i++) s += s; [...s]").unwrap_err();
|
||||
assert!(matches!(e.kind, RunErrorKind::Limit(_)), "{e:?}");
|
||||
throws("function f() {} f(...{ length: 100000 });", "RangeError");
|
||||
throws("var a = []; a.length = 4294967294; [0, ...a];", "RangeError");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spreading_a_rope_counts_its_flattened_length_first() {
|
||||
// `mk` returns a rope whose left half is a flat string of about half the heap, held by
|
||||
// nothing else. Its flattened copy is the other half, so the two don't fit together. Making
|
||||
// the left half takes about 16,400 fuel, and the elements read before the heap fills would
|
||||
// take more than the rest, so only the check before the copy ends the run with the heap limit.
|
||||
let build = "var s = 'x'; for (var i = 0; i < 18; i++) s = s + s; function f(c) { return s + c; } \
|
||||
function mk() { var a = f('a'); a[0]; return a + 'b'; }";
|
||||
let limits = Limits { heap_bytes: 4 * 262_146, fuel: 20_000, ..Limits::default() };
|
||||
for spread in ["[...mk()]", "Math.max(...mk())"] {
|
||||
let e = Realm::with_options(es_options(), limits.clone()).run(&format!("{build} {spread}; 0")).unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{spread}: {e:?}");
|
||||
}
|
||||
let made = Realm::with_options(es_options(), limits).run(&format!("{build} mk(); 0"));
|
||||
assert_eq!(made, Ok(JsValue::Number(0.0)), "the rope is made within the fuel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rest_parameter_checks_the_heap_before_its_array_is_made() {
|
||||
// The 20,000 arguments fit in the room left over, and the rest array of them does not, so
|
||||
// the call ends with the heap limit before the heap estimate passes it.
|
||||
let setup = "function f(...r) { return r.length; } var big = Array(20000); 0";
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let heap_bytes = measure.interp().heap.bytes + (512 << 10);
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
assert_eq!(realm.run(setup), Ok(JsValue::Number(0.0)));
|
||||
assert_eq!(realm.run("f.apply(null, Array(10))"), Ok(JsValue::Number(10.0)));
|
||||
let e = realm.run("f.apply(null, big)").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{e:?}");
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{} > {heap_bytes}", realm.interp().heap.bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_after_default_parameters_checks_the_heap_before_its_scope_is_made() {
|
||||
// The default value fills the heap a little more each run, so at some count the room left
|
||||
// after it is smaller than the body's long variable names need. The call then ends with the
|
||||
// heap limit before the heap estimate passes it.
|
||||
let vars = (0..200).map(|i| format!("v{i:0>60}")).collect::<Vec<_>>().join(", ");
|
||||
let setup = format!(
|
||||
"var keep = []; function fill(k) {{ for (var i = 0; i < k; i++) keep.push(i); }} function f(a = fill(count)) {{ var {vars}; return 1; }} 0"
|
||||
);
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(&setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let heap_bytes = measure.interp().heap.bytes + (256 << 10);
|
||||
let mut stopped = 0;
|
||||
for count in (0..4000).step_by(20) {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
assert_eq!(realm.run(&setup), Ok(JsValue::Number(0.0)));
|
||||
match realm.run(&format!("var count = {count}; f()")) {
|
||||
Ok(v) => assert_eq!(v, JsValue::Number(1.0), "{count}"),
|
||||
Err(e) => {
|
||||
assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{count}: {e:?}");
|
||||
stopped += 1;
|
||||
}
|
||||
}
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{count}: {} > {heap_bytes}", realm.interp().heap.bytes);
|
||||
}
|
||||
assert!(stopped > 0, "no count reached the heap limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declarations_are_checked_after_the_let_and_const_names_take_their_room() {
|
||||
// The `let` names and the variables each fit in the heap, but not always together. Each run
|
||||
// stops for lack of fuel at a different point, before a collection could correct the
|
||||
// estimate, and the estimate is within the limit at every one of them: in a body after
|
||||
// default parameters, in a plain function's body and in eval code.
|
||||
let names = |prefix: &str| (0..100).map(|i| format!("{prefix}{i:0>60}")).collect::<Vec<_>>().join(", ");
|
||||
let (lets, vars) = (names("l"), names("v"));
|
||||
let bodies = [
|
||||
format!("function f(a = 0) {{ let {lets}; var {vars}; return 1; }} 0"),
|
||||
format!("function f() {{ let {lets}; var {vars}; return 1; }} 0"),
|
||||
format!("function f() {{ eval('let {lets}; var {vars};'); return 1; }} 0"),
|
||||
];
|
||||
for setup in &bodies {
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let base = measure.interp().heap.bytes;
|
||||
assert_eq!(measure.run("f()"), Ok(JsValue::Number(1.0)));
|
||||
let fuel = Limits::default().fuel - measure.interp().fuel;
|
||||
for extra in (0..100).map(|k| k * 2048) {
|
||||
let heap_bytes = base + extra;
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
if realm.run(setup).is_err() {
|
||||
continue;
|
||||
}
|
||||
// The declarations are made in the last 600 units of fuel, after any parsing, and
|
||||
// the estimate stays past the limit for as many units as variables made after it
|
||||
// passed, so every fourth stop there finds it.
|
||||
for f in (fuel.saturating_sub(600).max(1)..=fuel).step_by(4) {
|
||||
realm.interp().collect_garbage();
|
||||
realm.set_limits(Limits { heap_bytes, fuel: f, ..Limits::default() });
|
||||
let at = &setup[..24];
|
||||
match realm.run("f()") {
|
||||
Ok(v) => assert_eq!(v, JsValue::Number(1.0), "{at}: {heap_bytes}, {f}"),
|
||||
Err(e) => assert!(matches!(e.kind, RunErrorKind::Limit(LimitKind::Heap | LimitKind::Fuel)), "{at}: {heap_bytes}, {f}: {e:?}"),
|
||||
}
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{at}: {heap_bytes}, {f}: {}", realm.interp().heap.bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_arguments_object_is_checked_after_the_let_and_const_names_take_their_room() {
|
||||
// The `let` names and the `arguments` object of 1,000 arguments each fit in the heap, but not
|
||||
// always together. Each run stops for lack of fuel at a different point while the variables
|
||||
// after the object are made, before a collection could correct the estimate, and the
|
||||
// estimate is within the limit at every one of them.
|
||||
let names = |prefix: &str, n: usize| (0..n).map(|i| format!("{prefix}{i:0>60}")).collect::<Vec<_>>().join(", ");
|
||||
let (lets, vars) = (names("l", 300), names("v", 100));
|
||||
let zeros = vec!["0"; 1000].join(", ");
|
||||
let setup = format!("function f() {{ let {lets}; var {vars}; return arguments.length; }} function g() {{ return f({zeros}); }} 0");
|
||||
let call = "g()";
|
||||
let mut measure = Realm::with_options(es_options(), Limits::default());
|
||||
assert_eq!(measure.run(&setup), Ok(JsValue::Number(0.0)));
|
||||
measure.interp().collect_garbage();
|
||||
let base = measure.interp().heap.bytes;
|
||||
assert_eq!(measure.run(call), Ok(JsValue::Number(1000.0)));
|
||||
let fuel = Limits::default().fuel - measure.interp().fuel;
|
||||
let mut stopped = 0;
|
||||
for extra in (0..150).map(|k| k * 2048) {
|
||||
let heap_bytes = base + extra;
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes, ..Limits::default() });
|
||||
if realm.run(&setup).is_err() {
|
||||
continue;
|
||||
}
|
||||
// The variables are made before the body runs its 300 `let` declarations, which take
|
||||
// about 700 units of fuel, so every third stop in the last 800 units finds them.
|
||||
for f in (fuel.saturating_sub(800).max(1)..=fuel).step_by(3) {
|
||||
realm.interp().collect_garbage();
|
||||
realm.set_limits(Limits { heap_bytes, fuel: f, ..Limits::default() });
|
||||
match realm.run(call) {
|
||||
Ok(v) => assert_eq!(v, JsValue::Number(1000.0), "{heap_bytes}, {f}"),
|
||||
Err(e) => {
|
||||
assert!(matches!(e.kind, RunErrorKind::Limit(LimitKind::Heap | LimitKind::Fuel)), "{heap_bytes}, {f}: {e:?}");
|
||||
stopped += usize::from(e.kind == RunErrorKind::Limit(LimitKind::Heap));
|
||||
}
|
||||
}
|
||||
assert!(realm.interp().heap.bytes <= heap_bytes, "{heap_bytes}, {f}: {}", realm.interp().heap.bytes);
|
||||
}
|
||||
}
|
||||
assert!(stopped > 0, "no run reached the heap limit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_scopes_survive_collections_while_they_are_made() {
|
||||
// Heaps just big enough make the collector run while function bodies and blocks set up their
|
||||
// scopes; each run gives the right total or stops at the heap limit.
|
||||
let src = "var total = 0; \
|
||||
function f(a = 1, ...r) { let x = a + r.length; const y = 1; function g() { return x + y; } function h() { return g(); } var junk = [a, a, a]; return h(); } \
|
||||
function p(c) { let x = c; function q() { return x + arguments.length; } return q(); } \
|
||||
for (var i = 0; i < 300; i++) { { let b = i; function k() { return b; } function m() { return k(); } total += f(1, 2) + m() - i + p(1) - 1; } } total";
|
||||
let mut completed = 0;
|
||||
for kib in (16..400).step_by(2) {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { heap_bytes: kib << 10, ..Limits::default() });
|
||||
match realm.run(src) {
|
||||
Ok(v) => {
|
||||
assert_eq!(v, JsValue::Number(900.0), "{kib} KiB");
|
||||
completed += 1;
|
||||
}
|
||||
Err(e) => assert_eq!(e.kind, RunErrorKind::Limit(LimitKind::Heap), "{kib} KiB: {e:?}"),
|
||||
}
|
||||
}
|
||||
assert!(completed > 0);
|
||||
}
|
||||
|
||||
/// Runs `src` with a collection at every heap reservation, and checks that it gives `true`.
|
||||
fn truth_collecting(src: &str) {
|
||||
let mut realm = es();
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(true));
|
||||
let r = realm.run(src);
|
||||
crate::interp::COLLECT_ON_RESERVE.with(|c| c.set(false));
|
||||
assert_eq!(r, Ok(JsValue::Bool(true)), "{src}");
|
||||
assert!(realm.interp().heap.collections > 0, "{src}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_a_call_enters_with_stay_reachable_while_its_scopes_are_made() {
|
||||
truth_collecting("function C() { let x = 1; this.x = x; } var o = new C(); o.x === 1 && o instanceof C");
|
||||
truth_collecting("function f(a) { let x = 1; return arguments[1].v; } f(0, { v: 3 }) === 3");
|
||||
truth_collecting("function g() { 'use strict'; let x = 1; return this.v + x; } g.call({ v: 4 }) === 5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_eval_environments_stay_reachable_while_their_scopes_are_made() {
|
||||
truth_collecting("(function () { 'use strict'; var v = 5; return eval('let x = 1; var y = 2; x + y + v'); })() === 8");
|
||||
truth_collecting("(0, eval)(\"'use strict'; let x = 1; var y = 2; x + y\") === 3");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_scopes_survive_a_collection_at_each_reservation() {
|
||||
// The sweep below makes collections fall where the heap size puts them; this one runs one at
|
||||
// every reservation, so every scope is made across a collection.
|
||||
truth_collecting(
|
||||
"var total = 0; \
|
||||
function f(a = 1, ...r) { let x = a + r.length; const y = 1; function g() { return x + y; } function h() { return g(); } return h(); } \
|
||||
for (var i = 0; i < 20; i++) { { let b = i; function k() { return b; } total += f(1, 2) + k() - i; } } total === 60",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nested_arrows_and_templates_stay_within_the_depth_limit() {
|
||||
let deep = format!("{}0", "x => ".repeat(400));
|
||||
let e = es().run(&deep).unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
|
||||
let deep = format!("{}1{}", "`${".repeat(300), "}`".repeat(300));
|
||||
let e = es().run(&deep).unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
|
||||
assert_eq!(string(&format!("{}1{}", "`${".repeat(50), "}`".repeat(50))), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn for_each_takes_let_and_const_with_e4x() {
|
||||
let mut realm = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default());
|
||||
let src = "var fs = []; for each (let v in [1, 2]) { fs.push(() => v); } \
|
||||
var s = 0; for each (const w in { a: 3, b: 4 }) { s += w; } \
|
||||
fs[0]() + fs[1]() + s === 10 && typeof v === 'undefined'";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::Bool(true)));
|
||||
let e = Realm::with_options(Options { e4x: true, ..es_options() }, Limits::default()).run("for each (let a = 1 in []) {}").unwrap_err();
|
||||
assert_eq!(e.kind, RunErrorKind::Syntax, "{e:?}");
|
||||
}
|
||||
|
||||
// ---- the language mode ----
|
||||
|
||||
#[test]
|
||||
fn without_the_option_the_new_forms_are_syntax_errors() {
|
||||
for src in ["let x = 1; x", "const c = 1;", "var f = x => x;", "`t`", "function f(a = 1) {}", "function f(...r) {}", "f(...a)", "[...a]"] {
|
||||
let r = Realm::new().run(src);
|
||||
assert!(matches!(r, Err(RunError { kind: RunErrorKind::Syntax, .. })), "{src}: {r:?}");
|
||||
}
|
||||
// `let` stays a name outside strict mode code.
|
||||
assert_eq!(Realm::new().run("var let = 1; let"), Ok(JsValue::Number(1.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_made_at_run_time_reads_the_realm_s_language() {
|
||||
truth("eval('let a = 1; `${a}`') === '1'");
|
||||
truth("new Function('a = 2', 'return a')() === 2");
|
||||
truth("Function('...r', 'return r.length')(1, 2) === 2");
|
||||
let legacy = Realm::new().run("eval('let a = 1;')");
|
||||
assert!(matches!(&legacy, Err(RunError { kind: RunErrorKind::Thrown, message, .. }) if message.starts_with("SyntaxError")), "{legacy:?}");
|
||||
}
|
||||
|
||||
/// Starts `src` with the option `start`, turns it to `!start` once the run has paused, and gives
|
||||
/// the run's value.
|
||||
fn run_switching_language(src: &str, start: bool) -> Result<JsValue, RunError> {
|
||||
let mut realm = Realm::with_options(Options { es2015: start, ..Options::default() }, Limits::default());
|
||||
realm.start(src)?;
|
||||
assert_eq!(realm.advance(20)?, crate::Progress::Paused);
|
||||
realm.set_es2015(!start);
|
||||
loop {
|
||||
if let crate::Progress::Done(v) = realm.advance(1000)? {
|
||||
assert_eq!(realm.interp().options.es2015, !start, "the new language applies once the run ends");
|
||||
return Ok(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_keeps_its_language_for_the_code_it_evaluates() {
|
||||
let src = "for (var i = 0; i < 200; i++) {} ";
|
||||
assert_eq!(run_switching_language(&format!("{src} eval('let a = 1; a')"), true), Ok(JsValue::Number(1.0)));
|
||||
let legacy = run_switching_language(&format!("{src} var r; try {{ eval('let a = 1; a'); }} catch (e) {{ r = e.name; }} r"), false);
|
||||
assert_eq!(legacy, Ok(JsValue::String("SyntaxError".into())));
|
||||
}
|
||||
|
||||
// ---- robustness ----
|
||||
|
||||
const FRAGMENTS: &[&str] = &[
|
||||
"let ",
|
||||
"const ",
|
||||
"var ",
|
||||
"x",
|
||||
"y",
|
||||
"=",
|
||||
"=>",
|
||||
"(",
|
||||
")",
|
||||
"{",
|
||||
"}",
|
||||
"[",
|
||||
"]",
|
||||
"...",
|
||||
",",
|
||||
";",
|
||||
"`",
|
||||
"${",
|
||||
"a",
|
||||
"1",
|
||||
"+",
|
||||
"function ",
|
||||
"f",
|
||||
"return ",
|
||||
"for (",
|
||||
" in ",
|
||||
"if (",
|
||||
"this",
|
||||
"arguments",
|
||||
"new ",
|
||||
"\n",
|
||||
"'use strict';",
|
||||
".",
|
||||
"?",
|
||||
":",
|
||||
"\\",
|
||||
"switch (",
|
||||
"case ",
|
||||
"default:",
|
||||
"break;",
|
||||
];
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig::with_cases(256))]
|
||||
|
||||
#[test]
|
||||
fn arbitrary_es2015_fragment_programs_never_panic(parts in proptest::collection::vec(0..FRAGMENTS.len(), 0..60)) {
|
||||
let src: String = parts.iter().map(|&i| FRAGMENTS[i]).collect();
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
|
||||
if let Err(e) = realm.run(&src) {
|
||||
prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arbitrary_es2015_text_never_panics(src in "[`$\\{\\}=>.()a-c1 ;,\\[\\]\\\\\n]{0,80}") {
|
||||
let mut realm = Realm::with_options(es_options(), Limits { fuel: 20_000, heap_bytes: 1 << 20, frames: 200, reentry: 8 });
|
||||
if let Err(e) = realm.run(&src) {
|
||||
prop_assert!(e.kind != RunErrorKind::Internal, "{src:?}: {e:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -348,6 +348,26 @@ pub(crate) struct Binding {
|
||||
pub(crate) value: Value,
|
||||
pub(crate) mutable: bool,
|
||||
pub(crate) deletable: bool,
|
||||
/// A `let`, `const` or parameter binding not yet initialized: reading or writing it is a
|
||||
/// `ReferenceError` (its temporal dead zone).
|
||||
pub(crate) uninitialized: bool,
|
||||
/// A `const` binding: writing it is a `TypeError`, in strict mode code or not.
|
||||
pub(crate) constant: bool,
|
||||
/// A `let` or `const` binding, or a function declared in a block: a `var` that eval code
|
||||
/// declares cannot take its name.
|
||||
pub(crate) lexical: bool,
|
||||
}
|
||||
|
||||
impl Binding {
|
||||
/// An initialized binding.
|
||||
pub(crate) fn new(value: Value, mutable: bool, deletable: bool) -> Self {
|
||||
Self { value, mutable, deletable, uninitialized: false, constant: false, lexical: false }
|
||||
}
|
||||
|
||||
/// A `let` (or with `constant`, a `const`) binding not yet initialized.
|
||||
pub(crate) fn lexical(constant: bool) -> Self {
|
||||
Self { value: Value::Undefined, mutable: !constant, deletable: false, uninitialized: true, constant, lexical: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// An environment record (section 10.2.1) with its outer environment.
|
||||
@@ -601,7 +621,9 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
+ code.functions.len()
|
||||
+ code.params.len()
|
||||
+ code.vars.len()
|
||||
+ 2 * code.fun_decls.len();
|
||||
+ 2 * code.fun_decls.len()
|
||||
+ code.scopes.iter().map(|s| 2 + s.lets.len() + 2 * s.funcs.len()).sum::<usize>()
|
||||
+ code.templates.iter().map(|t| 2 + t.cooked.len() + t.raw.len()).sum::<usize>();
|
||||
let tables = code.finally_tables.iter().map(|t| 24 + 4 * t.len()).sum::<usize>();
|
||||
strings.bytes += CODE_BYTES
|
||||
+ size_of::<Op>() * code.ops.len()
|
||||
@@ -618,9 +640,15 @@ fn mark_code(code: &Code, strings: &mut StringSizes) {
|
||||
strings.add(flags);
|
||||
}
|
||||
let keys = code.names.iter().chain(&code.params).chain(&code.vars).chain(code.fun_decls.iter().map(|(k, _)| k));
|
||||
for k in keys.chain(&code.self_name).chain(&code.decl_name) {
|
||||
for k in keys.chain(&code.self_name).chain(&code.decl_name).chain(&code.rest) {
|
||||
strings.add_key(k);
|
||||
}
|
||||
for scope in &code.scopes {
|
||||
scope.lets.iter().map(|(k, _)| k).chain(scope.funcs.iter().map(|(k, _)| k)).for_each(|k| strings.add_key(k));
|
||||
}
|
||||
for t in &code.templates {
|
||||
t.cooked.iter().chain(&t.raw).for_each(|s| strings.add(s));
|
||||
}
|
||||
stack.extend(code.functions.iter().map(|f| &**f));
|
||||
}
|
||||
}
|
||||
|
||||
+793
-52
File diff suppressed because it is too large
Load Diff
@@ -975,6 +975,14 @@ fn code(ops: Vec<Op>) -> Code {
|
||||
uses_arguments: false,
|
||||
source,
|
||||
span: (0, 0),
|
||||
scopes: Vec::new(),
|
||||
top_scope: None,
|
||||
templates: Vec::new(),
|
||||
rest: None,
|
||||
length: 0,
|
||||
arrow: false,
|
||||
uses_this: false,
|
||||
param_init: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+96
-1
@@ -30,6 +30,8 @@ const BACKSLASH: u32 = b'\\' as u32;
|
||||
const SLASH: u32 = b'/' as u32;
|
||||
const STAR: u32 = b'*' as u32;
|
||||
const DOT: u32 = b'.' as u32;
|
||||
const BACKTICK: u32 = b'`' as u32;
|
||||
const DOLLAR: u32 = b'$' as u32;
|
||||
const CR: u32 = 0x0D;
|
||||
const LF: u32 = 0x0A;
|
||||
|
||||
@@ -49,13 +51,15 @@ pub struct Lexer<'s> {
|
||||
max_depth: usize,
|
||||
/// Read the E4X punctuators `..`, `::` and `@`.
|
||||
e4x: bool,
|
||||
/// Read `=>`, `...` and template literals.
|
||||
es2015: bool,
|
||||
}
|
||||
|
||||
impl<'s> Lexer<'s> {
|
||||
/// A lexer of `src`. `preprocessor_lines` turns on the reading of preprocessor lines;
|
||||
/// `max_depth` limits how deeply a regular expression literal's groups may nest.
|
||||
pub fn new(src: &'s [u16], preprocessor_lines: bool, max_depth: usize) -> Self {
|
||||
Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false }
|
||||
Self { src, pos: 0, line: 1, line_start: 0, blank_line: true, preprocessor_lines, max_depth, e4x: false, es2015: false }
|
||||
}
|
||||
|
||||
/// The same lexer, reading the E4X punctuators when `e4x` is true.
|
||||
@@ -64,6 +68,12 @@ impl<'s> Lexer<'s> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The same lexer, reading `=>`, `...` and template literals when `es2015` is true.
|
||||
pub fn with_es2015(mut self, es2015: bool) -> Self {
|
||||
self.es2015 = es2015;
|
||||
self
|
||||
}
|
||||
|
||||
/// Moves to source offset `pos`, at the given line and column (both from 1), after the parser
|
||||
/// has read an XML literal up to there.
|
||||
pub(crate) fn seek(&mut self, pos: usize, line: u32, column: u32) {
|
||||
@@ -149,6 +159,9 @@ impl<'s> Lexer<'s> {
|
||||
self.string(start, line, column)?
|
||||
} else if c == SLASH && goal == Goal::RegExp {
|
||||
self.regexp(start, line, column)?
|
||||
} else if c == BACKTICK && self.es2015 {
|
||||
self.pos += 1;
|
||||
self.template(start, line, column)?
|
||||
} else {
|
||||
let punct = self.punct().ok_or_else(|| self.error_at(start, unexpected_character(c)))?;
|
||||
self.token(TokenKind::Punct(punct), start, line, column, false)
|
||||
@@ -172,6 +185,85 @@ impl<'s> Lexer<'s> {
|
||||
Ok(regexp)
|
||||
}
|
||||
|
||||
/// Reads the token `token`, a `}` that ends a template literal's substitution, again as the
|
||||
/// template's next piece.
|
||||
pub(crate) fn rescan_template(&mut self, token: &Token) -> Result<Token, SyntaxError> {
|
||||
let start = usize::try_from(token.span.start).unwrap_or(usize::MAX);
|
||||
self.pos = start + 1;
|
||||
self.line = token.line;
|
||||
self.line_start = start.saturating_sub(usize::try_from(token.column.saturating_sub(1)).unwrap_or(0));
|
||||
self.blank_line = false;
|
||||
let mut piece = self.template(start, token.line, token.column)?;
|
||||
// A piece continued over a line ends on a new line, but not at its start.
|
||||
self.blank_line = false;
|
||||
piece.newline_before = token.newline_before;
|
||||
Ok(piece)
|
||||
}
|
||||
|
||||
/// Reads a template literal's characters after its backtick or `}` up to `${` or the closing
|
||||
/// backtick (ECMA-262 2015 sections 11.8.6 and 11.8.6.1): the cooked text, with escapes read
|
||||
/// as a string literal's are except that octal escapes are errors, and the raw text as written,
|
||||
/// with each line terminator sequence (CR LF, CR or LF) read as LF in both, and a line
|
||||
/// continuation left out of the cooked text.
|
||||
fn template(&mut self, start: usize, line: u32, column: u32) -> Result<Token, SyntaxError> {
|
||||
let at = (start, line, column);
|
||||
let mut cooked = Vec::new();
|
||||
let mut raw = Vec::new();
|
||||
let tail = loop {
|
||||
match self.peek() {
|
||||
None => return Err(Self::error_from(at, "unterminated template literal")),
|
||||
Some(BACKTICK) => {
|
||||
self.pos += 1;
|
||||
break true;
|
||||
}
|
||||
Some(DOLLAR) if self.peek_at(1) == Some(u32::from(b'{')) => {
|
||||
self.pos += 2;
|
||||
break false;
|
||||
}
|
||||
Some(BACKSLASH) => {
|
||||
let begin = self.pos;
|
||||
let begin_line = self.line;
|
||||
self.template_escape(&mut cooked)?;
|
||||
// The raw text keeps the escape as written, its line terminator read as LF.
|
||||
if self.line != begin_line {
|
||||
let terminator = self.unit(begin + 1).unwrap_or(LF);
|
||||
raw.push(BACKSLASH as u16);
|
||||
raw.push(if terminator == CR { LF as u16 } else { terminator as u16 });
|
||||
} else {
|
||||
raw.extend_from_slice(self.src.get(begin..self.pos).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
Some(c) if is_line_terminator(c) => {
|
||||
let unit = if c == CR { LF as u16 } else { c as u16 };
|
||||
self.line_terminator();
|
||||
cooked.push(unit);
|
||||
raw.push(unit);
|
||||
}
|
||||
Some(c) => {
|
||||
cooked.push(c as u16);
|
||||
raw.push(c as u16);
|
||||
self.pos += 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
Ok(self.token(TokenKind::Template { cooked, raw, tail }, start, line, column, false))
|
||||
}
|
||||
|
||||
/// Reads an escape in a template literal into `cooked`. A line continuation adds nothing; an
|
||||
/// octal escape (`\1`, `\00`), `\8` and `\9` are errors, as are malformed `\x` and `\u` escapes.
|
||||
fn template_escape(&mut self, cooked: &mut Vec<u16>) -> Result<(), SyntaxError> {
|
||||
let at = self.pos;
|
||||
match self.peek_at(1).and_then(char::from_u32) {
|
||||
Some('0') if !self.peek_at(2).is_some_and(is_decimal_digit) => {
|
||||
self.pos += 2;
|
||||
cooked.push(0);
|
||||
Ok(())
|
||||
}
|
||||
Some('0'..='9') => Err(self.error_at(at, "octal escape sequences are not allowed in template literals")),
|
||||
_ => self.string_escape(cooked).map(drop),
|
||||
}
|
||||
}
|
||||
|
||||
fn token(&self, kind: TokenKind, start: usize, line: u32, column: u32, newline_before: bool) -> Token {
|
||||
Token {
|
||||
kind,
|
||||
@@ -598,6 +690,9 @@ impl<'s> Lexer<'s> {
|
||||
if !self.e4x && matches!(punct, Punct::DotDot | Punct::ColonColon | Punct::At) {
|
||||
continue;
|
||||
}
|
||||
if !self.es2015 && matches!(punct, Punct::Arrow | Punct::Ellipsis) {
|
||||
continue;
|
||||
}
|
||||
let bytes = spelling.as_bytes();
|
||||
if rest.len() >= bytes.len() && rest.iter().zip(bytes).all(|(&u, &b)| u == u16::from(b)) {
|
||||
self.pos += bytes.len();
|
||||
|
||||
+21
-3
@@ -46,6 +46,17 @@
|
||||
//! those of ECMAScript 5.1 above. XML trees live in the heap, and parsing, copying, comparing and
|
||||
//! serializing them, and evaluating XPath on them, use no native recursion and take fuel for each
|
||||
//! node.
|
||||
//!
|
||||
//! With [`Options::es2015`], the parser and the realm also read and run a part of ECMAScript 2015
|
||||
//! (<https://262.ecma-international.org/6.0/>): block-scoped `let` and `const` declarations with
|
||||
//! their temporal dead zone (section 13.3.1), a new `let` binding for each iteration of a `for`
|
||||
//! loop, function declarations in blocks scoped to the block (Annex B.3.3 in sloppy code), arrow
|
||||
//! functions (section 14.2), template literals and tagged templates (sections 12.2.9 and
|
||||
//! 12.3.7), default and rest parameters (section 14.1) and spread in array literals, calls and
|
||||
//! `new` (sections 12.2.5 and 12.3.6.1). Spread reads arrays by index, reading the length again
|
||||
//! before each element, strings and `String` objects by code point, and objects with a `length` by
|
||||
//! index; other values are a `TypeError`. Destructuring, `for … of`, classes,
|
||||
//! generators and modules stay syntax errors.
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod ast;
|
||||
@@ -76,8 +87,8 @@ mod xml_builtins;
|
||||
mod xpath;
|
||||
|
||||
pub use ast::{
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LogicalOp, Name, Program, Property,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionId, FunctionKind, LexKind, LogicalOp, Name, Program,
|
||||
Property, PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl, XmlNamePart, XmlPart, XmlQualifier,
|
||||
};
|
||||
pub use builtins::extensions::Localization;
|
||||
pub use error::{SyntaxError, TOO_DEEP, TOO_LONG};
|
||||
@@ -101,11 +112,16 @@ pub struct Options {
|
||||
pub max_source_units: usize,
|
||||
/// Read and run E4X (ECMA-357). Off, XML syntax is an error and a realm has no XML built-ins.
|
||||
pub e4x: bool,
|
||||
/// Read and run the ECMAScript 2015 forms this engine has: `let` and `const`, arrow functions,
|
||||
/// template literals (tagged ones included), default and rest parameters, and spread in array
|
||||
/// literals, calls and `new`. Off, they are syntax errors and the language is ES5.1's. Code a
|
||||
/// script evaluates at run time (`eval`, `Function`) is read the way the realm reads scripts.
|
||||
pub es2015: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false }
|
||||
Self { strict: false, preprocessor_lines: false, max_depth: DEFAULT_MAX_DEPTH, max_source_units: 64 << 20, e4x: false, es2015: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,6 +220,8 @@ impl LineTable {
|
||||
#[cfg(test)]
|
||||
mod builtins_tests;
|
||||
#[cfg(test)]
|
||||
mod es2015_tests;
|
||||
#[cfg(test)]
|
||||
mod extension_tests;
|
||||
#[cfg(test)]
|
||||
mod host_tests;
|
||||
|
||||
+467
-40
@@ -13,8 +13,8 @@ use std::collections::{HashMap, HashSet};
|
||||
|
||||
use crate::LineTable;
|
||||
use crate::ast::{
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LogicalOp, Name, Program, Property,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, UnaryOp, UpdateOp, VarDecl,
|
||||
AssignOp, Ast, BinaryOp, CatchClause, Expr, ExprId, ForInTarget, ForInit, Function, FunctionKind, LexKind, LogicalOp, Name, Program, Property,
|
||||
PropertyKey, PropertyValue, Stmt, StmtId, SwitchCase, TemplatePiece, UnaryOp, UpdateOp, VarDecl,
|
||||
};
|
||||
use crate::error::{SyntaxError, TOO_DEEP};
|
||||
use crate::lexer::{Goal, Lexer};
|
||||
@@ -34,8 +34,32 @@ struct Context {
|
||||
loops: u32,
|
||||
/// Iteration and `switch` statements open in the current function.
|
||||
breakables: u32,
|
||||
/// The current function body's directive prologue has a `"use strict"` directive.
|
||||
use_strict: bool,
|
||||
}
|
||||
|
||||
/// The names declared in a scope, for the early errors of ECMA-262 2015 about redeclarations
|
||||
/// (sections 13.2.1, 13.12.1, 13.15.1, 14.1.2 and 15.1.1). Kept only with
|
||||
/// [`crate::Options::es2015`].
|
||||
#[derive(Default)]
|
||||
struct Scope {
|
||||
/// The `let`, `const` and (in a block) function declarations, each with whether it is a
|
||||
/// function declaration.
|
||||
lexical: HashMap<String, bool>,
|
||||
/// The `var` names declared in this scope or in a block inside it.
|
||||
vars: HashSet<String>,
|
||||
/// Names a lexical declaration here must not take: a function's parameters, or a catch
|
||||
/// clause's parameter.
|
||||
params: HashSet<String>,
|
||||
/// A function body or the script: `var` names go no further out, and function declarations
|
||||
/// here are var-scoped.
|
||||
function: bool,
|
||||
}
|
||||
|
||||
/// The parameters of a function as they are read: plain names, each name's default value, and a
|
||||
/// rest parameter.
|
||||
type Params = (Vec<Name>, Vec<Option<ExprId>>, Option<Name>);
|
||||
|
||||
/// A binary operator, with the logical ones apart.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum BinKind {
|
||||
@@ -73,11 +97,15 @@ pub(crate) struct Parser<'s> {
|
||||
in_list: bool,
|
||||
/// Read E4X syntax.
|
||||
e4x: bool,
|
||||
/// Read the ECMAScript 2015 forms of [`crate::Options::es2015`].
|
||||
es2015: bool,
|
||||
/// The scopes open around the current token, outermost first (only with `es2015`).
|
||||
scopes: Vec<Scope>,
|
||||
}
|
||||
|
||||
impl<'s> Parser<'s> {
|
||||
pub(crate) fn new(src: &'s [u16], options: &crate::Options, keep_tokens: bool) -> Result<Self> {
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x);
|
||||
let lex = Lexer::new(src, options.preprocessor_lines, options.max_depth).with_e4x(options.e4x).with_es2015(options.es2015);
|
||||
let placeholder =
|
||||
Token { kind: TokenKind::Eof, span: Span::default(), line: 1, column: 1, newline_before: false, escaped: false, legacy_octal: false };
|
||||
let mut parser = Self {
|
||||
@@ -95,6 +123,8 @@ impl<'s> Parser<'s> {
|
||||
function_allowed: false,
|
||||
in_list: false,
|
||||
e4x: options.e4x,
|
||||
es2015: options.es2015,
|
||||
scopes: if options.es2015 { vec![Scope { function: true, ..Scope::default() }] } else { Vec::new() },
|
||||
};
|
||||
parser.tok = parser.next_significant()?;
|
||||
Ok(parser)
|
||||
@@ -108,7 +138,7 @@ impl<'s> Parser<'s> {
|
||||
if let Some(tokens) = &mut self.tokens {
|
||||
tokens.push(self.tok.clone());
|
||||
}
|
||||
let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines };
|
||||
let program = Program { ast: self.ast, body, strict: self.ctx.strict, directives: self.directives, lines: self.lines, es2015: self.es2015 };
|
||||
Ok((program, self.tokens.unwrap_or_default()))
|
||||
}
|
||||
|
||||
@@ -254,6 +284,122 @@ impl<'s> Parser<'s> {
|
||||
Ok(Name { name, span: token.span })
|
||||
}
|
||||
|
||||
// ---- scopes (ECMAScript 2015) ----
|
||||
|
||||
/// Opens a scope; `params` are the names a lexical declaration in it must not take.
|
||||
fn push_scope(&mut self, function: bool, params: impl IntoIterator<Item = String>) {
|
||||
if self.es2015 {
|
||||
self.scopes.push(Scope { function, params: params.into_iter().collect(), ..Scope::default() });
|
||||
}
|
||||
}
|
||||
|
||||
fn pop_scope(&mut self) {
|
||||
if self.es2015 {
|
||||
self.scopes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
fn redeclared(&self, name: &Name) -> SyntaxError {
|
||||
self.error_at_offset(name.span.start, format!("redeclaration of '{}'", name.name))
|
||||
}
|
||||
|
||||
/// Declares a `let`, a `const` or (`function`) a function declaration in a block, in the
|
||||
/// innermost scope. A name may be declared there once, and not as a `var` or a parameter too;
|
||||
/// outside strict mode code a function declaration may repeat another (Annex B.3.3.4).
|
||||
fn declare_lexical(&mut self, name: &Name, function: bool) -> Result<()> {
|
||||
let strict = self.ctx.strict;
|
||||
let Some(scope) = self.scopes.last_mut() else { return Ok(()) };
|
||||
let clash = match scope.lexical.get(&name.name) {
|
||||
Some(&was_function) => !(function && was_function && !strict),
|
||||
None => false,
|
||||
} || scope.vars.contains(&name.name)
|
||||
|| scope.params.contains(&name.name);
|
||||
if clash {
|
||||
return Err(self.redeclared(name));
|
||||
}
|
||||
scope.lexical.insert(name.name.clone(), function);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Declares a `var` name: in each scope out to the function's, where no lexical declaration
|
||||
/// may have it.
|
||||
fn declare_var(&mut self, name: &Name) -> Result<()> {
|
||||
let mut clash = false;
|
||||
for scope in self.scopes.iter_mut().rev() {
|
||||
if scope.lexical.contains_key(&name.name) {
|
||||
clash = true;
|
||||
break;
|
||||
}
|
||||
scope.vars.insert(name.name.clone());
|
||||
if scope.function {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if clash { Err(self.redeclared(name)) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// Declares a function declaration that stands in a statement list: var-scoped in a function
|
||||
/// body or the script, lexical in a block.
|
||||
fn declare_function(&mut self, id: crate::ast::FunctionId) -> Result<()> {
|
||||
let Some(name) = self.ast.function(id).and_then(|f| f.name.clone()) else { return Ok(()) };
|
||||
match self.scopes.last_mut() {
|
||||
Some(scope) if scope.function => {
|
||||
if scope.lexical.contains_key(&name.name) {
|
||||
return Err(self.redeclared(&name));
|
||||
}
|
||||
scope.vars.insert(name.name);
|
||||
Ok(())
|
||||
}
|
||||
Some(_) => self.declare_lexical(&name, true),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The current token starts a `let` or `const` declaration in a statement list: `const`, or a
|
||||
/// `let` written without escapes and followed by a name, `[` or `{` (ECMA-262 2015 section
|
||||
/// 13.3.1; a `let` followed by anything else is an identifier outside strict mode code).
|
||||
fn at_lexical_declaration(&self) -> Option<LexKind> {
|
||||
if !self.es2015 {
|
||||
return None;
|
||||
}
|
||||
if self.at_keyword(Keyword::Const) {
|
||||
return Some(LexKind::Const);
|
||||
}
|
||||
if self.tok.ident() == Some("let") && !self.tok.escaped {
|
||||
let next = self.peek()?;
|
||||
if matches!(next.kind, TokenKind::Ident(_)) || next.is_punct(Punct::LBracket) || next.is_punct(Punct::LBrace) {
|
||||
return Some(LexKind::Let);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// `let` or `const` declarations after the keyword: each name declared in the innermost scope.
|
||||
/// `no_in` leaves `in` to a `for (… in …)` around them, where a `const` may go without an
|
||||
/// initializer.
|
||||
fn parse_lexical_decls(&mut self, kind: LexKind, no_in: bool) -> Result<Vec<VarDecl>> {
|
||||
let mut decls = Vec::new();
|
||||
loop {
|
||||
if self.at(Punct::LBracket) || self.at(Punct::LBrace) {
|
||||
return Err(self.error_at_token(&self.tok, "destructuring declarations are not supported"));
|
||||
}
|
||||
let name = self.binding_identifier()?;
|
||||
if name.name == "let" {
|
||||
return Err(self.error_at_offset(name.span.start, "'let' cannot be the name of a let or const declaration"));
|
||||
}
|
||||
self.declare_lexical(&name, false)?;
|
||||
let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
|
||||
let in_head = no_in && self.at_keyword(Keyword::In) && decls.is_empty();
|
||||
if kind == LexKind::Const && init.is_none() && !in_head {
|
||||
return Err(self.error_at_offset(name.span.start, format!("const '{}' needs an initializer", name.name)));
|
||||
}
|
||||
decls.push(VarDecl { name, init });
|
||||
if !self.eat(Punct::Comma)? {
|
||||
return Ok(decls);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- program and function bodies ----
|
||||
|
||||
/// Reads source elements up to `}` (in a function body) or the end of the source, reading the
|
||||
@@ -275,6 +421,7 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
if self.is_use_strict(&first) {
|
||||
self.ctx.strict = true;
|
||||
self.ctx.use_strict = true;
|
||||
if let Some(octal) = &octal {
|
||||
return Err(self.error_at_token(octal, "octal escape sequences are not allowed in strict mode"));
|
||||
}
|
||||
@@ -314,7 +461,20 @@ impl<'s> Parser<'s> {
|
||||
self.enter()?;
|
||||
let result = self.parse_function_declaration();
|
||||
self.leave();
|
||||
return result;
|
||||
let id = result?;
|
||||
if let Some(Stmt::FunctionDecl(fid)) = self.ast.stmt(id) {
|
||||
self.declare_function(*fid)?;
|
||||
}
|
||||
return Ok(id);
|
||||
}
|
||||
if let Some(kind) = self.at_lexical_declaration() {
|
||||
let start = self.bump()?.span;
|
||||
self.enter()?;
|
||||
let decls = self.parse_lexical_decls(kind, false);
|
||||
self.leave();
|
||||
let decls = decls?;
|
||||
self.semicolon()?;
|
||||
return Ok(self.ast.push_stmt(Stmt::Lexical(kind, decls), self.span_from(start)));
|
||||
}
|
||||
self.in_list = true;
|
||||
self.parse_statement()
|
||||
@@ -407,7 +567,22 @@ impl<'s> Parser<'s> {
|
||||
|
||||
/// `{ … }`: its statements.
|
||||
fn parse_block(&mut self) -> Result<Vec<StmtId>> {
|
||||
self.parse_block_with(None)
|
||||
}
|
||||
|
||||
/// `{ … }`, a scope of its own; `param` is a catch clause's parameter, which a lexical
|
||||
/// declaration in the block must not take.
|
||||
fn parse_block_with(&mut self, param: Option<&str>) -> Result<Vec<StmtId>> {
|
||||
self.expect(Punct::LBrace)?;
|
||||
self.push_scope(false, param.map(str::to_string));
|
||||
let body = self.block_items();
|
||||
self.pop_scope();
|
||||
let body = body?;
|
||||
self.bump()?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn block_items(&mut self) -> Result<Vec<StmtId>> {
|
||||
let mut body = Vec::new();
|
||||
while !self.at(Punct::RBrace) {
|
||||
if self.tok.kind == TokenKind::Eof {
|
||||
@@ -415,7 +590,6 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
body.push(self.parse_statement_item()?);
|
||||
}
|
||||
self.bump()?;
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
@@ -424,6 +598,7 @@ impl<'s> Parser<'s> {
|
||||
let mut decls = Vec::new();
|
||||
loop {
|
||||
let name = self.binding_identifier()?;
|
||||
self.declare_var(&name)?;
|
||||
let init = if self.eat(Punct::Eq)? { Some(self.parse_assignment(no_in)?) } else { None };
|
||||
decls.push(VarDecl { name, init });
|
||||
if !self.eat(Punct::Comma)? {
|
||||
@@ -502,6 +677,13 @@ impl<'s> Parser<'s> {
|
||||
if each {
|
||||
return self.parse_for_each(start);
|
||||
}
|
||||
if let Some(kind) = self.at_lexical_declaration() {
|
||||
self.bump()?;
|
||||
self.push_scope(false, std::iter::empty());
|
||||
let result = self.parse_for_lexical(kind, start);
|
||||
self.pop_scope();
|
||||
return result;
|
||||
}
|
||||
let init = if self.at(Punct::Semicolon) {
|
||||
None
|
||||
} else if self.at_keyword(Keyword::Var) {
|
||||
@@ -525,6 +707,11 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
Some(ForInit::Expr(expr))
|
||||
};
|
||||
self.parse_for_rest(init, start)
|
||||
}
|
||||
|
||||
/// The rest of `for (init; test; update) body`, from the first `;`.
|
||||
fn parse_for_rest(&mut self, init: Option<ForInit>, start: Span) -> Result<StmtId> {
|
||||
self.expect(Punct::Semicolon)?;
|
||||
let test = if self.at(Punct::Semicolon) { None } else { Some(self.parse_expression(false)?) };
|
||||
self.expect(Punct::Semicolon)?;
|
||||
@@ -534,6 +721,19 @@ impl<'s> Parser<'s> {
|
||||
Ok(self.ast.push_stmt(Stmt::For { init, test, update, body }, self.span_from(start)))
|
||||
}
|
||||
|
||||
/// `for (let …` or `for (const …`, after the keyword, in the loop's own scope.
|
||||
fn parse_for_lexical(&mut self, kind: LexKind, start: Span) -> Result<StmtId> {
|
||||
let mut decls = self.parse_lexical_decls(kind, true)?;
|
||||
if decls.len() == 1 && self.at_keyword(Keyword::In) {
|
||||
let Some(decl) = decls.pop() else { return Err(self.unexpected()) };
|
||||
if decl.init.is_some() {
|
||||
return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
|
||||
}
|
||||
return self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, false);
|
||||
}
|
||||
self.parse_for_rest(Some(ForInit::Lexical(kind, decls)), start)
|
||||
}
|
||||
|
||||
/// The rest of `for (target in object) body`, from `in`.
|
||||
fn parse_for_in(&mut self, target: ForInTarget, start: Span, each: bool) -> Result<StmtId> {
|
||||
self.expect_keyword(Keyword::In)?;
|
||||
@@ -553,11 +753,31 @@ impl<'s> Parser<'s> {
|
||||
};
|
||||
return self.parse_for_in(ForInTarget::Var(decl), start, true);
|
||||
}
|
||||
if let Some(kind) = self.at_lexical_declaration() {
|
||||
self.bump()?;
|
||||
self.push_scope(false, std::iter::empty());
|
||||
let result = self.parse_for_each_lexical(kind, start);
|
||||
self.pop_scope();
|
||||
return result;
|
||||
}
|
||||
let expr = self.parse_expression(true)?;
|
||||
self.check_target(expr, "invalid left-hand side in for each loop")?;
|
||||
self.parse_for_in(ForInTarget::Expr(expr), start, true)
|
||||
}
|
||||
|
||||
/// `for each (let x in object) body` or `for each (const x in object) body`, after `let` or
|
||||
/// `const`.
|
||||
fn parse_for_each_lexical(&mut self, kind: LexKind, start: Span) -> Result<StmtId> {
|
||||
let mut decls = self.parse_lexical_decls(kind, true)?;
|
||||
let (Some(decl), true) = (decls.pop(), decls.is_empty()) else {
|
||||
return Err(self.error_at_token(&self.tok, "for each takes one variable"));
|
||||
};
|
||||
if decl.init.is_some() {
|
||||
return Err(self.error_at_token(&self.tok, "a for-in variable declared with let or const cannot have an initializer"));
|
||||
}
|
||||
self.parse_for_in(ForInTarget::Lexical(kind, decl.name), start, true)
|
||||
}
|
||||
|
||||
/// `break` or `continue`, with an optional label on the same line, which must name a label
|
||||
/// around it in the same function (an iteration statement's, for `continue`).
|
||||
fn parse_jump(&mut self, is_break: bool, start: Span) -> Result<StmtId> {
|
||||
@@ -621,7 +841,9 @@ impl<'s> Parser<'s> {
|
||||
self.expect(Punct::RParen)?;
|
||||
self.expect(Punct::LBrace)?;
|
||||
self.ctx.breakables += 1;
|
||||
self.push_scope(false, std::iter::empty());
|
||||
let cases = self.parse_cases();
|
||||
self.pop_scope();
|
||||
self.ctx.breakables -= 1;
|
||||
let cases = cases?;
|
||||
Ok(self.ast.push_stmt(Stmt::Switch { discriminant, cases }, self.span_from(start)))
|
||||
@@ -678,9 +900,13 @@ impl<'s> Parser<'s> {
|
||||
let handler = if self.at_keyword(Keyword::Catch) {
|
||||
self.bump()?;
|
||||
self.expect(Punct::LParen)?;
|
||||
if self.es2015 && (self.at(Punct::LBracket) || self.at(Punct::LBrace)) {
|
||||
return Err(self.error_at_token(&self.tok, "destructuring catch parameters are not supported"));
|
||||
}
|
||||
let param = self.binding_identifier()?;
|
||||
self.expect(Punct::RParen)?;
|
||||
Some(CatchClause { param, body: self.parse_block()? })
|
||||
let body = self.parse_block_with(Some(¶m.name))?;
|
||||
Some(CatchClause { param, body })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
@@ -723,6 +949,10 @@ impl<'s> Parser<'s> {
|
||||
self.ctx.labels.remove(&label.name);
|
||||
}
|
||||
let mut body = body?;
|
||||
// A labelled function in a statement list is declared there as one without labels is.
|
||||
if let Some(Stmt::FunctionDecl(fid)) = self.ast.stmt(body).filter(|_| in_list) {
|
||||
self.declare_function(*fid)?;
|
||||
}
|
||||
for (label, label_start) in labels.into_iter().rev() {
|
||||
let span = Span::new(label_start.start, self.ast.stmt_span(body).end);
|
||||
body = self.ast.push_stmt(Stmt::Labeled { label, body }, span);
|
||||
@@ -761,11 +991,23 @@ impl<'s> Parser<'s> {
|
||||
|
||||
fn function_rest(&mut self, kind: FunctionKind, name: Option<(Name, Token)>, start: Span) -> Result<crate::ast::FunctionId> {
|
||||
self.expect(Punct::LParen)?;
|
||||
let mut params: Vec<(Name, Token)> = Vec::new();
|
||||
let mut params: Vec<Name> = Vec::new();
|
||||
let mut defaults: Vec<Option<ExprId>> = Vec::new();
|
||||
let mut rest = None;
|
||||
if !self.at(Punct::RParen) {
|
||||
loop {
|
||||
let (param, token) = self.function_name_or_param()?;
|
||||
params.push((param, token));
|
||||
if self.es2015 && self.at(Punct::Ellipsis) {
|
||||
self.bump()?;
|
||||
rest = Some(self.function_name_or_param()?.0);
|
||||
if !self.at(Punct::RParen) {
|
||||
return Err(self.error_at_token(&self.tok, "a rest parameter must be the last parameter"));
|
||||
}
|
||||
break;
|
||||
}
|
||||
let (param, _) = self.function_name_or_param()?;
|
||||
let default = if self.es2015 && self.eat(Punct::Eq)? { Some(self.parse_assignment(false)?) } else { None };
|
||||
params.push(param);
|
||||
defaults.push(default);
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
@@ -773,29 +1015,97 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
let close = self.expect(Punct::RParen)?;
|
||||
match kind {
|
||||
FunctionKind::Getter if !params.is_empty() => return Err(self.error_at_token(&close, "a getter must not have parameters")),
|
||||
FunctionKind::Setter if params.len() != 1 => return Err(self.error_at_token(&close, "a setter must have exactly one parameter")),
|
||||
FunctionKind::Getter if !params.is_empty() || rest.is_some() => {
|
||||
return Err(self.error_at_token(&close, "a getter must not have parameters"));
|
||||
}
|
||||
FunctionKind::Setter if params.len() != 1 || rest.is_some() => {
|
||||
return Err(self.error_at_token(&close, "a setter must have exactly one parameter"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if defaults.iter().all(Option::is_none) {
|
||||
defaults.clear();
|
||||
}
|
||||
self.expect(Punct::LBrace)?;
|
||||
let inner = Context { strict: self.ctx.strict, in_function: true, ..Context::default() };
|
||||
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
|
||||
let outer_strict = self.ctx.strict;
|
||||
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
|
||||
let outer = std::mem::replace(&mut self.ctx, inner);
|
||||
self.push_scope(true, names);
|
||||
let body = self.parse_body(true);
|
||||
let strict = self.ctx.strict;
|
||||
self.pop_scope();
|
||||
let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
|
||||
self.ctx = outer;
|
||||
let body = body?;
|
||||
self.expect(Punct::RBrace)?;
|
||||
if strict {
|
||||
self.check_strict_function(name.as_ref(), ¶ms)?;
|
||||
let function = Function { kind, name: name.map(|(n, _)| n), params, defaults, rest, body, strict, span: self.span_from(start) };
|
||||
self.check_params(&function, use_strict)?;
|
||||
Ok(self.ast.push_function(function))
|
||||
}
|
||||
|
||||
/// An arrow function's body and the function, from `=>`, with its parameters read.
|
||||
fn parse_arrow(&mut self, start: Span, (params, defaults, rest): Params, no_in: bool) -> Result<ExprId> {
|
||||
if self.tok.newline_before {
|
||||
return Err(self.error_at_token(&self.tok, "a line break cannot come before '=>'"));
|
||||
}
|
||||
Ok(self.ast.push_function(Function {
|
||||
kind,
|
||||
name: name.map(|(n, _)| n),
|
||||
params: params.into_iter().map(|(n, _)| n).collect(),
|
||||
body,
|
||||
strict,
|
||||
span: self.span_from(start),
|
||||
}))
|
||||
self.expect(Punct::Arrow)?;
|
||||
self.enter()?;
|
||||
let names: Vec<String> = params.iter().chain(&rest).map(|p| p.name.clone()).collect();
|
||||
let outer_strict = self.ctx.strict;
|
||||
let inner = Context { strict: outer_strict, in_function: true, ..Context::default() };
|
||||
let outer = std::mem::replace(&mut self.ctx, inner);
|
||||
self.push_scope(true, names);
|
||||
let block = self.at(Punct::LBrace);
|
||||
let body = if block {
|
||||
self.bump().and_then(|_| self.parse_body(true))
|
||||
} else {
|
||||
self.parse_assignment(no_in).map(|e| vec![self.ast.push_stmt(Stmt::Return(Some(e)), self.ast.expr_span(e))])
|
||||
};
|
||||
self.pop_scope();
|
||||
let (strict, use_strict) = (self.ctx.strict, self.ctx.use_strict);
|
||||
self.ctx = outer;
|
||||
self.leave();
|
||||
let body = body?;
|
||||
if block {
|
||||
self.expect(Punct::RBrace)?;
|
||||
}
|
||||
let defaults = if defaults.iter().all(Option::is_none) { Vec::new() } else { defaults };
|
||||
let function = Function { kind: FunctionKind::Arrow, name: None, params, defaults, rest, body, strict, span: self.span_from(start) };
|
||||
self.check_params(&function, use_strict)?;
|
||||
let id = self.ast.push_function(function);
|
||||
Ok(self.ast.push_expr(Expr::Arrow(id), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// The parameters an arrow function's parenthesized head `expr` gives (ECMA-262 2015 section
|
||||
/// 14.2.1): names, names with `= default`, and a last `...name`, each written bare.
|
||||
fn arrow_params(&self, expr: ExprId) -> Result<Params> {
|
||||
let invalid = |at: ExprId| self.error_at_offset(self.ast.expr_span(at).start, "invalid arrow function parameters");
|
||||
let Some(Expr::Paren(inner)) = self.ast.expr(expr) else { return Err(invalid(expr)) };
|
||||
let items = match self.ast.expr(*inner) {
|
||||
Some(Expr::Sequence(list)) => list.clone(),
|
||||
_ => vec![*inner],
|
||||
};
|
||||
let (mut params, mut defaults, mut rest) = (Vec::new(), Vec::new(), None);
|
||||
let name_of = |id: ExprId| match self.ast.expr(id) {
|
||||
Some(Expr::Ident(n)) => Some(Name { name: n.clone(), span: self.ast.expr_span(id) }),
|
||||
_ => None,
|
||||
};
|
||||
let count = items.len();
|
||||
for (i, item) in items.into_iter().enumerate() {
|
||||
match self.ast.expr(item) {
|
||||
Some(Expr::Ident(_)) => {
|
||||
params.push(name_of(item).ok_or_else(|| invalid(item))?);
|
||||
defaults.push(None);
|
||||
}
|
||||
Some(Expr::Assign { op: None, target, value }) => {
|
||||
params.push(name_of(*target).ok_or_else(|| invalid(item))?);
|
||||
defaults.push(Some(*value));
|
||||
}
|
||||
Some(Expr::Spread(arg)) if i + 1 == count => rest = Some(name_of(*arg).ok_or_else(|| invalid(item))?),
|
||||
_ => return Err(invalid(item)),
|
||||
}
|
||||
}
|
||||
Ok((params, defaults, rest))
|
||||
}
|
||||
|
||||
/// A parameter's name.
|
||||
@@ -809,21 +1119,39 @@ impl<'s> Parser<'s> {
|
||||
Ok((Name { name, span: token.span }, token))
|
||||
}
|
||||
|
||||
/// The rules strict mode code sets for a function's name and parameters (Annex C): neither
|
||||
/// `eval`, `arguments` nor a strict-mode reserved word, and no parameter name twice.
|
||||
fn check_strict_function(&self, name: Option<&(Name, Token)>, params: &[(Name, Token)]) -> Result<()> {
|
||||
for (n, token) in name.into_iter().chain(params) {
|
||||
if is_eval_or_arguments(&n.name) {
|
||||
return Err(self.error_at_token(token, format!("'{}' cannot be declared in strict mode", n.name)));
|
||||
}
|
||||
if strict_reserved(&n.name) {
|
||||
return Err(self.error_at_token(token, format!("'{}' is a reserved word in strict mode", n.name)));
|
||||
/// The rules for a function's name and parameters. Strict mode code (Annex C): neither `eval`,
|
||||
/// `arguments` nor a strict-mode reserved word, and no parameter name twice. An arrow function
|
||||
/// or a function with a default or rest parameter has no parameter name twice either (ECMA-262
|
||||
/// 2015 sections 14.1.2 and 14.2.1), and its body cannot start with `"use strict"`
|
||||
/// (`body_strict`; ECMA-262 2016 section 14.1.2).
|
||||
fn check_params(&self, function: &Function, body_strict: bool) -> Result<()> {
|
||||
let params = || function.params.iter().chain(&function.rest);
|
||||
let simple = function.simple_params() && function.kind != FunctionKind::Arrow;
|
||||
if body_strict && !function.simple_params() {
|
||||
let at = function.body.first().map_or(function.span.start, |&s| self.ast.stmt_span(s).start);
|
||||
return Err(self.error_at_offset(at, "\"use strict\" is not allowed in a function with default or rest parameters"));
|
||||
}
|
||||
if function.strict {
|
||||
for n in function.name.iter().chain(params()) {
|
||||
if is_eval_or_arguments(&n.name) {
|
||||
return Err(self.error_at_offset(n.span.start, format!("'{}' cannot be declared in strict mode", n.name)));
|
||||
}
|
||||
if strict_reserved(&n.name) {
|
||||
return Err(self.error_at_offset(n.span.start, format!("'{}' is a reserved word in strict mode", n.name)));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
for (p, token) in params {
|
||||
if !seen.insert(p.name.as_str()) {
|
||||
return Err(self.error_at_token(token, format!("duplicate parameter name '{}' is not allowed in strict mode", p.name)));
|
||||
if function.strict || !simple {
|
||||
let mut seen = HashSet::new();
|
||||
for p in params() {
|
||||
if !seen.insert(p.name.as_str()) {
|
||||
let message = if function.strict {
|
||||
format!("duplicate parameter name '{}' is not allowed in strict mode", p.name)
|
||||
} else {
|
||||
format!("duplicate parameter name '{}'", p.name)
|
||||
};
|
||||
return Err(self.error_at_offset(p.span.start, message));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -857,7 +1185,10 @@ impl<'s> Parser<'s> {
|
||||
fn assignment(&mut self, no_in: bool) -> Result<ExprId> {
|
||||
let mut targets: Vec<(ExprId, AssignOp)> = Vec::new();
|
||||
loop {
|
||||
let expr = self.parse_conditional(no_in)?;
|
||||
let mut expr = self.parse_conditional(no_in)?;
|
||||
if self.es2015 && self.at(Punct::Arrow) {
|
||||
expr = self.arrow_from(expr, no_in)?;
|
||||
}
|
||||
let Some(op) = assign_op(&self.tok) else {
|
||||
let mut value = expr;
|
||||
while let Some((target, op)) = targets.pop() {
|
||||
@@ -872,6 +1203,18 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The arrow function whose head is `expr`, read before the current `=>`: a name standing
|
||||
/// alone, or parameters in parentheses.
|
||||
fn arrow_from(&mut self, expr: ExprId, no_in: bool) -> Result<ExprId> {
|
||||
let start = self.ast.expr_span(expr);
|
||||
let params = match self.ast.expr(expr) {
|
||||
Some(Expr::Ident(name)) => (vec![Name { name: name.clone(), span: start }], vec![None], None),
|
||||
Some(Expr::Paren(_)) => self.arrow_params(expr)?,
|
||||
_ => return Err(self.unexpected()),
|
||||
};
|
||||
self.parse_arrow(start, params, no_in)
|
||||
}
|
||||
|
||||
/// An assignment's, `++`'s, `--`'s or `for-in`'s target: an identifier (in strict code
|
||||
/// neither `eval` nor `arguments`), a property, an E4X name standing alone (`@a`, `ns::a`;
|
||||
/// ECMA-357 section 11.1), or outside strict mode code a call (assigning to its result fails
|
||||
@@ -1006,6 +1349,11 @@ impl<'s> Parser<'s> {
|
||||
let span = self.ast.expr_span(expr).to(close.span);
|
||||
expr = self.ast.push_expr(Expr::Index { object: expr, index }, span);
|
||||
}
|
||||
TokenKind::Template { .. } => {
|
||||
let (quasis, exprs) = self.parse_template()?;
|
||||
let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
|
||||
expr = self.ast.push_expr(Expr::TaggedTemplate { tag: expr, quasis, exprs }, span);
|
||||
}
|
||||
TokenKind::Punct(Punct::LParen) => {
|
||||
let args = self.parse_arguments()?;
|
||||
let span = Span::new(self.ast.expr_span(expr).start, self.prev_end);
|
||||
@@ -1024,12 +1372,23 @@ impl<'s> Parser<'s> {
|
||||
Ok(expr)
|
||||
}
|
||||
|
||||
/// An element of an array literal or an argument list: an assignment expression, or with
|
||||
/// [`crate::Options::es2015`] a spread (`...expression`).
|
||||
fn parse_element(&mut self) -> Result<ExprId> {
|
||||
if self.es2015 && self.at(Punct::Ellipsis) {
|
||||
let start = self.bump()?.span;
|
||||
let arg = self.parse_assignment(false)?;
|
||||
return Ok(self.ast.push_expr(Expr::Spread(arg), self.span_from(start)));
|
||||
}
|
||||
self.parse_assignment(false)
|
||||
}
|
||||
|
||||
fn parse_arguments(&mut self) -> Result<Vec<ExprId>> {
|
||||
self.expect(Punct::LParen)?;
|
||||
let mut args = Vec::new();
|
||||
if !self.at(Punct::RParen) {
|
||||
loop {
|
||||
args.push(self.parse_assignment(false)?);
|
||||
args.push(self.parse_element()?);
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
@@ -1081,12 +1440,17 @@ impl<'s> Parser<'s> {
|
||||
}
|
||||
TokenKind::Punct(Punct::LBracket) => return self.parse_array(),
|
||||
TokenKind::Punct(Punct::LBrace) => return self.parse_object(),
|
||||
TokenKind::Punct(Punct::LParen) if self.es2015 => return self.parse_paren_or_arrow_head(),
|
||||
TokenKind::Punct(Punct::LParen) => {
|
||||
self.bump()?;
|
||||
let inner = self.parse_expression(false)?;
|
||||
self.expect(Punct::RParen)?;
|
||||
return Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)));
|
||||
}
|
||||
TokenKind::Template { .. } => {
|
||||
let (quasis, exprs) = self.parse_template()?;
|
||||
return Ok(self.ast.push_expr(Expr::Template { quasis, exprs }, self.span_from(start)));
|
||||
}
|
||||
TokenKind::Punct(Punct::Lt) if self.e4x => return self.parse_xml_literal(),
|
||||
TokenKind::Punct(Punct::At | Punct::Star) if self.e4x => return self.parse_xml_scope_name(),
|
||||
_ => return Err(self.unexpected()),
|
||||
@@ -1099,6 +1463,68 @@ impl<'s> Parser<'s> {
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// `( … )` with [`crate::Options::es2015`]: a parenthesized expression, or the head of an arrow
|
||||
/// function, which may also be `()` or end with `...name`; those two must come before `=>`.
|
||||
fn parse_paren_or_arrow_head(&mut self) -> Result<ExprId> {
|
||||
let start = self.expect(Punct::LParen)?.span;
|
||||
let mut items = Vec::new();
|
||||
let mut head_only = self.at(Punct::RParen);
|
||||
while !self.at(Punct::RParen) {
|
||||
if self.at(Punct::Ellipsis) {
|
||||
let spread_start = self.bump()?.span;
|
||||
let name = self.binding_identifier()?;
|
||||
let arg = self.ast.push_expr(Expr::Ident(name.name), name.span);
|
||||
items.push(self.ast.push_expr(Expr::Spread(arg), self.span_from(spread_start)));
|
||||
head_only = true;
|
||||
break;
|
||||
}
|
||||
items.push(self.parse_assignment(false)?);
|
||||
if !self.eat(Punct::Comma)? {
|
||||
break;
|
||||
}
|
||||
if self.at(Punct::RParen) {
|
||||
return Err(self.unexpected());
|
||||
}
|
||||
}
|
||||
self.expect(Punct::RParen)?;
|
||||
if head_only && !self.at(Punct::Arrow) {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected '=>' but found {}", describe(&self.tok))));
|
||||
}
|
||||
let inner = match items.as_slice() {
|
||||
[one] => *one,
|
||||
_ => {
|
||||
let span = self.span_from(start);
|
||||
self.ast.push_expr(Expr::Sequence(items), span)
|
||||
}
|
||||
};
|
||||
Ok(self.ast.push_expr(Expr::Paren(inner), self.span_from(start)))
|
||||
}
|
||||
|
||||
/// A template literal from its first piece (the current token): its pieces and substitutions.
|
||||
fn parse_template(&mut self) -> Result<(Vec<TemplatePiece>, Vec<ExprId>)> {
|
||||
let mut quasis = Vec::new();
|
||||
let mut exprs = Vec::new();
|
||||
loop {
|
||||
let TokenKind::Template { cooked, raw, tail } = &self.tok.kind else { return Err(self.unexpected()) };
|
||||
let tail = *tail;
|
||||
quasis.push(TemplatePiece { cooked: cooked.clone(), raw: raw.clone() });
|
||||
if tail {
|
||||
self.bump()?;
|
||||
return Ok((quasis, exprs));
|
||||
}
|
||||
self.bump()?;
|
||||
self.enter()?;
|
||||
let expr = self.parse_expression(false);
|
||||
self.leave();
|
||||
exprs.push(expr?);
|
||||
if !self.at(Punct::RBrace) {
|
||||
return Err(self.error_at_token(&self.tok, format!("expected '}}' but found {}", describe(&self.tok))));
|
||||
}
|
||||
let piece = self.lex.rescan_template(&self.tok)?;
|
||||
self.tok = piece;
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_function_expression(&mut self) -> Result<ExprId> {
|
||||
let start = self.expect_keyword(Keyword::Function)?.span;
|
||||
let name = if matches!(self.tok.kind, TokenKind::Ident(_)) { Some(self.function_name()?) } else { None };
|
||||
@@ -1118,7 +1544,7 @@ impl<'s> Parser<'s> {
|
||||
elements.push(None);
|
||||
continue;
|
||||
}
|
||||
elements.push(Some(self.parse_assignment(false)?));
|
||||
elements.push(Some(self.parse_element()?));
|
||||
if !self.at(Punct::RBracket) {
|
||||
self.expect(Punct::Comma)?;
|
||||
}
|
||||
@@ -1276,5 +1702,6 @@ fn describe(token: &Token) -> String {
|
||||
TokenKind::RegExp { .. } => "regular expression".into(),
|
||||
TokenKind::Directive(_) => "preprocessor line".into(),
|
||||
TokenKind::XmlLiteral => "XML literal".into(),
|
||||
TokenKind::Template { .. } => "template literal".into(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -215,6 +215,19 @@ impl Realm {
|
||||
self.interp.reset_gc_threshold();
|
||||
}
|
||||
|
||||
/// Sets [`Options::es2015`] for the next runs, and for the code they evaluate. The `let` and
|
||||
/// `const` names earlier runs declared stay visible when it is turned off. A run begun with
|
||||
/// [`Realm::start`] that is still going keeps the language it started with for the code it
|
||||
/// evaluates; the new one applies once it ends.
|
||||
pub fn set_es2015(&mut self, es2015: bool) {
|
||||
if self.is_running() || self.interp.waiting {
|
||||
self.interp.next_es2015 = Some(es2015);
|
||||
} else {
|
||||
self.interp.next_es2015 = None;
|
||||
self.interp.set_es2015(es2015);
|
||||
}
|
||||
}
|
||||
|
||||
/// The realm's interrupt flag. Setting it stops a running script, or the next one to start.
|
||||
pub fn interrupt(&self) -> Interrupt {
|
||||
Interrupt(self.interp.interrupt.clone())
|
||||
@@ -293,6 +306,9 @@ impl Realm {
|
||||
interp.waiting = false;
|
||||
interp.resuming = None;
|
||||
interp.passing = Value::Undefined;
|
||||
if let Some(es2015) = interp.next_es2015.take() {
|
||||
interp.set_es2015(es2015);
|
||||
}
|
||||
match result {
|
||||
Ok(v) => Ok(interp.to_js_value(&v)),
|
||||
Err(Abrupt::Throw(v)) => {
|
||||
|
||||
@@ -210,12 +210,17 @@ pub enum Punct {
|
||||
ColonColon,
|
||||
/// `@`, read only with [`crate::Options::e4x`].
|
||||
At,
|
||||
/// `=>`, read only with [`crate::Options::es2015`].
|
||||
Arrow,
|
||||
/// `...`, read only with [`crate::Options::es2015`].
|
||||
Ellipsis,
|
||||
}
|
||||
|
||||
impl Punct {
|
||||
/// Punctuators by spelling, longest first, so the first that matches is the longest.
|
||||
pub(crate) const ALL: &'static [(&'static str, Punct)] = &[
|
||||
(">>>=", Punct::UShrEq),
|
||||
("...", Punct::Ellipsis),
|
||||
("===", Punct::EqEqEq),
|
||||
("!==", Punct::NotEqEq),
|
||||
(">>>", Punct::UShr),
|
||||
@@ -223,6 +228,7 @@ impl Punct {
|
||||
(">>=", Punct::ShrEq),
|
||||
("<=", Punct::LtEq),
|
||||
(">=", Punct::GtEq),
|
||||
("=>", Punct::Arrow),
|
||||
("==", Punct::EqEq),
|
||||
("!=", Punct::NotEq),
|
||||
("++", Punct::PlusPlus),
|
||||
@@ -354,6 +360,15 @@ pub enum TokenKind {
|
||||
Directive(Directive),
|
||||
/// An XML or XMLList literal; the tokens of its embedded expressions follow it.
|
||||
XmlLiteral,
|
||||
/// A piece of a template literal (read only with [`crate::Options::es2015`]): from its
|
||||
/// backtick, or from the `}` that ends a substitution, to the next `${` or the closing
|
||||
/// backtick (`tail`). `cooked` is the text with its escapes read and `raw` the text as written,
|
||||
/// both with each CR LF and each CR read as a line feed; U+2028 and U+2029 stay as written.
|
||||
Template {
|
||||
cooked: Vec<u16>,
|
||||
raw: Vec<u16>,
|
||||
tail: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// A token, with where it is and the facts the grammar's rules need about it.
|
||||
|
||||
@@ -573,7 +573,7 @@ impl Interp {
|
||||
let env = self.frame()?.var_env;
|
||||
if let Some(Env::Decl { bindings, .. }) = self.heap.env_mut(env) {
|
||||
let value = Value::String(Str::from_rc(uri));
|
||||
bindings.insert(Rc::from(DEFAULT_NS_BINDING), Binding { value, mutable: true, deletable: false });
|
||||
bindings.insert(Rc::from(DEFAULT_NS_BINDING), Binding::new(value, true, false));
|
||||
} else {
|
||||
self.xml_default_uri = uri;
|
||||
}
|
||||
|
||||
+172
-6
@@ -28,6 +28,10 @@
|
||||
//! `builtins-failures.txt`. The interpreter tests fail when the interpreter panics, when a harness
|
||||
//! or test file cannot be read, or when no ES5 test runs.
|
||||
//!
|
||||
//! A fifth test reads the ECMAScript 2015 subset that `Options::es2015` covers (`let`, `const`,
|
||||
//! arrow functions, templates, default and rest parameters) without and with that option, and
|
||||
//! prints both counts; its failures with the option go to `es2015-failures.txt`.
|
||||
//!
|
||||
//! Two more tests read the Annex B trees, where tests name any edition's section: one parses every
|
||||
//! test under `test/annexB/language/` without a feature tag the same way as the ES5 parse subset
|
||||
//! (failures in `annexb-parse-failures.txt`), and one runs those tests and the tests under the
|
||||
@@ -408,10 +412,20 @@ fn missing_builtins<'a>(provided: &[&str]) -> HashSet<&'a str> {
|
||||
/// in `this["Map"]`), and as a word in any string literal when one of the sources can run a string
|
||||
/// as code. Comments, and strings that only mention the name in a message, do not count.
|
||||
fn needs_missing_builtin(sources: &[&str], missing: &HashSet<&str>) -> bool {
|
||||
needs_missing_builtin_in(sources, missing, &Options::default())
|
||||
}
|
||||
|
||||
/// [`needs_missing_builtin`] for sources read with `options`. With [`Options::es2015`], a source
|
||||
/// that does not tokenize is left out of the check rather than skipping the test, so the run
|
||||
/// counts the tokenizer's error as a failure.
|
||||
fn needs_missing_builtin_in(sources: &[&str], missing: &HashSet<&str>, options: &Options) -> bool {
|
||||
let mut lists = Vec::with_capacity(sources.len());
|
||||
for source in sources {
|
||||
let Ok(tokens) = tokenize(source, &Options::default()) else { return true };
|
||||
lists.push(tokens);
|
||||
match tokenize(source, options) {
|
||||
Ok(tokens) => lists.push(tokens),
|
||||
Err(_) if options.es2015 => {}
|
||||
Err(_) => return true,
|
||||
}
|
||||
}
|
||||
let strings_are_code = lists.iter().any(|tokens| runs_strings_as_code(tokens));
|
||||
lists.iter().flatten().any(|t| match &t.kind {
|
||||
@@ -442,9 +456,9 @@ fn runs_strings_as_code(tokens: &[Token]) -> bool {
|
||||
})
|
||||
}
|
||||
|
||||
/// Runs one test in a new realm; `Err` describes a failure.
|
||||
fn run_one(script: &str, negative_type: Option<&str>) -> Result<(), String> {
|
||||
let mut realm = Realm::with_options(Options::default(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
/// Runs one test in a new realm made with `options`; `Err` describes a failure.
|
||||
fn run_one(script: &str, negative_type: Option<&str>, options: &Options) -> Result<(), String> {
|
||||
let mut realm = Realm::with_options(options.clone(), Limits { fuel: 20_000_000, heap_bytes: 256 << 20, ..Limits::default() });
|
||||
match (realm.run(script), negative_type) {
|
||||
(Ok(_), None) => Ok(()),
|
||||
(Ok(_), Some(t)) => Err(format!("completed; a {t} was expected")),
|
||||
@@ -622,7 +636,7 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
let outcome = std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref()));
|
||||
let outcome = std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), &Options::default()));
|
||||
match outcome {
|
||||
Ok(Ok(())) => counts.passed += 1,
|
||||
Ok(Err(why)) => {
|
||||
@@ -640,6 +654,145 @@ fn run_tests(dir: &Path, root: &Path, missing: &HashSet<&str>, later: bool) -> (
|
||||
(es5_counts, later_counts)
|
||||
}
|
||||
|
||||
/// The folders under `test/language/` that hold tests of the ECMAScript 2015 forms
|
||||
/// [`Options::es2015`] reads.
|
||||
const ES2015_FOLDERS: &[&str] = &[
|
||||
"block-scope",
|
||||
"statements/let",
|
||||
"statements/const",
|
||||
"expressions/arrow-function",
|
||||
"expressions/template-literal",
|
||||
"expressions/tagged-template",
|
||||
"rest-parameters",
|
||||
];
|
||||
|
||||
/// The feature tags of the forms [`Options::es2015`] reads.
|
||||
const ES2015_FEATURES: &[&str] = &["let", "const", "arrow-function", "template", "default-parameters", "rest-parameters"];
|
||||
|
||||
#[test]
|
||||
fn es2015_subset_runs() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
println!("test262 ES2015 subset: SKIPPED (no suite; run cargo xtask test262)");
|
||||
return;
|
||||
};
|
||||
let handle = std::thread::Builder::new().stack_size(64 << 20).spawn(move || run_es2015(&dir)).unwrap();
|
||||
handle.join().unwrap();
|
||||
}
|
||||
|
||||
/// The counts of the ES2015 subset read with one setting of [`Options::es2015`].
|
||||
#[derive(Default)]
|
||||
struct Es2015Counts {
|
||||
parse_passed: usize,
|
||||
parse_failed: usize,
|
||||
run_passed: usize,
|
||||
run_failed: usize,
|
||||
panicked: usize,
|
||||
failures: String,
|
||||
}
|
||||
|
||||
/// Runs the ES2015 subset: the tests under `test/language/` in [`ES2015_FOLDERS`] whose feature
|
||||
/// tags are all in [`ES2015_FEATURES`], and the tests elsewhere under `test/language/` with feature
|
||||
/// tags that are all in it. Negative parse tests must give a `SyntaxError`; the other tests run in a
|
||||
/// new realm after the harness, as [`run_tests`] runs them, skipping module and asynchronous tests
|
||||
/// and those that need a missing built-in. Each test is read twice, without and with
|
||||
/// [`Options::es2015`], and the counts of both are printed; the failures with it go to
|
||||
/// `es2015-failures.txt`.
|
||||
fn run_es2015(dir: &Path) {
|
||||
let language = or_fail(inside(dir, "test/language"));
|
||||
assert!(language.is_dir(), "{} is not a test262 checkout", dir.display());
|
||||
// A harness file is named by the test's `includes:`, so it is read only inside `harness/`.
|
||||
let harness = |name: &str| or_fail(inside(dir, &format!("harness/{name}")).and_then(|p| read_source(&p)));
|
||||
let prelude = format!("{}\n{}\n", harness("assert.js"), harness("sta.js"));
|
||||
let missing = missing_builtins(&[TEXT_BUILTINS]);
|
||||
let modern = Options { es2015: true, ..Options::default() };
|
||||
let editions = [Options::default(), modern.clone()];
|
||||
let mut counts = [Es2015Counts::default(), Es2015Counts::default()];
|
||||
let (mut selected, mut skipped, mut other_features) = (0usize, 0usize, 0usize);
|
||||
for path in or_fail(test_files(&language)) {
|
||||
let rel = path.strip_prefix(dir).unwrap_or(&path).display().to_string().replace('\\', "/");
|
||||
let in_folder = ES2015_FOLDERS.iter().any(|f| rel.starts_with(&format!("test/language/{f}/")));
|
||||
let source = or_fail(read_source(&path));
|
||||
let meta = meta(&source);
|
||||
let tags_in_set = meta.features.iter().all(|f| ES2015_FEATURES.contains(&f.as_str()));
|
||||
if !(in_folder || !meta.features.is_empty()) {
|
||||
continue;
|
||||
}
|
||||
if !tags_in_set {
|
||||
if in_folder {
|
||||
other_features += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let has = |flag: &str| meta.flags.iter().any(|f| f == flag);
|
||||
if has("module") || has("async") || meta.negative_phase.as_deref() == Some("resolution") {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
let expect_error = meta.negative_phase.as_deref() == Some("parse");
|
||||
let includes: String = meta.includes.iter().map(|i| harness(i) + "\n").collect();
|
||||
if !expect_error && needs_missing_builtin_in(&[&source, &includes], &missing, &modern) {
|
||||
skipped += 1;
|
||||
continue;
|
||||
}
|
||||
selected += 1;
|
||||
for (options, counts) in editions.iter().zip(counts.iter_mut()) {
|
||||
for &strict in modes(&meta) {
|
||||
let mode = if strict { "strict" } else { "sloppy" };
|
||||
let outcome = if expect_error {
|
||||
let text = if strict { format!("\"use strict\";\n{source}") } else { source.clone() };
|
||||
let result = parse(&text, options);
|
||||
if result.is_err() {
|
||||
counts.parse_passed += 1;
|
||||
continue;
|
||||
}
|
||||
counts.parse_failed += 1;
|
||||
"parsed; a SyntaxError was expected".to_string()
|
||||
} else {
|
||||
let body = if has("raw") { source.clone() } else { format!("{prelude}{includes}{source}") };
|
||||
let script = if strict { format!("\"use strict\";\n{body}") } else { body };
|
||||
let negative_type = meta.negative_type.clone().filter(|_| meta.negative_phase.as_deref() == Some("runtime"));
|
||||
match std::panic::catch_unwind(|| run_one(&script, negative_type.as_deref(), options)) {
|
||||
Ok(Ok(())) => {
|
||||
counts.run_passed += 1;
|
||||
continue;
|
||||
}
|
||||
Ok(Err(why)) => {
|
||||
counts.run_failed += 1;
|
||||
why
|
||||
}
|
||||
Err(_) => {
|
||||
counts.run_failed += 1;
|
||||
counts.panicked += 1;
|
||||
"PANIC".to_string()
|
||||
}
|
||||
}
|
||||
};
|
||||
counts.failures.push_str(&format!("{rel} ({mode}): {outcome}\n"));
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(selected > 0, "no ES2015 tests under {}", language.display());
|
||||
let [before, after] = counts;
|
||||
let report = dir.join("es2015-failures.txt");
|
||||
if let Err(e) = std::fs::write(&report, &after.failures) {
|
||||
println!("could not write {}: {e}", report.display());
|
||||
}
|
||||
let line = |c: &Es2015Counts| {
|
||||
format!(
|
||||
"negative parse runs {} passed, {} failed; other runs {} passed, {} failed ({} panicked)",
|
||||
c.parse_passed, c.parse_failed, c.run_passed, c.run_failed, c.panicked
|
||||
)
|
||||
};
|
||||
println!(
|
||||
"test262 ES2015 subset: {selected} tests. Without Options::es2015: {}. With it: {}. Skipped {skipped} module, asynchronous \
|
||||
or missing-built-in tests and {other_features} tests in the folders with other feature tags. Failures: {}",
|
||||
line(&before),
|
||||
line(&after),
|
||||
report.display()
|
||||
);
|
||||
assert_eq!(before.panicked + after.panicked, 0, "the interpreter panicked; see {}", report.display());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn annex_b_runs() {
|
||||
let Some(dir) = suite_dir() else {
|
||||
@@ -712,6 +865,19 @@ fn a_missing_name_in_a_message_string_does_not_skip() {
|
||||
assert!(!skips(&["var x = 1;", r#"function check(v) { if (!v) throw new Test262Error("no Symbol"); }"#]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_source_that_does_not_tokenize_as_es2015_is_run_and_not_skipped() {
|
||||
// The ES5 runs skip a test whose ES2015 syntax they cannot read. In the ES2015 subset, a
|
||||
// source that does not tokenize is run, so the tokenizer's error is counted as a failure.
|
||||
let missing: HashSet<&str> = ["Map"].into_iter().collect();
|
||||
let modern = Options { es2015: true, ..Options::default() };
|
||||
let unreadable = "var s = `never closed";
|
||||
assert!(needs_missing_builtin(&[unreadable], &missing));
|
||||
assert!(!needs_missing_builtin_in(&[unreadable], &missing, &modern));
|
||||
// A missing built-in in another source still skips.
|
||||
assert!(needs_missing_builtin_in(&[unreadable, "var m = new Map();"], &missing, &modern));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_name_in_code_skips() {
|
||||
assert!(skips(&["var m = new Map();"]));
|
||||
|
||||
+10
-1
@@ -2625,7 +2625,16 @@ https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-act
|
||||
describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
|
||||
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. The script reaches the
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
|
||||
`.js` (in any case) also reads these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and
|
||||
`const` with block scope and their temporal dead zone, a new `let` binding for each `for` loop iteration, function
|
||||
declarations scoped to their block, arrow functions, template literals and tagged templates, default and rest
|
||||
parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again
|
||||
before each element, strings and `String` objects by code point, and objects with a `length` property by index, and
|
||||
throws a `TypeError` for any other value; that rule is VectorCraft's own
|
||||
until iterators are added. `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does, and
|
||||
an engine that `#targetengine` keeps reads each run the way that run's script does. A
|
||||
`.jsx` file and a `source` string read ES5.1 only, and the ECMAScript 2015 forms are syntax errors there. The script reaches the
|
||||
app through the global object `vc`, and writes to the Script Console and runs other files through `$`:
|
||||
|
||||
- `vc.run(id, params)` runs a command and returns its result. A command that fails throws an error the script can
|
||||
|
||||
@@ -1085,6 +1085,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- `vectorcraft-js` parses JavaScript as ECMAScript 5.1 defines it, with the legacy octal forms, block functions and lenient regular expressions of Annex B, into a syntax tree with source spans; it reads the `#target`, `#include` and other preprocessor lines as directives without running them, and a script that breaks the grammar or an early-error rule gives a `SyntaxError` with its line and column. Nesting past the parser's depth limit (`Options::max_depth`, 200 by default) gives a `SyntaxError` instead of exhausting the stack. `cargo xtask test262` fetches the conformance suite at a pinned commit and parses its ES5 tests: 5,411 of 5,418 runs pass (the 7 others use `let` and `const`). This entry covers parsing; the next entry covers running scripts. Tests: `crates/js/src/tests.rs`, `crates/engine/tests/it/js_lexer_vs_scriptcheck.rs`.
|
||||
- `vectorcraft-js` identifiers, written out or as `\uXXXX` and `\u{...}` escapes, take the characters Unicode's `ID_Start` and `ID_Continue` properties allow (https://www.unicode.org/reports/tr31/), plus `$` and, at the start, `_`, as later ECMAScript editions define them (https://tc39.es/ecma262/#sec-names-and-keywords). `Other_ID_Start` characters such as U+2118 and `Other_ID_Continue` characters such as U+00B7 and the zero width non-joiner and joiner are accepted, and no `Pattern_Syntax` or `Pattern_White_Space` character is. Letter categories come from Unicode 17.0, so U+088F starts an identifier and U+1ACF may follow its first character; characters assigned after Unicode 17.0 are not yet identifier characters. Tests: `crates/js/src/tests.rs` (`identifier_characters_are_unicode_17_id_start_and_id_continue`, which checks every code point, `identifiers_take_the_characters_unicode_17_assigned`, `identifiers_take_the_other_id_start_and_continue_characters`, `identifiers_refuse_pattern_syntax_surrogates_and_bad_escapes`, `no_pattern_syntax_or_white_space_character_is_an_identifier_character`).
|
||||
- `vectorcraft-js`'s `Realm` runs ECMAScript 5.1 scripts: the parsed script compiles to verified bytecode that a non-recursive interpreter runs, with closures, `this`, `arguments`, `with`, direct and indirect `eval`, `new Function`, `try`/`catch`/`finally`, labeled `break` and `continue`, and `for`-`in` in insertion order, over a mark-and-sweep heap, with the built-ins the next two entries list. Every run is bounded by fuel, heap bytes, frames, nested host calls and an interrupt flag (smaller defaults in the wasm build), and a run that reaches a limit stops with a limit error that `try` cannot catch. `cargo xtask test262` also runs the suite's ES5 language tests that need only the built-ins present: 4,280 of 4,286 runs pass (4 of the others expect the completion values of later editions, and 2 expect a configurable function `length`). The app does not call it yet. Tests: `crates/js/src/interp_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- With `Options::es2015`, `vectorcraft-js` also reads and runs these ECMAScript 2015 forms (https://262.ecma-international.org/6.0/): `let` and `const` with block scope and their temporal dead zone (a read or write before the declaration runs throws a `ReferenceError`, and a write to a `const` throws a `TypeError` in any code), a new `let` binding for each iteration of a `for` or `for`-`in` loop, function declarations scoped to their block, arrow functions with the `this` and `arguments` of the code around them and no `prototype`, template literals and tagged templates with one frozen strings object for each site, default and rest parameters with an `arguments` object that does not follow the parameters, and spread in array literals, calls and `new`. Spread reads arrays by index, reading the length again before each element, strings and `String` objects by code point, and objects with a `length` property by index, and throws a `TypeError` for any other value; that rule is VectorCraft's own until iterators are added. Spread and template objects take fuel for each element and count against the heap limit, and nested arrows and templates count against `Options::max_depth`. `script.run` sets the option for a `.js` file, and `eval`, `Function`, `#include` files and `$.evalFile` read code the way the script does; a `.jsx` file and a `source` string stay ES5.1. Destructuring, `for`-`of`, classes, generators and modules are still syntax errors. `cargo xtask test262` reads the suite's tests of these forms without and with the option: 390 of 390 negative parse runs and 533 of 708 other runs pass with it (373 and 27 without it). Of the 175 failing runs, 151 do not parse because the tests also use forms this list leaves out (classes, method definitions, destructuring, `for`-`of`, trailing commas in parameter lists, and a later edition's rule for escapes in tagged templates), and 24 expect function `name` properties, a configurable function `length` and the `caller` and `arguments` restrictions, ECMAScript 2015 rules that `vectorcraft-js` does not implement. Tests: `crates/js/src/es2015_tests.rs`, `crates/js/tests/test262.rs`, `crates/engine/src/tests/script_run.rs`.
|
||||
- `vectorcraft-js` provides the ECMAScript 5.1 built-ins `Object` with its property-descriptor functions, `create`, `keys`, `seal` and `freeze` (section 15.2), `Function.prototype.bind` (15.3.4.5), `Array` with every ES5 method (15.4), the error types (15.11), `Math` (15.8), `JSON` with revivers, replacers and indentation (15.12), and the global functions with Annex B's `escape` and `unescape` (15.1, B.2). The array methods work on array-like objects. A method visits only the indices that exist when its range is longer than 4,096 indices and more than 8 times the properties on the object and its prototypes, so `new Array(4294967295).join("")` ends at once; a shorter range is visited index by index, holes included, and each index takes fuel. `join` writes a cycle back to an array as an empty string, `JSON.stringify` throws a `TypeError` on a cycle, and deep `JSON` nesting uses no native stack. Every loop takes fuel and every result is checked against the heap limit. `cargo xtask test262` runs the suite's ES5 built-in tests that need only these built-ins: 6,798 of 6,866 runs pass (the 34 failing tests expect rules of later editions). It also fetches the `json2.js` polyfill at a pinned commit and checks that its `stringify` and `parse` agree with the built-in `JSON`. Tests: `crates/js/src/builtins_tests.rs`, `crates/js/tests/test262.rs`, `crates/js/tests/json2.rs`.
|
||||
- `vectorcraft-js` has `String`, `Number`, `RegExp` and `Date` as ECMAScript 5.1 defines them (sections 15.5, 15.7, 15.9 and 15.10, https://262.ecma-international.org/5.1/), with Annex B's `substr`, `getYear`, `setYear` and `toGMTString`. `toFixed`, `toExponential` and `toPrecision` format a number from its exact decimal value, and `toString(radix)` writes any base from 2 to 36. Regular expressions (flags `g`, `i` and `m`) run on a backtracking matcher whose choice points and capture state count against the heap limit and which takes fuel for every step, so a catastrophic pattern stops at the fuel limit and 50,000 nested groups give a `SyntaxError` at the default depth limit. A string method that would build a string past the heap limit stops before it allocates. `Date` reads the clock and time zone the host sets (`Realm::set_clock`, `Realm::set_time_zone`; local time is UTC by default). `cargo xtask test262` runs the suite's `built-ins` tests for the four (https://github.com/tc39/test262): of the runs of the ES5 tests that need only the built-ins present, 1,379 of 1,411 pass for `String`, 298 of 298 for `Number`, 954 of 988 for `RegExp` and 8 of 8 for `Date`. The others expect later editions' rules (built-in functions whose `length` can be deleted, flags given with a RegExp object, a negative `lastIndex`, `RegExp.prototype` as a plain object, and `RegExp.prototype`'s `global`, `ignoreCase` and `multiline` properties that can be deleted). Tests: `crates/js/src/text_tests.rs`, `crates/js/tests/test262.rs`.
|
||||
- `cargo xtask test262` also reads the suite's Annex B tests (https://tc39.es/ecma262/#sec-additional-ecmascript-features-for-web-browsers), whichever edition they name. It parses the 819 tests under `test/annexB/language` without a feature tag in the modes their flags give, so a `for`-`in` variable with an initializer must parse in sloppy code and give a `SyntaxError` in strict code (682 of 843 runs pass), and it runs those tests and the `test/annexB/built-ins` tests for `String`, `Date`, `RegExp` and `Function` that need only the built-ins present (263 of 667 runs pass for the language tests and 56 of 252 for the built-ins). Failures go to `annexb-parse-failures.txt`, `annexb-language-failures.txt` and `annexb-builtins-failures.txt` beside the suite. A conformance failure does not fail the tests, but an interpreter panic fails `annex_b_runs`, so `cargo xtask test262` exits non-zero. A folder or file the runner cannot read also fails the test that reads it. The runner reads only regular files inside the suite, up to 8 MiB each, and does not follow symbolic links. Tests: `crates/js/tests/test262.rs`.
|
||||
|
||||
Reference in New Issue
Block a user