@oseo/compiler 0.0.0-stage → 0.1.0-canary.368

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +59 -2
  3. package/dist/agent-programs.d.ts +28 -0
  4. package/dist/agent-programs.d.ts.map +1 -0
  5. package/dist/agent-programs.js +134 -0
  6. package/dist/agent-programs.js.map +1 -0
  7. package/dist/agent-templates.d.ts +33 -0
  8. package/dist/agent-templates.d.ts.map +1 -0
  9. package/dist/agent-templates.js +45 -0
  10. package/dist/agent-templates.js.map +1 -0
  11. package/dist/compile.d.ts +20 -0
  12. package/dist/compile.d.ts.map +1 -0
  13. package/dist/compile.js +75 -0
  14. package/dist/compile.js.map +1 -0
  15. package/dist/fragments.d.ts +72 -0
  16. package/dist/fragments.d.ts.map +1 -0
  17. package/dist/fragments.js +158 -0
  18. package/dist/fragments.js.map +1 -0
  19. package/dist/hir-build.d.ts +80 -0
  20. package/dist/hir-build.d.ts.map +1 -0
  21. package/dist/hir-build.js +3077 -0
  22. package/dist/hir-build.js.map +1 -0
  23. package/dist/hir-print.d.ts +10 -0
  24. package/dist/hir-print.d.ts.map +1 -0
  25. package/dist/hir-print.js +271 -0
  26. package/dist/hir-print.js.map +1 -0
  27. package/dist/hir.d.ts +1246 -0
  28. package/dist/hir.d.ts.map +1 -0
  29. package/dist/hir.js +147 -0
  30. package/dist/hir.js.map +1 -0
  31. package/dist/host-scripts.d.ts +14 -0
  32. package/dist/host-scripts.d.ts.map +1 -0
  33. package/dist/host-scripts.js +204 -0
  34. package/dist/host-scripts.js.map +1 -0
  35. package/dist/index.d.ts +26 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +27 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/mir-build.d.ts +8 -0
  40. package/dist/mir-build.d.ts.map +1 -0
  41. package/dist/mir-build.js +5113 -0
  42. package/dist/mir-build.js.map +1 -0
  43. package/dist/mir-print.d.ts +7 -0
  44. package/dist/mir-print.d.ts.map +1 -0
  45. package/dist/mir-print.js +65 -0
  46. package/dist/mir-print.js.map +1 -0
  47. package/dist/mir-specialize.d.ts +7 -0
  48. package/dist/mir-specialize.d.ts.map +1 -0
  49. package/dist/mir-specialize.js +182 -0
  50. package/dist/mir-specialize.js.map +1 -0
  51. package/dist/mir.d.ts +571 -0
  52. package/dist/mir.d.ts.map +1 -0
  53. package/dist/mir.js +1 -0
  54. package/dist/module-builtin.d.ts +20 -0
  55. package/dist/module-builtin.d.ts.map +1 -0
  56. package/dist/module-builtin.js +57 -0
  57. package/dist/module-builtin.js.map +1 -0
  58. package/dist/module-compile.d.ts +64 -0
  59. package/dist/module-compile.d.ts.map +1 -0
  60. package/dist/module-compile.js +690 -0
  61. package/dist/module-compile.js.map +1 -0
  62. package/dist/module-json.d.ts +7 -0
  63. package/dist/module-json.d.ts.map +1 -0
  64. package/dist/module-json.js +88 -0
  65. package/dist/module-json.js.map +1 -0
  66. package/dist/modules.d.ts +87 -0
  67. package/dist/modules.d.ts.map +1 -0
  68. package/dist/modules.js +734 -0
  69. package/dist/modules.js.map +1 -0
  70. package/dist/native-fragments.d.ts +36 -0
  71. package/dist/native-fragments.d.ts.map +1 -0
  72. package/dist/native-fragments.js +110 -0
  73. package/dist/native-fragments.js.map +1 -0
  74. package/dist/native.d.ts +282 -0
  75. package/dist/native.d.ts.map +1 -0
  76. package/dist/native.js +47 -0
  77. package/dist/native.js.map +1 -0
  78. package/dist/regexp-execute.d.ts +74 -0
  79. package/dist/regexp-execute.d.ts.map +1 -0
  80. package/dist/regexp-execute.js +480 -0
  81. package/dist/regexp-execute.js.map +1 -0
  82. package/dist/regexp-matcher.d.ts +279 -0
  83. package/dist/regexp-matcher.d.ts.map +1 -0
  84. package/dist/regexp-matcher.js +1098 -0
  85. package/dist/regexp-matcher.js.map +1 -0
  86. package/dist/regexp-parse.d.ts +22 -0
  87. package/dist/regexp-parse.d.ts.map +1 -0
  88. package/dist/regexp-parse.js +1440 -0
  89. package/dist/regexp-parse.js.map +1 -0
  90. package/dist/regexp-print.d.ts +24 -0
  91. package/dist/regexp-print.d.ts.map +1 -0
  92. package/dist/regexp-print.js +147 -0
  93. package/dist/regexp-print.js.map +1 -0
  94. package/dist/regexp.d.ts +324 -0
  95. package/dist/regexp.d.ts.map +1 -0
  96. package/dist/regexp.js +22 -0
  97. package/dist/regexp.js.map +1 -0
  98. package/dist/source.d.ts +38 -0
  99. package/dist/source.d.ts.map +1 -0
  100. package/dist/source.js +10 -0
  101. package/dist/source.js.map +1 -0
  102. package/dist/syntax.d.ts +1232 -0
  103. package/dist/syntax.d.ts.map +1 -0
  104. package/dist/syntax.js +1 -0
  105. package/package.json +32 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"native.js","names":[],"sources":["../src/native.ts"],"sourcesContent":["/*\n * Oseo, an ahead-of-time compiler for JavaScript and TypeScript.\n * Copyright (C) 2026 Hong Minhee <https://hongminhee.org/>\n *\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <https://www.gnu.org/licenses/>.\n */\n\nimport type { MirProgram } from \"./mir.ts\";\n/** Architecture facts admitted by Oseo native targets. */\nexport type NativeArchitecture = \"aarch64\" | \"x86_64\";\n\n/** Operating-system facts admitted by Oseo native targets. */\nexport type NativeOperatingSystem = \"linux\" | \"macos\";\n\n/** ABI environments distinguished by Oseo's native Linux targets. */\nexport type NativeAbi = \"gnu\" | \"musl\";\n\n/** Stable Oseo native target IDs in OS-architecture-ABI order. */\nexport type TargetName =\n | \"linux-aarch64-musl\"\n | \"linux-x86_64-gnu\"\n | \"macos-aarch64\";\n\n/** Normalized host detection, including explicitly unknown reported facts. */\nexport interface ExecutionHostDescription {\n readonly architecture: NativeArchitecture | \"unknown\";\n readonly operatingSystem: NativeOperatingSystem | \"unknown\";\n}\n\n/** Toolchain-neutral artifact facts for one explicit Oseo target ID. */\nexport interface TargetDescription {\n readonly abi?: NativeAbi;\n readonly architecture: NativeArchitecture;\n /**\n * The processor hint the runtime's `Atomics.pause` executes once per\n * call: the x86-64 PAUSE instruction or the AArch64 YIELD instruction.\n */\n readonly atomicsPauseHint: \"aarch64-yield\" | \"x86-pause\";\n readonly cStandard: \"c11\";\n readonly executableFormat: \"elf\" | \"mach-o\";\n readonly name: TargetName;\n readonly operatingSystem: NativeOperatingSystem;\n readonly sanitizers: readonly (\"address\" | \"undefined\")[];\n}\n\n/** Deterministic source emitted by a replaceable native backend. */\nexport interface NativeSourceFile {\n readonly source: string;\n readonly sourceName: string;\n}\n\n/** Source display plus optional bounded units used for native compilation. */\nexport interface EmittedNativeSource extends NativeSourceFile {\n /**\n * Compile these files instead of the standalone source when present.\n * Stage the standalone source beside them under sourceName for includes.\n */\n readonly compilationUnits?: readonly NativeSourceFile[];\n}\n\n/** Backend boundary that never performs process execution. */\nexport interface NativeBackend {\n emit(input: MirProgram): EmittedNativeSource;\n}\n\n/** One reviewed native asset supplied by a runtime package. */\nexport interface RuntimeAsset {\n readonly kind: \"header\" | \"source\";\n readonly name: string;\n readonly url: URL;\n}\n\n/** A versioned set of native runtime inputs. */\nexport interface RuntimeInput {\n readonly abiVersion: string;\n readonly assets: readonly RuntimeAsset[];\n}\n\n/** Provider boundary between runtime selection and backend emission. */\nexport interface RuntimeInputProvider {\n getRuntimeInput(): RuntimeInput;\n}\n\n/**\n * Host-variable names a toolchain permits one of its subprocesses to inherit.\n */\nexport interface ProcessEnvironmentPolicy {\n readonly inherit: readonly string[];\n}\n\n/** Immutable host environment captured for one native workflow. */\nexport interface ProcessEnvironment {\n readonly variables: Readonly<Record<string, string>>;\n}\n\n/** One process request created by a native toolchain adapter. */\nexport interface ProcessRequest {\n readonly args: readonly string[];\n readonly command: string;\n readonly cwd: string;\n readonly environment?: ProcessEnvironment;\n /** Bytes or UTF-8 text written to stdin, then EOF; omission means EOF. */\n readonly input?: string | Uint8Array;\n /** Preserve output bytes as well as the legacy UTF-8 text observation. */\n readonly captureBytes?: boolean;\n /** Use the invoking terminal or pipe when no explicit input is supplied. */\n readonly inheritStdin?: boolean;\n /** Inherit stdout/stderr; observations then contain empty output strings. */\n readonly inheritOutput?: boolean;\n}\n\n/** Host-independent subprocess observation. */\nexport interface ProcessObservation {\n readonly exitStatus: number;\n readonly stderr: string;\n readonly stdout: string;\n /** Present when the request asks for byte-exact output capture. */\n readonly stdoutBytes?: Uint8Array;\n readonly stderrBytes?: Uint8Array;\n}\n\n/** Compiler configuration for the same native target. */\nexport type NativeBuildConfiguration = \"checked\" | \"optimized\";\n\n/** Files and commands required for one native build. */\nexport interface NativeBuildPlan {\n /** Defaults to checked when omitted. */\n readonly buildConfiguration?: NativeBuildConfiguration;\n readonly executablePath: string;\n readonly requests: readonly ProcessRequest[];\n readonly runtimeArchivePath?: string;\n readonly target: TargetDescription;\n}\n\n/** Runtime asset contents covered by one toolchain-owned archive key. */\nexport interface RuntimeArchiveAsset {\n readonly contents: string;\n readonly kind: RuntimeAsset[\"kind\"];\n readonly name: string;\n}\n\n/** Complete semantic and tool inputs covered by one runtime archive key. */\nexport interface RuntimeArchiveKeyInput {\n /** Defaults to checked when omitted. */\n readonly buildConfiguration?: NativeBuildConfiguration;\n readonly runtimeAbiVersion: string;\n readonly runtimeAssets: readonly RuntimeArchiveAsset[];\n readonly target: TargetDescription;\n readonly toolchainEnvironment: ProcessEnvironment;\n readonly toolchainIdentity: string;\n}\n\n/**\n * The executable a toolchain identity describes, and the paths whose\n * fingerprints decide whether that identity is still current. A composer\n * that reuses one identity across many builds pins the compiler by this\n * absolute path and rechecks the fingerprints before every build, so an\n * executable replaced or relinked mid-process cannot run under a key\n * derived from the previous one.\n */\nexport interface PinnedToolchain {\n readonly compilerPath: string;\n readonly watchedPaths: readonly string[];\n}\n\n/**\n * Facts a host reports about one path without reading it. The identity\n * fields describe the file the path resolves to, so replacing a file in\n * place and repointing a symbolic link both change them. `realPath` is that\n * resolved location, which a caller pins so later work runs the same file\n * the fingerprint describes.\n */\nexport interface FileFingerprint {\n /**\n * Inode change time. It moves on an in-place rewrite even when the writer\n * restores the size and the modification time, which the other fields\n * would then miss. A host that cannot report it leaves it absent, and a\n * caller that depends on detecting such a rewrite must refuse that host\n * rather than compare the remaining fields.\n */\n readonly changedAtMilliseconds?: number;\n readonly device: number;\n readonly inode: number;\n readonly modifiedAtMilliseconds: number;\n readonly realPath: string;\n readonly size: number;\n}\n\n/** Optional archive-reuse capability implemented by a native toolchain. */\nexport interface RuntimeArchiveReuse {\n createKey(input: RuntimeArchiveKeyInput): Promise<string>;\n /**\n * Ask the toolchain to report its identity. `compilerPath` repeats the\n * probe through an already resolved executable, which lets a composer\n * confirm that the identity it is about to record describes the file it\n * pinned rather than whatever the search path resolved a moment earlier.\n */\n createIdentityRequest(\n workingDirectory: string,\n environment: ProcessEnvironment,\n compilerPath?: string,\n ): ProcessRequest;\n /**\n * Read the adapter's own identity output and report which executable it\n * describes. An adapter that cannot name one returns undefined, and a\n * composer must then refuse to prepare rather than reuse an unpinned\n * identity.\n */\n pinToolchain?(identity: string): PinnedToolchain | undefined;\n}\n\n/**\n * Explicit inputs used to construct a native build plan. Runtime source\n * paths are an ordered collection: the toolchain compiles every listed\n * translation unit and archives the objects in exactly this order, so\n * filesystem enumeration never selects sources or archive layout.\n */\nexport interface NativeBuildInput {\n /** Defaults to checked when omitted. */\n readonly buildConfiguration?: NativeBuildConfiguration;\n /**\n * Absolute path the toolchain must invoke instead of resolving its\n * compiler through the host's search path. A composer that pinned the\n * compiler for a prepared runtime supplies it so that every build of that\n * preparation runs the executable the recorded identity describes.\n */\n readonly compilerPath?: string;\n readonly environment?: ProcessEnvironment;\n readonly generatedSourcePath: string;\n /** Opt-in additional units and already compiled objects, in link order. */\n readonly additionalGeneratedSourcePaths?: readonly string[];\n readonly prebuiltObjectPaths?: readonly string[];\n readonly prebuiltRuntimeArchivePath?: string;\n readonly runtimeDirectory: string;\n readonly runtimeSourcePaths: readonly string[];\n readonly target: TargetDescription;\n readonly workingDirectory: string;\n}\n\n/** Toolchain boundary that constructs commands without executing them. */\nexport interface NativeToolchain {\n /** Configuration selected by a composing test or application. */\n readonly buildConfiguration?: NativeBuildConfiguration;\n /** Exact compiler identity retained in failure and replay metadata. */\n readonly identity?: string;\n createBuildPlan(input: NativeBuildInput): NativeBuildPlan;\n readonly environment?: ProcessEnvironmentPolicy;\n readonly runtimeArchiveReuse?: RuntimeArchiveReuse;\n readonly harnessObjectReuse?: HarnessObjectReuse;\n}\n\n/** Exclusive lease over one host-owned compiler cache path. */\nexport interface CompilerCacheLock {\n release(): Promise<void>;\n}\n\n/** Persistent cache storage whose location and lifetime belong to one host. */\nexport interface CompilerCache {\n acquireFileLock(path: string): Promise<CompilerCacheLock>;\n getDirectory(name: string): Promise<string>;\n hasFile(path: string): Promise<boolean>;\n publishFile(sourcePath: string, destinationPath: string): Promise<void>;\n}\n\n/** Narrow host boundary used by compiler adapters and test infrastructure. */\nexport interface CompilerHost {\n readonly cache?: CompilerCache;\n canonicalizeFile?(path: string): Promise<string>;\n /**\n * Report one path's fingerprint without reading it, or undefined when the\n * path does not exist. It is a stat, so a caller may repeat it per native\n * execution.\n */\n describeFile?(path: string): Promise<FileFingerprint | undefined>;\n captureEnvironment?(\n policy: ProcessEnvironmentPolicy,\n ): Promise<ProcessEnvironment | undefined>;\n readonly executionHost?: ExecutionHostDescription;\n makeTemporaryDirectory(prefix: string): Promise<string>;\n readTextFile(path: string | URL): Promise<string>;\n remove(path: string): Promise<void>;\n run(request: ProcessRequest): Promise<ProcessObservation>;\n writeTextFile(path: string, contents: string): Promise<void>;\n}\n\n/** Return the immutable artifact facts for an explicit native target. */\nexport function describeTarget(name: TargetName): TargetDescription {\n if (name === \"linux-x86_64-gnu\") {\n return {\n abi: \"gnu\",\n architecture: \"x86_64\",\n atomicsPauseHint: \"x86-pause\",\n cStandard: \"c11\",\n executableFormat: \"elf\",\n name,\n operatingSystem: \"linux\",\n sanitizers: [\"address\", \"undefined\"],\n };\n }\n if (name === \"macos-aarch64\") {\n return {\n architecture: \"aarch64\",\n atomicsPauseHint: \"aarch64-yield\",\n cStandard: \"c11\",\n executableFormat: \"mach-o\",\n name,\n operatingSystem: \"macos\",\n sanitizers: [\"address\", \"undefined\"],\n };\n }\n if (name === \"linux-aarch64-musl\") {\n return {\n abi: \"musl\",\n architecture: \"aarch64\",\n atomicsPauseHint: \"aarch64-yield\",\n cStandard: \"c11\",\n executableFormat: \"elf\",\n name,\n operatingSystem: \"linux\",\n sanitizers: [],\n };\n }\n throw new Error(`Unsupported native target '${String(name)}'.`);\n}\n\n/** Whether one normalized host may execute an artifact for a target. */\nexport function canExecuteTarget(\n host: ExecutionHostDescription,\n target: TargetDescription,\n): boolean {\n return targetForExecutionHost(host)?.name === target.name;\n}\n\n/** Select the supported native target matching one execution host. */\nexport function targetForExecutionHost(\n host: ExecutionHostDescription,\n): TargetDescription | undefined {\n if (host.architecture === \"x86_64\" && host.operatingSystem === \"linux\") {\n return describeTarget(\"linux-x86_64-gnu\");\n }\n if (host.architecture === \"aarch64\" && host.operatingSystem === \"macos\") {\n return describeTarget(\"macos-aarch64\");\n }\n return undefined;\n}\n\n/** Normalized object staging contains harness.c and runtime headers. */\nexport interface HarnessObjectBuildInput {\n /** Defaults to checked when omitted. */\n readonly buildConfiguration?: NativeBuildConfiguration;\n /** Pinned compiler, with the same meaning as on `NativeBuildInput`. */\n readonly compilerPath?: string;\n readonly workingDirectory: string;\n readonly target: TargetDescription;\n readonly environment: ProcessEnvironment;\n}\n\n/** Complete bundle, compiler, runtime, and tool inputs for object reuse. */\nexport interface HarnessObjectKeyInput extends RuntimeArchiveKeyInput {\n readonly fragmentAbiVersion: string;\n readonly harnessSources: readonly {\n readonly sourceId: string;\n readonly source: string;\n }[];\n readonly strict: boolean;\n readonly specialization: \"enabled\" | \"disabled\";\n readonly observeSpecialization: boolean;\n /** Content identities must include uncommitted implementation changes. */\n readonly frontendIdentity: string;\n readonly compilerIdentity: string;\n readonly backendIdentity: string;\n readonly generatedSource: string;\n}\n\n/** Adapter-owned flags are included by createKey, never supplied ambiently. */\nexport interface HarnessObjectReuse {\n createKey(input: HarnessObjectKeyInput): Promise<string>;\n createBuildRequest(input: HarnessObjectBuildInput): ProcessRequest;\n}\n"],"mappings":";;AAySA,SAAgB,eAAe,MAAqC;CAClE,IAAI,SAAS,oBACX,OAAO;EACL,KAAK;EACL,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,kBAAkB;EAClB;EACA,iBAAiB;EACjB,YAAY,CAAC,WAAW,WAAW;CACrC;CAEF,IAAI,SAAS,iBACX,OAAO;EACL,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,kBAAkB;EAClB;EACA,iBAAiB;EACjB,YAAY,CAAC,WAAW,WAAW;CACrC;CAEF,IAAI,SAAS,sBACX,OAAO;EACL,KAAK;EACL,cAAc;EACd,kBAAkB;EAClB,WAAW;EACX,kBAAkB;EAClB;EACA,iBAAiB;EACjB,YAAY,CAAC;CACf;CAEF,MAAM,IAAI,MAAM,8BAA8B,OAAO,IAAI,EAAE,GAAG;AAChE;;AAGA,SAAgB,iBACd,MACA,QACS;CACT,OAAO,uBAAuB,IAAI,CAAC,EAAE,SAAS,OAAO;AACvD;;AAGA,SAAgB,uBACd,MAC+B;CAC/B,IAAI,KAAK,iBAAiB,YAAY,KAAK,oBAAoB,SAC7D,OAAO,eAAe,kBAAkB;CAE1C,IAAI,KAAK,iBAAiB,aAAa,KAAK,oBAAoB,SAC9D,OAAO,eAAe,eAAe;AAGzC"}
@@ -0,0 +1,74 @@
1
+ import { RegExpSpan } from "./regexp.js";
2
+ import { RegExpMatcherProgram } from "./regexp-matcher.js";
3
+ //#region src/regexp-execute.d.ts
4
+ /** One owned resource boundary the executor can reach. */
5
+ type RegExpExecutionLimit = "backtrack-entries" | "steps" | "trail-entries";
6
+ /**
7
+ * Owned boundaries applied while one match attempt runs.
8
+ *
9
+ * ECMA-262 bounds none of these. Reaching one is an owned failure that the
10
+ * caller observes: the executor never returns a wrong match, and never
11
+ * stops on a clock, so the same artifact, input, and limits always produce
12
+ * the same answer on every host and target.
13
+ */
14
+ interface RegExpExecutionLimits {
15
+ readonly backtrackEntries: number;
16
+ readonly steps: number;
17
+ readonly trailEntries: number;
18
+ }
19
+ /** The reviewed default execution limits. */
20
+ declare const defaultRegExpExecutionLimits: RegExpExecutionLimits;
21
+ /** One match attempt over one artifact. */
22
+ interface RegExpExecutionInput {
23
+ readonly limits?: RegExpExecutionLimits;
24
+ readonly program: RegExpMatcherProgram;
25
+ readonly startIndex: number;
26
+ readonly text: string;
27
+ }
28
+ /**
29
+ * One successful match.
30
+ *
31
+ * `captures[0]` is the whole match and `captures[index]` is capturing
32
+ * group `index`, which is undefined when the group did not participate.
33
+ * Every span is a half-open range of UTF-16 code units into the input.
34
+ */
35
+ interface RegExpMatchedExecution {
36
+ readonly captures: readonly (RegExpSpan | undefined)[];
37
+ readonly outcome: "matched";
38
+ readonly steps: number;
39
+ }
40
+ /** One attempt that completed with no match. */
41
+ interface RegExpUnmatchedExecution {
42
+ readonly outcome: "unmatched";
43
+ readonly steps: number;
44
+ }
45
+ /** One attempt that reached an owned resource boundary. */
46
+ interface RegExpLimitedExecution {
47
+ readonly limit: RegExpExecutionLimit;
48
+ readonly outcome: "limit";
49
+ readonly steps: number;
50
+ }
51
+ /** The outcome of one match attempt. */
52
+ type RegExpExecution = RegExpLimitedExecution | RegExpMatchedExecution | RegExpUnmatchedExecution;
53
+ /**
54
+ * Run one anchored match attempt at one position.
55
+ *
56
+ * The attempt starts at `startIndex` and never searches a later position;
57
+ * `searchRegExpMatcher` owns that loop. Under `u` or `v` a start index
58
+ * that splits a surrogate pair names the character the pair encodes, so
59
+ * the attempt begins at the pair rather than at its trailing code unit.
60
+ */
61
+ declare function matchRegExpMatcher(request: RegExpExecutionInput): RegExpExecution;
62
+ /**
63
+ * Search for the first match at or after one position.
64
+ *
65
+ * This is the position loop of the edition's built-in execution without
66
+ * any object state: a sticky pattern attempts only the given position, and
67
+ * every other pattern advances by one character until the input is
68
+ * exhausted. `lastIndex`, the result array, and `exec` dispatch belong to
69
+ * the unit that adds the `RegExp` intrinsic.
70
+ */
71
+ declare function searchRegExpMatcher(request: RegExpExecutionInput): RegExpExecution;
72
+ //#endregion
73
+ export { RegExpExecution, RegExpExecutionInput, RegExpExecutionLimit, RegExpExecutionLimits, RegExpLimitedExecution, RegExpMatchedExecution, RegExpUnmatchedExecution, defaultRegExpExecutionLimits, matchRegExpMatcher, searchRegExpMatcher };
74
+ //# sourceMappingURL=regexp-execute.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"regexp-execute.d.ts","names":[],"sources":["../src/regexp-execute.ts"],"mappings":";;;;KA2BY;;;;;;;;;UAaK;WACN;WACA;WACA;;;cAIE,8BAA8B;;UAO1B;WACN,SAAS;WACT,SAAS;WACT;WACA;;;;;;;;;UAUM;WACN,oBAAoB;WACpB;WACA;;;UAIM;WACN;WACA;;;UAIM;WACN,OAAO;WACP;WACA;;;KAIC,kBACR,yBACA,yBACA;;;;;;;;;iBAybY,mBACd,SAAS,uBACR;;;;;;;;;;iBA2La,oBACd,SAAS,uBACR"}
@@ -0,0 +1,480 @@
1
+ import { checkRegExpMatcherBound } from "./regexp-matcher.js";
2
+
3
+ //#region src/regexp-execute.ts
4
+ /** The reviewed default execution limits. */
5
+ const defaultRegExpExecutionLimits = {
6
+ backtrackEntries: 4194304,
7
+ steps: 16777216,
8
+ trailEntries: 4194304
9
+ };
10
+ /** An unset capture register. */
11
+ const unset = -1;
12
+ /**
13
+ * Reject a request a caller built wrong.
14
+ *
15
+ * A start position that is not a safe integer is not a position at all,
16
+ * and a limit that is not a count would silently disable the boundary it
17
+ * names. Both are caller defects, so both throw rather than producing a
18
+ * match state derived from them. A start position outside the input is a
19
+ * defined query with a defined answer and stays an ordinary outcome.
20
+ */
21
+ function checkRequest(request) {
22
+ if (!Number.isSafeInteger(request.startIndex)) throw new RangeError("A start position must be a safe integer.");
23
+ const limits = request.limits ?? defaultRegExpExecutionLimits;
24
+ checkRegExpMatcherBound(limits.backtrackEntries, "A backtrack-entry limit");
25
+ checkRegExpMatcherBound(limits.steps, "A step limit");
26
+ checkRegExpMatcherBound(limits.trailEntries, "A trail-entry limit");
27
+ return limits;
28
+ }
29
+ /** Whether one inversion list holds one character. */
30
+ function setHas(set, character) {
31
+ let low = 0;
32
+ let high = set.length;
33
+ while (low < high) {
34
+ const middle = low + high >> 1;
35
+ if ((set[middle] ?? 0) <= character) low = middle + 1;
36
+ else high = middle;
37
+ }
38
+ return (low & 1) === 1;
39
+ }
40
+ function canonicalize(table, character) {
41
+ if (table == null) return character;
42
+ const characters = table.characters;
43
+ let low = 0;
44
+ let high = characters.length;
45
+ while (low < high) {
46
+ const middle = low + high >> 1;
47
+ const value = characters[middle] ?? 0;
48
+ if (value === character) return table.canonical[middle] ?? character;
49
+ if (value < character) low = middle + 1;
50
+ else high = middle;
51
+ }
52
+ return character;
53
+ }
54
+ /**
55
+ * One character of the input read forward from `index`.
56
+ *
57
+ * A pattern with `u` or `v` matches a list of code points and every other
58
+ * pattern matches a list of UTF-16 code units, which is the only place the
59
+ * flag set changes what one position advances by. A lone surrogate is one
60
+ * character in both readings.
61
+ */
62
+ function characterAt(text, index, unicodeMode) {
63
+ const unit = text.charCodeAt(index);
64
+ if (!unicodeMode || unit < 55296 || unit > 56319) return unit;
65
+ const trail = text.charCodeAt(index + 1);
66
+ if (Number.isNaN(trail) || trail < 56320 || trail > 57343) return unit;
67
+ return (unit - 55296) * 1024 + (trail - 56320) + 65536;
68
+ }
69
+ /** How many code units the character starting at `index` occupies. */
70
+ function widthAt(text, index, unicodeMode) {
71
+ return characterAt(text, index, unicodeMode) > 65535 ? 2 : 1;
72
+ }
73
+ /** How many code units the character ending at `index` occupies. */
74
+ function widthBefore(text, index, unicodeMode) {
75
+ if (!unicodeMode || index < 2) return 1;
76
+ const trail = text.charCodeAt(index - 1);
77
+ const lead = text.charCodeAt(index - 2);
78
+ return trail >= 56320 && trail <= 57343 && lead >= 55296 && lead <= 56319 ? 2 : 1;
79
+ }
80
+ /** The character ending at `index`, or -1 at the start of the input. */
81
+ function characterBefore(text, index, unicodeMode) {
82
+ if (index <= 0) return -1;
83
+ return characterAt(text, index - widthBefore(text, index, unicodeMode), unicodeMode);
84
+ }
85
+ /**
86
+ * The position one attempt actually starts at.
87
+ *
88
+ * The edition converts a string index into an index into the character
89
+ * list it matches over, and under `u` or `v` both code units of a
90
+ * surrogate pair belong to the one character they encode. A start index
91
+ * that splits a pair therefore names that character, not its trailing
92
+ * code unit, so the attempt begins at the pair.
93
+ */
94
+ function alignedStart(text, index, unicodeMode) {
95
+ if (!unicodeMode || index <= 0 || index >= text.length) return index;
96
+ const trail = text.charCodeAt(index);
97
+ const lead = text.charCodeAt(index - 1);
98
+ return trail >= 56320 && trail <= 57343 && lead >= 55296 && lead <= 56319 ? index - 1 : index;
99
+ }
100
+ /** The four code points the LineTerminator production names. */
101
+ function isLineTerminator(character) {
102
+ return character === 10 || character === 13 || character === 8232 || character === 8233;
103
+ }
104
+ function write(machine, register, value) {
105
+ if (machine.trailRegister.length >= machine.limits.trailEntries) {
106
+ machine.limit = "trail-entries";
107
+ return false;
108
+ }
109
+ machine.trailRegister.push(register);
110
+ machine.trailValue.push(machine.registers[register] ?? unset);
111
+ machine.registers[register] = value;
112
+ return true;
113
+ }
114
+ function undoTrail(machine, height) {
115
+ while (machine.trailRegister.length > height) {
116
+ const register = machine.trailRegister.pop() ?? 0;
117
+ machine.registers[register] = machine.trailValue.pop() ?? unset;
118
+ }
119
+ }
120
+ function push(machine, address) {
121
+ if (machine.stackProgram.length >= machine.limits.backtrackEntries) {
122
+ machine.limit = "backtrack-entries";
123
+ return false;
124
+ }
125
+ machine.stackProgram.push(address);
126
+ machine.stackIndex.push(machine.index);
127
+ machine.stackTrail.push(machine.trailRegister.length);
128
+ return true;
129
+ }
130
+ /** The address one backtrack entry resumes at, or -1 when none is left. */
131
+ function pop(machine) {
132
+ const address = machine.stackProgram.pop();
133
+ if (address == null) return -1;
134
+ machine.index = machine.stackIndex.pop() ?? 0;
135
+ undoTrail(machine, machine.stackTrail.pop() ?? 0);
136
+ return address;
137
+ }
138
+ /**
139
+ * Match one backreference, or report that the path fails.
140
+ *
141
+ * The candidates run one at a time, in the order a lowering writes them,
142
+ * and `allowed` is how many of them the remaining step budget admits, so
143
+ * a request with one step left reads one candidate rather than the whole
144
+ * list. A candidate whose capture did not participate matches the empty
145
+ * string; the edition lets at most one of them participate, and running
146
+ * each in turn is what makes that a consequence rather than an
147
+ * assumption.
148
+ */
149
+ function matchBackreference(machine, slots, backward, ignoreCase, allowed) {
150
+ const total = Math.max(slots.length, 1);
151
+ const table = ignoreCase ? machine.program.canonicalization : void 0;
152
+ for (let candidate = 0; candidate < total; candidate += 1) {
153
+ if (candidate >= allowed) return {
154
+ limited: true,
155
+ matched: false,
156
+ steps: allowed
157
+ };
158
+ const refused = {
159
+ limited: false,
160
+ matched: false,
161
+ steps: candidate + 1
162
+ };
163
+ const slot = slots[candidate];
164
+ if (slot == null) continue;
165
+ const start = machine.registers[slot] ?? unset;
166
+ const end = machine.registers[slot + 1] ?? unset;
167
+ if (start === unset || end === unset) continue;
168
+ const length = end - start;
169
+ const target = backward ? machine.index - length : machine.index;
170
+ if (target < 0 || target + length > machine.text.length) return refused;
171
+ let source = start;
172
+ let compared = target;
173
+ let equal = true;
174
+ while (source < end) {
175
+ const width = widthAt(machine.text, source, machine.unicodeMode);
176
+ const left = characterAt(machine.text, source, machine.unicodeMode);
177
+ const right = characterAt(machine.text, compared, machine.unicodeMode);
178
+ if (canonicalize(table, left) !== canonicalize(table, right)) {
179
+ equal = false;
180
+ break;
181
+ }
182
+ source += width;
183
+ compared += width;
184
+ }
185
+ if (!equal) return refused;
186
+ machine.index = backward ? target : target + length;
187
+ }
188
+ return {
189
+ limited: false,
190
+ matched: true,
191
+ steps: total
192
+ };
193
+ }
194
+ function matchesBoundary(machine, set) {
195
+ const before = characterBefore(machine.text, machine.index, machine.unicodeMode);
196
+ return (before >= 0 && setHas(set, before)) !== (machine.index < machine.text.length && setHas(set, characterAt(machine.text, machine.index, machine.unicodeMode)));
197
+ }
198
+ function matchesEdge(machine, assertion, multiline) {
199
+ if (assertion === "start") {
200
+ if (machine.index === 0) return true;
201
+ if (!multiline) return false;
202
+ return isLineTerminator(characterBefore(machine.text, machine.index, machine.unicodeMode));
203
+ }
204
+ if (machine.index === machine.text.length) return true;
205
+ if (!multiline) return false;
206
+ return isLineTerminator(characterAt(machine.text, machine.index, machine.unicodeMode));
207
+ }
208
+ function collectCaptures(machine) {
209
+ const total = machine.program.captures.length + 1;
210
+ const captures = [];
211
+ for (let index = 0; index < total; index += 1) {
212
+ const start = machine.registers[2 * index] ?? unset;
213
+ const end = machine.registers[2 * index + 1] ?? unset;
214
+ captures.push(start === unset || end === unset ? void 0 : {
215
+ end,
216
+ start
217
+ });
218
+ }
219
+ return captures;
220
+ }
221
+ /**
222
+ * Prove the entire artifact is ^set+$ before touching match state.
223
+ *
224
+ * Keep this exact layout proof in sync with anchored_repeat_set in C.
225
+ * There is no continuation, capture, empty body or alternative whose
226
+ * state could escape the scan. Everything else keeps ordered execution.
227
+ */
228
+ function anchoredRepeatSet(program) {
229
+ if (![
230
+ "",
231
+ "u",
232
+ "v"
233
+ ].includes(program.flags.text) || program.captures.length !== 0 || program.registers !== 4 || program.instructions.length !== 11) return void 0;
234
+ const [save, start, init, repeat, enter, consume, end, edge, close, accept, fail] = program.instructions;
235
+ if (save?.kind !== "save" || save.slot !== 0 || start?.kind !== "edge" || start.assertion !== "start" || start.multiline || init?.kind !== "repeat-init" || init.counter !== 2 || repeat?.kind !== "repeat" || repeat.counter !== 2 || repeat.enter !== 4 || repeat.exit !== 7 || !repeat.greedy || repeat.minimum !== 1 || repeat.maximum !== Infinity || enter?.kind !== "repeat-enter" || enter.counter !== 2 || enter.position !== 3 || enter.body !== 5 || enter.clearFrom !== 0 || enter.clearTo !== 0 || consume?.kind !== "consume" || consume.backward || end?.kind !== "repeat-end" || end.counter !== 2 || end.position !== 3 || end.head !== 3 || end.minimum !== 1 || edge?.kind !== "edge" || edge.assertion !== "end" || edge.multiline || close?.kind !== "save" || close.slot !== 1 || accept?.kind !== "accept" || fail?.kind !== "fail") return void 0;
236
+ return program.sets[consume.set];
237
+ }
238
+ /**
239
+ * Constant-state scan of a proved complete pattern, with no undo state.
240
+ * Charge one entry, one per character tested, and one terminal decision.
241
+ * The existing step ceiling remains explicit; no trail or stack is used.
242
+ * Non-multiline $ requires InputLength, including after line terminators.
243
+ */
244
+ function scanAnchoredRepeat(request, limits, set) {
245
+ const { program, text } = request;
246
+ let steps = 0;
247
+ const limited = () => ({
248
+ limit: "steps",
249
+ outcome: "limit",
250
+ steps
251
+ });
252
+ if (steps >= limits.steps) return limited();
253
+ steps += 1;
254
+ if (alignedStart(text, request.startIndex, program.unicodeMode) !== 0) return {
255
+ outcome: "unmatched",
256
+ steps
257
+ };
258
+ let index = 0;
259
+ while (index < text.length) {
260
+ if (steps >= limits.steps) return limited();
261
+ steps += 1;
262
+ const character = characterAt(text, index, program.unicodeMode);
263
+ if (!setHas(set, character)) return {
264
+ outcome: "unmatched",
265
+ steps
266
+ };
267
+ index += character > 65535 ? 2 : 1;
268
+ }
269
+ if (steps >= limits.steps) return limited();
270
+ steps += 1;
271
+ return index === 0 ? {
272
+ outcome: "unmatched",
273
+ steps
274
+ } : {
275
+ captures: [{
276
+ end: index,
277
+ start: 0
278
+ }],
279
+ outcome: "matched",
280
+ steps
281
+ };
282
+ }
283
+ /**
284
+ * Run one anchored match attempt at one position.
285
+ *
286
+ * The attempt starts at `startIndex` and never searches a later position;
287
+ * `searchRegExpMatcher` owns that loop. Under `u` or `v` a start index
288
+ * that splits a surrogate pair names the character the pair encodes, so
289
+ * the attempt begins at the pair rather than at its trailing code unit.
290
+ */
291
+ function matchRegExpMatcher(request) {
292
+ const { program, startIndex, text } = request;
293
+ const limits = checkRequest(request);
294
+ if (startIndex < 0 || startIndex > text.length) return {
295
+ outcome: "unmatched",
296
+ steps: 0
297
+ };
298
+ const scanSet = anchoredRepeatSet(program);
299
+ if (scanSet != null) return scanAnchoredRepeat(request, limits, scanSet);
300
+ const machine = {
301
+ index: alignedStart(text, startIndex, program.unicodeMode),
302
+ limit: void 0,
303
+ limits,
304
+ program,
305
+ registers: Array.from({ length: program.registers }, () => unset),
306
+ stackIndex: [],
307
+ stackProgram: [],
308
+ stackTrail: [],
309
+ steps: 0,
310
+ text,
311
+ trailRegister: [],
312
+ trailValue: [],
313
+ unicodeMode: program.unicodeMode
314
+ };
315
+ for (let index = 2 * (program.captures.length + 1); index < program.registers; index += 1) machine.registers[index] = 0;
316
+ let address = 0;
317
+ for (;;) {
318
+ if (machine.steps >= limits.steps) return {
319
+ limit: "steps",
320
+ outcome: "limit",
321
+ steps: machine.steps
322
+ };
323
+ machine.steps += 1;
324
+ const instruction = program.instructions[address];
325
+ if (instruction == null) return {
326
+ outcome: "unmatched",
327
+ steps: machine.steps
328
+ };
329
+ let failed = false;
330
+ if (instruction.kind === "accept") return {
331
+ captures: collectCaptures(machine),
332
+ outcome: "matched",
333
+ steps: machine.steps
334
+ };
335
+ else if (instruction.kind === "consume") {
336
+ const width = instruction.backward ? widthBefore(text, machine.index, machine.unicodeMode) : widthAt(text, machine.index, machine.unicodeMode);
337
+ const at = instruction.backward ? machine.index - width : machine.index;
338
+ const next = instruction.backward ? at : machine.index + width;
339
+ const set = program.sets[instruction.set] ?? [];
340
+ if (at < 0 || at >= text.length || next < 0 || next > text.length || !setHas(set, characterAt(text, at, machine.unicodeMode))) failed = true;
341
+ else {
342
+ machine.index = next;
343
+ address += 1;
344
+ }
345
+ } else if (instruction.kind === "edge") if (matchesEdge(machine, instruction.assertion, instruction.multiline)) address += 1;
346
+ else failed = true;
347
+ else if (instruction.kind === "boundary") if (matchesBoundary(machine, program.sets[instruction.set] ?? []) !== instruction.negated) address += 1;
348
+ else failed = true;
349
+ else if (instruction.kind === "save") {
350
+ if (!write(machine, instruction.slot, machine.index)) return limitReached(machine);
351
+ address += 1;
352
+ } else if (instruction.kind === "clear") {
353
+ for (let slot = instruction.from; slot < instruction.to; slot += 1) if (!write(machine, slot, unset)) return limitReached(machine);
354
+ address += 1;
355
+ } else if (instruction.kind === "fork") {
356
+ if (!push(machine, instruction.alternative)) return limitReached(machine);
357
+ address = instruction.preferred;
358
+ } else if (instruction.kind === "jump") address = instruction.target;
359
+ else if (instruction.kind === "repeat") {
360
+ const done = machine.registers[instruction.counter] ?? 0;
361
+ if (done < instruction.minimum) address = instruction.enter;
362
+ else if (done >= instruction.maximum) address = instruction.exit;
363
+ else if (instruction.greedy) {
364
+ if (!push(machine, instruction.exit)) return limitReached(machine);
365
+ address = instruction.enter;
366
+ } else {
367
+ if (!push(machine, instruction.enter)) return limitReached(machine);
368
+ address = instruction.exit;
369
+ }
370
+ } else if (instruction.kind === "repeat-init") {
371
+ if (!write(machine, instruction.counter, 0)) return limitReached(machine);
372
+ address += 1;
373
+ } else if (instruction.kind === "repeat-enter") {
374
+ const done = machine.registers[instruction.counter] ?? 0;
375
+ if (!write(machine, instruction.counter, done + 1)) return limitReached(machine);
376
+ if (!write(machine, instruction.position, machine.index)) return limitReached(machine);
377
+ for (let slot = instruction.clearFrom; slot < instruction.clearTo; slot += 1) if (!write(machine, slot, unset)) return limitReached(machine);
378
+ address = instruction.body;
379
+ } else if (instruction.kind === "repeat-end") {
380
+ const done = (machine.registers[instruction.counter] ?? 1) - 1;
381
+ const started = machine.registers[instruction.position] ?? unset;
382
+ if (done >= instruction.minimum && started === machine.index) failed = true;
383
+ else address = instruction.head;
384
+ } else if (instruction.kind === "look-start") {
385
+ if (!push(machine, instruction.onFail)) return limitReached(machine);
386
+ if (!write(machine, instruction.frame, machine.stackProgram.length - 1)) return limitReached(machine);
387
+ address = instruction.body;
388
+ } else if (instruction.kind === "look-end") {
389
+ const frame = machine.registers[instruction.frame] ?? 0;
390
+ const entryIndex = machine.stackIndex[frame] ?? 0;
391
+ const entryTrail = machine.stackTrail[frame] ?? 0;
392
+ machine.stackProgram.length = frame;
393
+ machine.stackIndex.length = frame;
394
+ machine.stackTrail.length = frame;
395
+ machine.index = entryIndex;
396
+ if (instruction.negated) {
397
+ undoTrail(machine, entryTrail);
398
+ failed = true;
399
+ } else address = instruction.exit;
400
+ } else if (instruction.kind === "backreference") {
401
+ const attempt = matchBackreference(machine, instruction.slots, instruction.backward, instruction.ignoreCase, machine.limits.steps - machine.steps + 1);
402
+ machine.steps += attempt.steps - 1;
403
+ if (attempt.limited) return {
404
+ limit: "steps",
405
+ outcome: "limit",
406
+ steps: machine.steps
407
+ };
408
+ if (attempt.matched) address += 1;
409
+ else failed = true;
410
+ } else failed = true;
411
+ if (failed) {
412
+ const resumed = pop(machine);
413
+ if (resumed < 0) return {
414
+ outcome: "unmatched",
415
+ steps: machine.steps
416
+ };
417
+ address = resumed;
418
+ }
419
+ }
420
+ }
421
+ function limitReached(machine) {
422
+ return {
423
+ limit: machine.limit ?? "steps",
424
+ outcome: "limit",
425
+ steps: machine.steps
426
+ };
427
+ }
428
+ /**
429
+ * Search for the first match at or after one position.
430
+ *
431
+ * This is the position loop of the edition's built-in execution without
432
+ * any object state: a sticky pattern attempts only the given position, and
433
+ * every other pattern advances by one character until the input is
434
+ * exhausted. `lastIndex`, the result array, and `exec` dispatch belong to
435
+ * the unit that adds the `RegExp` intrinsic.
436
+ */
437
+ function searchRegExpMatcher(request) {
438
+ const { program, text } = request;
439
+ const limits = checkRequest(request);
440
+ let steps = 0;
441
+ if (request.startIndex < 0 || request.startIndex > text.length) return {
442
+ outcome: "unmatched",
443
+ steps: 0
444
+ };
445
+ const scanSet = anchoredRepeatSet(program);
446
+ if (scanSet != null) return scanAnchoredRepeat(request, limits, scanSet);
447
+ let index = alignedStart(text, request.startIndex, program.unicodeMode);
448
+ for (;;) {
449
+ const attempt = matchRegExpMatcher({
450
+ limits: {
451
+ backtrackEntries: limits.backtrackEntries,
452
+ steps: limits.steps - steps,
453
+ trailEntries: limits.trailEntries
454
+ },
455
+ program,
456
+ startIndex: index,
457
+ text
458
+ });
459
+ steps += attempt.steps;
460
+ if (attempt.outcome === "matched") return {
461
+ captures: attempt.captures,
462
+ outcome: "matched",
463
+ steps
464
+ };
465
+ if (attempt.outcome === "limit") return {
466
+ limit: attempt.limit,
467
+ outcome: "limit",
468
+ steps
469
+ };
470
+ if (program.flags.sticky || index >= text.length) return {
471
+ outcome: "unmatched",
472
+ steps
473
+ };
474
+ index += widthAt(text, index, program.unicodeMode);
475
+ }
476
+ }
477
+
478
+ //#endregion
479
+ export { defaultRegExpExecutionLimits, matchRegExpMatcher, searchRegExpMatcher };
480
+ //# sourceMappingURL=regexp-execute.js.map