nomen-lang 0.0.14 → 0.0.16

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 (2) hide show
  1. package/dist/index.mjs +2091 -76
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,12 +1,1631 @@
1
1
  #! /usr/bin/env node
2
2
  import { execFileSync, execSync } from "node:child_process";
3
- import fs from "node:fs";
4
- import path from "node:path";
3
+ import fs, { stat, unwatchFile, watch, watchFile } from "node:fs";
4
+ import * as sp from "node:path";
5
+ import path, { join, resolve, sep } from "node:path";
6
+ import { EventEmitter } from "node:events";
7
+ import { lstat, open, readdir, realpath, stat as stat$1 } from "node:fs/promises";
8
+ import { Readable } from "node:stream";
9
+ import { type } from "node:os";
5
10
  import { fileURLToPath } from "node:url";
6
- //#region node_modules/chokidar/index.mjs
7
- var chokidar_default = { watch() {
8
- throw new Error("chokidar stub: watch mode unavailable");
9
- } };
11
+ //#region ../node_modules/.pnpm/readdirp@5.1.1/node_modules/readdirp/index.js
12
+ const EntryTypes = {
13
+ FILE_TYPE: "files",
14
+ DIR_TYPE: "directories",
15
+ FILE_DIR_TYPE: "files_directories",
16
+ EVERYTHING_TYPE: "all"
17
+ };
18
+ const defaultOptions = {
19
+ root: ".",
20
+ fileFilter: (_entryInfo) => true,
21
+ directoryFilter: (_entryInfo) => true,
22
+ type: EntryTypes.FILE_TYPE,
23
+ lstat: false,
24
+ depth: 2147483648,
25
+ alwaysStat: false,
26
+ highWaterMark: 256
27
+ };
28
+ Object.freeze(defaultOptions);
29
+ const RECURSIVE_ERROR_CODE = "READDIRP_RECURSIVE_ERROR";
30
+ const NORMAL_FLOW_ERRORS = /* @__PURE__ */ new Set([
31
+ "ENOENT",
32
+ "EPERM",
33
+ "EACCES",
34
+ "ELOOP",
35
+ RECURSIVE_ERROR_CODE
36
+ ]);
37
+ const ALL_TYPES = [
38
+ EntryTypes.DIR_TYPE,
39
+ EntryTypes.EVERYTHING_TYPE,
40
+ EntryTypes.FILE_DIR_TYPE,
41
+ EntryTypes.FILE_TYPE
42
+ ];
43
+ const DIR_TYPES = /* @__PURE__ */ new Set([
44
+ EntryTypes.DIR_TYPE,
45
+ EntryTypes.EVERYTHING_TYPE,
46
+ EntryTypes.FILE_DIR_TYPE
47
+ ]);
48
+ const FILE_TYPES = /* @__PURE__ */ new Set([
49
+ EntryTypes.EVERYTHING_TYPE,
50
+ EntryTypes.FILE_DIR_TYPE,
51
+ EntryTypes.FILE_TYPE
52
+ ]);
53
+ const isNormalFlowError = (error) => NORMAL_FLOW_ERRORS.has(error.code);
54
+ const wantBigintFsStats = process.platform === "win32";
55
+ const emptyFn = (_entryInfo) => true;
56
+ const normalizeFilter = (filter) => {
57
+ if (filter === void 0) return emptyFn;
58
+ if (typeof filter === "function") return filter;
59
+ if (typeof filter === "string") {
60
+ const fl = filter.trim();
61
+ return (entry) => entry.basename === fl;
62
+ }
63
+ if (Array.isArray(filter)) {
64
+ const trItems = filter.map((item) => item.trim());
65
+ return (entry) => trItems.some((f) => entry.basename === f);
66
+ }
67
+ return emptyFn;
68
+ };
69
+ var ReaddirpStream = class extends Readable {
70
+ /**
71
+ * Directories discovered but not yet emitted from. Listings are read
72
+ * lazily (on pop, plus one prefetch) instead of eagerly on discovery:
73
+ * keeping whole listings for every queued dir balloons RAM on wide trees.
74
+ */
75
+ parents;
76
+ reading;
77
+ parent;
78
+ _stat;
79
+ _maxDepth;
80
+ _wantsDir;
81
+ _wantsFile;
82
+ _wantsEverything;
83
+ _root;
84
+ _isDirent;
85
+ _statsProp;
86
+ _rdOptions;
87
+ _fileFilter;
88
+ _directoryFilter;
89
+ _relStart;
90
+ constructor(options = {}) {
91
+ super({
92
+ objectMode: true,
93
+ autoDestroy: true,
94
+ highWaterMark: options.highWaterMark ?? defaultOptions.highWaterMark
95
+ });
96
+ const opts = {
97
+ ...defaultOptions,
98
+ ...options
99
+ };
100
+ const root = opts.root ?? defaultOptions.root;
101
+ const type = opts.type ?? defaultOptions.type;
102
+ this._fileFilter = normalizeFilter(opts.fileFilter);
103
+ this._directoryFilter = normalizeFilter(opts.directoryFilter);
104
+ const statMethod = opts.lstat ? lstat : stat$1;
105
+ if (wantBigintFsStats) this._stat = (path) => statMethod(path, { bigint: true });
106
+ else this._stat = statMethod;
107
+ this._maxDepth = opts.depth != null && Number.isSafeInteger(opts.depth) ? opts.depth : defaultOptions.depth;
108
+ this._wantsDir = DIR_TYPES.has(type);
109
+ this._wantsFile = FILE_TYPES.has(type);
110
+ this._wantsEverything = type === EntryTypes.EVERYTHING_TYPE;
111
+ this._root = resolve(root);
112
+ this._relStart = this._root.endsWith(sep) ? this._root.length : this._root.length + 1;
113
+ this._isDirent = !opts.alwaysStat;
114
+ this._statsProp = this._isDirent ? "dirent" : "stats";
115
+ this._rdOptions = {
116
+ encoding: "utf8",
117
+ withFileTypes: this._isDirent
118
+ };
119
+ const rootDir = {
120
+ path: this._root,
121
+ depth: 1
122
+ };
123
+ rootDir.pending = this._exploreDir(this._root, 1);
124
+ this.parents = [rootDir];
125
+ this.reading = false;
126
+ this.parent = void 0;
127
+ }
128
+ async _read(batch) {
129
+ if (this.reading) return;
130
+ this.reading = true;
131
+ try {
132
+ while (!this.destroyed && batch > 0) {
133
+ const par = this.parent;
134
+ const fil = par && par.files;
135
+ if (fil && fil.length > 0) {
136
+ const { path, depth } = par;
137
+ const slice = fil.splice(0, batch).map((dirent) => this._formatEntry(dirent, path));
138
+ const awaited = this._isDirent ? slice : await Promise.all(slice);
139
+ for (const entry of awaited) {
140
+ if (!entry) continue;
141
+ if (this.destroyed) return;
142
+ let entryType = this._getEntryType(entry);
143
+ if (typeof entryType !== "string") entryType = await entryType;
144
+ if (entryType === "directory" && this._directoryFilter(entry)) {
145
+ if (depth <= this._maxDepth) this.parents.push({
146
+ path: entry.fullPath,
147
+ depth: depth + 1
148
+ });
149
+ if (this._wantsDir) {
150
+ this.push(entry);
151
+ batch--;
152
+ }
153
+ } else if ((entryType === "file" || this._includeAsFile(entry)) && this._fileFilter(entry)) {
154
+ if (this._wantsFile) {
155
+ this.push(entry);
156
+ batch--;
157
+ }
158
+ }
159
+ }
160
+ } else {
161
+ const parent = this.parents.pop();
162
+ if (!parent) {
163
+ this.push(null);
164
+ break;
165
+ }
166
+ const dir = parent.pending ?? this._exploreDir(parent.path, parent.depth);
167
+ const next = this.parents[this.parents.length - 1];
168
+ if (next && !next.pending) next.pending = this._exploreDir(next.path, next.depth);
169
+ this.parent = await dir;
170
+ if (this.destroyed) return;
171
+ }
172
+ }
173
+ } catch (error) {
174
+ this.destroy(error);
175
+ } finally {
176
+ this.reading = false;
177
+ }
178
+ }
179
+ async _exploreDir(path, depth) {
180
+ let files;
181
+ try {
182
+ files = await readdir(path, this._rdOptions);
183
+ } catch (error) {
184
+ this._onError(error);
185
+ }
186
+ return {
187
+ files,
188
+ depth,
189
+ path
190
+ };
191
+ }
192
+ _formatEntry(dirent, path) {
193
+ const basename = this._isDirent ? dirent.name : dirent;
194
+ const fullPath = join(path, basename);
195
+ const entry = {
196
+ path: fullPath.slice(this._relStart),
197
+ fullPath,
198
+ basename
199
+ };
200
+ if (this._isDirent) {
201
+ entry.dirent = dirent;
202
+ return entry;
203
+ }
204
+ return this._stat(fullPath).then((stats) => {
205
+ entry.stats = stats;
206
+ return entry;
207
+ }, (err) => {
208
+ this._onError(err);
209
+ });
210
+ }
211
+ _onError(err) {
212
+ if (isNormalFlowError(err) && !this.destroyed) this.emit("warn", err);
213
+ else this.destroy(err);
214
+ }
215
+ _getEntryType(entry) {
216
+ if (!entry || !(this._statsProp in entry)) return "";
217
+ const stats = entry[this._statsProp];
218
+ if (stats.isFile()) return "file";
219
+ if (stats.isDirectory()) return "directory";
220
+ if (stats.isSymbolicLink()) return this._getSymlinkEntryType(entry);
221
+ return "";
222
+ }
223
+ async _getSymlinkEntryType(entry) {
224
+ const full = entry.fullPath;
225
+ try {
226
+ const entryRealPath = await realpath(full);
227
+ const entryRealPathStats = await lstat(entryRealPath);
228
+ if (entryRealPathStats.isFile()) return "file";
229
+ if (entryRealPathStats.isDirectory()) {
230
+ const len = entryRealPath.length;
231
+ if (full.startsWith(entryRealPath) && full[len] === sep) {
232
+ const recursiveError = /* @__PURE__ */ new Error(`Circular symlink detected: "${full}" points to "${entryRealPath}"`);
233
+ recursiveError.code = RECURSIVE_ERROR_CODE;
234
+ this._onError(recursiveError);
235
+ return "";
236
+ }
237
+ return "directory";
238
+ }
239
+ } catch (error) {
240
+ this._onError(error);
241
+ }
242
+ return "";
243
+ }
244
+ _includeAsFile(entry) {
245
+ const stats = entry && entry[this._statsProp];
246
+ return stats && this._wantsEverything && !stats.isDirectory();
247
+ }
248
+ };
249
+ /**
250
+ * Streaming version: Reads all files and directories in given root recursively.
251
+ * Consumes ~constant small amount of RAM.
252
+ * @param root Root directory
253
+ * @param options Options to specify root (start directory), filters and recursion depth
254
+ */
255
+ function readdirp(root, options = {}) {
256
+ let type = options.entryType || options.type;
257
+ if (type === "both") type = EntryTypes.FILE_DIR_TYPE;
258
+ if (!root) throw new Error("readdirp: root argument is required. Usage: readdirp(root, options)");
259
+ else if (typeof root !== "string") throw new TypeError("readdirp: root argument must be a string. Usage: readdirp(root, options)");
260
+ else if (type && !ALL_TYPES.includes(type)) throw new Error(`readdirp: Invalid type passed. Use one of ${ALL_TYPES.join(", ")}`);
261
+ const opts = {
262
+ ...options,
263
+ root
264
+ };
265
+ if (type) opts.type = type;
266
+ return new ReaddirpStream(opts);
267
+ }
268
+ //#endregion
269
+ //#region ../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/handler.js
270
+ const STR_DATA = "data";
271
+ const STR_CLOSE = "close";
272
+ const EMPTY_FN = () => {};
273
+ const pl = process.platform;
274
+ const isWindows = pl === "win32";
275
+ const isMacos = pl === "darwin";
276
+ const isLinux = pl === "linux";
277
+ const isFreeBSD = pl === "freebsd";
278
+ const isIBMi = type() === "OS400";
279
+ const EVENTS = {
280
+ ALL: "all",
281
+ READY: "ready",
282
+ ADD: "add",
283
+ CHANGE: "change",
284
+ ADD_DIR: "addDir",
285
+ UNLINK: "unlink",
286
+ UNLINK_DIR: "unlinkDir",
287
+ RAW: "raw",
288
+ ERROR: "error"
289
+ };
290
+ const EV = EVENTS;
291
+ const THROTTLE_MODE_WATCH = "watch";
292
+ const statMethods = {
293
+ lstat,
294
+ stat: stat$1
295
+ };
296
+ const KEY_LISTENERS = "listeners";
297
+ const KEY_ERR = "errHandlers";
298
+ const KEY_RAW = "rawEmitters";
299
+ const HANDLER_KEYS = [
300
+ KEY_LISTENERS,
301
+ KEY_ERR,
302
+ KEY_RAW
303
+ ];
304
+ const binaryExtensions = /* @__PURE__ */ new Set([
305
+ "3dm",
306
+ "3ds",
307
+ "3g2",
308
+ "3gp",
309
+ "7z",
310
+ "a",
311
+ "aac",
312
+ "adp",
313
+ "afdesign",
314
+ "afphoto",
315
+ "afpub",
316
+ "ai",
317
+ "aif",
318
+ "aiff",
319
+ "alz",
320
+ "ape",
321
+ "apk",
322
+ "appimage",
323
+ "ar",
324
+ "arj",
325
+ "asf",
326
+ "au",
327
+ "avi",
328
+ "bak",
329
+ "baml",
330
+ "bh",
331
+ "bin",
332
+ "bk",
333
+ "bmp",
334
+ "btif",
335
+ "bz2",
336
+ "bzip2",
337
+ "cab",
338
+ "caf",
339
+ "cgm",
340
+ "class",
341
+ "cmx",
342
+ "cpio",
343
+ "cr2",
344
+ "cur",
345
+ "dat",
346
+ "dcm",
347
+ "deb",
348
+ "dex",
349
+ "djvu",
350
+ "dll",
351
+ "dmg",
352
+ "dng",
353
+ "doc",
354
+ "docm",
355
+ "docx",
356
+ "dot",
357
+ "dotm",
358
+ "dra",
359
+ "DS_Store",
360
+ "dsk",
361
+ "dts",
362
+ "dtshd",
363
+ "dvb",
364
+ "dwg",
365
+ "dxf",
366
+ "ecelp4800",
367
+ "ecelp7470",
368
+ "ecelp9600",
369
+ "egg",
370
+ "eol",
371
+ "eot",
372
+ "epub",
373
+ "exe",
374
+ "f4v",
375
+ "fbs",
376
+ "fh",
377
+ "fla",
378
+ "flac",
379
+ "flatpak",
380
+ "fli",
381
+ "flv",
382
+ "fpx",
383
+ "fst",
384
+ "fvt",
385
+ "g3",
386
+ "gh",
387
+ "gif",
388
+ "graffle",
389
+ "gz",
390
+ "gzip",
391
+ "h261",
392
+ "h263",
393
+ "h264",
394
+ "icns",
395
+ "ico",
396
+ "ief",
397
+ "img",
398
+ "ipa",
399
+ "iso",
400
+ "jar",
401
+ "jpeg",
402
+ "jpg",
403
+ "jpgv",
404
+ "jpm",
405
+ "jxr",
406
+ "key",
407
+ "ktx",
408
+ "lha",
409
+ "lib",
410
+ "lvp",
411
+ "lz",
412
+ "lzh",
413
+ "lzma",
414
+ "lzo",
415
+ "m3u",
416
+ "m4a",
417
+ "m4v",
418
+ "mar",
419
+ "mdi",
420
+ "mht",
421
+ "mid",
422
+ "midi",
423
+ "mj2",
424
+ "mka",
425
+ "mkv",
426
+ "mmr",
427
+ "mng",
428
+ "mobi",
429
+ "mov",
430
+ "movie",
431
+ "mp3",
432
+ "mp4",
433
+ "mp4a",
434
+ "mpeg",
435
+ "mpg",
436
+ "mpga",
437
+ "mxu",
438
+ "nef",
439
+ "npx",
440
+ "numbers",
441
+ "nupkg",
442
+ "o",
443
+ "odp",
444
+ "ods",
445
+ "odt",
446
+ "oga",
447
+ "ogg",
448
+ "ogv",
449
+ "otf",
450
+ "ott",
451
+ "pages",
452
+ "pbm",
453
+ "pcx",
454
+ "pdb",
455
+ "pdf",
456
+ "pea",
457
+ "pgm",
458
+ "pic",
459
+ "png",
460
+ "pnm",
461
+ "pot",
462
+ "potm",
463
+ "potx",
464
+ "ppa",
465
+ "ppam",
466
+ "ppm",
467
+ "pps",
468
+ "ppsm",
469
+ "ppsx",
470
+ "ppt",
471
+ "pptm",
472
+ "pptx",
473
+ "psd",
474
+ "pya",
475
+ "pyc",
476
+ "pyo",
477
+ "pyv",
478
+ "qt",
479
+ "rar",
480
+ "ras",
481
+ "raw",
482
+ "resources",
483
+ "rgb",
484
+ "rip",
485
+ "rlc",
486
+ "rmf",
487
+ "rmvb",
488
+ "rpm",
489
+ "rtf",
490
+ "rz",
491
+ "s3m",
492
+ "s7z",
493
+ "scpt",
494
+ "sgi",
495
+ "shar",
496
+ "snap",
497
+ "sil",
498
+ "sketch",
499
+ "slk",
500
+ "smv",
501
+ "snk",
502
+ "so",
503
+ "stl",
504
+ "suo",
505
+ "sub",
506
+ "swf",
507
+ "tar",
508
+ "tbz",
509
+ "tbz2",
510
+ "tga",
511
+ "tgz",
512
+ "thmx",
513
+ "tif",
514
+ "tiff",
515
+ "tlz",
516
+ "ttc",
517
+ "ttf",
518
+ "txz",
519
+ "udf",
520
+ "uvh",
521
+ "uvi",
522
+ "uvm",
523
+ "uvp",
524
+ "uvs",
525
+ "uvu",
526
+ "viv",
527
+ "vob",
528
+ "war",
529
+ "wav",
530
+ "wax",
531
+ "wbmp",
532
+ "wdp",
533
+ "weba",
534
+ "webm",
535
+ "webp",
536
+ "whl",
537
+ "wim",
538
+ "wm",
539
+ "wma",
540
+ "wmv",
541
+ "wmx",
542
+ "woff",
543
+ "woff2",
544
+ "wrm",
545
+ "wvx",
546
+ "xbm",
547
+ "xif",
548
+ "xla",
549
+ "xlam",
550
+ "xls",
551
+ "xlsb",
552
+ "xlsm",
553
+ "xlsx",
554
+ "xlt",
555
+ "xltm",
556
+ "xltx",
557
+ "xm",
558
+ "xmind",
559
+ "xpi",
560
+ "xpm",
561
+ "xwd",
562
+ "xz",
563
+ "z",
564
+ "zip",
565
+ "zipx"
566
+ ]);
567
+ const isBinaryPath = (filePath) => binaryExtensions.has(sp.extname(filePath).slice(1).toLowerCase());
568
+ const foreach = (val, fn) => {
569
+ if (val instanceof Set) val.forEach(fn);
570
+ else fn(val);
571
+ };
572
+ const addAndConvert = (main, prop, item) => {
573
+ let container = main[prop];
574
+ if (!(container instanceof Set)) main[prop] = container = /* @__PURE__ */ new Set([container]);
575
+ container.add(item);
576
+ };
577
+ const clearItem = (cont) => (key) => {
578
+ const set = cont[key];
579
+ if (set instanceof Set) set.clear();
580
+ else delete cont[key];
581
+ };
582
+ const delFromSet = (main, prop, item) => {
583
+ const container = main[prop];
584
+ if (container instanceof Set) container.delete(item);
585
+ else if (container === item) delete main[prop];
586
+ };
587
+ const isEmptySet = (val) => val instanceof Set ? val.size === 0 : !val;
588
+ const FsWatchInstances = /* @__PURE__ */ new Map();
589
+ /**
590
+ * Instantiates the fs_watch interface
591
+ * @param path to be watched
592
+ * @param options to be passed to fs_watch
593
+ * @param listener main event handler
594
+ * @param errHandler emits info about errors
595
+ * @param emitRaw emits raw event data
596
+ * @returns {NativeFsWatcher}
597
+ */
598
+ function createFsWatchInstance(path, options, listener, errHandler, emitRaw) {
599
+ const handleEvent = (rawEvent, evPath) => {
600
+ listener(path);
601
+ emitRaw(rawEvent, evPath, { watchedPath: path });
602
+ if (evPath && path !== evPath) fsWatchBroadcast(sp.resolve(path, evPath), KEY_LISTENERS, sp.join(path, evPath));
603
+ };
604
+ try {
605
+ return watch(path, { persistent: options.persistent }, handleEvent);
606
+ } catch (error) {
607
+ errHandler(error);
608
+ return;
609
+ }
610
+ }
611
+ /**
612
+ * Helper for passing fs_watch event data to a collection of listeners
613
+ * @param fullPath absolute path bound to fs_watch instance
614
+ */
615
+ const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => {
616
+ const cont = FsWatchInstances.get(fullPath);
617
+ if (!cont) return;
618
+ foreach(cont[listenerType], (listener) => {
619
+ listener(val1, val2, val3);
620
+ });
621
+ };
622
+ /**
623
+ * Instantiates the fs_watch interface or binds listeners
624
+ * to an existing one covering the same file system entry
625
+ * @param path
626
+ * @param fullPath absolute path
627
+ * @param options to be passed to fs_watch
628
+ * @param handlers container for event listener functions
629
+ */
630
+ const setFsWatchListener = (path, fullPath, options, handlers) => {
631
+ const { listener, errHandler, rawEmitter } = handlers;
632
+ let cont = FsWatchInstances.get(fullPath);
633
+ let watcher;
634
+ if (!options.persistent) {
635
+ watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter);
636
+ if (!watcher) return;
637
+ return watcher.close.bind(watcher);
638
+ }
639
+ if (cont) {
640
+ addAndConvert(cont, KEY_LISTENERS, listener);
641
+ addAndConvert(cont, KEY_ERR, errHandler);
642
+ addAndConvert(cont, KEY_RAW, rawEmitter);
643
+ } else {
644
+ watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, fsWatchBroadcast.bind(null, fullPath, KEY_RAW));
645
+ if (!watcher) return;
646
+ watcher.on(EV.ERROR, async (error) => {
647
+ const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR);
648
+ if (cont) cont.watcherUnusable = true;
649
+ if (isWindows && error.code === "EPERM") try {
650
+ await (await open(path, "r")).close();
651
+ broadcastErr(error);
652
+ } catch (err) {}
653
+ else broadcastErr(error);
654
+ });
655
+ cont = {
656
+ listeners: listener,
657
+ errHandlers: errHandler,
658
+ rawEmitters: rawEmitter,
659
+ watcher
660
+ };
661
+ FsWatchInstances.set(fullPath, cont);
662
+ }
663
+ return () => {
664
+ delFromSet(cont, KEY_LISTENERS, listener);
665
+ delFromSet(cont, KEY_ERR, errHandler);
666
+ delFromSet(cont, KEY_RAW, rawEmitter);
667
+ if (isEmptySet(cont.listeners)) {
668
+ cont.watcher.close();
669
+ FsWatchInstances.delete(fullPath);
670
+ HANDLER_KEYS.forEach(clearItem(cont));
671
+ cont.watcher = void 0;
672
+ Object.freeze(cont);
673
+ }
674
+ };
675
+ };
676
+ const FsWatchFileInstances = /* @__PURE__ */ new Map();
677
+ /**
678
+ * Instantiates the fs_watchFile interface or binds listeners
679
+ * to an existing one covering the same file system entry
680
+ * @param path to be watched
681
+ * @param fullPath absolute path
682
+ * @param options options to be passed to fs_watchFile
683
+ * @param handlers container for event listener functions
684
+ * @returns closer
685
+ */
686
+ const setFsWatchFileListener = (path, fullPath, options, handlers) => {
687
+ const { listener, rawEmitter } = handlers;
688
+ let cont = FsWatchFileInstances.get(fullPath);
689
+ const copts = cont && cont.options;
690
+ if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) {
691
+ unwatchFile(fullPath);
692
+ cont = void 0;
693
+ }
694
+ if (cont) {
695
+ addAndConvert(cont, KEY_LISTENERS, listener);
696
+ addAndConvert(cont, KEY_RAW, rawEmitter);
697
+ } else {
698
+ cont = {
699
+ listeners: listener,
700
+ rawEmitters: rawEmitter,
701
+ options,
702
+ watcher: watchFile(fullPath, options, (curr, prev) => {
703
+ foreach(cont.rawEmitters, (rawEmitter) => {
704
+ rawEmitter(EV.CHANGE, fullPath, {
705
+ curr,
706
+ prev
707
+ });
708
+ });
709
+ const currmtime = curr.mtimeMs;
710
+ if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) foreach(cont.listeners, (listener) => listener(path, curr));
711
+ })
712
+ };
713
+ FsWatchFileInstances.set(fullPath, cont);
714
+ }
715
+ return () => {
716
+ delFromSet(cont, KEY_LISTENERS, listener);
717
+ delFromSet(cont, KEY_RAW, rawEmitter);
718
+ if (isEmptySet(cont.listeners)) {
719
+ FsWatchFileInstances.delete(fullPath);
720
+ unwatchFile(fullPath);
721
+ cont.options = cont.watcher = void 0;
722
+ Object.freeze(cont);
723
+ }
724
+ };
725
+ };
726
+ /**
727
+ * @mixin
728
+ */
729
+ var NodeFsHandler = class {
730
+ fsw;
731
+ _boundHandleError;
732
+ constructor(fsW) {
733
+ this.fsw = fsW;
734
+ this._boundHandleError = (error) => fsW._handleError(error);
735
+ }
736
+ /**
737
+ * Watch file for changes with fs_watchFile or fs_watch.
738
+ * @param path to file or dir
739
+ * @param listener on fs change
740
+ * @returns closer for the watcher instance
741
+ */
742
+ _watchWithNodeFs(path, listener) {
743
+ const opts = this.fsw.options;
744
+ const directory = sp.dirname(path);
745
+ const basename = sp.basename(path);
746
+ this.fsw._getWatchedDir(directory).add(basename);
747
+ const absolutePath = sp.resolve(path);
748
+ const options = { persistent: opts.persistent };
749
+ if (!listener) listener = EMPTY_FN;
750
+ let closer;
751
+ if (opts.usePolling) {
752
+ options.interval = opts.interval !== opts.binaryInterval && isBinaryPath(basename) ? opts.binaryInterval : opts.interval;
753
+ closer = setFsWatchFileListener(path, absolutePath, options, {
754
+ listener,
755
+ rawEmitter: this.fsw._emitRaw
756
+ });
757
+ } else closer = setFsWatchListener(path, absolutePath, options, {
758
+ listener,
759
+ errHandler: this._boundHandleError,
760
+ rawEmitter: this.fsw._emitRaw
761
+ });
762
+ return closer;
763
+ }
764
+ /**
765
+ * Watch a file and emit add event if warranted.
766
+ * @returns closer for the watcher instance
767
+ */
768
+ _handleFile(file, stats, initialAdd) {
769
+ if (this.fsw.closed) return;
770
+ const dirname = sp.dirname(file);
771
+ const basename = sp.basename(file);
772
+ const parent = this.fsw._getWatchedDir(dirname);
773
+ let prevStats = stats;
774
+ if (parent.has(basename)) return;
775
+ const listener = async (path, newStats) => {
776
+ if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) return;
777
+ if (!newStats || newStats.mtimeMs === 0) try {
778
+ const newStats = await stat$1(file);
779
+ if (this.fsw.closed) return;
780
+ const at = newStats.atimeMs;
781
+ const mt = newStats.mtimeMs;
782
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
783
+ if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) {
784
+ this.fsw._closeFile(path);
785
+ prevStats = newStats;
786
+ const closer = this._watchWithNodeFs(file, listener);
787
+ if (closer) this.fsw._addPathCloser(path, closer);
788
+ } else prevStats = newStats;
789
+ } catch (error) {
790
+ this.fsw._remove(dirname, basename);
791
+ }
792
+ else if (parent.has(basename)) {
793
+ const at = newStats.atimeMs;
794
+ const mt = newStats.mtimeMs;
795
+ if (!at || at <= mt || mt !== prevStats.mtimeMs) this.fsw._emit(EV.CHANGE, file, newStats);
796
+ prevStats = newStats;
797
+ }
798
+ };
799
+ const closer = this._watchWithNodeFs(file, listener);
800
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) {
801
+ if (!this.fsw._throttle(EV.ADD, file, 0)) return;
802
+ this.fsw._emit(EV.ADD, file, stats);
803
+ }
804
+ return closer;
805
+ }
806
+ /**
807
+ * Handle symlinks encountered while reading a dir.
808
+ * @param entry returned by readdirp
809
+ * @param directory path of dir being read
810
+ * @param path of this item
811
+ * @param item basename of this item
812
+ * @returns true if no more processing is needed for this entry.
813
+ */
814
+ async _handleSymlink(entry, directory, path, item) {
815
+ if (this.fsw.closed) return;
816
+ const full = entry.fullPath;
817
+ const dir = this.fsw._getWatchedDir(directory);
818
+ if (!this.fsw.options.followSymlinks) {
819
+ this.fsw._incrReadyCount();
820
+ let linkPath;
821
+ try {
822
+ linkPath = await realpath(path);
823
+ } catch (e) {
824
+ this.fsw._emitReady();
825
+ return true;
826
+ }
827
+ if (this.fsw.closed) return;
828
+ if (dir.has(item)) {
829
+ if (this.fsw._symlinkPaths.get(full) !== linkPath) {
830
+ this.fsw._symlinkPaths.set(full, linkPath);
831
+ this.fsw._emit(EV.CHANGE, path, entry.stats);
832
+ }
833
+ } else {
834
+ dir.add(item);
835
+ this.fsw._symlinkPaths.set(full, linkPath);
836
+ this.fsw._emit(EV.ADD, path, entry.stats);
837
+ }
838
+ this.fsw._emitReady();
839
+ return true;
840
+ }
841
+ if (this.fsw._symlinkPaths.has(full)) return true;
842
+ this.fsw._symlinkPaths.set(full, true);
843
+ }
844
+ _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) {
845
+ directory = sp.join(directory, "");
846
+ const throttleKey = target ? `${directory}:${target}` : directory;
847
+ throttler = this.fsw._throttle("readdir", throttleKey, 1e3);
848
+ if (!throttler) return;
849
+ const previous = this.fsw._getWatchedDir(wh.path);
850
+ const current = /* @__PURE__ */ new Set();
851
+ let stream = this.fsw._readdirp(directory, {
852
+ fileFilter: (entry) => wh.filterPath(entry),
853
+ directoryFilter: (entry) => wh.filterDir(entry)
854
+ });
855
+ if (!stream) return;
856
+ stream.on(STR_DATA, async (entry) => {
857
+ if (this.fsw.closed) {
858
+ stream = void 0;
859
+ return;
860
+ }
861
+ const item = entry.path;
862
+ let path = sp.join(directory, item);
863
+ current.add(item);
864
+ if (entry.stats.isSymbolicLink() && await this._handleSymlink(entry, directory, path, item)) return;
865
+ if (this.fsw.closed) {
866
+ stream = void 0;
867
+ return;
868
+ }
869
+ if (item === target || !target && !previous.has(item)) {
870
+ this.fsw._incrReadyCount();
871
+ path = sp.join(dir, sp.relative(dir, path));
872
+ this._addToNodeFs(path, initialAdd, wh, depth + 1);
873
+ }
874
+ }).on(EV.ERROR, this._boundHandleError);
875
+ return new Promise((resolve, reject) => {
876
+ if (!stream) return reject();
877
+ stream.once("end", () => {
878
+ if (this.fsw.closed) {
879
+ stream = void 0;
880
+ return;
881
+ }
882
+ const wasThrottled = throttler ? throttler.clear() : false;
883
+ resolve(void 0);
884
+ previous.getChildren().filter((item) => {
885
+ return item !== directory && !current.has(item);
886
+ }).forEach((item) => {
887
+ this.fsw._remove(directory, item);
888
+ });
889
+ stream = void 0;
890
+ if (wasThrottled) this._handleRead(directory, false, wh, target, dir, depth, throttler);
891
+ });
892
+ });
893
+ }
894
+ /**
895
+ * Read directory to add / remove files from `@watched` list and re-read it on change.
896
+ * @param dir fs path
897
+ * @param stats
898
+ * @param initialAdd
899
+ * @param depth relative to user-supplied path
900
+ * @param target child path targeted for watch
901
+ * @param wh Common watch helpers for this path
902
+ * @param realpath
903
+ * @returns closer for the watcher instance.
904
+ */
905
+ async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) {
906
+ const parentDir = this.fsw._getWatchedDir(sp.dirname(dir));
907
+ const tracked = parentDir.has(sp.basename(dir));
908
+ if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) this.fsw._emit(EV.ADD_DIR, dir, stats);
909
+ parentDir.add(sp.basename(dir));
910
+ this.fsw._getWatchedDir(dir);
911
+ let throttler;
912
+ let closer;
913
+ const oDepth = this.fsw.options.depth;
914
+ if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) {
915
+ if (!target) {
916
+ await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler);
917
+ if (this.fsw.closed) return;
918
+ }
919
+ closer = this._watchWithNodeFs(dir, (dirPath, stats) => {
920
+ if (stats && stats.mtimeMs === 0) return;
921
+ this._handleRead(dirPath, false, wh, target, dir, depth, throttler);
922
+ });
923
+ }
924
+ return closer;
925
+ }
926
+ /**
927
+ * Handle added file, directory, or glob pattern.
928
+ * Delegates call to _handleFile / _handleDir after checks.
929
+ * @param path to file or ir
930
+ * @param initialAdd was the file added at watch instantiation?
931
+ * @param priorWh depth relative to user-supplied path
932
+ * @param depth Child path actually targeted for watch
933
+ * @param target Child path actually targeted for watch
934
+ */
935
+ async _addToNodeFs(path, initialAdd, priorWh, depth, target) {
936
+ const ready = this.fsw._emitReady;
937
+ if (this.fsw._isIgnored(path) || this.fsw.closed) {
938
+ ready();
939
+ return false;
940
+ }
941
+ const wh = this.fsw._getWatchHelpers(path);
942
+ if (priorWh) {
943
+ wh.filterPath = (entry) => priorWh.filterPath(entry);
944
+ wh.filterDir = (entry) => priorWh.filterDir(entry);
945
+ }
946
+ try {
947
+ const stats = await statMethods[wh.statMethod](wh.watchPath);
948
+ if (this.fsw.closed) return;
949
+ if (this.fsw._isIgnored(wh.watchPath, stats)) {
950
+ ready();
951
+ return false;
952
+ }
953
+ const follow = this.fsw.options.followSymlinks;
954
+ let closer;
955
+ if (stats.isDirectory()) {
956
+ const absPath = sp.resolve(path);
957
+ const targetPath = follow ? await realpath(path) : path;
958
+ if (this.fsw.closed) return;
959
+ closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath);
960
+ if (this.fsw.closed) return;
961
+ if (absPath !== targetPath && targetPath !== void 0) this.fsw._symlinkPaths.set(absPath, targetPath);
962
+ } else if (stats.isSymbolicLink()) {
963
+ const targetPath = follow ? await realpath(path) : path;
964
+ if (this.fsw.closed) return;
965
+ const parent = sp.dirname(wh.watchPath);
966
+ this.fsw._getWatchedDir(parent).add(wh.watchPath);
967
+ this.fsw._emit(EV.ADD, wh.watchPath, stats);
968
+ closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath);
969
+ if (this.fsw.closed) return;
970
+ if (targetPath !== void 0) this.fsw._symlinkPaths.set(sp.resolve(path), targetPath);
971
+ } else closer = this._handleFile(wh.watchPath, stats, initialAdd);
972
+ ready();
973
+ if (closer) this.fsw._addPathCloser(path, closer);
974
+ return false;
975
+ } catch (error) {
976
+ if (this.fsw._handleError(error)) {
977
+ ready();
978
+ return path;
979
+ }
980
+ }
981
+ }
982
+ };
983
+ //#endregion
984
+ //#region ../node_modules/.pnpm/chokidar@5.0.0/node_modules/chokidar/index.js
985
+ /*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */
986
+ const SLASH = "/";
987
+ const SLASH_SLASH = "//";
988
+ const ONE_DOT = ".";
989
+ const TWO_DOTS = "..";
990
+ const STRING_TYPE = "string";
991
+ const BACK_SLASH_RE = /\\/g;
992
+ const DOUBLE_SLASH_RE = /\/\//g;
993
+ const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/;
994
+ const REPLACER_RE = /^\.[/\\]/;
995
+ function arrify(item) {
996
+ return Array.isArray(item) ? item : [item];
997
+ }
998
+ const isMatcherObject = (matcher) => typeof matcher === "object" && matcher !== null && !(matcher instanceof RegExp);
999
+ function createPattern(matcher) {
1000
+ if (typeof matcher === "function") return matcher;
1001
+ if (typeof matcher === "string") return (string) => matcher === string;
1002
+ if (matcher instanceof RegExp) return (string) => matcher.test(string);
1003
+ if (typeof matcher === "object" && matcher !== null) return (string) => {
1004
+ if (matcher.path === string) return true;
1005
+ if (matcher.recursive) {
1006
+ const relative = sp.relative(matcher.path, string);
1007
+ if (!relative) return false;
1008
+ return !relative.startsWith("..") && !sp.isAbsolute(relative);
1009
+ }
1010
+ return false;
1011
+ };
1012
+ return () => false;
1013
+ }
1014
+ function normalizePath(path) {
1015
+ if (typeof path !== "string") throw new Error("string expected");
1016
+ path = sp.normalize(path);
1017
+ path = path.replace(/\\/g, "/");
1018
+ let prepend = false;
1019
+ if (path.startsWith("//")) prepend = true;
1020
+ path = path.replace(DOUBLE_SLASH_RE, "/");
1021
+ if (prepend) path = "/" + path;
1022
+ return path;
1023
+ }
1024
+ function matchPatterns(patterns, testString, stats) {
1025
+ const path = normalizePath(testString);
1026
+ for (let index = 0; index < patterns.length; index++) {
1027
+ const pattern = patterns[index];
1028
+ if (pattern(path, stats)) return true;
1029
+ }
1030
+ return false;
1031
+ }
1032
+ function anymatch(matchers, testString) {
1033
+ if (matchers == null) throw new TypeError("anymatch: specify first argument");
1034
+ const patterns = arrify(matchers).map((matcher) => createPattern(matcher));
1035
+ if (testString == null) return (testString, stats) => {
1036
+ return matchPatterns(patterns, testString, stats);
1037
+ };
1038
+ return matchPatterns(patterns, testString);
1039
+ }
1040
+ const unifyPaths = (paths_) => {
1041
+ const paths = arrify(paths_).flat();
1042
+ if (!paths.every((p) => typeof p === STRING_TYPE)) throw new TypeError(`Non-string provided as watch path: ${paths}`);
1043
+ return paths.map(normalizePathToUnix);
1044
+ };
1045
+ const toUnix = (string) => {
1046
+ let str = string.replace(BACK_SLASH_RE, SLASH);
1047
+ let prepend = false;
1048
+ if (str.startsWith(SLASH_SLASH)) prepend = true;
1049
+ str = str.replace(DOUBLE_SLASH_RE, SLASH);
1050
+ if (prepend) str = SLASH + str;
1051
+ return str;
1052
+ };
1053
+ const normalizePathToUnix = (path) => toUnix(sp.normalize(toUnix(path)));
1054
+ const normalizeIgnored = (cwd = "") => (path) => {
1055
+ if (typeof path === "string") return normalizePathToUnix(sp.isAbsolute(path) ? path : sp.join(cwd, path));
1056
+ else return path;
1057
+ };
1058
+ const getAbsolutePath = (path, cwd) => {
1059
+ if (sp.isAbsolute(path)) return path;
1060
+ return sp.join(cwd, path);
1061
+ };
1062
+ const EMPTY_SET$1 = Object.freeze(/* @__PURE__ */ new Set());
1063
+ /**
1064
+ * Directory entry.
1065
+ */
1066
+ var DirEntry = class {
1067
+ path;
1068
+ _removeWatcher;
1069
+ items;
1070
+ constructor(dir, removeWatcher) {
1071
+ this.path = dir;
1072
+ this._removeWatcher = removeWatcher;
1073
+ this.items = /* @__PURE__ */ new Set();
1074
+ }
1075
+ add(item) {
1076
+ const { items } = this;
1077
+ if (!items) return;
1078
+ if (item !== ONE_DOT && item !== TWO_DOTS) items.add(item);
1079
+ }
1080
+ async remove(item) {
1081
+ const { items } = this;
1082
+ if (!items) return;
1083
+ items.delete(item);
1084
+ if (items.size > 0) return;
1085
+ const dir = this.path;
1086
+ try {
1087
+ await readdir(dir);
1088
+ } catch (err) {
1089
+ if (this._removeWatcher) this._removeWatcher(sp.dirname(dir), sp.basename(dir));
1090
+ }
1091
+ }
1092
+ has(item) {
1093
+ const { items } = this;
1094
+ if (!items) return;
1095
+ return items.has(item);
1096
+ }
1097
+ getChildren() {
1098
+ const { items } = this;
1099
+ if (!items) return [];
1100
+ return [...items.values()];
1101
+ }
1102
+ dispose() {
1103
+ this.items.clear();
1104
+ this.path = "";
1105
+ this._removeWatcher = EMPTY_FN;
1106
+ this.items = EMPTY_SET$1;
1107
+ Object.freeze(this);
1108
+ }
1109
+ };
1110
+ const STAT_METHOD_F = "stat";
1111
+ const STAT_METHOD_L = "lstat";
1112
+ var WatchHelper = class {
1113
+ fsw;
1114
+ path;
1115
+ watchPath;
1116
+ fullWatchPath;
1117
+ dirParts;
1118
+ followSymlinks;
1119
+ statMethod;
1120
+ constructor(path, follow, fsw) {
1121
+ this.fsw = fsw;
1122
+ const watchPath = path;
1123
+ this.path = path = path.replace(REPLACER_RE, "");
1124
+ this.watchPath = watchPath;
1125
+ this.fullWatchPath = sp.resolve(watchPath);
1126
+ this.dirParts = [];
1127
+ this.dirParts.forEach((parts) => {
1128
+ if (parts.length > 1) parts.pop();
1129
+ });
1130
+ this.followSymlinks = follow;
1131
+ this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L;
1132
+ }
1133
+ entryPath(entry) {
1134
+ return sp.join(this.watchPath, sp.relative(this.watchPath, entry.fullPath));
1135
+ }
1136
+ filterPath(entry) {
1137
+ const { stats } = entry;
1138
+ if (stats && stats.isSymbolicLink()) return this.filterDir(entry);
1139
+ const resolvedPath = this.entryPath(entry);
1140
+ return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats);
1141
+ }
1142
+ filterDir(entry) {
1143
+ return this.fsw._isntIgnored(this.entryPath(entry), entry.stats);
1144
+ }
1145
+ };
1146
+ /**
1147
+ * Watches files & directories for changes. Emitted events:
1148
+ * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error`
1149
+ *
1150
+ * new FSWatcher()
1151
+ * .add(directories)
1152
+ * .on('add', path => log('File', path, 'was added'))
1153
+ */
1154
+ var FSWatcher = class extends EventEmitter {
1155
+ closed;
1156
+ options;
1157
+ _closers;
1158
+ _ignoredPaths;
1159
+ _throttled;
1160
+ _streams;
1161
+ _symlinkPaths;
1162
+ _watched;
1163
+ _pendingWrites;
1164
+ _pendingUnlinks;
1165
+ _readyCount;
1166
+ _emitReady;
1167
+ _closePromise;
1168
+ _userIgnored;
1169
+ _readyEmitted;
1170
+ _emitRaw;
1171
+ _boundRemove;
1172
+ _nodeFsHandler;
1173
+ constructor(_opts = {}) {
1174
+ super();
1175
+ this.closed = false;
1176
+ this._closers = /* @__PURE__ */ new Map();
1177
+ this._ignoredPaths = /* @__PURE__ */ new Set();
1178
+ this._throttled = /* @__PURE__ */ new Map();
1179
+ this._streams = /* @__PURE__ */ new Set();
1180
+ this._symlinkPaths = /* @__PURE__ */ new Map();
1181
+ this._watched = /* @__PURE__ */ new Map();
1182
+ this._pendingWrites = /* @__PURE__ */ new Map();
1183
+ this._pendingUnlinks = /* @__PURE__ */ new Map();
1184
+ this._readyCount = 0;
1185
+ this._readyEmitted = false;
1186
+ const awf = _opts.awaitWriteFinish;
1187
+ const DEF_AWF = {
1188
+ stabilityThreshold: 2e3,
1189
+ pollInterval: 100
1190
+ };
1191
+ const opts = {
1192
+ persistent: true,
1193
+ ignoreInitial: false,
1194
+ ignorePermissionErrors: false,
1195
+ interval: 100,
1196
+ binaryInterval: 300,
1197
+ followSymlinks: true,
1198
+ usePolling: false,
1199
+ atomic: true,
1200
+ ..._opts,
1201
+ ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]),
1202
+ awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === "object" ? {
1203
+ ...DEF_AWF,
1204
+ ...awf
1205
+ } : false
1206
+ };
1207
+ if (isIBMi) opts.usePolling = true;
1208
+ if (opts.atomic === void 0) opts.atomic = !opts.usePolling;
1209
+ const envPoll = process.env.CHOKIDAR_USEPOLLING;
1210
+ if (envPoll !== void 0) {
1211
+ const envLower = envPoll.toLowerCase();
1212
+ if (envLower === "false" || envLower === "0") opts.usePolling = false;
1213
+ else if (envLower === "true" || envLower === "1") opts.usePolling = true;
1214
+ else opts.usePolling = !!envLower;
1215
+ }
1216
+ const envInterval = process.env.CHOKIDAR_INTERVAL;
1217
+ if (envInterval) opts.interval = Number.parseInt(envInterval, 10);
1218
+ let readyCalls = 0;
1219
+ this._emitReady = () => {
1220
+ readyCalls++;
1221
+ if (readyCalls >= this._readyCount) {
1222
+ this._emitReady = EMPTY_FN;
1223
+ this._readyEmitted = true;
1224
+ process.nextTick(() => this.emit(EVENTS.READY));
1225
+ }
1226
+ };
1227
+ this._emitRaw = (...args) => this.emit(EVENTS.RAW, ...args);
1228
+ this._boundRemove = this._remove.bind(this);
1229
+ this.options = opts;
1230
+ this._nodeFsHandler = new NodeFsHandler(this);
1231
+ Object.freeze(opts);
1232
+ }
1233
+ _addIgnoredPath(matcher) {
1234
+ if (isMatcherObject(matcher)) {
1235
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher.path && ignored.recursive === matcher.recursive) return;
1236
+ }
1237
+ this._ignoredPaths.add(matcher);
1238
+ }
1239
+ _removeIgnoredPath(matcher) {
1240
+ this._ignoredPaths.delete(matcher);
1241
+ if (typeof matcher === "string") {
1242
+ for (const ignored of this._ignoredPaths) if (isMatcherObject(ignored) && ignored.path === matcher) this._ignoredPaths.delete(ignored);
1243
+ }
1244
+ }
1245
+ /**
1246
+ * Adds paths to be watched on an existing FSWatcher instance.
1247
+ * @param paths_ file or file list. Other arguments are unused
1248
+ */
1249
+ add(paths_, _origAdd, _internal) {
1250
+ const { cwd } = this.options;
1251
+ this.closed = false;
1252
+ this._closePromise = void 0;
1253
+ let paths = unifyPaths(paths_);
1254
+ if (cwd) paths = paths.map((path) => {
1255
+ return getAbsolutePath(path, cwd);
1256
+ });
1257
+ paths.forEach((path) => {
1258
+ this._removeIgnoredPath(path);
1259
+ });
1260
+ this._userIgnored = void 0;
1261
+ if (!this._readyCount) this._readyCount = 0;
1262
+ this._readyCount += paths.length;
1263
+ Promise.all(paths.map(async (path) => {
1264
+ const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, void 0, 0, _origAdd);
1265
+ if (res) this._emitReady();
1266
+ return res;
1267
+ })).then((results) => {
1268
+ if (this.closed) return;
1269
+ results.forEach((item) => {
1270
+ if (item) this.add(sp.dirname(item), sp.basename(_origAdd || item));
1271
+ });
1272
+ });
1273
+ return this;
1274
+ }
1275
+ /**
1276
+ * Close watchers or start ignoring events from specified paths.
1277
+ */
1278
+ unwatch(paths_) {
1279
+ if (this.closed) return this;
1280
+ const paths = unifyPaths(paths_);
1281
+ const { cwd } = this.options;
1282
+ paths.forEach((path) => {
1283
+ if (!sp.isAbsolute(path) && !this._closers.has(path)) {
1284
+ if (cwd) path = sp.join(cwd, path);
1285
+ path = sp.resolve(path);
1286
+ }
1287
+ this._closePath(path);
1288
+ this._addIgnoredPath(path);
1289
+ if (this._watched.has(path)) this._addIgnoredPath({
1290
+ path,
1291
+ recursive: true
1292
+ });
1293
+ this._userIgnored = void 0;
1294
+ });
1295
+ return this;
1296
+ }
1297
+ /**
1298
+ * Close watchers and remove all listeners from watched paths.
1299
+ */
1300
+ close() {
1301
+ if (this._closePromise) return this._closePromise;
1302
+ this.closed = true;
1303
+ this.removeAllListeners();
1304
+ const closers = [];
1305
+ this._closers.forEach((closerList) => closerList.forEach((closer) => {
1306
+ const promise = closer();
1307
+ if (promise instanceof Promise) closers.push(promise);
1308
+ }));
1309
+ this._streams.forEach((stream) => stream.destroy());
1310
+ this._userIgnored = void 0;
1311
+ this._readyCount = 0;
1312
+ this._readyEmitted = false;
1313
+ this._watched.forEach((dirent) => dirent.dispose());
1314
+ this._closers.clear();
1315
+ this._watched.clear();
1316
+ this._streams.clear();
1317
+ this._symlinkPaths.clear();
1318
+ this._throttled.clear();
1319
+ this._closePromise = closers.length ? Promise.all(closers).then(() => void 0) : Promise.resolve();
1320
+ return this._closePromise;
1321
+ }
1322
+ /**
1323
+ * Expose list of watched paths
1324
+ * @returns for chaining
1325
+ */
1326
+ getWatched() {
1327
+ const watchList = {};
1328
+ this._watched.forEach((entry, dir) => {
1329
+ const index = (this.options.cwd ? sp.relative(this.options.cwd, dir) : dir) || ONE_DOT;
1330
+ watchList[index] = entry.getChildren().sort();
1331
+ });
1332
+ return watchList;
1333
+ }
1334
+ emitWithAll(event, args) {
1335
+ this.emit(event, ...args);
1336
+ if (event !== EVENTS.ERROR) this.emit(EVENTS.ALL, event, ...args);
1337
+ }
1338
+ /**
1339
+ * Normalize and emit events.
1340
+ * Calling _emit DOES NOT MEAN emit() would be called!
1341
+ * @param event Type of event
1342
+ * @param path File or directory path
1343
+ * @param stats arguments to be passed with event
1344
+ * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1345
+ */
1346
+ async _emit(event, path, stats) {
1347
+ if (this.closed) return;
1348
+ const opts = this.options;
1349
+ if (isWindows) path = sp.normalize(path);
1350
+ if (opts.cwd) path = sp.relative(opts.cwd, path);
1351
+ const args = [path];
1352
+ if (stats != null) args.push(stats);
1353
+ const awf = opts.awaitWriteFinish;
1354
+ let pw;
1355
+ if (awf && (pw = this._pendingWrites.get(path))) {
1356
+ pw.lastChange = /* @__PURE__ */ new Date();
1357
+ return this;
1358
+ }
1359
+ if (opts.atomic) {
1360
+ if (event === EVENTS.UNLINK) {
1361
+ this._pendingUnlinks.set(path, [event, ...args]);
1362
+ setTimeout(() => {
1363
+ this._pendingUnlinks.forEach((entry, path) => {
1364
+ this.emit(...entry);
1365
+ this.emit(EVENTS.ALL, ...entry);
1366
+ this._pendingUnlinks.delete(path);
1367
+ });
1368
+ }, typeof opts.atomic === "number" ? opts.atomic : 100);
1369
+ return this;
1370
+ }
1371
+ if (event === EVENTS.ADD && this._pendingUnlinks.has(path)) {
1372
+ event = EVENTS.CHANGE;
1373
+ this._pendingUnlinks.delete(path);
1374
+ }
1375
+ }
1376
+ if (awf && (event === EVENTS.ADD || event === EVENTS.CHANGE) && this._readyEmitted) {
1377
+ const awfEmit = (err, stats) => {
1378
+ if (err) {
1379
+ event = EVENTS.ERROR;
1380
+ args[0] = err;
1381
+ this.emitWithAll(event, args);
1382
+ } else if (stats) {
1383
+ if (args.length > 1) args[1] = stats;
1384
+ else args.push(stats);
1385
+ this.emitWithAll(event, args);
1386
+ }
1387
+ };
1388
+ this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit);
1389
+ return this;
1390
+ }
1391
+ if (event === EVENTS.CHANGE) {
1392
+ if (!this._throttle(EVENTS.CHANGE, path, 50)) return this;
1393
+ }
1394
+ if (opts.alwaysStat && stats === void 0 && (event === EVENTS.ADD || event === EVENTS.ADD_DIR || event === EVENTS.CHANGE)) {
1395
+ const fullPath = opts.cwd ? sp.join(opts.cwd, path) : path;
1396
+ let stats;
1397
+ try {
1398
+ stats = await stat$1(fullPath);
1399
+ } catch (err) {}
1400
+ if (!stats || this.closed) return;
1401
+ args.push(stats);
1402
+ }
1403
+ this.emitWithAll(event, args);
1404
+ return this;
1405
+ }
1406
+ /**
1407
+ * Common handler for errors
1408
+ * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag
1409
+ */
1410
+ _handleError(error) {
1411
+ const code = error && error.code;
1412
+ if (error && code !== "ENOENT" && code !== "ENOTDIR" && (!this.options.ignorePermissionErrors || code !== "EPERM" && code !== "EACCES")) this.emit(EVENTS.ERROR, error);
1413
+ return error || this.closed;
1414
+ }
1415
+ /**
1416
+ * Helper utility for throttling
1417
+ * @param actionType type being throttled
1418
+ * @param path being acted upon
1419
+ * @param timeout duration of time to suppress duplicate actions
1420
+ * @returns tracking object or false if action should be suppressed
1421
+ */
1422
+ _throttle(actionType, path, timeout) {
1423
+ if (!this._throttled.has(actionType)) this._throttled.set(actionType, /* @__PURE__ */ new Map());
1424
+ const action = this._throttled.get(actionType);
1425
+ if (!action) throw new Error("invalid throttle");
1426
+ const actionPath = action.get(path);
1427
+ if (actionPath) {
1428
+ actionPath.count++;
1429
+ return false;
1430
+ }
1431
+ let timeoutObject;
1432
+ const clear = () => {
1433
+ const item = action.get(path);
1434
+ const count = item ? item.count : 0;
1435
+ action.delete(path);
1436
+ clearTimeout(timeoutObject);
1437
+ if (item) clearTimeout(item.timeoutObject);
1438
+ return count;
1439
+ };
1440
+ timeoutObject = setTimeout(clear, timeout);
1441
+ const thr = {
1442
+ timeoutObject,
1443
+ clear,
1444
+ count: 0
1445
+ };
1446
+ action.set(path, thr);
1447
+ return thr;
1448
+ }
1449
+ _incrReadyCount() {
1450
+ return this._readyCount++;
1451
+ }
1452
+ /**
1453
+ * Awaits write operation to finish.
1454
+ * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback.
1455
+ * @param path being acted upon
1456
+ * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished
1457
+ * @param event
1458
+ * @param awfEmit Callback to be called when ready for event to be emitted.
1459
+ */
1460
+ _awaitWriteFinish(path, threshold, event, awfEmit) {
1461
+ const awf = this.options.awaitWriteFinish;
1462
+ if (typeof awf !== "object") return;
1463
+ const pollInterval = awf.pollInterval;
1464
+ let timeoutHandler;
1465
+ let fullPath = path;
1466
+ if (this.options.cwd && !sp.isAbsolute(path)) fullPath = sp.join(this.options.cwd, path);
1467
+ const now = /* @__PURE__ */ new Date();
1468
+ const writes = this._pendingWrites;
1469
+ function awaitWriteFinishFn(prevStat) {
1470
+ stat(fullPath, (err, curStat) => {
1471
+ if (err || !writes.has(path)) {
1472
+ if (err && err.code !== "ENOENT") awfEmit(err);
1473
+ return;
1474
+ }
1475
+ const now = Number(/* @__PURE__ */ new Date());
1476
+ if (prevStat && curStat.size !== prevStat.size) writes.get(path).lastChange = now;
1477
+ if (now - writes.get(path).lastChange >= threshold) {
1478
+ writes.delete(path);
1479
+ awfEmit(void 0, curStat);
1480
+ } else timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat);
1481
+ });
1482
+ }
1483
+ if (!writes.has(path)) {
1484
+ writes.set(path, {
1485
+ lastChange: now,
1486
+ cancelWait: () => {
1487
+ writes.delete(path);
1488
+ clearTimeout(timeoutHandler);
1489
+ return event;
1490
+ }
1491
+ });
1492
+ timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval);
1493
+ }
1494
+ }
1495
+ /**
1496
+ * Determines whether user has asked to ignore this path.
1497
+ */
1498
+ _isIgnored(path, stats) {
1499
+ if (this.options.atomic && DOT_RE.test(path)) return true;
1500
+ if (!this._userIgnored) {
1501
+ const { cwd } = this.options;
1502
+ const ignored = (this.options.ignored || []).map(normalizeIgnored(cwd));
1503
+ const list = [...[...this._ignoredPaths].map(normalizeIgnored(cwd)), ...ignored];
1504
+ this._userIgnored = anymatch(list, void 0);
1505
+ }
1506
+ return this._userIgnored(path, stats);
1507
+ }
1508
+ _isntIgnored(path, stat) {
1509
+ return !this._isIgnored(path, stat);
1510
+ }
1511
+ /**
1512
+ * Provides a set of common helpers and properties relating to symlink handling.
1513
+ * @param path file or directory pattern being watched
1514
+ */
1515
+ _getWatchHelpers(path) {
1516
+ return new WatchHelper(path, this.options.followSymlinks, this);
1517
+ }
1518
+ /**
1519
+ * Provides directory tracking objects
1520
+ * @param directory path of the directory
1521
+ */
1522
+ _getWatchedDir(directory) {
1523
+ const dir = sp.resolve(directory);
1524
+ if (!this._watched.has(dir)) this._watched.set(dir, new DirEntry(dir, this._boundRemove));
1525
+ return this._watched.get(dir);
1526
+ }
1527
+ /**
1528
+ * Check for read permissions: https://stackoverflow.com/a/11781404/1358405
1529
+ */
1530
+ _hasReadPermissions(stats) {
1531
+ if (this.options.ignorePermissionErrors) return true;
1532
+ return Boolean(Number(stats.mode) & 256);
1533
+ }
1534
+ /**
1535
+ * Handles emitting unlink events for
1536
+ * files and directories, and via recursion, for
1537
+ * files and directories within directories that are unlinked
1538
+ * @param directory within which the following item is located
1539
+ * @param item base path of item/directory
1540
+ */
1541
+ _remove(directory, item, isDirectory) {
1542
+ const path = sp.join(directory, item);
1543
+ const fullPath = sp.resolve(path);
1544
+ isDirectory = isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath);
1545
+ if (!this._throttle("remove", path, 100)) return;
1546
+ if (!isDirectory && this._watched.size === 1) this.add(directory, item, true);
1547
+ this._getWatchedDir(path).getChildren().forEach((nested) => this._remove(path, nested));
1548
+ const parent = this._getWatchedDir(directory);
1549
+ const wasTracked = parent.has(item);
1550
+ parent.remove(item);
1551
+ if (this._symlinkPaths.has(fullPath)) this._symlinkPaths.delete(fullPath);
1552
+ let relPath = path;
1553
+ if (this.options.cwd) relPath = sp.relative(this.options.cwd, path);
1554
+ if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) {
1555
+ if (this._pendingWrites.get(relPath).cancelWait() === EVENTS.ADD) return;
1556
+ }
1557
+ this._watched.delete(path);
1558
+ this._watched.delete(fullPath);
1559
+ const eventName = isDirectory ? EVENTS.UNLINK_DIR : EVENTS.UNLINK;
1560
+ if (wasTracked && !this._isIgnored(path)) this._emit(eventName, path);
1561
+ this._closePath(path);
1562
+ }
1563
+ /**
1564
+ * Closes all watchers for a path
1565
+ */
1566
+ _closePath(path) {
1567
+ this._closeFile(path);
1568
+ const dir = sp.dirname(path);
1569
+ this._getWatchedDir(dir).remove(sp.basename(path));
1570
+ }
1571
+ /**
1572
+ * Closes only file-specific watchers
1573
+ */
1574
+ _closeFile(path) {
1575
+ const closers = this._closers.get(path);
1576
+ if (!closers) return;
1577
+ closers.forEach((closer) => closer());
1578
+ this._closers.delete(path);
1579
+ }
1580
+ _addPathCloser(path, closer) {
1581
+ if (!closer) return;
1582
+ let list = this._closers.get(path);
1583
+ if (!list) {
1584
+ list = [];
1585
+ this._closers.set(path, list);
1586
+ }
1587
+ list.push(closer);
1588
+ }
1589
+ _readdirp(root, opts) {
1590
+ if (this.closed) return;
1591
+ let stream = readdirp(root, {
1592
+ type: EVENTS.ALL,
1593
+ alwaysStat: true,
1594
+ lstat: true,
1595
+ ...opts,
1596
+ depth: 0
1597
+ });
1598
+ this._streams.add(stream);
1599
+ stream.once(STR_CLOSE, () => {
1600
+ stream = void 0;
1601
+ });
1602
+ stream.once("end", () => {
1603
+ if (stream) {
1604
+ this._streams.delete(stream);
1605
+ stream = void 0;
1606
+ }
1607
+ });
1608
+ return stream;
1609
+ }
1610
+ };
1611
+ /**
1612
+ * Instantiates watcher with paths to be tracked.
1613
+ * @param paths file / directory paths
1614
+ * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others
1615
+ * @returns an instance of FSWatcher for chaining.
1616
+ * @example
1617
+ * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); });
1618
+ * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') })
1619
+ */
1620
+ function watch$1(paths, options = {}) {
1621
+ const watcher = new FSWatcher(options);
1622
+ watcher.add(paths);
1623
+ return watcher;
1624
+ }
1625
+ var chokidar_default = {
1626
+ watch: watch$1,
1627
+ FSWatcher
1628
+ };
10
1629
  //#endregion
11
1630
  //#region ../src/nodes/BaseNode.ts
12
1631
  /**
@@ -2519,37 +4138,46 @@ var SwitchNode = class extends BaseNode {
2519
4138
  };
2520
4139
  //#endregion
2521
4140
  //#region ../src/build_aarch64/utils/scan_force_heap_strings.ts
2522
- function scan_force_heap_strings(statements) {
4141
+ function scan_force_heap_strings(statements, structs) {
2523
4142
  const result = /* @__PURE__ */ new Set();
2524
- walk$1(statements, result);
4143
+ walk$1(statements, result, structs);
2525
4144
  return result;
2526
4145
  }
2527
- function walk$1(statements, result) {
4146
+ function walk$1(statements, result, structs) {
2528
4147
  if (!statements) return;
2529
- for (const stmt of statements) visit(stmt, result);
4148
+ for (const stmt of statements) visit(stmt, result, structs);
2530
4149
  }
2531
- function visit(node, result) {
4150
+ function visit(node, result, structs) {
2532
4151
  if (!node) return;
2533
4152
  switch (node.node_type) {
2534
4153
  case "assign": {
2535
4154
  const a = node;
2536
4155
  if (a.left_value.node_type === "value" && is_fresh_heap_string(a.right_value)) result.add(a.left_value.value);
4156
+ visit(a.right_value, result, structs);
4157
+ break;
4158
+ }
4159
+ case "access": {
4160
+ const n = node;
4161
+ if (n.access.node_type === "access_func" && n.target.node_type === "value") {
4162
+ const target = n.target;
4163
+ if (target.type?.name === "string" && structs?.find((s) => s.name === "string")?.functions.find((f) => f.name === n.access.name)?.params?.some((p) => p.is_self_param && (p.is_ref || p.type?.is_ref))) result.add(target.value);
4164
+ }
2537
4165
  break;
2538
4166
  }
2539
4167
  case "while":
2540
4168
  case "for":
2541
- walk$1(node.statements, result);
4169
+ walk$1(node.statements, result, structs);
2542
4170
  break;
2543
4171
  case "if": {
2544
4172
  const n = node;
2545
- walk$1(n.if_branch?.statements, result);
2546
- walk$1(n.else_branch?.statements, result);
4173
+ walk$1(n.if_branch?.statements, result, structs);
4174
+ walk$1(n.else_branch?.statements, result, structs);
2547
4175
  break;
2548
4176
  }
2549
4177
  case "switch": {
2550
4178
  const n = node;
2551
- for (const c of n.cases) walk$1(c.branch?.statements, result);
2552
- walk$1(n.else_branch?.statements, result);
4179
+ for (const c of n.cases) walk$1(c.branch?.statements, result, structs);
4180
+ walk$1(n.else_branch?.statements, result, structs);
2553
4181
  break;
2554
4182
  }
2555
4183
  }
@@ -2891,7 +4519,7 @@ function build_function_node$1(node, status) {
2891
4519
  pidx++;
2892
4520
  }
2893
4521
  const old_force_heap = status.force_heap_strings;
2894
- status.force_heap_strings = scan_force_heap_strings(node.statements);
4522
+ status.force_heap_strings = scan_force_heap_strings(node.statements, status.structs);
2895
4523
  status.buffer_data_cache = void 0;
2896
4524
  build_block_node$1(node, status);
2897
4525
  status.force_heap_strings = old_force_heap;
@@ -3672,8 +5300,10 @@ function build_assignment_node$1(node, status) {
3672
5300
  emit_compound_op(node.operator, status);
3673
5301
  status.code += `${ref_store_op} ${ref_store_reg}, [x2]\n`;
3674
5302
  } else {
5303
+ status.last_result_is_heap = false;
3675
5304
  build_node$1(node.right_value, status);
3676
5305
  if (!status.code.endsWith("\n")) status.code += "\n";
5306
+ if (ref_type_name === "string" && !status.last_result_is_heap) emit_strdup(status);
3677
5307
  load_ref_param_pointer("x2", name, status);
3678
5308
  status.code += `${ref_store_op} ${ref_store_reg}, [x2]\n`;
3679
5309
  }
@@ -5753,7 +7383,16 @@ function build_declaration_node$1(node, status) {
5753
7383
  if (node.value.node_type === "op" && node.value.type?.name === "string") {
5754
7384
  const op = node.value;
5755
7385
  const str_result = resolve_string_op(op, status);
5756
- if (str_result !== null) {
7386
+ if (str_result !== null && status.force_heap_strings?.has(node.name)) {
7387
+ const offset = allocate_stack_space(status, 8);
7388
+ status.stack_offsets.set(node.name, offset);
7389
+ const label = `_str_fold_${decl_const_counter++}`;
7390
+ emit_data(status, `${label}: .asciz ${escape_asciz(str_result)}\n.p2align 2\n`);
7391
+ status.code += `adr x0, ${label}\n`;
7392
+ emit_strdup(status);
7393
+ status.code += `str x0, [x29, #${offset}]\n`;
7394
+ mark_heap_string(status, node.name);
7395
+ } else if (str_result !== null) {
5757
7396
  if (status.function_return_label) emit_data(status, `${node.name}: .asciz ${escape_asciz(str_result)}\n.p2align 2\n`);
5758
7397
  else status.code += `${node.name}: .asciz ${escape_asciz(str_result)}\n.p2align 2\n`;
5759
7398
  status.string_literal_names.add(node.name);
@@ -5775,7 +7414,7 @@ function build_declaration_node$1(node, status) {
5775
7414
  const value_node = node.value;
5776
7415
  const raw = get_raw_value$1(value_node);
5777
7416
  const is_literal = /^(\+|-)?\d+(\.\d+)?$/.test(raw) || raw.startsWith("\"") || raw === "true" || raw === "false";
5778
- if (status.function_return_label && (node.declaration === "var" || !is_literal)) {
7417
+ if (!!status.function_return_label) {
5779
7418
  const offset = allocate_stack_space(status, size, size);
5780
7419
  status.stack_offsets.set(node.name, offset);
5781
7420
  if (node.type.name === "string" && !is_literal && status.heap_strings?.has(raw)) {
@@ -8127,6 +9766,155 @@ function build_value_node$1(node, status) {
8127
9766
  }
8128
9767
  }
8129
9768
  //#endregion
9769
+ //#region ../src/build_common/scan_string_length_hoists.ts
9770
+ const NON_IDENTIFIERS = /* @__PURE__ */ new Set([
9771
+ "true",
9772
+ "false",
9773
+ "null",
9774
+ "self",
9775
+ "as",
9776
+ "default"
9777
+ ]);
9778
+ function is_identifier(value) {
9779
+ return !!value && !NON_IDENTIFIERS.has(value) && !/^(\+|-)?\d+(\.\d+)?$/.test(value) && !value.startsWith("\"") && !value.startsWith("'");
9780
+ }
9781
+ function root_name(node) {
9782
+ if (!node) return void 0;
9783
+ if (node.node_type === "value") return node.value;
9784
+ if (node.node_type === "access") return root_name(node.target);
9785
+ }
9786
+ /**
9787
+ * Find the bare `string` variables whose `.length` is read inside a while
9788
+ * loop (condition, body, or update clause) and that the loop never
9789
+ * rebinds — the set of variables for which a single hoisted `strlen` before
9790
+ * the loop is equivalent to the per-evaluation `strlen` the backends
9791
+ * otherwise emit. Returns variable name → the `.length` target node.
9792
+ *
9793
+ * A variable is rejected when the loop subtree contains any of:
9794
+ * - an assignment whose left-hand root name is the variable (rebinds it)
9795
+ * - a declaration/parameter/for-item with the same name (shadows it)
9796
+ * - a call passing it `ref`/`mov`/`swap` (callee may rebind or drain it)
9797
+ * - a mutating (`ref self`) string method dispatched on it (e.g. `set`,
9798
+ * which can change the effective strlen in place)
9799
+ * - any reference inside a nested `func`/`async_block` boundary (those
9800
+ * bodies are emitted outside the loop's scope, where the hoisted temp
9801
+ * or slot is not visible)
9802
+ * - any `raw` block anywhere (its code is opaque and may rebind anything)
9803
+ * Nullable strings are also rejected: hoisting would evaluate `strlen`
9804
+ * before the first condition check, moving a null dereference that today
9805
+ * only happens if the condition is actually reached.
9806
+ */
9807
+ function scan_string_length_hoists(condition, statements, update, status) {
9808
+ const candidates = /* @__PURE__ */ new Map();
9809
+ const invalidated = /* @__PURE__ */ new Set();
9810
+ const boundary_refs = /* @__PURE__ */ new Set();
9811
+ let has_raw = false;
9812
+ const is_string_target = (target) => {
9813
+ const t = target.type;
9814
+ if (t?.is_view || t?.is_nullable) return false;
9815
+ if (t?.name) return t.name === "string";
9816
+ const vt = status.variable_types?.get(target.value);
9817
+ if (vt) return vt.name === "string" && !vt.is_view && !vt.is_nullable;
9818
+ const decl = status.scoped_declarations?.findLast((d) => d.name === target.value);
9819
+ if (!decl?.type) return false;
9820
+ return decl.type.name === "string" && !decl.type.is_view && !decl.type.is_nullable;
9821
+ };
9822
+ const is_mutating_string_call = (call) => {
9823
+ const method = (status.structs?.find((s) => s.name === "string"))?.functions?.find((f) => f.name === call.name || f.name === `#${call.name}`);
9824
+ if (!method) return false;
9825
+ const self_param = method.params?.[0];
9826
+ return !!self_param?.is_self_param && self_param.declaration === "var";
9827
+ };
9828
+ const walk_children = (n, in_boundary) => {
9829
+ const record = n;
9830
+ for (const key of Object.keys(record)) {
9831
+ if (key === "parent" || key === "scope" || key === "node_type") continue;
9832
+ walk(record[key], in_boundary);
9833
+ }
9834
+ };
9835
+ const walk = (value, in_boundary) => {
9836
+ if (!value || typeof value !== "object") return;
9837
+ if (Array.isArray(value)) {
9838
+ for (const item of value) walk(item, in_boundary);
9839
+ return;
9840
+ }
9841
+ const n = value;
9842
+ if (typeof n.node_type !== "string") return;
9843
+ switch (n.node_type) {
9844
+ case "raw":
9845
+ has_raw = true;
9846
+ return;
9847
+ case "func":
9848
+ case "async_block":
9849
+ walk_children(n, true);
9850
+ return;
9851
+ case "value": {
9852
+ const v = n.value;
9853
+ if (in_boundary && is_identifier(v)) boundary_refs.add(v);
9854
+ return;
9855
+ }
9856
+ case "access": {
9857
+ const access = n;
9858
+ if (!in_boundary && access.access.node_type === "access_field" && access.access.name === "length" && access.target.node_type === "value") {
9859
+ const target = access.target;
9860
+ if (is_identifier(target.value) && is_string_target(target)) candidates.set(target.value, target);
9861
+ }
9862
+ if (!in_boundary && access.access.node_type === "access_func" && access.target.node_type === "value") {
9863
+ const target = access.target;
9864
+ if (is_string_target(target) && is_mutating_string_call(access.access)) invalidated.add(target.value);
9865
+ }
9866
+ walk_children(n, in_boundary);
9867
+ return;
9868
+ }
9869
+ case "assign": {
9870
+ const assign = n;
9871
+ const lhs = root_name(assign.left_value);
9872
+ if (lhs) invalidated.add(lhs);
9873
+ const swap = root_name(assign.swap);
9874
+ if (swap) invalidated.add(swap);
9875
+ walk_children(n, in_boundary);
9876
+ return;
9877
+ }
9878
+ case "declare":
9879
+ case "param": {
9880
+ const name = n.name;
9881
+ if (name) invalidated.add(name);
9882
+ walk_children(n, in_boundary);
9883
+ return;
9884
+ }
9885
+ case "for": {
9886
+ const item = n.item;
9887
+ if (item?.value) invalidated.add(item.value);
9888
+ walk_children(n, in_boundary);
9889
+ return;
9890
+ }
9891
+ case "func_call":
9892
+ case "access_func": {
9893
+ const call = n;
9894
+ for (const indices of [call.ref_param_indices, call.mov_param_indices]) for (const i of indices ?? []) {
9895
+ const arg = root_name(call.params?.[i]);
9896
+ if (arg) invalidated.add(arg);
9897
+ }
9898
+ if (call.swap_params) {
9899
+ for (const [i, swap] of call.swap_params) for (const arg of [root_name(call.params?.[i]), root_name(swap)]) if (arg) invalidated.add(arg);
9900
+ }
9901
+ walk_children(n, in_boundary);
9902
+ return;
9903
+ }
9904
+ default:
9905
+ walk_children(n, in_boundary);
9906
+ return;
9907
+ }
9908
+ };
9909
+ walk(condition, false);
9910
+ walk(statements, false);
9911
+ if (update) walk(update, false);
9912
+ for (const name of invalidated) candidates.delete(name);
9913
+ for (const name of boundary_refs) candidates.delete(name);
9914
+ if (has_raw) candidates.clear();
9915
+ return candidates;
9916
+ }
9917
+ //#endregion
8130
9918
  //#region ../src/build_aarch64/build_while_loop_node.ts
8131
9919
  const CALLEE_SAVED_REGS = [
8132
9920
  "x23",
@@ -8279,6 +10067,20 @@ function build_while_loop_node$1(node, status) {
8279
10067
  for (const p of promoted) status.callee_saved_regs_used.add(p.reg);
8280
10068
  }
8281
10069
  }
10070
+ const old_length_slots = status.string_length_slots;
10071
+ const hoists = scan_string_length_hoists(node.condition, node.statements, node.update, status);
10072
+ if (hoists.size) {
10073
+ if (!status.string_length_slots) status.string_length_slots = /* @__PURE__ */ new Map();
10074
+ for (const [name, target] of hoists) {
10075
+ if (status.string_length_slots.has(name)) continue;
10076
+ const offset = allocate_stack_space(status, 8);
10077
+ status.string_length_slots.set(name, offset);
10078
+ build_node$1(target, status);
10079
+ if (!status.code.endsWith("\n")) status.code += "\n";
10080
+ status.code += `bl _strlen\n`;
10081
+ status.code += `str x0, [x29, #${offset}]\n`;
10082
+ }
10083
+ }
8282
10084
  status.code += `${start_label}:\n`;
8283
10085
  if (!(node.condition.node_type === "value" && node.condition.value === "true")) {
8284
10086
  build_node$1(node.condition, status);
@@ -8298,6 +10100,7 @@ function build_while_loop_node$1(node, status) {
8298
10100
  if (saved_reg_allocs) status.register_allocations = saved_reg_allocs;
8299
10101
  else status.register_allocations = void 0;
8300
10102
  status.buffer_data_cache = saved_buffer_cache;
10103
+ status.string_length_slots = old_length_slots;
8301
10104
  status.loop_labels.pop();
8302
10105
  exit_scope_frame(status, old_scoped_declarations);
8303
10106
  }
@@ -9362,10 +11165,12 @@ function build_struct_functions$1(node, status) {
9362
11165
  status.code += `stp x29, x30, [sp, #-16]!\n`;
9363
11166
  const is_self_param = func.params[0]?.is_self_param;
9364
11167
  const self_is_var = is_self_param && func.params[0]?.declaration === "var";
9365
- const needs_x19 = is_self_param && !self_is_var;
11168
+ const self_is_ref = is_self_param && !!(func.params[0].is_ref || func.params[0].type?.is_ref);
11169
+ const needs_x19 = is_self_param && (!self_is_var || self_is_ref && node.is_simple_type);
11170
+ const x19_through_ref = needs_x19 && self_is_var;
9366
11171
  if (needs_x19) {
9367
11172
  status.code += `str x19, [sp, #-16]!\n`;
9368
- status.code += `mov x19, x0\n`;
11173
+ status.code += x19_through_ref ? `ldr x19, [x0]\n` : `mov x19, x0\n`;
9369
11174
  }
9370
11175
  const param_regs = [
9371
11176
  "x0",
@@ -9399,7 +11204,7 @@ function build_struct_functions$1(node, status) {
9399
11204
  status.function_return_type = func.return_type;
9400
11205
  status.struct_return_buffer = "x8";
9401
11206
  }
9402
- if (needs_x19) status.function_param_regs.set("self", "x19");
11207
+ if (needs_x19 && !self_is_var) status.function_param_regs.set("self", "x19");
9403
11208
  let slot_idx = 0;
9404
11209
  for (let i = 0; i < func.params.length; i++) {
9405
11210
  const param = func.params[i];
@@ -9455,7 +11260,7 @@ function build_struct_functions$1(node, status) {
9455
11260
  const offset = allocate_stack_space(status, size, size);
9456
11261
  status.stack_offsets.set(param.name, offset);
9457
11262
  if (param.is_self_param) {
9458
- const save_reg = needs_x19 ? "x19" : param_regs[second_slot_idx];
11263
+ const save_reg = x19_through_ref ? "x0" : needs_x19 ? "x19" : param_regs[second_slot_idx];
9459
11264
  status.code += `str ${save_reg}, [x29, #${offset}]\n`;
9460
11265
  } else if (second_slot_idx < 8) {
9461
11266
  const reg = param_regs[second_slot_idx];
@@ -9506,7 +11311,7 @@ function build_struct_functions$1(node, status) {
9506
11311
  });
9507
11312
  }
9508
11313
  }
9509
- status.force_heap_strings = scan_force_heap_strings(func.statements);
11314
+ status.force_heap_strings = scan_force_heap_strings(func.statements, status.structs);
9510
11315
  status.buffer_data_cache = void 0;
9511
11316
  const moved_before = new Set(status.moved ?? []);
9512
11317
  if (!emit_owning_buffer_standalone_aarch64(node, func.name, status)) build_block_node$1(func, status);
@@ -10346,6 +12151,14 @@ function load_nursery_struct_address(target, status) {
10346
12151
  //#endregion
10347
12152
  //#region ../src/build_aarch64/build_access_node.ts
10348
12153
  function emit_string_length$1(target, status) {
12154
+ if (target.node_type === "value") {
12155
+ const slot = status.string_length_slots?.get(target.value);
12156
+ if (slot !== void 0) {
12157
+ status.last_result_is_heap = false;
12158
+ status.code += `ldr x0, [x29, #${slot}]\n`;
12159
+ return;
12160
+ }
12161
+ }
10349
12162
  status.last_result_is_heap = false;
10350
12163
  build_node$1(target, status);
10351
12164
  if (!status.code.endsWith("\n")) status.code += "\n";
@@ -11176,6 +12989,7 @@ function build_access_method(node, access_func, status) {
11176
12989
  if (specialized) mono_struct_name = specialized.name;
11177
12990
  }
11178
12991
  const method_name = access_func.mangled_name || `${mono_struct_name}_${access_func.name.replace(/#/g, "")}`;
12992
+ const method_self_is_ref = !!status.structs.find((s) => s.name === mono_struct_name && !s.is_generic)?.functions.find((f) => f.name === access_func.name)?.params?.some((p) => p.is_self_param && (p.is_ref || p.type?.is_ref));
11179
12993
  const return_struct = !access_func.type.is_view && !access_func.type.is_array && !!status.structs.find((s) => s.name === access_func.type.name && !s.is_simple_type && !s.is_class);
11180
12994
  let temp_addr = "";
11181
12995
  let temp_offset = 0;
@@ -11204,7 +13018,7 @@ function build_access_method(node, access_func, status) {
11204
13018
  status.code += `ldr x0, [x0]\n`;
11205
13019
  status.code += `add x0, x0, #8\n`;
11206
13020
  } else if (target_type.is_array && (status.function_array_params?.has(name) || status.function_variadic_params?.has(name)) && !is_local_ref_var(name, status)) status.code += `ldr x0, [x0]\n`;
11207
- else if (target_is_simple && !target_type.is_array && (target_type.name !== "string" || has_stack_offset) && !is_local_ref_var(name, status)) {
13021
+ else if (target_is_simple && !target_type.is_array && (target_type.name !== "string" || has_stack_offset) && !is_local_ref_var(name, status) && !method_self_is_ref) {
11208
13022
  const size = aarch64_size(target_type.name);
11209
13023
  const signed = target_type.name.startsWith("int") || target_type.name === "float" || target_type.name === "float32" || target_type.name === "float64";
11210
13024
  if (size === 1) status.code += signed ? `ldrsb x0, [x0]\n` : `ldrb w0, [x0]\n`;
@@ -12110,13 +13924,7 @@ function build_spawn_node(node, status) {
12110
13924
  if (!status.headers.includes("__nomen_pool_submit")) status.headers += POOL_HEADER;
12111
13925
  const struct_name = `__nomen_spawn_${id}_args`;
12112
13926
  const tramp_name = `__nomen_spawn_${id}_trampoline`;
12113
- const arg_c_types = [];
12114
- for (let i = 0; i < call.params.length; i++) {
12115
- const mono_name = mono_type_name(type_from_value_node$1(call.params[i]));
12116
- const is_class = !!status.structs.find((s) => s.name === mono_name && s.is_class);
12117
- const is_trait = !!status.traits.find((t) => t.name === mono_name);
12118
- arg_c_types.push(is_class || is_trait ? `struct ${mono_name} *` : c_type(mono_name));
12119
- }
13927
+ const arg_c_types = spawn_arg_c_types(call, status);
12120
13928
  const return_type_name = node.function_return_type?.name;
12121
13929
  const returns_value = !!(return_type_name && return_type_name !== "void" && return_type_name !== "?");
12122
13930
  const is_class_ret = returns_value && !!status.structs.find((s) => s.name === return_type_name && s.is_class);
@@ -12189,6 +13997,98 @@ function build_spawn_node(node, status) {
12189
13997
  }
12190
13998
  status.code += `})\n`;
12191
13999
  }
14000
+ const C_BUILTIN_TYPES = /* @__PURE__ */ new Set([
14001
+ "bool",
14002
+ "int",
14003
+ "uint",
14004
+ "int8",
14005
+ "uint8",
14006
+ "int16",
14007
+ "uint16",
14008
+ "int32",
14009
+ "uint32",
14010
+ "int64",
14011
+ "uint64",
14012
+ "float",
14013
+ "ufloat",
14014
+ "float32",
14015
+ "ufloat32",
14016
+ "float64",
14017
+ "ufloat64",
14018
+ "char",
14019
+ "string",
14020
+ "func",
14021
+ "void",
14022
+ "null"
14023
+ ]);
14024
+ /**
14025
+ * Resolve each spawn argument's C type. Classes/traits are pointers;
14026
+ * primitives and by-value structs use c_type's output directly. Generic
14027
+ * instantiations (e.g. Channel<uint64>) use the monomorphized C name
14028
+ * (`Channel_uint64`). The type comes from the CALLEE's declared parameter
14029
+ * whenever it can be resolved — an argument's own node type can differ
14030
+ * (e.g. an int literal `41` passed for a `uint64` param lowers to `long`,
14031
+ * conflicting with the emitted `unsigned long long` prototype). Falls back
14032
+ * to the argument's type when the callee (or its param type) can't be
14033
+ * resolved at build time.
14034
+ */
14035
+ function spawn_arg_c_types(call, status) {
14036
+ const arg_c_types = [];
14037
+ const callee_params = find_spawn_callee(call.name, status)?.params?.filter((p) => !p.is_self_param) ?? [];
14038
+ for (let i = 0; i < call.params.length; i++) {
14039
+ const mono_name = mono_type_name(callee_params[i]?.type && is_resolvable_c_type(callee_params[i].type, status) ? callee_params[i].type : type_from_value_node$1(call.params[i]));
14040
+ const is_class = !!status.structs.find((s) => s.name === mono_name && s.is_class);
14041
+ const is_trait = !!status.traits.find((t) => t.name === mono_name);
14042
+ arg_c_types.push(is_class || is_trait ? `struct ${mono_name} *` : c_type(mono_name));
14043
+ }
14044
+ return arg_c_types;
14045
+ }
14046
+ /** Whether a Nomen type name lowers to a real C type in this build: a
14047
+ * builtin primitive or a struct/enum the backend knows (post-monomorphization).
14048
+ * Unresolved generic type params (`T`) fail this check. */
14049
+ function is_resolvable_c_type(type, status) {
14050
+ if (C_BUILTIN_TYPES.has(type.name)) return true;
14051
+ return !!status.structs.find((s) => s.name === type.name);
14052
+ }
14053
+ /**
14054
+ * Find the spawned function's definition — a top-level function, a function
14055
+ * nested in a block (parse wrappers hoist user code into `main`), or a
14056
+ * struct/trait method (matched by its mangled `Struct_method` name) — so the
14057
+ * trampoline's forward declaration can copy the callee's DECLARED parameter
14058
+ * types. Monomorphized clones are also reachable this way (they are appended
14059
+ * to the AST). A same-named pair would already collide at C level, so the
14060
+ * first match is as good as any.
14061
+ */
14062
+ function find_spawn_callee(name, status) {
14063
+ let found;
14064
+ const visit = (node) => {
14065
+ if (found || !node || typeof node !== "object") return;
14066
+ if (node.node_type === "func") {
14067
+ if (node.name === name) {
14068
+ found = node;
14069
+ return;
14070
+ }
14071
+ } else if (node.node_type === "struct" || node.node_type === "trait") {
14072
+ const functions = node.functions ?? [];
14073
+ for (const func of functions) {
14074
+ const owner = node.name;
14075
+ if (func.name === name || `${owner}_${func.name}` === name) {
14076
+ found = func;
14077
+ return;
14078
+ }
14079
+ }
14080
+ }
14081
+ for (const key of Object.keys(node)) {
14082
+ if (key === "parent" || key === "scope") continue;
14083
+ const v = node[key];
14084
+ if (Array.isArray(v)) for (const item of v) visit(item);
14085
+ else if (v && typeof v === "object" && "node_type" in v) visit(v);
14086
+ if (found) return;
14087
+ }
14088
+ };
14089
+ visit(status.root);
14090
+ return found;
14091
+ }
12192
14092
  //#endregion
12193
14093
  //#region ../src/build_c/build_nursery_spawn.ts
12194
14094
  /**
@@ -12214,13 +14114,7 @@ function build_nursery_spawn(node, nursery_ptr, status) {
12214
14114
  if (!status.headers.includes("__nomen_pool_submit")) status.headers += POOL_HEADER;
12215
14115
  const struct_name = `__nomen_spawn_${id}_args`;
12216
14116
  const tramp_name = `__nomen_spawn_${id}_trampoline`;
12217
- const arg_c_types = [];
12218
- for (let i = 0; i < args.length; i++) {
12219
- const mono_name = mono_type_name(type_from_value_node$1(args[i]));
12220
- const is_class = !!status.structs.find((s) => s.name === mono_name && s.is_class);
12221
- const is_trait = !!status.traits.find((t) => t.name === mono_name);
12222
- arg_c_types.push(is_class || is_trait ? `struct ${mono_name} *` : c_type(mono_name));
12223
- }
14117
+ const arg_c_types = spawn_arg_c_types(call, status);
12224
14118
  const return_type_name = node.function_return_type?.name;
12225
14119
  const returns_value = !!(return_type_name && return_type_name !== "void" && return_type_name !== "?");
12226
14120
  const is_class_ret = returns_value && !!status.structs.find((s) => s.name === return_type_name && s.is_class);
@@ -12661,11 +14555,13 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12661
14555
  status.code += "\n// Auto-free\n";
12662
14556
  commented = true;
12663
14557
  }
12664
- status.code += `free(${key});\n`;
14558
+ const dot = key.indexOf(".");
14559
+ status.code += `free(${c_function_name(key.substring(0, dot))}${key.substring(dot)});\n`;
12665
14560
  if (!persist_string_field_records) status.heap_string_fields.delete(key);
12666
14561
  }
12667
14562
  }
12668
14563
  for (const dec of decls) {
14564
+ const cname = c_function_name(dec.name);
12669
14565
  const struct = status.structs.find((s) => s.name === dec.type.name);
12670
14566
  if (struct && struct.traits.includes("Disposable")) {
12671
14567
  const trait = status.traits.find((t) => t.name === "Disposable");
@@ -12678,7 +14574,7 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12678
14574
  const cast = "(void *(*)(void *))";
12679
14575
  const traitIndex = status.traits.indexOf(trait);
12680
14576
  const funcIndex = trait.functions.indexOf(func);
12681
- status.code += `(${cast}_get_trait_func((void *)&${dec.name}, ${traitIndex}, ${funcIndex}))(&${dec.name});\n`;
14577
+ status.code += `(${cast}_get_trait_func((void *)&${cname}, ${traitIndex}, ${funcIndex}))(&${cname});\n`;
12682
14578
  }
12683
14579
  }
12684
14580
  const is_destructured_field_access = dec.value?.node_type === "access" && dec.value.access.node_type === "access_field" && !dec.value.is_moved;
@@ -12697,15 +14593,15 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12697
14593
  status.code += "\n// Auto-free\n";
12698
14594
  commented = true;
12699
14595
  }
12700
- if (dec.type.is_nullable) status.code += `if (${dec.name}) { ${trait_class_trait}_destroy(${dec.name}); free(${dec.name}); }\n`;
12701
- else status.code += `${trait_class_trait}_destroy(${dec.name}); free(${dec.name});\n`;
14596
+ if (dec.type.is_nullable) status.code += `if (${cname}) { ${trait_class_trait}_destroy(${cname}); free(${cname}); }\n`;
14597
+ else status.code += `${trait_class_trait}_destroy(${cname}); free(${cname});\n`;
12702
14598
  }
12703
14599
  if (!is_destructured_field_access && !is_borrowed_string && (!dec.type.is_static || value_is_heap_string || was_strdup_string_var || is_normalized_join_string) && dec.type.name === "string" && !dec.type.is_array) {
12704
14600
  if (!commented) {
12705
14601
  status.code += "\n// Auto-free\n";
12706
14602
  commented = true;
12707
14603
  }
12708
- status.code += `free(${dec.name});\n`;
14604
+ status.code += `free(${cname});\n`;
12709
14605
  }
12710
14606
  if (!is_destructured_field_access && is_class_var && !dec.type.is_array) {
12711
14607
  if (!commented) {
@@ -12716,10 +14612,10 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12716
14612
  const mono_cls_name = cls ? mono_type_name(dec.type) : void 0;
12717
14613
  const has_destroy_fn = !!cls?.functions.find((f) => f.name === "#destroy") || !!cls?.is_class;
12718
14614
  if (cls) {
12719
- const destroy_call = has_destroy_fn ? `${mono_cls_name}_destroy(${dec.name}); ` : "";
12720
- if (dec.type.is_nullable) status.code += `if (${dec.name}) { ${destroy_call}free(${dec.name}); }\n`;
12721
- else status.code += `${destroy_call}free(${dec.name});\n`;
12722
- } else status.code += `free(${dec.name});\n`;
14615
+ const destroy_call = has_destroy_fn ? `${mono_cls_name}_destroy(${cname}); ` : "";
14616
+ if (dec.type.is_nullable) status.code += `if (${cname}) { ${destroy_call}free(${cname}); }\n`;
14617
+ else status.code += `${destroy_call}free(${cname});\n`;
14618
+ } else status.code += `free(${cname});\n`;
12723
14619
  }
12724
14620
  if (!is_destructured_field_access && !is_class_var && !dec.type.is_array && dec.type.name !== "string") {
12725
14621
  const mono_name = mono_type_name(dec.type);
@@ -12729,7 +14625,7 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12729
14625
  status.code += "\n// Auto-free\n";
12730
14626
  commented = true;
12731
14627
  }
12732
- emit_struct_destroys(status, struct_type, dec.name);
14628
+ emit_struct_destroys(status, struct_type, cname);
12733
14629
  }
12734
14630
  }
12735
14631
  if (!!status.traits.find((t) => t.name === dec.type.name) && !is_destructured_field_access && !dec.type.is_array && dec.value) {
@@ -12740,7 +14636,7 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12740
14636
  status.code += "\n// Auto-free\n";
12741
14637
  commented = true;
12742
14638
  }
12743
- emit_struct_destroys(status, concrete, dec.name);
14639
+ emit_struct_destroys(status, concrete, cname);
12744
14640
  }
12745
14641
  }
12746
14642
  if (!is_destructured_field_access && !is_class_var && !dec.type.is_array && is_nullable_struct_type(dec.type, status)) {
@@ -12750,8 +14646,8 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12750
14646
  status.code += "\n// Auto-free\n";
12751
14647
  commented = true;
12752
14648
  }
12753
- const body = capture_destroys(status, inner, dec.name, ".");
12754
- status.code += `if (${has_flag_name(dec.name)}) { ${body} }\n`;
14649
+ const body = capture_destroys(status, inner, cname, ".");
14650
+ status.code += `if (${has_flag_name(cname)}) { ${body} }\n`;
12755
14651
  }
12756
14652
  }
12757
14653
  if (!is_destructured_field_access && dec.type.is_array && status.heap_array_vars?.has(dec.name)) {
@@ -12764,17 +14660,17 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12764
14660
  const elem_is_string = elem_name === "string";
12765
14661
  const elem_c_type = elem_is_class ? `struct ${elem_name}*` : elem_name;
12766
14662
  if (elem_is_class) {
12767
- status.code += `for (long _i = 0; _i < ${dec.name}->length; _i++) {\n`;
12768
- status.code += `\t${elem_c_type}* _data = (${elem_c_type}*)((char*)${dec.name} + sizeof(struct Array_${elem_name}));\n`;
14663
+ status.code += `for (long _i = 0; _i < ${cname}->length; _i++) {\n`;
14664
+ status.code += `\t${elem_c_type}* _data = (${elem_c_type}*)((char*)${cname} + sizeof(struct Array_${elem_name}));\n`;
12769
14665
  status.code += `\t${elem_name}_destroy(_data[_i]); free(_data[_i]);\n`;
12770
14666
  status.code += `}\n`;
12771
14667
  } else if (elem_is_string) {
12772
- status.code += `for (long _i = 0; _i < ${dec.name}->length; _i++) {\n`;
12773
- status.code += `\tchar** _data = (char**)((char*)${dec.name} + sizeof(struct Array_string));\n`;
14668
+ status.code += `for (long _i = 0; _i < ${cname}->length; _i++) {\n`;
14669
+ status.code += `\tchar** _data = (char**)((char*)${cname} + sizeof(struct Array_string));\n`;
12774
14670
  status.code += `\tfree(_data[_i]);\n`;
12775
14671
  status.code += `}\n`;
12776
14672
  }
12777
- status.code += `free(${dec.name});\n`;
14673
+ status.code += `free(${cname});\n`;
12778
14674
  }
12779
14675
  if (!is_destructured_field_access && dec.type.is_array && status.stack_array_vars?.has(dec.name)) {
12780
14676
  if (!commented) {
@@ -12787,13 +14683,13 @@ function free_scoped_declarations(status, decls, persist_string_field_records =
12787
14683
  const elem_is_string = elem_name === "string";
12788
14684
  const elem_struct_type = status.structs.find((s) => s.name === elem_name && !s.is_simple_type && !s.is_generic);
12789
14685
  const arr_len = status.stack_array_lengths?.get(dec.name) ?? "0";
12790
- if (elem_is_string) status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { free(${dec.name}[_i]); }\n`;
14686
+ if (elem_is_string) status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { free(${cname}[_i]); }\n`;
12791
14687
  else if (elem_is_class) {
12792
- if (has_destroy(elem_struct)) status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { if (${dec.name}[_i]) { ${elem_name}_destroy(${dec.name}[_i]); free(${dec.name}[_i]); } }\n`;
12793
- else status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { free(${dec.name}[_i]); }\n`;
14688
+ if (has_destroy(elem_struct)) status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { if (${cname}[_i]) { ${elem_name}_destroy(${cname}[_i]); free(${cname}[_i]); } }\n`;
14689
+ else status.code += `for (long _i = 0; _i < ${arr_len}; _i++) { free(${cname}[_i]); }\n`;
12794
14690
  } else if (elem_struct_type && struct_needs_destroy(elem_struct_type, status)) {
12795
14691
  status.code += `for (long _i = 0; _i < ${arr_len}; _i++) {\n`;
12796
- emit_struct_destroys(status, elem_struct_type, `${dec.name}[_i]`);
14692
+ emit_struct_destroys(status, elem_struct_type, `${cname}[_i]`);
12797
14693
  status.code += `}\n`;
12798
14694
  }
12799
14695
  }
@@ -13331,7 +15227,8 @@ function build_access_node(node, status) {
13331
15227
  const label = access_func.mangled_name || trait_default_label || `${mono_struct_name}_${access_func.name.replace(/#/g, "")}`;
13332
15228
  status.code += `${label}(`;
13333
15229
  if (!access_func.is_static) {
13334
- if (!built_in_types.includes(method_type?.name || "")) {
15230
+ const method_self_is_ref = !!target_method?.params?.some((p) => p.is_self_param && (p.is_ref || p.type?.is_ref));
15231
+ if (!built_in_types.includes(method_type?.name || "") || method_self_is_ref) {
13335
15232
  const target_value = node.target.node_type === "value" ? node.target.value : "";
13336
15233
  const target_is_ref_class_param = !!status.ref_class_params?.has(target_value);
13337
15234
  if (!(!!status.function_ref_params?.has(target_value) || !!status.class_vars?.has(target_value) || !!status.heap_array_vars?.has(target_value))) status.code += "&";
@@ -13404,6 +15301,13 @@ function resolve_access_field_type(node, status) {
13404
15301
  return (status.structs.find((s) => s.name === base_type.name && !s.is_simple_type)?.fields.find((f) => f.name === field_name))?.type;
13405
15302
  }
13406
15303
  function emit_string_length(target, status) {
15304
+ if (target.node_type === "value") {
15305
+ const temp = status.string_length_temps?.get(target.value);
15306
+ if (temp) {
15307
+ status.code += temp;
15308
+ return;
15309
+ }
15310
+ }
13407
15311
  if (is_owned_heap_temp(target, status)) {
13408
15312
  const id = status.label_counter = (status.label_counter ?? 0) + 1;
13409
15313
  const tmp = `_slen_${id}`;
@@ -13517,12 +15421,14 @@ function build_assignment_node(node, status) {
13517
15421
  if (!node.operator && node.left_value.node_type === "access" && node.left_value.access.node_type === "access_field" && node.left_value.access.type?.name === "string" && !node.left_value.access.type?.is_ref && !node.left_value.access.type?.is_array) {
13518
15422
  const access_lhs = node.left_value;
13519
15423
  const field_access_node = access_lhs.access;
13520
- const target_type = type_from_value_node$1(access_lhs.target);
15424
+ let target_type = type_from_value_node$1(access_lhs.target);
15425
+ if (!target_type?.name && access_lhs.target.node_type === "value" && access_lhs.target.value === "self" && status.current_struct) target_type = new Type(status.current_struct.name);
13521
15426
  const target_struct = target_type?.name ? status.structs.find((s) => s.name === target_type.name && !s.is_simple_type) : null;
13522
15427
  const target_var = access_lhs.target.node_type === "value" ? access_lhs.target.value : "";
15428
+ const self_target = target_var === "self";
13523
15429
  const tracked_key = `${target_var}.${field_access_node.name}`;
13524
15430
  const old_was_heap = !!target_struct?.is_class || !!status.heap_string_fields?.has(tracked_key);
13525
- if (target_struct && target_var && target_var !== "self") {
15431
+ if (target_struct && target_var && (!self_target || target_struct.is_class)) {
13526
15432
  const fresh_heap = is_owned_heap_temp(node.right_value, status);
13527
15433
  const before_len = status.code.length;
13528
15434
  build_node(node.left_value, status);
@@ -13637,6 +15543,12 @@ function build_assignment_node(node, status) {
13637
15543
  }
13638
15544
  status.code += `free(${lhs_name});\n`;
13639
15545
  }
15546
+ if (lhs_is_string && !node.swap && rhs_is_bare_value && rhs.value.length >= 2 && rhs.value.startsWith("\"") && rhs.value.endsWith("\"")) {
15547
+ status.code += `${lhs_name} = strdup(`;
15548
+ build_node(node.right_value, status);
15549
+ status.code += `);\n`;
15550
+ return;
15551
+ }
13640
15552
  if (rhs_is_bare_value) {
13641
15553
  if (lhs_is_class) {
13642
15554
  if (!node.swap) splice_decl_from_c_scopes(status, rhs.value);
@@ -13685,6 +15597,20 @@ function build_assignment_node(node, status) {
13685
15597
  }
13686
15598
  return;
13687
15599
  }
15600
+ if (!node.operator && !node.swap && node.left_value.node_type === "value") {
15601
+ const lhs_name = node.left_value.value;
15602
+ const lhs_type = type_from_value_node$1(node.left_value);
15603
+ if (lhs_type?.name === "string" && !lhs_type.is_array && !!status.function_ref_params?.has(lhs_name) && !status.ref_class_params?.has(lhs_name)) {
15604
+ const fresh_heap = is_owned_heap_temp(node.right_value, status);
15605
+ build_node(node.left_value, status);
15606
+ status.code += ` = `;
15607
+ if (!fresh_heap) status.code += `strdup(`;
15608
+ build_node(node.right_value, status);
15609
+ if (!fresh_heap) status.code += `)`;
15610
+ status.code += `;\n`;
15611
+ return;
15612
+ }
15613
+ }
13688
15614
  if (!node.operator && node.left_value.node_type === "value" && status.ref_local_vars?.has(node.left_value.value)) {
13689
15615
  const lhs_name = node.left_value.value;
13690
15616
  status.code += `${lhs_name} = &`;
@@ -15808,6 +17734,52 @@ function emit_nullable_arg_flag(arg, status) {
15808
17734
  status.code += `1`;
15809
17735
  }
15810
17736
  //#endregion
17737
+ //#region ../src/build_c/utils/build_condition.ts
17738
+ /**
17739
+ * Build a controlling expression (an if/while/for condition or a switch-case
17740
+ * comparison) and emit it without redundant fully-wrapping outer parentheses.
17741
+ * The codegen wraps every binary operation in parens (build_default_binary),
17742
+ * so emitting the condition verbatim would read `if ((a == b))`, which clang
17743
+ * flags as -Wparentheses-equality ("equality comparison with extraneous
17744
+ * parentheses").
17745
+ */
17746
+ function build_condition(node, status) {
17747
+ const before = status.code.length;
17748
+ build_node(node, status);
17749
+ status.code = status.code.substring(0, before) + strip_outer_parens(status.code.substring(before));
17750
+ }
17751
+ /**
17752
+ * Strip outer paren layers that wrap the ENTIRE expression (the opening paren
17753
+ * matches only the final character). A layer is removed only when the inner
17754
+ * text does not start with `{` — a GCC/clang statement-expression
17755
+ * `({ ... })` must keep its wrapper to stay a valid expression. Parens
17756
+ * inside string/char literals can only make the scan conservative (they
17757
+ * unbalance the depth count, so nothing is stripped), never incorrect.
17758
+ */
17759
+ function strip_outer_parens(expr) {
17760
+ let code = expr.trim();
17761
+ while (code.length > 1 && code.startsWith("(") && code.endsWith(")")) {
17762
+ let depth = 0;
17763
+ let wraps_whole = true;
17764
+ for (let i = 0; i < code.length; i++) {
17765
+ const ch = code[i];
17766
+ if (ch === "(") depth++;
17767
+ else if (ch === ")") {
17768
+ depth--;
17769
+ if (depth === 0 && i < code.length - 1) {
17770
+ wraps_whole = false;
17771
+ break;
17772
+ }
17773
+ }
17774
+ }
17775
+ if (!wraps_whole || depth !== 0) break;
17776
+ const inner = code.slice(1, -1).trim();
17777
+ if (inner.startsWith("{")) break;
17778
+ code = inner;
17779
+ }
17780
+ return code;
17781
+ }
17782
+ //#endregion
15811
17783
  //#region ../src/build_c/build_if_else_node.ts
15812
17784
  function build_if_else_node(node, status) {
15813
17785
  const old_scoped_declarations = status.scoped_declarations;
@@ -15816,7 +17788,7 @@ function build_if_else_node(node, status) {
15816
17788
  status.deferred_frees = [];
15817
17789
  emit_allocations(node.condition, status);
15818
17790
  status.code += `if (`;
15819
- build_node(node.condition, status);
17791
+ build_condition(node.condition, status);
15820
17792
  status.code += `) {\n`;
15821
17793
  if (node.if_branch) {
15822
17794
  build_block_node(node.if_branch, status);
@@ -16229,6 +18201,7 @@ function build_switch_node(node, status) {
16229
18201
  }
16230
18202
  cond_code = cond_code.trim();
16231
18203
  while (cond_code.startsWith("(") && !cond_code.endsWith(")")) cond_code = cond_code.substring(1).trim();
18204
+ cond_code = strip_outer_parens(cond_code);
16232
18205
  if (decls.length > 0) status.code += decls.join("\n") + "\n";
16233
18206
  const prefix = status.code.endsWith("} else ") ? "" : "";
16234
18207
  status.code += `${prefix}if (${cond_code}) {\n`;
@@ -16302,16 +18275,29 @@ function build_while_loop_node(node, status) {
16302
18275
  const old_deferred_frees = status.deferred_frees;
16303
18276
  status.deferred_frees = [];
16304
18277
  push_c_loop_frame(status);
18278
+ const old_length_temps = status.string_length_temps;
18279
+ const hoists = scan_string_length_hoists(node.condition, node.statements, node.update, status);
18280
+ if (hoists.size) {
18281
+ if (!status.string_length_temps) status.string_length_temps = /* @__PURE__ */ new Map();
18282
+ for (const [name, target] of hoists) {
18283
+ if (status.string_length_temps.has(name)) continue;
18284
+ const temp = `_slh_${status.label_counter = (status.label_counter ?? 0) + 1}`;
18285
+ status.string_length_temps.set(name, temp);
18286
+ status.code += `const long ${temp} = (long)strlen(`;
18287
+ build_node(target, status);
18288
+ status.code += `);\n`;
18289
+ }
18290
+ }
16305
18291
  emit_allocations(node.condition, status);
16306
18292
  if (node.update) {
16307
18293
  status.code += `for (; `;
16308
- build_node(node.condition, status);
18294
+ build_condition(node.condition, status);
16309
18295
  status.code += `; `;
16310
18296
  build_node(node.update, status);
16311
18297
  status.code += `) {\n`;
16312
18298
  } else {
16313
18299
  status.code += `while (`;
16314
- build_node(node.condition, status);
18300
+ build_condition(node.condition, status);
16315
18301
  status.code += `) {\n`;
16316
18302
  }
16317
18303
  build_block_node(node, status);
@@ -16321,6 +18307,7 @@ function build_while_loop_node(node, status) {
16321
18307
  leave_c_scope(status);
16322
18308
  status.scoped_declarations = old_scoped_declarations;
16323
18309
  status.deferred_frees = old_deferred_frees;
18310
+ status.string_length_temps = old_length_temps;
16324
18311
  }
16325
18312
  //#endregion
16326
18313
  //#region ../src/build_c/build_node.ts
@@ -16897,7 +18884,7 @@ const PREFIX_POSITIONS = /* @__PURE__ */ new Set([
16897
18884
  "!"
16898
18885
  ]);
16899
18886
  /** Render a line's pieces with normalized spacing. */
16900
- function join$1(pieces) {
18887
+ function join$2(pieces) {
16901
18888
  let out = "";
16902
18889
  for (let i = 0; i < pieces.length; i++) {
16903
18890
  if (i > 0 && needs_space(pieces, i)) out += " ";
@@ -17529,19 +19516,19 @@ function is_continuation(previous, pieces) {
17529
19516
  }
17530
19517
  /** Emit a line, breaking its bracketed list up if it is over the print width. */
17531
19518
  function wrap(pieces, level, options) {
17532
- const text = join$1(pieces);
19519
+ const text = join$2(pieces);
17533
19520
  if (level * options.tab_width + text.length <= options.print_width) return [indent(level, options) + text];
17534
19521
  const group = find_group(pieces);
17535
19522
  if (!group) return [indent(level, options) + text];
17536
19523
  const items = split_items(pieces.slice(group.open + 1, group.close));
17537
19524
  if (items.length < 2) return [indent(level, options) + text];
17538
19525
  const trailing = options.trailing_comma && group.is_list;
17539
- const out = [indent(level, options) + join$1(pieces.slice(0, group.open + 1))];
19526
+ const out = [indent(level, options) + join$2(pieces.slice(0, group.open + 1))];
17540
19527
  items.forEach((item, index) => {
17541
19528
  const with_comma = !(index === items.length - 1) || trailing ? [...item, comma_piece()] : [...item];
17542
19529
  out.push(...wrap(with_comma, level + 1, options));
17543
19530
  });
17544
- out.push(indent(level, options) + join$1(pieces.slice(group.close)));
19531
+ out.push(indent(level, options) + join$2(pieces.slice(group.close)));
17545
19532
  return out;
17546
19533
  }
17547
19534
  /** The first bracket group on the line that opens and closes there and holds a list. */
@@ -17649,7 +19636,7 @@ function sort_imports(lines) {
17649
19636
  let end = i;
17650
19637
  while (end + 1 < lines.length && is_import(lines[end + 1])) end++;
17651
19638
  if (end > i) {
17652
- const run = lines.slice(i, end + 1).sort((a, b) => join$1(a.pieces) < join$1(b.pieces) ? -1 : 1);
19639
+ const run = lines.slice(i, end + 1).sort((a, b) => join$2(a.pieces) < join$2(b.pieces) ? -1 : 1);
17653
19640
  lines.splice(i, end - i + 1, ...run);
17654
19641
  }
17655
19642
  i = end;
@@ -17766,7 +19753,7 @@ function fallback_lib_path() {
17766
19753
  return default_lib_path;
17767
19754
  }
17768
19755
  let test_src_dir;
17769
- function join(entry_file_path, lib_path, options) {
19756
+ function join$1(entry_file_path, lib_path, options) {
17770
19757
  const folder_path = path.dirname(entry_file_path);
17771
19758
  const file_path = path.basename(entry_file_path);
17772
19759
  const inputs = /* @__PURE__ */ new Map();
@@ -22785,6 +24772,28 @@ function raw_c_type_name(name) {
22785
24772
  default: return name;
22786
24773
  }
22787
24774
  }
24775
+ /**
24776
+ * Whether a raw block's content is pure aarch64 assembly (`#arch: aarch64`).
24777
+ * asm immediates (`mov x3, #T_SIZE`) need the compiler's numeric layout
24778
+ * size; every other target (`#arch: c`, `aarch64_use_c`, or untagged) is C
24779
+ * source, where the size must be `sizeof(T)` — C lays out structs with
24780
+ * natural alignment (tail padding), so the compiler's unpadded numeric size
24781
+ * would disagree with C's own `sizeof`/pointer-arithmetic strides and
24782
+ * undersize heap slabs (heap-buffer-overflow on wide-struct elements).
24783
+ */
24784
+ function raw_block_is_pure_asm(value) {
24785
+ for (const line of value.split("\n")) {
24786
+ const trimmed = line.trim();
24787
+ if (!trimmed) continue;
24788
+ if (trimmed.startsWith("#arch:")) {
24789
+ const arches = trimmed.substring(6).split(",").map((a) => a.trim()).filter((a) => a.length > 0);
24790
+ return arches.length > 0 && arches.every((a) => a === "aarch64");
24791
+ }
24792
+ if (trimmed.startsWith("#platform:") || trimmed.startsWith("#scope:")) continue;
24793
+ break;
24794
+ }
24795
+ return false;
24796
+ }
22788
24797
  function substitute_raw_in_node(node, substitution, structs, deref_params = /* @__PURE__ */ new Set()) {
22789
24798
  if (node.node_type === "raw") {
22790
24799
  const raw = node;
@@ -22797,7 +24806,8 @@ function substitute_raw_in_node(node, substitution, structs, deref_params = /* @
22797
24806
  else c_type_name = raw_c_type_name(type);
22798
24807
  value = value.replace(new RegExp(`\\b${param}\\b`, "g"), c_type_name);
22799
24808
  const size = raw_type_size(type, structs);
22800
- value = value.replace(new RegExp(`\\b${param}_SIZE\\b`, "g"), String(size));
24809
+ const size_expr = raw_block_is_pure_asm(value) ? String(size) : `sizeof(${c_type_name})`;
24810
+ value = value.replace(new RegExp(`\\b${param}_SIZE\\b`, "g"), size_expr);
22801
24811
  value = value.replace(new RegExp(`\\b${param}_destroy\\b`, "g"), `${type}_destroy`);
22802
24812
  value = value.replace(new RegExp(`\\b${param}_NEEDS_STRDUP\\b`, "g"), type === "string" ? "1" : "0");
22803
24813
  }
@@ -23211,6 +25221,11 @@ function check_access_node(node, status) {
23211
25221
  add_error(status, `Unknown target: ${value_from_value_node(node.target)}`, node.target.start);
23212
25222
  return false;
23213
25223
  }
25224
+ if ((node.target.node_type === "func_call" || node.target.node_type === "access" && node.target.access.node_type === "access_func") && is_owning_struct_type_requiring_move(target_type, status)) {
25225
+ const decl = new DeclarationNode(node.target.start, "private", "const", `_recv_${status.var_name_counter.value++}`, target_type, node.target);
25226
+ status.allocations.push(decl);
25227
+ node.target = new ValueNode(node.target.start, decl.name, target_type);
25228
+ }
23214
25229
  if (node.access.node_type === "access_field") {
23215
25230
  const af = node.access;
23216
25231
  if (af.is_destructure) {
@@ -28243,7 +30258,7 @@ function run_test_file(entry_path, lib_path, arch) {
28243
30258
  ms: 0
28244
30259
  };
28245
30260
  const resolved = path.resolve(entry_path);
28246
- const input = join(resolved, lib_path);
30261
+ const input = join$1(resolved, lib_path);
28247
30262
  const library = lib_path ? get_library(lib_path) : void 0;
28248
30263
  const parsed = parse(input + "\n" + harness, library, resolved);
28249
30264
  if (parsed.errors.length) {
@@ -28609,7 +30624,7 @@ function processFile(filename, config, mode, program_args) {
28609
30624
  if (!config.lib) config.lib = resolve_lib(resolved);
28610
30625
  let startTime = performance.now();
28611
30626
  const resolved_path = path.resolve(filename);
28612
- const input = join(resolved_path, config.lib);
30627
+ const input = join$1(resolved_path, config.lib);
28613
30628
  const parsed = parse(input, config.lib ? get_library(config.lib) : void 0, resolved_path);
28614
30629
  let errors = parsed.errors;
28615
30630
  if (errors.length) {