nish 0.46.0 → 0.48.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 (45) hide show
  1. package/docs/AI.md +29 -18
  2. package/package.json +5 -5
  3. package/runtime/gfx/README.md +55 -0
  4. package/runtime/gfx/nish-gfx.c +1063 -0
  5. package/runtime/gfx/nish-gfx.h +221 -0
  6. package/runtime/gfx/nish-gfx.overrides.json +14 -0
  7. package/runtime/nish.d.ts +22 -5
  8. package/runtime/nish.h +1 -0
  9. package/runtime/nish.mjs +1 -0
  10. package/runtime/runtime-bytes.c +167 -7
  11. package/runtime/runtime-net.c +122 -52
  12. package/runtime/runtime-uring.c +150 -69
  13. package/runtime/sqlite/nish-sqlite.c +166 -39
  14. package/scripts/build.sh +88 -3
  15. package/std/README.md +2 -2
  16. package/std/base64.ts +28 -30
  17. package/std/compress/deflate.ts +1371 -704
  18. package/std/crypto/aes.ts +81 -45
  19. package/std/crypto/bcrypt-batch.ts +23 -4
  20. package/std/crypto/bcrypt.ts +36 -11
  21. package/std/crypto/chacha20poly1305.ts +93 -52
  22. package/std/crypto/x25519.ts +7 -4
  23. package/std/host/game.ts +52 -20
  24. package/std/host/ring.ts +115 -31
  25. package/std/host/text.ts +9 -3
  26. package/std/json.ts +83 -0
  27. package/std/math.ts +161 -131
  28. package/std/net/handler.ts +24 -6
  29. package/std/net/http-server.ts +358 -141
  30. package/std/net/http1-server.ts +44 -13
  31. package/std/net/prefork.ts +1 -2
  32. package/std/net/static.ts +7 -2
  33. package/std/random.ts +34 -51
  34. package/std/raster.ts +377 -113
  35. package/std/regex.ts +46 -15
  36. package/std/release.ts +19 -13
  37. package/std/sqlite.ts +380 -16
  38. package/std/synth.ts +20 -3
  39. package/std/temporal.ts +740 -363
  40. package/std/term-io.ts +81 -33
  41. package/std/term-pixels.ts +287 -112
  42. package/std/term-probe.ts +7 -3
  43. package/std/term-rate.ts +142 -66
  44. package/std/term.ts +782 -406
  45. package/std/testing.ts +14 -7
@@ -545,7 +545,9 @@ typedef struct nishsqlite_cursor {
545
545
  Btree *btree; /* `main`, from sqlite3DbNameToBtree */
546
546
  BtCursor *bt; /* in the same block, after this struct */
547
547
  KeyInfo *ki; /* the record's fields, for the decoder and a seek */
548
- UnpackedRecord *row; /* the current row, decoded on the first read of it */
548
+ const u8 *rec; /* the current row's record, on its page or in `buf` */
549
+ u32 *ftype; /* its fields' serial types, read from its header on the first read */
550
+ u32 *foff; /* and where each field's bytes start in `rec` */
549
551
  Mem *key; /* the seek key's `nkeyfields` values, in the block */
550
552
  UnpackedRecord seek; /* the key a seek or count hands SQLite: `key`, under `ki` */
551
553
  int32_t nkeyparts; /* how many of them are set */
@@ -568,7 +570,6 @@ static void cursor_free(nishsqlite_cursor *cur) {
568
570
  sqlite3 *db = cur->conn->db;
569
571
  sqlite3BtreeCloseCursor(cur->bt);
570
572
  for (int32_t i = 0; i < cur->nkeyfields; i++) sqlite3VdbeMemRelease(&cur->key[i]);
571
- if (cur->row) sqlite3DbFree(db, cur->row);
572
573
  sqlite3KeyInfoUnref(cur->ki);
573
574
  sqlite3_free(cur->buf);
574
575
  sqlite3_free(cur->counts);
@@ -908,7 +909,10 @@ build:;
908
909
  int32_t nkeyfields = is_index ? nkey : ncol;
909
910
  size_t head = ROUND8(sizeof(nishsqlite_cursor));
910
911
  size_t btsz = ROUND8((size_t)sqlite3BtreeCursorSize());
911
- nishsqlite_cursor *cur = sqlite3_malloc64(head + btsz + (size_t)nkeyfields * sizeof(Mem));
912
+ size_t keysz = ROUND8((size_t)nkeyfields * sizeof(Mem));
913
+ /* Room for a record's fields: the key's, and an index entry's rowid after them. */
914
+ size_t fieldsz = (size_t)(nkeyfields + 1) * sizeof(u32);
915
+ nishsqlite_cursor *cur = sqlite3_malloc64(head + btsz + keysz + 2 * fieldsz);
912
916
  if (cur == NULL) {
913
917
  sqlite3KeyInfoUnref(ki);
914
918
  return -SQLITE_NOMEM;
@@ -921,6 +925,8 @@ build:;
921
925
  sqlite3BtreeCursorZero(cur->bt);
922
926
  cur->ki = ki;
923
927
  cur->key = (Mem *)((u8 *)cur + head + btsz);
928
+ cur->ftype = (u32 *)((u8 *)cur + head + btsz + keysz);
929
+ cur->foff = cur->ftype + nkeyfields + 1;
924
930
  cur->nkeyfields = nkeyfields;
925
931
  for (int32_t i = 0; i < nkeyfields; i++) sqlite3VdbeMemInit(&cur->key[i], db, MEM_Null);
926
932
  cur->ncol = ncol;
@@ -929,9 +935,7 @@ build:;
929
935
  cur->int_first = int_first;
930
936
  cur->seek.pKeyInfo = ki;
931
937
  cur->seek.aMem = cur->key;
932
- cur->row = sqlite3VdbeAllocUnpackedRecord(ki);
933
- rc = cur->row ? SQLITE_OK : SQLITE_NOMEM;
934
- if (rc == SQLITE_OK) rc = sqlite3BtreeCursor(cur->btree, root, 0, is_index ? ki : NULL, cur->bt);
938
+ rc = sqlite3BtreeCursor(cur->btree, root, 0, is_index ? ki : NULL, cur->bt);
935
939
  int32_t hc = rc == SQLITE_OK ? slot_take(&nishsqlite_cursors, cur, c->self) : 0;
936
940
  if (hc == 0) {
937
941
  cursor_free(cur);
@@ -1109,8 +1113,14 @@ static int record_of(nishsqlite_cursor *cur, u32 *sz, const void **p) {
1109
1113
  return SQLITE_OK;
1110
1114
  }
1111
1115
 
1112
- /* The current row's record decoded into `row`, once per row. SQLITE_MISUSE
1113
- * with no row, SQLITE_CORRUPT for a record longer than SQLite allows. */
1116
+ /* The current row's record header read into `ftype` and `foff`, once per
1117
+ * row: each field's serial type and where its bytes start. The walk is
1118
+ * `sqlite3VdbeRecordUnpack`'s, bound for bound, so it finds the fields that
1119
+ * function would and no others, and like it a record whose last field runs
1120
+ * past its end reads that field as NULL. What it skips is building a Mem
1121
+ * per field: a column is decoded from its serial type when it is read
1122
+ * (`field_value`). SQLITE_MISUSE with no row, SQLITE_CORRUPT for a record
1123
+ * longer than SQLite allows. */
1114
1124
  static int row_of(nishsqlite_cursor *cur) {
1115
1125
  if (!cur->has_row) return SQLITE_MISUSE;
1116
1126
  if (cur->unpacked) return SQLITE_OK;
@@ -1120,41 +1130,101 @@ static int row_of(nishsqlite_cursor *cur) {
1120
1130
  int rc = record_of(cur, &sz, &p);
1121
1131
  if (rc != SQLITE_OK) return rc;
1122
1132
  cur->nfields = 0;
1133
+ cur->rec = p;
1123
1134
  if (sz > 0) {
1124
- cur->row->nField = (u16)(cur->nkeyfields + 1);
1125
- sqlite3VdbeRecordUnpack((int)sz, p, cur->row);
1126
- cur->nfields = cur->row->nField;
1135
+ const u8 *a = p;
1136
+ u32 hdr, idx, d, u = 0, nfield = (u32)cur->nkeyfields + 1;
1137
+ idx = getVarint32(a, hdr);
1138
+ d = hdr;
1139
+ while (idx < hdr && d <= sz) {
1140
+ u32 t;
1141
+ idx += getVarint32(&a[idx], t);
1142
+ cur->ftype[u] = t;
1143
+ cur->foff[u] = d;
1144
+ d += sqlite3VdbeSerialTypeLen(t);
1145
+ if (++u >= nfield) break;
1146
+ }
1147
+ if (d > sz && u) cur->ftype[u - 1] = 0;
1148
+ cur->nfields = (int32_t)u;
1127
1149
  }
1128
1150
  cur->unpacked = 1;
1129
1151
  return SQLITE_OK;
1130
1152
  }
1131
1153
 
1132
- /* Column `n` of the current row: NULL with `*rc` set when it cannot be read.
1133
- * The INTEGER PRIMARY KEY column is the row's key, not a field of its record,
1134
- * so it answers NULL with `*alias` set. A row whose record holds fewer fields
1135
- * than `n` (one written before ALTER TABLE added the column) is SQLITE_SCHEMA. */
1136
- static Mem *column_mem(nishsqlite_cursor *cur, int32_t n, int *alias, int *rc) {
1154
+ /* Field `n` of the current row's record, which `row_of` has read: its type
1155
+ * as `sqlite3_value_type` answers it, with `*v` as `column_value` describes.
1156
+ * Integers, NULL and text or blob bytes are read in place, as
1157
+ * `sqlite3VdbeSerialGet` reads them; anything else (a REAL, or a text or
1158
+ * blob read as an integer) goes through `sqlite3VdbeSerialGet` and SQLite's
1159
+ * own conversion, so every answer is the one a Mem would give. */
1160
+ /* The integer of serial type `t` at `b`: 1 to 6 big-endian and signed, 8
1161
+ * and 9 the constants 0 and 1, as `sqlite3VdbeSerialGet` reads them. Any
1162
+ * other type is 0; the callers check the type first. */
1163
+ static int64_t serial_int(u32 t, const u8 *b) {
1164
+ switch (t) {
1165
+ case 1: return ONE_BYTE_INT(b);
1166
+ case 2: return TWO_BYTE_INT(b);
1167
+ case 3: return THREE_BYTE_INT(b);
1168
+ case 4: return FOUR_BYTE_INT(b);
1169
+ case 5: return SIX_BYTE_INT(b);
1170
+ case 6: return (int64_t)sqlite3Get8byte(b);
1171
+ case 9: return 1;
1172
+ default: return 0;
1173
+ }
1174
+ }
1175
+
1176
+ static inline int32_t field_value(nishsqlite_cursor *cur, int32_t n, uint64_t *v, int bytes, uint8_t *buf, uint64_t room) {
1177
+ u32 t = cur->ftype[n];
1178
+ const u8 *b = cur->rec + cur->foff[n];
1179
+ if (t >= 12 && bytes) {
1180
+ *v = (t - 12) / 2;
1181
+ if (*v > 0 && *v <= room) memcpy(buf, b, (size_t)*v);
1182
+ return (t & 1) ? SQLITE_TEXT : SQLITE_BLOB;
1183
+ }
1184
+ if (t == 0 || t == 10 || t == 11) {
1185
+ *v = 0;
1186
+ return SQLITE_NULL;
1187
+ }
1188
+ if (t <= 9 && t != 7) {
1189
+ *v = (uint64_t)serial_int(t, b);
1190
+ return SQLITE_INTEGER;
1191
+ }
1192
+ Mem m;
1193
+ memset(&m, 0, sizeof m);
1194
+ m.enc = cur->ki->enc;
1195
+ m.db = cur->ki->db;
1196
+ sqlite3VdbeSerialGet(b, t, &m);
1197
+ *v = (uint64_t)sqlite3_value_int64((sqlite3_value *)&m);
1198
+ return sqlite3_value_type((sqlite3_value *)&m);
1199
+ }
1200
+
1201
+ /* Whether column `n` of the current row can be read from its record: 0
1202
+ * with `*rc` set when it cannot. The INTEGER PRIMARY KEY column is the row's
1203
+ * key, not a field of its record, so it answers 0 with `*alias` set. A row
1204
+ * whose record holds fewer fields than `n` (one written before ALTER TABLE
1205
+ * added the column) is SQLITE_SCHEMA. */
1206
+ static int column_field(nishsqlite_cursor *cur, int32_t n, int *alias, int *rc) {
1137
1207
  *alias = 0;
1138
1208
  if (cur == NULL || !cur->has_row) {
1139
1209
  *rc = SQLITE_MISUSE;
1140
- return NULL;
1210
+ return 0;
1141
1211
  }
1142
1212
  if (n < 0 || n >= cur->ncol) {
1143
1213
  *rc = SQLITE_RANGE;
1144
- return NULL;
1214
+ return 0;
1145
1215
  }
1146
1216
  if (n == cur->alias) {
1147
1217
  *alias = 1;
1148
1218
  *rc = SQLITE_OK;
1149
- return NULL;
1219
+ return 0;
1150
1220
  }
1151
1221
  *rc = row_of(cur);
1152
- if (*rc != SQLITE_OK) return NULL;
1222
+ if (*rc != SQLITE_OK) return 0;
1153
1223
  if (n >= cur->nfields) {
1154
1224
  *rc = SQLITE_SCHEMA;
1155
- return NULL;
1225
+ return 0;
1156
1226
  }
1157
- return &cur->row->aMem[n];
1227
+ return 1;
1158
1228
  }
1159
1229
 
1160
1230
  /* Column `n`'s type, SQLITE_INTEGER to SQLITE_NULL, or the negated code, with
@@ -1167,24 +1237,14 @@ static Mem *column_mem(nishsqlite_cursor *cur, int32_t n, int *alias, int *rc) {
1167
1237
  * would convert it. */
1168
1238
  static int32_t column_value(nishsqlite_cursor *cur, int32_t n, uint64_t *v, int bytes, uint8_t *buf, uint64_t room) {
1169
1239
  int alias, rc;
1170
- Mem *m = column_mem(cur, n, &alias, &rc);
1240
+ int ok = column_field(cur, n, &alias, &rc);
1171
1241
  if (alias) {
1172
1242
  if (sqlite3BtreeCursorHasMoved(cur->bt)) return -SQLITE_ABORT;
1173
1243
  *v = (uint64_t)sqlite3BtreeIntegerKey(cur->bt);
1174
1244
  return SQLITE_INTEGER;
1175
1245
  }
1176
- if (m == NULL) return -rc;
1177
- sqlite3_value *val = (sqlite3_value *)m;
1178
- int32_t type = sqlite3_value_type(val);
1179
- if (bytes && (type == SQLITE_TEXT || type == SQLITE_BLOB)) {
1180
- /* NULL for no bytes, so an empty value copies nothing. */
1181
- const void *p = sqlite3_value_blob(val);
1182
- *v = (uint32_t)sqlite3_value_bytes(val);
1183
- if (p != NULL && *v <= room) memcpy(buf, p, (size_t)*v);
1184
- } else {
1185
- *v = (uint64_t)sqlite3_value_int64(val);
1186
- }
1187
- return type;
1246
+ if (!ok) return -rc;
1247
+ return field_value(cur, n, v, bytes, buf, room);
1188
1248
  }
1189
1249
 
1190
1250
  static int32_t unlocked_cursor_column_type(nishsqlite_cursor *cur, int32_t n) {
@@ -1220,8 +1280,27 @@ static int32_t unlocked_cursor_column_into(nishsqlite_cursor *cur, int32_t c, ui
1220
1280
  static int64_t unlocked_cursor_rowid(nishsqlite_cursor *cur) {
1221
1281
  if (cur == NULL || !cur->has_row) return 0;
1222
1282
  if (!cur->is_index) return sqlite3BtreeCursorHasMoved(cur->bt) ? 0 : sqlite3BtreeIntegerKey(cur->bt);
1283
+ /* An index entry's rowid is its record's last field, so it is read off
1284
+ * the record's end, as `sqlite3VdbeIdxRowid` reads it, without walking
1285
+ * the header: the header's last byte is the rowid's serial type, an
1286
+ * integer's being one byte. Any other record takes the walk below. */
1287
+ if (!cur->unpacked) {
1288
+ if (sqlite3BtreeCursorHasMoved(cur->bt)) return 0;
1289
+ u32 sz = 0;
1290
+ const void *p = NULL;
1291
+ if (record_of(cur, &sz, &p) != SQLITE_OK) return 0;
1292
+ const u8 *a = p;
1293
+ u32 hdr = 0;
1294
+ if (sz >= 3) getVarint32NR(a, hdr);
1295
+ if (hdr >= 3 && hdr <= sz) {
1296
+ u32 t = a[hdr - 1];
1297
+ if (t >= 1 && t <= 9 && t != 7 && sz >= hdr + sqlite3SmallTypeSizes[t])
1298
+ return serial_int(t, a + sz - sqlite3SmallTypeSizes[t]);
1299
+ }
1300
+ }
1223
1301
  if (row_of(cur) != SQLITE_OK || cur->nfields < cur->ncol) return 0;
1224
- return sqlite3_value_int64((sqlite3_value *)&cur->row->aMem[cur->ncol - 1]);
1302
+ uint64_t v;
1303
+ return field_value(cur, cur->ncol - 1, &v, 0, NULL, 0) < 0 ? 0 : (int64_t)v;
1225
1304
  }
1226
1305
 
1227
1306
  /* ---- Range counts ------------------------------------------------------- */
@@ -1423,15 +1502,35 @@ int64_t nishsqlite_cursor_rowid(int32_t h) {
1423
1502
  #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__
1424
1503
  #error "readRow's slots are little-endian"
1425
1504
  #endif
1505
+ /* `column_value` for each listed column, with the checks it repeats per
1506
+ * column made once a row: the cursor's row, and its record's header, which
1507
+ * is read only when a listed column is a field of the record. Each column
1508
+ * answers what `column_value` would, in the same order, so the first refusal
1509
+ * is the one a column-by-column read would meet. */
1426
1510
  static int32_t unlocked_cursor_read_row(nishsqlite_cursor *cur, uint8_t *io, uint64_t n, uint8_t *text, uint64_t ntext) {
1427
1511
  if (cur == NULL || !cur->has_row) return -SQLITE_MISUSE;
1428
1512
  uint64_t ncols = n / 11, need = 0;
1429
1513
  uint8_t *out = io + 2 * ncols;
1514
+ int read = 0;
1430
1515
  for (uint64_t k = 0; k < ncols; k++, out += 9) {
1516
+ int32_t c = io[2 * k] | (io[2 * k + 1] << 8);
1431
1517
  uint64_t v;
1432
- int32_t type = column_value(cur, io[2 * k] | (io[2 * k + 1] << 8), &v, 1, text + need, need <= ntext ? ntext - need : 0);
1433
- if (type < 0) return type;
1434
- if (type == SQLITE_TEXT || type == SQLITE_BLOB) need += v;
1518
+ int32_t type;
1519
+ if (c >= cur->ncol) return -SQLITE_RANGE;
1520
+ if (c == cur->alias) {
1521
+ if (sqlite3BtreeCursorHasMoved(cur->bt)) return -SQLITE_ABORT;
1522
+ v = (uint64_t)sqlite3BtreeIntegerKey(cur->bt);
1523
+ type = SQLITE_INTEGER;
1524
+ } else {
1525
+ if (!read) {
1526
+ int rc = row_of(cur);
1527
+ if (rc != SQLITE_OK) return -rc;
1528
+ read = 1;
1529
+ }
1530
+ if (c >= cur->nfields) return -SQLITE_SCHEMA;
1531
+ type = field_value(cur, c, &v, 1, text + need, need <= ntext ? ntext - need : 0);
1532
+ if (type == SQLITE_TEXT || type == SQLITE_BLOB) need += v;
1533
+ }
1435
1534
  out[0] = (uint8_t)type;
1436
1535
  memcpy(out + 1, &v, 8);
1437
1536
  }
@@ -1441,3 +1540,31 @@ static int32_t unlocked_cursor_read_row(nishsqlite_cursor *cur, uint8_t *io, uin
1441
1540
  int32_t nishsqlite_cursor_read_row(int32_t h, uint8_t *io, uint64_t n, uint8_t *text, uint64_t ntext) {
1442
1541
  NISH_SQLITE_CURSOR(int32_t, unlocked_cursor_read_row(cur, io, n, text, ntext));
1443
1542
  }
1543
+
1544
+ /* Copies the current row's record, SQLite's record format whole (its header
1545
+ * of varints, then its fields' bytes), into `buf`, `n` its length, and
1546
+ * answers the record's length. A record longer than `n` copies nothing and
1547
+ * answers its length all the same, so the caller grows `buf` and asks again.
1548
+ * An index entry's record ends with its rowid; a table row's holds no
1549
+ * INTEGER PRIMARY KEY, which is the row's key (`rowid`). SQLITE_MISUSE with
1550
+ * no row, SQLITE_ABORT when the row has moved, SQLITE_CORRUPT for a record
1551
+ * longer than SQLite allows, negated. */
1552
+ static int32_t unlocked_cursor_record(nishsqlite_cursor *cur, uint8_t *buf, uint64_t n) {
1553
+ if (cur == NULL || !cur->has_row) return -SQLITE_MISUSE;
1554
+ if (sqlite3BtreeCursorHasMoved(cur->bt)) return -SQLITE_ABORT;
1555
+ u32 sz = sqlite3BtreePayloadSize(cur->bt);
1556
+ if (sz > SQLITE_MAX_LENGTH) return -SQLITE_CORRUPT;
1557
+ if (sz > n) return (int32_t)sz;
1558
+ u32 amt = 0;
1559
+ const void *p = sqlite3BtreePayloadFetch(cur->bt, &amt);
1560
+ if (amt >= sz) {
1561
+ if (sz > 0) memcpy(buf, p, sz);
1562
+ return (int32_t)sz;
1563
+ }
1564
+ int rc = sqlite3BtreePayload(cur->bt, 0, sz, buf);
1565
+ return rc == SQLITE_OK ? (int32_t)sz : -rc;
1566
+ }
1567
+
1568
+ int32_t nishsqlite_cursor_record(int32_t h, uint8_t *buf, uint64_t n) {
1569
+ NISH_SQLITE_CURSOR(int32_t, unlocked_cursor_record(cur, buf, n));
1570
+ }
package/scripts/build.sh CHANGED
@@ -431,6 +431,51 @@ if [ "$async_wanted" = 1 ] && [ -z "$objects_from" ]; then
431
431
  esac
432
432
  done
433
433
  fi
434
+ # The graphics shim (runtime/gfx/) is selected by the IR the same way: a module
435
+ # that declares one of its `nishgfx_*` functions gets runtime/gfx/'s units
436
+ # compiled and linked against SDL3 and wgpu-native (`gfx_objects`). Any other
437
+ # program compiles and links none of it, so its link line and binary stay as
438
+ # they were. It is one rule with `callsGfx` in src/run-cache.ts, which keys a
439
+ # run's binary on runtime/gfx/ and the libraries; change both or neither. The
440
+ # libraries are not in the tree: they are read from $NISH_GFX_PREFIX/{include,lib},
441
+ # or from build/gfx/<platform>/, where scripts/fetch-gfx.sh puts them.
442
+ gfx_wanted=0
443
+ if [ ${#lls[@]} -gt 0 ] && grep -Eq '^declare [^"]*@nishgfx_' "${lls[@]}"; then
444
+ gfx_wanted=1
445
+ fi
446
+ gfx_dir=""
447
+ gfx_prefix=""
448
+ if [ "$gfx_wanted" = 1 ]; then
449
+ case "$profile" in
450
+ debug|speed|size) ;;
451
+ *) echo "error: the module calls runtime/gfx/, which the $profile profile cannot link: SDL3 and wgpu-native are native libraries; use the debug, speed or size profile" >&2
452
+ exit 2 ;;
453
+ esac
454
+ gfx_dir="$(cd "$(dirname "$0")/../runtime/gfx" 2>/dev/null && pwd -P)" || gfx_dir=""
455
+ if [ -z "$gfx_dir" ]; then
456
+ echo "error: the module calls runtime/gfx/, and $(dirname "$0")/../runtime/gfx/ is not there" >&2
457
+ exit 2
458
+ fi
459
+ if [ -n "${NISH_GFX_PREFIX:-}" ]; then
460
+ gfx_prefix=$NISH_GFX_PREFIX
461
+ else
462
+ case "$(uname -s)-$(uname -m)" in
463
+ Linux-x86_64) gfx_platform=linux-x86_64 ;;
464
+ Linux-aarch64|Linux-arm64) gfx_platform=linux-aarch64 ;;
465
+ Darwin-x86_64) gfx_platform=macos-x86_64 ;;
466
+ Darwin-arm64) gfx_platform=macos-aarch64 ;;
467
+ *) echo "error: the module calls runtime/gfx/, and scripts/fetch-gfx.sh pins no SDL3 or wgpu-native for $(uname -s)-$(uname -m); set NISH_GFX_PREFIX to an install of both" >&2
468
+ exit 2 ;;
469
+ esac
470
+ gfx_prefix="$(cd "$(dirname "$0")/.." && pwd -P)/build/gfx/$gfx_platform"
471
+ fi
472
+ for need in include/SDL3/SDL.h include/webgpu/webgpu.h include/webgpu/wgpu.h lib/libSDL3.a lib/libwgpu_native.a; do
473
+ if [ ! -f "$gfx_prefix/$need" ]; then
474
+ echo "error: the module calls runtime/gfx/, and $gfx_prefix/$need is not there: run scripts/fetch-gfx.sh, or set NISH_GFX_PREFIX to an install of SDL3 and wgpu-native" >&2
475
+ exit 2
476
+ fi
477
+ done
478
+ fi
434
479
  if [ "$sqlite_wanted" = 1 ] && [ -z "$sqlite_dir" ]; then
435
480
  echo "error: the module calls SQLite, and $(dirname "$0")/../runtime/sqlite/ is not there" >&2
436
481
  exit 2
@@ -777,6 +822,46 @@ sqlite_objects() {
777
822
  done < <(sqlite_unit_names)
778
823
  }
779
824
 
825
+ # The units of runtime/gfx/, by name, in the order they are linked.
826
+ gfx_unit_names() {
827
+ (cd -- "$gfx_dir" && for unit in *.c; do [ -f "$unit" ] && printf '%s\n' "$unit"; done)
828
+ }
829
+ # Adds the objects of runtime/gfx/ and the libraries they call to this link.
830
+ # Each unit is compiled into the link's own directory, by its bare name from
831
+ # inside runtime/gfx/ as sqlite_units does, with the flags given less -flto:
832
+ # the shim is a thin layer over two native libraries, so there is nothing for
833
+ # LTO to see through. The libraries are static archives; what else each needs
834
+ # is the system's: on Linux, pthreads and dlopen (SDL opens its Wayland and
835
+ # X11 client libraries at run time) and libm; on macOS, the frameworks SDL's
836
+ # Cocoa driver and wgpu-native's Metal backend call. Nothing is added for a
837
+ # module that does not call runtime/gfx/.
838
+ gfx_libs=()
839
+ gfx_objects() {
840
+ local unit flag
841
+ local -a flags
842
+ [ "$gfx_wanted" = 1 ] || return 0
843
+ make_work
844
+ mkdir -p -- "$work/gfx"
845
+ flags=()
846
+ for flag in "$@"; do
847
+ case "$flag" in -flto) ;; *) flags+=("$flag") ;; esac
848
+ done
849
+ while IFS= read -r unit; do
850
+ (cd -- "$gfx_dir" && exec "$CC" "${flags[@]}" -I. -I"$gfx_prefix/include" -c "$unit" -o "$work/gfx/${unit%.c}.o") ||
851
+ { echo "error: runtime/gfx/$unit did not compile" >&2; exit 1; }
852
+ inputs+=("$work/gfx/${unit%.c}.o")
853
+ done < <(gfx_unit_names)
854
+ gfx_libs=(-L"$gfx_prefix/lib" -lSDL3 -lwgpu_native)
855
+ case "$(uname -s)" in
856
+ Darwin)
857
+ for flag in Cocoa CoreFoundation CoreVideo Foundation IOKit Carbon Metal QuartzCore; do
858
+ gfx_libs+=(-framework "$flag")
859
+ done
860
+ gfx_libs+=(-weak_framework UniformTypeIdentifiers) ;;
861
+ *) gfx_libs+=(-pthread -ldl) ;;
862
+ esac
863
+ }
864
+
780
865
  if [ -n "$sqlite_to" ]; then
781
866
  mkdir -p -- "$sqlite_to"
782
867
  sqlite_to=$(cd -- "$sqlite_to" && pwd)
@@ -855,7 +940,7 @@ fi
855
940
  # under `set -u` is a fatal "unbound variable" -- bash 4.4 made it legal, which is
856
941
  # why Linux never noticed. `pgo`, `elf`, `strip_flag` and `libs` are all empty on
857
942
  # ordinary builds, so please do not simplify these back.
858
- case "$profile" in debug|speed|size) sqlite_objects "${compile[@]}" ;; esac
943
+ case "$profile" in debug|speed|size) sqlite_objects "${compile[@]}"; gfx_objects "${compile[@]}" ;; esac
859
944
  # A package's own C sources join the inputs here, after the runtime's halves
860
945
  # and SQLite were decided from the IR alone, so a source can neither stand in
861
946
  # for runtime.c nor be taken for one of its siblings. clang compiles each by
@@ -868,10 +953,10 @@ if [ ${#link_libs[@]} -gt 0 ] || [ ${#link_sources[@]} -gt 0 ]; then
868
953
  fi
869
954
  case "$profile" in
870
955
  debug)
871
- "$CC" "${common[@]}" "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
956
+ "$CC" "${common[@]}" "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} ${gfx_libs[@]+"${gfx_libs[@]}"} -lm -o "$out" ;;
872
957
  speed|size)
873
958
  "$CC" "${common[@]}" "${optimise[@]}" ${lto_parts[@]+"${lto_parts[@]}"} \
874
- "${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} -lm -o "$out" ;;
959
+ "${gc[@]}" ${strip_flag[@]+"${strip_flag[@]}"} "${inputs[@]}" ${link_libs[@]+"${link_libs[@]}"} ${gfx_libs[@]+"${gfx_libs[@]}"} -lm -o "$out" ;;
875
960
  wasm|wasm-host)
876
961
  # A region's chunks come from malloc, and the freestanding wasm runtime
877
962
  # (runtime-wasm.c) has none, so IR that makes or enters one is refused here
package/std/README.md CHANGED
@@ -35,8 +35,8 @@ a call loads without an import (`collections.ts`, `array.ts`, `sort.ts`,
35
35
  | [`map.ts`](https://github.com/amritk/nish/blob/main/std/map.ts) | `reserve(m, n)` and `getOrInsert(m, k, v)` for the global `Map`. Their bodies are the meaning, and what runs under Node: `reserve` does nothing, and `getOrInsert` is a `get`, and a `set` of `v` when the key was missing. Natively the compiler lowers every call in place — `reserve` to the table's `reserveSlots`, which grows the buckets once so that `n` entries fit without a rebuild, and `getOrInsert` to one `probe` and a `valueAt` or an `insertAt` through its answer — so, like `collections.ts`, it writes no `.ll` of its own ([`docs/LANGUAGE.md`](../docs/reference/language/builtins.md#map-and-set)) |
36
36
  | [`bytes.ts`](https://github.com/amritk/nish/blob/main/std/bytes.ts) | `getU16LE` / `getU16BE` to `getF64LE` / `getF64BE` and the `set` twins: `u16`, `u32`, `u64`, `i32`, `i64` and `f64` read from and written into a `u8[]` at an offset, little- or big-endian. Each access is an ordinary index, so out of range is an `index` panic naming the first missing byte. In range the answers are those of the private copies `std/` keeps (`sha256LoadWord`, `chacha20Word`, `poly1305Le64`, sha512's `loadWord` / `storeWord`, `http2FramePut32`, `tlsPutU16`), none of which it replaces. A guard in the caller does not yet remove the checks after inlining. Under Node only the `u16` and `u32` functions answer as natively. Beside them are the runs a parser walks — `skipBlank`, `skipDigits`, `skipJsonText` and `skipJsonPlain`, the first index in a clamped range whose byte is not a JSON blank, a digit, a byte a JSON string holds as itself or a byte a JSON writer copies without an escape — and `copyBytes`, a window copied as one move that panics on a range outside its array. Their bodies call private walkers, which are what runs under Node; natively the compiler replaces each walker's call with a kernel of `runtime/runtime-bytes.c`, or `llvm.memmove` for the copy ([`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#byte-runs-skipblank-skipdigits-skipjsontext-skipjsonplain-and-copybytes-in-nishbytes)). The runs are variable-time. `tests/link/std_bytes*` are its programs |
37
37
  | [`base64.ts`](https://github.com/amritk/nish/blob/main/std/base64.ts) | `nish/base64`: padded standard base64 (RFC 4648 §4), encode only, for kitty graphics frames. `base64Encode(bytes)` answers a string, `base64EncodeInto(src, off, len, dst, at)` writes into a byte buffer allocating nothing, and `base64EncodedLength(n)` sizes it; a range outside its array panics before a byte is written. It indexes its alphabet by the sextet, so it is not constant-time: it is for pixels, not secrets. A strict decoder, and an encoder for key material, are `crypto/base64url.ts`'s `base64StdPadDecode` and `base64StdPadEncode` (`tests/link/std_base64`, `std_base64_f64`, `std_base64_negative_*`; the two modules in one program: `tests/link/std_base64_two_modules`; [guide](../docs/guide/using-nish/standard-library.md#nishbase64)) |
38
- | [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin. There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
39
- | [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, written with `nish:unsafe`'s `wrappingAdd`, `wrappingSub` and `wrappingMul` so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
38
+ | [`temporal.ts`](https://github.com/amritk/nish/blob/main/std/temporal.ts) | `nish/temporal`: TC39 `Temporal` in the ISO 8601 calendar. `PlainDate`, `PlainTime`, `PlainDateTime`, `Duration` and `Instant` are immutable classes, and each field reads as Temporal's getter of the same name. Temporal's statics are free functions named after the class: `plainDateFrom` (`Temporal.PlainDate.from`), `plainDateCompare`, `instantFromEpochMilliseconds`, `nowInstant` (`Temporal.Now.instant`), and the rest. `add`, `subtract`, `until`, `since`, `equals`, `toString` and `toJSON` follow the specification's defaults. Strings are RFC 9557, and one Temporal refuses panics with `RangeError:`, or answers `null` from the `...OrNull` twin; `tryPlainDate`, `tryPlainDateFrom` and `PlainDate.tryAdd` answer the `RangeError`'s text as a `Result` `Err` (`tests/link/std_temporal_result`). There are no time zones but UTC, no option bags, no `bigint` `epochNanoseconds` and no calendar but `iso8601` yet (`tests/link/std_temporal`, every case also answered by Node's `Temporal`; [guide](../docs/guide/using-nish/dates-and-times.md)) |
39
+ | [`random.ts`](https://github.com/amritk/nish/blob/main/std/random.ts) | `Rng`, a seeded generator of pseudo-random numbers: `new Rng(seed)`, `nextI32()`, `nextF64()` and `nextInt(lo, hi)`, an unbiased integer in [lo, hi] by rejection sampling. A Weyl sequence through all 2^32 states with MurmurHash3's finaliser on each, its wrapping add taken in `f64` on the state read as an unsigned count and its multiplies through `Math.imul`, so that every answer is the same bits natively and under Node (`tests/link/std_random`; [`docs/LANGUAGE.md`](../docs/reference/language/declarations.md#random-numbers-rng-in-nishrandom)). A parallel body or a task that makes its own steps it without a shared write. Not for cryptography |
40
40
  | [`cli.ts`](https://github.com/amritk/nish/blob/main/std/cli.ts) | a command-line tool's `--help`. `HelpMenu` builds it a line at a time — `header`, `usage`, `section`, `row(flag, placeholder, description)`, `note`, `value` — with descriptions lined up at the caller's columns, counted on the plain text, and answers it with `text()`. `Style` paints it in the basic ANSI colours, bold and faint, which the terminal's theme defines, or in bold and underline alone when `TERM` declares no colours; each role it paints (`heading`, `name`, `flag`, `meta`, `dim`) is a pair of SGR lists, `<role>Themed` and `<role>Mono`, a program may set. `Style` also paints any text: the sixteen colours (`red`, `brightBlack`, ...), their backgrounds (`bgRed`, `bgBrightRed`, ...), the attributes (`bold`, `faint`, `italic`, `underline`, `inverse`, `strikethrough`, which the failsafe keeps) and `sgr(text, codes)` for any parameter list, with the `SGR_` constants spelling the codes. `styleFor(fd, agent)` is the policy `nish --help` follows: plain unless the descriptor is a terminal, `NO_COLOR`, `FORCE_COLOR`, `CLICOLOR_FORCE`, `CLICOLOR` and `TERM=dumb` honoured, plain for an agent (`agentDriven`), forced colour always the theme's; it reads the environment and, for the terminal check, forks `/bin/sh` once, which runs `tput` by absolute path. `HelpMenu` and `Style` reach no capability. The compiler's own help is built with it through a relative import, so the module may use only what the last release compiles (`tests/link/std_cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli)) |
41
41
  | [`cli-args.ts`](https://github.com/amritk/nish/blob/main/std/cli-args.ts) | a command tree for a large command-line tool. `Cli` declares it with a builder — `group`, `command(parent, name, id, description)`, `alias`, `flag`, `globalFlag`, `argument`, then `defaultValue`, `required`, `repeatable`, `negatable` and `epilog` on what they answer — every declaration an `i32` handle and every mistake a panic at its call. `parse(argv, start)` walks the arguments once and answers a `ParseResult`: the reached command's id and path, each flag's value with its `source` (the command line, its default or unset), the positionals and what follows `--`, or the first error with a did-you-mean. `finish` prints help (laid out by `HelpMenu`), the version or the error and exits 0 or 2. `parse` reaches no capability (`tests/link/std_cli_args`, `examples/api-cli`; [guide](../docs/guide/using-nish/standard-library.md#nishcli-args)) |
42
42
  | [`cli-flags.ts`](https://github.com/amritk/nish/blob/main/std/cli-flags.ts) | `nish/cli-flags`: a command line read against a declared table. `FlagTable` declares `string`, `number` (an `f64`), `boolean` (`--name` / `--no-name`) and `repeatable` flags and `command` paths of one or more words; `parse(args)` (or `parseFrom(process.argv, 1)`) answers a `ParsedFlags` with the longest matched `command`, the `positionals` and each flag by name (`str`, `num`, `bool`, `all`, `has`). `--name value`, `--name=value`, `--` and a lone `-` follow the GNU long-option grammar; there are no short options. A usage error (unknown flag, missing value, not a number, given twice, value on a boolean, unknown command) is carried as `code`, `message` and `argument`, and `exitUsage()` writes it to stderr and exits 2. `writeHelp(menu)` adds the table's rows to a `nish/cli` `HelpMenu`. Reaches `exit` only through `exitUsage` (`tests/link/std_cli_flags`, `std_cli_flags_bad_*`; [guide](../docs/guide/using-nish/standard-library.md#parsing-flags)) |
package/std/base64.ts CHANGED
@@ -57,12 +57,10 @@ export const base64EncodedLength = (n: i32): i32 => {
57
57
  if (n > 1610612733) {
58
58
  panic("base64EncodedLength: the encoding is longer than 2^31 - 1 characters")
59
59
  }
60
- return (((n + 2) / 3) | 0) * 4
60
+ const groups: i32 = toI32((n + 2) / 3)
61
+ return groups * 4
61
62
  }
62
63
 
63
- /** The byte of the character for the sextet `v` (`0 <= v <= 63`). */
64
- const base64CharOf = (v: i32): u8 => toU8(BASE64_ALPHABET.charCodeAt(v))
65
-
66
64
  /**
67
65
  * Write the base64 of `src[off..off+len)` into `dst` from index `at`, and
68
66
  * answer the index just past the last character written, which is
@@ -91,40 +89,41 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
91
89
  panic("base64EncodeInto: the source range is outside the array")
92
90
  }
93
91
  const need: i32 = base64EncodedLength(len)
94
- if (at < 0 || at > dstLength - need) {
92
+ if (at < 0 || need > dstLength - at) {
95
93
  panic("base64EncodeInto: the encoding does not fit in the destination")
96
94
  }
95
+ // A local, so that `abc.length >= 64` below is a fact about the string each
96
+ // character is read from.
97
+ const abc: string = BASE64_ALPHABET
97
98
  let i: i32 = off
98
99
  let o: i32 = at
99
- const whole: i32 = off + len - (len % 3)
100
+ let rest: i32 = len
100
101
  // The checks above make every term after the first true; they are written out
101
102
  // because they are what proves the loop's accesses in range.
102
- while (i < whole && i >= 0 && i + 2 < srcLength && o >= 0 && o + 3 < dstLength) {
103
+ while (rest >= 3 && i >= 0 && i < srcLength - 2 && o >= 0 && o < dstLength - 3 && abc.length >= 64) {
103
104
  const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8) | toI32(src[i + 2])
104
- dst[o] = base64CharOf(group >> 18)
105
- dst[o + 1] = base64CharOf((group >> 12) & 63)
106
- dst[o + 2] = base64CharOf((group >> 6) & 63)
107
- dst[o + 3] = base64CharOf(group & 63)
105
+ dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
106
+ dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
107
+ dst[o + 2] = toU8(abc.charCodeAt((group >> 6) & 63))
108
+ dst[o + 3] = toU8(abc.charCodeAt(group & 63))
108
109
  i = i + 3
109
110
  o = o + 4
111
+ rest = rest - 3
110
112
  }
111
- const tail: i32 = len % 3
112
- if (tail === 1) {
113
- const group: i32 = toI32(src[i]) << 16
114
- dst[o] = base64CharOf(group >> 18)
115
- dst[o + 1] = base64CharOf((group >> 12) & 63)
116
- dst[o + 2] = toU8(BASE64_PAD)
117
- dst[o + 3] = toU8(BASE64_PAD)
118
- o = o + 4
119
- } else if (tail === 2) {
120
- const group: i32 = (toI32(src[i]) << 16) | (toI32(src[i + 1]) << 8)
121
- dst[o] = base64CharOf(group >> 18)
122
- dst[o + 1] = base64CharOf((group >> 12) & 63)
123
- dst[o + 2] = base64CharOf((group >> 6) & 63)
124
- dst[o + 3] = toU8(BASE64_PAD)
125
- o = o + 4
113
+ // A short final group of one or two bytes, padded. As in the loop, the
114
+ // checks above make every term after the first false.
115
+ if (rest === 0 || i < 0 || i >= srcLength || o < 0 || o >= dstLength - 3 || abc.length < 64) {
116
+ return o
126
117
  }
127
- return o
118
+ let group: i32 = toI32(src[i]) << 16
119
+ if (rest === 2 && i < srcLength - 1) {
120
+ group = group | (toI32(src[i + 1]) << 8)
121
+ }
122
+ dst[o] = toU8(abc.charCodeAt((group >> 18) & 63))
123
+ dst[o + 1] = toU8(abc.charCodeAt((group >> 12) & 63))
124
+ dst[o + 2] = rest === 2 ? toU8(abc.charCodeAt((group >> 6) & 63)) : toU8(BASE64_PAD)
125
+ dst[o + 3] = toU8(BASE64_PAD)
126
+ return o + 4
128
127
  }
129
128
 
130
129
  /**
@@ -135,9 +134,8 @@ export const base64EncodeInto = (src: u8[], off: i32, len: i32, dst: u8[], at: i
135
134
  * @returns A fresh string holding the padded encoding.
136
135
  */
137
136
  export const base64Encode = (bytes: u8[]): string => {
138
- if (bytes.length > 2147483647) {
139
- panic("base64Encode: more than 2^31 - 1 bytes")
140
- }
137
+ // A longer length saturates to the largest `i32` under `--number-mode f64`,
138
+ // which `base64EncodedLength` refuses, as it does any count past 1,610,612,733.
141
139
  const n: i32 = toI32(bytes.length)
142
140
  const out: u8[] = new Array<u8>(base64EncodedLength(n))
143
141
  const end: i32 = base64EncodeInto(bytes, 0, n, out, 0)