Repository navigation
V3 - #244
Merged
Merged
V3#244
Conversation
…205) * perf(lexer): skip identifier and number runs (#227) * perf(lexer): skip identifier and number runs On the 3,057 KiB sample corpus, Wasm drops from 15,356.31 to 13,010.46 us per sweep on Node 18.20.8 (-15.28%) and from 11,724.34 to 9,856.69 us on Node 24.18.0 (-15.93%). The asm.js build drops from 15,934.34 to 12,945.57 us on Node 24.18.0 (-18.76%). The fast path adds 379 raw / 105 gzip bytes to the full Wasm binary. Measurements used 1,500 warmup sweeps followed by 9 interleaved trials of 50 sweeps, dropping the best and worst trials. * chore: remove the unmaintained pure-JS lexer port lexer.js reimplemented the WebAssembly lexer in hand-written JS, kept in sync by hand, but was unreachable through the package `exports` (only `.` and `./js` are exposed - the wasm and asm.js builds) and `chomp test` never ran it, so it could drift silently. The asm.js build already covers the no-WebAssembly case, and the removed `if (!js)` test guards now run unconditionally, matching their existing behavior under the wasm and asm suites. * feat: report glob n for interpolated template dynamic imports A dynamic import whose entire argument is a template literal with substitutions returned n: undefined, so a consumer resolving the specifier (a bundler or glob importer) had nothing to work with. It now reports the static skeleton as a glob with each ${...} collapsed to a single "*": import(`./locales/${x}.js`) yields "./locales/*.js". Only a lone template literal qualifies. A template concatenated with anything else (import(`a` + b)) has no static skeleton and still returns undefined. Fixes: #137 * fix: drop interpolated template glob to undefined on ambiguous slash The glob walker that builds a dynamic-import template skeleton skips over strings, nested templates, and comments inside each ${...} substitution, but it cannot tell a regex literal from division without the main parser's token context. A regex carrying a "}" closed the substitution early and emitted a wrong specifier instead of bailing: import(`a${ /x}y/g }b`) reported "a*y/g }b" rather than undefined. skipInterpolation now flags a bare "/" (one that does not open a // or /* comment) and the three decoders drop n to undefined rather than guess. This over-bails the rare division case (import(`a${ b/c }d`)), which is acceptable: a missing glob is recoverable, a wrong one is not. Fixes: #137 * refactor: disambiguate template glob substitutions in the parser The interpolated-template glob walked each ${...} substitution with a hand-rolled scanner in all three decoders. None of them could tell a regex literal from division without token context, so a regex carrying a "}" closed the substitution early: import(`a${ /x}y/g }b`) reported "a*y/g }b". The prior fix bailed to undefined on any bare "/", which also dropped legitimate division (import(`a${ b/c }d`)). The parser already resolves regex vs division for the whole source and descends into ${ ... } for nested-import detection, so it now records each top-level substitution's end on the dynamic import (struct TemplateSpan). The decoders splice a "*" per span and jump the body, dropping their skipInterpolation / skipQuoted / skipComment scanners and the interpolationError bail. Both ambiguous cases now resolve correctly: "a*b" and "a*d". Fixes: #137 * fix: gate template glob to the full build and fix its cross-build defects ## Summary Interpolated template glob tracking leaked into minimal builds and diverged between decoders. Missing parser spans could evaluate a substitution, reload an exhausted span list into a loop, or lose the outer glob around a nested import. ## Why Keep span tracking behind LEXER_MIN, use parser-recorded spans as the substitution boundary, and copy static source without eval. The full Wasm and asm.js builds now agree while minimal output stays unchanged. Static parts remain raw source, so escapes are not cooked and a literal * stays literal. ## Test plan - chomp test Fixes: #137 * fix: escape literal stars in template glob output --------- Co-authored-by: Guy Bedford <guybedford@gmail.com>
Replace the terse v2 field names and numeric type tags in the full build with string-discriminated unions: Import = StaticImport | DynamicImport | ImportMetaRef with a 'source' | 'defer' | null phase, and Export = DirectExport | Reexport | ReexportAll, using descriptive field names (specifier, importStart, attributes, from, importIndex, exportStart, ...). The minimal build keeps the v2 terse shapes; its generated types are now self-contained rather than re-using the full build declarations. The shared test suites map full-build records back to the terse shape, with the new test/full-api.cjs asserting the full API record shapes directly.
SIMD setup dominates short scans, and whole-module `-msimd128` also changes scalar hot paths. This keeps short and unrelated scans scalar, then uses SIMD for long line comments and templates. Non-SIMD builds remain byte-identical to v3. Long line-comment scans improve 9-65%, and long templates improve 66.8% against the SHA-identical scalar control on Node 18 arm64. The complete 3.06 MB sample corpus shows no aggregate regression across Node 18-26. Two isolated-process runs each produced a 0.94% equal-version geomean improvement. The SIMD build is 563 bytes smaller than #231.
* feat: lex type-only TypeScript imports and exports Teach the full Wasm and asm.js builds to lex type-only imports, exports, type aliases, and interfaces accepted by Node.js type stripping. Type-only module edges carry `tp: true`, and erased declaration bodies do not leak nested `import()` types into the runtime graph. Plain JavaScript keeps the same graph, and minimal builds compile the TypeScript paths out. Import metadata uses bit 16 above the public import-type range. Export metadata uses the spare bit above import-name types because fastcomp clears a neighboring `_Bool` while linking pending exports. - chomp test - TypeScript differential fuzzer against `stripTypeScriptTypes` Fixes: #72 * feat: best-effort type-position classification for dynamic imports An import() type outside the skipped type declaration constructs (annotations, generic arguments, as / satisfies) previously leaked a phantom runtime edge. As a lexer without a full parser these positions cannot be comprehensively classified, so dynamic imports now carry a best-effort probablyTypeOnly flag classified by use: typeof import('m') and member or indexed access on the result other than the promise members then / catch / finally mark the type position, with await always vetoing as value-certain. Bare unqualified annotation types remain over-reported as runtime edges. * fix: TS lexing review fixes JS-superset fixes: * export { type as as } is again the value type renamed as; the type modifier now requires an identifier after the second as * U+00A0 is treated as whitespace in import/export names and around the as keyword, matching ES whitespace semantics TS lexing fixes: * multi-line conditional / union types stay erased: line-leading ?, :, ., =>, extends continue the erased alias RHS * import A = require('m') records a runtime import edge (type-only under import type); namespace alias RHS is erased * export declare declarations are erased with their names recorded as type-only exports; export abstract class records the class name; export enum / const enum / namespace record their value names * bracketed promise member access (import('m')['then']) stays runtime and comments no longer defeat dynamic import classification * reexport from is typed string | undefined and the asm.js build now matches the wasm build on undecodable specifiers All additions are guarded by LEX_TS: the minimal wasm build is byte-identical, and export * from stays t: 1 there. * perf: preserve strict specifier decoding Direct strict eval avoids V8's sloppy lookup and strict insertion cache mismatch. It reduces IITM fixture parsing from 25.95 µs to 0.755 µs on Node.js 24.18.0. The asm.js decoder and re-export types retain the same parse-error contract. * fix: collect typed export binding lists A type annotation ended exported variable scanning at its colon, so later declarators were omitted from the export list. * perf: defer TypeScript checks behind character gates Leading-character gates keep ordinary JavaScript imports and exports out of the TypeScript scanners. Two fresh Node 24.18.0 runs reduced a 147 KB parse from 312.2 to 302.7 µs and from 316.1 to 303.0 µs. * test: fuzz typed export binding lists Dynamic imports expose their heuristic through `probablyTypeOnly`. Reading `typeOnly` classified each typed dynamic import as runtime and kept annotated binding lists outside the oracle. * refactor: reuse type-only specifier detection * fix: correct TypeScript type-only classification Computed or escaped dynamic-import members can execute at runtime, while ambient declarations can span comments, binding lists, signatures, and bodies. Treating those forms as one-token cases either hid runtime edges or leaked erased imports and dropped exports. The fuzzer marks expected runtime imports, erased imports, and type-only exports because differential stripping alone cannot detect matching errors on both paths. * perf: decode module strings without eval (#239) * perf: decode module strings without eval The Wasm builds passed validated string literals through eval, so runtimes that disable string code generation rejected otherwise valid modules. On Node.js 24.20.0, a one-import parse changed from 354.06-361.01 ns to 238.12-240.85 ns. A mixed parse with seven import records changed from 2.035-2.036 µs to 1.128-1.133 µs. The full ESM bundle grows by 176 Brotli bytes. Refs: nodejs/cjs-module-lexer#118 * perf: bound module string scans Unbounded backslash searches made 1,000-import modules take 267.0 ns per record instead of 60.7 ns on Node 24.20.0. The same export workload improves from 531.3 to 92.6 ns per record. Benchmarks used V8 13.6, seven trials, and 500 parse iterations per shape after 50,000 warmup parses. No-substitution templates now normalize raw CR and CRLF. The parser records CR during its existing scan, so normal strings need no additional pass. * test: cover minimal CommonJS without eval The combined minimal and CommonJS mode loaded the full CommonJS bundle, so CI did not exercise the published minimal require path. * fix: TS review follow-ups * `export { type as }` / `import { type as }` are the type-only specifier `as`, matching the TypeScript parser table; previously the export was dropped entirely. * Bare `declare` ambient declarations are erased at statement position like bare `type` / `interface`, so `declare const x: import('m').T` no longer records a dynamic import edge. `declare` as a plain identifier is untouched. * `export default interface Foo {}` reports a type-only `default` export. * Decode on the SafeString bit rather than exact flag equality. * Drop the orphaned Acorn license header in the asm.js reader now that none of its code remains, and rename acornPos to errorPos. * README: document `probablyTypeOnly` on DynamicImport and the above. * Tests and fuzz forms for each case; the no-eval lane asserts eval is actually disabled. --------- Co-authored-by: Guy Bedford <guybedford@gmail.com>
* An unannotated `declare let` / `var` binding ended by a line break no
longer erases the following statement: the binding name satisfies the
pending operand.
* Shorthand `declare module 'm'`, bare or `export declare`, ends at the
statement unless a `{` body follows, rather than scanning ahead to the
next brace.
* `export default interface Foo {}` reports `Foo` as the local name,
matching `export default class Foo {}`.
Buffer setup outweighs the blit below 64 characters, so sources under that length use the typed-array loop; the Buffer availability check is hoisted.
The open token and dynamic import stacks were pushed without a depth check, so sources nested deeper than 1024 brackets or 512 dynamic imports wrote past the stack arrays. Pushes now go through a checked helper and report a parse error at the overflowing token.
…cture (#240) * feat: minimal build v3 API cleanup Drops the always-null `at` field from minimal import records, makes `ImportType` a type-only const enum with no runtime export, and reports the imported name of `export { a as b } from 'c'` in the minimal build's `ln` / `ls` / `le` rather than erasing it, matching the full build's importName fields. * docs: minimal build upgrading from v2 * docs: restructure the README, track types, drop initSync * README: package exports table carries footprint and cold / warm parse speed per MB; environment support, CSP and usage move to the top with the minimal build documented before the full build; the WASI build steps are removed in favour of the two emsdk checkouts the build installs itself. * `chomp bench` runs all four builds in one process and prints the per-MB table the README uses. * The generated `types/` declarations are tracked so the README can link to them. * `initSync` is internal only: `parse` initializes on first use and `init` covers browser main threads, so nothing needs to call it. The asm.js builds export `init` so all four entry points share one API. * test: check the lane's own entry point exports Each test lane builds only its own dist, so the export parity test now checks the module under test rather than importing all four. The README no longer claims the minimal build tags `export * from` with `t === 8`; it reports the plain static `1`. * feat: literal ImportType aliases, null dynamic attributes, README sizes `ImportType` is a union of named numeric literal type aliases (`StaticImportType = 1`, `DynamicImportType = 2`, ...) rather than an ambient const enum, so nothing is importable at runtime by mistake under single-file transpilers and type stripping. Dynamic import records type `attributes` as `null`: the options argument is not parsed, only located by `attributesStart`. README footprints match `chomp footprint`. * fix: import the shared types the minimal declarations use
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Breaking
type(static|reexport-star|dynamic|import-meta;direct|reexport|reexport-all) with descriptive fields (specifier,importStart/importEnd,attributes,phase,name,localName,from,importIndex,exportStart) replacing the terse v2 names and numeric type tags. (feat: descriptive full-build record fields #233)es-module-lexer/minimalis a new entry point holding the v2-shaped API:parsereturns[imports, exports]only;atis dropped (read attributes viasource.slice(a, se - 1));export { a as b } from 'c'reports the imported name inln/ls/le. (feat: minimal build variant for es-module-shims #211, feat: minimal build v3 API cleanup, literal ImportType, README restructure #240)ImportTypeis a type-only union of named numeric literal aliases (StaticImportType = 1,DynamicImportType = 2, …); no runtime enum is exported.initSyncis no longer exported —parseinitializes on first use. (feat: minimal build v3 API cleanup, literal ImportType, README restructure #240)es-module-lexer/jsis the asm.js build; the unmaintained pure-JS port is removed. (chore: remove the unmaintained pure-JS lexer port #204)undefined. (feat: always validate static specifier unicode in full build #238)Features
typeOnly, dynamic imports carry a best-effortprobablyTypeOnly, and erased declaration bodies never leak nestedimport()types. Full builds only. (feat: lex type-only TypeScript imports and exports #220, fix: bare declare erasure end conditions #241)importName,from,importIndex) regardless of statement order;export * fromappears inexportsasreexport-alland its import asreexport-star. (feat: add export origin analysis #229)${…}collapsed to*(./locales/*.js), disambiguated by the parser so regex/division inside substitutions is handled. (feat(lexer): report glob n for interpolated template dynamic imports #205)attributesis typednull; the options argument is located byattributesStart. (feat: minimal build v3 API cleanup, literal ImportType, README restructure #240)parseinitializes the Wasm synchronously on first call;await initis only required on browser main threads, and all four entry points export the sameparse/initAPI. (fix: make parse type-safe via automatic synchronous initialization #237, feat: minimal build v3 API cleanup, literal ImportType, README restructure #240)Performance
eval: one-import parse 354 → 238 ns, and the Wasm builds now work under--disallow-code-generation-from-strings. (perf: decode module strings without eval #239)Buffer. (perf: copy short sources with the charCodeAt loop #242)Fixes
declare let/varand shorthanddeclare module 'm'no longer erase the following statement;export default interface Foo {}reportsFooas its local name. (fix: bare declare erasure end conditions #241)export { type as }/type as asfollow TypeScript's specifier table; U+00A0 is whitespace around import/export names. (feat: lex type-only TypeScript imports and exports #220)Docs & tooling
chomp benchruns all four builds in one process and prints the README table; generatedtypes/are tracked in the repo. (feat: minimal build v3 API cleanup, literal ImportType, README restructure #240)stripTypeScriptTypesin CI; no-eval lanes for minimal and CommonJS. (feat: lex type-only TypeScript imports and exports #220, perf: decode module strings without eval #239)