nish 0.44.0 → 0.46.0

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 (119) hide show
  1. package/README.md +1 -1
  2. package/docs/AI.md +18 -16
  3. package/docs/INSTALL.md +3 -1
  4. package/package.json +5 -5
  5. package/runtime/core/numbers.mjs +3 -1
  6. package/runtime/core/strings.mjs +90 -38
  7. package/runtime/core.d.ts +8 -0
  8. package/runtime/core.mjs +16 -0
  9. package/runtime/nish.d.ts +88 -5
  10. package/runtime/nish.h +10 -0
  11. package/runtime/nish.mjs +5 -0
  12. package/runtime/runtime-host.c +15 -0
  13. package/runtime/runtime-net.c +223 -4
  14. package/runtime/runtime-os.c +15 -1
  15. package/runtime/runtime-uring.c +291 -31
  16. package/runtime/sqlite/nish-sqlite.c +301 -128
  17. package/std/README.md +15 -15
  18. package/std/array.ts +10 -2
  19. package/std/bytes.ts +239 -26
  20. package/std/cli-args.ts +1072 -606
  21. package/std/cli-flags.ts +180 -98
  22. package/std/cli.ts +21 -13
  23. package/std/collections.ts +245 -127
  24. package/std/compress/checksum.ts +32 -37
  25. package/std/compress/deflate.ts +1102 -542
  26. package/std/compress/gzip.ts +290 -145
  27. package/std/compress/zlib.ts +57 -21
  28. package/std/crypto/aes.ts +153 -75
  29. package/std/crypto/base64url.ts +84 -61
  30. package/std/crypto/bcrypt-batch.ts +164 -90
  31. package/std/crypto/bcrypt.ts +185 -107
  32. package/std/crypto/chacha20poly1305.ts +84 -68
  33. package/std/crypto/ct.ts +9 -7
  34. package/std/crypto/ed25519.ts +64 -27
  35. package/std/crypto/hkdf.ts +105 -63
  36. package/std/crypto/hmac.ts +95 -89
  37. package/std/crypto/jwt.ts +248 -126
  38. package/std/crypto/p256.ts +758 -444
  39. package/std/crypto/p384.ts +20 -13
  40. package/std/crypto/pki-roots.ts +95 -38
  41. package/std/crypto/pki.ts +164 -60
  42. package/std/crypto/rsa.ts +266 -223
  43. package/std/crypto/scram.ts +3 -4
  44. package/std/crypto/sha1.ts +107 -65
  45. package/std/crypto/sha256.ts +502 -422
  46. package/std/crypto/sha512.ts +204 -135
  47. package/std/crypto/x509-random.ts +9 -3
  48. package/std/crypto/x509.ts +331 -171
  49. package/std/json-equal.ts +35 -19
  50. package/std/json-format.ts +215 -108
  51. package/std/json-number.ts +126 -72
  52. package/std/json-pointer.ts +42 -13
  53. package/std/json-tokenizer.ts +498 -307
  54. package/std/json-typed.ts +115 -36
  55. package/std/json-value.ts +341 -152
  56. package/std/json.ts +300 -158
  57. package/std/net/buffer-pool.ts +17 -7
  58. package/std/net/dns-config.ts +427 -236
  59. package/std/net/dns-message.ts +114 -47
  60. package/std/net/dns-resolver.ts +736 -237
  61. package/std/net/dns.ts +205 -52
  62. package/std/net/fetch.ts +320 -184
  63. package/std/net/grpc.ts +948 -0
  64. package/std/net/handler.ts +1315 -222
  65. package/std/net/hpack.ts +395 -180
  66. package/std/net/http-compress.ts +502 -65
  67. package/std/net/http-fields.ts +85 -49
  68. package/std/net/http-server.ts +1764 -602
  69. package/std/net/http1-client-codec.ts +372 -161
  70. package/std/net/http1-codec.ts +665 -331
  71. package/std/net/http1-server.ts +660 -278
  72. package/std/net/http2-cleartext.ts +165 -95
  73. package/std/net/http2-frame.ts +232 -89
  74. package/std/net/http2-tls.ts +42 -12
  75. package/std/net/http2.ts +327 -101
  76. package/std/net/http3-frame.ts +68 -33
  77. package/std/net/http3-server.ts +647 -192
  78. package/std/net/http3.ts +667 -189
  79. package/std/net/oidc.ts +63 -24
  80. package/std/net/outbound.ts +207 -142
  81. package/std/net/postgres-async.ts +1165 -443
  82. package/std/net/postgres-carrier.ts +575 -372
  83. package/std/net/postgres.ts +1459 -559
  84. package/std/net/prefork.ts +254 -98
  85. package/std/net/protobuf.ts +1017 -0
  86. package/std/net/qpack.ts +143 -92
  87. package/std/net/quic-conn-ack.ts +50 -18
  88. package/std/net/quic-conn-cid.ts +66 -26
  89. package/std/net/quic-conn-params.ts +13 -7
  90. package/std/net/quic-datagram.ts +90 -27
  91. package/std/net/quic-frame.ts +225 -124
  92. package/std/net/quic-listener.ts +197 -89
  93. package/std/net/quic-packet.ts +289 -163
  94. package/std/net/quic-recovery.ts +279 -128
  95. package/std/net/quic-stream.ts +466 -167
  96. package/std/net/quic.ts +568 -257
  97. package/std/net/router.ts +450 -99
  98. package/std/net/serve.ts +651 -232
  99. package/std/net/static.ts +1458 -0
  100. package/std/net/tls/client.ts +140 -45
  101. package/std/net/tls/codec.ts +510 -260
  102. package/std/net/tls/record-client.ts +268 -76
  103. package/std/net/tls/record-server.ts +236 -79
  104. package/std/net/tls/record.ts +173 -47
  105. package/std/net/tls/schedule.ts +58 -39
  106. package/std/net/tls/ticket.ts +295 -103
  107. package/std/net/tls/verify.ts +1 -1
  108. package/std/net/tls-tcp.ts +218 -75
  109. package/std/net/tls.ts +260 -152
  110. package/std/net/upstream.ts +283 -86
  111. package/std/net/url.ts +277 -102
  112. package/std/net/websocket.ts +370 -186
  113. package/std/net/webtransport.ts +755 -436
  114. package/std/regex.ts +1659 -829
  115. package/std/sqlite.ts +171 -0
  116. package/std/sync/ring.ts +320 -156
  117. package/std/sync/shm.ts +53 -6
  118. package/std/text.ts +205 -124
  119. package/std/threads.ts +22 -2
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  ![TypeScript](https://img.shields.io/badge/TypeScript-static%20subset-3178c6?style=flat-square&logo=typescript&logoColor=white)
12
12
  ![LLVM](https://img.shields.io/badge/LLVM-18-4b5563?style=flat-square&logo=llvm&logoColor=white)
13
13
  ![WebAssembly](https://img.shields.io/badge/wasm-wasm32%20%C2%B7%20wasi-654ff0?style=flat-square&logo=webassembly&logoColor=white)
14
- ![vibe coded](https://img.shields.io/badge/vibe-coded-a855f7?style=flat-square)
14
+ ![built with Claude](https://img.shields.io/badge/built%20with-Claude-D97757?style=flat-square&logo=claude&logoColor=white)
15
15
 
16
16
  **[nishlang.com](https://nishlang.com/)** · [Get started](https://nishlang.com/getting-started/installation) · [Language reference](https://nishlang.com/reference/language) · [Changelog](https://nishlang.com/reference/changelog)
17
17
 
package/docs/AI.md CHANGED
@@ -130,13 +130,11 @@ are one node per line, which is to say diffable.
130
130
 
131
131
  ## A whole program
132
132
 
133
- This program divides by a value it does not test, so it builds with
134
- `--allow-panics` ([Proving it cannot panic](#proving-it-cannot-panic)); a
135
- guard that the divisor is not zero would let it build under the default. Other
136
- examples below that do integer arithmetic nothing bounds build the same way.
133
+ This program builds under the default: its `%` sits behind the loop's
134
+ `y > 0` test ([Proving it cannot panic](#proving-it-cannot-panic)). Examples
135
+ below that do integer arithmetic nothing bounds build with `--allow-panics`.
137
136
 
138
- <!-- allow-panics: divides by a value it does not test -->
139
- <!-- nish:ok --allow-panics -->
137
+ <!-- nish:ok -->
140
138
  ```ts
141
139
  const gcd = (a: i32, b: i32): i32 => {
142
140
  let x = a;
@@ -2568,6 +2566,10 @@ barrier, so neither ever becomes a branch; select and compare on a secret with
2568
2566
  these, never with `if`, `?:`, `===` or `table[secret]`, which they cannot fix.
2569
2567
  `secureZero(bytes)` sets every byte of a `u8[]` to zero in stores the optimiser
2570
2568
  may not drop, as a statement: how a key in a plain array is cleared once used.
2569
+ `mulHigh(a, b)` is the high 64 bits of the 128-bit product of two `u64`s
2570
+ (with `a * b` for the low half, the whole product), one multiply on x86-64 and
2571
+ AArch64 and four 32 × 32 products on wasm32, neither branching on an operand;
2572
+ `mulHighIsNative()` is `true` where it is one instruction.
2571
2573
 
2572
2574
  **Secrets.** Hold a key as a `Secret<T>` from `nish:secret` (`T` an integer
2573
2575
  array or a record of integer fields). It is opaque: no printing, interpolating,
@@ -2904,8 +2906,7 @@ was there) and `clear()`, and `keys()` / `values()` as the iterable of a
2904
2906
  and `s.forEach((x) => ...)` compile to that `for...of` walk with `f` inlined,
2905
2907
  and answer `void`. `entries` is refused by name.
2906
2908
 
2907
- <!-- allow-panics: calls `std/collections.ts` code that keeps panic sites no proof removes yet -->
2908
- <!-- nish:ok-body --allow-panics -->
2909
+ <!-- nish:ok-body -->
2909
2910
  ```ts
2910
2911
  const seen = new Set<string>();
2911
2912
  const counts: Map<string, i32> = new Map();
@@ -2932,7 +2933,7 @@ console.log(`${seen.size} ${counts.size} ${seen.has("b")}`);
2932
2933
  three ways: a default with `??`, a `const` tested with `!== undefined` (or
2933
2934
  `=== undefined` and an early `return`), or a bare test. Each is one probe.
2934
2935
 
2935
- <!-- allow-panics: does integer arithmetic nothing bounds; calls `std/collections.ts` code that keeps panic sites no proof removes yet -->
2936
+ <!-- allow-panics: does integer arithmetic nothing bounds -->
2936
2937
  <!-- nish:ok-body --allow-panics -->
2937
2938
  ```ts
2938
2939
  const counts = new Map<string, i32>();
@@ -2966,7 +2967,7 @@ may `set`, `delete` or `clear` the table inside the walk and get exactly what
2966
2967
  JavaScript gives (a new key is visited later in the same walk; a key deleted
2967
2968
  before it is reached is not).
2968
2969
 
2969
- <!-- allow-panics: does integer arithmetic nothing bounds; calls `std/collections.ts` code that keeps panic sites no proof removes yet -->
2970
+ <!-- allow-panics: does integer arithmetic nothing bounds -->
2970
2971
  <!-- nish:ok-body --allow-panics -->
2971
2972
  ```ts
2972
2973
  const ages = new Map<string, i32>();
@@ -3007,7 +3008,7 @@ string `+`) or assign. Anything else still compiles, as one probe per call.
3007
3008
  inserting it — and `reserve(m, n)`, which sizes the table for `n` entries; both
3008
3009
  are one module with the program and run unchanged under Node.
3009
3010
 
3010
- <!-- allow-panics: does integer arithmetic nothing bounds; calls `std/collections.ts` code that keeps panic sites no proof removes yet -->
3011
+ <!-- allow-panics: does integer arithmetic nothing bounds -->
3011
3012
  <!-- nish:ok --allow-panics -->
3012
3013
  ```ts
3013
3014
  import { getOrInsert, reserve } from "nish/map";
@@ -3072,7 +3073,7 @@ tag under one key (NL2721) as a different string (NL2720). A `tag` on a class
3072
3073
  no union holds does nothing, and a JSON call on that class refuses its
3073
3074
  enum-member field.
3074
3075
 
3075
- <!-- allow-panics: builds an array whose length it does not bound; indexes an array without a guard the checker reads; calls `std/json.ts` code that keeps panic sites no proof removes yet -->
3076
+ <!-- allow-panics: builds an array whose length it does not bound; indexes an array without a guard the checker reads; calls `std/json-typed.ts` code that keeps panic sites no proof removes yet -->
3076
3077
  <!-- nish:ok --allow-panics -->
3077
3078
  ```ts
3078
3079
  import { JsonWriter } from "nish/json";
@@ -3114,7 +3115,7 @@ export const main = (): i32 => {
3114
3115
  };
3115
3116
  ```
3116
3117
 
3117
- <!-- allow-panics: indexes an array without a guard the checker reads; calls `std/json.ts` code that keeps panic sites no proof removes yet -->
3118
+ <!-- allow-panics: indexes an array without a guard the checker reads; calls `std/json-typed.ts` code that keeps panic sites no proof removes yet -->
3118
3119
  <!-- nish:ok --allow-panics -->
3119
3120
  ```ts
3120
3121
  import { JsonWriter } from "nish/json";
@@ -3325,8 +3326,8 @@ you need to walk them, since there is no iteration yet.
3325
3326
  **Find the next byte of a few** — `indexOfAny(text, bytes, from)` from
3326
3327
  `nish/text` answers the first index at or after `from` whose byte is one of
3327
3328
  `bytes`, or -1: the scan for the next `"` or `\\` in a JSON string, the next
3328
- delimiter in a line. `bytes` holds 1 to 16 ASCII bytes and anything else
3329
- panics; `from` is clamped to `[0, text.length]`. Natively it reads 16 or 32
3329
+ delimiter in a line. `bytes` is any set, and an ASCII one answers the same
3330
+ natively and under Node; `from` is clamped to `[0, text.length]`. Natively it reads 16 or 32
3330
3331
  bytes at a time, so prefer it to a `charCodeAt` loop over a long text — and
3331
3332
  never call it on secret data, because its time says where the match is.
3332
3333
  (No block: a program importing `nish/text` writes two `.ll` files;
@@ -3338,7 +3339,8 @@ methods on a number and no optional parameters, so `x.toFixed(n)` is
3338
3339
  both from `nish/text` and both answering what JavaScript does. `toFixed`
3339
3340
  rounds the exact binary value (`toFixed(1.005, 2)` is `"1.00"`) and panics
3340
3341
  outside 0 to 100 digits; `splitLimit` keeps the first `limit` pieces, a
3341
- negative limit keeps all of them, and an empty separator panics.
3342
+ negative limit keeps all of them, and an empty separator splits into code
3343
+ points.
3342
3344
  (No block, as for `nish/text`; `tests/link/std_text_to_fixed` and
3343
3345
  `tests/link/std_text_split_limit` are its programs.)
3344
3346
 
package/docs/INSTALL.md CHANGED
@@ -194,7 +194,9 @@ The attestation is a Sigstore-signed statement, made by
194
194
  `SHA256SUMS` was built by `.github/workflows/release.yml` at the release's tag
195
195
  on a GitHub-hosted runner. A failed verification refuses the install; with no
196
196
  `gh`, a signed-out one or one too old for those options, the check is skipped
197
- with a note saying so, and the SHA-256 still applies. Set
197
+ with a note saying so, and the SHA-256 still applies. A `gh` that has a token
198
+ but whose `gh auth status` fails (it asks GitHub's API) is tried three times,
199
+ a second or two apart, before it counts as unusable, and the note quotes it. Set
198
200
  `NISH_REQUIRE_ATTESTATION=1` to refuse instead of skipping: the install then
199
201
  fails unless `gh` verifies the attestation, and refuses a release of 0.21.0 or
200
202
  older, which carries none. The same command by hand, on a tarball you
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nish",
3
- "version": "0.44.0",
3
+ "version": "0.46.0",
4
4
  "description": "Nish: an ahead-of-time compiler from a static subset of TypeScript to LLVM IR",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -114,9 +114,9 @@
114
114
  "typescript": "^5.6.0"
115
115
  },
116
116
  "optionalDependencies": {
117
- "@amritk/nish-aarch64-darwin": "0.44.0",
118
- "@amritk/nish-aarch64-linux": "0.44.0",
119
- "@amritk/nish-x86_64-darwin": "0.44.0",
120
- "@amritk/nish-x86_64-linux": "0.44.0"
117
+ "@amritk/nish-aarch64-darwin": "0.46.0",
118
+ "@amritk/nish-aarch64-linux": "0.46.0",
119
+ "@amritk/nish-x86_64-darwin": "0.46.0",
120
+ "@amritk/nish-x86_64-linux": "0.46.0"
121
121
  }
122
122
  }
@@ -250,7 +250,9 @@ export function convert(x, from, to) {
250
250
  // The hot paths of u64 arithmetic written over i64 (`toU64(a) * toU64(b)`)
251
251
  // stay in a function small enough for V8 to inline at the call: the two
252
252
  // 64-bit kinds reinterpret each other's bits, and a zext of an unsigned
253
- // 32-bit-or-narrower value to u64 keeps the value as it is.
253
+ // 32-bit-or-narrower value to u64 keeps the value as it is. Keep it this
254
+ // small: answering the integer `number` cases here, inline or through a
255
+ // helper, made ct_asm_x25519 under --emit-ts 1.1x to 1.8x slower.
254
256
  if (typeof x === "bigint") {
255
257
  if (to === "u64") return BigInt.asUintN(64, x);
256
258
  if (to === "i64") return BigInt.asIntN(64, x);
@@ -11,31 +11,65 @@ import { panicIndex, panicSlice, toIndex } from "./checks.mjs";
11
11
  const ENCODER = new TextEncoder();
12
12
  const DECODER = new TextDecoder("utf-8", { ignoreBOM: true });
13
13
 
14
- /** The string `bytesOf` encoded last, and its bytes. */
15
- let lastString = "";
16
- let lastBytes = new Uint8Array(0);
14
+ /** A UTF-16 unit that is not ASCII, so its UTF-8 bytes are not its units. */
15
+ const NON_ASCII = /[^\x00-\x7f]/;
17
16
 
18
17
  /**
19
- * The UTF-8 bytes of `s`, which is what an Nish string holds. The last string
20
- * encoded is kept with its bytes, so a loop of `s.charCodeAt(i)` over one
21
- * string encodes it once rather than once per byte. Nothing here writes to
18
+ * How many strings `bytesOf` keeps. A loop alternates between strings: std's
19
+ * `indexOfAnyFrom` and `yamlByte` read a byte of the document, then of a
20
+ * needle or a word, per step, so a cache of one encodes the document on every
21
+ * read. Eight covers the most std's loops keep live at once.
22
+ */
23
+ const SLOTS = 8;
24
+
25
+ /**
26
+ * The strings `bytesOf` saw last, most recent first, and their bytes: `null`
27
+ * for an ASCII string, whose units are its bytes and which is never encoded.
28
+ * A hit moves its entry to the front and a miss drops the last one, so a
29
+ * string stays while it is read and leaves when it is not. A lookup compares
30
+ * at most `SLOTS` strings with `===`, which answers at once for the same
31
+ * string or a different length and otherwise stops at the first unit that
32
+ * differs.
33
+ */
34
+ const keys = new Array(SLOTS).fill("");
35
+ const values = new Array(SLOTS).fill(null);
36
+ let used = 0;
37
+
38
+ /**
39
+ * The UTF-8 bytes of `s`, which is what an Nish string holds, or `null` when
40
+ * `s` is ASCII and its UTF-16 units are those bytes. Nothing here writes to
22
41
  * the bytes it is handed.
23
42
  */
24
43
  function bytesOf(s) {
25
- if (s !== lastString) {
26
- lastBytes = ENCODER.encode(s);
27
- lastString = s;
44
+ if (keys[0] === s) return values[0];
45
+ let at = 1;
46
+ while (at < used && keys[at] !== s) at++;
47
+ let bytes;
48
+ if (at < used) {
49
+ bytes = values[at];
50
+ } else {
51
+ bytes = NON_ASCII.test(s) ? ENCODER.encode(s) : null;
52
+ if (used < SLOTS) used++;
53
+ at = used - 1;
54
+ }
55
+ for (; at > 0; at--) {
56
+ keys[at] = keys[at - 1];
57
+ values[at] = values[at - 1];
28
58
  }
29
- return lastBytes;
59
+ keys[0] = s;
60
+ values[0] = bytes;
61
+ return bytes;
30
62
  }
31
63
 
32
64
  /**
33
65
  * `s.length`: UTF-8 byte length for strings (arrays keep their own `.length`).
34
- * The engine's encoder outruns a count in JavaScript, and the loop condition
35
- * `i < s.length` then leaves the bytes for the `s.charCodeAt(i)` it guards.
66
+ * The loop condition `i < s.length` then leaves the bytes for the
67
+ * `s.charCodeAt(i)` it guards.
36
68
  */
37
69
  export function strLen(x) {
38
- return typeof x === "string" ? bytesOf(x).length : x.length;
70
+ if (typeof x !== "string") return x.length;
71
+ const bytes = bytesOf(x);
72
+ return bytes === null ? x.length : bytes.length;
39
73
  }
40
74
 
41
75
  /**
@@ -52,6 +86,10 @@ export function strLenOpt(x) {
52
86
  export function charCodeAt(s, i) {
53
87
  const bytes = bytesOf(s);
54
88
  const k = toIndex(i);
89
+ if (bytes === null) {
90
+ if (!(k >= 0 && k < s.length)) panicIndex(k, s.length);
91
+ return s.charCodeAt(k);
92
+ }
55
93
  if (!(k >= 0 && k < bytes.length)) panicIndex(k, bytes.length);
56
94
  return bytes[k];
57
95
  }
@@ -59,9 +97,13 @@ export function charCodeAt(s, i) {
59
97
  /** `s.substring(a, b)`: JavaScript's clamp and swap, over byte offsets. */
60
98
  export function substring(s, a, b) {
61
99
  const bytes = bytesOf(s);
62
- const clamp = (v) => Math.max(0, Math.min(toIndex(v), bytes.length));
100
+ const len = bytes === null ? s.length : bytes.length;
101
+ const clamp = (v) => Math.max(0, Math.min(toIndex(v), len));
63
102
  const from = clamp(a);
64
- const to = b === undefined ? bytes.length : clamp(b);
103
+ const to = b === undefined ? len : clamp(b);
104
+ // A NaN index cuts nothing, as native's does; JavaScript's would read it as 0.
105
+ if (from !== from || to !== to) return "";
106
+ if (bytes === null) return s.substring(from, to);
65
107
  return DECODER.decode(bytes.subarray(Math.min(from, to), Math.max(from, to)));
66
108
  }
67
109
 
@@ -73,17 +115,22 @@ export function substring(s, a, b) {
73
115
  */
74
116
  export function slice(s, a, b) {
75
117
  const bytes = bytesOf(s);
118
+ const len = bytes === null ? s.length : bytes.length;
76
119
  const from = toIndex(a);
77
- const to = b === undefined ? bytes.length : toIndex(b);
78
- if (!(from >= 0 && from <= to && to <= bytes.length)) panicSlice(from, to, bytes.length);
79
- return DECODER.decode(bytes.subarray(from, to));
120
+ const to = b === undefined ? len : toIndex(b);
121
+ if (!(from >= 0 && from <= to && to <= len)) panicSlice(from, to, len);
122
+ return bytes === null ? s.slice(from, to) : DECODER.decode(bytes.subarray(from, to));
80
123
  }
81
124
 
82
- /** Whether `needle` sits in `bytes` at byte offset `at`. */
83
- function bytesAt(bytes, at, needle) {
84
- if (!(at >= 0 && at + needle.length <= bytes.length)) return false;
85
- for (let j = 0; j < needle.length; j++) {
86
- if (bytes[at + j] !== needle[j]) return false;
125
+ /**
126
+ * Whether `sub` sits in `bytes` at byte offset `at`; `needle` is `sub`'s
127
+ * bytes, or `null` when `sub` is ASCII and its units are compared instead.
128
+ */
129
+ function bytesAt(bytes, at, sub, needle) {
130
+ const n = needle === null ? sub.length : needle.length;
131
+ if (!(at >= 0 && at + n <= bytes.length)) return false;
132
+ for (let j = 0; j < n; j++) {
133
+ if (bytes[at + j] !== (needle === null ? sub.charCodeAt(j) : needle[j])) return false;
87
134
  }
88
135
  return true;
89
136
  }
@@ -92,35 +139,40 @@ function bytesAt(bytes, at, needle) {
92
139
  * `s.indexOf(sub, from)`: the first *byte* offset at or after `from`, or -1.
93
140
  * `from` is converted as JavaScript's `ToIntegerOrInfinity` converts it (NaN
94
141
  * is 0) and clamped into `[0, len]`, so an empty `sub` is found at `from`.
95
- * The engine's `indexOf` over the bytes finds each candidate for `sub`'s
96
- * first byte, and only those are compared in full.
142
+ * In an ASCII `s` the engine's own `indexOf` answers: offsets are bytes there,
143
+ * and a `sub` that is not ASCII is in it nowhere, as none of its bytes are.
144
+ * Otherwise the engine's `indexOf` over the bytes finds each candidate for
145
+ * `sub`'s first byte, and only those are compared in full.
97
146
  */
98
147
  export function indexOf(s, sub, from) {
99
148
  const haystack = bytesOf(s);
149
+ const len = haystack === null ? s.length : haystack.length;
100
150
  const at = from === undefined ? 0 : toIndex(from);
101
- const start = Number.isNaN(at) ? 0 : Math.max(0, Math.min(at, haystack.length));
151
+ const start = Number.isNaN(at) ? 0 : Math.max(0, Math.min(at, len));
102
152
  if (sub.length === 0) return start;
103
- const needle = ENCODER.encode(sub);
104
- const last = haystack.length - needle.length;
105
- for (let i = haystack.indexOf(needle[0], start); i >= 0 && i <= last; i = haystack.indexOf(needle[0], i + 1)) {
106
- if (bytesAt(haystack, i, needle)) return i;
153
+ if (haystack === null) return s.indexOf(sub, start);
154
+ const needle = bytesOf(sub);
155
+ const first = needle === null ? sub.charCodeAt(0) : needle[0];
156
+ const last = len - (needle === null ? sub.length : needle.length);
157
+ for (let i = haystack.indexOf(first, start); i >= 0 && i <= last; i = haystack.indexOf(first, i + 1)) {
158
+ if (bytesAt(haystack, i, sub, needle)) return i;
107
159
  }
108
160
  return -1;
109
161
  }
110
162
 
111
- /** `nish_str_at`: whether `sub`'s bytes sit at byte offset `at`. */
112
- function occursAt(s, at, sub) {
113
- return bytesAt(bytesOf(s), at, ENCODER.encode(sub));
114
- }
115
-
163
+ /** `s.startsWith(sub)`: whether `sub`'s bytes begin `s`'s; an ASCII `s` asks the engine. */
116
164
  export function startsWith(s, sub) {
117
- return occursAt(s, 0, sub);
165
+ const bytes = bytesOf(s);
166
+ if (bytes === null) return s.startsWith(sub);
167
+ return bytesAt(bytes, 0, sub, bytesOf(sub));
118
168
  }
119
169
 
170
+ /** `s.endsWith(sub)`: whether `sub`'s bytes end `s`'s; an ASCII `s` asks the engine. */
120
171
  export function endsWith(s, sub) {
121
172
  const bytes = bytesOf(s);
122
- const needle = ENCODER.encode(sub);
123
- return bytesAt(bytes, bytes.length - needle.length, needle);
173
+ if (bytes === null) return s.endsWith(sub);
174
+ const needle = bytesOf(sub);
175
+ return bytesAt(bytes, bytes.length - (needle === null ? sub.length : needle.length), sub, needle);
124
176
  }
125
177
 
126
178
  /**
package/runtime/core.d.ts CHANGED
@@ -147,3 +147,11 @@ export declare function asI32x4(v: SimdVector): i32x4;
147
147
  export declare function asU32x4(v: SimdVector): u32x4;
148
148
  export declare function asF32x4(v: SimdVector): f32x4;
149
149
  export declare function asF64x2(v: SimdVector): f64x2;
150
+
151
+ // `mulHigh` and `mulHighIsNative`: builtins, written out under these names.
152
+ import type { u64 } from "./core/numbers.js";
153
+
154
+ /** The high 64 bits of the 128-bit product of `a` and `b` (WP41): `(a * b) >> 64n`. */
155
+ export declare function mulHigh(a: u64, b: u64): u64;
156
+ /** `false` under Node, where `mulHigh` is a BigInt multiply rather than one instruction. */
157
+ export declare function mulHighIsNative(): boolean;
package/runtime/core.mjs CHANGED
@@ -89,6 +89,22 @@ const simdLoad = (Lanes) => (xs, i) => {
89
89
  export const Compact = Object.freeze({});
90
90
  export const Wide = Object.freeze({});
91
91
 
92
+ // `mulHigh` / `mulHighIsNative` (WP41). A `u64` is a BigInt here, so the high
93
+ // half is the exact product shifted down. A `number` operand is the mix the
94
+ // native checker refuses (NL2823), and throws rather than answering from a
95
+ // double. `mulHighIsNative` is `false`, so std keeps its narrow-limb code under
96
+ // Node, where `mulHigh` is a BigInt multiply and no faster than four products.
97
+ export function mulHigh(a, b) {
98
+ if (typeof a !== "bigint" || typeof b !== "bigint") {
99
+ throw new TypeError("mulHigh: takes u64 (BigInt) operands");
100
+ }
101
+ return (BigInt.asUintN(64, a) * BigInt.asUintN(64, b)) >> 64n;
102
+ }
103
+
104
+ export function mulHighIsNative() {
105
+ return false;
106
+ }
107
+
92
108
  export const u8x16 = simdMake(Uint8Array);
93
109
  export const u16x8 = simdMake(Uint16Array);
94
110
  export const i32x4 = simdMake(Int32Array);
package/runtime/nish.d.ts CHANGED
@@ -628,6 +628,36 @@ declare function ctSelect<T extends u32 | u64>(mask: T, a: T, b: T): T;
628
628
  * @returns a mask for `ctSelect`.
629
629
  */
630
630
  declare function ctEq<T extends u32 | u64>(a: T, b: T): T;
631
+ /**
632
+ * The high 64 bits of the 128-bit product of `a` and `b`, the half a `u64`
633
+ * `a * b` drops (WP41). Both operands are `u64`. Any other type is refused as
634
+ * `` `mulHigh` takes u64 operands (convert with toU64), got u32 `` (NL2823):
635
+ * `u32`, `i64`, `number` and a ranged integer included. A bare numeric
636
+ * literal is read as a `u64`, so `mulHigh(x, 3)` works, and one that does not
637
+ * fit is the literal's own refusal. The call takes exactly two arguments, and
638
+ * like every function it is not a value.
639
+ *
640
+ * On x86-64 and AArch64 it is one multiply (`mul`, `mulx` or `umulh`) and
641
+ * calls nothing. wasm32 has no wide multiply, so there it is four 32×32
642
+ * products and their carries, inline. Neither lowering branches on its
643
+ * operands. Under Node it is `(a * b) >> 64n` on BigInts, with the same
644
+ * answer. Capability: none.
645
+ *
646
+ * @param a one factor.
647
+ * @param b the other factor.
648
+ * @returns the top 64 bits of `a * b` computed in 128 bits.
649
+ */
650
+ declare function mulHigh(a: u64, b: u64): u64;
651
+ /**
652
+ * Whether `mulHigh` is one instruction on the build's target (WP41): `true` on
653
+ * x86-64 and AArch64, and `false` on wasm32 and under Node. It is a constant of
654
+ * the build, so a branch on it costs nothing and the path not taken is
655
+ * dropped. Code with a wide-limb algorithm and a narrow-limb one keeps both and
656
+ * picks with it. It takes no arguments. Capability: none.
657
+ *
658
+ * @returns `true` where the 64×64→128 product is native.
659
+ */
660
+ declare function mulHighIsNative(): boolean;
631
661
  /**
632
662
  * Every byte of `bytes` set to zero, in stores neither `-O2` nor `-flto` may
633
663
  * drop as dead (#385): how a key, a secret scalar or another secret is cleared
@@ -1968,6 +1998,27 @@ declare function pollRemove(loop: i32, fd: i32): i32;
1968
1998
  * the next wait), 0 on a timeout, or a negative errno.
1969
1999
  */
1970
2000
  declare function pollWait(loop: i32, ready: i32[], timeoutMs: i32): i32;
2001
+ /**
2002
+ * Wait as `pollWait` does, up to `timeoutMs` for the first event, and then up to `maxWaitMs`
2003
+ * more until `minEvents` pairs are ready, so a busy ring loop takes its events in batches. An
2004
+ * idle loop is not woken every `maxWaitMs`: the second wait starts only once an event is in.
2005
+ * The batch counts the slots and listeners of a `NET_LISTEN_RING` listener; a loop with no ring
2006
+ * listener, and Darwin, answer as `pollWait` does. A descriptor that becomes ready during the
2007
+ * second wait, `signalFd()` included, is reported at most `maxWaitMs` late. `minEvents` of 1 or
2008
+ * less, or a `maxWaitMs` of 0 or less, is `pollWait`. Not callable in a `scope()` task or a
2009
+ * parallel body. A call that writes `ready` is refused in a scope's region on an array a task may
2010
+ * read, as `fill` is. Refused at compile time on wasm32 and the WASI profile (NL2404).
2011
+ * Capability: net.
2012
+ *
2013
+ * @param loop the loop from `pollCreate`.
2014
+ * @param ready receives the pairs; shorter than 2 is -22. Its length caps the batch.
2015
+ * @param timeoutMs the most milliseconds to wait for the first event; negative: forever (-1).
2016
+ * @param minEvents the pairs a batch waits for once the first is in.
2017
+ * @param maxWaitMs the most milliseconds the batch waits after the first event.
2018
+ * @returns how many pairs, at most `ready.length / 2` and at most 64, 0 on a timeout, or a
2019
+ * negative errno.
2020
+ */
2021
+ declare function pollWaitBatch(loop: i32, ready: i32[], timeoutMs: i32, minEvents: i32, maxWaitMs: i32): i32;
1971
2022
  /**
1972
2023
  * Set one socket option from a whitelist: there is no raw level and option number, so a program
1973
2024
  * cannot pass a level, a name and a length through to the kernel. The ids are the runtime's own
@@ -3423,6 +3474,26 @@ declare module "nish:net" {
3423
3474
  * for a `ready` shorter than 2.
3424
3475
  */
3425
3476
  export function pollWait(loop: i32, ready: i32[], timeoutMs: i32): i32;
3477
+ /**
3478
+ * Wait as `pollWait` does for the first event, and then, on a loop holding
3479
+ * a `NET_LISTEN_RING` listener's slots, up to `maxWaitMs` more until
3480
+ * `minEvents` pairs are ready. An idle loop is not woken every `maxWaitMs`.
3481
+ * A descriptor that becomes ready during the second wait is reported at
3482
+ * most `maxWaitMs` late. A loop with no ring listener, and Darwin, answer
3483
+ * as `pollWait` does.
3484
+ *
3485
+ * @param loop The loop.
3486
+ * @param ready The array the pairs are written into; its length caps the
3487
+ * batch.
3488
+ * @param timeoutMs The most milliseconds to wait for the first event; any
3489
+ * negative number waits forever.
3490
+ * @param minEvents The pairs a batch waits for once the first is in.
3491
+ * @param maxWaitMs The most milliseconds the batch waits after the first
3492
+ * event.
3493
+ * @returns The count of pairs, at most `ready.length / 2` and at most 64,
3494
+ * `0` on a timeout, or `-22` for a `ready` shorter than 2.
3495
+ */
3496
+ export function pollWaitBatch(loop: i32, ready: i32[], timeoutMs: i32, minEvents: i32, maxWaitMs: i32): i32;
3426
3497
  /**
3427
3498
  * Set one socket option from a whitelist. There is no way to pass a raw
3428
3499
  * level and option number, because that would be an untyped call into the
@@ -5328,6 +5399,18 @@ declare module "nish:async" {
5328
5399
  * (or removed); `false` for a task that has finished or is `main`.
5329
5400
  */
5330
5401
  export function cancelAfter(task: i64, ms: i32): boolean;
5402
+ /**
5403
+ * Read `view`, an object or array its spawner owns, in place, without
5404
+ * copying it into the task's region. Inside a spawned task the view, and
5405
+ * what is built from it, is lent only while the task runs: the task may
5406
+ * read it, write numbers into it and copy out of it, but may not store a
5407
+ * pointer into it, grow it, or keep it, its parts or what holds it past its
5408
+ * end (NL2822). Outside a task, and under `--emit-ts`, it is the identity.
5409
+ *
5410
+ * @param view The spawner's object or array the task reads.
5411
+ * @returns `view` itself.
5412
+ */
5413
+ export function lend<T>(view: T): T;
5331
5414
  }
5332
5415
 
5333
5416
  // ---- Arena (docs/LANGUAGE.md -> Arena) ---------------------------------------
@@ -6227,9 +6310,9 @@ interface StringConstructor {
6227
6310
  * reached, visits a key set during the walk later in the same walk, and keeps a
6228
6311
  * re-set key in its place, as JavaScript's does.
6229
6312
  *
6230
- * At most 2^24 − 1 entries (one fewer than Node's 2^24); one more panics with
6231
- * `Map maximum size exceeded`, after first compacting away dead entries (not
6232
- * while a loop walks the table). String keys are hashed with SipHash-1-3 under
6313
+ * No entry cap of its own: past 2^29 entries the bucket table would outgrow
6314
+ * the largest array, and the program stops as out of memory, as any
6315
+ * allocation that size does (Node's `Map` throws at 2^24). String keys are hashed with SipHash-1-3 under
6233
6316
  * a per-process random key drawn from the system's entropy source before
6234
6317
  * `main`, and an integer, `boolean` or enum key under a per-process random
6235
6318
  * multiply-add-shift; if the entropy source fails the program panics before
@@ -6301,8 +6384,8 @@ interface Map<K, V> {
6301
6384
  * `new Set<T>()` takes no arguments ("`new Set<string>` takes no arguments in
6302
6385
  * this version"). `keys()` and `values()` are one walk, as JavaScript's are,
6303
6386
  * admitted only as the iterable of a `for...of`, which also takes the set
6304
- * itself: `for (const x of s)`. At most 2^24 − 1 members; one more panics with
6305
- * `Set maximum size exceeded`. Hashing, the entropy source and the walk's
6387
+ * itself: `for (const x of s)`. Its size is bounded as a `Map`'s is, by
6388
+ * memory alone. Hashing, the entropy source and the walk's
6306
6389
  * rules are `Map`'s. `add` and `has` are one probe each, and `if (!s.has(x)) {
6307
6390
  * s.add(x); ... }` with the `add` first in the branch asks about the member
6308
6391
  * once.
package/runtime/nish.h CHANGED
@@ -793,6 +793,15 @@ double nish_stat_mtime(const nish_str *path);
793
793
  * or a read that fails. */
794
794
  int32_t nish_signal_fd(void);
795
795
  int32_t nish_read_signal(int32_t fd);
796
+ /* The runtime's own, with no builtin: the read end `signalFd()` made, or -1
797
+ * while none is made, without making one. A loop's wait asks it to tell the
798
+ * signal descriptor from any other (runtime-net.c, the direct ring wait). */
799
+ int32_t nish_signal_fd_made(void);
800
+ /* Every closer that takes a program's descriptor number calls this first:
801
+ * once the signal read end is closed, `nish_signal_fd_made` answers -1 for
802
+ * good, since its number may be reused (docs/security/net-uring.md,
803
+ * NURING-49). */
804
+ void nish_signal_fd_closing(int32_t fd);
796
805
  /* Who owns a path, and whether it runs (docs/security/runtime.md, RT-9; the
797
806
  * builtins `lstatOwnerModeSync`, `geteuid` and `isExecutableSync`, #386).
798
807
  * `nish_lstat_owner_mode(path)`: `lstat`, so a
@@ -927,6 +936,7 @@ int32_t nish_poll_add(int32_t loop, int32_t fd, int32_t events, int32_t token);
927
936
  int32_t nish_poll_modify(int32_t loop, int32_t fd, int32_t events, int32_t token);
928
937
  int32_t nish_poll_remove(int32_t loop, int32_t fd);
929
938
  int32_t nish_poll_wait(int32_t loop, nish_array *ready, int32_t timeout_ms);
939
+ int32_t nish_poll_wait_batch(int32_t loop, nish_array *ready, int32_t timeout_ms, int32_t min_events, int32_t max_wait_ms);
930
940
  int32_t nish_unix_listen(const nish_str *path, int32_t backlog, int32_t flags);
931
941
  int32_t nish_unix_listen_mode(const nish_str *path, int32_t backlog, int32_t flags, int32_t mode);
932
942
  int32_t nish_unix_connect(const nish_str *path);
package/runtime/nish.mjs CHANGED
@@ -159,6 +159,7 @@ for (const name of [
159
159
  "pollModify",
160
160
  "pollRemove",
161
161
  "pollWait",
162
+ "pollWaitBatch",
162
163
  "netSetOption",
163
164
  "netMss",
164
165
  "unixListen",
@@ -251,6 +252,10 @@ provide("f32ToBits", shim.f32ToBits);
251
252
  // agree with a native run; the timing does not, and is not claimed here.
252
253
  provide("ctSelect", shim.ctSelect);
253
254
  provide("ctEq", shim.ctEq);
255
+ // `mulHigh` (WP41): exact on BigInts. `mulHighIsNative` is `false`, so std
256
+ // takes its narrow-limb path here.
257
+ provide("mulHigh", shim.mulHigh);
258
+ provide("mulHighIsNative", shim.mulHighIsNative);
254
259
  // `secureZero` (#385): the bytes are zero afterwards here too, though what a
255
260
  // collector may have copied before is out of reach.
256
261
  provide("secureZero", shim.secureZero);
@@ -212,6 +212,21 @@ int32_t nish_signal_fd(void) {
212
212
  return (int32_t)(cur >> 32);
213
213
  }
214
214
 
215
+ /* Set once a closer (`netClose`, `fileClose`) is handed the read end: from
216
+ then on its number may name any descriptor opened since, so
217
+ `nish_signal_fd_made` answers -1 rather than a number that is no longer the
218
+ signal pipe (docs/security/net-uring.md, NURING-48 and NURING-49). */
219
+ static int32_t nish_signal_closed;
220
+
221
+ int32_t nish_signal_fd_made(void) {
222
+ int64_t cur = __atomic_load_n(&nish_signal_pipe, __ATOMIC_ACQUIRE);
223
+ return cur < 0 || __atomic_load_n(&nish_signal_closed, __ATOMIC_ACQUIRE) ? -1 : (int32_t)(cur >> 32);
224
+ }
225
+
226
+ void nish_signal_fd_closing(int32_t fd) {
227
+ if (fd >= 0 && fd == nish_signal_fd_made()) __atomic_store_n(&nish_signal_closed, 1, __ATOMIC_RELEASE);
228
+ }
229
+
215
230
  /* Block until a signal's byte arrives and answer it: 15 or 2, or -1 for any
216
231
  `fd` that is not the signal descriptor and for a read that fails. */
217
232
  int32_t nish_read_signal(int32_t fd) {