|
| 1 | +// Script to inject code for an extra `program` getter on `class ParseResult` in WASM binding files. |
| 2 | + |
| 3 | +import assert from 'assert'; |
| 4 | +import { readFileSync, writeFileSync } from 'fs'; |
| 5 | +import { join as pathJoin } from 'path'; |
| 6 | +import { fileURLToPath } from 'url'; |
| 7 | + |
| 8 | +const pkgDirPath = pathJoin(fileURLToPath(import.meta.url), '../../../npm/parser-wasm'); |
| 9 | + |
| 10 | +const bindingFilename = 'oxc_parser_wasm.js'; |
| 11 | + |
| 12 | +// Extra getter on `ParseResult` `get program() { ... }` that gets the program as JSON string, |
| 13 | +// and parses it to a `Program` object. |
| 14 | +// |
| 15 | +// JSON parsing uses a reviver function that sets `value` field of `Literal`s for `BigInt`s and `RegExp`s. |
| 16 | +// This is not possible to do on Rust side, as neither can be represented correctly in JSON. |
| 17 | +// Invalid regexp, or valid regexp using syntax not supported by the platform is ignored. |
| 18 | +// |
| 19 | +// The getter caches the result to avoid re-parsing JSON every time `result.program` is accessed. |
| 20 | +// |
| 21 | +// Note: This code is repeated in `napi/parser/index.js`. |
| 22 | +// Any changes should be applied in both places. |
| 23 | +const getterCode = ` |
| 24 | + __program; |
| 25 | +
|
| 26 | + get program() { |
| 27 | + if (this.__program) return this.__program; |
| 28 | + return this.__program = JSON.parse(this.programJson, function(key, value) { |
| 29 | + if (value === null && key === 'value' && Object.hasOwn(this, 'type') && this.type === 'Literal') { |
| 30 | + if (Object.hasOwn(this, 'bigint')) { |
| 31 | + return BigInt(this.bigint); |
| 32 | + } |
| 33 | + if (Object.hasOwn(this, 'regex')) { |
| 34 | + const { regex } = this; |
| 35 | + try { |
| 36 | + return RegExp(regex.pattern, regex.flags); |
| 37 | + } catch (_err) {} |
| 38 | + } |
| 39 | + } |
| 40 | + return value; |
| 41 | + }); |
| 42 | + } |
| 43 | +`.trimEnd().replace(/ /g, ' '); |
| 44 | + |
| 45 | +const insertGetterAfter = 'class ParseResult {'; |
| 46 | + |
| 47 | +for (const dirName of ['node', 'web']) { |
| 48 | + const path = pathJoin(pkgDirPath, dirName, bindingFilename); |
| 49 | + const code = readFileSync(path, 'utf8'); |
| 50 | + |
| 51 | + const parts = code.split(insertGetterAfter); |
| 52 | + assert(parts.length === 2); |
| 53 | + const [before, after] = parts; |
| 54 | + const updatedCode = [before, insertGetterAfter, getterCode, after].join(''); |
| 55 | + writeFileSync(path, updatedCode); |
| 56 | +} |
0 commit comments