typenative 0.5.0 → 0.6.1

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 (149) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.github/workflows/npm-publish-github-packages.yml +2 -2
  3. package/CHANGELOG.md +339 -0
  4. package/CONTRIBUTION.md +2 -1
  5. package/README.md +16 -7
  6. package/bin/cli.js +1 -0
  7. package/bin/index.js +62 -3
  8. package/bin/main.js +1 -0
  9. package/bin/node/core.js +46 -0
  10. package/bin/node/events.js +154 -15
  11. package/bin/node/http.js +1265 -127
  12. package/bin/node/process.js +13 -0
  13. package/bin/node/punycode.js +2 -2
  14. package/bin/node/stream.js +56 -7
  15. package/bin/node/stream_web.js +2 -2
  16. package/bin/node/timers.js +4 -2
  17. package/bin/node/url.js +28 -3
  18. package/bin/parse-node.js +2 -2
  19. package/bin/regex_vm.js +2105 -0
  20. package/bin/transpiler.js +17970 -4419
  21. package/bin/typecheck-node.js +2 -1
  22. package/bin/version.js +1 -1
  23. package/conformance.md +57 -15
  24. package/examples/README.md +50 -28
  25. package/examples/angular-templates/README.md +141 -0
  26. package/examples/angular-templates/bench.mjs +173 -0
  27. package/examples/angular-templates/dom-type-globals.d.ts +21 -0
  28. package/examples/angular-templates/dom-type-stubs.ts +21 -0
  29. package/examples/angular-templates/main.ts +135 -0
  30. package/examples/angular-templates/parity.mjs +157 -0
  31. package/examples/angular-templates/run-node.mjs +69 -0
  32. package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
  33. package/examples/desktop-notes/README.md +11 -13
  34. package/examples/dupe-finder/README.md +7 -5
  35. package/examples/fibonacci/README.md +7 -7
  36. package/examples/hello-world/README.md +6 -6
  37. package/examples/json-server/README.md +22 -18
  38. package/examples/mandelbrot-png/README.md +11 -13
  39. package/examples/marked-cli/README.md +60 -44
  40. package/examples/marked-cli/main.ts +122 -4
  41. package/examples/openai-chat/README.md +148 -0
  42. package/examples/openai-chat/bench.mjs +175 -0
  43. package/examples/openai-chat/main.ts +488 -0
  44. package/examples/react-compiler/README.md +185 -0
  45. package/examples/react-compiler/bench.mjs +181 -0
  46. package/examples/react-compiler/main.ts +324 -0
  47. package/examples/react-compiler/parity.mjs +362 -0
  48. package/examples/react-compiler/run-node.mjs +90 -0
  49. package/examples/react-compiler/vendor/babel/LICENSE +22 -0
  50. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
  51. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
  52. package/examples/react-compiler/vendor/charcodes/package.json +25 -0
  53. package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
  54. package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
  55. package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
  56. package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
  57. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
  58. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
  59. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
  60. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
  61. package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
  62. package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
  63. package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
  64. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
  65. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
  66. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
  67. package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
  68. package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
  69. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
  70. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
  71. package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
  72. package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
  73. package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
  74. package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
  75. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
  76. package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
  77. package/examples/react-compiler/vendor/zod/LICENSE +21 -0
  78. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
  79. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
  80. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
  81. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
  82. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
  83. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
  84. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
  85. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
  86. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
  87. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
  88. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
  89. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
  90. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
  91. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
  92. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
  93. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
  94. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
  95. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
  96. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
  97. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
  98. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
  99. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
  100. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
  101. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
  102. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
  103. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
  104. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
  105. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
  106. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
  107. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
  108. package/examples/react-compiler/vendor.mjs +688 -0
  109. package/examples/todo-cli/README.md +9 -9
  110. package/examples/yaml-cli/README.md +50 -34
  111. package/examples/yaml-cli/main.ts +236 -14
  112. package/package.json +8 -5
  113. package/performance/README.md +196 -0
  114. package/performance/any-dynamic.ts +21 -0
  115. package/performance/any-record-view.ts +20 -0
  116. package/performance/arr-hof.ts +21 -0
  117. package/performance/arr-push-index.ts +15 -0
  118. package/performance/arr-sort.ts +21 -0
  119. package/performance/async-await.ts +24 -0
  120. package/performance/class-dispatch.ts +52 -0
  121. package/performance/events-emit.ts +27 -0
  122. package/performance/exc-throw-rare.ts +25 -0
  123. package/performance/exc-try-catch.ts +26 -0
  124. package/performance/fn-closures.ts +29 -0
  125. package/performance/fn-recursion-tree.ts +31 -0
  126. package/performance/gen-for-of.ts +46 -0
  127. package/performance/json-roundtrip.ts +27 -0
  128. package/performance/map-delete.ts +24 -0
  129. package/performance/map-string-keys.ts +22 -0
  130. package/performance/num-arith-loop.ts +14 -0
  131. package/performance/num-bitwise.ts +21 -0
  132. package/performance/num-mod-int.ts +16 -0
  133. package/performance/num-to-string.ts +16 -0
  134. package/performance/obj-alloc.ts +32 -0
  135. package/performance/regex-exec.ts +29 -0
  136. package/performance/regex-site.ts +28 -0
  137. package/performance/set-ops.ts +20 -0
  138. package/performance/str-char-scan.ts +35 -0
  139. package/performance/str-concat-plus.ts +18 -0
  140. package/performance/str-concat.ts +24 -0
  141. package/performance/str-short-scan.ts +26 -0
  142. package/performance/str-split-join.ts +23 -0
  143. package/performance/str-template.ts +16 -0
  144. package/performance/union-switch.ts +57 -0
  145. package/tsparser/check.go +2 -1
  146. package/tsparser/main.go +1 -0
  147. package/types/typenative-npm.d.ts +3 -2
  148. package/types/typenative.d.ts +42 -12
  149. package/ROUND2-HANDOFF.md +0 -200
@@ -53,17 +53,17 @@ Reproduce with `node bench.mjs [runs=30]`. The script compiles `main.ts`, fills
53
53
  a temp file with 50 items for each runtime, and then times **complete process
54
54
  runs** (spawn to exit) of `todo list` and `todo add`.
55
55
 
56
- **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
57
- TypeNative 0.4.1, default (non-`--release`) build.
56
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
57
+ TypeNative 0.5.0 (unreleased changes), default (non-`--release`) build.
58
58
 
59
59
  | Command | Runtime | min | median | mean | max |
60
60
  |-------------|------------|-----------|-----------|-----------|-----------|
61
- | `todo list` | Node.js | 104.98 ms | 111.37 ms | 112.74 ms | 130.05 ms |
62
- | `todo list` | TypeNative | 14.45 ms | 16.26 ms | 16.44 ms | 20.40 ms |
63
- | `todo add` | Node.js | 105.63 ms | 112.74 ms | 113.33 ms | 133.39 ms |
64
- | `todo add` | TypeNative | 15.23 ms | 16.98 ms | 17.15 ms | 23.72 ms |
61
+ | `todo list` | Node.js | 64.82 ms | 76.07 ms | 75.08 ms | 88.16 ms |
62
+ | `todo list` | TypeNative | 7.94 ms | 9.26 ms | 15.17 ms | 185.65 ms |
63
+ | `todo add` | Node.js | 64.27 ms | 75.78 ms | 75.47 ms | 92.32 ms |
64
+ | `todo add` | TypeNative | 8.76 ms | 10.02 ms | 10.07 ms | 12.51 ms |
65
65
 
66
- **TypeNative answers each command 6.6–6.8x faster** (median). At about 16 ms,
67
- a call feels instant. At about 110 ms, there's a visible pause, and it adds up
66
+ **TypeNative answers each command 7.6–8.2x faster** (median). At about 10 ms,
67
+ a call feels instant. At about 75 ms, there's a noticeable delay, and it adds up
68
68
  when the tool runs from a prompt or a hook on every keystroke or commit. The
69
- binary is a single 3.8 MB file, with no Node install and no `node_modules`.
69
+ binary is a single 4.6 MB file, with no Node install and no `node_modules`.
@@ -5,7 +5,11 @@ compiled from its **unmodified** upstream TypeScript source: about 11,000
5
5
  lines across 78 files, vendored as is in [vendor/yaml/](vendor/yaml/) (see
6
6
  [VENDOR.md](vendor/yaml/VENDOR.md): no patches). [main.ts](main.ts) ports
7
7
  upstream's `bin.js` to TypeScript. It hands stdin and the arguments to the
8
- library's `cli()` and turns the error it reports into an exit code.
8
+ library's `cli()` and turns the error it reports into an exit code. For
9
+ `yaml --json` on a large, plain stream it splits the input before the `---`
10
+ lines that start its documents and composes runs of them in parallel workers,
11
+ then joins their JSON arrays; any directive, error, warning, CR line ending or
12
+ non-scalar map key sends the whole input back through `cli()`.
9
13
 
10
14
  This is a test of TypeNative on real code nobody wrote for it: a lexer and
11
15
  parser driven by sticky regexes, class hierarchies with overrides (an
@@ -82,55 +86,67 @@ and checks that the two JSON outputs are identical:
82
86
  Deployments, Services and ConfigMaps in one stream, from a fixed-seed
83
87
  generator, so every machine gets the same input).
84
88
 
85
- **Environment:** Linux 6.18 container, 4 vCPUs of an Intel Xeon @ 2.80GHz,
86
- Node v24.22.2, Go 1.26.0, TypeNative 0.4.2 (unreleased changes), default
87
- (non-`--release`) build. The binary is 7.3 MB.
89
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600 (6 cores, 12 threads),
90
+ Node v26.13.0, Go 1.27.4, TypeNative 0.6.1, default
91
+ (non-`--release`) build.
88
92
 
89
93
  (a) `yaml --json < docker-compose.yml`, 30 runs each:
90
94
 
91
95
  | Runtime | min | median | mean | max |
92
96
  | ---------- | --------- | --------- | --------- | --------- |
93
- | Node.js | 214.80 ms | 249.92 ms | 248.16 ms | 305.68 ms |
94
- | TypeNative | 7.63 ms | 9.16 ms | 9.49 ms | 12.83 ms |
97
+ | Node.js | 102.38 ms | 104.87 ms | 106.76 ms | 117.83 ms |
98
+ | TypeNative | 8.23 ms | 8.78 ms | 9.89 ms | 41.91 ms |
95
99
 
96
100
  (b) `yaml --json < manifests.yaml` (10.0 MB), 5 runs each:
97
101
 
98
- | Runtime | min | median | mean | max | MB/s (median) |
99
- | ---------- | --------- | --------- | --------- | --------- | ------------- |
100
- | Node.js | 3,916 ms | 4,226 ms | 4,137 ms | 4,301 ms | 2.37 |
101
- | TypeNative | 14,955 ms | 15,170 ms | 15,184 ms | 15,547 ms | 0.66 |
102
+ | Runtime | min | median | mean | max | MB/s (median) |
103
+ | ---------- | -------- | -------- | -------- | -------- | ------------- |
104
+ | Node.js | 807.92 ms | 851.20 ms | 844.81 ms | 869.64 ms | 11.75 |
105
+ | TypeNative | 741.86 ms | 753.61 ms | 751.74 ms | 760.93 ms | 13.27 |
102
106
 
103
- **Per call, TypeNative is 27x faster** (9 ms vs 250 ms, median). Node's
107
+ **Per call, TypeNative is 11.9x faster** (9 ms vs 105 ms, median). Node's
104
108
  cost here is mostly startup. It loads and type-strips the 78 TypeScript
105
109
  files on every run before it reads a byte of input. That's what you feel
106
110
  when a tool calls the converter once per file.
107
111
 
108
- **On bulk throughput, TypeNative is 3.6x slower.** Once V8's JIT has warmed
109
- up on a long input, it runs this code faster than the compiled Go does. The
110
- library passes its values around as structural object types and unions
111
- (`Scalar | YAMLMap | YAMLSeq | Pair`, CST tokens), which TypeNative holds as
112
- `interface{}`. Property reads and calls on them go through reflection, and a
113
- value handed to a parameter of a narrower object type is copied field by
114
- field. Garbage collection takes about a fifth of the native run. Both costs
115
- grow linearly with input size, while Node's head start is fixed, so the
116
- native binary finishes first up to about 150–200 KB of YAML per process:
112
+ **On bulk throughput the two are close** (754 ms vs 851 ms, median; 13.3 vs
113
+ 11.8 MB/s). Both runtimes take the split-and-workers path for this input, so
114
+ Node pays six worker startups while the native binary pays almost none; that
115
+ largely cancels the native single-process deficit in this benchmark. Without
116
+ the workers, the native process takes about 3.0 s for the same 10 MB (lex
117
+ 0.31 s, parse 0.91 s, compose 1.42 s, JSON 0.40 s) against Node's 1.3 s.
118
+ Once V8's JIT has warmed up, it runs this dynamic object-heavy code faster:
119
+ the library passes structural object types and unions (`Scalar | YAMLMap |
120
+ YAMLSeq | Pair`, CST tokens) that TypeNative holds as `interface{}`, so the
121
+ cost is spread across property reads, conversions and allocation. Garbage
122
+ collection runs on other cores and hardly affects the wall clock.
117
123
 
118
- | Input | Node.js | TypeNative |
119
- | ------ | ------- | ---------- |
120
- | 16 KB | 284 ms | 38 ms |
121
- | 64 KB | 311 ms | 107 ms |
122
- | 128 KB | 345 ms | 253 ms |
123
- | 1 MB | 862 ms | 1,599 ms |
124
-
125
- (Medians of 5 full process runs each, same generator.)
126
-
127
- Getting here fixed three performance bugs in TypeNative's runtime, all
128
- general:
124
+ Getting here fixed performance bugs in TypeNative's runtime, all general:
129
125
 
130
126
  - Long strings' code-point indexes were evicted by the many short slices a
131
127
  lexer takes, so every sticky-regex match rebuilt the index of the whole
132
- input. That made lexing quadratic: about 23 s for 1 MB before (measured on
133
- a loaded machine), about 1.5 s after.
134
- - Struct field lookups by name are cached per type.
128
+ input. That made lexing quadratic.
129
+ - Properties of objects held as any are read and written through plans cached
130
+ per type and key, with no lock, string hash or reflection on a hit. A read
131
+ that's consumed on the spot, such as a comparison, doesn't box the value.
132
+ - `obj.list.push(x)` on an object held as any appends in place. It used to
133
+ convert the whole array on every push, which made building a list quadratic.
134
+ - Single-value pushes grow the backing slice by 2x, not Go's 1.25x: building
135
+ the lexer's 3.2 million tokens copies the array out about five times over
136
+ otherwise. This alone cuts roughly 40 ms from lexing and 50 ms from compose.
137
+ - Conversions between object types are compiled once per pair of types; a
138
+ fresh local object converted once copies without an identity entry, and a
139
+ conversion between two statically known struct types is a struct literal.
140
+ Conversion identity holds one weak pointer per entry and sweeps dead ones
141
+ in batches.
142
+ - `Object.assign({ defaults }, typedSource)` sets fields directly instead of
143
+ reflecting over them, `obj[key] = v` on a plain object skips reflection,
144
+ and `s += chunk` for an untyped chunk appends in place.
145
+ - An optional call or chain whose value is only tested returns its primitive
146
+ directly instead of boxing it into a pointer first.
147
+ - `switch` on a value held as any compiles to a string switch when its cases
148
+ are string literals.
149
+ - Regexes run on a VM that works on byte offsets, so a sticky match on a 10 MB
150
+ input costs no more than one on a short string.
135
151
  - `typeof f` types are func types, so the composer's callbacks are called
136
152
  directly instead of through reflection.
@@ -10,20 +10,242 @@
10
10
  // yaml cst < in.yaml print the concrete syntax tree
11
11
  //
12
12
  // Runs as-is under Node.js (`node main.ts`) and compiles with TypeNative.
13
+ //
14
+ // One addition to bin.js: `yaml --json` on a large stream of documents
15
+ // converts runs of documents in parallel worker processes (see below). The
16
+ // output is the same JSON cli() prints, byte for byte.
17
+ import { promises } from 'node:fs';
18
+ import { availableParallelism, tmpdir } from 'node:os';
19
+ import { PassThrough } from 'node:stream';
20
+ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
13
21
  import { UserError, cli, help } from './vendor/yaml/src/cli.ts';
22
+ import { Composer } from './vendor/yaml/src/compose/composer.ts';
23
+ import type { Document } from './vendor/yaml/src/doc/Document.ts';
24
+ import { Pair } from './vendor/yaml/src/nodes/Pair.ts';
25
+ import { Scalar } from './vendor/yaml/src/nodes/Scalar.ts';
26
+ import { YAMLMap } from './vendor/yaml/src/nodes/YAMLMap.ts';
27
+ import { YAMLSeq } from './vendor/yaml/src/nodes/YAMLSeq.ts';
28
+ import { YAMLSet } from './vendor/yaml/src/nodes/YAMLSet.ts';
29
+ import { Parser } from './vendor/yaml/src/parse/parser.ts';
30
+
31
+ const { readFile, unlink, writeFile } = promises;
32
+
33
+ function done(error?: Error) {
34
+ if (error instanceof UserError) {
35
+ if (error.code === UserError.ARGS) console.error(`${help}\n`);
36
+ console.error(error.message);
37
+ process.exitCode = error.code;
38
+ } else if (error) {
39
+ // bin.js rethrows here; Node then prints the error and exits with 1
40
+ console.error(error);
41
+ process.exitCode = 1;
42
+ }
43
+ }
44
+
45
+ // `yaml --json` on a large stream is split before the `---` lines that start
46
+ // its documents, and up to six worker processes each compose one contiguous
47
+ // run of documents and print it as JSON; the main process joins the arrays.
48
+ // A `---` at the start of a line always ends the document before it (it ends
49
+ // any scalar or collection still open, or that one is an error), so each
50
+ // run's documents are the ones the whole stream has. Only plain streams take
51
+ // this path: no directives (% lines, which carry over to later documents) and
52
+ // no CR line endings. Any error, warning, collection-valued key (its warning
53
+ // is printed while the JSON is made) or exception in a worker sends the whole
54
+ // input through cli() instead, which reports it as it always would. A run
55
+ // travels in workerData; its JSON comes back through a temporary file (the
56
+ // worker IPC carries one compact message, not megabytes).
57
+ const PARALLEL_MIN_BYTES = 512 * 1024;
58
+
59
+ interface ConvertJob {
60
+ text: string;
61
+ output: string;
62
+ indent?: string;
63
+ }
14
64
 
15
- cli(
16
- process.stdin,
17
- (error) => {
18
- if (error instanceof UserError) {
19
- if (error.code === UserError.ARGS) console.error(`${help}\n`);
20
- console.error(error.message);
21
- process.exitCode = error.code;
22
- } else if (error) {
23
- // bin.js rethrows here; Node then prints the error and exits with 1
24
- console.error(error);
25
- process.exitCode = 1;
65
+ // The --indent value when the arguments are just --json (and --indent):
66
+ // undefined for none, null when the arguments ask for anything else
67
+ function jsonOnlyArgs(argv: string[]): { indent?: string } | null {
68
+ let json = false;
69
+ let indent: string | undefined;
70
+ for (let i = 0; i < argv.length; i++) {
71
+ const arg = argv[i];
72
+ if (arg === '--json' || arg === '-j') json = true;
73
+ else if ((arg === '--indent' || arg === '-i') && i + 1 < argv.length && !argv[i + 1].startsWith('-')) indent = argv[++i];
74
+ else if (arg.startsWith('--indent=')) indent = arg.slice('--indent='.length);
75
+ else return null;
76
+ }
77
+ return json ? { indent } : null;
78
+ }
79
+
80
+ function splitDocuments(data: string): string[] | undefined {
81
+ if (data.length < PARALLEL_MIN_BYTES || data.includes('\r')) return undefined;
82
+ if (data.startsWith('%') || data.includes('\n%')) return undefined;
83
+ const cuts: number[] = [0];
84
+ let at = data.indexOf('\n---');
85
+ while (at !== -1) {
86
+ const after = data.charCodeAt(at + 4);
87
+ // (`---` then a space, a tab, a newline or the end: a document start)
88
+ if (Number.isNaN(after) || after === 32 || after === 9 || after === 10) cuts.push(at + 1);
89
+ at = data.indexOf('\n---', at + 4);
90
+ }
91
+ if (cuts.length < 3) return undefined;
92
+ cuts.push(data.length);
93
+ const requested = Number(process.env.YAML_WORKERS ?? '0') || availableParallelism();
94
+ const count = Math.min(6, Math.max(1, requested), cuts.length - 1);
95
+ if (count < 2) return undefined;
96
+ // one contiguous run of documents per process, balanced by size
97
+ const parts: string[] = [];
98
+ let next = 1;
99
+ let start = 0;
100
+ for (let m = 1; m <= count; m++) {
101
+ const target = (data.length * m) / count;
102
+ while (next < cuts.length - 1 && cuts[next] < target) next++;
103
+ const end = m === count ? data.length : cuts[next];
104
+ if (end > start) parts.push(data.slice(start, end));
105
+ start = end;
106
+ }
107
+ return parts.length > 1 ? parts : undefined;
108
+ }
109
+
110
+ // Whether toJS could warn on this node: a map key that is not a scalar (an
111
+ // alias, a collection) is stringified with a warning. (A set: assumed so.)
112
+ function warnsOnKeys(node: unknown): boolean {
113
+ if (node instanceof Pair) {
114
+ return (node.key !== null && !(node.key instanceof Scalar)) || warnsOnKeys(node.value);
115
+ }
116
+ if (node instanceof YAMLMap) {
117
+ for (const pair of node.values.values()) if (warnsOnKeys(pair)) return true;
118
+ return false;
119
+ }
120
+ if (node instanceof YAMLSeq) {
121
+ for (const item of node) if (warnsOnKeys(item)) return true;
122
+ return false;
123
+ }
124
+ return node instanceof YAMLSet;
125
+ }
126
+
127
+ async function workerMain() {
128
+ const job = workerData as ConvertJob;
129
+ const text = job.text as string;
130
+ const output = job.output as string;
131
+ const indent = job.indent as string | undefined;
132
+ try {
133
+ // as cli() composes a stream: new Composer({ version: opt.yaml, merge: opt.merge })
134
+ const composer = new Composer({ version: '1.2', merge: undefined });
135
+ const parser = new Parser();
136
+ for (const tok of parser.parse(text)) composer.next(tok);
137
+ const docs: Document[] = [];
138
+ let clean = true;
139
+ for (const doc of composer.end(false)) {
140
+ if (doc.errors.length > 0 || doc.warnings.length > 0 || warnsOnKeys(doc.value)) clean = false;
141
+ docs.push(doc);
142
+ }
143
+ // (a run with no document must be all blank lines and comments: an error
144
+ // with no document to report it is otherwise lost)
145
+ if (docs.length === 0 && /^[ \t]*[^ \t\n#]/m.test(job.text)) clean = false;
146
+ if (clean) {
147
+ await writeFile(output, JSON.stringify(docs, null, Number(indent)));
148
+ parentPort!.postMessage('ok');
149
+ } else {
150
+ parentPort!.postMessage('fallback');
26
151
  }
27
- },
28
- process.argv.slice(2)
29
- );
152
+ } catch {
153
+ parentPort!.postMessage('fallback');
154
+ }
155
+ parentPort!.close();
156
+ }
157
+
158
+ // The JSON of each run's array, as the JSON of one array of all their items
159
+ function joinArrays(arrays: string[]): string {
160
+ const items: string[] = [];
161
+ let separator = ',';
162
+ for (const json of arrays) {
163
+ if (json === '[]') continue;
164
+ if (json.startsWith('[\n')) {
165
+ separator = ',\n';
166
+ items.push(json.slice(2, -2));
167
+ } else {
168
+ items.push(json.slice(1, -1));
169
+ }
170
+ }
171
+ if (items.length === 0) return '[]';
172
+ return separator === ',' ? '[' + items.join(',') + ']' : '[\n' + items.join(',\n') + '\n]';
173
+ }
174
+
175
+ // The runs converted in workers: their JSON, or '' when a worker found
176
+ // something cli() has to report
177
+ async function convertParallel(parts: string[], indent: string | undefined): Promise<string> {
178
+ const base = tmpdir() + '/yaml-' + process.pid + '-' + Date.now();
179
+ const results: string[] = await Promise.all(parts.map((text, index) => new Promise<string>((resolve, reject) => {
180
+ const output = base + '-' + index + '.json';
181
+ const job: ConvertJob = { text, output, indent };
182
+ try {
183
+ const worker = new Worker(new URL(import.meta.url), { workerData: job });
184
+ worker.on('message', async (message: string) => {
185
+ try {
186
+ if (message === 'ok') {
187
+ const json: string = await readFile(output, 'utf8');
188
+ await unlink(output).catch(() => {});
189
+ resolve(json);
190
+ } else {
191
+ resolve('');
192
+ }
193
+ } catch (err) {
194
+ reject(err);
195
+ }
196
+ worker.terminate();
197
+ });
198
+ worker.on('error', (err: Error) => {
199
+ unlink(output).catch(() => {});
200
+ reject(err);
201
+ });
202
+ } catch (err) {
203
+ reject(err);
204
+ }
205
+ })));
206
+ if (results.some((json) => json === '')) return '';
207
+ return joinArrays(results);
208
+ }
209
+
210
+ function readStdin(): Promise<string> {
211
+ return new Promise((resolve, reject) => {
212
+ let source = '';
213
+ process.stdin.setEncoding('utf-8');
214
+ process.stdin.on('data', (chunk: string) => {
215
+ source += chunk;
216
+ });
217
+ process.stdin.on('error', (err: Error) => reject(err));
218
+ process.stdin.on('end', () => resolve(source));
219
+ });
220
+ }
221
+
222
+ async function main() {
223
+ const argv = process.argv.slice(2);
224
+ const json = jsonOnlyArgs(argv);
225
+ if (!json) {
226
+ cli(process.stdin, done, argv);
227
+ return;
228
+ }
229
+ const source = await readStdin();
230
+ const parts = splitDocuments(source);
231
+ if (parts) {
232
+ const output = await convertParallel(parts, json.indent);
233
+ if (output !== '') {
234
+ // (flushed before the process exits: a pipe gets all of it)
235
+ await new Promise<void>((resolve) => {
236
+ process.stdout.write(output + '\n', () => resolve());
237
+ });
238
+ return;
239
+ }
240
+ }
241
+ // (the input read here, replayed to cli() as its stdin)
242
+ const replay = new PassThrough();
243
+ replay.end(source);
244
+ cli(replay, done, argv);
245
+ }
246
+
247
+ if (isMainThread) {
248
+ main();
249
+ } else {
250
+ workerMain();
251
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typenative",
3
- "version": "0.5.0",
3
+ "version": "0.6.1",
4
4
  "description": "Build native applications using Typescript.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,6 +19,7 @@
19
19
  "conformance": "node scripts/conformance.mjs",
20
20
  "conformance:parallel": "node scripts/conformance-parallel.mjs",
21
21
  "bootstrap:check": "node scripts/bootstrap-check.mjs",
22
+ "perf": "node scripts/performance.mjs",
22
23
  "test": "npm run conformance",
23
24
  "release": "npm publish"
24
25
  },
@@ -32,13 +33,15 @@
32
33
  "url": "https://github.com/danisss9/typenative/issues"
33
34
  },
34
35
  "homepage": "https://github.com/danisss9/typenative#readme",
36
+ "engines": {
37
+ "node": ">=26"
38
+ },
35
39
  "devDependencies": {
36
- "@types/inquirer": "^9.0.10",
37
- "@types/node": "^24.19.2",
38
- "rimraf": "^6.1.3"
40
+ "@types/node": "^26.6.6",
41
+ "rimraf": "^6.1.4"
39
42
  },
40
43
  "dependencies": {
41
- "inquirer": "^14.2.3",
44
+ "inquirer": "^14.2.5",
42
45
  "typescript": "^6.0.3"
43
46
  }
44
47
  }
@@ -0,0 +1,196 @@
1
+ # Performance probes
2
+
3
+ Micro-benchmarks for TypeNative's hot paths. [conformance/](../conformance/)
4
+ proves that a construct compiles correctly, and this folder measures how fast the
5
+ compiled code runs. Each probe is one small standalone TypeScript program that
6
+ exercises one construct (string `+=`, `Map` lookups, `switch` over a
7
+ discriminated union, `any` property access, …) and runs unchanged under Node.js
8
+ and as a TypeNative binary. A transpiler or runtime change can then be measured
9
+ on the exact path it touches, instead of only through whole programs like
10
+ [examples/marked-cli](../examples/marked-cli/) where no single hot spot stands
11
+ out.
12
+
13
+ ## Running
14
+
15
+ From a checkout, after `npm run build`:
16
+
17
+ ```sh
18
+ npm run perf # every probe, 7 interleaved runs each
19
+ node scripts/performance.mjs str # only probes whose name contains "str"
20
+ node scripts/performance.mjs map --runs 15 # more runs for a tighter median
21
+ node scripts/performance.mjs --write # also update the results table below
22
+ node scripts/performance.mjs --native # compile with the self-hosted binary
23
+ ```
24
+
25
+ The runner ([scripts/performance.mjs](../scripts/performance.mjs)) builds each
26
+ probe once with the TypeNative CLI. It then runs the probe under Node.js and as
27
+ the native binary, alternating which runtime goes first in each round. It
28
+ prints a markdown table of the in-program timings. A probe stops taking more
29
+ rounds once its native runs have used 15 s, so a pathological probe can't stall
30
+ the suite. Those rows show how many runs they got.
31
+
32
+ The runner fails (exit 1) only when a probe doesn't build, crashes, or prints a
33
+ different `checksum` under the two runtimes. A slow probe never fails it,
34
+ because slowness is the thing being measured.
35
+
36
+ `--write` replaces the rows of the probes that ran inside the results region
37
+ below, keeps the other rows, and refreshes the environment line. Run the full
38
+ suite on an idle machine before committing new numbers.
39
+
40
+ ## Writing a probe
41
+
42
+ A probe is `performance/<area>-<name>.ts`. Areas: `num`, `str`, `arr`, `map`,
43
+ `set`, `obj`, `class`, `union`, `any`, `fn`, `gen`, `regex`, `json`, `exc`,
44
+ `events`, `async`.
45
+
46
+ ```ts
47
+ // perf: one line saying what this measures (shown in the results table)
48
+ import { performance } from 'node:perf_hooks';
49
+
50
+ const input = /* build the input here, outside the timed region */;
51
+
52
+ const start = performance.now();
53
+ let total = 0;
54
+ /* the hot loop, folding its results into total */
55
+ const elapsed = performance.now() - start;
56
+
57
+ console.log(`checksum: ${total}`);
58
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
59
+ ```
60
+
61
+ - **Line 1** must be `// perf: <description>`. The table's "Measures" column
62
+ is read from it.
63
+ - **Time only the hot loop.** Process startup is excluded on purpose, because
64
+ [examples/hello-world](../examples/hello-world/) already measures that.
65
+ - **Derive the checksum from the work**, so neither compiler can drop the loop.
66
+ The runner compares the checksums, which also catches wrong results.
67
+ - **Size it for Node.js at roughly 100–500 ms.** Shorter runs are noisy. If
68
+ TypeNative takes many seconds on it, that is a finding: shrink the probe only
69
+ until a run takes a few seconds, and note it below.
70
+ - **Measure one thing.** Keep `%` out of hot loops: it compiles to Go's slow
71
+ `math.Mod` (see [findings](#findings)) and would swamp whatever the probe is
72
+ about. Use `i & 1023` and friends instead.
73
+ - Keep it standalone (no local imports), like the conformance probes.
74
+
75
+ ## Methodology and caveats
76
+
77
+ - Numbers are the program's own `performance.now()` timings, never spawn-to-exit
78
+ times. Speedups compare medians, and the minimums are listed too because they
79
+ are the most stable figure on a noisy machine.
80
+ - Background load skews results a lot. A self-hosted compile or a .NET build
81
+ running in the background cut both runtimes about 3x on the reference
82
+ machine. Interleaving the runtimes spreads drift across both, but it can't
83
+ remove load, so check that the machine is idle before trusting a run.
84
+ - Micro-benchmarks flatter JITs: V8 optimizes these tight loops with type
85
+ feedback that a large program rarely gets. Use the ratios here to rank hot
86
+ paths against each other and to track them over time. They are not a
87
+ prediction for whole programs; see [examples/](../examples/) for those.
88
+ - To find out *why* a probe (or any program) is slow, build it with `--profile`:
89
+ the binary writes a CPU profile to `$TYPENATIVE_CPUPROFILE` (default
90
+ `cpu.pprof`) when it exits. Read it with `go tool pprof -top -cum <exe> <profile>`.
91
+ For example, `node bin/cli.js --source performance/num-bitwise.ts --output bw.exe --profile`.
92
+ `--emit-go <dir>` shows the Go the profile's lines refer to.
93
+
94
+ ## Results
95
+
96
+ <!-- perf-results:start -->
97
+
98
+ Last run 2026-11-13 (only `gen-for-of` probes updated): Windows_NT 10.0.26300, AMD Ryzen 5 7600 6-Core Processor, Node v26.13.0, go1.27.4 windows/amd64, TypeNative 0.5.0, 15 interleaved runs per probe.
99
+
100
+ | Probe | Measures | Node ms (min / median) | TypeNative ms (min / median) | TypeNative vs Node (median) |
101
+ | ----- | -------- | ---------------------: | ---------------------------: | :-------------------------- |
102
+ | [any-dynamic](any-dynamic.ts) | property reads and writes on `any` objects (nested objects, arrays) | 51.8 / 53.3 | 2474 / 2501 (6 runs) | 46.9x slower |
103
+ | [any-record-view](any-record-view.ts) | viewing an `any` object as `Record<string, any>` and reading keys through it | 5.6 / 6.1 | 269 / 273 | 45.0x slower |
104
+ | [arr-hof](arr-hof.ts) | `map` / `filter` / `reduce` / `some` chains with closure callbacks | 89.8 / 91.6 | 26.9 / 27.7 | **3.3x faster** |
105
+ | [arr-push-index](arr-push-index.ts) | `push`, indexed reads/writes and `length` on number arrays | 52.5 / 54.3 | 55.0 / 55.7 | 1.0x slower |
106
+ | [arr-sort](arr-sort.ts) | `sort` of numbers with a comparator and of strings in default order | 125 / 127 | 347 / 354 | 2.8x slower |
107
+ | [async-await](async-await.ts) | `await` chains of async functions that resolve immediately | 99.5 / 104 | 201 / 206 | 2.0x slower |
108
+ | [class-dispatch](class-dispatch.ts) | virtual method calls through an abstract base class and an interface | 68.6 / 71.7 | 124 / 127 | 1.8x slower |
109
+ | [events-emit](events-emit.ts) | `EventEmitter` `emit` to listeners taking 0, 1 and 2 arguments | 73.6 / 73.9 | 655 / 658 | 8.9x slower |
110
+ | [exc-throw-rare](exc-throw-rare.ts) | `try`/`catch`/`finally` in a hot loop where nothing throws | 204 / 205 | 241 / 242 | 1.2x slower |
111
+ | [exc-try-catch](exc-try-catch.ts) | `try`/`catch`/`finally` in a hot loop where one call in 1,024 throws | 24.7 / 24.9 | 60.8 / 61.1 | 2.5x slower |
112
+ | [fn-closures](fn-closures.ts) | creating closures over mutable state and calling them indirectly | 144 / 145 | 58.6 / 60.0 | **2.4x faster** |
113
+ | [fn-recursion-tree](fn-recursion-tree.ts) | building and walking binary trees (recursion plus allocation) | 101 / 103 | 149 / 152 | 1.5x slower |
114
+ | [gen-for-of](gen-for-of.ts) | sync generators (a method, `*[Symbol.iterator]()`, `yield*`) consumed by `for…of` | 52.5 / 53.6 | 11.6 / 12.2 | **4.4x faster** |
115
+ | [json-roundtrip](json-roundtrip.ts) | `JSON.stringify` and `JSON.parse` of an array of nested objects | 38.5 / 39.9 | 96.9 / 99.5 | 2.5x slower |
116
+ | [map-delete](map-delete.ts) | `Map<string, number>` insert/delete churn (an LRU-style sliding window) | 29.3 / 36.0 | 165 / 167 | 4.6x slower |
117
+ | [map-string-keys](map-string-keys.ts) | `Map<string, number>` `set` / `get` / `has` word counting | 92.3 / 93.5 | 118 / 119 | 1.3x slower |
118
+ | [num-arith-loop](num-arith-loop.ts) | tight float64 loop with `%`, `*` and `Math.floor` | 76.5 / 77.4 | 159 / 162 | 2.1x slower |
119
+ | [num-bitwise](num-bitwise.ts) | bitwise and, or, xor and shifts (`<<`, `>>`, `>>>`) on integers, and flag tests | 21.6 / 22.3 | 114 / 116 | 5.2x slower |
120
+ | [num-mod-int](num-mod-int.ts) | `%` on integer operands (hash buckets, cycling indexes) | 62.5 / 63.8 | 187 / 191 | 3.0x slower |
121
+ | [num-to-string](num-to-string.ts) | number/string conversion: `String(n)`, `toFixed`, `Number(str)`, `parseInt` | 102 / 105 | 402 / 416 | 4.0x slower |
122
+ | [obj-alloc](obj-alloc.ts) | allocating many short-lived object literals and class instances | 62.5 / 63.4 | 187 / 191 | 3.0x slower |
123
+ | [regex-exec](regex-exec.ts) | regex `test`, `exec` with groups and global `replace` over log lines | 67.9 / 69.5 | 105 / 107 | 1.5x slower |
124
+ | [regex-site](regex-site.ts) | `/g` regex literals evaluated inside a hot function, and `.index` on long input | 78.2 / 83.8 | 159 / 168 | 2.0x slower |
125
+ | [set-ops](set-ops.ts) | `Set<number>` `add` / `has` / `delete` on a 16,384-entry set | 38.6 / 39.5 | 95.5 / 97.0 | 2.5x slower |
126
+ | [str-char-scan](str-char-scan.ts) | lexer-style scan of a large string with `charCodeAt` and `str[i]` | 79.8 / 81.0 | 326 / 327 | 4.0x slower |
127
+ | [str-concat](str-concat.ts) | growing ~20 KB strings with `s += x` and `s = s + …` (each pass starts empty) | 10.1 / 10.6 | 25.5 / 26.4 | 2.5x slower |
128
+ | [str-concat-plus](str-concat-plus.ts) | growing strings with `s = s + x` (not `+=`), each pass starting empty | 30.5 / 31.8 | 97.1 / 101 | 3.2x slower |
129
+ | [str-short-scan](str-short-scan.ts) | `charCodeAt(i)` / `s[i]` scans of many short (< 512 byte) lines | 30.8 / 31.1 | 195 / 196 | 6.3x slower |
130
+ | [str-split-join](str-split-join.ts) | `split`, `join`, `indexOf`, `slice` and `trim` on CSV-like lines | 56.0 / 57.2 | 40.5 / 40.8 | **1.4x faster** |
131
+ | [str-template](str-template.ts) | template literals mixing strings, integers, floats and booleans | 53.5 / 54.7 | 84.1 / 84.6 | 1.5x slower |
132
+ | [union-switch](union-switch.ts) | evaluating an expression tree of a discriminated union with `switch (e.kind)` | 120 / 125 | 488 / 495 | 4.0x slower |
133
+
134
+ <!-- perf-results:end -->
135
+
136
+ ## Findings
137
+
138
+ Causes behind the worst rows. Each one is checked against the generated Go
139
+ (`--emit-go`), a `--profile` CPU profile, or the runtime source in
140
+ [src/transpiler.ts](../src/transpiler.ts). Update this section when a fix
141
+ lands or a new cause is confirmed. Before/after figures are native medians on
142
+ the reference machine.
143
+
144
+ ### Fixed
145
+
146
+ | Probe | Cause | Fix | Before → after |
147
+ | ----- | ----- | --- | -------------- |
148
+ | `num-bitwise` (and every probe that uses `&`) | Every bitwise operand went through `TnInt32`, which called `math.Mod(f, 2^32)`: about 90% of the probe's time. | `TnInt32` converts in-range values directly and falls back to `math.Mod` only past ±2^63. Literal operands fold at compile time, and nested bitwise expressions stay `int32` between operators. | 2160 → 129 ms |
149
+ | `num-arith-loop`, `num-mod-int` | `a % b` compiled to `math.Mod`, whose cost grows with the exponent gap between the operands (about 150 ns for `2e8 % 13`). | `TnMod`: an `int64` remainder when both operands are integers that fit, keeping a `-0` result; `math.Mod` otherwise. | 4527 → 162 ms; 2827 → 188 ms |
150
+ | `gen-for-of` | A generator ran as a goroutine sending on a channel, in lockstep with the loop: two goroutine hand-offs and two `sync.Map` lookups per value. | A sync generator also compiles to a push form, `name__seq(args)`: a Go range function whose `yield` runs the loop body. `for…of` over a direct generator call (or a class's `*[Symbol.iterator]()`) uses it. A break unwinds the generator through its `finally` blocks, and a throw from the loop body passes its `catch` clauses, as in JS. `.next()`, spread and stored generators keep the channel form. | 1843 → 12 ms |
151
+ | `set-ops`, `map-delete` | `TnMap.Delete` scanned and spliced the insertion-order key slice, so each delete was O(size). Every `Get`/`Has`/`Set` also called `reflect.TypeFor[K]().Kind()`. | Deletes mark the key's slot dead in O(1) (an index map built on the first delete of a map past 16 keys) and dead slots are compacted before keys are read. The key-kind check is made once per map. | 1556 → 97 ms; 367 → 167 ms |
152
+ | `any-record-view` | Viewing an `any` object as `Record<string, any>` rebuilt it through reflection on every conversion. | `TnRecordOf` wraps the object's own map in a `TnMap` (writes through the record reach the object, as in JS). | 1696 → 273 ms |
153
+ | `str-concat`, `str-concat-plus` | `s = s + a + b` compiled to Go string concatenation, which copies all of `s`: O(n²) for a growing string. `TnStrAppend` also locked with `defer`. | `s = s + …` on a string variable or field (the target as the leftmost operand) compiles to `TnStrAppend`, like `s += …`, and the lock no longer uses `defer`. | 51.5 → 26.4 ms; 3365 → 101 ms |
154
+ | `str-short-scan` | For strings under 512 bytes, `charCodeAt(i)` rescanned `s[:i+1]` for ASCII and `s.length` rescanned all of `s`, so walking a line was O(n²). | The ASCII answer for the last short string asked about is remembered (the entry holds the string). Indexes under 64 still scan their few bytes. | 300 → 196 ms |
155
+ | `any-dynamic` | Reads of `any` objects missed the field-plan table and went through accessor and reflect checks before reaching the map. Writes boxed every value through `reflect.ValueOf`. | `TnGetRef`/`TnGetPeek` read a `map[string]interface{}` first. `tnBoxArray` returns scalars and maps without reflect. | 3812 → 2501 ms |
156
+ | `num-to-string` | `toFixed` formatted 1100 digits on every call to round exactly. | `strconv` already rounds to nearest. Only a value exactly on a tie (its last binary fraction digit at 2^-(d+1)) takes the exact path. | 667 → 416 ms |
157
+ | `events-emit` | `TnInvoke` called every listener through `reflect.Value.Call`. `emit` copied the listener list and built a `kept` list on every call. | Typed fast paths for `func()`, `func(any)`, `func(any, any)`, `func(...any)`, `func(float64)` and `func(string)`. `emit` uses the copy-on-write listener slice as its snapshot. | 1372 → 658 ms |
158
+ | `regex-site` | Each evaluation of a regex literal looked its compiled program up again (key concatenation and a mutex). | One package-level `TnRegexSite` per literal shares the program and RE2 fallbacks. Each evaluation is still a new `RegExp` with its own `lastIndex`. | 177 → 168 ms |
159
+ | `gen-for-of` (examples) | Generators called through dynamic dispatch (`unit.ops()` on an abstract `CompilationUnit`, 26 phases of angular-templates) still ran as goroutines, and `for…of` over them collected every value first; spread and `Array.from` of a generator received through reflect. | `TnCallSeq_<m>[T]` dispatches a generator method on a dynamic receiver to the class's push form (its channel in lockstep for a generator without one, any other value's elements otherwise), for `for…of`, `yield*` and `super.m()`. A spread or `Array.from` of a generator call collects its push form into a typed slice (`TnGeneratorItems`). | angular-templates at 64 KB: 721 → 601 ms |
160
+ | `gen-for-of` (examples) | `Array.from` / spread over a class iterator reached through a dynamic field (`op.handlerOps`, `op.trackByOps` in angular-templates) found `*[Symbol.iterator]()` with `reflect.MethodByName`, called it, and drained its channel on a goroutine: one reflective call and two goroutine hand-offs per operation list. | `TnToArray` asserts the class's push form directly (`Symbol_iterator__seq`, a `func(func(T) bool)`) and iterates it in place; an interface-yield channel method gets its own type assertion too, without reflection. | angular-templates at 64 KB: 601 → 305 ms |
161
+ | `class-dispatch` | A call on an abstract base class or an interface went through `TnCall_<m>(recv, args ...interface{})`: arguments and the result boxed, then unboxed with `TnAs`. | When every class of the receiver's declared hierarchy declares the method with the same Go signature, the call goes through `TnCall_<C>_<m>(recv, a P0, …) R`: a type switch calling the method with its own types, the boxed dispatcher only for any other receiver. The call's inferred type is `R`, so the value isn't boxed again where it's used. | 709 → 124 ms |
162
+ | `async-await` | Each async call started a goroutine and handed the JS baton over twice, and each settle allocated two wake-up channels even with nobody waiting. | An async function that awaits only calls of other such functions (whose promises are settled when they return), with no `for await` and no promise returned, runs on the caller's goroutine (`TnRunAsyncInline`). `TnAsyncSend` / `TnAsyncClose` allocate a wake-up channel only for a parked awaiter. | 1985 → 201 ms |
163
+ | `json-roundtrip` | `JSON.parse` built a `TnMap` per object from `encoding/json` tokens, then `as Item[]` converted every map to a struct through `TnConvertDynamic`. | `JSON.parse(text)` into a typed slot is `TnJSONParseTyped[T]`: a scanner decodes the text straight into `T` (per-type plans over field offsets) when every object has `T`'s keys in its field order and every value its kind; anything else (other keys, null, any fields, invalid text) decodes and converts as before. | 347 → 97 ms |
164
+ | `num-bitwise` | Loop counters and flag locals were `float64`, so every bitwise operand converted float64 to int32 through `TnInt32`. | A `for` loop's `let` counter (an integer literal start, `++` / `--`, never written in the body) is a Go `int`, and a block `const` holding a bitwise result an `int32`, when every read is an arithmetic, comparison, bitwise, index or template operand: reads are `float64(i)`, bitwise operands take the integer directly. | 128 → 114 ms |
165
+
166
+ ### Open
167
+
168
+ | Probe | Cause | Status |
169
+ | ----- | ----- | ------ |
170
+ | `any-dynamic` | What remains is the representation: an `any` object is a Go `map[string]interface{}`, so every property access hashes its key (`memHashAES` and map lookups are about 45%), where V8 reads a slot through a hidden class. | open |
171
+ | `events-emit` | Listener shapes other than the fast paths (here `(a: number, b: string)`) still go through `reflect.Value.Call` (about a third), and each `emit` hashes the event name. | open |
172
+ | `str-short-scan`, `str-char-scan` | Indexes under 64 still rescan their prefix for ASCII (`tnStrIsASCII` is 40% of `str-short-scan`). A loop over `s.charCodeAt(i)` could test `s` once before the loop. | open |
173
+ | `num-mod-int`, `num-bitwise` | Integer loop counters are Go `int`s now, but `%` still runs on `float64` (`TnMod` converts both operands and checks them, then divides with `idiv`), and other integral locals (`k = (k + i) % 97`, module constants such as `F_A = 1 << 0`) stay `float64`. A `TnMod` by a constant divisor would let Go multiply instead of divide, but any fallback call puts the helper over Go's inlining budget; it would have to be emitted inline. | open |
174
+
175
+ Bugs found while writing the probes (not performance, not fixed here):
176
+ `'x' + null` and `'x' + undefined` render `<nil>`, and a `-0` concatenated
177
+ into a string renders `-0e+0` (JS gives `null`, `undefined` and `0`); a
178
+ subclass of a class with `*[Symbol.iterator]()` can't be iterated (the
179
+ generator isn't copied into it); and examples/marked-cli's parity run fails
180
+ 69 `--tokens` cases at this commit and before (a `def` token's unmatched
181
+ `title` group prints `""` where Node omits `undefined`).
182
+
183
+ Found while pinning the fixes above (also before them, not fixed here): an
184
+ `await` of a promise that is already settled resumes on the spot, so in
185
+ `const p = f(); log('x')` the part of `f` after its first `await` runs
186
+ before `x` (JS runs it after); a `for…of` over an array doesn't see elements
187
+ pushed during the loop; a class method returning `null` (`next(): Base |
188
+ null`) and a typed field read from JSON `null` compare `=== null` as
189
+ `undefined`, and `await` of a `Promise<void>` gives `{}`; an object literal
190
+ typed as an interface, called through a dynamic receiver, throws `area is
191
+ not a function`; a class whose arrow-function field implements an interface
192
+ method, and `[...shapes]` of a `Base[]` into a `Shape[]`, don't compile;
193
+ `.length` counts a character outside the BMP once (JS counts two UTF-16
194
+ units); `JSON.parse` of a number past the float range (`1e400`) throws
195
+ where JS gives `Infinity`; and a JSON object whose keys come in another
196
+ order than its type's fields loses that order once converted to the type.