@amritk/nish-aarch64-darwin 0.10.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.
@@ -0,0 +1,672 @@
1
+ /**
2
+ * Nish builtins for Node (WP13 differential testing).
3
+ *
4
+ * The differential runner (tests/differential/run.js) rewrites an Nish
5
+ * program into plain JavaScript and runs it under Node with this module as
6
+ * `__nish`. Every helper here reproduces the *runtime* semantics the compiled
7
+ * binary has (runtime/runtime.c and runtime/runtime_os.c, the system-call half,
8
+ * plus the intrinsics in docs/wp7-runtime.md) where JavaScript's own semantics
9
+ * differ:
10
+ *
11
+ * - `number` is a 32-bit integer in the default mode (`--number-mode i32`),
12
+ * `i64` is a 64-bit integer, both wrapping; JS has doubles and BigInt.
13
+ * - `u8`/`u16`/`u32`/`u64` are unsigned and wrapping, and JavaScript has no
14
+ * unsigned integers at all: the narrow three live in a `number` masked
15
+ * back into range (`& 0xFF`, `& 0xFFFF`, `>>> 0`) and `u64` is a BigInt
16
+ * kept in range with `BigInt.asUintN(64, x)`.
17
+ * - `f32` is a 32-bit float and JavaScript has only doubles, so every `f32`
18
+ * result is rounded with `Math.fround`.
19
+ * - `s.length` is the UTF-8 byte length, and so is every index the string
20
+ * methods take or return: `charCodeAt` yields a byte (and bounds-checks
21
+ * instead of returning `NaN`), `substring` cuts on byte offsets, and
22
+ * `indexOf` answers with one. `slice` cuts on byte offsets too and panics
23
+ * on a range the string does not contain, where JavaScript would clamp and
24
+ * read a negative offset from the end. `String.fromCharCode` builds a
25
+ * one-byte string from the low 8 bits.
26
+ * - `a[i]` is bounds-checked: out of range prints
27
+ * `index out of range: <i> >= <len>` to stderr and exits 1, and so is
28
+ * `a.pop()` on an empty array, which has no `undefined` to return.
29
+ * - `toI32/toI64` from f64 saturate (NaN -> 0), integer conversions wrap.
30
+ * - `console.log(x)` never prints the `n` suffix of an i64 and writes
31
+ * synchronously so `process.exit` cannot lose output.
32
+ * - file I/O errors print `nish: cannot read <path>` and exit 1.
33
+ * - a directory listing is sorted by UTF-8 bytes, which is `strcmp`'s order
34
+ * and not `Array#sort`'s UTF-16 one; `monotonicNanos` reads a clock whose
35
+ * origin is arbitrary, so two readings can agree with a native run and a
36
+ * single reading never can.
37
+ * - `process.argv[0]` is the program (the script here, the executable
38
+ * natively); `parseInt` is base 10 only and saturates into i32 (0 for no
39
+ * digits); `parseFloat`/`Number` accept ASCII whitespace, decimal forms,
40
+ * `Infinity`, and a `0x` hex prefix (parseFloat too, unlike JS).
41
+ *
42
+ * The rewrite rules that call these helpers are listed in docs/wp13-differential.md.
43
+ */
44
+ import child_process from "node:child_process";
45
+ import fs from "node:fs";
46
+ import os from "node:os";
47
+
48
+ const I32_MIN = -2147483648;
49
+ const I32_MAX = 2147483647;
50
+ const I64_MIN = -(1n << 63n);
51
+ const I64_MAX = (1n << 63n) - 1n;
52
+
53
+ /** `trunc i64 -> i32` (wrap) for BigInt, `llvm.fptosi.sat.i32.f64` for numbers. */
54
+ export function toI32(x) {
55
+ if (typeof x === "bigint") return Number(BigInt.asIntN(32, x));
56
+ if (Number.isNaN(x)) return 0;
57
+ if (x >= I32_MAX) return I32_MAX;
58
+ if (x <= I32_MIN) return I32_MIN;
59
+ return Math.trunc(x) | 0;
60
+ }
61
+
62
+ /** `sext i32 -> i64` for int32 numbers, `llvm.fptosi.sat.i64.f64` for doubles. */
63
+ export function toI64(x) {
64
+ if (typeof x === "bigint") return x;
65
+ if (Number.isNaN(x)) return 0n;
66
+ if (x >= 9223372036854775808) return I64_MAX;
67
+ if (x <= -9223372036854775808) return I64_MIN;
68
+ return BigInt(Math.trunc(x));
69
+ }
70
+
71
+ /** `sitofp` for both integer widths; a double is returned unchanged. */
72
+ export function toF64(x) {
73
+ return typeof x === "bigint" ? Number(x) : x;
74
+ }
75
+
76
+ /**
77
+ * `f64ToBits` / `bitsToF64`: reinterpret the 64 bits, never convert the value.
78
+ * The compiler lowers each to one `bitcast`; here it is a one-element
79
+ * DataView, which is the only way JavaScript lets you see a double's bits.
80
+ * The result is signed, matching the i64 the compiler produces.
81
+ */
82
+ const BITS = new DataView(new ArrayBuffer(8));
83
+
84
+ export function f64ToBits(x) {
85
+ BITS.setFloat64(0, x);
86
+ return BigInt.asIntN(64, BITS.getBigUint64(0));
87
+ }
88
+
89
+ export function bitsToF64(b) {
90
+ BITS.setBigInt64(0, BigInt.asIntN(64, b));
91
+ return BITS.getFloat64(0);
92
+ }
93
+
94
+ /** Wrap a BigInt to the i64 range: every i64 `+ - * /` and unary minus goes through here. */
95
+ export function wrapI64(x) {
96
+ return BigInt.asIntN(64, x);
97
+ }
98
+
99
+ /**
100
+ * The i64 shifts. BigInt has no `>>>` and neither of its shifts masks the
101
+ * count, so all three do here what `codegen/emit/bitwise.ts` emits: mask the
102
+ * count to 6 bits, then shift. `lshrI64` reads the operand as unsigned before
103
+ * shifting and hands back the signed reading of the result, which is `lshr`.
104
+ */
105
+ export function shlI64(a, b) {
106
+ return BigInt.asIntN(64, a << (b & 63n));
107
+ }
108
+ export function ashrI64(a, b) {
109
+ return a >> (b & 63n);
110
+ }
111
+ export function lshrI64(a, b) {
112
+ return BigInt.asIntN(64, BigInt.asUintN(64, a) >> (b & 63n));
113
+ }
114
+
115
+ /** `llvm.abs.i64(x, false)`: the minimum value wraps to itself. */
116
+ export function absI64(x) {
117
+ return BigInt.asIntN(64, x < 0n ? -x : x);
118
+ }
119
+
120
+ /** `llvm.smin.i64` / `llvm.smax.i64` (Math.min/max reject BigInt). */
121
+ export function minI64(a, b) {
122
+ return a < b ? a : b;
123
+ }
124
+ export function maxI64(a, b) {
125
+ return a > b ? a : b;
126
+ }
127
+
128
+ // ---- Unsigned integers (WP15) -------------------------------------------------------
129
+ //
130
+ // JavaScript has no unsigned integer type, so every unsigned result is masked
131
+ // back into its width right where the compiled code would have relied on the
132
+ // LLVM type. u8/u16/u32 fit a `number` exactly (2^32 - 1 < 2^53); u64 is a
133
+ // BigInt, so it goes through `wrapU64` the way i64 goes through `wrapI64`.
134
+
135
+ /** Wrap into the u64 range: every u64 `+ - * /`, unary minus and shift ends here. */
136
+ export function wrapU64(x) {
137
+ return BigInt.asUintN(64, x);
138
+ }
139
+
140
+ /**
141
+ * The u64 shifts. A u64 is already held as a non-negative BigInt, so its `>>`
142
+ * *is* the logical shift; what these add over the operator is the count mask
143
+ * (BigInt does not mask) and the wrap back into the unsigned range.
144
+ */
145
+ export function shlU64(a, b) {
146
+ return BigInt.asUintN(64, a << (b & 63n));
147
+ }
148
+ export function lshrU64(a, b) {
149
+ return BigInt.asUintN(64, a) >> (b & 63n);
150
+ }
151
+
152
+ /**
153
+ * The widths, as the rewriter names them. `bits` drives every mask and
154
+ * `BigInt.asIntN`/`asUintN` call; `big` says whether the value is a BigInt
155
+ * (i64/u64) or a `number` in JavaScript.
156
+ */
157
+ const INT_KINDS = {
158
+ i32: { bits: 32, signed: true, big: false },
159
+ i64: { bits: 64, signed: true, big: true },
160
+ u8: { bits: 8, signed: false, big: false },
161
+ u16: { bits: 16, signed: false, big: false },
162
+ u32: { bits: 32, signed: false, big: false },
163
+ u64: { bits: 64, signed: false, big: true },
164
+ };
165
+
166
+ /** `llvm.umin`/`umax` on u64 (`Math.min`/`max` reject BigInt); the u32-and-below widths use Math. */
167
+ export function minU64(a, b) {
168
+ return a < b ? a : b;
169
+ }
170
+ export function maxU64(a, b) {
171
+ return a > b ? a : b;
172
+ }
173
+
174
+ /**
175
+ * Every numeric conversion whose source or target is unsigned (`toU8`,
176
+ * `toU32(i)`, `toI32(u)`, ...), as one function taking the kind names the
177
+ * checker recorded. Doing it through BigInt is what makes the whole matrix
178
+ * exact in one place: an integer source is turned into its true mathematical
179
+ * value, then `asIntN`/`asUintN` performs the sign-extend, zero-extend or
180
+ * truncate that the target's width and signedness call for — which is exactly
181
+ * what `sext`/`zext`/`trunc` do natively.
182
+ */
183
+ export function convert(x, from, to) {
184
+ const num = typeof x === "bigint" ? Number(x) : x;
185
+ if (to === "f64") return num; // sitofp / uitofp / fpext
186
+ if (to === "f32") return Math.fround(num); // ... / fptrunc, then rounded to a float
187
+ const target = INT_KINDS[to];
188
+ const lo = target.signed ? -(1n << BigInt(target.bits - 1)) : 0n;
189
+ const hi = target.signed ? (1n << BigInt(target.bits - 1)) - 1n : (1n << BigInt(target.bits)) - 1n;
190
+ let exact;
191
+ if (INT_KINDS[from] === undefined) {
192
+ // A float source (f32 or f64) goes through the saturating intrinsics: NaN
193
+ // is 0 and out-of-range values clamp. The bounds are BigInt because
194
+ // 2^64 - 1 has no exact `number`.
195
+ if (Number.isNaN(x)) exact = 0n;
196
+ else if (x <= Number(lo)) exact = lo;
197
+ else if (x >= Number(hi)) exact = hi;
198
+ else exact = BigInt(Math.trunc(x));
199
+ } else {
200
+ exact = BigInt(x); // sext/zext/trunc, below
201
+ }
202
+ const wrapped = target.signed ? BigInt.asIntN(target.bits, exact) : BigInt.asUintN(target.bits, exact);
203
+ return target.big ? wrapped : Number(wrapped);
204
+ }
205
+
206
+ /** `s.length`: UTF-8 byte length for strings (arrays keep their own `.length`). */
207
+ export function strLen(x) {
208
+ return typeof x === "string" ? Buffer.byteLength(x, "utf8") : x.length;
209
+ }
210
+
211
+ /** The UTF-8 bytes of `s`, which is what an Nish string holds. */
212
+ function bytesOf(s) {
213
+ return Buffer.from(s, "utf8");
214
+ }
215
+
216
+ /** `s.charCodeAt(i)`: the byte at `i`, bounds-checked as `a[i]` is (JavaScript answers NaN). */
217
+ export function charCodeAt(s, i) {
218
+ const bytes = bytesOf(s);
219
+ const k = toIndex(i);
220
+ if (!(k >= 0 && k < bytes.length)) panicIndex(k, bytes.length);
221
+ return bytes[k];
222
+ }
223
+
224
+ /** `s.substring(a, b)`: JavaScript's clamp and swap, over byte offsets. */
225
+ export function substring(s, a, b) {
226
+ const bytes = bytesOf(s);
227
+ const clamp = (v) => Math.max(0, Math.min(toIndex(v), bytes.length));
228
+ const from = clamp(a);
229
+ const to = b === undefined ? bytes.length : clamp(b);
230
+ return bytes.subarray(Math.min(from, to), Math.max(from, to)).toString("utf8");
231
+ }
232
+
233
+ /**
234
+ * `s.slice(a, b)`: the bytes of `[a, b)` with no clamp, `b` defaulting to the
235
+ * byte length (WP15 §4). Out of range panics rather than clamping, so the two
236
+ * compares the native code emits are reproduced here rather than JavaScript's
237
+ * negative-from-the-end rule.
238
+ */
239
+ export function slice(s, a, b) {
240
+ const bytes = bytesOf(s);
241
+ const from = toIndex(a);
242
+ const to = b === undefined ? bytes.length : toIndex(b);
243
+ if (!(from >= 0 && from <= to && to <= bytes.length)) panicSlice(from, to, bytes.length);
244
+ return bytes.subarray(from, to).toString("utf8");
245
+ }
246
+
247
+ /** `s.indexOf(sub)`: the first *byte* offset, or -1. */
248
+ export function indexOf(s, sub) {
249
+ return bytesOf(s).indexOf(bytesOf(sub));
250
+ }
251
+
252
+ /** `nish_str_at`: whether `sub`'s bytes sit at byte offset `at`. */
253
+ function occursAt(s, at, sub) {
254
+ const bytes = bytesOf(s);
255
+ const needle = bytesOf(sub);
256
+ return at >= 0 && at + needle.length <= bytes.length && bytes.subarray(at, at + needle.length).equals(needle);
257
+ }
258
+
259
+ export function startsWith(s, sub) {
260
+ return occursAt(s, 0, sub);
261
+ }
262
+
263
+ export function endsWith(s, sub) {
264
+ return occursAt(s, bytesOf(s).length - bytesOf(sub).length, sub);
265
+ }
266
+
267
+ /** `String.fromCharCode(c)`: the one-byte string of `c & 0xFF`. */
268
+ export function fromCharCode(code) {
269
+ return Buffer.from([toIndex(code) & 0xff]).toString("latin1");
270
+ }
271
+
272
+ /** `console.log(x)`: `String(x)` (no `n` suffix for i64) plus a newline, written synchronously. */
273
+ export function log(x) {
274
+ fs.writeSync(1, `${String(x)}\n`);
275
+ }
276
+
277
+ /** `console.error(x)`: the same, on stderr. */
278
+ export function error(x) {
279
+ fs.writeSync(2, `${String(x)}\n`);
280
+ }
281
+
282
+ /** `write(s)` / `writeError(s)`: the bytes as they are, no trailing newline. */
283
+ export function write(s) {
284
+ fs.writeSync(1, s);
285
+ }
286
+
287
+ export function writeError(s) {
288
+ fs.writeSync(2, s);
289
+ }
290
+
291
+ /** `panic(message)`: the message on stderr, then exit 1. */
292
+ export function panic(message) {
293
+ fs.writeSync(2, `${message}\n`);
294
+ process.exit(1);
295
+ }
296
+
297
+ // ---- Result (WP16) ---------------------------------------------------------
298
+ //
299
+ // Natively a `Result` is a two-arm struct in the arena; here it is an ordinary
300
+ // object with the same three names, so `r.ok`, `r.value` and `r.error` in the
301
+ // rewritten program mean what they mean in the compiled one. Only `orReturn`
302
+ // needs help: it returns from the *enclosing* function, which no expression in
303
+ // JavaScript can do, so it throws a sentinel that `rewrite.js` catches in a
304
+ // wrapper around every body that contains one.
305
+
306
+ class Propagate {
307
+ constructor(error) {
308
+ this.error = error;
309
+ }
310
+ }
311
+
312
+ class NishResult {
313
+ constructor(ok, value, error) {
314
+ this.ok = ok;
315
+ if (ok) this.value = value;
316
+ else this.error = error;
317
+ }
318
+ isOk() {
319
+ return this.ok;
320
+ }
321
+ isErr() {
322
+ return !this.ok;
323
+ }
324
+ unwrapOr(fallback) {
325
+ return this.ok ? this.value : fallback;
326
+ }
327
+ expect(message) {
328
+ if (this.ok) return this.value;
329
+ panic(message);
330
+ }
331
+ orReturn() {
332
+ if (this.ok) return this.value;
333
+ throw new Propagate(this.error);
334
+ }
335
+ }
336
+
337
+ /** `Ok(v)`; `Ok()` on a `Result<void, E>` carries nothing. */
338
+ export function Ok(value) {
339
+ return new NishResult(true, value, undefined);
340
+ }
341
+
342
+ /** `Err(e)`. */
343
+ export function Err(error) {
344
+ return new NishResult(false, undefined, error);
345
+ }
346
+
347
+ /**
348
+ * The `catch` half of `orReturn`: re-raise anything that is not a propagation,
349
+ * and answer the `Err` the enclosing function should return otherwise. The
350
+ * rewriter emits `return __nish.caught(e)` and nothing else, so a genuine
351
+ * runtime error still reaches Node unchanged.
352
+ */
353
+ export function caught(thrown) {
354
+ if (thrown instanceof Propagate) return new NishResult(false, undefined, thrown.error);
355
+ throw thrown;
356
+ }
357
+
358
+ /** Index conversion as in the compiler: `sext` from i32, `fptosi` (truncation) from f64. */
359
+ function toIndex(i) {
360
+ return typeof i === "bigint" ? Number(i) : Math.trunc(i);
361
+ }
362
+
363
+ function panicIndex(i, len) {
364
+ fs.writeSync(2, `index out of range: ${i} >= ${len}\n`);
365
+ process.exit(1);
366
+ }
367
+
368
+ /** `nish_panic_slice`: the failed range check of `s.slice(start, end)`; the offsets print signed. */
369
+ function panicSlice(start, end, len) {
370
+ fs.writeSync(2, `slice out of range: [${start}, ${end}) of length ${len}\n`);
371
+ process.exit(1);
372
+ }
373
+
374
+ /** `a[i]` read with the WP4 bounds check (negative indices fail like the unsigned compare does). */
375
+ export function idx(a, i) {
376
+ const k = toIndex(i);
377
+ if (!(k >= 0 && k < a.length)) panicIndex(k, a.length);
378
+ return a[k];
379
+ }
380
+
381
+ /** `a.pop()`: the last element, or the bounds panic — Nish has no `undefined` to return. */
382
+ export function pop(a) {
383
+ if (a.length === 0) panicIndex(0, 0);
384
+ return a.pop();
385
+ }
386
+
387
+ /** `a[i] = v`: evaluates `a`, `i`, `v`, then checks and stores; yields `v`. */
388
+ export function setIdx(a, i, v) {
389
+ const k = toIndex(i);
390
+ if (!(k >= 0 && k < a.length)) panicIndex(k, a.length);
391
+ a[k] = v;
392
+ return v;
393
+ }
394
+
395
+ /** `a[i] op= v`: evaluates `a`, `i`, checks, loads, then `f(old)` computes the new element. */
396
+ export function updIdx(a, i, f) {
397
+ const k = toIndex(i);
398
+ if (!(k >= 0 && k < a.length)) panicIndex(k, a.length);
399
+ const v = f(a[k]);
400
+ a[k] = v;
401
+ return v;
402
+ }
403
+
404
+ /** `new Array<T>(n)`: `n` zero-filled elements (`0`, `0n`, or `false`). */
405
+ export function newArray(n, zero) {
406
+ return new Array(toIndex(n)).fill(zero);
407
+ }
408
+
409
+ /** `process.exit(code)`: libc `exit` truncates to 8 bits exactly like Node does. */
410
+ export function exit(code) {
411
+ process.exit(toIndex(code));
412
+ }
413
+
414
+
415
+ function ioFail(verb, path) {
416
+ fs.writeSync(2, `nish: cannot ${verb} ${path}\n`);
417
+ process.exit(1);
418
+ }
419
+
420
+ export function readFileSync(path) {
421
+ try {
422
+ return fs.readFileSync(path, "utf8");
423
+ } catch {
424
+ return ioFail("read", path);
425
+ }
426
+ }
427
+
428
+ /** `readFileSyncOrNull(path)`: null instead of exiting, so the program decides. */
429
+ export function readFileSyncOrNull(path) {
430
+ try {
431
+ return fs.readFileSync(path, "utf8");
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+
437
+ export function writeFileSync(path, data) {
438
+ try {
439
+ fs.writeFileSync(path, data, "utf8");
440
+ } catch {
441
+ ioFail("write", path);
442
+ }
443
+ }
444
+
445
+ export function appendFileSync(path, data) {
446
+ try {
447
+ fs.appendFileSync(path, data, "utf8");
448
+ } catch {
449
+ ioFail("write", path);
450
+ }
451
+ }
452
+
453
+ /**
454
+ * `mkdirSync(path)` (WP14 D4): one directory, not recursive, answering whether
455
+ * a directory is there afterwards. Node throws where the runtime answers
456
+ * false, and `EEXIST` on a plain file is a failure here as it is there, so the
457
+ * `statSync` decides rather than the exception.
458
+ */
459
+ export function mkdirSync(path) {
460
+ try {
461
+ fs.mkdirSync(path);
462
+ return true;
463
+ } catch {
464
+ try {
465
+ return fs.statSync(path).isDirectory();
466
+ } catch {
467
+ return false;
468
+ }
469
+ }
470
+ }
471
+
472
+ /**
473
+ * `isDirectorySync(path)` (WP14 §7a): one stat, and a boolean out of it rather
474
+ * than an exception, which is what the runtime's `stat` answers too.
475
+ */
476
+ export function isDirectorySync(path) {
477
+ try {
478
+ return fs.statSync(path).isDirectory();
479
+ } catch {
480
+ return false;
481
+ }
482
+ }
483
+
484
+ /**
485
+ * `readdirSync(path)`: the entries, sorted ascending by bytes, or `null` when
486
+ * the directory cannot be read. Node throws where the runtime answers a value,
487
+ * so the `catch` is what makes the two agree, and a directory that exists and
488
+ * is empty answers an empty array on both sides. Node's readdir never yields
489
+ * `.` or `..` — the pair `runtime_os.c` skips explicitly — so there is nothing
490
+ * to filter out here.
491
+ *
492
+ * The sort is the semantic point. `runtime_os.c` orders the names with
493
+ * `strcmp`, which compares UTF-8 bytes, and `Array#sort` compares UTF-16 code
494
+ * units. The two agree on ASCII names and part company above the BMP, where a
495
+ * surrogate pair sorts below `U+E000`..`U+FFFF` in UTF-16 and above them in
496
+ * UTF-8. So the comparison is over the encoded bytes, which is the native order
497
+ * exactly rather than the native order for the names that happen to be ASCII.
498
+ */
499
+ export function readdirSync(path) {
500
+ let names;
501
+ try {
502
+ names = fs.readdirSync(path);
503
+ } catch {
504
+ return null;
505
+ }
506
+ return names.sort((a, b) => Buffer.compare(Buffer.from(a, "utf8"), Buffer.from(b, "utf8")));
507
+ }
508
+
509
+ /**
510
+ * `realpathSync(path)` (WP19 §5a item 4): `path` with its symbolic links
511
+ * resolved, or `null` when it does not resolve.
512
+ *
513
+ * `fs.realpathSync` throws where the native `realpath` answers NULL — a
514
+ * missing path, a loop, a component that is not a directory — so the `catch`
515
+ * is what makes the two runtimes agree, exactly as it does for `readdirSync`
516
+ * above. Node's own answer is already absolute and already normalised, which
517
+ * is what POSIX `realpath` guarantees, so nothing here has to normalise it.
518
+ */
519
+ export function realpathSync(path) {
520
+ try {
521
+ return fs.realpathSync(path);
522
+ } catch {
523
+ return null;
524
+ }
525
+ }
526
+
527
+ /**
528
+ * `process.platform` / `process.arch` (WP14 §7a). Node's spellings are the
529
+ * ones `runtime_os.c` answers with, so on any machine this compiler has a
530
+ * triple for the two runtimes give the same string; elsewhere the native build
531
+ * says `unknown` where Node names the platform, which is the one place they
532
+ * part.
533
+ */
534
+ export function platform() {
535
+ return process.platform;
536
+ }
537
+
538
+ export function arch() {
539
+ return process.arch;
540
+ }
541
+
542
+ /**
543
+ * `getenv(name)` (WP19 R1): the value, or `null` when the variable is unset.
544
+ * Node answers `undefined` there and the language has no `undefined`, so the
545
+ * `??` is what makes the two runtimes agree; an empty value stays an empty
546
+ * string on both sides, because `CC=` is set and `CC` unset is not.
547
+ */
548
+ export function getenv(name) {
549
+ return process.env[name] ?? null;
550
+ }
551
+
552
+ /**
553
+ * `spawnSync(argv)` and `spawnSyncTo(argv, out, err)` (WP14 D4), which are one
554
+ * run with its streams answered differently: the child's exit status, 128 + n
555
+ * when signal n killed it, -1 for an empty vector or a program that would not
556
+ * start. `runtime_os.c` puts one `static nish_spawn_impl` behind both builtins
557
+ * for the same reason this module puts one function behind both helpers — the
558
+ * argument vector, the wait and the signal convention are written once and
559
+ * cannot drift between the two.
560
+ *
561
+ * `out` and `err` are paths for the child's stdout and stderr, and an **empty**
562
+ * string leaves that stream inherited. Each file is created or truncated at
563
+ * 0644, which is what `"w"` asks `open(2)` for (`O_WRONLY | O_CREAT | O_TRUNC`)
564
+ * and what the runtime's file actions ask for. The descriptors opened here are
565
+ * closed again whichever way the child went; natively the child opens them and
566
+ * its exit drops them.
567
+ */
568
+ function spawnImpl(argv, out, err) {
569
+ if (argv.length === 0) return -1;
570
+ const opened = [];
571
+ const stream = (target) => {
572
+ if (target.length === 0) return "inherit";
573
+ const fd = fs.openSync(target, "w", 0o644);
574
+ opened.push(fd);
575
+ return fd;
576
+ };
577
+ try {
578
+ const r = child_process.spawnSync(argv[0], argv.slice(1), {
579
+ stdio: ["inherit", stream(out), stream(err)],
580
+ });
581
+ if (r.error !== undefined) return -1;
582
+ if (r.signal !== null && r.signal !== undefined) return 128 + (os.constants.signals[r.signal] ?? 0);
583
+ return r.status === null ? -1 : r.status;
584
+ } catch {
585
+ // A path that cannot be opened is, natively, a file action the child could
586
+ // not perform, and `posix_spawnp` reports that through its return value:
587
+ // -1, with no child having run. Opening the second path is what can fail
588
+ // after the first file was already created, so the truncation a caller can
589
+ // observe happens on both sides.
590
+ return -1;
591
+ } finally {
592
+ for (const fd of opened) fs.closeSync(fd);
593
+ }
594
+ }
595
+
596
+ /** `spawnSync(argv)`: the child inherits this process's streams, as it does natively. */
597
+ export function spawnSync(argv) {
598
+ return spawnImpl(argv, "", "");
599
+ }
600
+
601
+ /** `spawnSyncTo(argv, stdoutPath, stderrPath)`: the same run with a stream sent to a file. */
602
+ export function spawnSyncTo(argv, out, err) {
603
+ return spawnImpl(argv, out, err);
604
+ }
605
+
606
+ /**
607
+ * `monotonicNanos()`: `process.hrtime.bigint()`, a monotonic clock in
608
+ * nanoseconds (`CLOCK_MONOTONIC` on every platform that has it, which is the
609
+ * one `runtime_os.c` reads). The value is a BigInt because that is how an `i64`
610
+ * is held on this side.
611
+ *
612
+ * No rewrite can make a *reading* agree with a native run: both origins are
613
+ * arbitrary and neither is the other's. Only the difference between two reads
614
+ * means anything, so a differential program may compare two readings and must
615
+ * never print one.
616
+ */
617
+ export function monotonicNanos() {
618
+ return process.hrtime.bigint();
619
+ }
620
+
621
+ /** `process.argv`: index 0 is the program (the script here, the executable natively), then the arguments. */
622
+ export function argv() {
623
+ return process.argv.slice(1);
624
+ }
625
+
626
+ const SPACES = "[ \\t\\n\\v\\f\\r]*";
627
+ /** What `nish_parse_number` recognises: strtod's decimal and hex-integer forms, or an exact `Infinity`. */
628
+ const LITERAL = new RegExp(`^${SPACES}([+-]?)(Infinity|0[xX][0-9a-fA-F]+|(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?)`);
629
+ const BLANK = new RegExp(`^${SPACES}$`);
630
+ const WHOLE = new RegExp(`${LITERAL.source}${SPACES}$`);
631
+
632
+ /** The value of a `LITERAL` match: hex goes through parseInt(16), and `-` applies afterwards as in strtod. */
633
+ function literalValue(m) {
634
+ const magnitude = /^0[xX]/.test(m[2]) ? Number.parseInt(m[2], 16) : Number(m[2]);
635
+ return m[1] === "-" ? -magnitude : magnitude;
636
+ }
637
+
638
+ /** `parseInt(s)`: strtoll base 10 (ASCII whitespace, sign, digits; 0 without digits) saturated into i32. */
639
+ export function parseInt(s) {
640
+ const m = new RegExp(`^${SPACES}([+-]?\\d+)`).exec(s);
641
+ return m ? toI32(Number(m[1])) : 0;
642
+ }
643
+
644
+ /** `parseFloat(s)`: the longest literal after ASCII whitespace, else NaN (`0x1A` is 26, as strtod reads it). */
645
+ export function parseFloat(s) {
646
+ const m = LITERAL.exec(s);
647
+ return m ? literalValue(m) : NaN;
648
+ }
649
+
650
+ /** `Number(x)`: a string must be one literal bar surrounding ASCII whitespace (blank is 0); others convert numerically. */
651
+ export function number(x) {
652
+ if (typeof x === "bigint") return Number(x);
653
+ if (typeof x === "boolean") return x ? 1 : 0;
654
+ if (typeof x !== "string") return x;
655
+ const m = WHOLE.exec(x);
656
+ if (m) return literalValue(m);
657
+ return BLANK.test(x) ? 0 : NaN;
658
+ }
659
+
660
+ // Arena introspection has no JS counterpart: the stubs keep programs that only
661
+ // compare `Arena.used()` before/after (a "stayed flat" check) in agreement, while
662
+ // programs that print raw byte counts are listed as known differences.
663
+ //
664
+ // `nish --threads` makes the native arena thread-local (WP20 T0) and nothing
665
+ // here moves with it: a rewritten program runs on the one thread Node gives it,
666
+ // so "the arena of the calling thread" and "the arena" are the same object, and
667
+ // these stubs answer for both. If T1 ever lands a spawn the rewrite can reach,
668
+ // that is when this file grows a second arena to keep count of.
669
+ export function arenaUsed() { return 0; }
670
+ export function arenaMark() { return 0; }
671
+ export function arenaRelease() {}
672
+ export function arenaReset() {}