From cd6efb0a35b80dbdb7b5b2e3c13a061ddbd399cb Mon Sep 17 00:00:00 2001 From: Simon Klee Date: Sat, 28 Nov 2026 22:54:24 +0100 Subject: [PATCH] feat: erase type-only TypeScript syntax in both implementations Add opt-in erasable TypeScript mode via typescript: true on compile, program, execute, and parseProgram (CompileOptions::typescript and ProgramOptions::typescript in Rust, with Runtime::compile_with). Type-only syntax is erased at compile time in both the Acorn-based TypeScript reference and the oxc-based Rust compiler: type annotations, interface, type, as, satisfies, non-null !, generics and instantiation expressions, import type / export type, declare ambient statements, type-only namespace, overload signatures, and class member modifiers. Non-erasable syntax with runtime meaning (enum, namespace with values, constructor parameter properties, decorators, import =, export =, and expr assertions) fails at compile time with UnsupportedSyntax at its exact line and column. Snapshots record typescript: true on saved sources so TypeScript runs suspend and resume across both runtimes. Includes TS unit tests, a 46-case reference-recorded parity suite (rust/conformance/typescript.ts -> typescript.json -> tests/typescript.rs), and a round-trip conformance case (typescript-erasure). --- README.md | 6 +- interpreter-support.md | 8 +- rust/README.md | 13 +- rust/bench/tests/conformance.rs | 4 +- rust/conformance/cases/typescript-erasure.js | 71 + .../conformance/cases/typescript-erasure.json | 13 + rust/conformance/generate.ts | 5 +- rust/conformance/typescript.json | 40 + rust/conformance/typescript.ts | 407 +++ rust/crates/psychoscript/src/compiler.rs | 680 ++++- rust/crates/psychoscript/src/lib.rs | 3 +- rust/crates/psychoscript/src/nesting.rs | 110 +- rust/crates/psychoscript/src/program.rs | 5 +- rust/crates/psychoscript/src/run.rs | 34 +- rust/crates/psychoscript/src/runtime.rs | 41 +- rust/crates/psychoscript/src/snapshot.rs | 22 +- rust/crates/psychoscript/src/test262.rs | 2 +- rust/crates/psychoscript/tests/typescript.rs | 247 ++ src/compiler/scope.ts | 24 +- src/compiler/typescript.ts | 2425 +++++++++++++++++ src/effect/runtime.ts | 9 +- src/runtime.ts | 7 +- src/runtime/execute.ts | 55 +- src/runtime/options.ts | 13 +- src/runtime/source.ts | 1 + src/snapshot.ts | 5 +- src/snapshot/snapshot.ts | 5 + test/typescript.test.ts | 155 ++ 28 files changed, 4227 insertions(+), 183 deletions(-) create mode 100644 rust/conformance/cases/typescript-erasure.js create mode 100644 rust/conformance/cases/typescript-erasure.json create mode 100644 rust/conformance/typescript.json create mode 100644 rust/conformance/typescript.ts create mode 100644 rust/crates/psychoscript/tests/typescript.rs create mode 100644 src/compiler/typescript.ts create mode 100644 test/typescript.test.ts diff --git a/README.md b/README.md index eb3bb76b..be042f2d 100644 --- a/README.md +++ b/README.md @@ -343,7 +343,11 @@ Unsupported syntax fails before the program runs, with a hint. `Symbol.toStringTag` exist). - **Binary and weak-reference built-ins:** typed arrays other than `Uint8Array`, resizable or shared buffers, `WeakRef`, and `FinalizationRegistry`. -- **TypeScript syntax:** programs must be plain JavaScript. +- **Non-erasable TypeScript syntax:** pass `{ typescript: true }` to `execute`, `program`, `compile` or + `parseProgram` to run erasable TypeScript (type annotations, `interface`, `type`, `as`, `satisfies`, `!`, + generics, `import type`/`export type`, `declare`, type-only `namespace`, and class member modifiers are erased at + compile time). Syntax with runtime meaning (`enum`, `namespace` with values, parameter properties, decorators, + `import x = require`, `export =`, and `expr` assertions) is refused with `UnsupportedSyntax` at its line. ## Determinism diff --git a/interpreter-support.md b/interpreter-support.md index 498457f0..9d1b1e55 100644 --- a/interpreter-support.md +++ b/interpreter-support.md @@ -15,7 +15,13 @@ the ultimate source of truth. Upstream test262 files run verbatim from `test/tes ## Source and execution model - [x] JavaScript parsed with the latest syntax accepted by Acorn, then restricted by the interpreter allowlist. - TypeScript-only syntax is rejected rather than stripped before execution. +- [x] Optional erasable TypeScript (`{ typescript: true }` on `execute`, `program`, `compile`, and `parseProgram`, + or `CompileOptions::typescript(true)` / `ProgramOptions::typescript(true)` in Rust): type-only syntax + (annotations, `interface`, `type`, `as`, `satisfies`, `!`, generics, `import type`/`export type`, `declare`, + type-only `namespace`, overload signatures, and class member modifiers) is erased at compile time; non-erasable + syntax with runtime meaning (`enum`, `namespace` with values, constructor parameter properties, decorators, + `import =`, `export =`, and `expr` assertions) fails at compile time with `UnsupportedSyntax` at its line. + Snapshots record `typescript: true` on saved sources so TypeScript runs suspend and resume cleanly. - [x] Top-level `await` and `return` through the program's implicit async-function scope. - [x] Explicit `return`, final top-level expression as a REPL-style result, and `null` when no value is produced. - [x] The result boundary is `JSON.stringify` plus a short table. The program result crosses as diff --git a/rust/README.md b/rust/README.md index 181bf8a4..0477a70f 100644 --- a/rust/README.md +++ b/rust/README.md @@ -50,7 +50,8 @@ let mesh = HostFunction::new(|_, _| HostValue::TypedArray(TypedArray::from_f32(& | `Host.fn`, `Host.durableFn`, `Host.namespace` | `HostFunction`, `DurableFunction`, `Namespace` | | `Host.fail`, `Host.missing` | `Failure::new`, `Failure::missing` | | `properties` of `Host.fn`, `Host.durableFn` | `HostFunction::properties`, `DurableFunction::properties` | -| `runtime.execute`, `runtime.program`, `runtime.compile`, `runtime.resume` | `execute`/`execute_async`, `program`, `compile`, `resume`/`resume_bytes` | +| `runtime.execute`, `runtime.program`, `runtime.compile`, `runtime.resume` | `execute`/`execute_with`/`execute_async`, `program`, `compile`/`compile_with`, `resume`/`resume_bytes` | +| `CompileOptions { typescript }`, `ProgramOptions { typescript }` | `CompileOptions::typescript`, `ProgramOptions::typescript` | | `toBytes`, `fromBytes` | `to_bytes`, `from_bytes` | | `limits.timeoutMs`, `limits.maxOutputBytes` | `Limits::timeout_ms`, `Limits::max_output_bytes` | | a host tag's `strings.raw` | `Call::raw_strings` | @@ -105,7 +106,7 @@ After a change to the TypeScript reference, regenerate the recordings and commit them pass: ```sh -bun conformance/generate.ts && bun conformance/host.ts && bun conformance/boundary.ts && bun conformance/streaming.ts +bun conformance/generate.ts && bun conformance/host.ts && bun conformance/boundary.ts && bun conformance/streaming.ts && bun conformance/typescript.ts bun conformance/date-locale.ts # the Date locale matrix, its expected output and its differences from ICU4X bun conformance/number-locale.ts # the same for Number and BigInt toLocaleString ``` @@ -117,8 +118,8 @@ reference, never from hand: - `conformance/cases/*.js` → `.json` (`generate.ts`), replayed by `bench/tests/conformance.rs`, also in round-trip mode, which saves and restores every run at each host stop and loop slice. -- `conformance/host.json` (`host.ts`), `boundary.json` (`boundary.ts`) and `streaming.json` (`streaming.ts`), replayed - by `crates/psychoscript/tests/`. +- `conformance/host.json` (`host.ts`), `boundary.json` (`boundary.ts`), `streaming.json` (`streaming.ts`) and + `typescript.json` (`typescript.ts`), replayed by `crates/psychoscript/tests/`. - Rust-only features have no reference: their expected results are written in Rust's own tests (`crates/psychoscript/tests/heap.rs`, `clock.rs`, `typed.rs`, `host_recording.rs`, `value_depth.rs`; the programs of `tests/cases/*.js` also run in round-trip mode). @@ -132,6 +133,10 @@ workflow. The cases marked `@platform "linux"` depend on the system libm and are Known differences: - A saved state resumes only in the implementation and build that saved it: the snapshot formats differ. +- In TypeScript mode, Rust also refuses what oxc's own TypeScript checks refuse, as a `ParseError`: a class member + declared twice, a required parameter after an optional one, `abstract` in a class that isn't, a second declaration + of a `declare`d name or a type alias. The reference skips types without checking them and runs these; `tsc` + reports them all. - Date's `toLocaleString`, `toLocaleDateString` and `toLocaleTimeString` format any locale and `Intl.DateTimeFormat` options through ICU4X rather than the host ICU4C: the common cases — and every error kind and message — match, and the rest render ICU4X's closest output. The differences are recorded by `conformance/date-locale.ts` in diff --git a/rust/bench/tests/conformance.rs b/rust/bench/tests/conformance.rs index 0137b78c..1bdaed9f 100644 --- a/rust/bench/tests/conformance.rs +++ b/rust/bench/tests/conformance.rs @@ -47,7 +47,9 @@ fn check(name: &str, code: &str, expected: &Json, future: bool) -> Result<(), St }, }; let rt = runtime(limits, translate); - let options = ProgramOptions::new().bindings(bindings); + let options = ProgramOptions::new() + .bindings(bindings) + .typescript(expected["typescript"].as_bool().unwrap_or(false)); let run = || match future { true => drive(rt.execute_async(code, &options)).unwrap_or_else(|i| psychoscript::Outcome { result: Err(psychoscript::Diagnostic { diff --git a/rust/conformance/cases/typescript-erasure.js b/rust/conformance/cases/typescript-erasure.js new file mode 100644 index 00000000..6ff16fb8 --- /dev/null +++ b/rust/conformance/cases/typescript-erasure.js @@ -0,0 +1,71 @@ +// @typescript true +// Erasable TypeScript: annotations, interfaces, types, generics, as/satisfies/!, import/export type, declare, +// class modifiers, overloads, and async host calls (also exercised under round-trip snapshotting). +import type { Missing } from "does-not-exist" +import { type OnlyType } from "also-does-not-exist" +export type { Missing } +export interface ExportedShape { id: number } +export type ExportedAlias = string +export declare const ignoredAmbient: number + +declare const tools: { echo: (x: unknown) => Promise } +declare enum AmbientEnum { A, B } +declare namespace AmbientNs { const x: number } + +interface Boxed { + readonly value: T +} + +type Pair = readonly [A, B] + +namespace TypeOnly { + export type Tag = "ok" + export interface Wrapped { inner: T } +} + +function add(a: number, b: number): number +function add(a: string, b: string): string +function add(a: any, b: any): any { + return a + b +} + +abstract class Base { + public readonly kind: TypeOnly.Tag = "ok" + declare ghost: number + [key: string]: unknown + protected v: T + protected constructor(v: T) { + this.v = v + } + public abstract get(): T +} + +class Box extends Base implements Boxed { + public readonly value: T + constructor(v: T) + constructor(v: T) { + super(v) + this.value = v + } + public override get(): T { + return this.v + } +} + +const id = (x: T): T => x +const asyncId = async (x: T): Promise => (await tools.echo(x)) as T + +let total: number = 0 +for (let i: number = 1; i <= 3; i++) { + total += await asyncId(i) +} + +const b = new Box(total) +const pair = [b.get(), add(10, 20)] as const satisfies Pair +const maybe: { n?: number } = { n: pair[0]! + pair[1]! } +return { + kind: b.kind, + hasGhost: "ghost" in b, + sum: maybe.n!, + generic: id("ts"), +} diff --git a/rust/conformance/cases/typescript-erasure.json b/rust/conformance/cases/typescript-erasure.json new file mode 100644 index 00000000..4b7ce94b --- /dev/null +++ b/rust/conformance/cases/typescript-erasure.json @@ -0,0 +1,13 @@ +{ + "bindings": {}, + "typescript": true, + "ok": true, + "value": { + "kind": "ok", + "hasGhost": false, + "sum": 30, + "generic": "ts" + }, + "logs": [], + "metadata": null +} diff --git a/rust/conformance/generate.ts b/rust/conformance/generate.ts index 43c94fca..a46e29bd 100644 --- a/rust/conformance/generate.ts +++ b/rust/conformance/generate.ts @@ -13,6 +13,7 @@ // // @limits {"timeout_ms": 50, "max_output_bytes": 9} the runtime's `limits` (default none) // // @translate {"functions": "drop", "promises": "await"} the runtime's `translate` (default the reference's: // both "error") +// // @typescript true parse the source as erasable TypeScript (default false) // // @platform "linux" // A case with @platform depends on the system libm or compiler, so it is recorded and checked only on that platform // (`process.platform`). Elsewhere this keeps its recorded outcome but rewrites it in the current format, and fails @@ -88,6 +89,7 @@ for (const name of names) { const bindings = header(code, "bindings") ?? {} const limits = header(code, "limits") const translate = header(code, "translate") + const typescript = header(code, "typescript") === true if (platform !== undefined && platform !== process.platform) { console.log( `${name.padEnd(36)} ${refreshSkipped(name, { bindings, limits, translate }) ? "reformatted" : "skipped"} (${platform} only)`, @@ -106,11 +108,12 @@ for (const name of names) { }), ...(translate === undefined ? {} : { translate }), }) - const result = await Effect.runPromise(runtime.execute(code, { bindings })) + const result = await Effect.runPromise(runtime.execute(code, { bindings, ...(typescript ? { typescript: true } : {}) })) const expected = { bindings, ...(limits === undefined ? {} : { limits }), ...(translate === undefined ? {} : { translate }), + ...(typescript ? { typescript: true } : {}), ...(result.ok ? { ok: true, value: result.value } : { ok: false, kind: result.error.kind }), logs: result.logs ?? [], metadata: result.metadata, diff --git a/rust/conformance/typescript.json b/rust/conformance/typescript.json new file mode 100644 index 00000000..c0724124 --- /dev/null +++ b/rust/conformance/typescript.json @@ -0,0 +1,40 @@ +{ + "cases": [ + {"name":"var annotations and definite assignment","code":"const x: number = 1\nlet y: string = \"hi\"\nlet z!: boolean\nz = true\nvar w: number | null = null\nconst { a, b = 2 }: { a: number; b?: number } = { a: 5 }\nconst [first, second]: [string, number] = [\"k\", 9]\nreturn [x, y, z, w, a, b, first, second]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[1,"hi",true,null,5,2,"k",9],"logs":[]}}, + {"name":"interface, type aliases, and type/value name merging","code":"interface Base { id: number }\ninterface User extends Base {\n readonly name: string\n meta?: T\n (x: number): string\n new (x: number): object\n [key: string]: unknown\n}\ntype ID = string | number\ntype Mapped = { -readonly [K in keyof T as `get_${string & K}`]-?: T[K] extends number ? string : boolean }\ntype Tuple = [first: number, second?: string, ...rest: boolean[]]\nconst obj = { a: 1, b: \"x\" }\ntype Key = keyof typeof obj\nconst k: Key = \"a\"\nconst u: Pick, \"id\" | \"name\"> = { id: 1, name: \"ada\" }\ntype Inferred = T extends infer Q extends string ? Q : never\ntype Merged = { a: number }\nconst Merged = 42\ninterface Bar { x: number }\nclass Bar { x = 7 }\nreturn [k, u, Merged, new Bar().x]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":["a",{"id":1,"name":"ada"},42,7],"logs":[]}}, + {"name":"as and satisfies expressions and precedence","code":"const o = { a: 1 as number, b: \"x\" } satisfies Record\nconst sum = (o.a as number) + 1\nconst sum2 = 1 + 2 as number\nconst eq = o.a as number === 1\nconst cmp1 = o.a as number < 2\nconst cmp2 = 0 < o.a as number\nconst chained = o.a as unknown as number\nconst lit = { x: 1, y: [2, 3] } as const\nlet target: unknown = 0\n;(target as any) = 5\ntarget as any = 7\nreturn [sum, sum2, eq, cmp1, cmp2, chained, lit.x, target]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[2,3,true,true,true,1,1,7],"logs":[]}}, + {"name":"non-null assertions in expressions chains calls and assignments","code":"const o: { f?: (x: number) => number; n?: { v: number }; k?: number } = {\n v: 100,\n f(this: { v?: number }, x: number): number { return (this.v ?? 0) + x },\n n: { v: 5 },\n k: 1,\n} as any\nconst a = o.f!(3)\nconst b = o.n!.v\nconst c = o?.n!.v\nconst d = o.n!!.v\nlet x: number | null = 1\nx! = 2\nx!++\nconst obj: { a?: number; b?: number } = { a: 10, b: 20 }\nobj.a! += 5\nlet p: number | null = 0\nlet q: number | null = 0\n;[p!, q!] = [7, 8]\n;({ a: p! } = { a: 9 })\ndelete o!.k\nclass Sup { v = 1 }\nclass Sub extends Sup { m() { super.v! = 5; super.v!++; return this.v } }\nreturn [a, b, c, d, x, obj.a, p, q, \"k\" in o, new Sub().m()]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[103,5,5,5,3,15,9,8,false,null],"logs":[]}}, + {"name":"generics functions arrows classes calls new tagged templates and instantiation","code":"function id(x: T, y?: U): [T, U | undefined] { return [x, y] }\nconst f = (x: T): T => x\nconst f2 = (x: T): T => x\nconst af = async (x: T): Promise => x\nconst fnExpr = function(x: T): T { return x }\nconst g = id\nconst opt: { fn?: (x: T) => T } = { fn: id }\nconst map = new Map>([[\"a\", [1, 2]]])\nconst nested: Record>> = {}\ntype Defaulted> = T\nconst defVal: Defaulted = [3]\nfunction tag(s: TemplateStringsArray, v: T): [string, T] { return [s[0]!, v] }\nreturn [\n id(1, 2),\n f(\"ok\"),\n f2(\"const\"),\n await af(4),\n fnExpr(true),\n g(5),\n opt.fn?.(6),\n map.get(\"a\"),\n Object.keys(nested),\n defVal,\n tag`hi ${7 as number}`,\n]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[[1,2],"ok","const",4,true,[5,null],[6,null],[1,2],[],[3],["hi ",7]],"logs":[]}}, + {"name":"generic vs comparison and ternary disambiguation","code":"const a = 1, b = 2, c = 0\nconst cond = true\nconst paren = cond ? (a) : b => b\nconst typed = cond ? (x: number): number => x + 1 : y => y\nconst body = cond ? x => (a) : y => y\nreturn [a < b > c, a < b > -1, cond ? (1) : 2, (false ? 1 : 2), paren, typed(1), body(0)]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[true,true,1,2,1,2,1],"logs":[]}}, + {"name":"top-level await and for await","code":"const seen: number[] = []\nfor await (const n of [1, 2] as number[]) seen.push(n)\nreturn [seen, await Promise.resolve(3 as number)]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[[1,2],3],"logs":[]}}, + {"name":"typed arrow functions and optional and rest params","code":"const f = (a: number, b?: string, c: number = 10, ...rest: boolean[]): [number, string | undefined, number, number] =>\n [a, b, c, rest.length]\nconst g = async (x: number): Promise => x * 3\nconst h = ({ a }: { a: number }, [b]: [number]): number => a + b\nreturn [f(1, undefined, undefined, true, false), await g(4), h({ a: 2 }, [3])]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[[1,null,10,2],12,5],"logs":[]}}, + {"name":"explicit this parameter and type predicates","code":"function greet(this: { name: string }, prefix: string): string {\n return prefix + this.name\n}\nfunction isNum(x: unknown): x is number { return typeof x === \"number\" }\nfunction assertStr(x: unknown): asserts x is string {\n if (typeof x !== \"string\") throw new Error(\"not string\")\n}\nfunction assertOk(x: unknown): asserts x {\n if (!x) throw new Error(\"falsy\")\n}\nassertStr(\"ok\")\nassertOk(1)\nreturn [greet.length, greet.call({ name: \"world\" }, \"hi \"), isNum(1), isNum(\"a\")]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[1,"hi world",true,false],"logs":[]}}, + {"name":"function and class overloads in strict mode","code":"\"use strict\"\nfunction combine(a: number, b: number): number;\nfunction combine(a: string, b: string): string;\nfunction combine(a: number | string, b: number | string): number | string {\n return (a as any) + (b as any)\n}\nclass Pair {\n v: number | string\n constructor(x: number);\n constructor(x: string);\n constructor(x: number | string) { this.v = x }\n fmt(prefix: string): string;\n fmt(prefix: number): string;\n fmt(prefix: string | number): string { return String(prefix) + \":\" + String(this.v) }\n}\nreturn [combine(1, 2), combine(\"a\", \"b\"), new Pair(7).fmt(\"n\")]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[3,"ab","n:7"],"logs":[]}}, + {"name":"class modifiers abstract declare index signatures and field semantics","code":"interface HasTag { readonly tag: string }\nabstract class Base implements HasTag {\n public readonly tag: string = \"base\"\n public static count: number = 0\n private static readonly secret: number = 99\n declare ghost: number\n abstract val: T\n [key: string]: unknown\n protected constructor(protected_v: T) {\n Base.count++\n this._v = protected_v\n }\n private _v: T\n public abstract get(): T\n protected read(): T { return this._v }\n public static getSecret(): number { return Base.secret }\n}\nclass Sub extends Base {\n val: number\n uninit: number\n public override get(): number { return this.read() }\n constructor(n: number) {\n super(n)\n this.val = n\n }\n}\nconst s = new Sub(42)\nclass ModNames {\n public = 1\n private() { return 2 }\n readonly = 3\n declare = 4\n override = 5\n abstract = 6\n static public = 7\n}\nconst mn = new ModNames()\nreturn [\n s.tag, s.get(), s.val, \"uninit\" in s, s.uninit === undefined, \"ghost\" in s, Base.count, Base.getSecret(),\n mn.public, mn.private(), mn.readonly, mn.declare, mn.override, mn.abstract, ModNames.public,\n]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":["base",42,42,true,true,false,1,99,1,2,3,4,5,6,7],"logs":[]}}, + {"name":"object literal typed and generic methods and accessors","code":"const obj = {\n _v: 1 as number,\n m(this: { _v: number }, x: T): [number, T] { return [this._v, x] },\n get v(): number { return this._v },\n set v(n: number) { this._v = n },\n}\nobj.v = 7\nreturn [obj.m(\"hi\"), obj.v]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[[7,"hi"],7],"logs":[]}}, + {"name":"import type and export type erasure","code":"import type { Foo } from \"missing-a\"\nimport type Def from \"missing-b\"\nimport type * as NS from \"missing-c\"\nimport { type Bar } from \"missing-d\"\nimport Def2, { type Baz, a } from \"mod\"\nexport type { Foo, Def, NS, Bar, Baz }\nexport type * from \"missing-e\"\nexport type * as Re from \"missing-f\"\nexport interface ExportedI { x: number }\nexport type ExportedT = string\nexport declare const exportedDecl: number\nexport function exportedOverload(x: number): number;\nexport namespace ExportedNs { export type Inner = number }\nexport { type ExportedI }\nexport as namespace GlobalLib\nreturn [Def2.b, a]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[20,10],"logs":[]}}, + {"name":"declare ambient does not shadow host globals","code":"declare const double: (n: number) => number\ndeclare let x: string\ndeclare var y: number\ndeclare function noop(): void\ndeclare class Ghost { constructor(a: number) }\ndeclare abstract class AbsGhost {}\ndeclare enum AmbientE { A, B }\ndeclare const enum AmbientCE { C }\ndeclare namespace AmbientNS { const k: number }\ndeclare module \"ambient-mod\" { export const m: number }\ndeclare global { interface Window { custom: number } }\nreturn double(21)","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":42,"logs":[]}}, + {"name":"type-only namespaces erased","code":"namespace Empty {}\nnamespace TypesOnly {\n export type T = number\n export interface I { x: T }\n namespace Inner {\n type U = string\n }\n}\nnamespace A.B {\n export type C = boolean\n}\nconst x: TypesOnly.T = 9\nconst y: A.B.C = true\nreturn [x, y]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[9,true],"logs":[]}}, + {"name":"catch annotation and repl trailing type declarations","code":"let msg: string = \"\"\ntry {\n throw new Error(\"boom\")\n} catch (e: unknown) {\n msg = (e as Error).message\n}\nmsg\ntype Trailing = number\ninterface AlsoTrailing {}","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":"boom","logs":[]}}, + {"name":"type-only program returns null","code":"type A = number\ninterface B { x: A }","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":null,"logs":[]}}, + {"name":"contextual keywords as identifiers and newline rules","code":"const type = 1\nconst declare = 2\nconst abstract = 3\nconst namespace = 4\nconst module = 5\nconst as = 6\nconst satisfies = 7\nconst afterBang = 1\n!false\nconst afterAs = 1\nas\nconst afterSat = 1\nsatisfies\nreturn [type, declare, abstract, namespace, module, as, satisfies]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":[1,2,3,4,5,6,7],"logs":[]}}, + {"name":"Function.prototype.toString on TypeScript functions and methods","code":"function f(x: number): number { return x }\nconst id = (x: T): T => x\nabstract class A {\n public m(x: number): number { return x }\n public static sm(x: number): number { return x }\n protected static override async *gen(x: T): AsyncGenerator { yield x }\n}\nreturn [f.toString(), id.toString(), A.toString(), A.prototype.m.toString(), A.sm.toString(), A.gen.toString()]","typescript":true,"compile":{"ok":true},"execute":{"ok":true,"value":["function f(x: number): number { return x }","(x: T): T => x","abstract class A {\n public m(x: number): number { return x }\n public static sm(x: number): number { return x }\n protected static override async *gen(x: T): AsyncGenerator { yield x }\n}","m(x: number): number { return x }","sm(x: number): number { return x }","async *gen(x: T): AsyncGenerator { yield x }"],"logs":[]}}, + {"name":"refuse enum","code":"const a = 1\nenum Color { Red, Green }","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :2:1","location":[2,1]},"logs":[]}}, + {"name":"refuse const enum in unreached block","code":"if (false) { const enum Dir { Up, Down } }","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :1:14","location":[1,14]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :1:14","location":[1,14]},"logs":[]}}, + {"name":"refuse export enum","code":"export enum E { A }","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :1:8","location":[1,8]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript enums are not supported. Use a plain object instead.\n at :1:8","location":[1,8]},"logs":[]}}, + {"name":"refuse namespace with values","code":"const a = 1\nnamespace N { export const x = 1 }","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript namespaces with runtime values are not supported.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript namespaces with runtime values are not supported.\n at :2:1","location":[2,1]},"logs":[]}}, + {"name":"refuse nested namespace with values","code":"namespace Outer {\n type T = number\n namespace Inner { export const x = 1 }\n}","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript namespaces with runtime values are not supported.\n at :1:1","location":[1,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript namespaces with runtime values are not supported.\n at :1:1","location":[1,1]},"logs":[]}}, + {"name":"refuse constructor param property","code":"class A {\n constructor(x: number, private readonly y: string = \"a\") {}\n}","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript parameter properties are not supported. Declare and assign the field in the constructor instead.\n at :2:26","location":[2,26]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript parameter properties are not supported. Declare and assign the field in the constructor instead.\n at :2:26","location":[2,26]},"logs":[]}}, + {"name":"refuse class decorator","code":"const a = 1\n@dec\nclass A {}","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:1","location":[2,1]},"logs":[]}}, + {"name":"refuse member decorator","code":"class A {\n @dec\n m() {}\n}","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:3","location":[2,3]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:3","location":[2,3]},"logs":[]}}, + {"name":"refuse param decorator","code":"class A {\n m(@dec x: number) {}\n}","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:5","location":[2,5]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Decorators are not supported.\n at :2:5","location":[2,5]},"logs":[]}}, + {"name":"refuse import equals","code":"const a = 1\nimport fs = require(\"fs\")","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'import =' declarations are not supported.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'import =' declarations are not supported.\n at :2:1","location":[2,1]},"logs":[]}}, + {"name":"refuse import type equals","code":"import type fs = require(\"fs\")","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'import =' declarations are not supported.\n at :1:1","location":[1,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'import =' declarations are not supported.\n at :1:1","location":[1,1]},"logs":[]}}, + {"name":"refuse export equals","code":"const x = 1\nexport = x","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'export =' declarations are not supported.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: TypeScript 'export =' declarations are not supported.\n at :2:1","location":[2,1]},"logs":[]}}, + {"name":"refuse angle bracket assertion","code":"const x = 1\nconst y = x","typescript":true,"compile":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Angle-bracket type assertions are not supported. Use 'as' instead.\n at :2:11","location":[2,11]}},"execute":{"ok":false,"error":{"kind":"UnsupportedSyntax","message":"SyntaxError: Angle-bracket type assertions are not supported. Use 'as' instead.\n at :2:11","location":[2,11]},"logs":[]}}, + {"name":"js mode refuses type annotation","code":"const x: number = 1","typescript":false,"compile":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body.\n at :1:8","location":[1,8]}},"execute":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Unexpected token. Code must be plain JavaScript written as a program body.\n at :1:8","location":[1,8]},"logs":[]}}, + {"name":"js mode refuses decorator as ParseError","code":"@dec class A {}","typescript":false,"compile":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Decorators are not supported.\n at :1:1","location":[1,1]}},"execute":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Decorators are not supported.\n at :1:1","location":[1,1]},"logs":[]}}, + {"name":"ts mode still refuses value export as ParseError","code":"export const x: number = 1","typescript":true,"compile":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Exports aren't available. Return the result instead.\n at :1:1","location":[1,1]}},"execute":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Exports aren't available. Return the result instead.\n at :1:1","location":[1,1]},"logs":[]}}, + {"name":"ts mode refuses an export list as it does in js mode","code":"const x = 1\nexport { x }","typescript":true,"compile":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Exports aren't available. Return the result instead.\n at :2:1","location":[2,1]}},"execute":{"ok":false,"error":{"kind":"ParseError","message":"SyntaxError: Exports aren't available. Return the result instead.\n at :2:1","location":[2,1]},"logs":[]}} + ] +} diff --git a/rust/conformance/typescript.ts b/rust/conformance/typescript.ts new file mode 100644 index 00000000..5f6945be --- /dev/null +++ b/rust/conformance/typescript.ts @@ -0,0 +1,407 @@ +#!/usr/bin/env bun + +// Records the reference's erasable TypeScript behavior — both erasure and compile-time UnsupportedSyntax refusals +// with exact locations and messages — into conformance/typescript.json, replayed by +// crates/psychoscript/tests/typescript.rs. + +import { join } from "node:path" +import { writeRecording } from "./recording.js" +import { reference } from "./reference.js" + +const ref = await reference(process.argv[2] ?? process.env.PSYCHOSCRIPT_REF) + +const makeRuntime = () => + ref.Language.Runtime.make({ + globals: () => ({ + double: ref.Language.Host.fn(([n]: ReadonlyArray) => Number(n) * 2), + mod: { a: 10, b: 20 }, + }), + }) + +type Case = { + readonly name: string + readonly code: string + readonly typescript?: boolean +} + +const cases: ReadonlyArray = [ + // --- Erasable TypeScript --- + { + name: "var annotations and definite assignment", + code: `const x: number = 1 +let y: string = "hi" +let z!: boolean +z = true +var w: number | null = null +const { a, b = 2 }: { a: number; b?: number } = { a: 5 } +const [first, second]: [string, number] = ["k", 9] +return [x, y, z, w, a, b, first, second]`, + }, + { + name: "interface, type aliases, and type/value name merging", + code: `interface Base { id: number } +interface User extends Base { + readonly name: string + meta?: T + (x: number): string + new (x: number): object + [key: string]: unknown +} +type ID = string | number +type Mapped = { -readonly [K in keyof T as \`get_\${string & K}\`]-?: T[K] extends number ? string : boolean } +type Tuple = [first: number, second?: string, ...rest: boolean[]] +const obj = { a: 1, b: "x" } +type Key = keyof typeof obj +const k: Key = "a" +const u: Pick, "id" | "name"> = { id: 1, name: "ada" } +type Inferred = T extends infer Q extends string ? Q : never +type Merged = { a: number } +const Merged = 42 +interface Bar { x: number } +class Bar { x = 7 } +return [k, u, Merged, new Bar().x]`, + }, + { + name: "as and satisfies expressions and precedence", + code: `const o = { a: 1 as number, b: "x" } satisfies Record +const sum = (o.a as number) + 1 +const sum2 = 1 + 2 as number +const eq = o.a as number === 1 +const cmp1 = o.a as number < 2 +const cmp2 = 0 < o.a as number +const chained = o.a as unknown as number +const lit = { x: 1, y: [2, 3] } as const +let target: unknown = 0 +;(target as any) = 5 +target as any = 7 +return [sum, sum2, eq, cmp1, cmp2, chained, lit.x, target]`, + }, + { + name: "non-null assertions in expressions chains calls and assignments", + code: `const o: { f?: (x: number) => number; n?: { v: number }; k?: number } = { + v: 100, + f(this: { v?: number }, x: number): number { return (this.v ?? 0) + x }, + n: { v: 5 }, + k: 1, +} as any +const a = o.f!(3) +const b = o.n!.v +const c = o?.n!.v +const d = o.n!!.v +let x: number | null = 1 +x! = 2 +x!++ +const obj: { a?: number; b?: number } = { a: 10, b: 20 } +obj.a! += 5 +let p: number | null = 0 +let q: number | null = 0 +;[p!, q!] = [7, 8] +;({ a: p! } = { a: 9 }) +delete o!.k +class Sup { v = 1 } +class Sub extends Sup { m() { super.v! = 5; super.v!++; return this.v } } +return [a, b, c, d, x, obj.a, p, q, "k" in o, new Sub().m()]`, + }, + { + name: "generics functions arrows classes calls new tagged templates and instantiation", + code: `function id(x: T, y?: U): [T, U | undefined] { return [x, y] } +const f = (x: T): T => x +const f2 = (x: T): T => x +const af = async (x: T): Promise => x +const fnExpr = function(x: T): T { return x } +const g = id +const opt: { fn?: (x: T) => T } = { fn: id } +const map = new Map>([["a", [1, 2]]]) +const nested: Record>> = {} +type Defaulted> = T +const defVal: Defaulted = [3] +function tag(s: TemplateStringsArray, v: T): [string, T] { return [s[0]!, v] } +return [ + id(1, 2), + f("ok"), + f2("const"), + await af(4), + fnExpr(true), + g(5), + opt.fn?.(6), + map.get("a"), + Object.keys(nested), + defVal, + tag\`hi \${7 as number}\`, +]`, + }, + { + name: "generic vs comparison and ternary disambiguation", + code: `const a = 1, b = 2, c = 0 +const cond = true +const paren = cond ? (a) : b => b +const typed = cond ? (x: number): number => x + 1 : y => y +const body = cond ? x => (a) : y => y +return [a < b > c, a < b > -1, cond ? (1) : 2, (false ? 1 : 2), paren, typed(1), body(0)]`, + }, + { + name: "top-level await and for await", + code: `const seen: number[] = [] +for await (const n of [1, 2] as number[]) seen.push(n) +return [seen, await Promise.resolve(3 as number)]`, + }, + { + name: "typed arrow functions and optional and rest params", + code: `const f = (a: number, b?: string, c: number = 10, ...rest: boolean[]): [number, string | undefined, number, number] => + [a, b, c, rest.length] +const g = async (x: number): Promise => x * 3 +const h = ({ a }: { a: number }, [b]: [number]): number => a + b +return [f(1, undefined, undefined, true, false), await g(4), h({ a: 2 }, [3])]`, + }, + { + name: "explicit this parameter and type predicates", + code: `function greet(this: { name: string }, prefix: string): string { + return prefix + this.name +} +function isNum(x: unknown): x is number { return typeof x === "number" } +function assertStr(x: unknown): asserts x is string { + if (typeof x !== "string") throw new Error("not string") +} +function assertOk(x: unknown): asserts x { + if (!x) throw new Error("falsy") +} +assertStr("ok") +assertOk(1) +return [greet.length, greet.call({ name: "world" }, "hi "), isNum(1), isNum("a")]`, + }, + { + name: "function and class overloads in strict mode", + code: `"use strict" +function combine(a: number, b: number): number; +function combine(a: string, b: string): string; +function combine(a: number | string, b: number | string): number | string { + return (a as any) + (b as any) +} +class Pair { + v: number | string + constructor(x: number); + constructor(x: string); + constructor(x: number | string) { this.v = x } + fmt(prefix: string): string; + fmt(prefix: number): string; + fmt(prefix: string | number): string { return String(prefix) + ":" + String(this.v) } +} +return [combine(1, 2), combine("a", "b"), new Pair(7).fmt("n")]`, + }, + { + name: "class modifiers abstract declare index signatures and field semantics", + code: `interface HasTag { readonly tag: string } +abstract class Base implements HasTag { + public readonly tag: string = "base" + public static count: number = 0 + private static readonly secret: number = 99 + declare ghost: number + abstract val: T + [key: string]: unknown + protected constructor(protected_v: T) { + Base.count++ + this._v = protected_v + } + private _v: T + public abstract get(): T + protected read(): T { return this._v } + public static getSecret(): number { return Base.secret } +} +class Sub extends Base { + val: number + uninit: number + public override get(): number { return this.read() } + constructor(n: number) { + super(n) + this.val = n + } +} +const s = new Sub(42) +class ModNames { + public = 1 + private() { return 2 } + readonly = 3 + declare = 4 + override = 5 + abstract = 6 + static public = 7 +} +const mn = new ModNames() +return [ + s.tag, s.get(), s.val, "uninit" in s, s.uninit === undefined, "ghost" in s, Base.count, Base.getSecret(), + mn.public, mn.private(), mn.readonly, mn.declare, mn.override, mn.abstract, ModNames.public, +]`, + }, + { + name: "object literal typed and generic methods and accessors", + code: `const obj = { + _v: 1 as number, + m(this: { _v: number }, x: T): [number, T] { return [this._v, x] }, + get v(): number { return this._v }, + set v(n: number) { this._v = n }, +} +obj.v = 7 +return [obj.m("hi"), obj.v]`, + }, + { + name: "import type and export type erasure", + code: `import type { Foo } from "missing-a" +import type Def from "missing-b" +import type * as NS from "missing-c" +import { type Bar } from "missing-d" +import Def2, { type Baz, a } from "mod" +export type { Foo, Def, NS, Bar, Baz } +export type * from "missing-e" +export type * as Re from "missing-f" +export interface ExportedI { x: number } +export type ExportedT = string +export declare const exportedDecl: number +export function exportedOverload(x: number): number; +export namespace ExportedNs { export type Inner = number } +export { type ExportedI } +export as namespace GlobalLib +return [Def2.b, a]`, + }, + { + name: "declare ambient does not shadow host globals", + code: `declare const double: (n: number) => number +declare let x: string +declare var y: number +declare function noop(): void +declare class Ghost { constructor(a: number) } +declare abstract class AbsGhost {} +declare enum AmbientE { A, B } +declare const enum AmbientCE { C } +declare namespace AmbientNS { const k: number } +declare module "ambient-mod" { export const m: number } +declare global { interface Window { custom: number } } +return double(21)`, + }, + { + name: "type-only namespaces erased", + code: `namespace Empty {} +namespace TypesOnly { + export type T = number + export interface I { x: T } + namespace Inner { + type U = string + } +} +namespace A.B { + export type C = boolean +} +const x: TypesOnly.T = 9 +const y: A.B.C = true +return [x, y]`, + }, + { + name: "catch annotation and repl trailing type declarations", + code: `let msg: string = "" +try { + throw new Error("boom") +} catch (e: unknown) { + msg = (e as Error).message +} +msg +type Trailing = number +interface AlsoTrailing {}`, + }, + { + name: "type-only program returns null", + code: `type A = number +interface B { x: A }`, + }, + { + name: "contextual keywords as identifiers and newline rules", + code: `const type = 1 +const declare = 2 +const abstract = 3 +const namespace = 4 +const module = 5 +const as = 6 +const satisfies = 7 +const afterBang = 1 +!false +const afterAs = 1 +as +const afterSat = 1 +satisfies +return [type, declare, abstract, namespace, module, as, satisfies]`, + }, + { + name: "Function.prototype.toString on TypeScript functions and methods", + code: `function f(x: number): number { return x } +const id = (x: T): T => x +abstract class A { + public m(x: number): number { return x } + public static sm(x: number): number { return x } + protected static override async *gen(x: T): AsyncGenerator { yield x } +} +return [f.toString(), id.toString(), A.toString(), A.prototype.m.toString(), A.sm.toString(), A.gen.toString()]`, + }, + + // --- Non-erasable TypeScript refusals (UnsupportedSyntax with exact line & col) --- + { name: "refuse enum", code: `const a = 1 +enum Color { Red, Green }` }, + { name: "refuse const enum in unreached block", code: `if (false) { const enum Dir { Up, Down } }` }, + { name: "refuse export enum", code: `export enum E { A }` }, + { name: "refuse namespace with values", code: `const a = 1 +namespace N { export const x = 1 }` }, + { name: "refuse nested namespace with values", code: `namespace Outer { + type T = number + namespace Inner { export const x = 1 } +}` }, + { name: "refuse constructor param property", code: `class A { + constructor(x: number, private readonly y: string = "a") {} +}` }, + { name: "refuse class decorator", code: `const a = 1 +@dec +class A {}` }, + { name: "refuse member decorator", code: `class A { + @dec + m() {} +}` }, + { name: "refuse param decorator", code: `class A { + m(@dec x: number) {} +}` }, + { name: "refuse import equals", code: `const a = 1 +import fs = require("fs")` }, + { name: "refuse import type equals", code: `import type fs = require("fs")` }, + { name: "refuse export equals", code: `const x = 1 +export = x` }, + { name: "refuse angle bracket assertion", code: `const x = 1 +const y = x` }, + + // --- Mode isolation & value export refusal --- + { name: "js mode refuses type annotation", code: `const x: number = 1`, typescript: false }, + { name: "js mode refuses decorator as ParseError", code: `@dec class A {}`, typescript: false }, + { name: "ts mode still refuses value export as ParseError", code: `export const x: number = 1`, typescript: true }, + { name: "ts mode refuses an export list as it does in js mode", code: `const x = 1 +export { x }`, typescript: true }, +] + +const describeError = (e: { kind: string; message: string; location?: { line: number; column: number } }) => ({ + kind: e.kind, + message: e.message, + ...(e.location ? { location: [e.location.line, e.location.column] } : {}), +}) + +const recorded = [] +for (const c of cases) { + const typescript = c.typescript ?? true + const rt = makeRuntime() + const compiled = rt.compile(c.code, { typescript }) + const executed = await ref.Effect.runPromise(rt.execute(c.code, { typescript })) + recorded.push({ + name: c.name, + code: c.code, + typescript, + compile: compiled.ok ? { ok: true } : { ok: false, error: describeError(compiled.error) }, + execute: executed.ok + ? { ok: true, value: executed.value, logs: executed.logs ?? [] } + : { ok: false, error: describeError(executed.error), logs: executed.logs ?? [] }, + }) +} + +writeRecording(join(import.meta.dir, "typescript.json"), { cases: recorded }) +console.log(`recorded ${recorded.length} TypeScript parity cases`) diff --git a/rust/crates/psychoscript/src/compiler.rs b/rust/crates/psychoscript/src/compiler.rs index 4723001e..a485338f 100644 --- a/rust/crates/psychoscript/src/compiler.rs +++ b/rust/crates/psychoscript/src/compiler.rs @@ -38,27 +38,61 @@ const MAX_NESTING: u32 = 2_000; /// Largest program accepted, which bounds the parser's own recursion. const MAX_SOURCE_BYTES: usize = 256 * 1024; -pub fn compile(source: &str, atoms: &mut Strings) -> R { - compile_as(source, atoms, false) +pub fn compile(source: &str, typescript: bool, atoms: &mut Strings) -> R { + compile_as(source, typescript, atoms, false) } /// Compiles a built-in the reference writes in its bytecode prelude, from the reference's source: its `$Call(f, /// thisArg, ...args)` is a call of `f` with that receiver and `$ArraySet(array, index, value)` an element write, as /// the reference lowers them; any other `$` helper is a global the caller binds. pub(crate) fn compile_internal(source: &str, atoms: &mut Strings) -> R { - compile_as(source, atoms, true) + compile_as(source, false, atoms, true) } -/// The offset of the first token after a class element's leading `static`. -fn skip_static(source: &str, start: u32) -> u32 { - let rest = &source[start as usize + "static".len()..]; - (source.len() - rest.trim_start().len()) as u32 +/// The offset of the first token after a class element's leading modifiers (`static`, TS access/override modifiers). +fn skip_method_modifiers(source: &str, start: u32, key_start: u32) -> u32 { + let bytes = source.as_bytes(); + let limit = (key_start as usize).min(bytes.len()); + let mut at = (start as usize).min(limit); + while at < limit { + while at < limit && source[at..limit].starts_with(char::is_whitespace) { + at += source[at..limit].chars().next().map_or(1, char::len_utf8); + } + let word_start = at; + while at < limit && bytes[at].is_ascii_lowercase() { + at += 1; + } + if at == word_start + || (at < bytes.len() + && (bytes[at].is_ascii_alphanumeric() || bytes[at] == b'_' || bytes[at] == b'$')) + { + return word_start as u32; + } + let word = &source[word_start..at]; + if !matches!( + word, + "static" + | "public" + | "private" + | "protected" + | "override" + | "readonly" + | "abstract" + | "declare" + ) { + return word_start as u32; + } + while at < limit && source[at..limit].starts_with(char::is_whitespace) { + at += source[at..limit].chars().next().map_or(1, char::len_utf8); + } + } + at as u32 } /// The most a thread's parse arena keeps between compiles: a larger one, grown by a large program, is let go. const ARENA_KEEP_BYTES: usize = 256 * 1024; -fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { +fn compile_as(source: &str, typescript: bool, atoms: &mut Strings, internal: bool) -> R { thread_local! { /// The arena the parser and the analysis allocate in, kept from one compile to the next on the thread: /// a short program's compile then allocates no arena of its own. @@ -66,7 +100,7 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { } ARENA.with(|arena| match arena.try_borrow_mut() { Ok(mut arena) => { - let r = compile_in(&arena, source, atoms, internal); + let r = compile_in(&arena, source, typescript, atoms, internal); match arena.capacity() > ARENA_KEEP_BYTES { true => *arena = Allocator::default(), false => arena.reset(), @@ -74,13 +108,14 @@ fn compile_as(source: &str, atoms: &mut Strings, internal: bool) -> R { r } // A compile within a compile on one thread: none is, but it would only cost an arena. - Err(_) => compile_in(&Allocator::default(), source, atoms, internal), + Err(_) => compile_in(&Allocator::default(), source, typescript, atoms, internal), }) } fn compile_in( allocator: &Allocator, source: &str, + typescript: bool, atoms: &mut Strings, internal: bool, ) -> R { @@ -98,9 +133,21 @@ fn compile_in( offset: None, }); } + // `SourceType::ts()` alone is a script unless the file has an import or export, where a top-level `for await` + // does not parse. + let module_st = if typescript { + SourceType::ts().with_module(true) + } else { + SourceType::mjs() + }; + let script_st = if typescript { + SourceType::ts().with_script(true) + } else { + SourceType::script() + }; let renamed: String; let mut await_alias = None; - let mut parsed = parse(allocator, source, SourceType::mjs()); + let mut parsed = parse(allocator, source, module_st); // The reference parses a script that allows top-level `await`: `await` is a plain name there, read as the // operator only where an expression starts with it. A program whose first error is naming something `await` is // parsed again as a script, unless it also uses `await` as an expression at the top level; then the names are @@ -111,15 +158,15 @@ fn compile_in( .next() .is_some_and(|d| names_await(source, d)) { - let script = parse(allocator, source, SourceType::script()); + let script = parse(allocator, source, script_st); if script.diagnostics.errors().next().is_none() && !script.fatal_error && !TopLevelAwait::uses(&script.program) { parsed = script; - } else if let Some((text, alias)) = rename_await_names(source) { + } else if let Some((text, alias)) = rename_await_names(source, module_st) { renamed = text; - parsed = parse(allocator, &renamed, SourceType::mjs()); + parsed = parse(allocator, &renamed, module_st); await_alias = Some(alias); } } @@ -161,36 +208,41 @@ fn compile_in( } // Parsed as a module for top-level `await`, but bound as a script, like the reference: top-level functions and // `var`s share one scope, so redeclaring one as the other is allowed. - parsed.program.source_type = SourceType::script(); + parsed.program.source_type = script_st; let program = &parsed.program; - if let Some(export) = program - .body - .iter() - .find(|s| s.is_module_declaration() && !matches!(s, Statement::ImportDeclaration(_))) - { + if typescript { + check_unsupported_ts(program)?; + } + if let Some(export) = program.body.iter().find(|s| { + s.is_module_declaration() + && !matches!(s, Statement::ImportDeclaration(_)) + && !(typescript && is_erased_stmt(s)) + }) { return Err(CompileError { kind: DiagnosticKind::ParseError, message: "SyntaxError: Exports aren't available. Return the result instead.".into(), offset: Some(export.span().start), }); } - // Acorn does not read decorators: the first `@` is an unexpected character. - struct Decorators(Option); - impl<'a> Visit<'a> for Decorators { - fn visit_decorator(&mut self, it: &Decorator<'a>) { - if self.0.is_none_or(|at| it.span.start < at) { - self.0 = Some(it.span.start); + if !typescript { + // Acorn does not read decorators in JS mode: the first `@` is an unexpected character. + struct Decorators(Option); + impl<'a> Visit<'a> for Decorators { + fn visit_decorator(&mut self, it: &Decorator<'a>) { + if self.0.is_none_or(|at| it.span.start < at) { + self.0 = Some(it.span.start); + } } } - } - let mut decorators = Decorators(None); - decorators.visit_program(program); - if let Some(at) = decorators.0 { - return Err(CompileError { - kind: DiagnosticKind::ParseError, - message: parse_message("Unexpected character '@'"), - offset: Some(at), - }); + let mut decorators = Decorators(None); + decorators.visit_program(program); + if let Some(at) = decorators.0 { + return Err(CompileError { + kind: DiagnosticKind::ParseError, + message: parse_message("Unexpected character '@'"), + offset: Some(at), + }); + } } let mut depth = DepthCheck { depth: 0, @@ -215,6 +267,7 @@ fn compile_in( let mut c = Compiler::new(scoping, semantic.semantic.nodes(), atoms); c.await_alias = await_alias; c.internal = internal; + c.typescript = typescript; c.source = program.source_text; c.find_unbound(program); c.find_field_values(program); @@ -244,14 +297,14 @@ fn parse<'a>(allocator: &'a Allocator, text: &'a str, source_type: SourceType) - /// The source with each `await` the reference reads as a name replaced by the returned five-letter identifier, which /// the source does not contain, padded with spaces to keep every offset (an escaped `await` is longer); `await` /// expressions stay. `None` when the module parse fails for another reason. -fn rename_await_names(source: &str) -> Option<(String, String)> { +fn rename_await_names(source: &str, module_st: SourceType) -> Option<(String, String)> { let alias = (0..100) .map(|i| format!("$aw{i:02}")) .find(|p| !source.contains(p.as_str()))?; let mut text = source.to_owned(); for _ in 0..256 { let allocator = Allocator::default(); - let parsed = parse(&allocator, &text, SourceType::mjs()); + let parsed = parse(&allocator, &text, module_st); let first = parsed.diagnostics.errors().next(); // After an escaped `await` label, its `break` reports a plain unexpected token. let escaped_await = |d: &oxc_diagnostics::OxcDiagnostic| { @@ -1282,6 +1335,8 @@ struct Compiler<'a, 's> { last_home: bool, /// Compiling a prelude built-in (see `compile_internal`). internal: bool, + /// Compiling a TypeScript source with type-only syntax erased. + typescript: bool, /// The text the program was parsed from, which spans index. source: &'a str, } @@ -1327,6 +1382,7 @@ impl<'a, 's> Compiler<'a, 's> { pseudo: 0, last_home: false, internal: false, + typescript: false, source: "", } } @@ -1659,10 +1715,15 @@ impl<'a, 's> Compiler<'a, 's> { fn decl_end(&self, s: SymbolId) -> u32 { // The end of the whole declaration, so references from inside the initializer stay checked. - self.nodes + let mut end = self + .nodes .kind(self.scoping.symbol_declaration(s)) .span() - .end + .end; + for r in self.scoping.symbol_redeclarations(s) { + end = end.max(r.span.end); + } + end } /// Emits a scope's entry: fresh cells, TDZ markers, `var` initial values. @@ -1703,6 +1764,9 @@ impl<'a, 's> Compiler<'a, 's> { let Statement::ImportDeclaration(d) = st else { continue; }; + if self.typescript && d.import_kind.is_type() { + continue; + } if d.import_kind.is_type() || d.phase.is_some() { return Err(unsupported("This form of `import`", d.span)); } @@ -1732,6 +1796,7 @@ impl<'a, 's> Compiler<'a, 's> { None, )?; self.emit(Op::Pop); + continue; } for spec in specifiers { let (kind, name, local, pos) = match spec { @@ -1742,6 +1807,9 @@ impl<'a, 's> Compiler<'a, 's> { (1, None, &x.local, x.span.start) } ImportDeclarationSpecifier::ImportSpecifier(x) => { + if self.typescript && x.import_kind.is_type() { + continue; + } (2, Some(x.imported.name().as_str()), &x.local, x.span.start) } }; @@ -1793,6 +1861,9 @@ impl<'a, 's> Compiler<'a, 's> { fn hoist_functions(&mut self, stmts: &'a [Statement<'a>]) -> R<()> { for st in stmts { if let Statement::FunctionDeclaration(f) = st { + if self.typescript && (f.declare || f.body.is_none()) { + continue; + } self.closure_for_function(f, None)?; let id = f.id.as_ref().and_then(|id| id.symbol_id.get()); match id { @@ -1911,25 +1982,48 @@ impl<'a, 's> Compiler<'a, 's> { } fn find_unbound(&mut self, program: &oxc_ast::ast::Program) { - struct Withs(Vec); - impl<'a> Visit<'a> for Withs { + struct Erased { + spans: Vec, + typescript: bool, + } + impl<'a> Visit<'a> for Erased { fn visit_with_statement(&mut self, it: &WithStatement<'a>) { - self.0.push(it.body.span()); + self.spans.push(it.body.span()); + } + fn visit_statement(&mut self, it: &Statement<'a>) { + if self.typescript && is_erased_stmt(it) { + self.spans.push(it.span()); + return; + } + walk::walk_statement(self, it); + } + fn visit_import_specifier(&mut self, it: &ImportSpecifier<'a>) { + if self.typescript && it.import_kind.is_type() { + self.spans.push(it.span); + return; + } + walk::walk_import_specifier(self, it); } } - let mut withs = Withs(Vec::new()); - withs.visit_program(program); - if withs.0.is_empty() { - return; - } + let mut erased = Erased { + spans: Vec::new(), + typescript: self.typescript, + }; + erased.visit_program(program); let inside = |span: oxc_span::Span| { - withs - .0 + erased + .spans .iter() .any(|w| w.start <= span.start && span.end <= w.end) }; for sym in self.scoping.symbol_ids() { - if inside(self.scoping.symbol_span(sym)) + let flags = self.scoping.symbol_flags(sym); + if self.typescript && !flags.is_value() { + self.unbound.insert(sym); + continue; + } + if !erased.spans.is_empty() + && inside(self.scoping.symbol_span(sym)) && self .scoping .symbol_redeclarations(sym) @@ -2082,16 +2176,20 @@ impl<'a, 's> Compiler<'a, 's> { self.init_scope(&syms); self.imports(&program.body)?; self.hoist_functions(&program.body)?; - if program.body.is_empty() + let last_runtime = if self.typescript { + program.body.iter().rposition(|st| !is_erased_stmt(st)) + } else { + program.body.len().checked_sub(1) + }; + if last_runtime.is_none() && let Some(d) = program.directives.last() { let text = js_str(&d.expression.value); self.push_str(&text); self.emit(Op::Return); } - let n = program.body.len(); for (i, st) in program.body.iter().enumerate() { - if i + 1 == n + if Some(i) == last_runtime && let Statement::ExpressionStatement(e) = st { self.pos = e.span.start; @@ -2404,6 +2502,9 @@ impl<'a, 's> Compiler<'a, 's> { } fn stmt(&mut self, st: &'a Statement<'a>) -> R<()> { + if self.typescript && is_erased_stmt(st) { + return Ok(()); + } self.pos = st.span().start; match st { Statement::BlockStatement(b) => self.block(b), @@ -3424,12 +3525,12 @@ impl<'a, 's> Compiler<'a, 's> { } fn assign_simple(&mut self, s: &'a SimpleAssignmentTarget<'a>) -> R<()> { - if let Some(m) = Self::super_member(s.as_member_expression()) { - return self.super_target(m.object().span()); - } - match s { - SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => self.store_ident(id), - SimpleAssignmentTarget::StaticMemberExpression(m) => { + match unwrap_simple_target(s) { + Some(UnwrappedTarget::Ident(id)) => self.store_ident(id), + Some(UnwrappedTarget::Member(m)) if Self::super_member(Some(m)).is_some() => { + self.super_target(m.object().span()) + } + Some(UnwrappedTarget::Member(MemberExpression::StaticMemberExpression(m))) => { self.expr(&m.object)?; self.emit(Op::Swap); let a = self.atom(m.property.name.as_str()); @@ -3437,7 +3538,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - SimpleAssignmentTarget::ComputedMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::ComputedMemberExpression(m))) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -3446,14 +3547,19 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Pop); Ok(()) } - other => Err(unsupported("This assignment target", other.span())), + _ => Err(unsupported("This assignment target", s.span())), } } // ---------- expressions ---------- fn expr_named(&mut self, e: &'a Expression<'a>, name: Option<&str>) -> R<()> { - match e { + let inner = if self.typescript { + unwrap_ts_expr(e) + } else { + e + }; + match inner { Expression::ClassExpression(c) if c.id.is_none() => { self.pos = c.span.start; self.compile_class(c, name) @@ -3576,6 +3682,9 @@ impl<'a, 's> Compiler<'a, 's> { self.chains.push(Vec::new()); match &c.expression { ChainElement::CallExpression(call) => self.call(call)?, + ChainElement::TSNonNullExpression(t) if self.typescript => { + self.expr(&t.expression)?; + } other => match other.as_member_expression() { Some(m) => self.expr(m_as_expr(m))?, None => return Err(unsupported("TypeScript syntax", other.span())), @@ -3642,6 +3751,12 @@ impl<'a, 's> Compiler<'a, 's> { Expression::PrivateInExpression(p) => { return Err(unsupported("Private fields", p.span)); } + Expression::TSAsExpression(t) if self.typescript => self.expr(&t.expression)?, + Expression::TSSatisfiesExpression(t) if self.typescript => self.expr(&t.expression)?, + Expression::TSNonNullExpression(t) if self.typescript => self.expr(&t.expression)?, + Expression::TSInstantiationExpression(t) if self.typescript => { + self.expr(&t.expression)? + } other => return Err(unsupported("This syntax", other.span())), } Ok(()) @@ -3692,7 +3807,12 @@ impl<'a, 's> Compiler<'a, 's> { /// `tag\`...\``: calls the tag, read like a callee, with the site's strings array and the substitutions. fn tagged_template(&mut self, t: &'a TaggedTemplateExpression<'a>) -> R<()> { - match &t.tag { + let tag = if self.typescript { + unwrap_ts_expr(&t.tag) + } else { + &t.tag + }; + match tag { Expression::StaticMemberExpression(m) => { self.expr(&m.object)?; let a = self.atom(m.property.name.as_str()); @@ -3887,7 +4007,11 @@ impl<'a, 's> Compiler<'a, 's> { /// `delete`: a member expression deletes, optionally; an identifier fails when it runs, as in the reference; /// anything else is evaluated and gives true. fn delete(&mut self, argument: &'a Expression<'a>) -> R<()> { - let argument = argument.without_parentheses(); + let argument = if self.typescript { + unwrap_ts_expr(argument) + } else { + argument.without_parentheses() + }; if let Expression::Identifier(id) = argument { let msg = self.str_const("Only data fields may be deleted."); self.pos = id.span.start; @@ -3895,7 +4019,12 @@ impl<'a, 's> Compiler<'a, 's> { return Ok(()); } let member = match argument { - Expression::ChainExpression(c) => c.expression.as_member_expression(), + Expression::ChainExpression(c) => match &c.expression { + ChainElement::TSNonNullExpression(t) if self.typescript => { + unwrap_ts_expr(&t.expression).as_member_expression() + } + other => other.as_member_expression(), + }, other => other.as_member_expression(), }; let Some(member) = member else { @@ -3977,7 +4106,12 @@ impl<'a, 's> Compiler<'a, 's> { _ => {} } } - match &c.callee { + let callee_expr = if self.typescript { + unwrap_ts_expr(&c.callee) + } else { + &c.callee + }; + match callee_expr { callee if Self::super_member(callee.as_member_expression()).is_some() => { if let Some(m) = callee.as_member_expression() { self.super_get(m, true)?; @@ -4038,7 +4172,12 @@ impl<'a, 's> Compiler<'a, 's> { fn unary(&mut self, u: &'a UnaryExpression<'a>) -> R<()> { match u.operator { UnaryOperator::Typeof => { - if let Expression::Identifier(id) = &u.argument + let arg = if self.typescript { + unwrap_ts_expr(&u.argument) + } else { + &u.argument + }; + if let Expression::Identifier(id) = arg && self.ident_symbol(id).is_none() && id.name.as_str() != "undefined" && id.name.as_str() != "arguments" @@ -4076,40 +4215,51 @@ impl<'a, 's> Compiler<'a, 's> { } fn assignment(&mut self, a: &'a AssignmentExpression<'a>) -> R<()> { - if let Some(m) = Self::super_member(a.left.as_member_expression()) { + let op = a.operator; + if op == AssignmentOperator::Assign + && matches!( + &a.left, + AssignmentTarget::ArrayAssignmentTarget(_) + | AssignmentTarget::ObjectAssignmentTarget(_) + ) + { + self.expr(&a.right)?; + self.emit(Op::Dup); + return self.assign_target(&a.left); + } + let target = a + .left + .as_simple_assignment_target() + .and_then(unwrap_simple_target); + if let Some(UnwrappedTarget::Member(m)) = target + && let Some(m) = Self::super_member(Some(m)) + { return self.super_assign(m, a); } - let op = a.operator; if op == AssignmentOperator::Assign { - match &a.left { - AssignmentTarget::AssignmentTargetIdentifier(id) => { + return match target { + Some(UnwrappedTarget::Ident(id)) => { self.expr_named(&a.right, Some(id.name.as_str()))?; self.emit(Op::Dup); - return self.store_ident(id); + self.store_ident(id) } - AssignmentTarget::StaticMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::StaticMemberExpression(m))) => { self.expr(&m.object)?; self.expr(&a.right)?; let at = self.atom(m.property.name.as_str()); self.emit_member(Op::SetProp(at), &m.object, None); - return Ok(()); + Ok(()) } - AssignmentTarget::ComputedMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::ComputedMemberExpression(m))) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); self.expr(&a.right)?; self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); - return Ok(()); - } - AssignmentTarget::ArrayAssignmentTarget(_) - | AssignmentTarget::ObjectAssignmentTarget(_) => { - self.expr(&a.right)?; - self.emit(Op::Dup); - return self.assign_target(&a.left); + Ok(()) } - other => return Err(unsupported("This assignment target", other.span())), - } + _ => Err(unsupported("This assignment target", a.left.span())), + }; } let logical = match op { AssignmentOperator::LogicalAnd => Some(Op::JumpIfFalseKeep(0)), @@ -4117,8 +4267,8 @@ impl<'a, 's> Compiler<'a, 's> { AssignmentOperator::LogicalNullish => Some(Op::JumpIfNotNullishKeep(0)), _ => None, }; - match &a.left { - AssignmentTarget::AssignmentTargetIdentifier(id) => { + match target { + Some(UnwrappedTarget::Ident(id)) => { if let Some(jop) = logical { self.load_ident(id)?; let j = self.emit(jop); @@ -4134,7 +4284,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit(Op::Dup); self.store_ident(id) } - AssignmentTarget::StaticMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::StaticMemberExpression(m))) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4155,7 +4305,7 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetProp(at), &m.object, None); Ok(()) } - AssignmentTarget::ComputedMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::ComputedMemberExpression(m))) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4178,21 +4328,18 @@ impl<'a, 's> Compiler<'a, 's> { self.emit_member(Op::SetElem, &m.object, Some(&m.expression)); Ok(()) } - other => Err(unsupported("This assignment target", other.span())), + _ => Err(unsupported("This assignment target", a.left.span())), } } fn update(&mut self, u: &'a UpdateExpression<'a>) -> R<()> { - if let Some(m) = Self::super_member(u.argument.as_member_expression()) { - return self.super_update(m, u); - } let step = if u.operator == UpdateOperator::Increment { Op::Inc } else { Op::Dec }; - match &u.argument { - SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => { + match unwrap_simple_target(&u.argument) { + Some(UnwrappedTarget::Ident(id)) => { self.load_ident(id)?; if u.prefix { self.emit(step); @@ -4204,7 +4351,10 @@ impl<'a, 's> Compiler<'a, 's> { } self.store_ident(id) } - SimpleAssignmentTarget::StaticMemberExpression(m) => { + Some(UnwrappedTarget::Member(m)) if Self::super_member(Some(m)).is_some() => { + self.super_update(m, u) + } + Some(UnwrappedTarget::Member(MemberExpression::StaticMemberExpression(m))) => { let at = self.atom(m.property.name.as_str()); self.expr(&m.object)?; self.emit(Op::Dup); @@ -4222,7 +4372,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - SimpleAssignmentTarget::ComputedMemberExpression(m) => { + Some(UnwrappedTarget::Member(MemberExpression::ComputedMemberExpression(m))) => { self.expr(&m.object)?; self.expr(&m.expression)?; self.emit_member(Op::WriteKey, &m.object, Some(&m.expression)); @@ -4243,7 +4393,7 @@ impl<'a, 's> Compiler<'a, 's> { } Ok(()) } - other => Err(unsupported("This update target", other.span())), + _ => Err(unsupported("This update target", u.argument.span())), } } } @@ -4416,7 +4566,10 @@ fn compound_op(op: AssignmentOperator) -> Op { // ---------- classes ---------- /// A class element the reference compiles: a method, an accessor or a field, with a plain or computed name. -fn supported_member(m: &ClassElement) -> bool { +fn supported_member(m: &ClassElement, typescript: bool) -> bool { + if typescript && is_erased_member(m) { + return true; + } let (key, computed) = match m { ClassElement::MethodDefinition(d) => (&d.key, d.computed), ClassElement::PropertyDefinition(d) => (&d.key, d.computed), @@ -4466,7 +4619,7 @@ fn class_syntax_name(m: &ClassElement) -> &'static str { /// NamedEvaluation: whether `e` is an anonymous function or class definition, which takes the name it is given. fn is_anonymous_fn(e: &Expression) -> bool { - match e { + match unwrap_ts_expr(e) { Expression::ArrowFunctionExpression(_) => true, Expression::FunctionExpression(f) => f.id.is_none(), Expression::ClassExpression(c) => c.id.is_none(), @@ -4477,18 +4630,30 @@ fn is_anonymous_fn(e: &Expression) -> bool { impl<'a, 's> Compiler<'a, 's> { /// Notes the class field initializers, whose references come from a function of their own. fn find_field_values(&mut self, program: &oxc_ast::ast::Program) { - struct Fields(Vec); + struct Fields { + spans: Vec, + typescript: bool, + } impl<'a> Visit<'a> for Fields { fn visit_property_definition(&mut self, it: &PropertyDefinition<'a>) { + if self.typescript + && (it.declare + || it.r#type == PropertyDefinitionType::TSAbstractPropertyDefinition) + { + return; + } if let Some(v) = &it.value { - self.0.push(v.span()); + self.spans.push(v.span()); } walk::walk_property_definition(self, it); } } - let mut f = Fields(Vec::new()); + let mut f = Fields { + spans: Vec::new(), + typescript: self.typescript, + }; f.visit_program(program); - self.field_values = f.0; + self.field_values = f.spans; } /// Whether a reference at `at` is in a field initializer that its declaration at `decl` is not in. @@ -4583,7 +4748,11 @@ impl<'a, 's> Compiler<'a, 's> { } fn class_declaration(&mut self, c: &'a Class<'a>) -> R<()> { - if c.body.body.iter().any(|m| !supported_member(m)) { + if c.body + .body + .iter() + .any(|m| !supported_member(m, self.typescript)) + { return self.compile_class(c, None); } self.compile_class(c, None)?; @@ -4599,7 +4768,12 @@ impl<'a, 's> Compiler<'a, 's> { /// A class definition, which leaves its constructor on the stack (see `classes.rs`). `name` is an anonymous /// class's NamedEvaluation name. fn compile_class(&mut self, c: &'a Class<'a>, name: Option<&str>) -> R<()> { - if let Some(m) = c.body.body.iter().find(|m| !supported_member(m)) { + if let Some(m) = c + .body + .body + .iter() + .find(|m| !supported_member(m, self.typescript)) + { return self.throw_syntax(class_syntax_name(m), m.span()); } let saved_pos = self.pos; @@ -4619,8 +4793,12 @@ impl<'a, 's> Compiler<'a, 's> { } None => None, }; + let ts = self.typescript; // A computed field's key is evaluated once, in order, into a binding of its own. for m in &c.body.body { + if ts && is_erased_member(m) { + continue; + } if let ClassElement::PropertyDefinition(p) = m && p.computed { @@ -4635,7 +4813,9 @@ impl<'a, 's> Compiler<'a, 's> { self.expr(sc)?; } let ctor = c.body.body.iter().find_map(|m| match m { - ClassElement::MethodDefinition(d) if d.kind == MethodDefinitionKind::Constructor => { + ClassElement::MethodDefinition(d) + if d.kind == MethodDefinitionKind::Constructor && !(ts && is_erased_member(m)) => + { Some(d) } _ => None, @@ -4645,7 +4825,11 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) if !p.r#static => Some(&**p), + ClassElement::PropertyDefinition(p) + if !p.r#static && !(ts && is_erased_member(m)) => + { + Some(&**p) + } _ => None, }) .collect(); @@ -4654,7 +4838,11 @@ impl<'a, 's> Compiler<'a, 's> { .body .iter() .filter_map(|m| match m { - ClassElement::PropertyDefinition(p) if p.r#static => Some(&**p), + ClassElement::PropertyDefinition(p) + if p.r#static && !(ts && is_erased_member(m)) => + { + Some(&**p) + } _ => None, }) .collect(); @@ -4705,6 +4893,9 @@ impl<'a, 's> Compiler<'a, 's> { let at = heritage.map_or(c.span.start, |s| s.without_parentheses().span().start); self.emit_at(at, Op::Class(derived)); for m in &c.body.body { + if ts && is_erased_member(m) { + continue; + } match m { ClassElement::PropertyDefinition(p) if p.computed => { let Some(e) = p.key.as_expression() else { @@ -4737,9 +4928,11 @@ impl<'a, 's> Compiler<'a, 's> { }; let flags = u8::from(d.r#static) | if d.computed { 2 } else { 0 } | kind; self.pos = d.span.start; - // `static` belongs to the class element, not the method, so the text starts after it. - let start = match d.r#static { - true => skip_static(self.source, d.span.start), + // `static` and TypeScript modifiers belong to the class element, not the method, so the text starts after them. + let start = match d.r#static || ts { + true => { + skip_method_modifiers(self.source, d.span.start, d.key.span().start) + } false => d.span.start, }; self.closure_for_method(&d.value, "", [start, d.span.end])?; @@ -5120,3 +5313,268 @@ impl<'a, 's> Compiler<'a, 's> { self.throw_syntax("Super", at) } } +// ---------- erasable TypeScript ---------- + +/// Rejects non-erasable TypeScript syntax (`enum`, `namespace` with values, parameter properties, decorators, +/// `import =`, `export =`, angle-bracket type assertions) with `UnsupportedSyntax` at the earliest site. +fn check_unsupported_ts(program: &oxc_ast::ast::Program) -> R<()> { + struct Check { + first: Option<(u32, &'static str)>, + in_ambient: bool, + } + impl Check { + fn record(&mut self, at: u32, message: &'static str) { + if self.first.is_none_or(|(prev, _)| at < prev) { + self.first = Some((at, message)); + } + } + } + impl<'a> Visit<'a> for Check { + fn visit_decorator(&mut self, it: &Decorator<'a>) { + self.record(it.span.start, "SyntaxError: Decorators are not supported."); + } + + fn visit_ts_enum_declaration(&mut self, it: &TSEnumDeclaration<'a>) { + if it.declare || self.in_ambient { + return; + } + self.record( + it.span.start, + "SyntaxError: TypeScript enums are not supported. Use a plain object instead.", + ); + } + + fn visit_ts_namespace_declaration(&mut self, it: &TSNamespaceDeclaration<'a>) { + if it.declare || self.in_ambient || is_type_only_namespace(it) { + return; + } + self.record( + it.span.start, + "SyntaxError: TypeScript namespaces with runtime values are not supported.", + ); + } + + fn visit_ts_external_module_declaration(&mut self, it: &TSExternalModuleDeclaration<'a>) { + if it.declare || self.in_ambient { + return; + } + self.record( + it.span.start, + "SyntaxError: TypeScript namespaces with runtime values are not supported.", + ); + } + + fn visit_ts_import_equals_declaration(&mut self, it: &TSImportEqualsDeclaration<'a>) { + if self.in_ambient { + return; + } + self.record( + it.span.start, + "SyntaxError: TypeScript 'import =' declarations are not supported.", + ); + } + + fn visit_ts_export_assignment(&mut self, it: &TSExportAssignment<'a>) { + if self.in_ambient { + return; + } + self.record( + it.span.start, + "SyntaxError: TypeScript 'export =' declarations are not supported.", + ); + } + + fn visit_ts_type_assertion(&mut self, it: &TSTypeAssertion<'a>) { + if self.in_ambient { + return; + } + self.record( + it.span.start, + "SyntaxError: Angle-bracket type assertions are not supported. Use 'as' instead.", + ); + } + + fn visit_formal_parameter(&mut self, it: &FormalParameter<'a>) { + if !self.in_ambient && (it.accessibility.is_some() || it.readonly || it.r#override) { + self.record( + it.span.start, + "SyntaxError: TypeScript parameter properties are not supported. Declare and assign the field in the constructor instead.", + ); + } + walk::walk_formal_parameter(self, it); + } + + fn visit_variable_declaration(&mut self, it: &VariableDeclaration<'a>) { + if it.declare { + let prev = self.in_ambient; + self.in_ambient = true; + walk::walk_variable_declaration(self, it); + self.in_ambient = prev; + return; + } + walk::walk_variable_declaration(self, it); + } + + fn visit_function(&mut self, it: &Function<'a>, flags: oxc_syntax::scope::ScopeFlags) { + if it.declare { + let prev = self.in_ambient; + self.in_ambient = true; + walk::walk_function(self, it, flags); + self.in_ambient = prev; + return; + } + walk::walk_function(self, it, flags); + } + + fn visit_class(&mut self, it: &Class<'a>) { + if it.declare { + let prev = self.in_ambient; + self.in_ambient = true; + walk::walk_class(self, it); + self.in_ambient = prev; + return; + } + walk::walk_class(self, it); + } + } + let mut check = Check { + first: None, + in_ambient: false, + }; + check.visit_program(program); + if let Some((at, message)) = check.first { + return Err(CompileError { + kind: DiagnosticKind::UnsupportedSyntax, + message: message.into(), + offset: Some(at), + }); + } + Ok(()) +} + +/// Whether a `namespace` / `module` declaration contains only type declarations (no runtime values). +fn is_type_only_namespace(m: &TSNamespaceDeclaration) -> bool { + if m.declare { + return true; + } + match &m.body { + TSNamespaceDeclarationBody::TSNamespaceDeclaration(inner) => is_type_only_namespace(inner), + TSNamespaceDeclarationBody::TSModuleBlock(block) => { + block.directives.is_empty() + && block + .body + .iter() + .all(|st| matches!(st, Statement::EmptyStatement(_)) || is_erased_stmt(st)) + } + } +} + +fn is_erased_decl(d: &Declaration) -> bool { + match d { + Declaration::TSTypeAliasDeclaration(_) + | Declaration::TSInterfaceDeclaration(_) + | Declaration::TSGlobalDeclaration(_) => true, + Declaration::TSExternalModuleDeclaration(m) => m.declare, + Declaration::TSNamespaceDeclaration(m) => is_type_only_namespace(m), + Declaration::TSEnumDeclaration(e) => e.declare, + Declaration::VariableDeclaration(v) => v.declare, + Declaration::FunctionDeclaration(f) => f.declare || f.body.is_none(), + Declaration::ClassDeclaration(c) => c.declare, + Declaration::TSImportEqualsDeclaration(_) => false, + } +} + +/// Whether a statement is purely type-only (erased with no runtime effect in TypeScript mode). +fn is_erased_stmt(st: &Statement) -> bool { + if let Some(d) = st.as_declaration() { + return is_erased_decl(d); + } + match st { + Statement::TSNamespaceExportDeclaration(_) => true, + Statement::ImportDeclaration(d) => { + d.import_kind.is_type() + || d.specifiers.as_ref().is_some_and(|specs| { + !specs.is_empty() + && specs.iter().all(|s| { + matches!( + s, + ImportDeclarationSpecifier::ImportSpecifier(x) + if x.import_kind.is_type() + ) + }) + }) + } + Statement::ExportAllDeclaration(d) => d.export_kind.is_type(), + Statement::ExportDeclaration(d) => is_erased_decl(&d.declaration), + Statement::ExportNamedDeclaration(d) => { + d.export_kind.is_type() + || (!d.specifiers.is_empty() + && d.specifiers.iter().all(|s| s.export_kind.is_type())) + } + Statement::ExportFromDeclaration(d) => { + d.export_kind.is_type() + || (!d.specifiers.is_empty() + && d.specifiers.iter().all(|s| s.export_kind.is_type())) + } + _ => false, + } +} + +/// Whether a class element is purely type-only (erased with no runtime effect in TypeScript mode). +fn is_erased_member(m: &ClassElement) -> bool { + match m { + ClassElement::TSIndexSignature(_) => true, + ClassElement::PropertyDefinition(p) => { + p.declare || p.r#type == PropertyDefinitionType::TSAbstractPropertyDefinition + } + ClassElement::MethodDefinition(d) => { + d.r#type == MethodDefinitionType::TSAbstractMethodDefinition || d.value.body.is_none() + } + _ => false, + } +} + +/// Unwraps erased TypeScript expression wrappers (`as`, `satisfies`, `!`, instantiation) and parens. +fn unwrap_ts_expr<'a>(mut e: &'a Expression<'a>) -> &'a Expression<'a> { + loop { + e = match e { + Expression::ParenthesizedExpression(p) => &p.expression, + Expression::TSAsExpression(t) => &t.expression, + Expression::TSSatisfiesExpression(t) => &t.expression, + Expression::TSNonNullExpression(t) => &t.expression, + Expression::TSTypeAssertion(t) => &t.expression, + Expression::TSInstantiationExpression(t) => &t.expression, + _ => return e, + }; + } +} + +enum UnwrappedTarget<'a> { + Ident(&'a IdentifierReference<'a>), + Member(&'a MemberExpression<'a>), +} + +fn unwrap_simple_target<'a>(s: &'a SimpleAssignmentTarget<'a>) -> Option> { + match s { + SimpleAssignmentTarget::AssignmentTargetIdentifier(id) => Some(UnwrappedTarget::Ident(id)), + SimpleAssignmentTarget::StaticMemberExpression(_) + | SimpleAssignmentTarget::ComputedMemberExpression(_) => { + s.as_member_expression().map(UnwrappedTarget::Member) + } + SimpleAssignmentTarget::TSAsExpression(t) => unwrap_expr_target(&t.expression), + SimpleAssignmentTarget::TSSatisfiesExpression(t) => unwrap_expr_target(&t.expression), + SimpleAssignmentTarget::TSNonNullExpression(t) => unwrap_expr_target(&t.expression), + SimpleAssignmentTarget::TSTypeAssertion(t) => unwrap_expr_target(&t.expression), + _ => None, + } +} + +fn unwrap_expr_target<'a>(e: &'a Expression<'a>) -> Option> { + match unwrap_ts_expr(e) { + Expression::Identifier(id) => Some(UnwrappedTarget::Ident(id)), + e @ (Expression::StaticMemberExpression(_) | Expression::ComputedMemberExpression(_)) => { + e.as_member_expression().map(UnwrappedTarget::Member) + } + _ => None, + } +} diff --git a/rust/crates/psychoscript/src/lib.rs b/rust/crates/psychoscript/src/lib.rs index b2c9e5ce..dc197d9b 100644 --- a/rust/crates/psychoscript/src/lib.rs +++ b/rust/crates/psychoscript/src/lib.rs @@ -66,7 +66,8 @@ pub use host_function::{ pub use program::{Program, RunOutcome, RunningCall, SuspendError, Suspended, Suspender}; pub use run::{Code, Compiled}; pub use runtime::{ - Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, TranslatePromises, + CompileOptions, Outcome, ProgramOptions, Run, Runtime, Translate, TranslateFunctions, + TranslatePromises, }; pub use serde_json::Value as Json; pub use snapshot::{Snapshot, SnapshotError, from_bytes, to_bytes}; diff --git a/rust/crates/psychoscript/src/nesting.rs b/rust/crates/psychoscript/src/nesting.rs index a6bf669e..77684da9 100644 --- a/rust/crates/psychoscript/src/nesting.rs +++ b/rust/crates/psychoscript/src/nesting.rs @@ -14,9 +14,16 @@ //! close nothing. No reading of that line can nest deeper than that, and the readings agree again at the line's end, //! unless the line can start something that spans lines (a template, a block comment, a string continued with a //! backslash); then, as after source the parser cannot tokenize, everything to the end counts raw. - -/// The bound for `code`: never less than its deepest syntax nesting, close to it for ordinary programs. -pub fn bound(code: &str) -> usize { +//! +//! A TypeScript source nests in three more ways, which the scan reads when it is told the source is one. A `<` may +//! open a list of types, whose commas separate types that nest as the list does: until a `>` closes it, neither a +//! comma nor a line break ends an item. A type may follow a word (`keyof`, `as`) or `extends` on the next line, so a +//! line break there ends no item either. And a `/` divides after a list of types, after a `!` that asserts a value, +//! and after the types `const` and `void`, where JavaScript reads a regular expression: there it may be either. + +/// The bound for `code`, read as TypeScript when `typescript` is set: never less than its deepest syntax nesting, +/// close to it for ordinary programs. +pub fn bound(code: &str, typescript: bool) -> usize { let mut scan = Scan { src: code.as_bytes(), at: 0, @@ -25,6 +32,7 @@ pub fn bound(code: &str) -> usize { newline: false, control: false, dot: false, + ts: typescript, }; scan.run(); let mut child = 0; @@ -47,6 +55,8 @@ struct Frame { chained: usize, /// Parentheses holding an `if`, `for`, `while` or `with` head: a statement follows. control: bool, + /// TypeScript: the `<` of the current item that no `>` has closed. Each may hold a list of types. + angles: usize, } impl Frame { @@ -58,6 +68,7 @@ impl Frame { best: 0, chained: 0, control, + angles: 0, } } @@ -65,6 +76,7 @@ impl Frame { self.best = self.best.max(self.tokens + self.child); self.tokens = 0; self.child = 0; + self.angles = 0; } fn close(&mut self) -> usize { @@ -130,6 +142,8 @@ struct Scan<'a> { control: bool, /// The previous token was a `.` of member access: a keyword after it is a property name. dot: bool, + /// The source is TypeScript. + ts: bool, } impl Scan<'_> { @@ -174,6 +188,12 @@ impl Scan<'_> { self.at += 1; self.close(b); } + // A comma inside `<` and `>` separates the types of a list, which nest as the list does. + b',' if self.top().angles > 0 => { + self.token(false); + self.after(OPERATOR); + self.at += 1; + } b';' | b',' => { self.top().end_item(); self.after(OPERATOR); @@ -229,6 +249,29 @@ impl Scan<'_> { self.dot = !spread; self.at += 1; } + b'<' if self.ts => { + self.token(false); + self.top().angles += 1; + self.after(OPERATOR); + self.at += 1; + } + // The `>` of `=>` closes no list. Any other may close one, and a `/` after a list divides. + b'>' if self.ts => { + self.token(false); + let arrow = self.at > 0 && self.src[self.at - 1] == b'='; + if !arrow { + let top = self.top(); + top.angles = top.angles.saturating_sub(1); + } + self.after(if arrow { OPERATOR } else { EITHER }); + self.at += 1; + } + // After a value a `!` may assert it non-null, and then a `/` divides. + b'!' if self.ts && self.prev.slash != Slash::Regex => { + self.token(false); + self.after(EITHER); + self.at += 1; + } // `++` and `--` may be postfix, after which a `/` divides, or prefix, after which it may not. b'+' | b'-' => { self.token(false); @@ -264,7 +307,7 @@ impl Scan<'_> { /// Counts a token in the current item, first ending the item when a line break before it ends a statement. fn token(&mut self, starts_statement: bool) { - if self.newline && starts_statement && self.prev.ends { + if self.newline && starts_statement && self.prev.ends && self.top().angles == 0 { self.top().end_item(); } self.newline = false; @@ -302,6 +345,9 @@ impl Scan<'_> { if matches!(b, b'(' | b'[' | b'{') { self.frames.push(Frame::new(b, false)); } + if b == b'<' && self.ts { + self.top().angles += 1; + } } self.at = end; self.after(EITHER); @@ -345,10 +391,10 @@ impl Scan<'_> { let member = self.dot; // Words that continue the statement before a line break. let continues = !member - && matches!( + && (matches!( word, b"in" | b"instanceof" | b"of" | b"else" | b"catch" | b"finally" | b"while" - ); + ) || (self.ts && matches!(word, b"extends" | b"as" | b"satisfies" | b"is"))); self.token(!continues); if matches!(word, b"else" | b"do") { self.top().chained += 1; @@ -359,6 +405,9 @@ impl Scan<'_> { // Keywords in some places and names in others. b"await" | b"yield" | b"of" | b"let" => EITHER, b"get" | b"set" | b"static" | b"async" | b"accessor" => PREFIX, + // A type: after `as const` or `as void` a `/` divides. + b"const" | b"void" if self.ts => EITHER, + _ if self.ts && is_type_word(word) => PREFIX, _ if is_keyword(word) => OPERATOR, _ => VALUE, }; @@ -470,6 +519,22 @@ fn line_end(src: &[u8], at: usize) -> usize { .unwrap_or(src.len()) } +/// TypeScript's words that a type follows, across a line break too. +fn is_type_word(word: &[u8]) -> bool { + matches!( + word, + b"abstract" + | b"as" + | b"asserts" + | b"infer" + | b"is" + | b"keyof" + | b"readonly" + | b"satisfies" + | b"unique" + ) +} + /// Words after which an expression, not an operator, comes next. fn is_keyword(word: &[u8]) -> bool { matches!( @@ -509,7 +574,9 @@ fn is_keyword(word: &[u8]) -> bool { #[cfg(test)] mod tests { - use super::bound; + fn bound(code: &str) -> usize { + super::bound(code, false) + } #[test] fn brackets_in_strings_comments_templates_and_regexes_do_not_count() { @@ -647,6 +714,35 @@ mod tests { } } + /// Each source nests 400 deep where the reading of JavaScript ends an item or reads a regular expression. + #[test] + fn typescript_hides_no_nesting_either() { + let n = 400; + let d = format!("{}1{}", "(".repeat(n), ")".repeat(n)); + let cases = [ + format!("type X = {}B{}", "A<0, ".repeat(n), ">".repeat(n)), + format!("const x = {}1", "(a: T) => ".repeat(n)), + format!("const x = f<{}B{}>()", "A<0,\n".repeat(n), ">".repeat(n)), + format!("type X = {}B", "keyof\n".repeat(n)), + format!("type X = {}B", "abstract\nnew () => ".repeat(n)), + format!("type X = {}D", "A\nextends B ? C :\n".repeat(n)), + format!("const x = 1{}", " as\nunknown".repeat(n)), + format!("const x = f / {d} / 1"), + format!("const x = a! / {d} / 1"), + format!("const x = 1 as const / {d} / 1"), + format!("const x = 1 as void / {d} / 1"), + ]; + for case in cases { + let b = super::bound(&case, true); + assert!(b >= n, "{} is bounded by {b}", &case[..case.len().min(70)]); + } + // What it keeps for the lists costs ordinary code little: a comparison holds its line's item open, no more. + let lines = + "const narrow = width < 80\nconst wide = width > 120\nif (narrow) { f(a, b) }\n"; + let bounded = super::bound(&lines.repeat(200), true); + assert!(bounded < 40, "{bounded}"); + } + #[test] fn regexes_and_divisions_the_scan_is_sure_of_stay_cheap() { let plain = bound("const r = /[(]+/g; const q = a / b / c; return r.test(q)"); diff --git a/rust/crates/psychoscript/src/program.rs b/rust/crates/psychoscript/src/program.rs index 5826c841..5ae190ea 100644 --- a/rust/crates/psychoscript/src/program.rs +++ b/rust/crates/psychoscript/src/program.rs @@ -28,6 +28,7 @@ enum State { pub(crate) struct Running { pub vm: Vm, pub code: Arc, + pub typescript: bool, started: bool, timer_armed: bool, /// Active time earlier runs of the same execution used, before a resume. @@ -574,6 +575,7 @@ impl<'a> Program<'a> { &r.vm, &snapshot::Capture { code: &r.code, + typescript: r.typescript, active_ms, }, ); @@ -713,10 +715,11 @@ fn restore(rt: &Runtime, state: &Snapshot) -> Result, snapshot::Sna } impl Running { - pub fn new(vm: Vm, code: Arc) -> Self { + pub fn new(vm: Vm, code: Arc, typescript: bool) -> Self { Self { vm, code, + typescript, started: false, timer_armed: false, active_before: Duration::ZERO, diff --git a/rust/crates/psychoscript/src/run.rs b/rust/crates/psychoscript/src/run.rs index b05e46a0..a0e64499 100644 --- a/rust/crates/psychoscript/src/run.rs +++ b/rust/crates/psychoscript/src/run.rs @@ -37,6 +37,7 @@ pub struct Compiled(Arc); struct CompiledProgram { code: Arc, + typescript: bool, program: Program, atoms: Strings, } @@ -82,11 +83,12 @@ impl<'a> From<&'a Compiled> for Code<'a> { } /// Parses and compiles a program, or the diagnostic a run of it would fail with before running anything. -pub fn compile_program(code: &str) -> Result { +pub fn compile_program(code: &str, typescript: bool) -> Result { let mut atoms = Strings::fresh(); - let program = compile(code, &mut atoms).map_err(|e| compile_diagnostic(code, e))?; + let program = compile(code, typescript, &mut atoms).map_err(|e| compile_diagnostic(code, e))?; Ok(Compiled(Arc::new(CompiledProgram { code: Arc::from(code), + typescript, program, atoms, }))) @@ -113,15 +115,15 @@ pub fn execute(rt: &Runtime, code: Code<'_>, options: &ProgramOptions) -> Outcom /// more native stack for deep syntax, so only compiling moves. On `wasm32`, where spawning a helper thread is /// unsupported, programs exceeding `RUN_STACK_BUDGET` return an error instead of attempting to spawn or overflowing /// the wasm stack. -pub fn compile(code: &str, atoms: &mut Strings) -> Result { +pub fn compile(code: &str, typescript: bool, atoms: &mut Strings) -> Result { // A program nests no deeper than it has bytes, so a short one needs no scan to know it fits. let fits = |levels: usize| levels.saturating_mul(COMPILE_STACK_PER_LEVEL) <= RUN_STACK_BUDGET; let need = match fits(code.len()) { true => 0, - false => nesting::bound(code).saturating_mul(COMPILE_STACK_PER_LEVEL), + false => nesting::bound(code, typescript).saturating_mul(COMPILE_STACK_PER_LEVEL), }; if need <= RUN_STACK_BUDGET { - return compiler::compile(code, atoms); + return compiler::compile(code, typescript, atoms); } #[cfg(target_arch = "wasm32")] { @@ -137,7 +139,7 @@ pub fn compile(code: &str, atoms: &mut Strings) -> Result std::thread::scope(|s| { std::thread::Builder::new() .stack_size(need.saturating_add(THREAD_STACK_BASE)) - .spawn_scoped(s, || compiler::compile(code, atoms)) + .spawn_scoped(s, || compiler::compile(code, typescript, atoms)) .map_err(|_| CompileError { kind: DiagnosticKind::ExecutionFailure, message: @@ -182,12 +184,17 @@ pub fn start( code: Code<'_>, options: &ProgramOptions, ) -> Result, Box> { - let (code, mut program, atoms) = match code { - Code::Compiled(c) => (c.0.code.clone(), c.0.program.clone(), c.0.atoms.clone()), + let (code, typescript, mut program, atoms) = match code { + Code::Compiled(c) => ( + c.0.code.clone(), + c.0.typescript, + c.0.program.clone(), + c.0.atoms.clone(), + ), Code::Source(code) => { let mut atoms = Strings::fresh(); - match compile(code, &mut atoms) { - Ok(p) => (Arc::from(code), p, atoms), + match compile(code, options.typescript, &mut atoms) { + Ok(p) => (Arc::from(code), options.typescript, p, atoms), Err(e) => return Err(Box::new(failed(compile_diagnostic(code, e)))), } } @@ -216,7 +223,7 @@ pub fn start( vm.code = code.clone(); vm.program = setup.program_lines.map(|lines| program_range(&code, lines)); vm.load(program); - Ok(Box::new(Running::new(vm, code))) + Ok(Box::new(Running::new(vm, code, typescript))) } /// A fresh run for a saved program: compiled and set up with the saved limits and no bindings, ready to be filled in. @@ -230,8 +237,9 @@ pub fn start_for_resume( restored: crate::snapshot::Restored, ) -> Result { let code = restored.code; + let typescript = restored.typescript; let mut atoms = Strings::fresh(); - let mut program = compile(&code, &mut atoms).map_err(|_| { + let mut program = compile(&code, typescript, &mut atoms).map_err(|_| { crate::snapshot::SnapshotError::new( "Source main does not compile in this build, so it can't resume.", ) @@ -259,7 +267,7 @@ pub fn start_for_resume( vm.program = setup.program_lines.map(|lines| program_range(&code, lines)); vm.load(program); Ok(Resumed { - running: Box::new(Running::new(vm, code)), + running: Box::new(Running::new(vm, code, typescript)), bytecode, }) } diff --git a/rust/crates/psychoscript/src/runtime.rs b/rust/crates/psychoscript/src/runtime.rs index 9c01e716..185c89cc 100644 --- a/rust/crates/psychoscript/src/runtime.rs +++ b/rust/crates/psychoscript/src/runtime.rs @@ -141,11 +141,34 @@ pub enum TranslatePromises { Await, } +/// Options for [`Runtime::compile_with`], the reference's `CompileOptions`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CompileOptions { + pub(crate) typescript: bool, +} + +impl CompileOptions { + pub fn new() -> Self { + Self::default() + } + + /// Parse the source as TypeScript and erase type-only syntax (annotations, `interface`, `type`, `as`, + /// `satisfies`, `!`, generics, `import type`/`export type`, `declare`, and class member modifiers). + /// Non-erasable syntax (`enum`, `namespace` with values, parameter properties, decorators, + /// `import x = require`) fails with [`DiagnosticKind::UnsupportedSyntax`](crate::DiagnosticKind::UnsupportedSyntax). + /// Defaults to `false` (plain JavaScript). + pub fn typescript(mut self, enabled: bool) -> Self { + self.typescript = enabled; + self + } +} + /// Options for one program: [`Runtime::program`], [`Runtime::execute_with`], the reference's `ProgramOptions`. #[derive(Clone, Debug, Default)] pub struct ProgramOptions { pub(crate) bindings: Vec<(HostString, Data)>, pub(crate) run_id: Option, + pub(crate) typescript: bool, } impl ProgramOptions { @@ -172,6 +195,13 @@ impl ProgramOptions { self.run_id = Some(run_id.into()); self } + + /// Parse the source as TypeScript and erase type-only syntax; see [`CompileOptions::typescript`]. + /// Ignored when running an already-[compiled](Runtime::compile_with) program. + pub fn typescript(mut self, enabled: bool) -> Self { + self.typescript = enabled; + self + } } type GlobalsFn = dyn Fn(&Run) -> Vec<(String, HostValue)> + Send + Sync; @@ -314,7 +344,16 @@ impl Runtime { /// without doing it again; or the diagnostic a run of it would fail with first (an empty program, a syntax /// error). Unsupported syntax still fails where it runs, as from source. A compiled program runs in any runtime. pub fn compile(&self, code: &str) -> Result { - crate::run::compile_program(code) + self.compile_with(code, &CompileOptions::default()) + } + + /// [`Runtime::compile`] with [`CompileOptions`], such as TypeScript mode. + pub fn compile_with( + &self, + code: &str, + options: &CompileOptions, + ) -> Result { + crate::run::compile_program(code, options.typescript) } /// A program continuing a suspended run, from its state. It keeps the limits it was saved with, and its globals diff --git a/rust/crates/psychoscript/src/snapshot.rs b/rust/crates/psychoscript/src/snapshot.rs index 5774e339..00105f0e 100644 --- a/rust/crates/psychoscript/src/snapshot.rs +++ b/rust/crates/psychoscript/src/snapshot.rs @@ -388,6 +388,7 @@ fn cross(c: &crate::cross::Cross) -> J { /// What a capture needs to know beyond the VM. pub struct Capture<'c> { pub code: &'c str, + pub typescript: bool, pub active_ms: u64, } @@ -436,7 +437,7 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { }; let state = enc.state(c).map_err(|e| Refusal::Other(e.message))?; let base = vm.snapshot_base; - let program = crate::run::compile(c.code, &mut crate::strings::Strings::fresh()) + let program = crate::run::compile(c.code, c.typescript, &mut crate::strings::Strings::fresh()) .map_err(|e| Refusal::Other(e.message))?; let limits = *vm.limits; let metadata = vm.host.run.metadata(); @@ -459,6 +460,9 @@ pub fn capture(vm: &Vm, c: &Capture) -> Result { "base": base.json(), "state": state_hash(&state), }); + if c.typescript { + header["source"]["typescript"] = json!(true); + } if let Some(n) = limits.max_heap_bytes { header["limits"]["maxHeapBytes"] = json!(n); } @@ -482,7 +486,7 @@ impl Enc<'_> { let vm = self.vm; let base = vm.snapshot_base; let (texts, atoms) = vm.atoms.save_from(base.bufs, base.atoms); - let baseline = baseline(vm, c.code)?; + let baseline = baseline(vm, c.code, c.typescript)?; let mut changed = Vec::new(); for (id, o) in vm.heap.iter().enumerate().take(base.heap) { let now = self.obj(o)?; @@ -990,10 +994,10 @@ fn hex_bytes(s: &str) -> R> { } /// Each object of a fresh run's base, encoded, to see which ones the run changed. -fn baseline(vm: &Vm, code: &str) -> R> { +fn baseline(vm: &Vm, code: &str, typescript: bool) -> R> { let mut atoms = crate::strings::Strings::fresh(); - let program = - crate::run::compile(code, &mut atoms).map_err(|e| SnapshotError::new(e.message))?; + let program = crate::run::compile(code, typescript, &mut atoms) + .map_err(|e| SnapshotError::new(e.message))?; let h = &vm.host; let host = host::RunHost::new( h.globals.clone(), @@ -2173,6 +2177,7 @@ fn pairs(j: &J) -> R> { /// A saved state, checked against this runtime and ready to resume. pub struct Restored { pub code: String, + pub typescript: bool, pub run_id: Option, pub metadata: crate::Data, /// The shape of the host globals it was saved with (`hosts_id`). @@ -2198,6 +2203,12 @@ pub fn header(snapshot: &Snapshot) -> R { } let source = field(header, "source")?; let code = string(field(source, "code")?)?; + let typescript = match source.get("typescript") { + None => false, + Some(v) => v + .as_bool() + .ok_or_else(|| invalid("a source typescript flag is not a boolean."))?, + }; if field(source, "hash")?.as_str() != Some(hex(hash(code.as_bytes())).as_str()) { return Err(SnapshotError::new("Source main does not match its hash.")); } @@ -2209,6 +2220,7 @@ pub fn header(snapshot: &Snapshot) -> R { let budget = field(header, "budget")?; Ok(Restored { code, + typescript, run_id: field(header, "runId")?.as_str().map(str::to_owned), metadata: match header.get("metadataData") { Some(saved) if !saved.is_null() => crate::Data::from_host(&host_value_from(saved)?), diff --git a/rust/crates/psychoscript/src/test262.rs b/rust/crates/psychoscript/src/test262.rs index 2eb29437..2cfd946c 100644 --- a/rust/crates/psychoscript/src/test262.rs +++ b/rust/crates/psychoscript/src/test262.rs @@ -59,7 +59,7 @@ fn run_here(code: &str, timeout_ms: u64) -> Run { let probe = 0u8; DONE.with(|d| *d.borrow_mut() = None); let mut atoms = Strings::fresh(); - let program = match compiler::compile(code, &mut atoms) { + let program = match compiler::compile(code, false, &mut atoms) { Ok(p) => p, Err(e) => { return Run { diff --git a/rust/crates/psychoscript/tests/typescript.rs b/rust/crates/psychoscript/tests/typescript.rs new file mode 100644 index 00000000..7d427f2e --- /dev/null +++ b/rust/crates/psychoscript/tests/typescript.rs @@ -0,0 +1,247 @@ +//! Erasable TypeScript parity against the reference recording in `conformance/typescript.json` (generated by +//! `bun conformance/typescript.ts`), plus compiled reuse and snapshot suspend/resume tests. + +use std::sync::mpsc; +use std::thread; + +use psychoscript::{ + CompileOptions, Diagnostic, HostFunction, HostValue, Json, ProgramOptions, RunOutcome, Runtime, + from_bytes, to_bytes, +}; + +#[path = "../../../conformance/reference.rs"] +mod reference; + +use reference::same; + +fn make_runtime() -> Runtime { + Runtime::make().globals(|_| { + [ + ( + "double", + HostValue::from(HostFunction::new(|args, _| { + let n = args.first().and_then(HostValue::as_f64).unwrap_or(0.0); + HostValue::from(n * 2.0) + })), + ), + ( + "mod", + HostValue::object([("a", HostValue::from(10.0)), ("b", HostValue::from(20.0))]), + ), + ] + }) +} + +fn check_error(label: &str, actual: &Diagnostic, expected: &Json, problems: &mut Vec) { + if actual.kind.name() != expected["kind"] { + problems.push(format!( + "{label} kind: expected {}, got {} ({})", + expected["kind"], + actual.kind.name(), + actual.message + )); + } + let expected_loc = expected + .get("location") + .and_then(|l| Some((l.get(0)?.as_u64()? as u32, l.get(1)?.as_u64()? as u32))); + if actual.location != expected_loc { + problems.push(format!( + "{label} location: expected {expected_loc:?}, got {:?}", + actual.location + )); + } + // Check exact message parity on UnsupportedSyntax and ParseError where both engines format the same message. + if actual.kind.name() == "UnsupportedSyntax" + && actual.message_lossy() != expected["message"].as_str().unwrap_or("") + { + problems.push(format!( + "{label} message: + expected: {} + actual: {}", + expected["message"], + actual.message_lossy() + )); + } +} + +#[test] +fn typescript_parity() { + let path = + std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../conformance/typescript.json"); + let data: Json = + serde_json::from_str(&std::fs::read_to_string(&path).expect("typescript.json")).unwrap(); + let cases = data["cases"].as_array().expect("cases array"); + assert!(!cases.is_empty()); + + let mut failures = Vec::new(); + for c in cases { + let name = c["name"].as_str().unwrap(); + let code = c["code"].as_str().unwrap(); + let typescript = c["typescript"].as_bool().unwrap(); + let rt = make_runtime(); + let mut problems = Vec::new(); + + // Check Runtime::compile_with + let compiled = rt.compile_with(code, &CompileOptions::new().typescript(typescript)); + match (&compiled, c["compile"]["ok"].as_bool()) { + (Ok(_), Some(true)) => {} + (Err(d), Some(false)) => { + check_error("compile", d, &c["compile"]["error"], &mut problems) + } + (Ok(_), Some(false)) => problems.push(format!( + "compile: expected {}, got ok", + c["compile"]["error"]["kind"] + )), + (Err(d), Some(true)) => problems.push(format!( + "compile: expected ok, got {}: {}", + d.kind.name(), + d.message + )), + _ => unreachable!(), + } + + // Check Runtime::execute_with (from source) + let outcome = rt.execute_with(code, &ProgramOptions::new().typescript(typescript)); + match (&outcome.result, c["execute"]["ok"].as_bool()) { + (Ok(v), Some(true)) => { + if !same(&v.to_json(), &c["execute"]["value"]) { + problems.push(format!( + "execute value: + expected: {} + actual: {}", + c["execute"]["value"], + v.to_json() + )); + } + } + (Err(d), Some(false)) => { + check_error("execute", d, &c["execute"]["error"], &mut problems) + } + (Ok(v), Some(false)) => problems.push(format!( + "execute: expected {}, got ok {v}", + c["execute"]["error"]["kind"] + )), + (Err(d), Some(true)) => problems.push(format!( + "execute: expected ok {}, got {}: {}", + c["execute"]["value"], + d.kind.name(), + d.message + )), + _ => unreachable!(), + } + + // Also check running the pre-compiled program produces the same result. + if let Ok(compiled) = compiled { + let from_compiled = rt.execute(&compiled); + if let (Ok(a), Ok(b)) = (&outcome.result, &from_compiled.result) + && !same(&a.to_json(), &b.to_json()) + { + problems.push(format!("compiled result differed: {a} vs {b}")); + } + } + + if !problems.is_empty() { + failures.push(format!( + "{name}: + {}", + problems.join( + " + " + ) + )); + } + } + + if !failures.is_empty() { + panic!( + "{} of {} TypeScript parity cases failed: +{}", + failures.len(), + cases.len(), + failures.join( + " +" + ) + ); + } +} + +#[test] +fn typescript_suspend_and_resume() { + let code = r#" + declare const step: (n: number) => Promise + interface Acc { total: number } + const acc: Acc = { total: 0 } + for (const n of [1, 2, 3] as readonly number[]) { + acc.total += await step(n) + } + return acc.total + "#; + + let (started, ready) = mpsc::channel(); + let waiting = Runtime::make().globals(move |_| { + let started = started.clone(); + [( + "step", + HostFunction::new_async(move |args, _| { + let n = args.first().and_then(HostValue::as_f64).unwrap_or(0.0); + let started = started.clone(); + async move { + if n == 2.0 { + let _ = started.send(()); + std::future::pending::<()>().await; + } + Ok(HostValue::from(n * 10.0)) + } + }) + .idempotent(), + )] + }); + + let program = waiting.program(code, &ProgramOptions::new().typescript(true)); + let suspender = program.suspender(); + let handle = thread::spawn(move || { + ready.recv().unwrap(); + suspender.suspend(None).unwrap() + }); + let outcome = program.run_resumable().unwrap(); + let _ = handle.join().unwrap(); + let RunOutcome::Suspended(suspended) = outcome else { + panic!("expected suspended outcome"); + }; + let bytes = to_bytes(&suspended.state); + + let resuming = Runtime::make().globals(|_| { + [( + "step", + HostFunction::new_async(|args, _| { + let n = args.first().and_then(HostValue::as_f64).unwrap_or(0.0); + async move { Ok(HostValue::from(n * 10.0)) } + }) + .idempotent(), + )] + }); + let restored = from_bytes(&bytes).unwrap(); + let finished = resuming.resume(&restored).unwrap().run().unwrap(); + assert_eq!(finished.json().unwrap(), serde_json::json!(60)); +} + +/// A TypeScript source is parsed on a thread with the stack its nesting needs, by a bound that reads it as +/// TypeScript: each of these nests 500 deep where the reading of JavaScript sees no nesting, and overflowed the +/// stack. It may compile or not: it returns. +#[test] +fn typescript_nesting_does_not_overflow_the_stack() { + for (head, open, close) in [ + ("type X = ", "A<0, ", ">"), + ("type X = ", "keyof\n", ""), + ("type X = ", "A extends\nB ? C :\n", ""), + ("x = ", "(a: T) => ", ""), + ("x = ", "f(", ")"), + ("x = ", "a / [", "] / 1"), + ("x = ", "a! / [", "] / 1"), + ("x = ", "1 as\nunknown as\n", ""), + ] { + let code = format!("{head}{}1{}", open.repeat(500), close.repeat(500)); + let _ = Runtime::make().compile_with(&code, &CompileOptions::new().typescript(true)); + } +} diff --git a/src/compiler/scope.ts b/src/compiler/scope.ts index 31e0268c..72b81e48 100644 --- a/src/compiler/scope.ts +++ b/src/compiler/scope.ts @@ -122,10 +122,19 @@ const plainKey = (key: Expression | PrivateIdentifier): boolean => * Pass 1: walks the AST to build lexical/var scopes, assign pre-order function indices, * resolve all identifier and `this` references, mark captured bindings, and assign local/upvalue slots. */ -// The offset of the first token after a class element's leading `static`. -const skipStatic = (code: string, start: number): number => { - let at = start + "static".length - while (at < code.length && /\s/.test(code[at]!)) at++ +const METHOD_MODIFIERS = new Set(["static", "public", "private", "protected", "override", "readonly", "abstract", "declare"]) + +// The offset of the first token after a class element's leading modifiers (`static`, TS access/override modifiers). +const skipMethodModifiers = (code: string, start: number, keyStart: number): number => { + let at = start + while (at < keyStart) { + while (at < keyStart && /\s/.test(code[at]!)) at++ + const wordStart = at + while (at < keyStart && /[a-z]/.test(code[at]!)) at++ + if (at === wordStart || (at < code.length && /[\w$]/.test(code[at]!))) return wordStart + if (!METHOD_MODIFIERS.has(code.slice(wordStart, at))) return wordStart + while (at < keyStart && /\s/.test(code[at]!)) at++ + } return at } @@ -572,8 +581,11 @@ export const analyzeScopes = (source: Source, internal = false): ScopeAnalysis = if (m.kind === "constructor") continue const method = visitFunction(m.value, classScope, fnInfo.index) method.flags |= CodeFlags.METHOD - // `static` belongs to the class element, not the method, so the text starts after it. - method.text = { start: m.static ? skipStatic(source.code, m.start) : m.start, end: m.end } + // `static` and TypeScript modifiers belong to the class element, not the method, so the text starts after them. + method.text = { + start: m.static || source.typescript ? skipMethodModifiers(source.code, m.start, m.key.start) : m.start, + end: m.end, + } } const fields = node.body.body.filter((m) => m.type === "PropertyDefinition") const instance = fieldInit( diff --git a/src/compiler/typescript.ts b/src/compiler/typescript.ts new file mode 100644 index 00000000..8e9d2235 --- /dev/null +++ b/src/compiler/typescript.ts @@ -0,0 +1,2425 @@ +import { Parser, TokenType, tokTypes, type Options, type Position, type Program } from "acorn" +import { formatLocation, type Diagnostic } from "../runtime/model.js" + +const atToken = new (TokenType as unknown as new (label: string) => TokenType)("@") +const ERASED_STATEMENT = "TsErasedStatement" + +/** Thrown inside the TypeScript parser when a valid non-erasable TypeScript construct is encountered. */ +class UnsupportedTsError extends Error { + constructor( + message: string, + readonly loc: Position, + ) { + super(message) + } +} + +const unsupportedTsDiagnostic = (message: string, loc: Position): Diagnostic => { + const location = { line: loc.line, column: loc.column + 1 } + return { + kind: "UnsupportedSyntax", + message: `SyntaxError: ${message}${formatLocation(location)}`, + location, + } +} + +const TS_UNSUPPORTED = { + enum: "TypeScript enums are not supported. Use a plain object instead.", + namespace: "TypeScript namespaces with runtime values are not supported.", + parameterProperty: + "TypeScript parameter properties are not supported. Declare and assign the field in the constructor instead.", + decorator: "Decorators are not supported.", + importEquals: "TypeScript 'import =' declarations are not supported.", + exportAssignment: "TypeScript 'export =' declarations are not supported.", + angleBracketAssertion: "Angle-bracket type assertions are not supported. Use 'as' instead.", +} as const + +// Acorn's internal Parser methods and fields are not declared on its public .d.ts, so we type the exact subset +// used by our Parser.extend plugin (acorn is pinned to 8.16.0). +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type AnyNode = Record + +interface AcornScope { + flags: number + var: Array + lexical: Array + functions: Array +} + +interface AcornPrivateName { + declared: Record + used: Array +} + +interface AcornParserState { + pos: number + curLine: number + lineStart: number + start: number + end: number + startLoc: Position + endLoc: Position + lastTokStart: number + lastTokEnd: number + lastTokStartLoc: Position + lastTokEndLoc: Position + type: TokenType + value: unknown + containsEsc: boolean + exprAllowed: boolean + strict: boolean + potentialArrowAt: number + potentialArrowInForAwait: boolean + awaitIdentPos: number + awaitPos: number + yieldPos: number + context: Array + labels: Array + undefinedExports: Record + scopeStack: Array + privateNameStack: Array +} + +interface AcornInternals { + options: Options + input: string + pos: number + curLine: number + lineStart: number + start: number + end: number + startLoc: Position + endLoc: Position + lastTokStart: number + lastTokEnd: number + lastTokStartLoc: Position + lastTokEndLoc: Position + type: TokenType + value: unknown + containsEsc: boolean + exprAllowed: boolean + strict: boolean + potentialArrowAt: number + potentialArrowInForAwait: boolean + awaitIdentPos: number + awaitPos: number + yieldPos: number + context: Array + labels: Array + undefinedExports: Record + scopeStack: Array + privateNameStack: Array + treatFunctionsAsVar: boolean + next(ignoreEscapeSequenceInKeyword?: boolean): void + nextToken(): void + finishToken(type: TokenType, val?: unknown): void + eat(type: TokenType): boolean + eatContextual(name: string): boolean + isContextual(name: string): boolean + expect(type: TokenType): void + expectContextual(name: string): void + semicolon(): void + canInsertSemicolon(): boolean + afterTrailingComma(tokType: TokenType, notNext?: boolean): boolean + startNode(): AnyNode + startNodeAt(pos: number, loc: Position): AnyNode + finishNode(node: AnyNode, type: string): AnyNode + raise(pos: number, message: string): never + raiseRecoverable(pos: number, message: string): void + unexpected(pos?: number): never + enterScope(flags: number): void + exitScope(): void + checkLValSimple(expr: AnyNode, bindingType?: number, checkClashes?: Record | false): void + checkLValPattern(expr: AnyNode, bindingType?: number, checkClashes?: Record | false): void + checkUnreserved(node: AnyNode): void + checkLocalExport(id: AnyNode): void + checkExport(exports: Record | undefined, name: unknown, pos: number): void + checkYieldAwaitInDefaultParams(): void + isAsyncFunction(): boolean + isClassElementNameStart(): boolean + parseTopLevel(node: AnyNode): AnyNode + parseStatement(context: string | null, topLevel?: boolean, exports?: Record): AnyNode + parseExpression(noIn?: boolean, refDestructuringErrors?: AnyNode): AnyNode + parseMaybeAssign(forInit?: boolean, refDestructuringErrors?: AnyNode | null, afterLeftParse?: unknown): AnyNode + parseMaybeConditional(forInit?: boolean, refDestructuringErrors?: AnyNode | null): AnyNode + parseExprOps(forInit?: boolean, refDestructuringErrors?: AnyNode | null): AnyNode + checkExpressionErrors(refDestructuringErrors?: AnyNode | null, andThrow?: boolean): boolean + parseExprOp(left: AnyNode, leftStartPos: number, leftStartLoc: Position, minPrec: number, forInit?: boolean): AnyNode + parseExprSubscripts(refDestructuringErrors?: AnyNode | null, forInit?: boolean): AnyNode + parseSubscripts(base: AnyNode, startPos: number, startLoc: Position, noCalls?: boolean, forInit?: boolean): AnyNode + parseSubscript( + base: AnyNode, + startPos: number, + startLoc: Position, + noCalls: boolean, + maybeAsyncArrow: boolean, + optionalChained: boolean, + forInit: boolean, + ): AnyNode + parseExprAtom(refDestructuringErrors?: AnyNode | null, forInit?: boolean, forNew?: boolean): AnyNode + parseExprList(close: TokenType, allowTrailingComma: boolean, allowEmpty: boolean, refDestructuringErrors?: AnyNode): Array + parseParenAndDistinguishExpression(canBeArrow: boolean, forInit?: boolean): AnyNode + parseArrowExpression(node: AnyNode, params: Array, isAsync: boolean, forInit?: boolean): AnyNode + parseIdent(liberal?: boolean): AnyNode + parsePropertyValue( + prop: AnyNode, + isPattern: boolean, + isGenerator: boolean, + isAsync: boolean, + startPos: number, + startLoc: Position, + refDestructuringErrors: AnyNode, + containsEsc: boolean, + ): void + parseMethod(isGenerator: boolean, isAsync: boolean, allowDirectSuper?: boolean): AnyNode + parseFunction(node: AnyNode, statement: number, allowExpressionBody?: boolean, isAsync?: boolean, forInit?: boolean): AnyNode + parseFunctionParams(node: AnyNode): void + parseFunctionBody(node: AnyNode, isArrowFunction?: boolean, isMethod?: boolean, forInit?: boolean): void + initFunction(node: AnyNode): void + parseBindingAtom(): AnyNode + parseBindingListItem(param: AnyNode): AnyNode + parseRestBinding(): AnyNode + parseMaybeDefault(startPos: number, startLoc: Position, left?: AnyNode): AnyNode + parseVarId(decl: AnyNode, kind: string): void + parseClass(node: AnyNode, isStatement: boolean | string): AnyNode + parseClassId(node: AnyNode, isStatement: boolean | string): void + parseClassSuper(node: AnyNode): void + parseClassElement(constructorAllowsSuper: boolean): AnyNode | null + parseClassElementName(element: AnyNode): void + parseClassMethod(method: AnyNode, isGenerator: boolean, isAsync: boolean, allowsDirectSuper: boolean): AnyNode + parseClassField(field: AnyNode): AnyNode + parseClassStaticBlock(node: AnyNode): AnyNode + parseImport(node: AnyNode): AnyNode + parseImportSpecifier(): AnyNode + parseImportDefaultSpecifier(): AnyNode + parseImportNamespaceSpecifier(): AnyNode + parseExport(node: AnyNode, exports?: Record): AnyNode + parseExportSpecifier(exports?: Record): AnyNode + parseModuleExportName(): AnyNode + parseWithClause(): Array + parseBlock(createNewLexicalScope?: boolean, node?: AnyNode, exitStrict?: boolean): AnyNode + parseSwitchStatement(node: AnyNode): AnyNode + parseCatchClauseParam(): AnyNode + getTokenFromCode(code: number): void + shouldParseExportStatement(): boolean +} + +// Acorn's binding constants (matching acorn 8.16.0). +const BIND_VAR = 1 +const BIND_LEXICAL = 2 +const BIND_FUNCTION = 3 +const BIND_SIMPLE_CATCH = 4 +const FUNC_STATEMENT = 1 +const FUNC_HANGING_STATEMENT = 2 +const FUNC_NULLABLE_ID = 4 +const SCOPE_FUNCTION = 2 +const SCOPE_ASYNC = 4 +const SCOPE_GENERATOR = 8 +const SCOPE_SUPER = 64 +const SCOPE_DIRECT_SUPER = 128 +const SCOPE_SIMPLE_CATCH = 32 + +const functionFlags = (async: boolean, generator: boolean) => + SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0) + +const lineBreakRe = /[\r\n\u2028\u2029]/ + +const CLASS_MODIFIERS = new Set(["public", "private", "protected", "readonly", "override", "abstract", "declare"]) +const PARAM_MODIFIERS = new Set(["public", "private", "protected", "readonly", "override"]) + +const TYPE_DECLARATION_STARTERS = new Set([ + "const", + "let", + "var", + "function", + "async", + "class", + "abstract", + "interface", + "type", + "enum", + "namespace", + "module", + "global", +]) + +// Tokens that may immediately follow a TSInstantiationExpression `expr` without making `<` a comparison. +const isInstantiationFollower = (type: TokenType, value: unknown, canInsertSemi: boolean): boolean => { + if (canInsertSemi) return true + if ( + type === tokTypes.eof || + type === tokTypes.semi || + type === tokTypes.comma || + type === tokTypes.parenR || + type === tokTypes.bracketR || + type === tokTypes.braceR || + type === tokTypes.braceL || + type === tokTypes.colon || + type === tokTypes.question || + type === tokTypes.dot || + type === tokTypes.questionDot || + type === tokTypes.bracketL || + type === tokTypes.eq || + type === tokTypes.assign || + type === tokTypes.equality || + type === tokTypes.logicalAND || + type === tokTypes.logicalOR || + type === tokTypes.coalesce || + type === tokTypes._in || + type === tokTypes._instanceof + ) { + return true + } + if (type === tokTypes.prefix && value === "!") return true + if (type === tokTypes.name && (value === "as" || value === "satisfies" || value === "implements")) return true + return false +} + +const isMemberNameFollowNotModifier = (type: TokenType, value: unknown): boolean => + type === tokTypes.parenL || + type === tokTypes.eq || + type === tokTypes.colon || + type === tokTypes.question || + type === tokTypes.semi || + type === tokTypes.braceR || + (type === tokTypes.prefix && value === "!") || + (type === tokTypes.relational && value === "<") + +const tsPlugin = (Base: typeof Parser): typeof Parser => { + const Super = Base as unknown as new (...args: Array) => AcornInternals + + class TsParser extends Super { + tsInConstructorParams = false + tsInAmbient = false + /** Whether the type being skipped is a conditional type's `extends` operand, where no conditional type may start. */ + tsNoConditional = false + /** Where the conditional consequent being parsed starts, or the expression body of an arrow that starts one. */ + tsConsequentStart = -1 + + tsUnsupported(message: string, loc: Position = this.startLoc): never { + throw new UnsupportedTsError(message, loc) + } + + tsErased(): AnyNode { + return { type: ERASED_STATEMENT, start: this.start, end: this.start } + } + + tsHasLineBreakBefore(): boolean { + return lineBreakRe.test(this.input.slice(this.lastTokEnd, this.start)) + } + + tsSaveState(): AcornParserState { + return { + pos: this.pos, + curLine: this.curLine, + lineStart: this.lineStart, + start: this.start, + end: this.end, + startLoc: this.startLoc, + endLoc: this.endLoc, + lastTokStart: this.lastTokStart, + lastTokEnd: this.lastTokEnd, + lastTokStartLoc: this.lastTokStartLoc, + lastTokEndLoc: this.lastTokEndLoc, + type: this.type, + value: this.value, + containsEsc: this.containsEsc, + exprAllowed: this.exprAllowed, + strict: this.strict, + potentialArrowAt: this.potentialArrowAt, + potentialArrowInForAwait: this.potentialArrowInForAwait, + awaitIdentPos: this.awaitIdentPos, + awaitPos: this.awaitPos, + yieldPos: this.yieldPos, + context: this.context.slice(), + labels: this.labels.slice(), + undefinedExports: Object.assign(Object.create(null), this.undefinedExports), + scopeStack: this.scopeStack.map((s) => ({ + flags: s.flags, + var: s.var.slice(), + lexical: s.lexical.slice(), + functions: s.functions.slice(), + })), + privateNameStack: this.privateNameStack.map((p) => ({ + declared: Object.assign(Object.create(null), p.declared), + used: p.used.slice(), + })), + } + } + + tsRestoreState(s: AcornParserState): void { + this.pos = s.pos + this.curLine = s.curLine + this.lineStart = s.lineStart + this.start = s.start + this.end = s.end + this.startLoc = s.startLoc + this.endLoc = s.endLoc + this.lastTokStart = s.lastTokStart + this.lastTokEnd = s.lastTokEnd + this.lastTokStartLoc = s.lastTokStartLoc + this.lastTokEndLoc = s.lastTokEndLoc + this.type = s.type + this.value = s.value + this.containsEsc = s.containsEsc + this.exprAllowed = s.exprAllowed + this.strict = s.strict + this.potentialArrowAt = s.potentialArrowAt + this.potentialArrowInForAwait = s.potentialArrowInForAwait + this.awaitIdentPos = s.awaitIdentPos + this.awaitPos = s.awaitPos + this.yieldPos = s.yieldPos + this.context = s.context + this.labels = s.labels + this.undefinedExports = s.undefinedExports + this.scopeStack = s.scopeStack + this.privateNameStack = s.privateNameStack + } + + tsTryParse(fn: () => T): { ok: true; value: T } | { ok: false } { + const state = this.tsSaveState() + try { + return { ok: true, value: fn() } + } catch (error) { + this.tsRestoreState(state) + if (error instanceof UnsupportedTsError) throw error + if (error instanceof SyntaxError) return { ok: false } + throw error + } + } + + tsLookAhead(fn: () => T): T { + const state = this.tsSaveState() + try { + return fn() + } finally { + this.tsRestoreState(state) + } + } + + override getTokenFromCode(code: number): void { + if (code === 64) { + ++this.pos + this.finishToken(atToken) + return + } + super.getTokenFromCode(code) + } + + tsIsLt(): boolean { + return this.type === tokTypes.relational && this.value === "<" + } + + tsIsGt(): boolean { + if (this.type === tokTypes.relational && (this.value === ">" || this.value === ">=")) return true + if (this.type === tokTypes.bitShift && (this.value === ">>" || this.value === ">>>")) return true + if (this.type === tokTypes.assign && (this.value === ">>=" || this.value === ">>>=")) return true + return false + } + + tsEatGt(): boolean { + if (this.type === tokTypes.relational && this.value === ">") { + this.next() + return true + } + if (!this.tsIsGt()) return false + const nextPos = this.start + 1 + this.lastTokStart = this.start + this.lastTokEnd = nextPos + this.lastTokStartLoc = this.startLoc + this.lastTokEndLoc = { line: this.startLoc.line, column: this.startLoc.column + 1 } + this.pos = nextPos + this.exprAllowed = false + this.nextToken() + return true + } + + tsExpectGt(): void { + if (!this.tsEatGt()) this.unexpected() + } + + tsIsIdentOrKeyword(): boolean { + return this.type === tokTypes.name || this.type.keyword !== undefined + } + + // --- Type Grammar --- + + tsSkipTypeAnnotation(): void { + if (this.eat(tokTypes.colon)) this.tsSkipType() + } + + tsSkipReturnType(): void { + if (this.eat(tokTypes.colon)) this.tsSkipTypeOrPredicate() + } + + tsSkipTypeOrPredicate(): void { + // `asserts x [is T]` or `asserts this [is T]` + if (this.isContextual("asserts") && !this.containsEsc) { + const matched = this.tsTryParse(() => { + this.next() + if (this.tsHasLineBreakBefore()) this.unexpected() + if (this.type === tokTypes._this || this.type === tokTypes.name) { + this.next() + if (this.isContextual("is") && !this.containsEsc && !this.tsHasLineBreakBefore()) { + this.next() + this.tsSkipType() + } + return true + } + this.unexpected() + }) + if (matched.ok) return + } + // `x is T` or `this is T` + if (this.type === tokTypes._this || this.type === tokTypes.name) { + const isPred = this.tsLookAhead(() => { + this.next() + return this.isContextual("is") && !this.containsEsc && !this.tsHasLineBreakBefore() + }) + if (isPred) { + this.next() + this.next() + this.tsSkipType() + return + } + } + this.tsSkipType() + } + + tsSkipType(allowConditional = true): void { + const outer = this.tsNoConditional + this.tsNoConditional = !allowConditional + try { + if (this.tsIsFnOrCtorType()) { + this.tsSkipFnOrCtorType() + return + } + this.tsSkipUnionType() + if (allowConditional && this.type === tokTypes._extends && !this.tsHasLineBreakBefore()) { + this.next() + this.tsSkipType(false) + this.expect(tokTypes.question) + this.tsSkipType(true) + this.expect(tokTypes.colon) + this.tsSkipType(true) + } + } finally { + this.tsNoConditional = outer + } + } + + tsIsFnOrCtorType(): boolean { + if (this.type === tokTypes._new || this.tsIsLt()) return true + if (this.isContextual("abstract") && !this.containsEsc) { + return this.tsLookAhead(() => { + this.next() + return !this.tsHasLineBreakBefore() && this.type === tokTypes._new + }) + } + if (this.type !== tokTypes.parenL) return false + return this.tsLookAhead(() => { + const attempt = this.tsTryParse(() => { + this.tsSkipTypeParamListTuple() + return this.type === tokTypes.arrow + }) + return attempt.ok && attempt.value + }) + } + + tsSkipTypeParamListTuple(): void { + this.expect(tokTypes.parenL) + while (this.type !== tokTypes.parenR) { + if (this.eat(tokTypes.ellipsis)) { + this.tsSkipTypeParamBinding() + if (this.eat(tokTypes.colon)) this.tsSkipType() + this.eat(tokTypes.comma) + break + } + this.tsSkipTypeParamBinding() + this.eat(tokTypes.question) + if (this.eat(tokTypes.colon)) this.tsSkipType() + if (!this.eat(tokTypes.comma)) break + } + this.expect(tokTypes.parenR) + } + + tsSkipTypeParamBinding(): void { + if (this.type === tokTypes.braceL || this.type === tokTypes.bracketL) { + this.tsSkipBalanced(this.type === tokTypes.braceL ? tokTypes.braceR : tokTypes.bracketR) + return + } + if (this.type === tokTypes._this || this.tsIsIdentOrKeyword()) { + this.next() + return + } + this.unexpected() + } + + tsSkipFnOrCtorType(): void { + if (this.isContextual("abstract") && !this.containsEsc) this.next() + this.eat(tokTypes._new) + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipTypeParamListTuple() + this.expect(tokTypes.arrow) + this.tsSkipTypeOrPredicate() + } + + tsSkipUnionType(): void { + this.eat(tokTypes.bitwiseOR) + this.tsSkipIntersectionType() + while (this.eat(tokTypes.bitwiseOR)) this.tsSkipIntersectionType() + } + + tsSkipIntersectionType(): void { + this.eat(tokTypes.bitwiseAND) + this.tsSkipTypeOperatorOrHigher() + while (this.eat(tokTypes.bitwiseAND)) this.tsSkipTypeOperatorOrHigher() + } + + tsSkipTypeOperatorOrHigher(): void { + if ( + (this.isContextual("keyof") || this.isContextual("readonly") || this.isContextual("unique")) && + !this.containsEsc + ) { + const isReadonly = this.value === "readonly" + const isOp = this.tsLookAhead(() => { + this.next() + return ( + this.type !== tokTypes.dot && + (isReadonly || this.type !== tokTypes.bracketL) && + this.type !== tokTypes.comma && + this.type !== tokTypes.parenR && + this.type !== tokTypes.bracketR && + this.type !== tokTypes.braceR && + this.type !== tokTypes.semi && + this.type !== tokTypes.bitwiseOR && + this.type !== tokTypes.bitwiseAND && + this.type !== tokTypes.question && + this.type !== tokTypes.colon && + this.type !== tokTypes.eq && + !this.tsIsGt() && + !this.tsIsLt() + ) + }) + if (isOp) { + this.next() + this.tsSkipTypeOperatorOrHigher() + return + } + } + if (this.isContextual("infer") && !this.containsEsc) { + const isInfer = this.tsLookAhead(() => { + this.next() + return !this.tsHasLineBreakBefore() && this.type === tokTypes.name + }) + if (isInfer) { + this.next() + this.next() + if (this.type === tokTypes._extends && !this.tsHasLineBreakBefore()) { + const inExtendsOperand = this.tsNoConditional + const hasExtends = this.tsTryParse(() => { + this.next() + this.tsSkipType(false) + // Followed by `?`, the `extends` starts a conditional type on `infer T`, unless none may start here: in + // `A extends infer T extends U ? X : Y` it is the constraint and the `?` is the outer conditional's. + if (!inExtendsOperand && this.type === tokTypes.question) this.unexpected() + return true + }) + if (hasExtends.ok) return + } + return + } + } + this.tsSkipPostfixType() + } + + tsSkipPostfixType(): void { + this.tsSkipPrimaryType() + while (!this.tsHasLineBreakBefore() && this.type === tokTypes.bracketL) { + this.next() + if (!this.eat(tokTypes.bracketR)) { + this.tsSkipType() + this.expect(tokTypes.bracketR) + } + } + } + + tsSkipPrimaryType(): void { + switch (this.type) { + case tokTypes.parenL: + this.next() + this.tsSkipType() + this.expect(tokTypes.parenR) + return + case tokTypes.braceL: + this.tsSkipObjectOrMappedType() + return + case tokTypes.bracketL: + this.tsSkipTupleType() + return + case tokTypes.backQuote: + this.tsSkipTemplateLiteralType() + return + case tokTypes.string: + case tokTypes.num: + case tokTypes._true: + case tokTypes._false: + case tokTypes._null: + case tokTypes._void: + case tokTypes._this: + this.next() + return + case tokTypes.plusMin: + if (this.value === "-") { + this.next() + if (this.type !== tokTypes.num) this.unexpected() + this.next() + return + } + this.unexpected() + case tokTypes._typeof: + this.next() + if (this.type === tokTypes._import) { + this.tsSkipImportType() + return + } + this.tsSkipQualifiedName() + if (this.tsIsLt() && !this.tsHasLineBreakBefore()) this.tsSkipTypeArguments() + return + case tokTypes._import: + this.tsSkipImportType() + return + default: + if (this.type === tokTypes.name || this.type.keyword !== undefined) { + const singleWord = this.type === tokTypes.name && !this.containsEsc ? String(this.value) : undefined + const dotted = this.tsSkipQualifiedName() + const isPrimitiveKeyword = + !dotted && + singleWord !== undefined && + (singleWord === "any" || + singleWord === "unknown" || + singleWord === "never" || + singleWord === "boolean" || + singleWord === "number" || + singleWord === "bigint" || + singleWord === "string" || + singleWord === "symbol" || + singleWord === "object" || + singleWord === "undefined") + if (!isPrimitiveKeyword && this.tsIsLt() && !this.tsHasLineBreakBefore()) { + this.tsTryParse(() => { + this.tsSkipTypeArguments() + return true + }) + } + return + } + this.unexpected() + } + } + + tsSkipImportType(): void { + this.expect(tokTypes._import) + this.expect(tokTypes.parenL) + this.tsSkipType() + if (this.eat(tokTypes.comma)) { + if (this.type !== tokTypes.parenR) { + this.tsSkipType() + this.eat(tokTypes.comma) + } + } + this.expect(tokTypes.parenR) + if (this.eat(tokTypes.dot)) this.tsSkipQualifiedName() + if (this.tsIsLt() && !this.tsHasLineBreakBefore()) this.tsSkipTypeArguments() + } + + tsSkipQualifiedName(): boolean { + if (!this.tsIsIdentOrKeyword()) this.unexpected() + this.next() + let dotted = false + while (this.eat(tokTypes.dot)) { + dotted = true + if (!this.tsIsIdentOrKeyword()) this.unexpected() + this.next() + } + return dotted + } + + tsSkipTemplateLiteralType(): void { + this.expect(tokTypes.backQuote) + // Acorn switches lexer context inside template literals; read template chunks and skip ${Type} slots. + while (this.type !== tokTypes.backQuote) { + if (this.type === tokTypes.dollarBraceL) { + this.next() + this.tsSkipType() + this.expect(tokTypes.braceR) + } else if (this.type === tokTypes.template || this.type === tokTypes.invalidTemplate) { + this.next() + } else { + this.unexpected() + } + } + this.expect(tokTypes.backQuote) + } + + tsSkipTupleType(): void { + this.expect(tokTypes.bracketL) + while (!this.eat(tokTypes.bracketR)) { + const isRest = this.eat(tokTypes.ellipsis) + const isLabeled = this.tsLookAhead(() => { + if (!this.tsIsIdentOrKeyword()) return false + this.next() + this.eat(tokTypes.question) + return this.type === tokTypes.colon + }) + if (isLabeled) { + this.next() + this.eat(tokTypes.question) + this.expect(tokTypes.colon) + } + this.tsSkipType() + if (!isRest) this.eat(tokTypes.question) + if (!this.eat(tokTypes.comma)) { + this.expect(tokTypes.bracketR) + break + } + } + } + + tsSkipObjectOrMappedType(): void { + this.expect(tokTypes.braceL) + // Mapped type: { [+|-]? readonly? [K in T (as U)?] [+|-]? ? : V ;? } + const isMapped = this.tsLookAhead(() => { + if (this.type === tokTypes.plusMin) this.next() + if (this.isContextual("readonly")) this.next() + if (!this.eat(tokTypes.bracketL)) return false + if (!this.tsIsIdentOrKeyword()) return false + this.next() + return this.type === tokTypes._in + }) + if (isMapped) { + if (this.type === tokTypes.plusMin) this.next() + if (this.isContextual("readonly")) this.next() + this.expect(tokTypes.bracketL) + this.next() // key name + this.expect(tokTypes._in) + this.tsSkipType() + if (this.eatContextual("as")) this.tsSkipType() + this.expect(tokTypes.bracketR) + if (this.type === tokTypes.plusMin) this.next() + this.eat(tokTypes.question) + if (this.eat(tokTypes.colon)) this.tsSkipType() + this.eat(tokTypes.semi) || this.eat(tokTypes.comma) + this.expect(tokTypes.braceR) + return + } + while (!this.eat(tokTypes.braceR)) { + if (this.eat(tokTypes.semi) || this.eat(tokTypes.comma)) continue + this.tsSkipTypeMember() + this.eat(tokTypes.semi) || this.eat(tokTypes.comma) + } + } + + tsSkipTypeMember(): void { + // Call signature: (...): R + if (this.type === tokTypes.parenL || this.tsIsLt()) { + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipTypeParamListTuple() + this.tsSkipReturnType() + return + } + // Construct signature: new (...): R + if (this.type === tokTypes._new) { + const isCtorSig = this.tsLookAhead(() => { + this.next() + return this.type === tokTypes.parenL || this.tsIsLt() + }) + if (isCtorSig) { + this.next() + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipTypeParamListTuple() + this.tsSkipReturnType() + return + } + } + // readonly modifier and get / set accessor in type literal + if (this.isContextual("readonly") && this.tsIsTypeMemberModifier()) this.next() + if ((this.isContextual("get") || this.isContextual("set")) && this.tsIsTypeMemberModifier()) this.next() + // Index signature [k: string]: V or computed property [expr]: V + if (this.eat(tokTypes.bracketL)) { + const isIndex = this.tsLookAhead(() => { + if (!this.tsIsIdentOrKeyword()) return false + this.next() + return this.type === tokTypes.colon + }) + if (isIndex) { + this.next() + this.expect(tokTypes.colon) + this.tsSkipType() + this.expect(tokTypes.bracketR) + this.tsSkipTypeAnnotation() + return + } + this.parseExpression() + this.expect(tokTypes.bracketR) + } else if (this.type === tokTypes.string || this.type === tokTypes.num || this.tsIsIdentOrKeyword()) { + this.next() + } else { + this.unexpected() + } + this.eat(tokTypes.question) + if (this.tsIsLt() || this.type === tokTypes.parenL) { + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipTypeParamListTuple() + this.tsSkipReturnType() + } else { + this.tsSkipTypeAnnotation() + } + } + + tsIsTypeMemberModifier(): boolean { + return this.tsLookAhead(() => { + this.next() + return ( + this.type !== tokTypes.colon && + this.type !== tokTypes.question && + this.type !== tokTypes.parenL && + this.type !== tokTypes.semi && + this.type !== tokTypes.comma && + this.type !== tokTypes.braceR && + !this.tsIsLt() + ) + }) + } + + tsSkipTypeParameters(): void { + if (!this.tsIsLt()) this.unexpected() + this.next() + while (!this.tsEatGt()) { + // Modifiers: const, in, out (in any valid combination: const, in, out, in out) + while ( + (this.type === tokTypes._const || this.type === tokTypes._in || this.isContextual("out")) && + this.tsLookAhead(() => { + this.next() + return this.tsIsIdentOrKeyword() + }) + ) { + this.next() + } + if (!this.tsIsIdentOrKeyword()) this.unexpected() + this.next() + if (this.eat(tokTypes._extends)) this.tsSkipType() + if (this.eat(tokTypes.eq)) this.tsSkipType() + if (!this.eat(tokTypes.comma)) { + this.tsExpectGt() + break + } + } + } + + tsSkipTypeArguments(): void { + if (!this.tsIsLt()) this.unexpected() + this.next() + if (this.tsIsGt()) this.unexpected() // empty <> is invalid in TS type arguments + while (!this.tsEatGt()) { + this.tsSkipType() + if (!this.eat(tokTypes.comma)) { + this.tsExpectGt() + break + } + } + } + + tsSkipBalanced(close: TokenType): void { + this.next() + let depth = 1 + while (depth > 0 && this.type !== tokTypes.eof) { + if (this.type === tokTypes.braceL || this.type === tokTypes.bracketL || this.type === tokTypes.parenL) { + depth++ + } else if (this.type === tokTypes.braceR || this.type === tokTypes.bracketR || this.type === tokTypes.parenR) { + depth-- + if (depth === 0) { + if (this.type !== close) this.unexpected() + this.next() + return + } + } + this.next() + } + this.unexpected() + } + + // --- Statement Lists (skip erased TS declarations) --- + + override parseTopLevel(node: AnyNode): AnyNode { + const program = super.parseTopLevel(node) + program.body = program.body.filter((s: AnyNode) => s.type !== ERASED_STATEMENT) + return program + } + + override parseBlock(createNewLexicalScope = true, node?: AnyNode, exitStrict?: boolean): AnyNode { + const block = super.parseBlock(createNewLexicalScope, node, exitStrict) + block.body = block.body.filter((s: AnyNode) => s.type !== ERASED_STATEMENT) + return block + } + + override parseSwitchStatement(node: AnyNode): AnyNode { + const sw = super.parseSwitchStatement(node) + for (const c of sw.cases) c.consequent = c.consequent.filter((s: AnyNode) => s.type !== ERASED_STATEMENT) + return sw + } + + // --- Statements --- + + override parseStatement(context: string | null, topLevel?: boolean, exports?: Record): AnyNode { + // Decorators at statement position (`@dec class A {}`, `@dec export class A {}`) + if (this.type === atToken) { + this.tsUnsupported(TS_UNSUPPORTED.decorator) + } + + // `const enum` + if (this.type === tokTypes._const) { + const isConstEnum = this.tsLookAhead(() => { + this.next() + return !this.tsHasLineBreakBefore() && this.isContextual("enum") && !this.containsEsc + }) + if (isConstEnum) { + if (this.tsInAmbient) { + this.next() + return this.tsSkipEnum() + } + this.tsUnsupported(TS_UNSUPPORTED.enum) + } + } + + // `enum` + if (this.isContextual("enum") && !this.containsEsc) { + if (this.tsInAmbient) return this.tsSkipEnum() + this.tsUnsupported(TS_UNSUPPORTED.enum) + } + + if (this.type === tokTypes.name && !this.containsEsc) { + const word = this.value + if (word === "interface" && this.tsIsInterfaceDeclaration()) { + if (context) this.unexpected() + return this.tsSkipInterface() + } + if (word === "type" && this.tsIsTypeAliasDeclaration()) { + if (context) this.unexpected() + return this.tsSkipTypeAlias() + } + if (word === "declare" && this.tsIsDeclareStatement()) { + if (context) this.unexpected() + return this.tsSkipDeclare() + } + if (word === "abstract" && this.tsIsAbstractClass()) { + if (context) this.unexpected() + const node = this.startNode() + this.next() // skip `abstract` + return this.parseClass(node, true) + } + if ((word === "namespace" || word === "module") && this.tsIsNamespaceDeclaration()) { + if (context) this.unexpected() + return this.tsParseNamespace(this.tsInAmbient) + } + } + + return super.parseStatement(context, topLevel, exports) + } + + tsIsInterfaceDeclaration(): boolean { + return this.tsLookAhead(() => { + this.next() + if (this.tsHasLineBreakBefore() || !this.tsIsIdentOrKeyword()) return false + this.next() + return this.type === tokTypes.braceL || this.type === tokTypes._extends || this.tsIsLt() + }) + } + + tsSkipInterface(): AnyNode { + this.next() // interface + this.next() // name + if (this.tsIsLt()) this.tsSkipTypeParameters() + if (this.eat(tokTypes._extends)) { + do { + this.tsSkipQualifiedName() + if (this.tsIsLt()) this.tsSkipTypeArguments() + } while (this.eat(tokTypes.comma)) + } + this.tsSkipObjectOrMappedType() + return this.tsErased() + } + + tsIsTypeAliasDeclaration(): boolean { + return this.tsLookAhead(() => { + this.next() + if (this.tsHasLineBreakBefore() || !this.tsIsIdentOrKeyword()) return false + this.next() + return this.type === tokTypes.eq || this.tsIsLt() + }) + } + + tsSkipTypeAlias(): AnyNode { + this.next() // type + this.next() // name + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.expect(tokTypes.eq) + this.tsSkipType() + this.semicolon() + return this.tsErased() + } + + tsIsDeclareStatement(): boolean { + return this.tsLookAhead(() => { + this.next() + if (this.tsHasLineBreakBefore()) return false + const name = this.type === tokTypes.name ? String(this.value) : this.type.keyword + if (name === undefined || !TYPE_DECLARATION_STARTERS.has(name)) return false + if (name === "async") { + this.next() + return !this.tsHasLineBreakBefore() && this.type === tokTypes._function + } + if (name === "abstract") { + this.next() + return !this.tsHasLineBreakBefore() && this.type === tokTypes._class + } + if (name === "global") { + this.next() + return this.type === tokTypes.braceL + } + return true + }) + } + + tsSkipDeclare(): AnyNode { + this.next() // declare + const prevAmbient = this.tsInAmbient + this.tsInAmbient = true + try { + if (this.type === tokTypes._const) { + if ( + this.tsLookAhead(() => { + this.next() + return !this.tsHasLineBreakBefore() && this.isContextual("enum") && !this.containsEsc + }) + ) { + this.next() + return this.tsSkipEnum() + } + return this.tsSkipAmbientVar() + } + if (this.type === tokTypes._var || this.isContextual("let")) return this.tsSkipAmbientVar() + if (this.isContextual("enum") && !this.containsEsc) return this.tsSkipEnum() + if (this.type === tokTypes._function) return this.tsSkipAmbientFunction() + if (this.isContextual("async")) { + this.next() + return this.tsSkipAmbientFunction() + } + if (this.isContextual("abstract")) { + this.next() + return this.tsSkipAmbientClass() + } + if (this.type === tokTypes._class) return this.tsSkipAmbientClass() + if (this.isContextual("interface")) return this.tsSkipInterface() + if (this.isContextual("type")) return this.tsSkipTypeAlias() + if (this.isContextual("global")) { + this.next() + this.tsSkipBalanced(tokTypes.braceR) + return this.tsErased() + } + if (this.isContextual("namespace") || this.isContextual("module")) { + return this.tsParseNamespace(true) + } + this.unexpected() + } finally { + this.tsInAmbient = prevAmbient + } + } + + tsSkipAmbientVar(): AnyNode { + this.next() // const/let/var + do { + this.tsSkipAmbientPattern() + this.eat(tokTypes.prefix) // optional ! + this.tsSkipTypeAnnotation() + if (this.eat(tokTypes.eq)) this.parseMaybeAssign() + } while (this.eat(tokTypes.comma)) + this.semicolon() + return this.tsErased() + } + + tsSkipAmbientPattern(): void { + if (this.type === tokTypes.braceL || this.type === tokTypes.bracketL) { + this.tsSkipBalanced(this.type === tokTypes.braceL ? tokTypes.braceR : tokTypes.bracketR) + return + } + if (!this.tsIsIdentOrKeyword()) this.unexpected() + this.next() + } + + tsSkipAmbientFunction(): AnyNode { + this.expect(tokTypes._function) + this.eat(tokTypes.star) + if (this.tsIsIdentOrKeyword()) this.next() + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipAmbientParams() + this.tsSkipReturnType() + this.semicolon() + return this.tsErased() + } + + tsSkipAmbientParams(): void { + this.expect(tokTypes.parenL) + while (this.type !== tokTypes.parenR) { + if (this.eat(tokTypes.ellipsis)) { + this.tsSkipAmbientPattern() + this.tsSkipTypeAnnotation() + this.eat(tokTypes.comma) + break + } + // Skip modifiers in ambient constructor signatures + while (this.type === tokTypes.name && PARAM_MODIFIERS.has(String(this.value))) { + const isMod = this.tsLookAhead(() => { + this.next() + return this.type !== tokTypes.colon && this.type !== tokTypes.question && this.type !== tokTypes.comma && this.type !== tokTypes.parenR && this.type !== tokTypes.eq + }) + if (!isMod) break + this.next() + } + this.tsSkipAmbientPattern() + this.eat(tokTypes.question) + this.tsSkipTypeAnnotation() + if (this.eat(tokTypes.eq)) this.parseMaybeAssign() + if (!this.eat(tokTypes.comma)) break + } + this.expect(tokTypes.parenR) + } + + tsSkipAmbientClass(): AnyNode { + this.expect(tokTypes._class) + if (this.tsIsIdentOrKeyword()) this.next() + if (this.tsIsLt()) this.tsSkipTypeParameters() + if (this.eat(tokTypes._extends)) { + this.parseExprSubscripts(null, false) + if (this.tsIsLt()) this.tsSkipTypeArguments() + } + if (this.eatContextual("implements")) { + do { + this.tsSkipQualifiedName() + if (this.tsIsLt()) this.tsSkipTypeArguments() + } while (this.eat(tokTypes.comma)) + } + this.tsSkipBalanced(tokTypes.braceR) + return this.tsErased() + } + + tsSkipEnum(): AnyNode { + this.expectContextual("enum") + if (!this.tsIsIdentOrKeyword()) this.unexpected() + this.next() + this.tsSkipBalanced(tokTypes.braceR) + return this.tsErased() + } + + tsIsAbstractClass(): boolean { + return this.tsLookAhead(() => { + this.next() + return !this.tsHasLineBreakBefore() && this.type === tokTypes._class + }) + } + + tsIsNamespaceDeclaration(): boolean { + return this.tsLookAhead(() => { + const kw = this.value + this.next() + if (this.tsHasLineBreakBefore()) return false + if (kw === "module" && this.type === tokTypes.string) { + this.next() + return this.type === tokTypes.braceL || this.type === tokTypes.semi || this.canInsertSemicolon() + } + if (this.type !== tokTypes.name) return false + this.next() + while (this.eat(tokTypes.dot)) { + if (!this.tsIsIdentOrKeyword()) return false + this.next() + } + return this.type === tokTypes.braceL + }) + } + + tsParseNamespace(ambient: boolean): AnyNode { + const startLoc = this.startLoc + this.next() // namespace / module + if (this.type === tokTypes.string) { + // Ambient module `declare module "foo" { ... }` or `declare module "foo";` + if (!ambient) this.tsUnsupported(TS_UNSUPPORTED.namespace, startLoc) + this.next() + if (this.type === tokTypes.braceL) { + this.tsSkipBalanced(tokTypes.braceR) + } else { + this.semicolon() + } + return this.tsErased() + } + this.tsSkipQualifiedName() + if (ambient) { + this.tsSkipBalanced(tokTypes.braceR) + return this.tsErased() + } + // Non-ambient namespace: allowed only if every statement in its body is type-only (no runtime values). + this.expect(tokTypes.braceL) + while (!this.eat(tokTypes.braceR)) { + if (this.eat(tokTypes.semi)) continue + if (!this.tsSkipTypeOnlyNamespaceMember()) { + this.tsUnsupported(TS_UNSUPPORTED.namespace, startLoc) + } + } + return this.tsErased() + } + + tsSkipTypeOnlyNamespaceMember(): boolean { + if (this.type === tokTypes._export) { + this.next() + if (this.isContextual("type") && !this.containsEsc) { + if (this.tsIsTypeAliasDeclaration()) { + this.tsSkipTypeAlias() + return true + } + // `export type { ... } [from ...]` or `export type * ...` + if (this.tsLookAhead(() => { this.next(); return this.type === tokTypes.braceL || this.type === tokTypes.star })) { + this.tsSkipExportType() + return true + } + } + if (this.isContextual("interface") && !this.containsEsc && this.tsIsInterfaceDeclaration()) { + this.tsSkipInterface() + return true + } + if (this.isContextual("declare") && !this.containsEsc && this.tsIsDeclareStatement()) { + this.tsSkipDeclare() + return true + } + if ((this.isContextual("namespace") || this.isContextual("module")) && !this.containsEsc && this.tsIsNamespaceDeclaration()) { + // Nested namespace inside a type-only namespace: recursively check if type-only. + return this.tsTryTypeOnlyNestedNamespace() + } + if (this.type === tokTypes.braceL) { + const onlyTypes = this.tsTryParse(() => { + this.expect(tokTypes.braceL) + let count = 0 + while (!this.eat(tokTypes.braceR)) { + if (!this.isContextual("type") || this.containsEsc) this.unexpected() + this.next() + this.parseModuleExportName() + if (this.eatContextual("as")) this.parseModuleExportName() + count++ + if (!this.eat(tokTypes.comma)) { + this.expect(tokTypes.braceR) + break + } + } + if (count === 0) this.unexpected() + if (this.eatContextual("from")) { + if (this.type !== tokTypes.string) this.unexpected() + this.next() + } + this.semicolon() + return true + }) + return onlyTypes.ok + } + return false + } + if (this.type === tokTypes._import) { + const isImportType = this.tsLookAhead(() => { + this.next() + return this.isContextual("type") && !this.containsEsc + }) + if (!isImportType) return false + const stmt = this.parseImport(this.startNode()) + return stmt.type === ERASED_STATEMENT + } + if (this.type === tokTypes.name && !this.containsEsc) { + if (this.value === "interface" && this.tsIsInterfaceDeclaration()) { + this.tsSkipInterface() + return true + } + if (this.value === "type" && this.tsIsTypeAliasDeclaration()) { + this.tsSkipTypeAlias() + return true + } + if (this.value === "declare" && this.tsIsDeclareStatement()) { + this.tsSkipDeclare() + return true + } + if ((this.value === "namespace" || this.value === "module") && this.tsIsNamespaceDeclaration()) { + return this.tsTryTypeOnlyNestedNamespace() + } + } + return false + } + + tsTryTypeOnlyNestedNamespace(): boolean { + this.next() // namespace / module + this.tsSkipQualifiedName() + this.expect(tokTypes.braceL) + while (!this.eat(tokTypes.braceR)) { + if (this.eat(tokTypes.semi)) continue + if (!this.tsSkipTypeOnlyNamespaceMember()) return false + } + return true + } + + // --- Imports & Exports --- + + override parseImport(node: AnyNode): AnyNode { + const startLoc = this.startLoc + this.next() // import + + // `import "mod"` + if (this.type === tokTypes.string) { + node.specifiers = [] + node.source = this.parseExprAtom() + node.attributes = this.parseWithClause() + this.semicolon() + return this.finishNode(node, "ImportDeclaration") + } + + // `import type ...` + if (this.isContextual("type") && !this.containsEsc) { + const kind = this.tsLookAhead(() => { + this.next() + if (this.type === tokTypes.eq) return "default-eq" + if (this.type === tokTypes.name && this.value === "from") return "default-named-type" + if (this.type === tokTypes.comma) return "default-named-type" + if (this.type === tokTypes.braceL || this.type === tokTypes.star) return "import-type" + if (this.type === tokTypes.name) { + this.next() + if (this.type === tokTypes.eq) return "import-type-eq" + return "import-type" + } + return "default-named-type" + }) + if (kind === "import-type-eq") { + this.tsUnsupported(TS_UNSUPPORTED.importEquals, startLoc) + } + if (kind === "import-type") { + this.next() // consume `type` + this.tsSkipTypeOnlyImportSpecifiers() + this.expectContextual("from") + if (this.type !== tokTypes.string) this.unexpected() + this.next() + this.parseWithClause() + this.semicolon() + return this.tsErased() + } + } + + // `import x = require("...")` or `import x = A.B` + if (this.type === tokTypes.name) { + const isImportEquals = this.tsLookAhead(() => { + this.next() + return this.type === tokTypes.eq + }) + if (isImportEquals) { + this.tsUnsupported(TS_UNSUPPORTED.importEquals, startLoc) + } + } + + let hadTypeSpecifier = false + const specifiers: Array = [] + if (this.type === tokTypes.name) { + specifiers.push(this.parseImportDefaultSpecifier()) + if (this.eat(tokTypes.comma)) { + if (this.type === tokTypes.star) { + specifiers.push(this.parseImportNamespaceSpecifier()) + } else { + hadTypeSpecifier = this.tsParseNamedImportSpecifiers(specifiers) + } + } + } else if (this.type === tokTypes.star) { + specifiers.push(this.parseImportNamespaceSpecifier()) + } else { + hadTypeSpecifier = this.tsParseNamedImportSpecifiers(specifiers) + } + + this.expectContextual("from") + node.source = this.type === tokTypes.string ? this.parseExprAtom() : this.unexpected() + node.attributes = this.parseWithClause() + this.semicolon() + + // `import { type Foo } from "mod"`: all specifiers were type-only, so erase the whole import. + if (hadTypeSpecifier && specifiers.length === 0) return this.tsErased() + + node.specifiers = specifiers + return this.finishNode(node, "ImportDeclaration") + } + + tsSkipTypeOnlyImportSpecifiers(): void { + if (this.type === tokTypes.name) { + this.next() + if (!this.eat(tokTypes.comma)) return + } + if (this.eat(tokTypes.star)) { + this.expectContextual("as") + this.parseIdent() + return + } + this.expect(tokTypes.braceL) + while (!this.eat(tokTypes.braceR)) { + this.parseModuleExportName() + if (this.eatContextual("as")) this.parseIdent() + if (!this.eat(tokTypes.comma)) { + this.expect(tokTypes.braceR) + break + } + } + } + + // Inline `type Foo` or `type Foo as Bar` (not `type` as a value or `type as x`). + tsIsTypeSpecifier(): boolean { + return ( + this.isContextual("type") && + !this.containsEsc && + this.tsLookAhead(() => { + this.next() + if (this.type === tokTypes.comma || this.type === tokTypes.braceR) return false + if (this.isContextual("as") && !this.containsEsc) { + this.next() + return this.isContextual("as") && !this.containsEsc + } + return true + }) + ) + } + + tsParseNamedImportSpecifiers(out: Array): boolean { + let hadType = false + this.expect(tokTypes.braceL) + let first = true + while (!this.eat(tokTypes.braceR)) { + if (!first) { + this.expect(tokTypes.comma) + if (this.afterTrailingComma(tokTypes.braceR)) break + } else { + first = false + } + if (this.tsIsTypeSpecifier()) { + hadType = true + this.next() // skip `type` + this.parseModuleExportName() + if (this.eatContextual("as")) this.parseIdent() + } else { + out.push(this.parseImportSpecifier()) + } + } + return hadType + } + + override shouldParseExportStatement(): boolean { + return ( + (this.isContextual("abstract") && !this.containsEsc && this.tsIsAbstractClass()) || + super.shouldParseExportStatement() + ) + } + + override parseExport(node: AnyNode, exports?: Record): AnyNode { + const startLoc = this.startLoc + // Peek past `export` for TS-specific forms before deferring to Acorn. + const nextKind = this.tsLookAhead(() => { + this.next() + if (this.type === tokTypes.eq) return "export-eq" + if (this.type === atToken) return "decorator" + if (this.isContextual("enum") && !this.containsEsc) return "enum" + if (this.type === tokTypes._const) { + this.next() + if (!this.tsHasLineBreakBefore() && this.isContextual("enum") && !this.containsEsc) return "const-enum" + return "other" + } + if (this.type === tokTypes._function || this.isAsyncFunction()) return "function" + if (this.type === tokTypes.name && !this.containsEsc) { + if (this.value === "interface" && this.tsIsInterfaceDeclaration()) return "interface" + if (this.value === "type") { + if (this.tsIsTypeAliasDeclaration()) return "type-alias" + this.next() + if (this.type === tokTypes.braceL || this.type === tokTypes.star) return "export-type" + return "other" + } + if (this.value === "declare" && this.tsIsDeclareStatement()) return "declare" + if ((this.value === "namespace" || this.value === "module") && this.tsIsNamespaceDeclaration()) { + return "namespace" + } + if (this.value === "as") { + this.next() + if (this.isContextual("namespace") && !this.containsEsc) return "as-namespace" + } + } + if (this.type === tokTypes.braceL) return "named-braces" + return "other" + }) + + if (nextKind === "export-eq") { + this.tsUnsupported(TS_UNSUPPORTED.exportAssignment, startLoc) + } + if (nextKind === "decorator") { + this.next() + this.tsUnsupported(TS_UNSUPPORTED.decorator) + } + if (nextKind === "enum" || nextKind === "const-enum") { + this.next() + this.tsUnsupported(TS_UNSUPPORTED.enum) + } + if (nextKind === "function") { + // Erase `export [async] function f(...): R;` overloads instead of letting Acorn read `declaration.id`. + const saved = this.tsSaveState() + this.next() + const decl = this.parseStatement(null) + if (decl.type === ERASED_STATEMENT) return decl + this.tsRestoreState(saved) + } + if (nextKind === "interface") { + this.next() + return this.tsSkipInterface() + } + if (nextKind === "type-alias") { + this.next() + return this.tsSkipTypeAlias() + } + if (nextKind === "export-type") { + this.next() + return this.tsSkipExportType() + } + if (nextKind === "declare") { + this.next() + return this.tsSkipDeclare() + } + if (nextKind === "namespace") { + this.next() + return this.tsParseNamespace(this.tsInAmbient) + } + if (nextKind === "as-namespace") { + this.next() // export + this.next() // as + this.next() // namespace + this.parseIdent() + this.semicolon() + return this.tsErased() + } + if (nextKind === "named-braces") { + // Check if `export { type A, type B } [from ...]` has only type specifiers. + const saved = this.tsSaveState() + this.next() // export + const specifiers: Array = [] + let hadType = false + this.expect(tokTypes.braceL) + let first = true + while (!this.eat(tokTypes.braceR)) { + if (!first) { + this.expect(tokTypes.comma) + if (this.afterTrailingComma(tokTypes.braceR)) break + } else { + first = false + } + if (this.tsIsTypeSpecifier()) { + hadType = true + this.next() + this.parseModuleExportName() + if (this.eatContextual("as")) this.parseModuleExportName() + } else { + // Not registered in `exports` yet: without a type specifier this list is parsed again by Acorn below. + specifiers.push(this.parseExportSpecifier()) + } + } + if (hadType && specifiers.length === 0) { + if (this.eatContextual("from")) { + if (this.type !== tokTypes.string) this.unexpected() + this.next() + this.parseWithClause() + } + this.semicolon() + return this.tsErased() + } + if (hadType) { + // Mixed value + type export: return ExportNamedDeclaration with remaining value specifiers. + for (const spec of specifiers) this.checkExport(exports, spec.exported, spec.exported.start) + node.declaration = null + node.specifiers = specifiers + if (this.eatContextual("from")) { + if (this.type !== tokTypes.string) this.unexpected() + node.source = this.parseExprAtom() + node.attributes = this.parseWithClause() + } else { + for (const spec of specifiers) { + this.checkUnreserved(spec.local) + this.checkLocalExport(spec.local) + if (spec.local.type === "Literal") { + this.raise(spec.local.start, "A string literal cannot be used as an exported binding without `from`.") + } + } + node.source = null + node.attributes = [] + } + this.semicolon() + return this.finishNode(node, "ExportNamedDeclaration") + } + this.tsRestoreState(saved) + } + + return super.parseExport(node, exports) + } + + tsSkipExportType(): AnyNode { + this.next() // type + if (this.eat(tokTypes.star)) { + if (this.eatContextual("as")) this.parseModuleExportName() + this.expectContextual("from") + if (this.type !== tokTypes.string) this.unexpected() + this.next() + this.parseWithClause() + this.semicolon() + return this.tsErased() + } + this.expect(tokTypes.braceL) + let first = true + while (!this.eat(tokTypes.braceR)) { + if (!first) { + this.expect(tokTypes.comma) + if (this.afterTrailingComma(tokTypes.braceR)) break + } else { + first = false + } + this.parseModuleExportName() + if (this.eatContextual("as")) this.parseModuleExportName() + } + if (this.eatContextual("from")) { + if (this.type !== tokTypes.string) this.unexpected() + this.next() + this.parseWithClause() + } + this.semicolon() + return this.tsErased() + } + + // --- Variables, Catch, Functions, Methods --- + + override parseVarId(decl: AnyNode, kind: string): void { + super.parseVarId(decl, kind) + // Definite assignment assertion `let x!: number` + if ( + decl.id.type === "Identifier" && + this.type === tokTypes.prefix && + this.value === "!" && + !this.tsHasLineBreakBefore() + ) { + this.next() + } + this.tsSkipTypeAnnotation() + } + + override parseCatchClauseParam(): AnyNode { + const param = this.parseBindingAtom() + this.tsSkipTypeAnnotation() + const simple = param.type === "Identifier" + this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0) + this.checkLValPattern(param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL) + this.expect(tokTypes.parenR) + return param + } + + override parseFunction( + node: AnyNode, + statement: number, + allowExpressionBody?: boolean, + isAsync?: boolean, + forInit?: boolean, + ): AnyNode { + this.initFunction(node) + if (this.type === tokTypes.star && (statement & FUNC_HANGING_STATEMENT)) this.unexpected() + node.generator = this.eat(tokTypes.star) + node.async = !!isAsync + + if (statement & FUNC_STATEMENT) { + node.id = (statement & FUNC_NULLABLE_ID) && this.type !== tokTypes.name ? null : this.parseIdent() + } + + const oldYieldPos = this.yieldPos + const oldAwaitPos = this.awaitPos + const oldAwaitIdentPos = this.awaitIdentPos + this.yieldPos = 0 + this.awaitPos = 0 + this.awaitIdentPos = 0 + this.enterScope(functionFlags(node.async, node.generator)) + + if (!(statement & FUNC_STATEMENT)) { + node.id = this.type === tokTypes.name ? this.parseIdent() : null + } + + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.parseFunctionParams(node) + this.tsSkipReturnType() + + // Function overload signature (no body): `function f(x: number): number;` (not allowed in single-statement bodies). + if ((statement & FUNC_STATEMENT) && !(statement & FUNC_HANGING_STATEMENT) && this.type !== tokTypes.braceL) { + this.semicolon() + this.exitScope() + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + this.awaitIdentPos = oldAwaitIdentPos + return this.tsErased() + } + + // Register the function declaration's name in the enclosing scope only once we know it has a body. + if ((statement & FUNC_STATEMENT) && node.id && !(statement & FUNC_HANGING_STATEMENT)) { + const fnScope = this.scopeStack.pop()! + this.checkLValSimple( + node.id, + this.strict || node.generator || node.async + ? this.treatFunctionsAsVar + ? BIND_VAR + : BIND_LEXICAL + : BIND_FUNCTION, + ) + this.scopeStack.push(fnScope) + } + + this.parseFunctionBody(node, allowExpressionBody, false, forInit) + + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + this.awaitIdentPos = oldAwaitIdentPos + return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression") + } + + override parseFunctionParams(node: AnyNode): void { + this.expect(tokTypes.parenL) + node.params = this.tsParseParamList(this.tsInConstructorParams) + this.checkYieldAwaitInDefaultParams() + } + + tsParseParamList(inConstructor: boolean): Array { + const elts: Array = [] + let first = true + while (!this.eat(tokTypes.parenR)) { + if (first) first = false + else this.expect(tokTypes.comma) + if (this.afterTrailingComma(tokTypes.parenR)) break + // Parameter decorator + if (this.type === atToken) this.tsUnsupported(TS_UNSUPPORTED.decorator) + // Explicit `this` parameter (first parameter only): erased completely. + if (elts.length === 0 && this.type === tokTypes._this) { + this.next() + this.eat(tokTypes.question) + this.tsSkipTypeAnnotation() + continue + } + // Constructor parameter property modifiers (`public`, `private`, `protected`, `readonly`, `override`) + if (inConstructor && this.type === tokTypes.name && !this.containsEsc && PARAM_MODIFIERS.has(String(this.value))) { + const isParamProp = this.tsLookAhead(() => { + this.next() + return ( + this.type !== tokTypes.colon && + this.type !== tokTypes.question && + this.type !== tokTypes.comma && + this.type !== tokTypes.parenR && + this.type !== tokTypes.eq + ) + }) + if (isParamProp) this.tsUnsupported(TS_UNSUPPORTED.parameterProperty) + } + if (this.type === tokTypes.ellipsis) { + const rest = this.parseRestBinding() + this.eat(tokTypes.question) + this.tsSkipTypeAnnotation() + this.parseBindingListItem(rest) + elts.push(rest) + if (this.type === tokTypes.comma) { + this.raiseRecoverable(this.start, "Comma is not permitted after the rest element") + } + this.expect(tokTypes.parenR) + break + } + const startPos = this.start + const startLoc = this.startLoc + const atom = this.parseBindingAtom() + this.eat(tokTypes.question) + this.tsSkipTypeAnnotation() + const elem = this.parseMaybeDefault(startPos, startLoc, atom) + this.parseBindingListItem(elem) + elts.push(elem) + } + return elts + } + + override parseMethod(isGenerator: boolean, isAsync: boolean, allowDirectSuper?: boolean): AnyNode { + const node = this.startNode() + const oldYieldPos = this.yieldPos + const oldAwaitPos = this.awaitPos + const oldAwaitIdentPos = this.awaitIdentPos + + this.initFunction(node) + node.generator = isGenerator + node.async = !!isAsync + + this.yieldPos = 0 + this.awaitPos = 0 + this.awaitIdentPos = 0 + this.enterScope( + functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0), + ) + + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.expect(tokTypes.parenL) + node.params = this.tsParseParamList(this.tsInConstructorParams) + this.checkYieldAwaitInDefaultParams() + this.tsSkipReturnType() + this.parseFunctionBody(node, false, true, false) + + this.yieldPos = oldYieldPos + this.awaitPos = oldAwaitPos + this.awaitIdentPos = oldAwaitIdentPos + return this.finishNode(node, "FunctionExpression") + } + + override parsePropertyValue( + prop: AnyNode, + isPattern: boolean, + isGenerator: boolean, + isAsync: boolean, + startPos: number, + startLoc: Position, + refDestructuringErrors: AnyNode, + containsEsc: boolean, + ): void { + // Generic method in object literal: `{ m(x: T): T { return x } }` + if (!isPattern && this.tsIsLt()) { + prop.method = true + prop.value = this.parseMethod(isGenerator, isAsync) + prop.kind = "init" + return + } + super.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) + } + + // --- Classes --- + + override parseClassId(node: AnyNode, isStatement: boolean | string): void { + super.parseClassId(node, isStatement) + if (this.tsIsLt()) this.tsSkipTypeParameters() + } + + override parseClassSuper(node: AnyNode): void { + if (this.eat(tokTypes._extends)) { + node.superClass = this.parseExprSubscripts(null, false) + if (this.tsIsLt()) this.tsSkipTypeArguments() + } else { + node.superClass = null + } + if (this.eatContextual("implements")) { + do { + this.tsSkipQualifiedName() + if (this.tsIsLt()) this.tsSkipTypeArguments() + } while (this.eat(tokTypes.comma)) + } + } + + override parseClassElement(constructorAllowsSuper: boolean): AnyNode | null { + if (this.eat(tokTypes.semi)) return null + + // Decorator on a class element + if (this.type === atToken) { + this.tsUnsupported(TS_UNSUPPORTED.decorator) + } + + const node = this.startNode() + let keyName = "" + let isGenerator = false + let isAsync = false + let kind = "method" + let isStatic = false + let isAbstract = false + let isDeclare = false + + // Parse leading TS & JS class member modifiers in any valid order + // (public, private, protected, readonly, override, abstract, declare, static). + while (this.type === tokTypes.name && !this.containsEsc) { + const word = String(this.value) + if (word === "static") { + const nextIsBlock = this.tsLookAhead(() => { + this.next() + return this.type === tokTypes.braceL + }) + if (nextIsBlock) { + this.next() // static + this.next() // { + this.parseClassStaticBlock(node) + return node + } + const isMod = this.tsLookAhead(() => { + this.next() + return ( + !isMemberNameFollowNotModifier(this.type, this.value) && + (this.isClassElementNameStart() || this.type === tokTypes.star) + ) + }) + if (!isMod) break + isStatic = true + this.next() + continue + } + if (CLASS_MODIFIERS.has(word)) { + const disallowNewline = word === "abstract" || word === "declare" || word === "override" + const isMod = this.tsLookAhead(() => { + this.next() + if (disallowNewline && this.tsHasLineBreakBefore()) return false + return ( + !isMemberNameFollowNotModifier(this.type, this.value) && + (this.isClassElementNameStart() || this.type === tokTypes.star) + ) + }) + if (!isMod) break + if (word === "abstract") isAbstract = true + if (word === "declare") isDeclare = true + this.next() + continue + } + break + } + + // Index signature: `[key: string]: unknown;` + if (this.type === tokTypes.bracketL) { + const isIndexSig = this.tsLookAhead(() => { + this.next() + if (!this.tsIsIdentOrKeyword()) return false + this.next() + return this.type === tokTypes.colon + }) + if (isIndexSig) { + this.next() // [ + this.next() // key + this.expect(tokTypes.colon) + this.tsSkipType() + this.expect(tokTypes.bracketR) + this.tsSkipTypeAnnotation() + this.semicolon() + return null + } + } + + node.static = isStatic + + if (this.eatContextual("async")) { + if ((this.isClassElementNameStart() || this.type === tokTypes.star) && !this.canInsertSemicolon()) { + isAsync = true + } else { + keyName = "async" + } + } + if (!keyName && this.eat(tokTypes.star)) { + isGenerator = true + } + if (!keyName && !isAsync && !isGenerator) { + const lastValue = String(this.value) + if (this.eatContextual("get") || this.eatContextual("set")) { + if ( + !isMemberNameFollowNotModifier(this.type, this.value) && + this.isClassElementNameStart() + ) { + kind = lastValue + } else { + keyName = lastValue + } + } + } + + if (keyName) { + node.computed = false + node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc) + node.key.name = keyName + this.finishNode(node.key, "Identifier") + } else { + this.parseClassElementName(node) + } + + // Optional `?` or definite assignment `!` on a member + const hasOptional = this.eat(tokTypes.question) + const hasDefinite = + !hasOptional && + this.type === tokTypes.prefix && + this.value === "!" && + !this.tsHasLineBreakBefore() && + (this.next(), true) + + const isMethodStart = + !hasDefinite && + (this.type === tokTypes.parenL || this.tsIsLt() || kind !== "method" || isGenerator || isAsync) + + if (isMethodStart) { + const isConstructor = !node.static && this.tsCheckKeyName(node, "constructor") + const allowsDirectSuper = isConstructor && constructorAllowsSuper + if (isConstructor && kind !== "method") this.raise(node.key.start, "Constructor can't have get/set modifier") + node.kind = isConstructor ? "constructor" : kind + + // Abstract method or overload signature (no body `{`): parse signature and erase. + const isSignature = isAbstract || isDeclare || this.tsLookAhead(() => { + const check = this.tsTryParse(() => { + if (this.tsIsLt()) this.tsSkipTypeParameters() + this.tsSkipAmbientParams() + this.tsSkipReturnType() + return this.type !== tokTypes.braceL + }) + return check.ok && check.value + }) + if (isSignature) { + if (this.tsIsLt()) this.tsSkipTypeParameters() + const prevCtor = this.tsInConstructorParams + this.tsInConstructorParams = isConstructor + try { + this.expect(tokTypes.parenL) + this.tsParseParamList(isConstructor) + } finally { + this.tsInConstructorParams = prevCtor + } + this.tsSkipReturnType() + this.semicolon() + return null + } + + const prevCtor = this.tsInConstructorParams + this.tsInConstructorParams = isConstructor + try { + this.parseClassMethod(node, isGenerator, isAsync, allowsDirectSuper) + } finally { + this.tsInConstructorParams = prevCtor + } + return node + } + + // Class field + this.tsSkipTypeAnnotation() + if (isAbstract || isDeclare) { + if (this.eat(tokTypes.eq)) this.parseMaybeAssign() + this.semicolon() + return null + } + this.parseClassField(node) + return node + } + + tsCheckKeyName(node: AnyNode, name: string): boolean { + const key = node.key + return !node.computed && ((key.type === "Identifier" && key.name === name) || (key.type === "Literal" && key.value === name)) + } + + // --- Expressions --- + + override parseExprOp( + left: AnyNode, + leftStartPos: number, + leftStartLoc: Position, + minPrec: number, + forInit?: boolean, + ): AnyNode { + // `expr as Type` and `expr satisfies Type` at relational precedence (7), no line terminator before keyword. + const AS_PREC = 7 + if ( + AS_PREC > minPrec && + !this.tsHasLineBreakBefore() && + this.type === tokTypes.name && + !this.containsEsc && + (this.value === "as" || this.value === "satisfies") + ) { + const isAs = this.value === "as" + this.next() + if (isAs && this.type === tokTypes._const) { + this.next() + } else { + this.tsSkipType() + } + return this.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, forInit) + } + return super.parseExprOp(left, leftStartPos, leftStartLoc, minPrec, forInit) + } + + override parseExprAtom(refDestructuringErrors?: AnyNode | null, forInit?: boolean, forNew?: boolean): AnyNode { + // `abstract class { ... }` expression + if (this.type === tokTypes.name && !this.containsEsc && this.value === "abstract" && this.tsIsAbstractClass()) { + const node = this.startNode() + this.next() + return this.parseClass(node, false) + } + + // Decorated class expression: `(@dec class {})` + if (this.type === atToken) { + this.tsUnsupported(TS_UNSUPPORTED.decorator) + } + + // Generic arrow `(x: T): T => ...` or angle-bracket assertion `expr` + if (this.tsIsLt()) { + const startPos = this.start + const startLoc = this.startLoc + const genericArrow = this.tsTryParse(() => { + this.tsSkipTypeParameters() + if (this.type !== tokTypes.parenL) this.unexpected() + const arrow = this.tsParseArrowAfterTypeParams(startPos, startLoc, false, forInit) + return arrow + }) + if (genericArrow.ok) return genericArrow.value + + const angleAssertion = this.tsTryParse(() => { + this.next() // < + this.tsSkipType() + this.tsExpectGt() + return true + }) + if (angleAssertion.ok) { + this.tsUnsupported(TS_UNSUPPORTED.angleBracketAssertion, startLoc) + } + } + + // `async (x: T): Promise => ...` + if (this.type === tokTypes.name && !this.containsEsc && this.value === "async") { + const isAsyncGenericArrow = this.tsLookAhead(() => { + this.next() + return !this.canInsertSemicolon() && this.tsIsLt() + }) + if (isAsyncGenericArrow) { + const startPos = this.start + const startLoc = this.startLoc + const genericAsyncArrow = this.tsTryParse(() => { + this.next() // async + this.tsSkipTypeParameters() + if (this.type !== tokTypes.parenL) this.unexpected() + return this.tsParseArrowAfterTypeParams(startPos, startLoc, true, forInit) + }) + if (genericAsyncArrow.ok) return genericAsyncArrow.value + } + } + + return super.parseExprAtom(refDestructuringErrors, forInit, forNew) + } + + // As tsc does, `c ? (a) : b => d` is `(a)` and then the alternate: where a conditional's consequent starts, an arrow + // function with a return type must leave a `:` behind it. + override parseMaybeConditional(forInit?: boolean, refDestructuringErrors?: AnyNode | null): AnyNode { + const startPos = this.start + const startLoc = this.startLoc + const expr = this.parseExprOps(forInit, refDestructuringErrors) + if (this.checkExpressionErrors(refDestructuringErrors) || !this.eat(tokTypes.question)) return expr + const node = this.startNodeAt(startPos, startLoc) + node.test = expr + const outer = this.tsConsequentStart + this.tsConsequentStart = this.start + try { + node.consequent = this.parseMaybeAssign() + } finally { + this.tsConsequentStart = outer + } + this.expect(tokTypes.colon) + node.alternate = this.parseMaybeAssign(forInit) + return this.finishNode(node, "ConditionalExpression") + } + + override parseArrowExpression(node: AnyNode, params: Array, isAsync: boolean, forInit?: boolean): AnyNode { + const outer = this.tsConsequentStart + if (node.start === outer) this.tsConsequentStart = this.start + try { + return super.parseArrowExpression(node, params, isAsync, forInit) + } finally { + this.tsConsequentStart = outer + } + } + + tsParseArrowAfterTypeParams(startPos: number, startLoc: Position, isAsync: boolean, forInit?: boolean): AnyNode { + const startsConsequent = startPos === this.tsConsequentStart + const oldYield = this.yieldPos + const oldAwait = this.awaitPos + const oldAwaitIdent = this.awaitIdentPos + this.yieldPos = 0 + this.awaitPos = 0 + this.awaitIdentPos = 0 + this.expect(tokTypes.parenL) + const params = this.tsParseParamList(false) + const returnTyped = this.type === tokTypes.colon + this.tsSkipReturnType() + if (this.canInsertSemicolon() || !this.eat(tokTypes.arrow)) this.unexpected() + this.checkYieldAwaitInDefaultParams() + if (isAsync && this.awaitIdentPos > 0) { + this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function") + } + this.yieldPos = oldYield + this.awaitPos = oldAwait + this.awaitIdentPos = oldAwaitIdent + const arrow = this.parseArrowExpression(this.startNodeAt(startPos, startLoc), params, isAsync, forInit) + if (returnTyped && startsConsequent && this.type !== tokTypes.colon) this.unexpected() + return arrow + } + + override parseSubscripts( + base: AnyNode, + startPos: number, + startLoc: Position, + noCalls?: boolean, + forInit?: boolean, + ): AnyNode { + const maybeAsyncArrow = + base.type === "Identifier" && + base.name === "async" && + this.lastTokEnd === base.end && + !this.canInsertSemicolon() && + base.end - base.start === 5 && + this.potentialArrowAt === base.start + let optionalChained = false + + while (true) { + // Postfix non-null assertion `expr!` (no line terminator before `!`) + if (this.type === tokTypes.prefix && this.value === "!" && !this.canInsertSemicolon()) { + this.next() + continue + } + + // Generic call / tagged template / instantiation expression: `fn(x)`, `new C(x)`, `tag`...``, `const g = fn` + if (this.tsIsLt()) { + const typeArgs = this.tsTryParse(() => { + this.tsSkipTypeArguments() + if (this.type === tokTypes.parenL || this.type === tokTypes.backQuote) return "call" as const + if (isInstantiationFollower(this.type, this.value, this.canInsertSemicolon())) { + return "instantiation" as const + } + this.unexpected() + }) + if (typeArgs.ok) continue + } + + // Optional generic call / instantiation: `fn?.(x)` + if (this.type === tokTypes.questionDot) { + const isOptTypeArgs = this.tsLookAhead(() => { + this.next() + return this.tsIsLt() + }) + if (isOptTypeArgs) { + this.next() // ?. + this.tsSkipTypeArguments() + if (!noCalls && this.eat(tokTypes.parenL)) { + const args = this.parseExprList(tokTypes.parenR, true, false) + const callNode = this.startNodeAt(startPos, startLoc) + callNode.callee = base + callNode.arguments = args + callNode.optional = true + base = this.finishNode(callNode, "CallExpression") + optionalChained = true + continue + } + optionalChained = true + continue + } + } + + // `async (x: number): Promise => ...` + if (maybeAsyncArrow && this.type === tokTypes.parenL) { + const asyncArrow = this.tsTryParse(() => this.tsParseArrowAfterTypeParams(startPos, startLoc, true, forInit)) + if (asyncArrow.ok) return asyncArrow.value + } + + const element = this.parseSubscript( + base, + startPos, + startLoc, + !!noCalls, + maybeAsyncArrow, + optionalChained, + !!forInit, + ) + + if (element.optional) optionalChained = true + if (element === base || element.type === "ArrowFunctionExpression") { + if (optionalChained) { + const chainNode = this.startNodeAt(startPos, startLoc) + chainNode.expression = element + return this.finishNode(chainNode, "ChainExpression") + } + return element + } + + base = element + } + } + + override parseParenAndDistinguishExpression(canBeArrow: boolean, forInit?: boolean): AnyNode { + if (!canBeArrow) return super.parseParenAndDistinguishExpression(false, forInit) + + const startPos = this.start + const startLoc = this.startLoc + // Fast check: only try TS-typed arrow params when the parenthesized list actually contains TS parameter + // syntax or is followed by `: ReturnType =>`. Plain JS expressions like `((((1))))` skip this in O(1). + if (this.tsPeekParenHasTsArrow()) { + const tsArrow = this.tsTryParse(() => this.tsParseArrowAfterTypeParams(startPos, startLoc, false, forInit)) + if (tsArrow.ok) return tsArrow.value + } + + return super.parseParenAndDistinguishExpression(true, forInit) + } + + tsPeekParenHasTsArrow(): boolean { + // Quick scan inside `(...)` at depth 1 for top-level `:` (type annotation) or `?` before `,`/`)`/`=`/`:`, + // or `: ... =>` right after the matching `)`. + return this.tsLookAhead(() => { + this.expect(tokTypes.parenL) + let depth = 1 + while (depth > 0 && this.type !== tokTypes.eof) { + if (depth === 1) { + if (this.type === tokTypes.colon) return true + if (this.type === tokTypes.question) { + this.next() + if ( + this.type === tokTypes.colon || + this.type === tokTypes.comma || + this.type === tokTypes.parenR || + this.type === tokTypes.eq + ) { + return true + } + continue + } + } + if (this.type === tokTypes.parenL || this.type === tokTypes.braceL || this.type === tokTypes.bracketL) { + depth++ + } else if ( + this.type === tokTypes.parenR || + this.type === tokTypes.braceR || + this.type === tokTypes.bracketR + ) { + depth-- + if (depth === 0) { + this.next() + return this.type === tokTypes.colon + } + } + this.next() + } + return false + }) + } + } + + return TsParser as unknown as typeof Parser +} + +export { tsPlugin } + +const TsAcornParser = Parser.extend(tsPlugin) + +/** Parses a TypeScript source into a clean ESTree Program with type-only syntax erased. */ +export const parseTypeScriptProgram = ( + code: string, + options: Options, + parser: typeof Parser = TsAcornParser, +): { ok: true; program: Program } | { ok: false; error: Diagnostic } => { + try { + return { ok: true, program: parser.parse(code, options) } + } catch (error) { + if (error instanceof UnsupportedTsError) { + return { ok: false, error: unsupportedTsDiagnostic(error.message, error.loc) } + } + throw error + } +} diff --git a/src/effect/runtime.ts b/src/effect/runtime.ts index 5190b6ac..6e4af651 100644 --- a/src/effect/runtime.ts +++ b/src/effect/runtime.ts @@ -18,12 +18,12 @@ import { SuspendError, type Suspended, } from "../runtime/execute.js" -import { type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "../runtime/options.js" +import { type CompileOptions, type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "../runtime/options.js" import { SnapshotError } from "../snapshot/snapshot.js" export { Script, SuspendError } export type { Outcome, Result, Run, Suspended } -export type { Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "../runtime/options.js" +export type { CompileOptions, Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "../runtime/options.js" /** A reusable confined runtime over host globals. */ export type Runtime = { @@ -37,6 +37,7 @@ export type Runtime = { */ readonly compile: ( code: string, + options?: CompileOptions, ) => { readonly ok: true; readonly value: Script } | { readonly ok: false; readonly error: Diagnostic } /** * A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the @@ -85,13 +86,13 @@ export const make = (options: Options = {}): Ru type R = Services const setup = { ...makeSetup(options), adapt } const program = (code: string | Script, programOptions?: ProgramOptions): Program => - wrap(makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId))) + wrap(makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId, programOptions?.typescript))) return { execute: (code, programOptions) => Effect.flatMap(Effect.context(), (services) => fromPromise((signal) => finishExecution( - makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId)).run({ + makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId, programOptions?.typescript)).run({ signal, context: services, }), diff --git a/src/runtime.ts b/src/runtime.ts index 760147a4..a464059b 100644 --- a/src/runtime.ts +++ b/src/runtime.ts @@ -16,11 +16,11 @@ import { SuspendError, type Suspended, } from "./runtime/execute.js" -import { type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "./runtime/options.js" +import { type CompileOptions, type Globals, makeSetup, type Options, type ProgramOptions, type SuspendOptions } from "./runtime/options.js" export { Script, SuspendError } export type { Outcome, Result, Run, Suspended } -export type { Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "./runtime/options.js" +export type { CompileOptions, Globals, Limits, Options, ProgramOptions, SuspendOptions, Translate } from "./runtime/options.js" /** How one run is stopped: aborting `signal` makes it reject with an `AbortError`. */ export type RunOptions = { @@ -45,6 +45,7 @@ export type Runtime = { */ readonly compile: ( code: string, + options?: CompileOptions, ) => { readonly ok: true; readonly value: Script } | { readonly ok: false; readonly error: Diagnostic } /** * A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the @@ -77,7 +78,7 @@ export type Program = { export const make = (options: Options = {}): Runtime => { const setup = makeSetup(options) const start = (code: string | Script, programOptions?: ProgramOptions) => - makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId)) + makeProgram(() => startProgram(setup, code, programOptions?.bindings, programOptions?.runId, programOptions?.typescript)) return { execute: (code, executeOptions) => aborting(finishExecution(start(code, executeOptions).run({ signal: executeOptions?.signal })), executeOptions?.signal), diff --git a/src/runtime/execute.ts b/src/runtime/execute.ts index a2e43a65..21fa5865 100644 --- a/src/runtime/execute.ts +++ b/src/runtime/execute.ts @@ -14,7 +14,8 @@ import { Interruption } from "./signals.js" import { Source } from "./source.js" import { compileCodes, type Vm } from "../vm.js" import type { Code } from "../code.js" -import type { Translate } from "../runtime.js" +import type { CompileOptions, Translate } from "../runtime.js" +import { parseTypeScriptProgram, tsPlugin } from "../compiler/typescript.js" /** * A suspend that failed, leaving the run running: `running` names each host call that blocked it by its key and its @@ -184,21 +185,23 @@ export class Script { */ export const compileProgram = ( code: string, + options?: CompileOptions, ): { readonly ok: true; readonly value: Script } | { readonly ok: false; readonly error: Diagnostic } => { if (code.trim().length === 0) return { ok: false, error: { kind: "ParseError", message: "Code cannot be empty." } } - const known = compiledTexts.get(code) + const key = (options?.typescript ? "ts:" : "js:") + code + const known = compiledTexts.get(key) if (known !== undefined) { - compiledTexts.delete(code) - compiledTexts.set(code, known) + compiledTexts.delete(key) + compiledTexts.set(key, known) return { ok: true, value: known } } - const parsed = parseProgram(code) + const parsed = parseProgram(code, options) if (!parsed.ok) return parsed const script = new Script(code, parsed.source, compileCodes(parsed.source)) // A RangeError (a program nested deeper than the host stack allowed this time) is never kept: another try may compile. if (code.length <= MAX_COMPILED_TEXT && !(script.codes instanceof RangeError)) { if (compiledTexts.size >= MAX_COMPILED_TEXTS) compiledTexts.delete(compiledTexts.keys().next().value!) - compiledTexts.set(code, script) + compiledTexts.set(key, script) } return { ok: true, value: script } } @@ -216,9 +219,11 @@ export const startProgram = ( code: string | Script, bindings?: Readonly>, runId: string = crypto.randomUUID(), + typescript?: boolean, ): Running => new Running(setup, 0, () => { - const compiled = typeof code === "string" ? compileProgram(code) : { ok: true as const, value: code } + const compiled = + typeof code === "string" ? compileProgram(code, typescript ? { typescript: true } : undefined) : { ok: true as const, value: code } if (!compiled.ok) return { ok: false, error: compiled.error, metadata: null } const run: Run = { id: runId, metadata: null } const runtime = acquire(setup, run, bindings) @@ -266,8 +271,8 @@ export const resumeProgram = ( // A saved source comes from the same cache as a program's, so runs restored from the same program share its parse. const restoreInto = (saved: unknown, vm: Vm): Snapshot => vm.restore(saved, { - parse: (code) => { - const compiled = compileProgram(code) + parse: (code, typescript) => { + const compiled = compileProgram(code, typescript ? { typescript: true } : undefined) if (!compiled.ok) throw new SnapshotError(`A saved source no longer parses: ${compiled.error.message}`) return compiled.value.source }, @@ -619,17 +624,27 @@ const attempt = (run: () => A): { ok: true; value: A } | { ok: false; error: export const parseProgram = ( code: string, + options?: CompileOptions, ): { ok: true; program: Program; source: Source } | { ok: false; error: Diagnostic } => { + const typescript = options?.typescript === true + const parseOptions = { + ecmaVersion: "latest" as const, + sourceType: "script" as const, + allowReturnOutsideFunction: true, + allowAwaitOutsideFunction: true, + // Imports bind globals by module name; scripts keep sloppy-mode semantics, which module source would make strict. + allowImportExportEverywhere: true, + locations: true, + } try { - const program = BigIntLimitParser.parse(code, { - ecmaVersion: "latest", - sourceType: "script", - allowReturnOutsideFunction: true, - allowAwaitOutsideFunction: true, - // Imports bind globals by module name; scripts keep sloppy-mode semantics, which module source would make strict. - allowImportExportEverywhere: true, - locations: true, - }) + let program: Program + if (typescript) { + const parsed = parseTypeScriptProgram(code, parseOptions, TsBigIntLimitParser) + if (!parsed.ok) return parsed + program = parsed.program + } else { + program = BigIntLimitParser.parse(code, parseOptions) + } const exported = program.body.find((statement) => statement.type.startsWith("Export")) if (exported) { const location = sourceLocation(exported) @@ -642,7 +657,7 @@ export const parseProgram = ( }, } } - return { ok: true, program, source: new Source("main", code, program) } + return { ok: true, program, source: new Source("main", code, program, typescript) } } catch (error) { // Only acorn's own syntax errors become a located ParseError; anything else keeps the generic failure path. if (!(error instanceof SyntaxError) || !isAcornError(error)) throw error @@ -675,6 +690,8 @@ const BigIntLimitParser = Parser.extend((Base) => { return Limited }) +const TsBigIntLimitParser = BigIntLimitParser.extend(tsPlugin) + // Acorn appends ` (line:column)` to its messages; its lines are 1-based and its columns 0-based. type AcornError = { readonly message: string; readonly loc: { readonly line: number; readonly column: number } } diff --git a/src/runtime/options.ts b/src/runtime/options.ts index a74cbc58..43583808 100644 --- a/src/runtime/options.ts +++ b/src/runtime/options.ts @@ -62,8 +62,19 @@ export type Options = { readonly reuse?: boolean | undefined } +/** Options for compiling or parsing a source. */ +export type CompileOptions = { + /** + * Parse the source as TypeScript and erase type-only syntax (annotations, `interface`, `type`, `as`, `satisfies`, + * `!`, generics, `import type`/`export type`, `declare`, and class member modifiers). Non-erasable syntax + * (`enum`, `namespace` with values, parameter properties, decorators, `import x = require`) fails with + * `UnsupportedSyntax`. Defaults to `false` (plain JavaScript). + */ + readonly typescript?: boolean | undefined +} + /** Options for `Runtime.program`. */ -export type ProgramOptions = { +export type ProgramOptions = CompileOptions & { /** Read-only JSON values bound in the program's outer scope (shadowable by top-level declarations). */ readonly bindings?: Readonly> | undefined /** Names this run's host calls (`:`); a random UUID by default. */ diff --git a/src/runtime/source.ts b/src/runtime/source.ts index 7a36155c..3072369f 100644 --- a/src/runtime/source.ts +++ b/src/runtime/source.ts @@ -16,6 +16,7 @@ export class Source { readonly id: string, readonly code: string, program: Program | (() => Program), + readonly typescript = false, ) { this.tree = program if (typeof program !== "function") this.numbered = numberNodes(program, this) diff --git a/src/snapshot.ts b/src/snapshot.ts index b39d0841..26392f51 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -37,7 +37,7 @@ export type CaptureOptions = { export type RestoreOptions = { /** Parses a saved program source (cached by text). */ - readonly parse: (code: string) => Source + readonly parse: (code: string, typescript?: boolean) => Source readonly interruption: () => Interruption } @@ -196,6 +196,7 @@ export const captureVm = ( code: source.code, hash: hash(source.code), bytecode: vm.sourceCodes.get(source.id)![0]!.source.hash, + ...(source.typescript ? { typescript: true } : {}), })), limits: options.limits ?? { timeoutMs: null, maxOutputBytes: null }, budget: { activeMs: options.activeMs ?? 0 }, @@ -226,7 +227,7 @@ export const restoreVm = (vm: Vm, saved: unknown, options: RestoreOptions): Snap } for (const source of header.sources) { if (hash(source.code) !== source.hash) throw new SnapshotError(`Source ${source.id} does not match its hash.`) - const parsed = options.parse(source.code) + const parsed = options.parse(source.code, source.typescript) if (parsed.id !== source.id || vm.sourceCodes.has(source.id)) { throw new SnapshotError(`Source ${source.id} is not a program source.`) } diff --git a/src/snapshot/snapshot.ts b/src/snapshot/snapshot.ts index 3a4f0740..1f33a35e 100644 --- a/src/snapshot/snapshot.ts +++ b/src/snapshot/snapshot.ts @@ -45,6 +45,7 @@ export type Header = { readonly code: string readonly hash: string readonly bytecode: string + readonly typescript?: boolean }> readonly limits: { readonly timeoutMs: number | null @@ -78,6 +79,9 @@ const array = (value: unknown, what: string): ReadonlyArray => const string = (value: unknown, what: string): string => typeof value === "string" ? value : fail(`${what} is not text.`) +const boolean = (value: unknown, what: string): boolean => + typeof value === "boolean" ? value : fail(`${what} is not a boolean.`) + const number = (value: unknown, what: string): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fail(`${what} is not a number.`) @@ -109,6 +113,7 @@ export const validate = (saved: unknown): Snapshot => { code: string(source.code, "a source"), hash: string(source.hash, "a source hash"), bytecode: string(source.bytecode, "a bytecode hash"), + ...(source.typescript === undefined ? {} : { typescript: boolean(source.typescript, "a source typescript flag") }), } }), limits: { diff --git a/test/typescript.test.ts b/test/typescript.test.ts new file mode 100644 index 00000000..88fae0fd --- /dev/null +++ b/test/typescript.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { Effect } from "effect" +import { type Diagnostic, Host, parseProgram, Runtime, toBytes } from "../src/index.js" +import { Host as EffectHost, Runtime as EffectRuntime } from "../src/effect/index.js" + +// What `rust/conformance/typescript.ts` records from this implementation, and Rust is held to. +const recording = JSON.parse(readFileSync(join(import.meta.dir, "../rust/conformance/typescript.json"), "utf8")) as { + readonly cases: ReadonlyArray<{ + readonly name: string + readonly code: string + readonly typescript: boolean + readonly compile: unknown + readonly execute: unknown + }> +} + +const recorded = (error: Diagnostic) => ({ + kind: error.kind, + message: error.message, + ...(error.location ? { location: [error.location.line, error.location.column] } : {}), +}) + +describe("erasable TypeScript", () => { + const makeRuntime = () => + Runtime.make({ + globals: () => ({ + double: Host.fn(([n]) => Number(n) * 2), + mod: { a: 10, b: 20 }, + }), + }) + + test("matches the parity recording Rust replays: erasure, refusals with their locations, and JavaScript mode", async () => { + expect(recording.cases.length).toBeGreaterThan(30) + for (const entry of recording.cases) { + const rt = makeRuntime() + const options = { typescript: entry.typescript } + const compiled = rt.compile(entry.code, options) + expect(compiled.ok ? { ok: true } : { ok: false, error: recorded(compiled.error) }, entry.name).toEqual( + entry.compile, + ) + const executed = await rt.execute(entry.code, options) + expect( + executed.ok + ? { ok: true, value: executed.value, logs: executed.logs ?? [] } + : { ok: false, error: recorded(executed.error), logs: executed.logs ?? [] }, + entry.name, + ).toEqual(entry.execute) + } + }) + + test("erases type-only syntax in execute, program, compile, and parseProgram", async () => { + const rt = makeRuntime() + const code = ` + import type { Unused } from "nonexistent" + import { type T, a } from "mod" + export type { Unused, T } + export interface Shape { value: number } + declare const double: (n: number) => number + type Pair = readonly [A, B] + namespace TypesOnly { export type Tag = "ok" } + function add(x: number, y: number): number + function add(x: number, y: number): number { return x + y } + abstract class Base { + declare ghost: string + public readonly tag: TypesOnly.Tag = "ok"; + [k: string]: unknown + public abstract get(): V + } + class Box extends Base { + private v: V + constructor(v: V) { super(); this.v = v } + public override get(): V { return this.v } + } + const id = (x: X): X => x + const pair = [double(a), add(1, 2)] as const satisfies Pair + const b = new Box(pair[0]! + pair[1]!) + return [b.tag, id(b.get()), "ghost" in b] + ` + + const parsed = parseProgram(code, { typescript: true }) + expect(parsed.ok).toBe(true) + + const compiled = rt.compile(code, { typescript: true }) + expect(compiled.ok).toBe(true) + if (!compiled.ok) return + + const fromSource = await rt.execute(code, { typescript: true }) + expect(fromSource).toEqual({ ok: true, value: ["ok", 23, false], metadata: null }) + + if (parsed.ok) expect(compiled.value.ast).toEqual(parsed.program) + const fromCompiled = await rt.execute(compiled.value) + expect(fromCompiled).toEqual(fromSource) + + const viaProgram = await rt.program(code, { typescript: true }).run() + expect(viaProgram).toEqual(fromSource) + }) + + test("Effect API supports typescript: true on compile, program, and execute", async () => { + const rt = EffectRuntime.make({ + globals: () => ({ + double: EffectHost.fn(([n]) => Effect.succeed(Number(n) * 2)), + }), + }) + const code = "declare const double: (n: number) => number; const x: number = 21; return double(x)" + const compiled = rt.compile(code, { typescript: true }) + expect(compiled.ok).toBe(true) + const r = await Effect.runPromise(rt.execute(code, { typescript: true })) + expect(r).toEqual({ ok: true, value: 42, metadata: null }) + }) + + test("suspends and resumes a TypeScript program through bytes", async () => { + const code = ` + declare const fetchNum: (n: number) => Promise + interface Acc { total: number } + const acc: Acc = { total: 0 } + for (const n of [1, 2, 3] as readonly number[]) { + acc.total += await fetchNum(n) + } + return acc.total + ` + const reached = Promise.withResolvers() + const waiting = Runtime.make({ + globals: () => ({ + fetchNum: Host.fn( + ([n]) => { + if (n === 2) { + reached.resolve() + return new Promise(() => {}) + } + return Number(n) * 10 + }, + { type: "async", idempotent: true }, + ), + }), + }) + const program = waiting.program(code, { typescript: true }) + const running = program.run() + await reached.promise + const suspended = await program.suspend() + await running + expect(suspended.ok).toBe("suspended") + if (suspended.ok !== "suspended") return + + const bytes = toBytes(suspended.state) + const resuming = Runtime.make({ + globals: () => ({ + fetchNum: Host.fn(([n]) => Number(n) * 10, { type: "async", idempotent: true }), + }), + }) + const finished = await resuming.resume(bytes).run() + expect(finished).toEqual({ ok: true, value: 60, metadata: null }) + }) +})