nish 0.26.0 → 0.28.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,822 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Generate the Unicode tables of `std/regex.ts` and the oracle its tests read.
4
+ *
5
+ * node scripts/gen-regex-unicode.mjs rewrite the tables and the oracle
6
+ * node scripts/gen-regex-unicode.mjs --check exit 1 if either differs by a byte, or if
7
+ * a table disagrees with this Node's RegExp
8
+ *
9
+ * The tables are the region of `std/regex.ts` between the
10
+ * `gen-regex-unicode:begin` and `gen-regex-unicode:end` lines. They are read
11
+ * from the Unicode Character Database files below, each pinned by its URL and
12
+ * sha256 and cached under `build/ucd/`, at the Unicode version the ICU of the
13
+ * Node that CI pins ships (`process.versions.unicode`), so that `--check` can
14
+ * hold every table to that Node's `RegExp` with the `u` flag, code point by
15
+ * code point. The region lives inside `regex.ts` rather than in a module of
16
+ * its own because a file under `std/` is a public `nish/` module, listed as
17
+ * one by the compiler and the release.
18
+ *
19
+ * **A range list** is a string of base-32 digits, each one byte `0` (48) to
20
+ * `o` (111): a digit of 32 or more is a continuation carrying its low five
21
+ * bits, most significant first, and one below 32 ends the number. A list is
22
+ * its count of ranges, then per range the gap since the last one ended (the
23
+ * first range's start; for later ones `lo - prevHi - 2`, since ranges never
24
+ * touch) and its length less one. The lists are concatenated into
25
+ * `REGEX_PROPERTY_DATA`, an identical list stored once.
26
+ *
27
+ * **The name index** `REGEX_PROPERTY_NAMES` is `|key=offset|…`, the key a
28
+ * namespace letter and a name as ECMA-262 spells it, case and all: `g` a
29
+ * General_Category value (alias or long name, groups such as `L` included),
30
+ * `b` a binary property, `s` a Script value, whose entry is the Script list's
31
+ * offset, a comma and the Script_Extensions list's. An offset starting `~`
32
+ * names the complement of the list there.
33
+ *
34
+ * **The fold table** `REGEX_FOLD_DATA` is CaseFolding.txt's simple folding
35
+ * (statuses C and S) as orbits, the sets of code points that fold to the same
36
+ * one, kept to their members above ASCII: the ASCII letters fold by their own
37
+ * table and nothing crosses into it, so ſ (U+017F) and the Kelvin sign
38
+ * (U+212A) do not match `s` or `k`. An orbit left with fewer than two members
39
+ * is dropped. It is, per member by code point, the gap since the last
40
+ * member and the zigzag-coded step to the next member of its orbit, the last
41
+ * member stepping back to the first; the step is doubled, plus one in an
42
+ * orbit of two, whose walk then ends without reading the table again.
43
+ * **The fold runs** `REGEX_FOLD_SPANS` are the same code points as maximal runs, at a fixed
44
+ * width so `regexCompile` can binary-search them without reading the fold
45
+ * table: a class with no folding code point, or none in its gaps, such as
46
+ * `\S` under `i`, then never decodes it. **The fold index** `REGEX_FOLD_INDEX`
47
+ * holds, per block of `FOLD_BLOCK` members, the first member and the offset
48
+ * of its step, so `regexCompile` reads only the block a code point falls in
49
+ * rather than decoding the table.
50
+ *
51
+ * **The oracle** `tests/link/std_regex_unicode/oracle.ts` is what this
52
+ * Node's `RegExp` answers over the sample text the test builds: per property,
53
+ * the runs `\p{…}+` finds, as a count and a digest of their byte offsets; per
54
+ * folded code point, the same for the code point under `iu`.
55
+ */
56
+ import { createHash } from "node:crypto"
57
+ import fs from "node:fs"
58
+ import path from "node:path"
59
+ import { fileURLToPath } from "node:url"
60
+
61
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..")
62
+ const target = path.join(root, "std", "regex.ts")
63
+ const oracleFile = path.join(root, "tests", "link", "std_regex_unicode", "oracle.ts")
64
+ const cacheDir = path.join(root, "build", "ucd")
65
+
66
+ const UNICODE_VERSION = "16.0.0"
67
+ const UCD = `https://www.unicode.org/Public/${UNICODE_VERSION}/ucd`
68
+ /** Each file the tables read, and its sha256. */
69
+ const FILES = {
70
+ "CaseFolding.txt": "6f1f9c588eb4a5c718d9e8f93b782685e5c7fec872cf05e8e6878053599e09bb",
71
+ "DerivedCoreProperties.txt": "39d35161f2954497f69e08bdb9e701493f476a3d30222de20028feda36c1dabd",
72
+ "DerivedNormalizationProps.txt": "4d4c03892dea9146d674b686e495df2d55a28d071ac474041d73518f887abddc",
73
+ "PropList.txt": "53d614508e2a0b2305a8aa21cd60d993de9326cdf65993660dfcce4503548583",
74
+ "PropertyAliases.txt": "33a9f2266ad6b8e8de05c0ea3dfac411ac62cf8839ff1c94057471e4c5f6a2b3",
75
+ "PropertyValueAliases.txt": "440fd3e5460b9bfe31da67b6f923992e1989d31fe2ed91e091c4b8f8e2620bf9",
76
+ "ScriptExtensions.txt": "049117ce26b9769fe2749b06eef51a50a89faef4a97764dd2d81daa715980700",
77
+ "Scripts.txt": "9e88f0a677df47311106340be8ede2ecdacd9c1c931831218d2be6d5508e0039",
78
+ "emoji/emoji-data.txt": "f1365a5173eee18e1f98b240cdc492e84a25f1ce7e0c9d1094eb29c41a22696a",
79
+ "extracted/DerivedBinaryProperties.txt": "1ed4d4791c0e34fcad4dfcb5dd4c4122e16428241b75452f05d780ffa661f89d",
80
+ "extracted/DerivedGeneralCategory.txt": "7676ab755a41ef82108460238569e60ad65c191ddafe61b36c6765ec1353f293",
81
+ }
82
+
83
+ /** ECMA-262's table of binary Unicode properties, by long name; `Any`, `ASCII` and `Assigned` are its own. */
84
+ const BINARY = [
85
+ "ASCII",
86
+ "ASCII_Hex_Digit",
87
+ "Alphabetic",
88
+ "Any",
89
+ "Assigned",
90
+ "Bidi_Control",
91
+ "Bidi_Mirrored",
92
+ "Case_Ignorable",
93
+ "Cased",
94
+ "Changes_When_Casefolded",
95
+ "Changes_When_Casemapped",
96
+ "Changes_When_Lowercased",
97
+ "Changes_When_NFKC_Casefolded",
98
+ "Changes_When_Titlecased",
99
+ "Changes_When_Uppercased",
100
+ "Dash",
101
+ "Default_Ignorable_Code_Point",
102
+ "Deprecated",
103
+ "Diacritic",
104
+ "Emoji",
105
+ "Emoji_Component",
106
+ "Emoji_Modifier",
107
+ "Emoji_Modifier_Base",
108
+ "Emoji_Presentation",
109
+ "Extended_Pictographic",
110
+ "Extender",
111
+ "Grapheme_Base",
112
+ "Grapheme_Extend",
113
+ "Hex_Digit",
114
+ "IDS_Binary_Operator",
115
+ "IDS_Trinary_Operator",
116
+ "ID_Continue",
117
+ "ID_Start",
118
+ "Ideographic",
119
+ "Join_Control",
120
+ "Logical_Order_Exception",
121
+ "Lowercase",
122
+ "Math",
123
+ "Noncharacter_Code_Point",
124
+ "Pattern_Syntax",
125
+ "Pattern_White_Space",
126
+ "Quotation_Mark",
127
+ "Radical",
128
+ "Regional_Indicator",
129
+ "Sentence_Terminal",
130
+ "Soft_Dotted",
131
+ "Terminal_Punctuation",
132
+ "Unified_Ideograph",
133
+ "Uppercase",
134
+ "Variation_Selector",
135
+ "White_Space",
136
+ "XID_Continue",
137
+ "XID_Start",
138
+ ]
139
+
140
+ /** The General_Category groups, as the values they are the union of. */
141
+ const GROUPS = {
142
+ C: ["Cc", "Cf", "Cn", "Co", "Cs"],
143
+ L: ["Ll", "Lm", "Lo", "Lt", "Lu"],
144
+ LC: ["Ll", "Lt", "Lu"],
145
+ M: ["Mc", "Me", "Mn"],
146
+ N: ["Nd", "Nl", "No"],
147
+ P: ["Pc", "Pd", "Pe", "Pf", "Pi", "Po", "Ps"],
148
+ S: ["Sc", "Sk", "Sm", "So"],
149
+ Z: ["Zl", "Zp", "Zs"],
150
+ }
151
+
152
+ /** Script values ECMA-262 lists but no character has, which V8 refuses. */
153
+ const NO_SCRIPT = new Set(["Hrkt"])
154
+
155
+ const MAX_CP = 0x10ffff
156
+
157
+ // ---- The UCD files --------------------------------------------------------------
158
+
159
+ const readUcd = async (name) => {
160
+ const file = path.join(cacheDir, UNICODE_VERSION, name)
161
+ let bytes = fs.existsSync(file) ? fs.readFileSync(file) : null
162
+ if (bytes === null) {
163
+ const res = await fetch(`${UCD}/${name}`)
164
+ if (!res.ok) {
165
+ throw new Error(`gen-regex-unicode: ${UCD}/${name}: HTTP ${res.status}`)
166
+ }
167
+ bytes = Buffer.from(await res.arrayBuffer())
168
+ }
169
+ const sum = createHash("sha256").update(bytes).digest("hex")
170
+ if (sum !== FILES[name]) {
171
+ throw new Error(`gen-regex-unicode: ${name} has sha256 ${sum}, not the pinned ${FILES[name]}`)
172
+ }
173
+ fs.mkdirSync(path.dirname(file), { recursive: true })
174
+ fs.writeFileSync(file, bytes)
175
+ return bytes.toString("utf8")
176
+ }
177
+
178
+ /** The data lines of a UCD file, split on `;` and trimmed, comments dropped. */
179
+ const records = (text) =>
180
+ text
181
+ .split("\n")
182
+ .map((line) => line.replace(/#.*/, "").trim())
183
+ .filter((line) => line !== "")
184
+ .map((line) => line.split(";").map((f) => f.trim()))
185
+
186
+ /** `XXXX` or `XXXX..YYYY` as [lo, hi]. */
187
+ const span = (field) => {
188
+ const [lo, hi] = field.split("..")
189
+ return [Number.parseInt(lo, 16), Number.parseInt(hi ?? lo, 16)]
190
+ }
191
+
192
+ // ---- Sets of code points, as sorted, merged [lo, hi] lists ----------------------
193
+
194
+ const normalize = (ranges) => {
195
+ const sorted = [...ranges].sort((a, b) => a[0] - b[0])
196
+ const out = []
197
+ for (const [lo, hi] of sorted) {
198
+ const last = out[out.length - 1]
199
+ if (last && lo <= last[1] + 1) {
200
+ last[1] = Math.max(last[1], hi)
201
+ } else {
202
+ out.push([lo, hi])
203
+ }
204
+ }
205
+ return out
206
+ }
207
+
208
+ const complement = (ranges) => {
209
+ const out = []
210
+ let from = 0
211
+ for (const [lo, hi] of ranges) {
212
+ if (lo > from) {
213
+ out.push([from, lo - 1])
214
+ }
215
+ from = hi + 1
216
+ }
217
+ if (from <= MAX_CP) {
218
+ out.push([from, MAX_CP])
219
+ }
220
+ return out
221
+ }
222
+
223
+ /** The ranges of every two-field record, grouped by the second field. */
224
+ const byValue = (text) => {
225
+ const map = new Map()
226
+ for (const f of records(text)) {
227
+ if (f.length !== 2) {
228
+ continue
229
+ }
230
+ if (!map.has(f[1])) {
231
+ map.set(f[1], [])
232
+ }
233
+ map.get(f[1]).push(span(f[0]))
234
+ }
235
+ return map
236
+ }
237
+
238
+ // ---- The encoding ---------------------------------------------------------------
239
+
240
+ const DIGIT0 = 48
241
+ /** The members of `REGEX_FOLD_DATA` per entry of `REGEX_FOLD_INDEX`. */
242
+ const FOLD_BLOCK = 16
243
+
244
+ const varint = (v) => {
245
+ if (!Number.isInteger(v) || v < 0) {
246
+ throw new Error(`gen-regex-unicode: cannot encode ${v}`)
247
+ }
248
+ const digits = [v & 31]
249
+ let rest = v >>> 5
250
+ while (rest > 0) {
251
+ digits.unshift(32 + (rest & 31))
252
+ rest >>>= 5
253
+ }
254
+ return String.fromCharCode(...digits.map((d) => DIGIT0 + d))
255
+ }
256
+
257
+ const encodeList = (ranges) => {
258
+ let s = varint(ranges.length)
259
+ let prev = -2
260
+ ranges.forEach(([lo, hi], i) => {
261
+ s += varint(i === 0 ? lo : lo - prev - 2) + varint(hi - lo)
262
+ prev = hi
263
+ })
264
+ return s
265
+ }
266
+
267
+ const zigzag = (v) => (v >= 0 ? v * 2 : -v * 2 - 1)
268
+
269
+ /** A JavaScript string literal of `s`, which holds only bytes 48 to 111. */
270
+ const literal = (s) => `"${s.replaceAll("\\", "\\\\")}"`
271
+
272
+ // ---- Reading the database ------------------------------------------------------
273
+
274
+ const load = async () => {
275
+ const text = {}
276
+ for (const name of Object.keys(FILES)) {
277
+ text[name] = await readUcd(name)
278
+ }
279
+
280
+ // Aliases: per property short name, its value aliases; and binary property aliases.
281
+ const propAliases = new Map()
282
+ for (const f of records(text["PropertyAliases.txt"])) {
283
+ propAliases.set(f[1], f)
284
+ }
285
+ const valueAliases = new Map()
286
+ for (const f of records(text["PropertyValueAliases.txt"])) {
287
+ if (!valueAliases.has(f[0])) {
288
+ valueAliases.set(f[0], [])
289
+ }
290
+ valueAliases.get(f[0]).push(f.slice(1))
291
+ }
292
+
293
+ const gc = byValue(text["extracted/DerivedGeneralCategory.txt"])
294
+ const binarySources = [
295
+ byValue(text["PropList.txt"]),
296
+ byValue(text["DerivedCoreProperties.txt"]),
297
+ byValue(text["emoji/emoji-data.txt"]),
298
+ byValue(text["extracted/DerivedBinaryProperties.txt"]),
299
+ byValue(text["DerivedNormalizationProps.txt"]),
300
+ ]
301
+ const binary = new Map()
302
+ for (const name of BINARY) {
303
+ let ranges = null
304
+ if (name === "Any") {
305
+ ranges = [[0, MAX_CP]]
306
+ } else if (name === "ASCII") {
307
+ ranges = [[0, 127]]
308
+ } else if (name === "Assigned") {
309
+ ranges = null
310
+ } else {
311
+ for (const src of binarySources) {
312
+ if (src.has(name)) {
313
+ ranges = normalize(src.get(name))
314
+ }
315
+ }
316
+ if (ranges === null) {
317
+ throw new Error(`gen-regex-unicode: no file lists ${name}`)
318
+ }
319
+ }
320
+ binary.set(name, ranges)
321
+ }
322
+
323
+ // General_Category: each value, then the groups.
324
+ const gcSets = new Map()
325
+ for (const [value, ranges] of gc) {
326
+ gcSets.set(value, normalize(ranges))
327
+ }
328
+ for (const [group, members] of Object.entries(GROUPS)) {
329
+ gcSets.set(group, normalize(members.flatMap((m) => gcSets.get(m))))
330
+ }
331
+
332
+ // Script: listed values, then Unknown (Zzzz) as everything unlisted.
333
+ const scriptLong = new Map()
334
+ for (const v of valueAliases.get("sc")) {
335
+ scriptLong.set(v[1], v[0])
336
+ }
337
+ const scRaw = byValue(text["Scripts.txt"])
338
+ const sc = new Map()
339
+ for (const [long, ranges] of scRaw) {
340
+ sc.set(scriptLong.get(long), normalize(ranges))
341
+ }
342
+ sc.set("Zzzz", complement(normalize([...sc.values()].flat())))
343
+ // Script_Extensions: a code point listed in ScriptExtensions.txt has those
344
+ // scripts; any other has its Script.
345
+ const scxOf = new Map()
346
+ for (const f of records(text["ScriptExtensions.txt"])) {
347
+ const [lo, hi] = span(f[0])
348
+ for (let c = lo; c <= hi; c++) {
349
+ scxOf.set(c, f[1].split(/\s+/))
350
+ }
351
+ }
352
+ const scx = new Map()
353
+ for (const [short, ranges] of sc) {
354
+ const extra = []
355
+ for (const [c, list] of scxOf) {
356
+ if (list.includes(short)) {
357
+ extra.push([c, c])
358
+ }
359
+ }
360
+ const kept = []
361
+ for (const [lo, hi] of ranges) {
362
+ for (let c = lo; c <= hi; c++) {
363
+ if (!scxOf.has(c)) {
364
+ kept.push([c, c])
365
+ }
366
+ }
367
+ }
368
+ scx.set(short, normalize([...kept, ...extra]))
369
+ }
370
+
371
+ // Simple case folding, as orbits of code points above ASCII.
372
+ const foldTo = new Map()
373
+ for (const f of records(text["CaseFolding.txt"])) {
374
+ if (f[1] === "C" || f[1] === "S") {
375
+ foldTo.set(Number.parseInt(f[0], 16), Number.parseInt(f[2], 16))
376
+ }
377
+ }
378
+ const orbitOf = new Map()
379
+ for (const [c, t] of foldTo) {
380
+ if (!orbitOf.has(t)) {
381
+ orbitOf.set(t, new Set([t]))
382
+ }
383
+ orbitOf.get(t).add(c)
384
+ }
385
+ const orbits = []
386
+ for (const set of orbitOf.values()) {
387
+ const members = [...set].filter((c) => c >= 128).sort((a, b) => a - b)
388
+ if (members.length >= 2) {
389
+ orbits.push(members)
390
+ }
391
+ }
392
+
393
+ return { propAliases, valueAliases, binary, gcSets, sc, scx, orbits }
394
+ }
395
+
396
+ // ---- The tables -----------------------------------------------------------------
397
+
398
+ /** Every name a `\p{…}` may use, as [key, set, how] where `how` is `g`, `b` or `s`. */
399
+ const names = (db) => {
400
+ const out = []
401
+ for (const v of db.valueAliases.get("gc")) {
402
+ // [short, long, ...more]
403
+ const set = db.gcSets.get(v[0])
404
+ for (const alias of new Set(v)) {
405
+ out.push({ key: `g${alias}`, gc: v[0], set })
406
+ }
407
+ }
408
+ for (const name of BINARY) {
409
+ const aliases = new Set([name])
410
+ for (const f of db.propAliases.values()) {
411
+ if (f[1] === name) {
412
+ for (const a of f) {
413
+ aliases.add(a)
414
+ }
415
+ }
416
+ }
417
+ for (const alias of aliases) {
418
+ out.push({ key: `b${alias}`, binary: name })
419
+ }
420
+ }
421
+ for (const v of db.valueAliases.get("sc")) {
422
+ if (NO_SCRIPT.has(v[0])) {
423
+ continue
424
+ }
425
+ for (const alias of new Set(v)) {
426
+ out.push({ key: `s${alias}`, script: v[0] })
427
+ }
428
+ }
429
+ return out
430
+ }
431
+
432
+ const tables = (db) => {
433
+ let data = ""
434
+ const at = new Map()
435
+ const offset = (ranges) => {
436
+ const enc = encodeList(ranges)
437
+ if (!at.has(enc)) {
438
+ at.set(enc, data.length)
439
+ data += enc
440
+ }
441
+ return at.get(enc)
442
+ }
443
+ const cn = db.gcSets.get("Cn")
444
+ let index = "|"
445
+ for (const n of names(db)) {
446
+ let value = ""
447
+ if (n.gc !== undefined) {
448
+ value = `${offset(n.set)}`
449
+ } else if (n.binary !== undefined) {
450
+ const set = db.binary.get(n.binary)
451
+ value = set === null ? `~${offset(cn)}` : `${offset(set)}`
452
+ } else {
453
+ value = `${offset(db.sc.get(n.script))},${offset(db.scx.get(n.script))}`
454
+ }
455
+ index += `${n.key}=${value}|`
456
+ }
457
+ const members = db.orbits
458
+ .flatMap((o) => o.map((c, i) => [c, o[(i + 1) % o.length], o.length === 2 ? 1 : 0]))
459
+ .sort((a, b) => a[0] - b[0])
460
+ let fold = ""
461
+ let prev = 0
462
+ // Per block of `FOLD_BLOCK` members, the first member and where its step starts.
463
+ const blocks = []
464
+ members.forEach(([c, to, pair], k) => {
465
+ fold += varint(c - prev)
466
+ if (k % FOLD_BLOCK === 0) {
467
+ blocks.push([c, fold.length])
468
+ }
469
+ fold += varint(zigzag(to - c) * 2 + pair)
470
+ prev = c
471
+ })
472
+ // The folding code points as maximal runs, each end four base-32 digits.
473
+ const runs = []
474
+ for (const [c] of members) {
475
+ if (runs.length > 0 && runs[runs.length - 1][1] === c - 1) {
476
+ runs[runs.length - 1][1] = c
477
+ } else {
478
+ runs.push([c, c])
479
+ }
480
+ }
481
+ const fixed = (v) => {
482
+ if (v >= 1 << 20) {
483
+ throw new Error(`gen-regex-unicode: ${v} needs more than four digits`)
484
+ }
485
+ return String.fromCharCode(...[15, 10, 5, 0].map((b) => DIGIT0 + ((v >>> b) & 31)))
486
+ }
487
+ const spans = runs.map(([lo, hi]) => fixed(lo) + fixed(hi)).join("")
488
+ const foldIndex = blocks.map(([first, stepAt]) => fixed(first) + fixed(stepAt)).join("")
489
+ return { index, data, fold, spans, foldIndex }
490
+ }
491
+
492
+ // ---- The region ----------------------------------------------------------------
493
+
494
+ const BEGIN = "// gen-regex-unicode:begin"
495
+ const END = "// gen-regex-unicode:end"
496
+
497
+ const region = (t) =>
498
+ [
499
+ `${BEGIN} -- generated by scripts/gen-regex-unicode.mjs; edit that, not this.`,
500
+ `/** \`\\p{…}\` names, \`|key=offset|\`; the key is \`g\`, \`b\` or \`s\` and the name (Unicode ${UNICODE_VERSION}). */`,
501
+ "const REGEX_PROPERTY_NAMES: string =",
502
+ ` ${literal(t.index)}`,
503
+ "/** The range lists `REGEX_PROPERTY_NAMES` points into, in base-32 digits from `0`. */",
504
+ "const REGEX_PROPERTY_DATA: string =",
505
+ ` ${literal(t.data)}`,
506
+ "/** Simple case folding above ASCII: per member of an orbit, its gap and the zigzag step to the next member, doubled, plus one in a pair. */",
507
+ "const REGEX_FOLD_DATA: string =",
508
+ ` ${literal(t.fold)}`,
509
+ "/** The code points `REGEX_FOLD_DATA` folds, as runs: per run its first and last, four base-32 digits each. */",
510
+ "const REGEX_FOLD_SPANS: string =",
511
+ ` ${literal(t.spans)}`,
512
+ `/** Per block of ${FOLD_BLOCK} members in \`REGEX_FOLD_DATA\`, the first and where its step starts, four base-32 digits each. */`,
513
+ "const REGEX_FOLD_INDEX: string =",
514
+ ` ${literal(t.foldIndex)}`,
515
+ END,
516
+ ].join("\n")
517
+
518
+ // ---- The oracle ----------------------------------------------------------------
519
+
520
+ /**
521
+ * The sample text's code points, as the test builds them: every code point
522
+ * up to U+323AF and from U+E0000 to U+E01EF, one in 251 of the rest and the
523
+ * plane edges in `EDGES`, less the surrogates and the four ASCII letters
524
+ * whose folding crosses ASCII (`s`, `S`, `k` and `K`), which would join ſ and
525
+ * the Kelvin sign to their neighbours' runs.
526
+ */
527
+ const SKIP = new Set([0x53, 0x73, 0x4b, 0x6b])
528
+ // The ends of the unassigned run after plane 3, of planes 4 to 13, of plane
529
+ // 14's tags and of the private-use planes 15 and 16, with their noncharacters.
530
+ const EDGES = new Set([
531
+ 0x323b0, 0x3fffe, 0x3ffff, 0x40000, 0xdfffe, 0xdffff, 0xe01f0, 0xefffe, 0xeffff, 0xf0000, 0xffffd, 0xffffe,
532
+ 0xfffff, 0x100000, 0x10fffd, 0x10fffe, 0x10ffff,
533
+ ])
534
+ // `\w`, `\b` and `\B` under `i` around ſ and the Kelvin sign, which are word
535
+ // characters there, and a shorthand before a folded atom above ASCII.
536
+ const WORD_TEXT = "aſ ſa \u212a k\u212ab s_ſ é É aÉ ſ\u212a -ſ- x"
537
+ const WORD_PATTERNS = [
538
+ "\\w+",
539
+ "\\W+",
540
+ "[\\w]+",
541
+ "[^\\w]+",
542
+ "\\b.",
543
+ ".\\b",
544
+ "\\B.",
545
+ ".\\B",
546
+ "\\b\\w+\\b",
547
+ "\\wé",
548
+ "\\Wé",
549
+ ]
550
+ const sample = () => {
551
+ const out = []
552
+ for (let c = 0; c <= MAX_CP; c++) {
553
+ const dense = c <= 0x323af || (c >= 0xe0000 && c <= 0xe01ef)
554
+ if ((dense || c % 251 === 0 || EDGES.has(c)) && !(c >= 0xd800 && c <= 0xdfff) && !SKIP.has(c)) {
555
+ out.push(c)
556
+ }
557
+ }
558
+ return out
559
+ }
560
+
561
+ const utf8Width = (c) => {
562
+ if (c < 0x80) {
563
+ return 1
564
+ }
565
+ if (c < 0x800) {
566
+ return 2
567
+ }
568
+ return c < 0x10000 ? 3 : 4
569
+ }
570
+
571
+ /** The runs of consecutive code points that `test` accepts: [count, digest]. */
572
+ const digestRuns = (cps, test) => {
573
+ let count = 0
574
+ let digest = 0
575
+ let off = 0
576
+ let start = -1
577
+ const close = (end) => {
578
+ count += 1
579
+ digest = (Math.imul(digest, 31) + start * 7 + end) | 0
580
+ start = -1
581
+ }
582
+ for (const c of cps) {
583
+ if (test(c)) {
584
+ if (start < 0) {
585
+ start = off
586
+ }
587
+ } else if (start >= 0) {
588
+ close(off)
589
+ }
590
+ off += utf8Width(c)
591
+ }
592
+ if (start >= 0) {
593
+ close(off)
594
+ }
595
+ return [count, digest]
596
+ }
597
+
598
+ /** What Node's `RegExp` says of each name and fold, over the sample text. */
599
+ const oracle = (db, cps) => {
600
+ const props = []
601
+ for (const n of names(db)) {
602
+ const ns = n.key[0]
603
+ const name = n.key.slice(1)
604
+ const sources = ns === "s" ? [`Script=${name}`, `scx=${name}`] : [name]
605
+ for (const src of sources) {
606
+ const re = new RegExp(`^\\p{${src}}$`, "u")
607
+ const [count, digest] = digestRuns(cps, (c) => re.test(String.fromCodePoint(c)))
608
+ props.push(` "${src} ${count} ${digest}",`)
609
+ }
610
+ }
611
+ // Under `i`, a sample of property and range classes, and each folded code point.
612
+ const folds = []
613
+ const iClasses = [
614
+ "\\p{Lu}",
615
+ "\\p{Ll}",
616
+ "\\P{Ll}",
617
+ "\\P{Lu}",
618
+ "[^\\P{Ll}]",
619
+ "[^\\P{Lu}]",
620
+ "\\p{Script=Greek}",
621
+ "[\\u{100}-\\u{17e}]",
622
+ "[^\\p{Lt}]",
623
+ "[\\u{80}-\\u{10ffff}]",
624
+ "\\S",
625
+ "\\w",
626
+ "\\W",
627
+ "[\\w]",
628
+ "[\\W]",
629
+ "\\D",
630
+ ]
631
+ for (const cls of iClasses) {
632
+ const re = new RegExp(`^${cls}$`, "iu")
633
+ // Nothing folds across ASCII but `\w` and `\W`, so ſ and the Kelvin sign
634
+ // meet every other class as they are, as under `u` alone.
635
+ const across = /\\[wW]/.test(cls) ? re : new RegExp(`^${cls}$`, "u")
636
+ const test = (c) => (c === 0x17f || c === 0x212a ? across : re).test(String.fromCodePoint(c))
637
+ const [count, digest] = digestRuns(cps, test)
638
+ folds.push(` "${cls.replaceAll("\\", "\\\\")} ${count} ${digest}",`)
639
+ }
640
+ const foldText = db.orbits.flat().sort((a, b) => a - b)
641
+ const lits = []
642
+ for (const c of foldText) {
643
+ const re = new RegExp(`^\\u{${c.toString(16)}}$`, "iu")
644
+ const [count, digest] = digestRuns(foldText, (d) => re.test(String.fromCodePoint(d)))
645
+ lits.push(` "${c} ${count} ${digest}",`)
646
+ }
647
+ // Patterns under `i` over `WORD_TEXT`: the runs `exec` finds one after another.
648
+ const words = []
649
+ for (const src of WORD_PATTERNS) {
650
+ const re = new RegExp(src, "giu")
651
+ let count = 0
652
+ let digest = 0
653
+ let m = re.exec(WORD_TEXT)
654
+ while (m !== null) {
655
+ const start = Buffer.byteLength(WORD_TEXT.slice(0, m.index))
656
+ const end = start + Buffer.byteLength(m[0])
657
+ count += 1
658
+ digest = (Math.imul(digest, 31) + start * 7 + end) | 0
659
+ m = re.exec(WORD_TEXT)
660
+ }
661
+ words.push(` "${src.replaceAll("\\", "\\\\")} ${count} ${digest}",`)
662
+ }
663
+ return [
664
+ "// Generated by scripts/gen-regex-unicode.mjs from this Node's RegExp; do not edit.",
665
+ `// Unicode ${UNICODE_VERSION}. Each row is a name, pattern or code point, the number of runs it matches and their digest.`,
666
+ "",
667
+ "/** Per `\\p{…}` name: the runs `\\p{name}+` finds in the sample text, and their digest. */",
668
+ "export const propertyRows = (): string[] => [",
669
+ ...props,
670
+ "]",
671
+ "",
672
+ "/** Per class under `i`: the same, over the sample text. */",
673
+ "export const foldClassRows = (): string[] => [",
674
+ ...folds,
675
+ "]",
676
+ "",
677
+ "/** The text the word rows run over. */",
678
+ `export const wordText = (): string => "${WORD_TEXT}"`,
679
+ "",
680
+ "/** Per pattern under `i`: the runs it finds in `wordText`, one after another. */",
681
+ "export const wordRows = (): string[] => [",
682
+ ...words,
683
+ "]",
684
+ "",
685
+ "/** Every code point that folds to another above ASCII, in order. */",
686
+ "export const foldCodePoints = (): i32[] => [",
687
+ ...foldText.map((c) => ` ${c},`),
688
+ "]",
689
+ "",
690
+ "/** Per folded code point: the same for the code point under `i`, over the text of `foldCodePoints`. */",
691
+ "export const foldCharRows = (): string[] => [",
692
+ ...lits,
693
+ "]",
694
+ "",
695
+ ].join("\n")
696
+ }
697
+
698
+ // ---- Checking against Node -----------------------------------------------------
699
+
700
+ const checkNode = (db) => {
701
+ if (process.versions.unicode !== UNICODE_VERSION.replace(/\.0$/, "")) {
702
+ throw new Error(
703
+ `gen-regex-unicode: this Node has Unicode ${process.versions.unicode}, not ${UNICODE_VERSION}`
704
+ )
705
+ }
706
+ const bad = []
707
+ const compare = (src, ranges, negate) => {
708
+ let re = null
709
+ try {
710
+ re = new RegExp(`^\\p{${src}}$`, "u")
711
+ } catch {
712
+ bad.push(`\\p{${src}}: Node refuses it`)
713
+ return
714
+ }
715
+ let i = 0
716
+ for (let c = 0; c <= MAX_CP; c++) {
717
+ while (i < ranges.length && ranges[i][1] < c) {
718
+ i++
719
+ }
720
+ const ours = (i < ranges.length && ranges[i][0] <= c) !== negate
721
+ if (ours !== re.test(String.fromCodePoint(c))) {
722
+ bad.push(`\\p{${src}} at U+${c.toString(16)}`)
723
+ return
724
+ }
725
+ }
726
+ }
727
+ for (const n of names(db)) {
728
+ const name = n.key.slice(1)
729
+ if (n.gc !== undefined) {
730
+ compare(name, n.set, false)
731
+ } else if (n.binary !== undefined) {
732
+ const set = db.binary.get(n.binary)
733
+ compare(name, set ?? db.gcSets.get("Cn"), set === null)
734
+ } else {
735
+ compare(`Script=${name}`, db.sc.get(n.script), false)
736
+ compare(`scx=${name}`, db.scx.get(n.script), false)
737
+ }
738
+ }
739
+ // A General_Category or Script alias is ours exactly when Node accepts it.
740
+ for (const [prop, ns] of [
741
+ ["gc", "g"],
742
+ ["sc", "s"],
743
+ ]) {
744
+ const ours = new Set(
745
+ names(db)
746
+ .filter((n) => n.key[0] === ns)
747
+ .map((n) => n.key.slice(1))
748
+ )
749
+ for (const alias of db.valueAliases.get(prop).flat()) {
750
+ let accepted = true
751
+ try {
752
+ new RegExp(`\\p{${prop === "gc" ? alias : `Script=${alias}`}}`, "u")
753
+ } catch {
754
+ accepted = false
755
+ }
756
+ if (accepted !== ours.has(alias)) {
757
+ bad.push(`${prop}=${alias}: Node ${accepted ? "accepts" : "refuses"} it and the tables do not`)
758
+ }
759
+ }
760
+ }
761
+ // Folding: every orbit member matches exactly its orbit's members above ASCII under `iu`.
762
+ for (const o of db.orbits) {
763
+ for (const c of o) {
764
+ const re = new RegExp(`^\\u{${c.toString(16)}}$`, "iu")
765
+ for (const d of o) {
766
+ if (!re.test(String.fromCodePoint(d))) {
767
+ bad.push(`U+${c.toString(16)} does not fold to U+${d.toString(16)}`)
768
+ }
769
+ }
770
+ }
771
+ }
772
+ const folded = new Set(db.orbits.flat())
773
+ for (let c = 128; c <= MAX_CP; c++) {
774
+ if (folded.has(c) || c === 0x17f || c === 0x212a || (c >= 0xd800 && c <= 0xdfff)) {
775
+ continue
776
+ }
777
+ const s = String.fromCodePoint(c)
778
+ if (s.toLowerCase() !== s && new RegExp(`^\\u{${c.toString(16)}}$`, "iu").test(s.toLowerCase())) {
779
+ bad.push(`U+${c.toString(16)} folds in Node but has no orbit`)
780
+ }
781
+ }
782
+ return bad
783
+ }
784
+
785
+ // ---- Main -----------------------------------------------------------------------
786
+
787
+ const ucd = await load()
788
+ const built = tables(ucd)
789
+ const source = fs.readFileSync(target, "utf8")
790
+ const begin = source.indexOf(BEGIN)
791
+ const regionEnd = source.indexOf(END)
792
+ if (begin < 0 || regionEnd < begin) {
793
+ throw new Error(`gen-regex-unicode: no ${BEGIN} … ${END} region in std/regex.ts`)
794
+ }
795
+ const next = source.slice(0, begin) + region(built) + source.slice(regionEnd + END.length)
796
+ const nextOracle = oracle(ucd, sample())
797
+
798
+ if (process.argv.includes("--check")) {
799
+ const bad = checkNode(ucd)
800
+ if (next !== source) {
801
+ bad.push("std/regex.ts: the tables differ from the generator's; run node scripts/gen-regex-unicode.mjs")
802
+ }
803
+ if (!fs.existsSync(oracleFile) || fs.readFileSync(oracleFile, "utf8") !== nextOracle) {
804
+ bad.push(`${path.relative(root, oracleFile)} differs from the generator's`)
805
+ }
806
+ for (const line of bad) {
807
+ console.error(`gen-regex-unicode: ${line}`)
808
+ }
809
+ if (bad.length > 0) {
810
+ process.exit(1)
811
+ }
812
+ console.log(
813
+ `gen-regex-unicode: the tables match Unicode ${UNICODE_VERSION} and this Node's RegExp (${built.index.length + built.data.length + built.fold.length + built.spans.length} bytes)`
814
+ )
815
+ } else {
816
+ fs.writeFileSync(target, next)
817
+ fs.mkdirSync(path.dirname(oracleFile), { recursive: true })
818
+ fs.writeFileSync(oracleFile, nextOracle)
819
+ console.log(
820
+ `gen-regex-unicode: names ${built.index.length} bytes, ranges ${built.data.length}, folds ${built.fold.length}, fold runs ${built.spans.length}; wrote std/regex.ts and ${path.relative(root, oracleFile)}`
821
+ )
822
+ }