Compare commits

...
10 changed files with 629 additions and 21 deletions
+15 -4
View File
@@ -58,7 +58,7 @@ ultimate source of truth.
- [x] Predeclare `let` and `const` bindings in every lexical scope, including program/block bodies, switch bodies, and
loop headers, so reads before initialization and self- or cross-referential initializers observe the JavaScript
temporal dead zone.
- [ ] Hoist function declarations accepted directly in switch cases.
- [x] Function declarations are hoisted across all cases of a `switch`, like any other statement list.
- [x] Computed object destructuring keys such as `const { [field]: value } = record`.
- [x] Object destructuring from arrays, such as `const { length } = values`.
- [x] Array binding and assignment destructuring from strings, Maps, Sets, URLSearchParams, custom synchronous
@@ -364,6 +364,17 @@ ultimate source of truth.
`entries`, `toString`, and `size`.
- [x] URL values serialize to their href; URLSearchParams serialize to `{}`.
## Web platform helpers
- [x] `atob` and `btoa` with forgiving-base64 decoding and WebIDL string conversion; invalid input throws an Error
named `InvalidCharacterError`, since there is no `DOMException`.
- [x] `crypto.randomUUID()`.
- [x] `structuredClone` over the data model: objects, arrays with holes, Date, RegExp (`lastIndex` reset), Map, Set,
URL, URLSearchParams, and Errors (name, message, and cause only); shared references stay shared within one
clone; functions, promises, and tool references throw an Error named `DataCloneError`.
- [ ] `crypto.getRandomValues` and `crypto.subtle`, `TextEncoder`/`TextDecoder`, and `Blob`: these need a binary
value type, which the JSON-like data model does not have yet.
## Errors and diagnostics
- [x] `Error`, `TypeError`, `RangeError`, `SyntaxError`, `ReferenceError`, `EvalError`, and `URIError`, callable with
@@ -380,6 +391,6 @@ ultimate source of truth.
shift them. The diagnostic names the rejected node type and attaches a short orientation to the supported
subset; this matrix is the full reference.
- [x] Model-visible host failure messages and underlying causes, including output-validation errors.
- [ ] Distinguish user-thrown failures from interpreter defects and explicit tool refusals from internal tool
failures; preserve those categories in caught errors, promise rejection handlers, and `Promise.allSettled`
reasons.
- [x] Caught errors do not distinguish user throws, interpreter failures, and tool failures; a program sees one
Error-shaped value with `name` and `message` in `catch`, rejection handlers, and `Promise.allSettled` reasons.
This is deliberate: the program should handle a failure the same way regardless of where it originated.
+1 -1
View File
@@ -138,6 +138,6 @@ const copy = (value: unknown, label: string, mode: Mode, depth: number, seen: Se
// Own data property regardless of the target's prototype, so a "__proto__" key on a host object or
// array never reaches the Object.prototype setter.
const define = (target: object, key: string, value: unknown): void => {
export const define = (target: object, key: string, value: unknown): void => {
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true })
}
@@ -11,6 +11,7 @@ import { regexpGlobal } from "../stdlib/regexp.js"
import { stringGlobal } from "../stdlib/string.js"
import { uriGlobal, urlGlobal, urlSearchParamsGlobal } from "../stdlib/url.js"
import { coercion, errorConstructors } from "../stdlib/value.js"
import { atobGlobal, btoaGlobal, cryptoGlobal, structuredCloneGlobal } from "../stdlib/web.js"
import { ToolReference } from "../tool-runtime.js"
import { errorGlobal } from "./errors.js"
import { HostFunction } from "./host.js"
@@ -71,5 +72,9 @@ export const globals = <R>(host: Host<R>): ReadonlyArray<readonly [string, unkno
["encodeURIComponent", uriGlobal("encodeURIComponent")],
["decodeURI", uriGlobal("decodeURI")],
["decodeURIComponent", uriGlobal("decodeURIComponent")],
["atob", atobGlobal],
["btoa", btoaGlobal],
["crypto", cryptoGlobal],
["structuredClone", structuredCloneGlobal],
...[...errorConstructors].map((name) => [name, errorGlobal(name, host.runner)] as const),
]
+14 -16
View File
@@ -171,6 +171,8 @@ const collectPatternNames = (pattern: Pattern, out: Array<string> = []): Array<s
}
// `var` names declared anywhere in a function body except inside nested functions, which own theirs.
// Memoized per body: a function's var names never change, and hoisting runs on every call.
const varNames = new WeakMap<ReadonlyArray<Statement | ModuleDeclaration>, ReadonlyArray<string>>()
const collectVarNames = (
node: Statement | ModuleDeclaration | null | undefined,
out: Array<string> = [],
@@ -446,12 +448,14 @@ class Frame<R> {
// Hoisted `var` bindings start undefined, or copy a same-named parameter. Function bodies hoist
// into their own scope above the parameters so closures in parameter defaults keep seeing outer names.
private hoistVars(statements: ReadonlyArray<Statement | ModuleDeclaration>, parameters?: Map<string, Binding>): void {
const names =
varNames.get(statements) ??
statements.reduce<Array<string>>((out, statement) => collectVarNames(statement, out), [])
varNames.set(statements, names)
const scope = this.scopes.current()
for (const statement of statements) {
for (const name of collectVarNames(statement)) {
if (scope.has(name)) continue
scope.set(name, { mutable: true, value: parameters?.get(name)?.value, initialized: true })
}
for (const name of names) {
if (scope.has(name)) continue
scope.set(name, { mutable: true, value: parameters?.get(name)?.value, initialized: true })
}
}
@@ -492,7 +496,9 @@ class Frame<R> {
self.scopes.push()
return yield* Effect.gen(function* () {
const cases = node.cases
self.predeclareLexical(cases.flatMap((branch) => branch.consequent))
const statements = cases.flatMap((branch) => branch.consequent)
self.predeclareLexical(statements)
self.hoistFunctions(statements)
let defaultIndex: number | undefined
let selected: number | undefined
for (const [index, branch] of cases.entries()) {
@@ -1649,16 +1655,8 @@ class Frame<R> {
})
if (fn.generator) return Effect.succeed(this.createGenerator(invocation, run, fn.async))
if (!fn.async) return run
// The initial yield assigns the promise before the body can self-resolve.
const box: { promise?: Values.Promise } = {}
return Effect.map(
this.createPromise(
Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, fn.body, box)),
),
(promise) => {
box.promise = promise
return promise
},
return this.runtime.promises.createWithSelf((self) =>
Effect.flatMap(run, (value) => resolvePromiseValue(invocation.runtime.runner, value, fn.body, self)),
)
}
+80
View File
@@ -0,0 +1,80 @@
import { define, type SafeObject } from "../data.js"
import { HostNamespace, sync } from "../interpreter/host.js"
import { type AstNode, InterpreterRuntimeError } from "../interpreter/model.js"
import { describeValue, isRuntimeReference } from "../interpreter/references.js"
import { Values } from "../values.js"
import { coerceToString, createErrorValue, errorBrandName } from "./value.js"
// WebIDL DOMString conversion: a missing argument is a TypeError, anything else stringifies.
const base64 = (name: "atob" | "btoa") =>
sync(name, (args, node) => {
if (args.length === 0) {
throw new InterpreterRuntimeError(`${name} requires 1 argument, but only 0 were provided.`, node).as("TypeError")
}
const input = coerceToString(args[0])
try {
return name === "atob" ? atob(input) : btoa(input)
} catch {
throw new InterpreterRuntimeError("The string contains invalid characters.", node).as("InvalidCharacterError")
}
})
export const atobGlobal = base64("atob")
export const btoaGlobal = base64("btoa")
export const cryptoGlobal = new HostNamespace("crypto", {
randomUUID: sync("crypto.randomUUID", () => crypto.randomUUID()),
})
// HTML structured clone over the data model: wrappers are copied, shared references stay shared within
// one clone, Errors keep only name, message, and cause, and RegExp lastIndex resets like the spec.
const cloneValue = (value: unknown, seen: Map<object, unknown>, node: AstNode): unknown => {
if (value === null || typeof value !== "object") return value
if (value instanceof Values.Promise || (isRuntimeReference(value) && !Values.isValue(value))) {
throw new InterpreterRuntimeError(`${describeValue(value)} could not be cloned.`, node).as("DataCloneError")
}
const existing = seen.get(value)
if (existing !== undefined) return existing
const remember = <T extends object>(copied: T): T => {
seen.set(value, copied)
return copied
}
if (value instanceof Values.Date) return remember(new Values.Date(value.time))
if (value instanceof Values.RegExp) return remember(new Values.RegExp(value.regex.source, value.regex.flags))
if (value instanceof Values.URL) return remember(new Values.URL(new URL(value.url.href)))
if (value instanceof Values.URLSearchParams) {
return remember(new Values.URLSearchParams(new URLSearchParams(value.params)))
}
if (value instanceof Values.Map) {
const copied = remember(new Values.Map())
for (const [key, item] of value.map) copied.map.set(cloneValue(key, seen, node), cloneValue(item, seen, node))
return copied
}
if (value instanceof Values.Set) {
const copied = remember(new Values.Set())
for (const item of value.set) copied.set.add(cloneValue(item, seen, node))
return copied
}
if (Array.isArray(value)) {
const copied = remember(new Array<unknown>(value.length))
for (const [key, item] of Object.entries(value)) define(copied, key, cloneValue(item, seen, node))
return copied
}
const brand = errorBrandName(value)
if (brand !== undefined) {
const error = value as { name?: unknown; message?: unknown; cause?: unknown }
const copied = remember(createErrorValue(brand, coerceToString(error.message)))
if (Object.hasOwn(value, "cause")) copied.cause = cloneValue(error.cause, seen, node)
return copied
}
const copied = remember(Object.create(null) as SafeObject)
for (const [key, item] of Object.entries(value)) define(copied, key, cloneValue(item, seen, node))
return copied
}
export const structuredCloneGlobal = sync("structuredClone", (args, node) => {
if (args.length === 0) {
throw new InterpreterRuntimeError("structuredClone requires a value to clone.", node).as("TypeError")
}
return cloneValue(args[0], new Map(), node)
})
+11
View File
@@ -0,0 +1,11 @@
# The 3-Clause BSD License
Copyright © web-platform-tests contributors
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+82
View File
@@ -0,0 +1,82 @@
[
["", []],
["abcd", [105, 183, 29]],
[" abcd", [105, 183, 29]],
["abcd ", [105, 183, 29]],
[" abcd===", null],
["abcd=== ", null],
["abcd ===", null],
["a", null],
["ab", [105]],
["abc", [105, 183]],
["abcde", null],
["𐀀", null],
["=", null],
["==", null],
["===", null],
["====", null],
["=====", null],
["a=", null],
["a==", null],
["a===", null],
["a====", null],
["a=====", null],
["ab=", null],
["ab==", [105]],
["ab===", null],
["ab====", null],
["ab=====", null],
["abc=", [105, 183]],
["abc==", null],
["abc===", null],
["abc====", null],
["abc=====", null],
["abcd=", null],
["abcd==", null],
["abcd===", null],
["abcd====", null],
["abcd=====", null],
["abcde=", null],
["abcde==", null],
["abcde===", null],
["abcde====", null],
["abcde=====", null],
["=a", null],
["=a=", null],
["a=b", null],
["a=b=", null],
["ab=c", null],
["ab=c=", null],
["abc=d", null],
["abc=d=", null],
["ab\u000Bcd", null],
["ab\u3000cd", null],
["ab\u3001cd", null],
["ab\tcd", [105, 183, 29]],
["ab\ncd", [105, 183, 29]],
["ab\fcd", [105, 183, 29]],
["ab\rcd", [105, 183, 29]],
["ab cd", [105, 183, 29]],
["ab\u00a0cd", null],
["ab\t\n\f\r cd", [105, 183, 29]],
[" \t\n\f\r ab\t\n\f\r cd\t\n\f\r ", [105, 183, 29]],
["ab\t\n\f\r =\t\n\f\r =\t\n\f\r ", [105]],
["A", null],
["/A", [252]],
["//A", [255, 240]],
["///A", [255, 255, 192]],
["////A", null],
["/", null],
["A/", [3]],
["AA/", [0, 15]],
["AAAA/", null],
["AAA/", [0, 0, 63]],
["\u0000nonsense", null],
["abcd\u0000nonsense", null],
["YQ", [97]],
["YR", [97]],
["~~", null],
["..", null],
["--", null],
["__", null]
]
@@ -0,0 +1,245 @@
/**
* Portions adapted from web-platform-tests at revision 863077959ca8c1a7ceecfbe2534b75d2527b9013:
* - html/webappapis/structured-clone/structured-clone-battery-of-tests.js
*
* Copyright © web-platform-tests contributors. Governed by the 3-Clause BSD license in LICENSE.wpt.
*
* The battery's `check(description, input, compare)` shape and its `compare_*` helpers are kept, run
* inside the interpreter. Ported: primitives, Array/Object of primitives, Date, RegExp, Error, sparse
* arrays, identical (shared) property values, and the index-property-plus-length object. Not portable:
* boxed primitives, BigInt, Blob/File/ImageData/ArrayBuffer/typed arrays (no binary values), circular
* references (rejected at insertion here), property descriptors and prototype properties (no
* defineProperty or prototypes), and the throwing-getter case (no getters). `assert_throws_dom` for
* `DataCloneError` becomes an `error.name` check.
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
return result.value
}
// The WPT harness, minus async: assertions push a failure description instead of throwing so one run
// reports every failing check.
const harness = `
const failures = []
const assert_equals = (a, b, m) => { if (!Object.is(a, b) && !(a !== a && b !== b)) failures.push((m ?? "") + ": " + String(a) + " !== " + String(b)) }
const assert_not_equals = (a, b, m) => { if (a === b) failures.push((m ?? "") + ": unexpectedly identical") }
const assert_true = (a, m) => { if (a !== true) failures.push((m ?? "") + ": not true") }
const assert_false = (a, m) => { if (a !== false) failures.push((m ?? "") + ": not false") }
let current = ""
function check(description, input, callback) {
current = description
const newInput = typeof input === "function" ? input() : input
const copy = structuredClone(newInput)
const before = failures.length
callback(copy, newInput)
for (let i = before; i < failures.length; i++) failures[i] = description + " — " + failures[i]
}
function compare_primitive(actual, input) { assert_equals(actual, input) }
function compare_Array(callback) {
return function (actual, input) {
assert_true(Array.isArray(actual), "instanceof Array")
assert_not_equals(actual, input)
assert_equals(actual.length, input.length, "length")
callback(actual, input)
}
}
function compare_Object(callback) {
return function (actual, input) {
assert_true(actual instanceof Object, "instanceof Object")
assert_false(Array.isArray(actual), "instanceof Array")
assert_not_equals(actual, input)
callback(actual, input)
}
}
function enumerate_props(compare_func) {
return function (actual, input) { for (const x in input) compare_func(actual[x], input[x]) }
}
`
describe("structuredClone WPT battery", () => {
test("primitives, and arrays and objects of primitives", async () => {
expect(
await value(`
${harness}
check('primitive undefined', undefined, compare_primitive)
check('primitive null', null, compare_primitive)
check('primitive true', true, compare_primitive)
check('primitive false', false, compare_primitive)
check('primitive string, empty string', '', compare_primitive)
check('primitive string, lone high surrogate', '\\uD800', compare_primitive)
check('primitive string, lone low surrogate', '\\uDC00', compare_primitive)
check('primitive string, NUL', '\\u0000', compare_primitive)
check('primitive string, astral character', '\\uDBFF\\uDFFD', compare_primitive)
check('primitive number, 0.2', 0.2, compare_primitive)
check('primitive number, 0', 0, compare_primitive)
check('primitive number, -0', -0, compare_primitive)
check('primitive number, NaN', NaN, compare_primitive)
check('primitive number, Infinity', Infinity, compare_primitive)
check('primitive number, -Infinity', -Infinity, compare_primitive)
check('primitive number, 9007199254740992', 9007199254740992, compare_primitive)
check('primitive number, -9007199254740992', -9007199254740992, compare_primitive)
check('primitive number, 9007199254740994', 9007199254740994, compare_primitive)
check('primitive number, -9007199254740994', -9007199254740994, compare_primitive)
check('Array primitives', [undefined, null, true, false, '', '\\uD800', '\\uDC00', '\\u0000', '\\uDBFF\\uDFFD',
0.2, 0, -0, NaN, Infinity, -Infinity, 9007199254740992, -9007199254740992, 9007199254740994, -9007199254740994],
compare_Array(enumerate_props(compare_primitive)))
check('Object primitives', { 'undefined': undefined, 'null': null, 'true': true, 'false': false, 'empty': '',
'high surrogate': '\\uD800', 'low surrogate': '\\uDC00', 'nul': '\\u0000', 'astral': '\\uDBFF\\uDFFD',
'0.2': 0.2, '0': 0, '-0': -0, 'NaN': NaN, 'Infinity': Infinity, '-Infinity': -Infinity,
'9007199254740992': 9007199254740992, '-9007199254740992': -9007199254740992,
'9007199254740994': 9007199254740994, '-9007199254740994': -9007199254740994 },
compare_Object(enumerate_props(compare_primitive)))
return failures
`),
).toEqual([])
})
test("Date", async () => {
expect(
await value(`
${harness}
function compare_Date(actual, input) {
assert_true(actual instanceof Date, 'instanceof Date')
assert_equals(Number(actual), Number(input), 'converted to primitive')
assert_not_equals(actual, input)
}
check('Date 0', new Date(0), compare_Date)
check('Date -0', new Date(-0), compare_Date)
check('Date -8.64e15', new Date(-8.64e15), compare_Date)
check('Date 8.64e15', new Date(8.64e15), compare_Date)
check('Array Date objects', [new Date(0), new Date(-0), new Date(-8.64e15), new Date(8.64e15)],
compare_Array(enumerate_props(compare_Date)))
check('Object Date objects', { '0': new Date(0), '-0': new Date(-0), '-8.64e15': new Date(-8.64e15), '8.64e15': new Date(8.64e15) },
compare_Object(enumerate_props(compare_Date)))
return failures
`),
).toEqual([])
})
test("RegExp: flags copied, lastIndex reset, source escaped", async () => {
expect(
await value(`
${harness}
function compare_RegExp(expected_source) {
return function (actual, input) {
assert_true(actual instanceof RegExp, 'instanceof RegExp')
assert_equals(actual.global, input.global, 'global')
assert_equals(actual.ignoreCase, input.ignoreCase, 'ignoreCase')
assert_equals(actual.multiline, input.multiline, 'multiline')
assert_equals(actual.source, expected_source, 'source')
assert_equals(actual.sticky, input.sticky, 'sticky')
assert_equals(actual.unicode, input.unicode, 'unicode')
assert_equals(actual.lastIndex, 0, 'lastIndex')
assert_not_equals(actual, input)
}
}
function func_RegExp_flags_lastIndex() {
const r = /foo/gim
r.lastIndex = 2
return r
}
function func_RegExp_sticky() { return new RegExp('foo', 'y') }
function func_RegExp_unicode() { return new RegExp('foo', 'u') }
check('RegExp flags and lastIndex', func_RegExp_flags_lastIndex, compare_RegExp('foo'))
check('RegExp sticky flag', func_RegExp_sticky, compare_RegExp('foo'))
check('RegExp unicode flag', func_RegExp_unicode, compare_RegExp('foo'))
check('RegExp empty', new RegExp(''), compare_RegExp('(?:)'))
check('RegExp slash', new RegExp('/'), compare_RegExp('\\\\/'))
check('RegExp new line', new RegExp('\\n'), compare_RegExp('\\\\n'))
check('Array RegExp object, RegExp flags and lastIndex', [func_RegExp_flags_lastIndex()], compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp sticky flag', function () { return [func_RegExp_sticky()] }, compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp unicode flag', function () { return [func_RegExp_unicode()] }, compare_Array(enumerate_props(compare_RegExp('foo'))))
check('Array RegExp object, RegExp empty', [new RegExp('')], compare_Array(enumerate_props(compare_RegExp('(?:)'))))
check('Array RegExp object, RegExp slash', [new RegExp('/')], compare_Array(enumerate_props(compare_RegExp('\\\\/'))))
check('Array RegExp object, RegExp new line', [new RegExp('\\n')], compare_Array(enumerate_props(compare_RegExp('\\\\n'))))
check('Object RegExp object, RegExp flags and lastIndex', { 'x': func_RegExp_flags_lastIndex() }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp sticky flag', function () { return { 'x': func_RegExp_sticky() } }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp unicode flag', function () { return { 'x': func_RegExp_unicode() } }, compare_Object(enumerate_props(compare_RegExp('foo'))))
check('Object RegExp object, RegExp empty', { 'x': new RegExp('') }, compare_Object(enumerate_props(compare_RegExp('(?:)'))))
check('Object RegExp object, RegExp slash', { 'x': new RegExp('/') }, compare_Object(enumerate_props(compare_RegExp('\\\\/'))))
check('Object RegExp object, RegExp new line', { 'x': new RegExp('\\n') }, compare_Object(enumerate_props(compare_RegExp('\\\\n'))))
return failures
`),
).toEqual([])
})
test("Error: name and message kept, custom properties dropped", async () => {
expect(
await value(`
${harness}
function compare_Error(actual, input) {
assert_true(actual instanceof Error, "Checking instanceof")
assert_equals(actual.name, input.name, "Checking name")
assert_equals(Object.hasOwn(actual, "message"), Object.hasOwn(input, "message"), "Checking message existence")
assert_equals(actual.message, input.message, "Checking message")
assert_equals(actual.foo, undefined, "Checking for absence of custom property")
}
check('Empty Error object', new Error(), compare_Error)
for (const constructor of [Error, RangeError, ReferenceError, SyntaxError, TypeError, URIError]) {
check(constructor.name, () => {
const error = new constructor("Error message here")
error.foo = "testing"
return error
}, compare_Error)
}
return failures
`),
).toEqual([])
})
test("sparse arrays, index-property objects, and identical property values", async () => {
expect(
await value(`
${harness}
check('Array sparse', new Array(10), compare_Array(enumerate_props(compare_primitive)))
check('Object with index property and length', { '0': 'foo', 'length': 1 }, compare_Object(enumerate_props(compare_primitive)))
function check_identical_property_values(prop1, prop2) {
return function (actual) { assert_equals(actual[prop1], actual[prop2]) }
}
check('Array with identical property values', function () {
const obj = {}
return [obj, obj]
}, compare_Array(check_identical_property_values('0', '1')))
check('Object with identical property values', function () {
const obj = {}
return { 'x': obj, 'y': obj }
}, compare_Object(check_identical_property_values('x', 'y')))
return failures
`),
).toEqual([])
})
})
describe("structuredClone beyond the WPT battery", () => {
test("Map, Set, URL, and URLSearchParams are copied, with shared references preserved across containers", async () => {
expect(
await value(`
const shared = { n: 1 }
const input = { m: new Map([[shared, shared]]), s: new Set([shared]), u: new URL("https://a.b/c?d=1") }
const copy = structuredClone(input)
const [[key, item]] = [...copy.m]
copy.u.searchParams.set("d", "2")
return [
copy.m !== input.m, key !== shared, key === item, key === [...copy.s][0],
copy.u !== input.u, input.u.href, copy.u.href,
]
`),
).toEqual([true, true, true, true, true, "https://a.b/c?d=1", "https://a.b/c?d=2"])
})
test("functions, promises, and tool references throw DataCloneError", async () => {
expect(
await value(`
return [() => 1, Promise.resolve(1), tools, Math, { nested: [() => 1] }].map((input) => {
try { structuredClone(input); return "cloned" } catch (error) { return error.name }
})
`),
).toEqual(Array(5).fill("DataCloneError"))
expect(await value(`try { structuredClone() } catch (error) { return error.name }`)).toBe("TypeError")
})
})
@@ -233,3 +233,10 @@ describe("var semantics beyond Test262", () => {
expect(await value(`function* gen() { var t = 1; yield t; var t = 2; yield t } return [...gen()]`)).toEqual([1, 2])
})
})
describe("switch case function hoisting", () => {
test("function declarations are visible across all cases before their statement runs", async () => {
expect(await value(`switch (1) { case 1: return foo(); function foo() { return "hoisted" } }`)).toBe("hoisted")
expect(await value(`switch (2) { case 1: function foo() { return "a" } break; case 2: return foo() }`)).toBe("a")
})
})
+169
View File
@@ -0,0 +1,169 @@
/**
* Portions adapted from web-platform-tests at revision 863077959ca8c1a7ceecfbe2534b75d2527b9013:
* - html/webappapis/atob/base64.any.js (btoa reference encoder, input list, and atob WebIDL cases)
* - fetch/data-urls/resources/base64.json (copied to fixtures/wpt-base64.json)
* - WebCryptoAPI/randomUUID.https.any.js
*
* Copyright © web-platform-tests contributors. Governed by the 3-Clause BSD license in LICENSE.wpt.
*
* `assert_throws_dom("InvalidCharacterError", …)` becomes a check on `error.name`: CodeMode has no
* DOMException, so the name is carried on a plain Error.
*/
import { describe, expect, test } from "bun:test"
import { Effect } from "effect"
import { CodeMode } from "../src/index.js"
const base64Cases = (await Bun.file(new URL("./fixtures/wpt-base64.json", import.meta.url)).json()) as Array<
[string, Array<number> | null]
>
const value = async (code: string) => {
const result = await Effect.runPromise(CodeMode.execute({ code, tools: {} }))
if (!result.ok) throw new Error(`expected success, got ${result.error.kind}: ${result.error.message}`)
return result.value
}
// The reference encoder from base64.any.js, run inside the interpreter so btoa is checked against
// an independent implementation rather than against the host's btoa.
const referenceEncoder = `
function btoaLookup(idx) {
if (idx < 26) return String.fromCharCode(idx + "A".charCodeAt(0))
if (idx < 52) return String.fromCharCode(idx - 26 + "a".charCodeAt(0))
if (idx < 62) return String.fromCharCode(idx - 52 + "0".charCodeAt(0))
if (idx == 62) return "+"
if (idx == 63) return "/"
}
function mybtoa(s) {
s = String(s)
for (var i = 0; i < s.length; i++) if (s.charCodeAt(i) > 255) return "INVALID_CHARACTER_ERR"
var out = ""
for (var i = 0; i < s.length; i += 3) {
var groupsOfSix = [undefined, undefined, undefined, undefined]
groupsOfSix[0] = s.charCodeAt(i) >> 2
groupsOfSix[1] = (s.charCodeAt(i) & 0x03) << 4
if (s.length > i + 1) {
groupsOfSix[1] |= s.charCodeAt(i + 1) >> 4
groupsOfSix[2] = (s.charCodeAt(i + 1) & 0x0f) << 2
}
if (s.length > i + 2) {
groupsOfSix[2] |= s.charCodeAt(i + 2) >> 6
groupsOfSix[3] = s.charCodeAt(i + 2) & 0x3f
}
for (var j = 0; j < groupsOfSix.length; j++) {
out += typeof groupsOfSix[j] == "undefined" ? "=" : btoaLookup(groupsOfSix[j])
}
}
return out
}
function testBtoa(input) {
var expected = mybtoa(input)
if (expected === "INVALID_CHARACTER_ERR") {
try { btoa(input) } catch (error) { return error.name === "InvalidCharacterError" ? "ok" : error.name }
return "did not throw"
}
if (btoa(input) !== expected) return "btoa mismatch"
if (atob(btoa(input)) !== String(input)) return "roundtrip mismatch"
return "ok"
}
`
describe("btoa WPT parity (html/webappapis/atob/base64.any.js)", () => {
test("every input encodes like the reference encoder and round-trips through atob", async () => {
expect(
await value(`
${referenceEncoder}
var tests = ["עברית", "", "ab", "abc", "abcd", "abcde", "\\xff\\xff\\xc0", "\\0a", "a\\0b",
undefined, null, 7, 12, 1.5, true, false, NaN, +Infinity, -Infinity, 0, -0]
for (var i = 0; i < 258; i++) tests.push(String.fromCharCode(i))
tests.push(String.fromCharCode(10000), String.fromCharCode(65534), String.fromCharCode(65535))
tests.push(String.fromCharCode(0xd800, 0xdc00))
var everything = ""
for (var i = 0; i < 256; i++) everything += String.fromCharCode(i)
tests.push(everything)
return tests.map(testBtoa).filter((outcome) => outcome !== "ok")
`),
).toEqual([])
})
})
describe("atob WPT parity (fetch/data-urls/resources/base64.json)", () => {
const idlCases: Array<[unknown, Array<number> | null]> = [
[undefined, null],
[null, [158, 233, 101]],
[7, null],
[12, [215]],
[1.5, null],
[true, [182, 187]],
[false, null],
[NaN, [53, 163]],
[Infinity, [34, 119, 226, 158, 43, 114]],
[-Infinity, null],
[0, null],
[-0, null],
]
test(`${base64Cases.length} forgiving-base64 inputs decode to the expected bytes or throw InvalidCharacterError`, async () => {
expect(
await value(`
const cases = ${JSON.stringify(base64Cases)}
return cases.flatMap(([input, output]) => {
try {
const result = atob(input)
if (output === null) return [[input, "expected throw"]]
const bytes = Array.from({ length: result.length }, (_, i) => result.charCodeAt(i))
return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[input, bytes]]
} catch (error) {
return output === null && error.name === "InvalidCharacterError" ? [] : [[input, error.name]]
}
})
`),
).toEqual([])
})
test("WebIDL argument conversion stringifies non-string inputs", async () => {
const literal = (input: unknown) =>
Object.is(input, -0)
? "-0"
: typeof input === "number" || input === undefined
? String(input)
: JSON.stringify(input)
expect(
await value(`
const cases = [${idlCases.map(([input, output]) => `[${literal(input)}, ${JSON.stringify(output)}]`).join(",")}]
return cases.flatMap(([input, output]) => {
try {
const result = atob(input)
if (output === null) return [[String(input), "expected throw"]]
// The source loop checks only the listed prefix of the decoded bytes.
const bytes = output.map((_, i) => result.charCodeAt(i))
return JSON.stringify(bytes) === JSON.stringify(output) ? [] : [[String(input), bytes]]
} catch (error) {
return output === null && error.name === "InvalidCharacterError" ? [] : [[String(input), error.name]]
}
})
`),
).toEqual([])
})
})
describe("crypto.randomUUID WPT parity (WebCryptoAPI/randomUUID.https.any.js)", () => {
test("namespace format, version, and variant bits over 256 iterations without collision", async () => {
expect(
await value(`
const uuids = new Set()
const randomUUID = () => {
const uuid = crypto.randomUUID()
if (uuids.has(uuid)) throw new Error("uuid collision " + uuid)
uuids.add(uuid)
return uuid
}
const UUIDRegex = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
let format = true, version = true, variant = true
for (let i = 0; i < 256; i++) format = format && UUIDRegex.test(randomUUID())
for (let i = 0; i < 256; i++) version = version && (parseInt(randomUUID().split("-")[2].slice(0, 2), 16) & 0b11110000) === 0b01000000
for (let i = 0; i < 256; i++) variant = variant && (parseInt(randomUUID().split("-")[3].slice(0, 2), 16) & 0b11000000) === 0b10000000
return [format, version, variant, uuids.size]
`),
).toEqual([true, true, true, 768])
})
})