tinyc-web 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/tinyc-web.js ADDED
@@ -0,0 +1,3501 @@
1
+ var TinycWeb = (() => {
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // web-entry.mjs
21
+ var web_entry_exports = {};
22
+ __export(web_entry_exports, {
23
+ DEFAULT_RUN_OUTPUT: () => DEFAULT_RUN_OUTPUT,
24
+ DEFAULT_TARGET: () => DEFAULT_TARGET,
25
+ IndexedDbFsStore: () => IndexedDbFsStore,
26
+ MemoryFsStore: () => MemoryFsStore,
27
+ SUPPORTED_TARGETS: () => SUPPORTED_TARGETS,
28
+ TARGETS: () => TARGETS,
29
+ TCC_OUTPUT: () => TCC_OUTPUT,
30
+ Tinyc: () => Tinyc,
31
+ TinycError: () => TinycError,
32
+ TinycMissingExportError: () => TinycMissingExportError,
33
+ TinycMissingImportError: () => TinycMissingImportError,
34
+ TinycRunNotSupportedError: () => TinycRunNotSupportedError,
35
+ TinycState: () => TinycState,
36
+ VFS_CACHE_MAX_BYTES: () => VFS_CACHE_MAX_BYTES,
37
+ VFS_CACHE_MAX_ENTRIES: () => VFS_CACHE_MAX_ENTRIES,
38
+ VIRTUAL_BIN_PATH: () => VIRTUAL_BIN_PATH,
39
+ VirtualFS: () => VirtualFS,
40
+ WasiExit: () => WasiExit,
41
+ clearTargetModuleCache: () => clearTargetModuleCache,
42
+ createDefaultIO: () => createDefaultIO,
43
+ createFsStore: () => createFsStore,
44
+ default: () => index_default,
45
+ flushIO: () => flushIO,
46
+ getLoadedTargets: () => getLoadedTargets,
47
+ isRunnableTarget: () => isRunnableTarget,
48
+ loadSysrootManifest: () => loadSysrootManifest,
49
+ loadTinyc: () => loadTinyc,
50
+ normalizeIO: () => normalizeIO,
51
+ normalizeVfsPath: () => normalizeVfsPath,
52
+ readModuleCString: () => readModuleCString,
53
+ readModuleData: () => readModuleData,
54
+ registerGlobalShim: () => registerGlobalShim,
55
+ registerGlobalShims: () => registerGlobalShims,
56
+ runWasmModule: () => runWasmModule,
57
+ runWasmModuleSync: () => runWasmModuleSync,
58
+ sysrootManifest: () => sysrootManifest,
59
+ targetModuleFiles: () => targetModuleFiles,
60
+ unregisterGlobalShim: () => unregisterGlobalShim,
61
+ writeModuleData: () => writeModuleData
62
+ });
63
+
64
+ // sysroot-manifests/wasm32-wasi.json
65
+ var wasm32_wasi_default = {
66
+ name: "tinyc-sysroot",
67
+ version: 1,
68
+ target: "wasm32-wasi",
69
+ binPath: "/sysroot/bin/tinyc",
70
+ includeDir: "/sysroot/include",
71
+ includeFiles: [
72
+ {
73
+ path: "/sysroot/include/float.h",
74
+ source: "include/float.h"
75
+ },
76
+ {
77
+ path: "/sysroot/include/stdalign.h",
78
+ source: "include/stdalign.h"
79
+ },
80
+ {
81
+ path: "/sysroot/include/stdarg.h",
82
+ source: "include/stdarg.h"
83
+ },
84
+ {
85
+ path: "/sysroot/include/stdatomic.h",
86
+ source: "include/stdatomic.h"
87
+ },
88
+ {
89
+ path: "/sysroot/include/stdbool.h",
90
+ source: "include/stdbool.h"
91
+ },
92
+ {
93
+ path: "/sysroot/include/stddef.h",
94
+ source: "include/stddef.h"
95
+ },
96
+ {
97
+ path: "/sysroot/include/stdnoreturn.h",
98
+ source: "include/stdnoreturn.h"
99
+ },
100
+ {
101
+ path: "/sysroot/include/tccdefs.h",
102
+ source: "include/tccdefs.h"
103
+ },
104
+ {
105
+ path: "/sysroot/include/tgmath.h",
106
+ source: "include/tgmath.h"
107
+ },
108
+ {
109
+ path: "/sysroot/include/varargs.h",
110
+ source: "include/varargs.h"
111
+ },
112
+ {
113
+ path: "/sysroot/include/tcclib.h",
114
+ source: "tcclib.h"
115
+ }
116
+ ],
117
+ libDir: "/sysroot/lib",
118
+ libFiles: [
119
+ {
120
+ binary: true,
121
+ path: "/sysroot/lib/libtcc1.a",
122
+ source: "lib/wasm32-wasi/libtcc1.a"
123
+ }
124
+ ],
125
+ outputs: {
126
+ module: {
127
+ format: "WebAssembly",
128
+ ext: ".wasm"
129
+ }
130
+ }
131
+ };
132
+
133
+ // sysroot-manifests/x86_64-linux-gnu.json
134
+ var x86_64_linux_gnu_default = {
135
+ name: "tinyc-sysroot",
136
+ version: 1,
137
+ target: "x86_64-linux-gnu",
138
+ binPath: "/sysroot/bin/tinyc",
139
+ includeDir: "/sysroot/include",
140
+ includeFiles: [
141
+ {
142
+ path: "/sysroot/include/float.h",
143
+ source: "include/float.h"
144
+ },
145
+ {
146
+ path: "/sysroot/include/stdalign.h",
147
+ source: "include/stdalign.h"
148
+ },
149
+ {
150
+ path: "/sysroot/include/stdarg.h",
151
+ source: "include/stdarg.h"
152
+ },
153
+ {
154
+ path: "/sysroot/include/stdatomic.h",
155
+ source: "include/stdatomic.h"
156
+ },
157
+ {
158
+ path: "/sysroot/include/stdbool.h",
159
+ source: "include/stdbool.h"
160
+ },
161
+ {
162
+ path: "/sysroot/include/stddef.h",
163
+ source: "include/stddef.h"
164
+ },
165
+ {
166
+ path: "/sysroot/include/stdnoreturn.h",
167
+ source: "include/stdnoreturn.h"
168
+ },
169
+ {
170
+ path: "/sysroot/include/tccdefs.h",
171
+ source: "include/tccdefs.h"
172
+ },
173
+ {
174
+ path: "/sysroot/include/tgmath.h",
175
+ source: "include/tgmath.h"
176
+ },
177
+ {
178
+ path: "/sysroot/include/varargs.h",
179
+ source: "include/varargs.h"
180
+ },
181
+ {
182
+ path: "/sysroot/include/tcclib.h",
183
+ source: "tcclib.h"
184
+ }
185
+ ],
186
+ libDir: "/sysroot/lib",
187
+ libFiles: [
188
+ {
189
+ binary: true,
190
+ path: "/sysroot/lib/libtcc1.a",
191
+ source: "lib/x86_64-linux-gnu/libtcc1.a"
192
+ }
193
+ ],
194
+ outputs: {
195
+ exe: {
196
+ format: "ELF executable",
197
+ ext: ""
198
+ },
199
+ obj: {
200
+ format: "ELF relocatable",
201
+ ext: ".o"
202
+ },
203
+ shared: {
204
+ format: "ELF shared object",
205
+ ext: ".so"
206
+ },
207
+ ar: {
208
+ format: "ar archive",
209
+ ext: ".a"
210
+ }
211
+ }
212
+ };
213
+
214
+ // sysroot-manifests/aarch64-linux-gnu.json
215
+ var aarch64_linux_gnu_default = {
216
+ name: "tinyc-sysroot",
217
+ version: 1,
218
+ target: "aarch64-linux-gnu",
219
+ binPath: "/sysroot/bin/tinyc",
220
+ includeDir: "/sysroot/include",
221
+ includeFiles: [
222
+ {
223
+ path: "/sysroot/include/float.h",
224
+ source: "include/float.h"
225
+ },
226
+ {
227
+ path: "/sysroot/include/stdalign.h",
228
+ source: "include/stdalign.h"
229
+ },
230
+ {
231
+ path: "/sysroot/include/stdarg.h",
232
+ source: "include/stdarg.h"
233
+ },
234
+ {
235
+ path: "/sysroot/include/stdatomic.h",
236
+ source: "include/stdatomic.h"
237
+ },
238
+ {
239
+ path: "/sysroot/include/stdbool.h",
240
+ source: "include/stdbool.h"
241
+ },
242
+ {
243
+ path: "/sysroot/include/stddef.h",
244
+ source: "include/stddef.h"
245
+ },
246
+ {
247
+ path: "/sysroot/include/stdnoreturn.h",
248
+ source: "include/stdnoreturn.h"
249
+ },
250
+ {
251
+ path: "/sysroot/include/tccdefs.h",
252
+ source: "include/tccdefs.h"
253
+ },
254
+ {
255
+ path: "/sysroot/include/tgmath.h",
256
+ source: "include/tgmath.h"
257
+ },
258
+ {
259
+ path: "/sysroot/include/varargs.h",
260
+ source: "include/varargs.h"
261
+ },
262
+ {
263
+ path: "/sysroot/include/tcclib.h",
264
+ source: "tcclib.h"
265
+ }
266
+ ],
267
+ libDir: "/sysroot/lib",
268
+ libFiles: [
269
+ {
270
+ binary: true,
271
+ path: "/sysroot/lib/libtcc1.a",
272
+ source: "lib/aarch64-linux-gnu/libtcc1.a"
273
+ }
274
+ ],
275
+ outputs: {
276
+ exe: {
277
+ format: "ELF executable",
278
+ ext: ""
279
+ },
280
+ obj: {
281
+ format: "ELF relocatable",
282
+ ext: ".o"
283
+ },
284
+ shared: {
285
+ format: "ELF shared object",
286
+ ext: ".so"
287
+ },
288
+ ar: {
289
+ format: "ar archive",
290
+ ext: ".a"
291
+ }
292
+ }
293
+ };
294
+
295
+ // sysroot-manifests/riscv64-linux-gnu.json
296
+ var riscv64_linux_gnu_default = {
297
+ name: "tinyc-sysroot",
298
+ version: 1,
299
+ target: "riscv64-linux-gnu",
300
+ binPath: "/sysroot/bin/tinyc",
301
+ includeDir: "/sysroot/include",
302
+ includeFiles: [
303
+ {
304
+ path: "/sysroot/include/float.h",
305
+ source: "include/float.h"
306
+ },
307
+ {
308
+ path: "/sysroot/include/stdalign.h",
309
+ source: "include/stdalign.h"
310
+ },
311
+ {
312
+ path: "/sysroot/include/stdarg.h",
313
+ source: "include/stdarg.h"
314
+ },
315
+ {
316
+ path: "/sysroot/include/stdatomic.h",
317
+ source: "include/stdatomic.h"
318
+ },
319
+ {
320
+ path: "/sysroot/include/stdbool.h",
321
+ source: "include/stdbool.h"
322
+ },
323
+ {
324
+ path: "/sysroot/include/stddef.h",
325
+ source: "include/stddef.h"
326
+ },
327
+ {
328
+ path: "/sysroot/include/stdnoreturn.h",
329
+ source: "include/stdnoreturn.h"
330
+ },
331
+ {
332
+ path: "/sysroot/include/tccdefs.h",
333
+ source: "include/tccdefs.h"
334
+ },
335
+ {
336
+ path: "/sysroot/include/tgmath.h",
337
+ source: "include/tgmath.h"
338
+ },
339
+ {
340
+ path: "/sysroot/include/varargs.h",
341
+ source: "include/varargs.h"
342
+ },
343
+ {
344
+ path: "/sysroot/include/tcclib.h",
345
+ source: "tcclib.h"
346
+ }
347
+ ],
348
+ libDir: "/sysroot/lib",
349
+ libFiles: [
350
+ {
351
+ binary: true,
352
+ path: "/sysroot/lib/libtcc1.a",
353
+ source: "lib/riscv64-linux-gnu/libtcc1.a"
354
+ }
355
+ ],
356
+ outputs: {
357
+ exe: {
358
+ format: "ELF executable",
359
+ ext: ""
360
+ },
361
+ obj: {
362
+ format: "ELF relocatable",
363
+ ext: ".o"
364
+ },
365
+ shared: {
366
+ format: "ELF shared object",
367
+ ext: ".so"
368
+ },
369
+ ar: {
370
+ format: "ar archive",
371
+ ext: ".a"
372
+ }
373
+ }
374
+ };
375
+
376
+ // sysroot-manifests/x86_64-windows.json
377
+ var x86_64_windows_default = {
378
+ name: "tinyc-sysroot",
379
+ version: 1,
380
+ target: "x86_64-windows",
381
+ binPath: "/sysroot/bin/tinyc",
382
+ includeDir: "/sysroot/include",
383
+ includeFiles: [
384
+ {
385
+ path: "/sysroot/include/float.h",
386
+ source: "include/float.h"
387
+ },
388
+ {
389
+ path: "/sysroot/include/stdalign.h",
390
+ source: "include/stdalign.h"
391
+ },
392
+ {
393
+ path: "/sysroot/include/stdarg.h",
394
+ source: "include/stdarg.h"
395
+ },
396
+ {
397
+ path: "/sysroot/include/stdatomic.h",
398
+ source: "include/stdatomic.h"
399
+ },
400
+ {
401
+ path: "/sysroot/include/stdbool.h",
402
+ source: "include/stdbool.h"
403
+ },
404
+ {
405
+ path: "/sysroot/include/stddef.h",
406
+ source: "include/stddef.h"
407
+ },
408
+ {
409
+ path: "/sysroot/include/stdnoreturn.h",
410
+ source: "include/stdnoreturn.h"
411
+ },
412
+ {
413
+ path: "/sysroot/include/tccdefs.h",
414
+ source: "include/tccdefs.h"
415
+ },
416
+ {
417
+ path: "/sysroot/include/tgmath.h",
418
+ source: "include/tgmath.h"
419
+ },
420
+ {
421
+ path: "/sysroot/include/varargs.h",
422
+ source: "include/varargs.h"
423
+ },
424
+ {
425
+ path: "/sysroot/include/tcclib.h",
426
+ source: "tcclib.h"
427
+ }
428
+ ],
429
+ libDir: "/sysroot/lib",
430
+ libFiles: [
431
+ {
432
+ binary: true,
433
+ path: "/sysroot/lib/libtcc1.a",
434
+ source: "lib/x86_64-windows/libtcc1.a"
435
+ }
436
+ ],
437
+ outputs: {
438
+ exe: {
439
+ format: "PE executable",
440
+ ext: ".exe"
441
+ },
442
+ obj: {
443
+ format: "COFF object",
444
+ ext: ".o"
445
+ },
446
+ shared: {
447
+ format: "PE DLL",
448
+ ext: ".dll"
449
+ },
450
+ ar: {
451
+ format: "ar archive",
452
+ ext: ".a"
453
+ }
454
+ }
455
+ };
456
+
457
+ // sysroot-manifests/aarch64-linux-android.json
458
+ var aarch64_linux_android_default = {
459
+ name: "tinyc-sysroot",
460
+ version: 1,
461
+ target: "aarch64-linux-android",
462
+ binPath: "/sysroot/bin/tinyc",
463
+ includeDir: "/sysroot/include",
464
+ includeFiles: [
465
+ {
466
+ path: "/sysroot/include/float.h",
467
+ source: "include/float.h"
468
+ },
469
+ {
470
+ path: "/sysroot/include/stdalign.h",
471
+ source: "include/stdalign.h"
472
+ },
473
+ {
474
+ path: "/sysroot/include/stdarg.h",
475
+ source: "include/stdarg.h"
476
+ },
477
+ {
478
+ path: "/sysroot/include/stdatomic.h",
479
+ source: "include/stdatomic.h"
480
+ },
481
+ {
482
+ path: "/sysroot/include/stdbool.h",
483
+ source: "include/stdbool.h"
484
+ },
485
+ {
486
+ path: "/sysroot/include/stddef.h",
487
+ source: "include/stddef.h"
488
+ },
489
+ {
490
+ path: "/sysroot/include/stdnoreturn.h",
491
+ source: "include/stdnoreturn.h"
492
+ },
493
+ {
494
+ path: "/sysroot/include/tccdefs.h",
495
+ source: "include/tccdefs.h"
496
+ },
497
+ {
498
+ path: "/sysroot/include/tgmath.h",
499
+ source: "include/tgmath.h"
500
+ },
501
+ {
502
+ path: "/sysroot/include/varargs.h",
503
+ source: "include/varargs.h"
504
+ },
505
+ {
506
+ path: "/sysroot/include/tcclib.h",
507
+ source: "tcclib.h"
508
+ }
509
+ ],
510
+ libDir: "/sysroot/lib",
511
+ libFiles: [
512
+ {
513
+ binary: true,
514
+ path: "/sysroot/lib/libtcc1.a",
515
+ source: "lib/aarch64-linux-android/libtcc1.a"
516
+ }
517
+ ],
518
+ outputs: {
519
+ exe: {
520
+ format: "ELF executable",
521
+ ext: ""
522
+ },
523
+ obj: {
524
+ format: "ELF relocatable",
525
+ ext: ".o"
526
+ },
527
+ shared: {
528
+ format: "ELF shared object",
529
+ ext: ".so"
530
+ },
531
+ ar: {
532
+ format: "ar archive",
533
+ ext: ".a"
534
+ }
535
+ },
536
+ libc: "bionic",
537
+ androidApi: 30,
538
+ dynamicLinker: "/system/bin/linker64"
539
+ };
540
+
541
+ // sysroot-manifests/x86_64-linux-android.json
542
+ var x86_64_linux_android_default = {
543
+ name: "tinyc-sysroot",
544
+ version: 1,
545
+ target: "x86_64-linux-android",
546
+ binPath: "/sysroot/bin/tinyc",
547
+ includeDir: "/sysroot/include",
548
+ includeFiles: [
549
+ {
550
+ path: "/sysroot/include/float.h",
551
+ source: "include/float.h"
552
+ },
553
+ {
554
+ path: "/sysroot/include/stdalign.h",
555
+ source: "include/stdalign.h"
556
+ },
557
+ {
558
+ path: "/sysroot/include/stdarg.h",
559
+ source: "include/stdarg.h"
560
+ },
561
+ {
562
+ path: "/sysroot/include/stdatomic.h",
563
+ source: "include/stdatomic.h"
564
+ },
565
+ {
566
+ path: "/sysroot/include/stdbool.h",
567
+ source: "include/stdbool.h"
568
+ },
569
+ {
570
+ path: "/sysroot/include/stddef.h",
571
+ source: "include/stddef.h"
572
+ },
573
+ {
574
+ path: "/sysroot/include/stdnoreturn.h",
575
+ source: "include/stdnoreturn.h"
576
+ },
577
+ {
578
+ path: "/sysroot/include/tccdefs.h",
579
+ source: "include/tccdefs.h"
580
+ },
581
+ {
582
+ path: "/sysroot/include/tgmath.h",
583
+ source: "include/tgmath.h"
584
+ },
585
+ {
586
+ path: "/sysroot/include/varargs.h",
587
+ source: "include/varargs.h"
588
+ },
589
+ {
590
+ path: "/sysroot/include/tcclib.h",
591
+ source: "tcclib.h"
592
+ }
593
+ ],
594
+ libDir: "/sysroot/lib",
595
+ libFiles: [
596
+ {
597
+ binary: true,
598
+ path: "/sysroot/lib/libtcc1.a",
599
+ source: "lib/x86_64-linux-android/libtcc1.a"
600
+ }
601
+ ],
602
+ outputs: {
603
+ exe: {
604
+ format: "ELF executable",
605
+ ext: ""
606
+ },
607
+ obj: {
608
+ format: "ELF relocatable",
609
+ ext: ".o"
610
+ },
611
+ shared: {
612
+ format: "ELF shared object",
613
+ ext: ".so"
614
+ },
615
+ ar: {
616
+ format: "ar archive",
617
+ ext: ".a"
618
+ }
619
+ },
620
+ libc: "bionic",
621
+ androidApi: 30,
622
+ dynamicLinker: "/system/bin/linker64"
623
+ };
624
+
625
+ // sysroot-manifests/arm64-apple-darwin.json
626
+ var arm64_apple_darwin_default = {
627
+ name: "tinyc-sysroot",
628
+ version: 1,
629
+ target: "arm64-apple-darwin",
630
+ binPath: "/sysroot/bin/tinyc",
631
+ includeDir: "/sysroot/include",
632
+ includeFiles: [
633
+ {
634
+ path: "/sysroot/include/float.h",
635
+ source: "include/float.h"
636
+ },
637
+ {
638
+ path: "/sysroot/include/stdalign.h",
639
+ source: "include/stdalign.h"
640
+ },
641
+ {
642
+ path: "/sysroot/include/stdarg.h",
643
+ source: "include/stdarg.h"
644
+ },
645
+ {
646
+ path: "/sysroot/include/stdatomic.h",
647
+ source: "include/stdatomic.h"
648
+ },
649
+ {
650
+ path: "/sysroot/include/stdbool.h",
651
+ source: "include/stdbool.h"
652
+ },
653
+ {
654
+ path: "/sysroot/include/stddef.h",
655
+ source: "include/stddef.h"
656
+ },
657
+ {
658
+ path: "/sysroot/include/stdnoreturn.h",
659
+ source: "include/stdnoreturn.h"
660
+ },
661
+ {
662
+ path: "/sysroot/include/tccdefs.h",
663
+ source: "include/tccdefs.h"
664
+ },
665
+ {
666
+ path: "/sysroot/include/tgmath.h",
667
+ source: "include/tgmath.h"
668
+ },
669
+ {
670
+ path: "/sysroot/include/varargs.h",
671
+ source: "include/varargs.h"
672
+ },
673
+ {
674
+ path: "/sysroot/include/tcclib.h",
675
+ source: "tcclib.h"
676
+ }
677
+ ],
678
+ libDir: "/sysroot/lib",
679
+ libFiles: [
680
+ {
681
+ binary: true,
682
+ path: "/sysroot/lib/libtcc1.a",
683
+ source: "lib/arm64-apple-darwin/libtcc1.a"
684
+ }
685
+ ],
686
+ outputs: {
687
+ exe: {
688
+ format: "Mach-O executable",
689
+ ext: ""
690
+ },
691
+ obj: {
692
+ format: "Mach-O object",
693
+ ext: ".o"
694
+ },
695
+ shared: {
696
+ format: "Mach-O dylib",
697
+ ext: ".dylib"
698
+ },
699
+ ar: {
700
+ format: "ar archive",
701
+ ext: ".a"
702
+ }
703
+ },
704
+ systemHeaders: "user-sdk"
705
+ };
706
+
707
+ // sysroot-manifests/x86_64-apple-darwin.json
708
+ var x86_64_apple_darwin_default = {
709
+ name: "tinyc-sysroot",
710
+ version: 1,
711
+ target: "x86_64-apple-darwin",
712
+ binPath: "/sysroot/bin/tinyc",
713
+ includeDir: "/sysroot/include",
714
+ includeFiles: [
715
+ {
716
+ path: "/sysroot/include/float.h",
717
+ source: "include/float.h"
718
+ },
719
+ {
720
+ path: "/sysroot/include/stdalign.h",
721
+ source: "include/stdalign.h"
722
+ },
723
+ {
724
+ path: "/sysroot/include/stdarg.h",
725
+ source: "include/stdarg.h"
726
+ },
727
+ {
728
+ path: "/sysroot/include/stdatomic.h",
729
+ source: "include/stdatomic.h"
730
+ },
731
+ {
732
+ path: "/sysroot/include/stdbool.h",
733
+ source: "include/stdbool.h"
734
+ },
735
+ {
736
+ path: "/sysroot/include/stddef.h",
737
+ source: "include/stddef.h"
738
+ },
739
+ {
740
+ path: "/sysroot/include/stdnoreturn.h",
741
+ source: "include/stdnoreturn.h"
742
+ },
743
+ {
744
+ path: "/sysroot/include/tccdefs.h",
745
+ source: "include/tccdefs.h"
746
+ },
747
+ {
748
+ path: "/sysroot/include/tgmath.h",
749
+ source: "include/tgmath.h"
750
+ },
751
+ {
752
+ path: "/sysroot/include/varargs.h",
753
+ source: "include/varargs.h"
754
+ },
755
+ {
756
+ path: "/sysroot/include/tcclib.h",
757
+ source: "tcclib.h"
758
+ }
759
+ ],
760
+ libDir: "/sysroot/lib",
761
+ libFiles: [
762
+ {
763
+ binary: true,
764
+ path: "/sysroot/lib/libtcc1.a",
765
+ source: "lib/x86_64-apple-darwin/libtcc1.a"
766
+ }
767
+ ],
768
+ outputs: {
769
+ exe: {
770
+ format: "Mach-O executable",
771
+ ext: ""
772
+ },
773
+ obj: {
774
+ format: "Mach-O object",
775
+ ext: ".o"
776
+ },
777
+ shared: {
778
+ format: "Mach-O dylib",
779
+ ext: ".dylib"
780
+ },
781
+ ar: {
782
+ format: "ar archive",
783
+ ext: ".a"
784
+ }
785
+ },
786
+ systemHeaders: "user-sdk"
787
+ };
788
+
789
+ // runtime-shims.mjs
790
+ var textEncoder = new TextEncoder();
791
+ var textDecoder = new TextDecoder();
792
+ var ShimExit = class extends Error {
793
+ constructor(code) {
794
+ super(`tinyc: libc exit(${code})`);
795
+ this.name = "ShimExit";
796
+ this.exitCode = code;
797
+ }
798
+ };
799
+ var ALLOC_USED = 2702233105;
800
+ function createDefaultShims(options = {}) {
801
+ const { holder } = options;
802
+ const io = options.io ?? {};
803
+ const emitOut = typeof io.out === "function" ? io.out : () => {
804
+ };
805
+ const emitErr = typeof io.err === "function" ? io.err : () => {
806
+ };
807
+ const heapBase = options.heapBase ?? 65536;
808
+ const memory = () => holder?.memory ?? null;
809
+ const u8 = () => new Uint8Array(memory().buffer);
810
+ const dv = () => new DataView(memory().buffer);
811
+ const readU32 = (ptr) => dv().getUint32(ptr, true);
812
+ const writeU32 = (ptr, v) => dv().setUint32(ptr, v >>> 0, true);
813
+ const readBytes = (ptr, len) => u8().slice(ptr, ptr + len);
814
+ const writeBytes = (ptr, data) => {
815
+ u8().set(data, ptr);
816
+ };
817
+ const readCString = (ptr, max = 1 << 20) => {
818
+ if (!ptr) return "";
819
+ const m = u8();
820
+ let end = ptr;
821
+ while (end < m.length && end - ptr < max && m[end] !== 0) end++;
822
+ return textDecoder.decode(m.subarray(ptr, end));
823
+ };
824
+ const writeCStringBytes = (ptr, bytes) => {
825
+ writeBytes(ptr, bytes);
826
+ u8()[ptr + bytes.length] = 0;
827
+ return bytes.length;
828
+ };
829
+ let heapTop = 0;
830
+ let freeHead = 0;
831
+ const moduleAllocator = () => {
832
+ const ex = holder?.instance?.exports;
833
+ return ex && typeof ex.malloc === "function" ? ex : null;
834
+ };
835
+ function ensureCapacity(end) {
836
+ const mem = memory();
837
+ if (!mem) return false;
838
+ if (mem.buffer.byteLength >= end) return true;
839
+ const pages = Math.ceil((end - mem.buffer.byteLength) / 65536);
840
+ try {
841
+ mem.grow(pages);
842
+ return true;
843
+ } catch {
844
+ return false;
845
+ }
846
+ }
847
+ function rawMalloc(size) {
848
+ size = Math.max(8, size + 7 & ~7);
849
+ let prev = 0;
850
+ let cur = freeHead;
851
+ while (cur) {
852
+ const csize = readU32(cur);
853
+ const cnext = readU32(cur + 4);
854
+ if (csize >= size) {
855
+ if (csize - size >= 16) {
856
+ const rem = cur + 8 + size;
857
+ writeU32(rem, csize - size - 8);
858
+ writeU32(rem + 4, cnext);
859
+ writeU32(cur, size);
860
+ if (prev) writeU32(prev + 4, rem);
861
+ else freeHead = rem;
862
+ } else {
863
+ if (prev) writeU32(prev + 4, cnext);
864
+ else freeHead = cnext;
865
+ }
866
+ writeU32(cur + 4, ALLOC_USED);
867
+ return cur + 8;
868
+ }
869
+ prev = cur;
870
+ cur = cnext;
871
+ }
872
+ if (!heapTop) heapTop = heapBase;
873
+ const header = heapTop;
874
+ const end = header + 8 + size;
875
+ if (!ensureCapacity(end)) return 0;
876
+ writeU32(header, size);
877
+ writeU32(header + 4, ALLOC_USED);
878
+ heapTop = end;
879
+ return header + 8;
880
+ }
881
+ function rawFree(ptr) {
882
+ if (!ptr) return;
883
+ const header = ptr - 8;
884
+ if (readU32(header + 4) !== ALLOC_USED) return;
885
+ writeU32(header + 4, freeHead);
886
+ freeHead = header;
887
+ }
888
+ function malloc(size) {
889
+ const own = moduleAllocator();
890
+ return own ? own.malloc(size) : rawMalloc(size);
891
+ }
892
+ function free(ptr) {
893
+ const own = moduleAllocator();
894
+ if (own && typeof own.free === "function") {
895
+ own.free(ptr);
896
+ return;
897
+ }
898
+ rawFree(ptr);
899
+ }
900
+ function calloc(n, size) {
901
+ const own = moduleAllocator();
902
+ if (own && typeof own.calloc === "function") return own.calloc(n, size);
903
+ const total = n * size;
904
+ const ptr = malloc(total);
905
+ if (ptr) writeBytes(ptr, new Uint8Array(total));
906
+ return ptr;
907
+ }
908
+ function realloc(ptr, size) {
909
+ if (!ptr) return malloc(size);
910
+ if (size === 0) {
911
+ free(ptr);
912
+ return 0;
913
+ }
914
+ const own = moduleAllocator();
915
+ if (own) {
916
+ if (typeof own.realloc === "function") return own.realloc(ptr, size);
917
+ const np2 = own.malloc(size);
918
+ if (!np2) return 0;
919
+ writeBytes(np2, readBytes(ptr, size));
920
+ if (typeof own.free === "function") own.free(ptr);
921
+ return np2;
922
+ }
923
+ const oldSize = readU32(ptr - 8);
924
+ if (size <= oldSize) return ptr;
925
+ const np = rawMalloc(size);
926
+ if (!np) return 0;
927
+ writeBytes(np, readBytes(ptr, oldSize));
928
+ rawFree(ptr);
929
+ return np;
930
+ }
931
+ function memcpy(dest, src, n) {
932
+ writeBytes(dest, readBytes(src, n));
933
+ return dest;
934
+ }
935
+ function memmove(dest, src, n) {
936
+ writeBytes(dest, readBytes(src, n));
937
+ return dest;
938
+ }
939
+ function memset(ptr, value, n) {
940
+ u8().fill(value & 255, ptr, ptr + n);
941
+ return ptr;
942
+ }
943
+ function memcmp(a, b, n) {
944
+ const ma = u8();
945
+ for (let i = 0; i < n; i++) {
946
+ const d = ma[a + i] - ma[b + i];
947
+ if (d !== 0) return d;
948
+ }
949
+ return 0;
950
+ }
951
+ function strlen(ptr) {
952
+ const m = u8();
953
+ let n = 0;
954
+ while (m[ptr + n] !== 0) n++;
955
+ return n;
956
+ }
957
+ function strcpy(dest, src) {
958
+ writeBytes(dest, readBytes(src, strlen(src) + 1));
959
+ return dest;
960
+ }
961
+ function strncpy(dest, src, n) {
962
+ const m = u8();
963
+ let i = 0;
964
+ while (i < n && m[src + i] !== 0) {
965
+ m[dest + i] = m[src + i];
966
+ i++;
967
+ }
968
+ while (i < n) m[dest + i++] = 0;
969
+ return dest;
970
+ }
971
+ function strcat(dest, src) {
972
+ writeBytes(dest + strlen(dest), readBytes(src, strlen(src) + 1));
973
+ return dest;
974
+ }
975
+ function strncat(dest, src, n) {
976
+ const m = u8();
977
+ const at = dest + strlen(dest);
978
+ let i = 0;
979
+ while (i < n && m[src + i] !== 0) {
980
+ m[at + i] = m[src + i];
981
+ i++;
982
+ }
983
+ m[at + i] = 0;
984
+ return dest;
985
+ }
986
+ function strcmp(a, b) {
987
+ const m = u8();
988
+ let i = 0;
989
+ for (; ; ) {
990
+ const d = m[a + i] - m[b + i];
991
+ if (d !== 0 || m[a + i] === 0) return d;
992
+ i++;
993
+ }
994
+ }
995
+ function strncmp(a, b, n) {
996
+ const m = u8();
997
+ for (let i = 0; i < n; i++) {
998
+ const d = m[a + i] - m[b + i];
999
+ if (d !== 0 || m[a + i] === 0) return d;
1000
+ }
1001
+ return 0;
1002
+ }
1003
+ function strchr(ptr, c) {
1004
+ const m = u8();
1005
+ const want = c & 255;
1006
+ let i = 0;
1007
+ for (; ; ) {
1008
+ if (m[ptr + i] === want) return ptr + i;
1009
+ if (m[ptr + i] === 0) return 0;
1010
+ i++;
1011
+ }
1012
+ }
1013
+ function strrchr(ptr, c) {
1014
+ const m = u8();
1015
+ const want = c & 255;
1016
+ let found = 0;
1017
+ let i = 0;
1018
+ for (; ; ) {
1019
+ if (m[ptr + i] === want) found = ptr + i;
1020
+ if (m[ptr + i] === 0) return found;
1021
+ i++;
1022
+ }
1023
+ }
1024
+ function strstr(haystack, needle) {
1025
+ const h = readCString(haystack);
1026
+ const ndl = readCString(needle);
1027
+ if (ndl === "") return haystack;
1028
+ const idx = h.indexOf(ndl);
1029
+ return idx < 0 ? 0 : haystack + textEncoder.encode(h.slice(0, idx)).length;
1030
+ }
1031
+ function strdup(ptr) {
1032
+ const copy = readBytes(ptr, strlen(ptr) + 1);
1033
+ const dest = malloc(copy.length);
1034
+ if (dest) writeBytes(dest, copy);
1035
+ return dest;
1036
+ }
1037
+ const CT = (() => {
1038
+ const t = new Uint8Array(256);
1039
+ const U = 1, L = 2, D = 4, S = 8, P = 16, C = 32, X = 64, B = 128;
1040
+ for (let c = 0; c < 32; c++) t[c] |= C;
1041
+ t[127] |= C;
1042
+ for (let c = 48; c <= 57; c++) t[c] |= D | X;
1043
+ for (let c = 65; c <= 70; c++) t[c] |= X;
1044
+ for (let c = 97; c <= 102; c++) t[c] |= X;
1045
+ for (let c = 65; c <= 90; c++) t[c] |= U;
1046
+ for (let c = 97; c <= 122; c++) t[c] |= L;
1047
+ for (const c of [32, 9, 10, 11, 12, 13]) t[c] |= S;
1048
+ t[32] |= B;
1049
+ t[9] |= B;
1050
+ for (let c = 33; c <= 126; c++) {
1051
+ if (!(t[c] & (U | L | D))) t[c] |= P;
1052
+ }
1053
+ return { t, U, L, D, S, P, C, X, B };
1054
+ })();
1055
+ const ctFlag = (bit) => (c) => c >= 0 && c <= 255 ? CT.t[c] & bit ? 1 : 0 : 0;
1056
+ const isupper = ctFlag(CT.U);
1057
+ const islower = ctFlag(CT.L);
1058
+ const isdigit = ctFlag(CT.D);
1059
+ const isspace = ctFlag(CT.S);
1060
+ const ispunct = ctFlag(CT.P);
1061
+ const iscntrl = ctFlag(CT.C);
1062
+ const isxdigit = ctFlag(CT.X);
1063
+ const isblank = ctFlag(CT.B);
1064
+ const isalpha = (c) => isupper(c) || islower(c) ? 1 : 0;
1065
+ const isalnum = (c) => isalpha(c) || isdigit(c) ? 1 : 0;
1066
+ const isprint = (c) => c >= 32 && c <= 126 ? 1 : 0;
1067
+ const isgraph = (c) => c >= 33 && c <= 126 ? 1 : 0;
1068
+ const tolower = (c) => isupper(c) ? c + 32 : c;
1069
+ const toupper = (c) => islower(c) ? c - 32 : c;
1070
+ function scanInt(ptr, base) {
1071
+ const s = readCString(ptr);
1072
+ let i = 0;
1073
+ while (i < s.length && " \n\v\f\r".includes(s[i])) i++;
1074
+ let sign = 1n;
1075
+ if (s[i] === "+" || s[i] === "-") {
1076
+ if (s[i] === "-") sign = -1n;
1077
+ i++;
1078
+ }
1079
+ let b = base;
1080
+ if (b === 0) {
1081
+ if (s[i] === "0" && (s[i + 1] === "x" || s[i + 1] === "X")) b = 16;
1082
+ else if (s[i] === "0") b = 8;
1083
+ else b = 10;
1084
+ }
1085
+ if (b === 16 && s[i] === "0" && (s[i + 1] === "x" || s[i + 1] === "X")) i += 2;
1086
+ const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
1087
+ let value = 0n;
1088
+ let any = false;
1089
+ while (i < s.length) {
1090
+ const d = digits.indexOf(s[i].toLowerCase());
1091
+ if (d < 0 || d >= b) break;
1092
+ value = value * BigInt(b) + BigInt(d);
1093
+ i++;
1094
+ any = true;
1095
+ }
1096
+ return { value: sign * value, consumed: any ? i : 0, any };
1097
+ }
1098
+ function finishEndptr(endptr, ptr, consumed) {
1099
+ if (endptr) writeU32(endptr, ptr + consumed);
1100
+ }
1101
+ const I32_MIN = -2147483648n;
1102
+ const I32_MAX = 2147483647n;
1103
+ const U32_MAX = 4294967295n;
1104
+ function clampBig(v, lo, hi) {
1105
+ return v < lo ? lo : v > hi ? hi : v;
1106
+ }
1107
+ function strtol(ptr, endptr, base) {
1108
+ const r = scanInt(ptr, base | 0);
1109
+ finishEndptr(endptr, ptr, r.consumed);
1110
+ return Number(clampBig(r.value, I32_MIN, I32_MAX));
1111
+ }
1112
+ function strtoul(ptr, endptr, base) {
1113
+ const r = scanInt(ptr, base | 0);
1114
+ finishEndptr(endptr, ptr, r.consumed);
1115
+ return Number(clampBig(r.value, 0n, U32_MAX)) >>> 0;
1116
+ }
1117
+ function strtoll(ptr, endptr, base) {
1118
+ const r = scanInt(ptr, base | 0);
1119
+ finishEndptr(endptr, ptr, r.consumed);
1120
+ return r.value;
1121
+ }
1122
+ function strtoull(ptr, endptr, base) {
1123
+ const r = scanInt(ptr, base | 0);
1124
+ finishEndptr(endptr, ptr, r.consumed);
1125
+ return r.value < 0n ? 0n : r.value;
1126
+ }
1127
+ function scanFloat(ptr) {
1128
+ const s = readCString(ptr);
1129
+ const m = /^[\s]*[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(s) ?? /^[\s]*[+-]?(inf(inity)?|nan)/i.exec(s);
1130
+ if (!m) return { value: 0, consumed: 0 };
1131
+ return { value: parseFloat(m[0]), consumed: m[0].length };
1132
+ }
1133
+ function strtod(ptr, endptr) {
1134
+ const r = scanFloat(ptr);
1135
+ finishEndptr(endptr, ptr, r.consumed);
1136
+ return r.value;
1137
+ }
1138
+ function strtof(ptr, endptr) {
1139
+ return Math.fround(strtod(ptr, endptr));
1140
+ }
1141
+ function atoi(ptr) {
1142
+ return Number(clampBig(scanInt(ptr, 10).value, I32_MIN, I32_MAX));
1143
+ }
1144
+ function atol(ptr) {
1145
+ return atoi(ptr);
1146
+ }
1147
+ function atoll(ptr) {
1148
+ return scanInt(ptr, 10).value;
1149
+ }
1150
+ function atof(ptr) {
1151
+ return scanFloat(ptr).value;
1152
+ }
1153
+ const abs = (v) => Math.abs(v | 0);
1154
+ const labs = (v) => Math.abs(v | 0);
1155
+ const llabs = (v) => v < 0n ? -v : v;
1156
+ let randState = 1;
1157
+ function srand(seed) {
1158
+ randState = seed >>> 0 || 1;
1159
+ }
1160
+ function rand() {
1161
+ randState = Math.imul(randState, 1103515245) + 12345 & 2147483647;
1162
+ return randState >> 16 & 32767;
1163
+ }
1164
+ const atexitHandlers = [];
1165
+ function atexit(fnPtr) {
1166
+ atexitHandlers.push(fnPtr);
1167
+ return 0;
1168
+ }
1169
+ function exit(code) {
1170
+ const table = holder?.instance?.exports?.__indirect_function_table;
1171
+ if (table && typeof table.get === "function") {
1172
+ for (let i = atexitHandlers.length - 1; i >= 0; i--) {
1173
+ try {
1174
+ const fn = table.get(atexitHandlers[i]);
1175
+ if (typeof fn === "function") fn();
1176
+ } catch {
1177
+ }
1178
+ }
1179
+ }
1180
+ throw new ShimExit(code | 0);
1181
+ }
1182
+ function abort() {
1183
+ throw new ShimExit(134);
1184
+ }
1185
+ let stdinBuf = null;
1186
+ let stdinPos = 0;
1187
+ const pushback = [];
1188
+ if (options.stdin != null) {
1189
+ stdinBuf = typeof options.stdin === "string" ? textEncoder.encode(options.stdin) : options.stdin;
1190
+ }
1191
+ function stdinPull() {
1192
+ if (stdinBuf && stdinPos < stdinBuf.length) return true;
1193
+ if (typeof io.in === "function") {
1194
+ const chunk = io.in();
1195
+ if (chunk == null) return false;
1196
+ const b = typeof chunk === "string" ? textEncoder.encode(chunk) : chunk;
1197
+ if (!b || b.length === 0) return false;
1198
+ stdinBuf = b;
1199
+ stdinPos = 0;
1200
+ return true;
1201
+ }
1202
+ return false;
1203
+ }
1204
+ function stdinRead(n) {
1205
+ const parts = [];
1206
+ let got = 0;
1207
+ while (got < n) {
1208
+ if (pushback.length) {
1209
+ parts.push(Uint8Array.of(pushback.pop()));
1210
+ got++;
1211
+ continue;
1212
+ }
1213
+ if (!stdinPull()) break;
1214
+ const take = Math.min(n - got, stdinBuf.length - stdinPos);
1215
+ parts.push(stdinBuf.slice(stdinPos, stdinPos + take));
1216
+ stdinPos += take;
1217
+ got += take;
1218
+ }
1219
+ const result = new Uint8Array(got);
1220
+ let at = 0;
1221
+ for (const p of parts) {
1222
+ result.set(p, at);
1223
+ at += p.length;
1224
+ }
1225
+ return result;
1226
+ }
1227
+ function makeVa(vaPtr) {
1228
+ let cur = vaPtr;
1229
+ const alignTo = (n) => {
1230
+ cur = cur + n - 1 & ~(n - 1);
1231
+ };
1232
+ return {
1233
+ i32() {
1234
+ alignTo(4);
1235
+ const v = dv().getInt32(cur, true);
1236
+ cur += 4;
1237
+ return v;
1238
+ },
1239
+ u32() {
1240
+ alignTo(4);
1241
+ const v = dv().getUint32(cur, true);
1242
+ cur += 4;
1243
+ return v;
1244
+ },
1245
+ i64() {
1246
+ alignTo(8);
1247
+ const v = dv().getBigInt64(cur, true);
1248
+ cur += 8;
1249
+ return v;
1250
+ },
1251
+ u64() {
1252
+ alignTo(8);
1253
+ const v = dv().getBigUint64(cur, true);
1254
+ cur += 8;
1255
+ return v;
1256
+ },
1257
+ f64() {
1258
+ alignTo(8);
1259
+ const v = dv().getFloat64(cur, true);
1260
+ cur += 8;
1261
+ return v;
1262
+ }
1263
+ };
1264
+ }
1265
+ function padSpaces(s, width, left) {
1266
+ if (s.length >= width) return s;
1267
+ const p = " ".repeat(width - s.length);
1268
+ return left ? s + p : p + s;
1269
+ }
1270
+ function fmtInteger(digits, sign, prefix, flags, width, precision) {
1271
+ let body = digits;
1272
+ if (precision >= 0) body = body.padStart(precision, "0");
1273
+ const head = sign + prefix;
1274
+ if (flags.includes("0") && !flags.includes("-") && precision < 0) {
1275
+ const total = head.length + body.length;
1276
+ if (total < width) body = "0".repeat(width - total) + body;
1277
+ return head + body;
1278
+ }
1279
+ return padSpaces(head + body, width, flags.includes("-"));
1280
+ }
1281
+ function fmtFloatNumber(body, flags, width) {
1282
+ let sign = "";
1283
+ let rest = body;
1284
+ if (rest.startsWith("-")) {
1285
+ sign = "-";
1286
+ rest = rest.slice(1);
1287
+ } else if (flags.includes("+")) {
1288
+ sign = "+";
1289
+ } else if (flags.includes(" ")) {
1290
+ sign = " ";
1291
+ }
1292
+ const special = /^(inf|nan)/i.test(rest);
1293
+ if (flags.includes("0") && !flags.includes("-") && !special) {
1294
+ const total = sign.length + rest.length;
1295
+ if (total < width) rest = "0".repeat(width - total) + rest;
1296
+ return sign + rest;
1297
+ }
1298
+ return padSpaces(sign + rest, width, flags.includes("-"));
1299
+ }
1300
+ function expParts(s) {
1301
+ const [mant, exp] = s.split("e");
1302
+ const e = parseInt(exp, 10);
1303
+ return [mant, (e < 0 ? "-" : "+") + String(Math.abs(e)).padStart(2, "0")];
1304
+ }
1305
+ function fmtE(v, precision, upper) {
1306
+ if (Number.isNaN(v)) return upper ? "NAN" : "nan";
1307
+ if (!Number.isFinite(v)) return (v > 0 ? "" : "-") + (upper ? "INF" : "inf");
1308
+ const [mant, e] = expParts(v.toExponential(precision));
1309
+ return mant + (upper ? "E" : "e") + e;
1310
+ }
1311
+ function fmtF(v, precision, upper) {
1312
+ if (Number.isNaN(v)) return upper ? "NAN" : "nan";
1313
+ if (!Number.isFinite(v)) return (v > 0 ? "" : "-") + (upper ? "INF" : "inf");
1314
+ return v.toFixed(precision);
1315
+ }
1316
+ function fmtG(v, precision, upper, alt) {
1317
+ if (Number.isNaN(v) || !Number.isFinite(v)) return fmtF(v, 0, upper);
1318
+ const p = precision <= 0 ? 1 : precision;
1319
+ let s = v.toPrecision(p);
1320
+ if (!alt) {
1321
+ const strip = (m) => m.includes(".") ? m.replace(/0+$/, "").replace(/\.$/, "") : m;
1322
+ if (s.includes("e")) {
1323
+ const [m, e] = s.split("e");
1324
+ s = strip(m) + "e" + e;
1325
+ } else {
1326
+ s = strip(s);
1327
+ }
1328
+ s = s.replace(/e([+-])(\d)$/, "e$10$2");
1329
+ }
1330
+ return upper ? s.toUpperCase() : s;
1331
+ }
1332
+ function convert(conv, { flags, width, precision, length, va }, outLen) {
1333
+ switch (conv) {
1334
+ case "d":
1335
+ case "i": {
1336
+ let sign = "";
1337
+ let digits;
1338
+ if (length === "ll") {
1339
+ const v = va.i64();
1340
+ if (v < 0n) {
1341
+ sign = "-";
1342
+ digits = (-v).toString(10);
1343
+ } else digits = v.toString(10);
1344
+ if (v === 0n && precision === 0) digits = "";
1345
+ } else {
1346
+ let v = va.i32();
1347
+ if (length === "hh") v = v << 24 >> 24;
1348
+ else if (length === "h") v = v << 16 >> 16;
1349
+ if (v < 0) {
1350
+ sign = "-";
1351
+ digits = String(-v);
1352
+ } else digits = String(v);
1353
+ if (v === 0 && precision === 0) digits = "";
1354
+ }
1355
+ if (!sign && flags.includes("+")) sign = "+";
1356
+ else if (!sign && flags.includes(" ")) sign = " ";
1357
+ return fmtInteger(digits, sign, "", flags, width, precision);
1358
+ }
1359
+ case "u":
1360
+ case "x":
1361
+ case "X":
1362
+ case "o": {
1363
+ const radix = conv === "u" ? 10 : conv === "o" ? 8 : 16;
1364
+ let digits;
1365
+ let isZero;
1366
+ if (length === "ll") {
1367
+ const v = va.u64();
1368
+ isZero = v === 0n;
1369
+ digits = v.toString(radix);
1370
+ if (isZero && precision === 0) digits = "";
1371
+ } else {
1372
+ let v = va.u32();
1373
+ if (length === "hh") v &= 255;
1374
+ else if (length === "h") v &= 65535;
1375
+ isZero = v === 0;
1376
+ digits = v.toString(radix);
1377
+ if (isZero && precision === 0) digits = "";
1378
+ }
1379
+ if (conv === "X") digits = digits.toUpperCase();
1380
+ let prefix = "";
1381
+ if (flags.includes("#") && conv !== "u") {
1382
+ if (conv === "o") {
1383
+ if (!digits.startsWith("0")) prefix = "0";
1384
+ } else if (!isZero) {
1385
+ prefix = conv === "X" ? "0X" : "0x";
1386
+ }
1387
+ }
1388
+ return fmtInteger(digits, "", prefix, flags, width, precision);
1389
+ }
1390
+ case "c": {
1391
+ const ch = String.fromCharCode(va.i32() & 255);
1392
+ return padSpaces(ch, width, flags.includes("-"));
1393
+ }
1394
+ case "s": {
1395
+ const ptr = va.u32();
1396
+ let s = ptr ? readCString(ptr) : "(null)";
1397
+ if (precision >= 0) s = s.slice(0, precision);
1398
+ return padSpaces(s, width, flags.includes("-"));
1399
+ }
1400
+ case "p": {
1401
+ const ptr = va.u32();
1402
+ return padSpaces("0x" + ptr.toString(16), width, flags.includes("-"));
1403
+ }
1404
+ case "f":
1405
+ case "F":
1406
+ return fmtFloatNumber(
1407
+ fmtF(va.f64(), precision < 0 ? 6 : precision, conv === "F"),
1408
+ flags,
1409
+ width
1410
+ );
1411
+ case "e":
1412
+ case "E":
1413
+ return fmtFloatNumber(
1414
+ fmtE(va.f64(), precision < 0 ? 6 : precision, conv === "E"),
1415
+ flags,
1416
+ width
1417
+ );
1418
+ case "g":
1419
+ case "G":
1420
+ return fmtFloatNumber(
1421
+ fmtG(va.f64(), precision < 0 ? 6 : precision, conv === "G", flags.includes("#")),
1422
+ flags,
1423
+ width
1424
+ );
1425
+ case "a":
1426
+ case "A": {
1427
+ const v = va.f64();
1428
+ return fmtFloatNumber(String(v), flags, width);
1429
+ }
1430
+ case "n": {
1431
+ const ptr = va.u32();
1432
+ if (ptr) {
1433
+ if (length === "ll") dv().setBigInt64(ptr, BigInt(outLen), true);
1434
+ else dv().setInt32(ptr, outLen, true);
1435
+ }
1436
+ return "";
1437
+ }
1438
+ default:
1439
+ return "%" + conv;
1440
+ }
1441
+ }
1442
+ function formatString(fmtPtr, vaPtr) {
1443
+ const fmt = readCString(fmtPtr);
1444
+ const va = makeVa(vaPtr);
1445
+ let out = "";
1446
+ let i = 0;
1447
+ while (i < fmt.length) {
1448
+ if (fmt[i] !== "%") {
1449
+ out += fmt[i++];
1450
+ continue;
1451
+ }
1452
+ i++;
1453
+ if (fmt[i] === "%") {
1454
+ out += "%";
1455
+ i++;
1456
+ continue;
1457
+ }
1458
+ let flags = "";
1459
+ while (i < fmt.length && "-+ #0".includes(fmt[i])) flags += fmt[i++];
1460
+ let width = 0;
1461
+ if (fmt[i] === "*") {
1462
+ width = va.i32();
1463
+ i++;
1464
+ if (width < 0) {
1465
+ flags += "-";
1466
+ width = -width;
1467
+ }
1468
+ } else {
1469
+ while (i < fmt.length && fmt[i] >= "0" && fmt[i] <= "9") {
1470
+ width = width * 10 + (fmt.charCodeAt(i++) - 48);
1471
+ }
1472
+ }
1473
+ let precision = -1;
1474
+ if (fmt[i] === ".") {
1475
+ i++;
1476
+ if (fmt[i] === "*") {
1477
+ precision = va.i32();
1478
+ i++;
1479
+ } else {
1480
+ precision = 0;
1481
+ while (i < fmt.length && fmt[i] >= "0" && fmt[i] <= "9") {
1482
+ precision = precision * 10 + (fmt.charCodeAt(i++) - 48);
1483
+ }
1484
+ }
1485
+ if (precision < 0) precision = -1;
1486
+ }
1487
+ let length = "";
1488
+ if (fmt.startsWith("hh", i)) {
1489
+ length = "hh";
1490
+ i += 2;
1491
+ } else if (fmt.startsWith("ll", i)) {
1492
+ length = "ll";
1493
+ i += 2;
1494
+ } else if (i < fmt.length && "hlzjtL".includes(fmt[i])) {
1495
+ length = fmt[i++];
1496
+ }
1497
+ const conv = fmt[i++] ?? "";
1498
+ out += convert(conv, { flags, width, precision, length, va }, out.length);
1499
+ }
1500
+ return out;
1501
+ }
1502
+ function emitText(text, toErr) {
1503
+ const bytes = textEncoder.encode(text);
1504
+ (toErr ? emitErr : emitOut)(bytes);
1505
+ return bytes.length;
1506
+ }
1507
+ function printf(fmt, va) {
1508
+ return emitText(formatString(fmt, va), false);
1509
+ }
1510
+ function fprintf(stream, fmt, va) {
1511
+ return emitText(formatString(fmt, va), stream === 2);
1512
+ }
1513
+ function sprintf(dest, fmt, va) {
1514
+ const bytes = textEncoder.encode(formatString(fmt, va));
1515
+ return writeCStringBytes(dest, bytes);
1516
+ }
1517
+ function snprintf(dest, size, fmt, va) {
1518
+ const bytes = textEncoder.encode(formatString(fmt, va));
1519
+ if (size > 0) {
1520
+ const n = Math.min(bytes.length, size - 1);
1521
+ writeBytes(dest, bytes.subarray(0, n));
1522
+ u8()[dest + n] = 0;
1523
+ }
1524
+ return bytes.length;
1525
+ }
1526
+ function puts(ptr) {
1527
+ return emitText(readCString(ptr) + "\n", false) >= 0 ? 0 : -1;
1528
+ }
1529
+ function putchar(c) {
1530
+ emitOut(Uint8Array.of(c & 255));
1531
+ return c;
1532
+ }
1533
+ function fputs(ptr, stream) {
1534
+ emitText(readCString(ptr), stream === 2);
1535
+ return 0;
1536
+ }
1537
+ function putc(c, stream) {
1538
+ (stream === 2 ? emitErr : emitOut)(Uint8Array.of(c & 255));
1539
+ return c;
1540
+ }
1541
+ function fwrite(ptr, size, nmemb, stream) {
1542
+ const total = size * nmemb;
1543
+ if (total === 0) return 0;
1544
+ (stream === 2 ? emitErr : emitOut)(readBytes(ptr, total));
1545
+ return nmemb;
1546
+ }
1547
+ function fread(ptr, size, nmemb, _stream) {
1548
+ if (size === 0 || nmemb === 0) return 0;
1549
+ const data = stdinRead(size * nmemb);
1550
+ if (data.length) writeBytes(ptr, data);
1551
+ return Math.floor(data.length / size);
1552
+ }
1553
+ function fgetc(_stream) {
1554
+ const data = stdinRead(1);
1555
+ return data.length ? data[0] : -1;
1556
+ }
1557
+ function ungetc(c, _stream) {
1558
+ if (c >= 0) pushback.push(c & 255);
1559
+ return c;
1560
+ }
1561
+ const env = {
1562
+ // memory / string
1563
+ memcpy,
1564
+ memmove,
1565
+ memset,
1566
+ memcmp,
1567
+ strlen,
1568
+ strcpy,
1569
+ strncpy,
1570
+ strcat,
1571
+ strncat,
1572
+ strcmp,
1573
+ strncmp,
1574
+ strchr,
1575
+ strrchr,
1576
+ strstr,
1577
+ strdup,
1578
+ // allocation
1579
+ malloc,
1580
+ calloc,
1581
+ realloc,
1582
+ free,
1583
+ // stdio
1584
+ printf,
1585
+ fprintf,
1586
+ vprintf: printf,
1587
+ vfprintf: fprintf,
1588
+ sprintf,
1589
+ vsprintf: sprintf,
1590
+ snprintf,
1591
+ vsnprintf: snprintf,
1592
+ puts,
1593
+ putchar,
1594
+ fputs,
1595
+ putc,
1596
+ fputc: putc,
1597
+ fwrite,
1598
+ fread,
1599
+ fgetc,
1600
+ getchar: () => fgetc(0),
1601
+ ungetc,
1602
+ // stdlib
1603
+ exit,
1604
+ abort,
1605
+ atexit,
1606
+ atoi,
1607
+ atol,
1608
+ atoll,
1609
+ atof,
1610
+ strtol,
1611
+ strtoul,
1612
+ strtoll,
1613
+ strtoull,
1614
+ strtod,
1615
+ strtof,
1616
+ abs,
1617
+ labs,
1618
+ llabs,
1619
+ rand,
1620
+ srand,
1621
+ getenv: (_name) => 0,
1622
+ system: (cmd) => cmd === 0 ? 0 : -1,
1623
+ // ctype
1624
+ isalpha,
1625
+ isdigit,
1626
+ isspace,
1627
+ isalnum,
1628
+ isupper,
1629
+ islower,
1630
+ ispunct,
1631
+ iscntrl,
1632
+ isxdigit,
1633
+ isblank,
1634
+ isprint,
1635
+ isgraph,
1636
+ tolower,
1637
+ toupper,
1638
+ // math
1639
+ sin: Math.sin,
1640
+ cos: Math.cos,
1641
+ tan: Math.tan,
1642
+ asin: Math.asin,
1643
+ acos: Math.acos,
1644
+ atan: Math.atan,
1645
+ atan2: Math.atan2,
1646
+ exp: Math.exp,
1647
+ log: Math.log,
1648
+ log10: Math.log10,
1649
+ pow: Math.pow,
1650
+ sqrt: Math.sqrt,
1651
+ floor: Math.floor,
1652
+ ceil: Math.ceil,
1653
+ fabs: Math.abs,
1654
+ round: Math.round,
1655
+ trunc: Math.trunc,
1656
+ fmod: (a, b) => a % b,
1657
+ // time
1658
+ time: (tloc) => {
1659
+ const sec = Math.floor(Date.now() / 1e3);
1660
+ if (tloc) writeU32(tloc, sec);
1661
+ return sec;
1662
+ },
1663
+ clock: () => Math.floor(performance.now() * 1e3),
1664
+ difftime: (a, b) => a - b
1665
+ };
1666
+ return { env };
1667
+ }
1668
+
1669
+ // vfs-store.mjs
1670
+ var MemoryFsStore = class {
1671
+ constructor() {
1672
+ this.kind = "memory";
1673
+ this._records = /* @__PURE__ */ new Map();
1674
+ this.index = /* @__PURE__ */ new Map();
1675
+ }
1676
+ async open() {
1677
+ this.index = /* @__PURE__ */ new Map();
1678
+ for (const [path, rec] of this._records) {
1679
+ this.index.set(path, { size: rec.size, mtime: rec.mtime });
1680
+ }
1681
+ return this.index;
1682
+ }
1683
+ async get(path) {
1684
+ const rec = this._records.get(path);
1685
+ return rec ? { bytes: rec.bytes, size: rec.size, mtime: rec.mtime } : null;
1686
+ }
1687
+ async put(path, record) {
1688
+ this._records.set(path, {
1689
+ bytes: record.bytes,
1690
+ size: record.size,
1691
+ mtime: record.mtime
1692
+ });
1693
+ }
1694
+ async delete(path) {
1695
+ this._records.delete(path);
1696
+ }
1697
+ async close() {
1698
+ }
1699
+ };
1700
+ var IndexedDbFsStore = class {
1701
+ constructor(dbName) {
1702
+ this.kind = "indexeddb";
1703
+ this.dbName = dbName;
1704
+ this.index = /* @__PURE__ */ new Map();
1705
+ this._db = null;
1706
+ }
1707
+ _openDatabase() {
1708
+ return new Promise((resolve, reject) => {
1709
+ const req = globalThis.indexedDB.open(this.dbName, 1);
1710
+ req.onupgradeneeded = () => {
1711
+ const db = req.result;
1712
+ if (!db.objectStoreNames.contains("files")) db.createObjectStore("files");
1713
+ };
1714
+ req.onsuccess = () => resolve(req.result);
1715
+ req.onerror = () => reject(req.error);
1716
+ });
1717
+ }
1718
+ async open() {
1719
+ this._db = await this._openDatabase();
1720
+ this.index = /* @__PURE__ */ new Map();
1721
+ await new Promise((resolve, reject) => {
1722
+ const tx = this._db.transaction("files", "readonly");
1723
+ const req = tx.objectStore("files").openCursor();
1724
+ req.onsuccess = () => {
1725
+ const cursor = req.result;
1726
+ if (!cursor) {
1727
+ resolve();
1728
+ return;
1729
+ }
1730
+ const value = cursor.value;
1731
+ this.index.set(cursor.key, { size: value.size, mtime: value.mtime });
1732
+ cursor.continue();
1733
+ };
1734
+ req.onerror = () => reject(req.error);
1735
+ tx.onerror = () => reject(tx.error);
1736
+ });
1737
+ return this.index;
1738
+ }
1739
+ _request(request) {
1740
+ return new Promise((resolve, reject) => {
1741
+ request.onsuccess = () => resolve(request.result);
1742
+ request.onerror = () => reject(request.error);
1743
+ });
1744
+ }
1745
+ _transactionDone(tx) {
1746
+ return new Promise((resolve, reject) => {
1747
+ tx.oncomplete = () => resolve();
1748
+ tx.onerror = () => reject(tx.error);
1749
+ tx.onabort = () => reject(tx.error);
1750
+ });
1751
+ }
1752
+ async get(path) {
1753
+ const tx = this._db.transaction("files", "readonly");
1754
+ const rec = await this._request(tx.objectStore("files").get(path));
1755
+ return rec ?? null;
1756
+ }
1757
+ async put(path, record) {
1758
+ const tx = this._db.transaction("files", "readwrite");
1759
+ tx.objectStore("files").put(
1760
+ { bytes: record.bytes, size: record.size, mtime: record.mtime },
1761
+ path
1762
+ );
1763
+ await this._transactionDone(tx);
1764
+ }
1765
+ async delete(path) {
1766
+ const tx = this._db.transaction("files", "readwrite");
1767
+ tx.objectStore("files").delete(path);
1768
+ await this._transactionDone(tx);
1769
+ }
1770
+ async close() {
1771
+ if (this._db) {
1772
+ this._db.close();
1773
+ this._db = null;
1774
+ }
1775
+ }
1776
+ };
1777
+ function createFsStore(target, options = {}) {
1778
+ if (options.fsStore) return options.fsStore;
1779
+ if (typeof options.storeFactory === "function") {
1780
+ return options.storeFactory(target);
1781
+ }
1782
+ if (typeof globalThis.indexedDB !== "undefined" && globalThis.indexedDB) {
1783
+ return new IndexedDbFsStore(`tinyc-web-fs-${target}`);
1784
+ }
1785
+ return new MemoryFsStore();
1786
+ }
1787
+ async function openFsStore(target, options = {}) {
1788
+ const injected = Boolean(options.fsStore) || typeof options.storeFactory === "function";
1789
+ let store = await createFsStore(target, options);
1790
+ try {
1791
+ await store.open();
1792
+ } catch (err) {
1793
+ if (injected || store.kind !== "indexeddb") throw err;
1794
+ store = new MemoryFsStore();
1795
+ await store.open();
1796
+ }
1797
+ return store;
1798
+ }
1799
+
1800
+ // index.mjs
1801
+ var import_meta = {};
1802
+ var sysrootManifest = wasm32_wasi_default;
1803
+ var SYSROOT_MANIFESTS = Object.freeze({
1804
+ "wasm32-wasi": wasm32_wasi_default,
1805
+ "x86_64-linux-gnu": x86_64_linux_gnu_default,
1806
+ "aarch64-linux-gnu": aarch64_linux_gnu_default,
1807
+ "riscv64-linux-gnu": riscv64_linux_gnu_default,
1808
+ "x86_64-windows": x86_64_windows_default,
1809
+ "aarch64-linux-android": aarch64_linux_android_default,
1810
+ "x86_64-linux-android": x86_64_linux_android_default,
1811
+ "arm64-apple-darwin": arm64_apple_darwin_default,
1812
+ "x86_64-apple-darwin": x86_64_apple_darwin_default
1813
+ });
1814
+ var SCRIPT_DIR_HREF = (() => {
1815
+ try {
1816
+ const script = typeof document !== "undefined" ? document.currentScript : null;
1817
+ if (script && script.src) return new URL(".", script.src).href;
1818
+ } catch {
1819
+ }
1820
+ return null;
1821
+ })();
1822
+ var MODULE_URL = (() => {
1823
+ try {
1824
+ return import_meta.url || null;
1825
+ } catch {
1826
+ return null;
1827
+ }
1828
+ })();
1829
+ var PAGE_DIR_HREF = (() => {
1830
+ try {
1831
+ if (typeof location !== "undefined" && location.href) {
1832
+ return new URL(".", location.href).href;
1833
+ }
1834
+ } catch {
1835
+ }
1836
+ return null;
1837
+ })();
1838
+ function dirHref(url) {
1839
+ return url.endsWith("/") ? url : url + "/";
1840
+ }
1841
+ function assetUrl(name, baseUrl) {
1842
+ const base = baseUrl ? dirHref(baseUrl) : SCRIPT_DIR_HREF ?? MODULE_URL ?? PAGE_DIR_HREF;
1843
+ return base ? new URL(name, base).href : name;
1844
+ }
1845
+ var VIRTUAL_BIN_PATH = sysrootManifest.binPath;
1846
+ var TinycError = class extends Error {
1847
+ constructor(message, code) {
1848
+ super(message);
1849
+ this.name = "TinycError";
1850
+ if (code !== void 0) this.code = code;
1851
+ }
1852
+ };
1853
+ var TinycMissingExportError = class extends TinycError {
1854
+ constructor(exportName) {
1855
+ super(
1856
+ `tinyc: native module does not export "${exportName}". The WASM build must list it in EXPORTED_FUNCTIONS (see build.sh).`
1857
+ );
1858
+ this.name = "TinycMissingExportError";
1859
+ this.exportName = exportName;
1860
+ }
1861
+ };
1862
+ var DEFAULT_TARGET = "wasm32-wasi";
1863
+ var TARGETS = Object.freeze({
1864
+ "wasm32-wasi": { runnable: true, description: "WebAssembly (WASI); output runs in the browser" },
1865
+ "x86_64-linux-gnu": { runnable: false, description: "Linux x86-64 ELF" },
1866
+ "aarch64-linux-gnu": { runnable: false, description: "Linux AArch64 ELF" },
1867
+ "riscv64-linux-gnu": { runnable: false, description: "Linux RISC-V 64 ELF" },
1868
+ "x86_64-windows": { runnable: false, description: "Windows x86-64 PE" },
1869
+ "aarch64-linux-android": { runnable: false, description: "Android AArch64 ELF (bionic)" },
1870
+ "x86_64-linux-android": { runnable: false, description: "Android x86-64 ELF (bionic)" },
1871
+ "arm64-apple-darwin": { runnable: false, description: "macOS arm64 Mach-O" },
1872
+ "x86_64-apple-darwin": { runnable: false, description: "macOS x86-64 Mach-O" }
1873
+ });
1874
+ var SUPPORTED_TARGETS = Object.freeze(Object.keys(TARGETS));
1875
+ function isRunnableTarget(target) {
1876
+ return Boolean(TARGETS[target]?.runnable);
1877
+ }
1878
+ function targetModuleFiles(target) {
1879
+ return { wasmFile: `tcc-${target}.wasm`, glueFile: `tcc-${target}.mjs` };
1880
+ }
1881
+ function assertKnownTarget(target) {
1882
+ if (!Object.hasOwn(TARGETS, target)) {
1883
+ throw new TinycError(
1884
+ `tinyc: unknown target "${target}". Supported targets: ${SUPPORTED_TARGETS.join(", ")}`
1885
+ );
1886
+ }
1887
+ }
1888
+ var TinycRunNotSupportedError = class extends TinycError {
1889
+ constructor(target) {
1890
+ super(
1891
+ `tinyc: target "${target}" cannot be run in the browser: in the browser it can only be compiled to a file. Running compiled output is only possible for the "${DEFAULT_TARGET}" target, whose output is WebAssembly and is instantiated and executed by the browser itself.`
1892
+ );
1893
+ this.name = "TinycRunNotSupportedError";
1894
+ this.target = target;
1895
+ }
1896
+ };
1897
+ function lineBuffered(sink) {
1898
+ let pending = "";
1899
+ const write = (text) => {
1900
+ pending += text;
1901
+ let idx;
1902
+ while ((idx = pending.indexOf("\n")) >= 0) {
1903
+ sink(pending.slice(0, idx));
1904
+ pending = pending.slice(idx + 1);
1905
+ }
1906
+ };
1907
+ write.flush = () => {
1908
+ if (pending.length > 0) {
1909
+ sink(pending);
1910
+ pending = "";
1911
+ }
1912
+ };
1913
+ return write;
1914
+ }
1915
+ function createDefaultIO() {
1916
+ return {
1917
+ out: lineBuffered((line) => console.log(line)),
1918
+ err: lineBuffered((line) => console.error(line)),
1919
+ in: () => null
1920
+ };
1921
+ }
1922
+ function normalizeIO(partial, base) {
1923
+ const io = { ...base ?? createDefaultIO() };
1924
+ if (partial) {
1925
+ for (const key of ["out", "err", "in"]) {
1926
+ if (partial[key] !== void 0) {
1927
+ if (typeof partial[key] !== "function") {
1928
+ throw new TinycError(`tinyc: io.${key} must be a function`);
1929
+ }
1930
+ io[key] = partial[key];
1931
+ }
1932
+ }
1933
+ }
1934
+ return io;
1935
+ }
1936
+ function flushIO(io) {
1937
+ for (const key of ["out", "err"]) {
1938
+ if (typeof io[key]?.flush === "function") io[key].flush();
1939
+ }
1940
+ }
1941
+ var VFS_CACHE_MAX_ENTRIES = 32;
1942
+ var VFS_CACHE_MAX_BYTES = 16 * 1024 * 1024;
1943
+ var textEncoder2 = new TextEncoder();
1944
+ var textDecoder2 = new TextDecoder();
1945
+ function normalizeVfsPath(path) {
1946
+ if (typeof path !== "string" || path.length === 0) {
1947
+ throw new TinycError("tinyc: vfs path must be a non-empty string");
1948
+ }
1949
+ const parts = [];
1950
+ for (const seg of path.split("/")) {
1951
+ if (seg === "" || seg === ".") continue;
1952
+ if (seg === "..") parts.pop();
1953
+ else parts.push(seg);
1954
+ }
1955
+ return "/" + parts.join("/");
1956
+ }
1957
+ function contentToBytesSync(content) {
1958
+ if (typeof content === "string") return textEncoder2.encode(content);
1959
+ if (content instanceof Uint8Array) return new Uint8Array(content);
1960
+ if (content instanceof ArrayBuffer) return new Uint8Array(content);
1961
+ if (typeof Blob !== "undefined" && content instanceof Blob) return null;
1962
+ throw new TinycError(
1963
+ "tinyc: addFile content must be a string, Uint8Array, ArrayBuffer, File or Blob"
1964
+ );
1965
+ }
1966
+ async function contentToBytes(content) {
1967
+ const syncBytes = contentToBytesSync(content);
1968
+ if (syncBytes) return syncBytes;
1969
+ return new Uint8Array(await content.arrayBuffer());
1970
+ }
1971
+ var VirtualFS = class {
1972
+ /** `store` is an opened FsStore (see vfs-store.mjs); its persisted
1973
+ * index becomes this filesystem's initial file set. With no store
1974
+ * argument, a volatile in-memory store is used. loadTinyc opens
1975
+ * the per-target store (IndexedDB by default) before building
1976
+ * the instance's VirtualFS. */
1977
+ constructor(store = null) {
1978
+ this._store = store ?? new MemoryFsStore();
1979
+ this.index = new Map(this._store.index ?? []);
1980
+ this.includeDirs = [];
1981
+ this._emscriptenFS = null;
1982
+ this._moduleFsPrefix = "";
1983
+ this._cache = /* @__PURE__ */ new Map();
1984
+ this._cacheBytes = 0;
1985
+ this._pending = /* @__PURE__ */ new Set();
1986
+ this._idleError = null;
1987
+ }
1988
+ /** The kind of the backing store: 'indexeddb' or 'memory'. */
1989
+ get storeKind() {
1990
+ return this._store.kind;
1991
+ }
1992
+ _cacheGet(path) {
1993
+ const bytes = this._cache.get(path);
1994
+ if (bytes) {
1995
+ this._cache.delete(path);
1996
+ this._cache.set(path, bytes);
1997
+ }
1998
+ return bytes;
1999
+ }
2000
+ _cachePut(path, bytes) {
2001
+ const prev = this._cache.get(path);
2002
+ if (prev) {
2003
+ this._cache.delete(path);
2004
+ this._cacheBytes -= prev.byteLength;
2005
+ }
2006
+ this._cache.set(path, bytes);
2007
+ this._cacheBytes += bytes.byteLength;
2008
+ while (this._cache.size > 1 && (this._cache.size > VFS_CACHE_MAX_ENTRIES || this._cacheBytes > VFS_CACHE_MAX_BYTES)) {
2009
+ const oldest = this._cache.keys().next().value;
2010
+ this._cacheBytes -= this._cache.get(oldest).byteLength;
2011
+ this._cache.delete(oldest);
2012
+ }
2013
+ }
2014
+ _cacheDelete(path) {
2015
+ const prev = this._cache.get(path);
2016
+ if (prev) {
2017
+ this._cache.delete(path);
2018
+ this._cacheBytes -= prev.byteLength;
2019
+ }
2020
+ }
2021
+ /** Queue a store operation kicked off by a synchronous method
2022
+ * (addFileSync / removeFile / clear). Tracked so whenIdle() can
2023
+ * await the queue; the first failure is remembered and rethrown
2024
+ * by whenIdle() instead of surfacing as an unhandled rejection. */
2025
+ _queueStoreOp(op) {
2026
+ let base;
2027
+ try {
2028
+ base = Promise.resolve(op());
2029
+ } catch (err) {
2030
+ base = Promise.reject(err);
2031
+ }
2032
+ const tracked = base.then(
2033
+ () => {
2034
+ this._pending.delete(tracked);
2035
+ },
2036
+ (err) => {
2037
+ this._pending.delete(tracked);
2038
+ if (this._idleError == null) this._idleError = err;
2039
+ }
2040
+ );
2041
+ this._pending.add(tracked);
2042
+ }
2043
+ /** Resolve once every queued store write/delete has landed.
2044
+ * Rethrows the first queued operation's failure, if any. */
2045
+ async whenIdle() {
2046
+ while (this._pending.size > 0) {
2047
+ await Promise.all([...this._pending]);
2048
+ }
2049
+ if (this._idleError != null) {
2050
+ const err = this._idleError;
2051
+ this._idleError = null;
2052
+ throw err;
2053
+ }
2054
+ }
2055
+ /** Synchronous half of a write: index, content cache and the
2056
+ * Emscripten FS mirror. Returns the normalized path and the
2057
+ * record to persist. */
2058
+ _stage(path, bytes) {
2059
+ const p = normalizeVfsPath(path);
2060
+ const buf = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
2061
+ const meta = { size: buf.byteLength, mtime: Date.now() };
2062
+ this.index.set(p, meta);
2063
+ this._cachePut(p, buf);
2064
+ this.syncFile(p);
2065
+ return { p, record: { bytes: buf, size: meta.size, mtime: meta.mtime } };
2066
+ }
2067
+ /** Add or replace a file. `content` may be a string, Uint8Array,
2068
+ * ArrayBuffer, File or Blob. For the content kinds whose bytes
2069
+ * are at hand (string, Uint8Array, ArrayBuffer) the file is
2070
+ * staged — index, content cache and the Emscripten FS mirror —
2071
+ * synchronously, before this call returns its promise, so a
2072
+ * compile or read issued immediately afterwards, without
2073
+ * awaiting, already sees the file; Blob and File content stages
2074
+ * once its bytes have been read. The returned promise resolves
2075
+ * once the content is persisted in the store. */
2076
+ async addFile(path, content) {
2077
+ const bytes = contentToBytesSync(content) ?? await contentToBytes(content);
2078
+ const { p, record } = this._stage(path, bytes);
2079
+ await this._store.put(p, record);
2080
+ }
2081
+ /** Synchronous write: index, cache and the Emscripten mirror are
2082
+ * updated immediately (so the file can be compiled and read back
2083
+ * synchronously); the store write is queued behind any other
2084
+ * queued operations — await whenIdle() for it to land. */
2085
+ addFileSync(path, content) {
2086
+ const bytes = typeof content === "string" ? textEncoder2.encode(content) : content;
2087
+ const { p, record } = this._stage(path, bytes);
2088
+ this._queueStoreOp(() => this._store.put(p, record));
2089
+ return p;
2090
+ }
2091
+ /** Fetch a file from a URL into the virtual filesystem.
2092
+ * `fetchImpl` is injectable for tests and non-window contexts. */
2093
+ async addFileFromUrl(path, url, { fetchImpl = globalThis.fetch } = {}) {
2094
+ if (typeof fetchImpl !== "function") {
2095
+ throw new TinycError("tinyc: addFileFromUrl needs a fetch implementation");
2096
+ }
2097
+ const res = await fetchImpl(url);
2098
+ if (res && res.ok === false) {
2099
+ throw new TinycError(`tinyc: fetching ${url} failed with status ${res.status}`);
2100
+ }
2101
+ const buf = await res.arrayBuffer();
2102
+ const bytes = new Uint8Array(buf);
2103
+ const { p, record } = this._stage(path, bytes);
2104
+ await this._store.put(p, record);
2105
+ return p;
2106
+ }
2107
+ /** Register a directory as a header search directory. Every state
2108
+ * created afterwards gets it via tcc_add_include_path, in
2109
+ * registration order, ahead of the sysroot. */
2110
+ registerIncludeDir(path) {
2111
+ const p = normalizeVfsPath(path);
2112
+ if (!this.includeDirs.includes(p)) this.includeDirs.push(p);
2113
+ return p;
2114
+ }
2115
+ getIncludeDirs() {
2116
+ return [...this.includeDirs];
2117
+ }
2118
+ hasFile(path) {
2119
+ return this.index.has(normalizeVfsPath(path));
2120
+ }
2121
+ /** Synchronous read, served from the content cache: files written
2122
+ * or read during this session are cached, so this covers the
2123
+ * compile/read-back paths. A persisted file that is not cached
2124
+ * throws, naming the async alternative — use readFileAsync. */
2125
+ readFile(path) {
2126
+ const p = normalizeVfsPath(path);
2127
+ if (!this.index.has(p)) {
2128
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
2129
+ }
2130
+ const bytes = this._cacheGet(p);
2131
+ if (!bytes) {
2132
+ throw new TinycError(
2133
+ `tinyc: ${p} is persisted in the virtual FS store but is not in the in-memory cache; read it with readFileAsync() instead`
2134
+ );
2135
+ }
2136
+ return bytes;
2137
+ }
2138
+ readTextFile(path) {
2139
+ return textDecoder2.decode(this.readFile(path));
2140
+ }
2141
+ /** Read a file's content from the store, warming the content
2142
+ * cache, so later synchronous reads of the same file succeed. */
2143
+ async readFileAsync(path) {
2144
+ const p = normalizeVfsPath(path);
2145
+ if (!this.index.has(p)) {
2146
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
2147
+ }
2148
+ const hit = this._cacheGet(p);
2149
+ if (hit) return hit;
2150
+ const rec = await this._store.get(p);
2151
+ if (!rec) {
2152
+ throw new TinycError(`tinyc: no such file in virtual FS: ${path}`);
2153
+ }
2154
+ this._cachePut(p, rec.bytes);
2155
+ return rec.bytes;
2156
+ }
2157
+ async readTextFileAsync(path) {
2158
+ return textDecoder2.decode(await this.readFileAsync(path));
2159
+ }
2160
+ /** Delete one file. Every copy goes: the index entry and cached
2161
+ * content, the persisted record (queued — see whenIdle), and,
2162
+ * when an Emscripten FS is mounted, the mirrored file inside the
2163
+ * native module (an unlink is attempted even for a path missing
2164
+ * from the index, e.g. a file the compiler created natively).
2165
+ * Returns true when the index or the native copy existed. */
2166
+ removeFile(path) {
2167
+ const p = normalizeVfsPath(path);
2168
+ const had = this.index.delete(p);
2169
+ this._cacheDelete(p);
2170
+ this._queueStoreOp(() => this._store.delete(p));
2171
+ let unlinked = false;
2172
+ const FS = this._emscriptenFS;
2173
+ if (FS && typeof FS.unlink === "function") {
2174
+ try {
2175
+ FS.unlink(this._nativePath(p));
2176
+ unlinked = true;
2177
+ } catch {
2178
+ }
2179
+ }
2180
+ return had || unlinked;
2181
+ }
2182
+ /** Delete every file tracked by this virtual FS except the
2183
+ * mounted sysroot (paths under /sysroot/), which stays so the
2184
+ * instance can keep compiling. Store records are deleted (queued)
2185
+ * and mirrors in the native module FS are unlinked as well.
2186
+ * Returns the number of files removed. */
2187
+ clear() {
2188
+ let removed = 0;
2189
+ for (const p of [...this.index.keys()]) {
2190
+ if (p.startsWith("/sysroot/")) continue;
2191
+ if (this.removeFile(p)) removed += 1;
2192
+ }
2193
+ return removed;
2194
+ }
2195
+ listFiles(prefix = "/") {
2196
+ const p = normalizeVfsPath(prefix);
2197
+ return [...this.index.keys()].filter((f) => f.startsWith(p)).sort();
2198
+ }
2199
+ // === Emscripten FS adaptation point (see header note) ===
2200
+ /** Mirror the whole virtual FS into the native module's FS. The
2201
+ * mounted FS is registered synchronously; copying the persisted
2202
+ * files is asynchronous (their bytes may have to come out of the
2203
+ * store), so this returns a promise loadTinyc awaits before the
2204
+ * instance is handed out. Callers that mount an empty or
2205
+ * cache-resident FS can ignore the promise.
2206
+ * `moduleFsPrefix` is the directory inside the module FS the
2207
+ * mirror lands under — the bridge's moduleFsPrefix ("/opfs" when
2208
+ * the WasmFS OPFS backend is mounted there, "" for the memory
2209
+ * root). It is remembered here so syncFile() and removeFile()
2210
+ * hit the same locations; the virtual FS's own paths, index and
2211
+ * store are unaffected by it. */
2212
+ async mountTo(emscriptenFS, moduleFsPrefix = "") {
2213
+ this._emscriptenFS = emscriptenFS ?? null;
2214
+ this._moduleFsPrefix = moduleFsPrefix ?? "";
2215
+ if (!this._emscriptenFS) return;
2216
+ for (const path of [...this.index.keys()]) {
2217
+ let bytes = this._cacheGet(path);
2218
+ if (!bytes) {
2219
+ const rec = await this._store.get(path);
2220
+ if (rec) {
2221
+ bytes = rec.bytes;
2222
+ this._cachePut(path, bytes);
2223
+ }
2224
+ }
2225
+ if (bytes) this._writeNative(path, bytes);
2226
+ }
2227
+ }
2228
+ /** Mirror one file into the native FS from the content cache.
2229
+ * Files written through this FS are synced as they are written;
2230
+ * a file whose content is neither cached nor already mirrored
2231
+ * cannot be synced synchronously and is left to mountTo. */
2232
+ syncFile(path) {
2233
+ const FS = this._emscriptenFS;
2234
+ if (!FS) return;
2235
+ const bytes = this._cacheGet(path);
2236
+ if (!bytes) return;
2237
+ this._writeNative(path, bytes);
2238
+ }
2239
+ /** The location of a (normalized) virtual path inside the
2240
+ * native module's filesystem: under the mount prefix when one
2241
+ * was given to mountTo, at the module FS root otherwise. */
2242
+ _nativePath(path) {
2243
+ return this._moduleFsPrefix ? this._moduleFsPrefix + path : path;
2244
+ }
2245
+ _writeNative(path, bytes) {
2246
+ const FS = this._emscriptenFS;
2247
+ const nativePath = this._nativePath(path);
2248
+ const dir = nativePath.slice(0, nativePath.lastIndexOf("/")) || "/";
2249
+ if (typeof FS.mkdirTree === "function") FS.mkdirTree(dir);
2250
+ FS.writeFile(nativePath, bytes);
2251
+ }
2252
+ };
2253
+ var NativeBridge = class {
2254
+ constructor(native, io) {
2255
+ this.native = native;
2256
+ this.io = io;
2257
+ this.moduleFsPrefix = "";
2258
+ if (native && typeof native.ccall === "function") this.mode = "emscripten";
2259
+ else if (native && native.memory instanceof WebAssembly.Memory) this.mode = "raw";
2260
+ else if (native && typeof native === "object") this.mode = "mock";
2261
+ else {
2262
+ throw new TinycError(
2263
+ "tinyc: unsupported native module shape; pass an Emscripten module, WebAssembly exports, or a mock object implementing the tcc_* functions"
2264
+ );
2265
+ }
2266
+ }
2267
+ /** Translate a virtual FS path to the path the native module
2268
+ * knows it by: the normalized path under moduleFsPrefix. With no
2269
+ * prefix (memory backend) the argument passes through exactly as
2270
+ * given, so native calls are unchanged in that mode. */
2271
+ modulePath(path) {
2272
+ if (!this.moduleFsPrefix) return path;
2273
+ return this.moduleFsPrefix + normalizeVfsPath(path);
2274
+ }
2275
+ has(name) {
2276
+ const n = this.native;
2277
+ switch (this.mode) {
2278
+ case "emscripten":
2279
+ return typeof n["_" + name] === "function" || typeof n[name] === "function";
2280
+ case "raw":
2281
+ return typeof n[name] === "function" || typeof n["_" + name] === "function";
2282
+ default:
2283
+ return typeof n[name] === "function";
2284
+ }
2285
+ }
2286
+ requireExport(name) {
2287
+ if (!this.has(name)) throw new TinycMissingExportError(name);
2288
+ }
2289
+ _rawFn(name) {
2290
+ return this.native[name] ?? this.native["_" + name];
2291
+ }
2292
+ /** Call a tcc_* style export. argTypes entries: 'number' | 'string'.
2293
+ * In mock mode arguments pass through as JS values untouched. */
2294
+ call(name, returnType, argTypes, args) {
2295
+ this.requireExport(name);
2296
+ if (this.mode === "mock") return this.native[name](...args);
2297
+ if (this.mode === "emscripten") {
2298
+ return this.native.ccall(name, returnType, argTypes, args);
2299
+ }
2300
+ return this._callRaw(name, argTypes, args);
2301
+ }
2302
+ _mem() {
2303
+ return new Uint8Array(this.native.memory.buffer);
2304
+ }
2305
+ _alloc(bytes) {
2306
+ const malloc = this._rawFn("malloc");
2307
+ if (typeof malloc !== "function") {
2308
+ throw new TinycMissingExportError("malloc (needed to pass strings to the raw WASM module)");
2309
+ }
2310
+ const ptr = malloc(bytes);
2311
+ if (!ptr) throw new TinycError("tinyc: WASM malloc returned null");
2312
+ return ptr;
2313
+ }
2314
+ _free(ptr) {
2315
+ const free = this._rawFn("free");
2316
+ if (typeof free === "function" && ptr) free(ptr);
2317
+ }
2318
+ _allocCString(str) {
2319
+ const bytes = textEncoder2.encode(str + "\0");
2320
+ const ptr = this._alloc(bytes.length);
2321
+ this._mem().set(bytes, ptr);
2322
+ return ptr;
2323
+ }
2324
+ _callRaw(name, argTypes, args) {
2325
+ const fn = this._rawFn(name);
2326
+ const ptrs = [];
2327
+ try {
2328
+ const conv = args.map((arg, i) => {
2329
+ if (argTypes[i] === "string") {
2330
+ const p = this._allocCString(arg);
2331
+ ptrs.push(p);
2332
+ return p;
2333
+ }
2334
+ return arg;
2335
+ });
2336
+ return fn(...conv);
2337
+ } finally {
2338
+ for (const p of ptrs) this._free(p);
2339
+ }
2340
+ }
2341
+ /** Call the exported main / tinyc_main with a fully assembled argv.
2342
+ * argvStrings[0] is the program name slot, already filled by the
2343
+ * caller. tinyc_main is preferred when both are exported. */
2344
+ callMain(argvStrings) {
2345
+ const entry = this.has("tinyc_main") ? "tinyc_main" : "main";
2346
+ this.requireExport(entry);
2347
+ const argc = argvStrings.length;
2348
+ if (this.mode === "mock") return this.native[entry](argc, [...argvStrings]);
2349
+ if (this.mode === "emscripten") return this._callMainEmscripten(entry, argvStrings);
2350
+ return this._callMainRaw(entry, argvStrings);
2351
+ }
2352
+ _callMainRaw(entry, argvStrings) {
2353
+ const fn = this._rawFn(entry);
2354
+ const strPtrs = argvStrings.map((s) => this._allocCString(s));
2355
+ const argvPtr = this._alloc((argvStrings.length + 1) * 4);
2356
+ try {
2357
+ const view = new DataView(this.native.memory.buffer);
2358
+ strPtrs.forEach((p, i) => view.setUint32(argvPtr + i * 4, p, true));
2359
+ view.setUint32(argvPtr + argvStrings.length * 4, 0, true);
2360
+ return fn(argvStrings.length, argvPtr);
2361
+ } finally {
2362
+ for (const p of strPtrs) this._free(p);
2363
+ this._free(argvPtr);
2364
+ }
2365
+ }
2366
+ _callMainEmscripten(entry, argvStrings) {
2367
+ const n = this.native;
2368
+ if (typeof n._malloc !== "function" || !n.HEAPU8) {
2369
+ throw new TinycError(
2370
+ "tinyc: Emscripten module must export _malloc and HEAPU8 to assemble argv"
2371
+ );
2372
+ }
2373
+ const strPtrs = argvStrings.map((s) => {
2374
+ const bytes = textEncoder2.encode(s + "\0");
2375
+ const p = n._malloc(bytes.length);
2376
+ n.HEAPU8.set(bytes, p);
2377
+ return p;
2378
+ });
2379
+ const argvPtr = n._malloc((argvStrings.length + 1) * 4);
2380
+ try {
2381
+ const view = new DataView(n.HEAPU8.buffer);
2382
+ strPtrs.forEach((p, i) => view.setUint32(argvPtr + i * 4, p, true));
2383
+ view.setUint32(argvPtr + argvStrings.length * 4, 0, true);
2384
+ const fn = n["_" + entry];
2385
+ return fn(argvStrings.length, argvPtr);
2386
+ } finally {
2387
+ for (const p of strPtrs) n._free(p);
2388
+ n._free(argvPtr);
2389
+ }
2390
+ }
2391
+ };
2392
+ var WasiExit = class extends Error {
2393
+ constructor(code) {
2394
+ super(`tinyc: wasi proc_exit(${code})`);
2395
+ this.name = "WasiExit";
2396
+ this.exitCode = code;
2397
+ }
2398
+ };
2399
+ var WASI_ERRNO = {
2400
+ SUCCESS: 0,
2401
+ BADF: 8,
2402
+ FAULT: 21,
2403
+ INVAL: 28,
2404
+ NOSYS: 52,
2405
+ SPIPE: 70
2406
+ };
2407
+ var WASI_RIGHTS_FD_READ = 1n << 1n;
2408
+ var WASI_RIGHTS_FD_WRITE = 1n << 6n;
2409
+ function createDefaultByteIO() {
2410
+ const outDec = new TextDecoder();
2411
+ const errDec = new TextDecoder();
2412
+ return {
2413
+ out: (bytes) => console.log(outDec.decode(bytes, { stream: true })),
2414
+ err: (bytes) => console.error(errDec.decode(bytes, { stream: true }))
2415
+ };
2416
+ }
2417
+ function createWasiShim(options, holder, io) {
2418
+ const argv = (options.args ?? []).map(String);
2419
+ const envPairs = Object.entries(options.env ?? {}).map(([k, v]) => `${k}=${v}`);
2420
+ let stdin = options.stdin ?? new Uint8Array(0);
2421
+ if (typeof stdin === "string") stdin = textEncoder2.encode(stdin);
2422
+ let stdinPos = 0;
2423
+ const mem = () => holder.memory;
2424
+ const view = () => new DataView(mem().buffer);
2425
+ const bytes = () => new Uint8Array(mem().buffer);
2426
+ function writeStringTable(ptrAddr, bufAddr, strings) {
2427
+ const v = view();
2428
+ const m = bytes();
2429
+ let offset = 0;
2430
+ strings.forEach((s, i) => {
2431
+ const encoded = textEncoder2.encode(s + "\0");
2432
+ v.setUint32(ptrAddr + i * 4, bufAddr + offset, true);
2433
+ m.set(encoded, bufAddr + offset);
2434
+ offset += encoded.length;
2435
+ });
2436
+ return offset;
2437
+ }
2438
+ const stringTableSize = (strings) => strings.reduce((n, s) => n + textEncoder2.encode(s).length + 1, 0);
2439
+ return {
2440
+ fd_write(fd, iovs, iovsLen, nwrittenPtr) {
2441
+ if (fd !== 1 && fd !== 2) return WASI_ERRNO.BADF;
2442
+ if (!mem()) return WASI_ERRNO.FAULT;
2443
+ const v = view();
2444
+ const m = bytes();
2445
+ const chunks = [];
2446
+ let total = 0;
2447
+ for (let i = 0; i < iovsLen; i++) {
2448
+ const ptr = v.getUint32(iovs + i * 8, true);
2449
+ const len = v.getUint32(iovs + i * 8 + 4, true);
2450
+ chunks.push(m.slice(ptr, ptr + len));
2451
+ total += len;
2452
+ }
2453
+ const merged = new Uint8Array(total);
2454
+ let at = 0;
2455
+ for (const c of chunks) {
2456
+ merged.set(c, at);
2457
+ at += c.length;
2458
+ }
2459
+ (fd === 1 ? io.out : io.err)(merged);
2460
+ v.setUint32(nwrittenPtr, total, true);
2461
+ return WASI_ERRNO.SUCCESS;
2462
+ },
2463
+ fd_read(fd, iovs, iovsLen, nreadPtr) {
2464
+ if (fd !== 0) return WASI_ERRNO.BADF;
2465
+ if (!mem()) return WASI_ERRNO.FAULT;
2466
+ const v = view();
2467
+ const m = bytes();
2468
+ let total = 0;
2469
+ for (let i = 0; i < iovsLen && stdinPos < stdin.length; i++) {
2470
+ const ptr = v.getUint32(iovs + i * 8, true);
2471
+ const len = v.getUint32(iovs + i * 8 + 4, true);
2472
+ const n = Math.min(len, stdin.length - stdinPos);
2473
+ m.set(stdin.subarray(stdinPos, stdinPos + n), ptr);
2474
+ stdinPos += n;
2475
+ total += n;
2476
+ }
2477
+ v.setUint32(nreadPtr, total, true);
2478
+ return WASI_ERRNO.SUCCESS;
2479
+ },
2480
+ fd_close(fd) {
2481
+ return fd >= 0 && fd <= 2 ? WASI_ERRNO.SUCCESS : WASI_ERRNO.BADF;
2482
+ },
2483
+ fd_seek(fd, _offset, _whence, newoffsetPtr) {
2484
+ if (fd < 0 || fd > 2) return WASI_ERRNO.BADF;
2485
+ if (!mem()) return WASI_ERRNO.FAULT;
2486
+ view().setBigUint64(newoffsetPtr, 0n, true);
2487
+ return WASI_ERRNO.SPIPE;
2488
+ },
2489
+ fd_fdstat_get(fd, ptr) {
2490
+ if (fd < 0 || fd > 2) return WASI_ERRNO.BADF;
2491
+ if (!mem()) return WASI_ERRNO.FAULT;
2492
+ const m = bytes();
2493
+ m.fill(0, ptr, ptr + 24);
2494
+ const v = view();
2495
+ m[ptr] = 2;
2496
+ v.setBigUint64(ptr + 8, fd === 0 ? WASI_RIGHTS_FD_READ : WASI_RIGHTS_FD_WRITE, true);
2497
+ v.setBigUint64(ptr + 16, 0n, true);
2498
+ return WASI_ERRNO.SUCCESS;
2499
+ },
2500
+ proc_exit(code) {
2501
+ throw new WasiExit(code);
2502
+ },
2503
+ args_sizes_get(argcPtr, argvBufSizePtr) {
2504
+ if (!mem()) return WASI_ERRNO.FAULT;
2505
+ const v = view();
2506
+ v.setUint32(argcPtr, argv.length, true);
2507
+ v.setUint32(argvBufSizePtr, stringTableSize(argv), true);
2508
+ return WASI_ERRNO.SUCCESS;
2509
+ },
2510
+ args_get(argvPtr, bufPtr) {
2511
+ if (!mem()) return WASI_ERRNO.FAULT;
2512
+ writeStringTable(argvPtr, bufPtr, argv);
2513
+ return WASI_ERRNO.SUCCESS;
2514
+ },
2515
+ environ_sizes_get(countPtr, sizePtr) {
2516
+ if (!mem()) return WASI_ERRNO.FAULT;
2517
+ const v = view();
2518
+ v.setUint32(countPtr, envPairs.length, true);
2519
+ v.setUint32(sizePtr, stringTableSize(envPairs), true);
2520
+ return WASI_ERRNO.SUCCESS;
2521
+ },
2522
+ environ_get(envPtr, bufPtr) {
2523
+ if (!mem()) return WASI_ERRNO.FAULT;
2524
+ writeStringTable(envPtr, bufPtr, envPairs);
2525
+ return WASI_ERRNO.SUCCESS;
2526
+ },
2527
+ clock_time_get(id, _precision, resultPtr) {
2528
+ if (!mem()) return WASI_ERRNO.FAULT;
2529
+ const nowNs = id === 0 ? BigInt(Date.now()) * 1000000n : BigInt(Math.round(performance.now() * 1e6));
2530
+ view().setBigUint64(resultPtr, nowNs, true);
2531
+ return WASI_ERRNO.SUCCESS;
2532
+ },
2533
+ random_get(bufPtr, len) {
2534
+ if (!mem()) return WASI_ERRNO.FAULT;
2535
+ const m = bytes();
2536
+ const chunk = new Uint8Array(len);
2537
+ if (typeof globalThis.crypto?.getRandomValues === "function") {
2538
+ for (let at = 0; at < len; at += 65536) {
2539
+ globalThis.crypto.getRandomValues(
2540
+ chunk.subarray(at, Math.min(at + 65536, len))
2541
+ );
2542
+ }
2543
+ } else {
2544
+ for (let i = 0; i < len; i++) chunk[i] = Math.floor(Math.random() * 256);
2545
+ }
2546
+ m.set(chunk, bufPtr);
2547
+ return WASI_ERRNO.SUCCESS;
2548
+ },
2549
+ sched_yield() {
2550
+ return WASI_ERRNO.SUCCESS;
2551
+ }
2552
+ };
2553
+ }
2554
+ var globalShimRegistry = /* @__PURE__ */ new Map();
2555
+ function splitShimKey(key) {
2556
+ const dot = key.indexOf(".");
2557
+ if (dot < 0) return { module: "env", name: key };
2558
+ return { module: key.slice(0, dot), name: key.slice(dot + 1) };
2559
+ }
2560
+ function canonicalShimKey(key) {
2561
+ const { module, name } = splitShimKey(key);
2562
+ return `${module}.${name}`;
2563
+ }
2564
+ function setShimEntry(map, name, fn) {
2565
+ if (typeof name !== "string" || name.length === 0) {
2566
+ throw new TinycError("tinyc: shim name must be a non-empty string");
2567
+ }
2568
+ if (typeof fn !== "function") {
2569
+ throw new TinycError(`tinyc: shim "${name}" must be a function`);
2570
+ }
2571
+ map.set(canonicalShimKey(name), fn);
2572
+ }
2573
+ function shimEntriesOf(layer) {
2574
+ if (!layer) return [];
2575
+ if (layer instanceof Map) return [...layer.entries()];
2576
+ return Object.entries(layer);
2577
+ }
2578
+ function registerGlobalShim(name, fn) {
2579
+ setShimEntry(globalShimRegistry, name, fn);
2580
+ }
2581
+ function registerGlobalShims(shims) {
2582
+ for (const [name, fn] of shimEntriesOf(shims)) {
2583
+ setShimEntry(globalShimRegistry, name, fn);
2584
+ }
2585
+ }
2586
+ function unregisterGlobalShim(name) {
2587
+ globalShimRegistry.delete(canonicalShimKey(name));
2588
+ }
2589
+ function createShimContext(holder, byteIO) {
2590
+ return {
2591
+ memory: () => holder.memory,
2592
+ u8: () => new Uint8Array(holder.memory.buffer),
2593
+ readCString(ptr, maxLength = 1 << 16) {
2594
+ const m = new Uint8Array(holder.memory.buffer);
2595
+ let end = ptr;
2596
+ while (end < m.length && end - ptr < maxLength && m[end] !== 0) end++;
2597
+ return textDecoder2.decode(m.subarray(ptr, end));
2598
+ },
2599
+ writeCString(ptr, str) {
2600
+ const bytes = textEncoder2.encode(str);
2601
+ const m = new Uint8Array(holder.memory.buffer);
2602
+ m.set(bytes, ptr);
2603
+ m[ptr + bytes.length] = 0;
2604
+ return bytes.length + 1;
2605
+ },
2606
+ readBytes(ptr, length) {
2607
+ return new Uint8Array(holder.memory.buffer).slice(ptr, ptr + length);
2608
+ },
2609
+ writeBytes(ptr, data) {
2610
+ new Uint8Array(holder.memory.buffer).set(data, ptr);
2611
+ },
2612
+ io: byteIO
2613
+ };
2614
+ }
2615
+ function buildWasmImports(options, holder) {
2616
+ const defaults = createDefaultByteIO();
2617
+ const byteIO = {
2618
+ out: options.io?.out ?? defaults.out,
2619
+ err: options.io?.err ?? defaults.err,
2620
+ in: options.io?.in
2621
+ };
2622
+ const imports = {};
2623
+ const put = (moduleName, name, value) => {
2624
+ (imports[moduleName] ??= {})[name] = value;
2625
+ };
2626
+ const wasi = createWasiShim(options, holder, byteIO);
2627
+ for (const [name, fn] of Object.entries(wasi)) {
2628
+ put("wasi_snapshot_preview1", name, fn);
2629
+ }
2630
+ const defaultShims = createDefaultShims({
2631
+ io: byteIO,
2632
+ holder,
2633
+ args: options.args,
2634
+ env: options.env,
2635
+ stdin: options.stdin,
2636
+ heapBase: options.heapBase
2637
+ });
2638
+ for (const [moduleName, fns] of Object.entries(defaultShims)) {
2639
+ for (const [name, fn] of Object.entries(fns)) put(moduleName, name, fn);
2640
+ }
2641
+ const ctx = createShimContext(holder, byteIO);
2642
+ for (const layer of [globalShimRegistry, options._instanceShims, options.shims]) {
2643
+ for (const [key, fn] of shimEntriesOf(layer)) {
2644
+ const { module: moduleName, name } = splitShimKey(key);
2645
+ put(moduleName, name, (...cArgs) => fn(ctx, ...cArgs));
2646
+ }
2647
+ }
2648
+ for (const [moduleName, fns] of Object.entries(options.imports ?? {})) {
2649
+ for (const [name, value] of Object.entries(fns)) put(moduleName, name, value);
2650
+ }
2651
+ return imports;
2652
+ }
2653
+ var TinycMissingImportError = class extends TinycError {
2654
+ constructor(missing) {
2655
+ const list = missing.map((m) => `${m.module}.${m.name}`);
2656
+ super(
2657
+ `tinyc: wasm module imports are not satisfied: ${list.join(", ")}. Provide them as shims: runWasmModule(bytes, { shims: { name: fn } }), instance.registerShim(name, fn) / instance.registerShims({ ... }), or registerGlobalShim(name, fn); use a "module.name" key for imports outside the default "env" module.`
2658
+ );
2659
+ this.name = "TinycMissingImportError";
2660
+ this.missing = list;
2661
+ }
2662
+ };
2663
+ function assertAllImportsSatisfied(module, imports) {
2664
+ const missing = [];
2665
+ for (const imp of WebAssembly.Module.imports(module)) {
2666
+ const provided = imports[imp.module]?.[imp.name];
2667
+ const ok = imp.kind === "function" ? typeof provided === "function" : provided !== void 0;
2668
+ if (!ok) missing.push(imp);
2669
+ }
2670
+ if (missing.length > 0) throw new TinycMissingImportError(missing);
2671
+ }
2672
+ function runWasmInstance(instance, options, holder) {
2673
+ holder.memory = instance.exports.memory ?? null;
2674
+ holder.instance = instance;
2675
+ const exports = instance.exports;
2676
+ try {
2677
+ if (options.entry !== void 0) {
2678
+ const fn = exports[options.entry];
2679
+ if (typeof fn !== "function") {
2680
+ throw new TinycError(`tinyc: wasm module does not export "${options.entry}"`);
2681
+ }
2682
+ return fn(...options.callArgs ?? options.args ?? []);
2683
+ }
2684
+ if (typeof exports._start === "function") {
2685
+ exports._start();
2686
+ return { exitCode: 0 };
2687
+ }
2688
+ throw new TinycError(
2689
+ "tinyc: wasm module exports no _start; pass options.entry to call an exported function"
2690
+ );
2691
+ } catch (err) {
2692
+ if (err instanceof WasiExit) return { exitCode: err.exitCode };
2693
+ if (err instanceof ShimExit) return { exitCode: err.exitCode };
2694
+ throw err;
2695
+ }
2696
+ }
2697
+ async function runWasmModule(bytes, options = {}) {
2698
+ const holder = { memory: null, instance: null };
2699
+ const imports = buildWasmImports(options, holder);
2700
+ const module = bytes instanceof WebAssembly.Module ? bytes : await WebAssembly.compile(bytes);
2701
+ assertAllImportsSatisfied(module, imports);
2702
+ const instance = await WebAssembly.instantiate(module, imports);
2703
+ return runWasmInstance(instance, options, holder);
2704
+ }
2705
+ function runWasmModuleSync(bytes, options = {}) {
2706
+ const holder = { memory: null, instance: null };
2707
+ const imports = buildWasmImports(options, holder);
2708
+ const module = bytes instanceof WebAssembly.Module ? bytes : new WebAssembly.Module(bytes);
2709
+ assertAllImportsSatisfied(module, imports);
2710
+ const instance = new WebAssembly.Instance(module, imports);
2711
+ return runWasmInstance(instance, options, holder);
2712
+ }
2713
+ var DEFAULT_RUN_OUTPUT = "/a.out";
2714
+ function textIOToByteIO(io) {
2715
+ const outDec = new TextDecoder();
2716
+ const errDec = new TextDecoder();
2717
+ return {
2718
+ out: (chunk) => io.out(outDec.decode(chunk, { stream: true })),
2719
+ err: (chunk) => io.err(errDec.decode(chunk, { stream: true }))
2720
+ };
2721
+ }
2722
+ function writeModuleData(instance, data, options = {}) {
2723
+ const memory = instance.exports.memory;
2724
+ if (!memory) throw new TinycError("tinyc: writeModuleData: module exports no memory");
2725
+ const chunk = typeof data === "string" ? textEncoder2.encode(data) : data;
2726
+ const malloc = instance.exports.malloc ?? instance.exports._malloc;
2727
+ let ptr;
2728
+ let free = null;
2729
+ if (typeof malloc === "function" && options.offset === void 0) {
2730
+ ptr = malloc(chunk.length);
2731
+ if (!ptr && chunk.length > 0) throw new TinycError("tinyc: writeModuleData: malloc returned null");
2732
+ const freeFn = instance.exports.free ?? instance.exports._free;
2733
+ if (typeof freeFn === "function") free = () => freeFn(ptr);
2734
+ } else if (options.offset !== void 0) {
2735
+ ptr = typeof options.offset === "function" ? options.offset(chunk.length) : options.offset;
2736
+ } else {
2737
+ throw new TinycError(
2738
+ "tinyc: writeModuleData needs an exported malloc or options.offset"
2739
+ );
2740
+ }
2741
+ new Uint8Array(memory.buffer).set(chunk, ptr);
2742
+ return { ptr, length: chunk.length, free };
2743
+ }
2744
+ function readModuleData(instance, ptr, length) {
2745
+ const memory = instance.exports.memory;
2746
+ if (!memory) throw new TinycError("tinyc: readModuleData: module exports no memory");
2747
+ return new Uint8Array(memory.buffer).slice(ptr, ptr + length);
2748
+ }
2749
+ function readModuleCString(instance, ptr, maxLength = 1 << 16) {
2750
+ const memory = instance.exports.memory;
2751
+ if (!memory) throw new TinycError("tinyc: readModuleCString: module exports no memory");
2752
+ const m = new Uint8Array(memory.buffer);
2753
+ let end = ptr;
2754
+ while (end < m.length && end - ptr < maxLength && m[end] !== 0) end++;
2755
+ return textDecoder2.decode(m.subarray(ptr, end));
2756
+ }
2757
+ var TCC_OUTPUT = {
2758
+ MEMORY: 1,
2759
+ EXE: 2,
2760
+ OBJ: 3,
2761
+ DLL: 4,
2762
+ PREPROCESS: 5
2763
+ };
2764
+ var TinycState = class {
2765
+ constructor(instance, handle) {
2766
+ this._instance = instance;
2767
+ this._bridge = instance._bridge;
2768
+ this.handle = handle;
2769
+ this._io = null;
2770
+ this._deleted = false;
2771
+ }
2772
+ _call(name, returnType, argTypes, args) {
2773
+ if (this._deleted) throw new TinycError("tinyc: state already deleted");
2774
+ return this._bridge.call(name, returnType, argTypes, [this.handle, ...args]);
2775
+ }
2776
+ _checkRc(name, rc) {
2777
+ if (typeof rc === "number" && rc < 0) {
2778
+ throw new TinycError(`tinyc: ${name} failed with code ${rc}`, rc);
2779
+ }
2780
+ return rc;
2781
+ }
2782
+ /** Per-state IO. The error channel takes effect immediately through
2783
+ * tcc_set_error_func; out/in are kept for JS-side helpers because
2784
+ * native stdout routing is per-module (see Tinyc.setIO). */
2785
+ setIO(partial) {
2786
+ this._io = normalizeIO(partial, this._io ?? this._instance.io);
2787
+ this._installErrorFunc();
2788
+ return this;
2789
+ }
2790
+ get io() {
2791
+ return this._io ?? this._instance.io;
2792
+ }
2793
+ _installErrorFunc() {
2794
+ if (!this._bridge.has("tcc_set_error_func")) return;
2795
+ const io = this.io;
2796
+ const errorFunc = (opaque, msg) => {
2797
+ io.err(String(msg) + "\n");
2798
+ };
2799
+ this._errorFunc = errorFunc;
2800
+ if (this._bridge.mode === "mock") {
2801
+ this._bridge.native.tcc_set_error_func(this.handle, null, errorFunc);
2802
+ } else if (this._bridge.mode === "emscripten") {
2803
+ const n = this._bridge.native;
2804
+ if (typeof n.addFunction === "function") {
2805
+ const ptr = n.addFunction((opaque, msgPtr) => {
2806
+ errorFunc(opaque, n.UTF8ToString(msgPtr));
2807
+ }, "vii");
2808
+ this._errorFuncPtr = ptr;
2809
+ n.ccall(
2810
+ "tcc_set_error_func",
2811
+ null,
2812
+ ["number", "number", "number"],
2813
+ [this.handle, 0, ptr]
2814
+ );
2815
+ }
2816
+ }
2817
+ }
2818
+ setLibPath(path) {
2819
+ this._call("tcc_set_lib_path", null, ["string"], [this._bridge.modulePath(path)]);
2820
+ return this;
2821
+ }
2822
+ setOptions(str) {
2823
+ return this._checkRc(
2824
+ "tcc_set_options",
2825
+ this._call("tcc_set_options", "number", ["string"], [str])
2826
+ );
2827
+ }
2828
+ addIncludePath(path) {
2829
+ return this._checkRc(
2830
+ "tcc_add_include_path",
2831
+ this._call("tcc_add_include_path", "number", ["string"], [this._bridge.modulePath(path)])
2832
+ );
2833
+ }
2834
+ addSysincludePath(path) {
2835
+ return this._checkRc(
2836
+ "tcc_add_sysinclude_path",
2837
+ this._call("tcc_add_sysinclude_path", "number", ["string"], [this._bridge.modulePath(path)])
2838
+ );
2839
+ }
2840
+ addLibraryPath(path) {
2841
+ return this._checkRc(
2842
+ "tcc_add_library_path",
2843
+ this._call("tcc_add_library_path", "number", ["string"], [this._bridge.modulePath(path)])
2844
+ );
2845
+ }
2846
+ addLibrary(name) {
2847
+ return this._checkRc(
2848
+ "tcc_add_library",
2849
+ this._call("tcc_add_library", "number", ["string"], [name])
2850
+ );
2851
+ }
2852
+ defineSymbol(sym, value = "1") {
2853
+ this._call("tcc_define_symbol", null, ["string", "string"], [sym, value]);
2854
+ return this;
2855
+ }
2856
+ undefineSymbol(sym) {
2857
+ this._call("tcc_undefine_symbol", null, ["string"], [sym]);
2858
+ return this;
2859
+ }
2860
+ setOutputType(type) {
2861
+ return this._checkRc(
2862
+ "tcc_set_output_type",
2863
+ this._call("tcc_set_output_type", "number", ["number"], [type])
2864
+ );
2865
+ }
2866
+ /** Add a file (source, object or archive) by virtual path. The file
2867
+ * must exist in the instance's virtual FS; it is synced to the
2868
+ * native filesystem first when an adapter is mounted. The path
2869
+ * handed to tcc_add_file is the file's location inside the
2870
+ * module FS (bridge.modulePath), which differs from the virtual
2871
+ * path when the OPFS backend is mounted. */
2872
+ addFile(path) {
2873
+ const p = normalizeVfsPath(path);
2874
+ if (this._bridge.mode !== "mock" && !this._instance.fs.hasFile(p)) {
2875
+ throw new TinycError(`tinyc: addFile: ${p} is not in the virtual FS`);
2876
+ }
2877
+ this._instance.fs.syncFile(p);
2878
+ return this._checkRc(
2879
+ "tcc_add_file",
2880
+ this._call("tcc_add_file", "number", ["string"], [this._bridge.modulePath(p)])
2881
+ );
2882
+ }
2883
+ compileString(source) {
2884
+ return this._checkRc(
2885
+ "tcc_compile_string",
2886
+ this._call("tcc_compile_string", "number", ["string"], [source])
2887
+ );
2888
+ }
2889
+ /** Compile a file from the virtual FS: its content is fed through
2890
+ * tcc_compile_string with a #line marker carrying the path, so no
2891
+ * native filesystem access is needed for plain sources. The
2892
+ * marker carries the virtual path exactly as given — it is what
2893
+ * diagnostics show the user — never the file's location inside
2894
+ * the module FS. */
2895
+ compileFile(path) {
2896
+ const p = normalizeVfsPath(path);
2897
+ const src = this._instance.fs.readTextFile(p);
2898
+ const marked = `#line 1 "${p}"
2899
+ ${src}`;
2900
+ return this._checkRc(
2901
+ "tcc_compile_string",
2902
+ this._call("tcc_compile_string", "number", ["string"], [marked])
2903
+ );
2904
+ }
2905
+ /** Write the compiled product to a virtual path. TCC writes it
2906
+ * inside the module FS (at bridge.modulePath(path)); exportFile
2907
+ * reads it back from there into the virtual FS. */
2908
+ outputFile(path) {
2909
+ return this._checkRc(
2910
+ "tcc_output_file",
2911
+ this._call(
2912
+ "tcc_output_file",
2913
+ "number",
2914
+ ["string"],
2915
+ [this._bridge.modulePath(normalizeVfsPath(path))]
2916
+ )
2917
+ );
2918
+ }
2919
+ relocate() {
2920
+ return this._checkRc(
2921
+ "tcc_relocate",
2922
+ this._call("tcc_relocate", "number", [], [])
2923
+ );
2924
+ }
2925
+ getSymbol(name) {
2926
+ return this._call("tcc_get_symbol", "number", ["string"], [name]);
2927
+ }
2928
+ /** Run the compiled program. Only on the wasm32 target, and not
2929
+ * through the native module: a WASM module cannot instantiate
2930
+ * another module from inside itself, and native TCC provides no
2931
+ * tcc_run for the wasm target. Instead the glue layer writes the
2932
+ * product to a file in the virtual FS (options.outputPath,
2933
+ * default DEFAULT_RUN_OUTPUT), reads its bytes back, and
2934
+ * instantiates it in the host with runWasmModuleSync — the WASI
2935
+ * argv is [outputPath, ...args]. Returns the program's exit code
2936
+ * for a _start module, or the named entry's return value when
2937
+ * options.entry is given. This switches the state to EXE output
2938
+ * type. On every other target the glue layer throws
2939
+ * TinycRunNotSupportedError before anything is passed to the
2940
+ * native module — those targets compile to files only.
2941
+ * options: { outputPath, entry, callArgs, env, imports, shims,
2942
+ * stdin, heapBase, io } — entry/callArgs/env/imports/shims/stdin/
2943
+ * heapBase forward to runWasmModuleSync, and the instance's
2944
+ * registered shims apply automatically; io is a text IO partial
2945
+ * (default: this state's IO) whose out/err receive the program's
2946
+ * fd_write output, decoded. */
2947
+ run(args = [], options = {}) {
2948
+ if (!isRunnableTarget(this._instance.target)) {
2949
+ throw new TinycRunNotSupportedError(this._instance.target);
2950
+ }
2951
+ const outputPath = options.outputPath ?? DEFAULT_RUN_OUTPUT;
2952
+ this.setOutputType(TCC_OUTPUT.EXE);
2953
+ this.outputFile(outputPath);
2954
+ const bytes = this._instance.exportFile(outputPath);
2955
+ const io = normalizeIO(options.io, this.io);
2956
+ const result = runWasmModuleSync(bytes, {
2957
+ args: [outputPath, ...args.map(String)],
2958
+ entry: options.entry,
2959
+ callArgs: options.callArgs,
2960
+ env: options.env,
2961
+ imports: options.imports,
2962
+ shims: options.shims,
2963
+ stdin: options.stdin,
2964
+ heapBase: options.heapBase,
2965
+ _instanceShims: this._instance._shims,
2966
+ io: textIOToByteIO(io)
2967
+ });
2968
+ flushIO(io);
2969
+ if (result && typeof result === "object" && "exitCode" in result) {
2970
+ return result.exitCode;
2971
+ }
2972
+ return result;
2973
+ }
2974
+ delete() {
2975
+ if (this._deleted) return;
2976
+ this._deleted = true;
2977
+ if (this._bridge.has("tcc_delete")) {
2978
+ this._bridge.call("tcc_delete", null, [], [this.handle]);
2979
+ }
2980
+ if (this._errorFuncPtr && typeof this._bridge.native.removeFunction === "function") {
2981
+ this._bridge.native.removeFunction(this._errorFuncPtr);
2982
+ this._errorFuncPtr = null;
2983
+ }
2984
+ this._instance._forgetState(this);
2985
+ }
2986
+ [Symbol.dispose]() {
2987
+ this.delete();
2988
+ }
2989
+ };
2990
+ var PATH_VALUE_OPTIONS = /* @__PURE__ */ new Set([
2991
+ "-o",
2992
+ "-I",
2993
+ "-L",
2994
+ "-B",
2995
+ "-MF",
2996
+ "-include",
2997
+ "-isystem",
2998
+ "-idirafter",
2999
+ "-iquote",
3000
+ "-iprefix",
3001
+ "-iwithprefix",
3002
+ "-iwithprefixbefore"
3003
+ ]);
3004
+ var PATH_JOINED_OPTIONS = [
3005
+ "-iwithprefixbefore",
3006
+ "-iwithprefix",
3007
+ "-idirafter",
3008
+ "-isystem",
3009
+ "-iprefix",
3010
+ "-iquote",
3011
+ "-include",
3012
+ "-I",
3013
+ "-L",
3014
+ "-B",
3015
+ "-MF",
3016
+ "-o"
3017
+ ];
3018
+ var Tinyc = class {
3019
+ constructor(bridge, { fs, io, target = DEFAULT_TARGET }) {
3020
+ this._bridge = bridge;
3021
+ this.fs = fs;
3022
+ this._io = io;
3023
+ this.target = target;
3024
+ this._states = /* @__PURE__ */ new Set();
3025
+ this._mainRunning = false;
3026
+ this._shims = /* @__PURE__ */ new Map();
3027
+ this._fsBackend = "memory";
3028
+ }
3029
+ get io() {
3030
+ return this._io;
3031
+ }
3032
+ /** True only for the wasm32 target: its compiled output is
3033
+ * WebAssembly, which the browser itself instantiates and runs.
3034
+ * All other targets compile to files only. */
3035
+ get canRun() {
3036
+ return isRunnableTarget(this.target);
3037
+ }
3038
+ get nativeMode() {
3039
+ return this._bridge.mode;
3040
+ }
3041
+ /** The backend mounted at "/opfs" in the native module's
3042
+ * filesystem: 'opfs' when loadTinyc mounted the WasmFS OPFS
3043
+ * backend there, 'memory' when it did not — the browser main
3044
+ * thread, a browser without OPFS, and every non-Emscripten
3045
+ * module land on 'memory'. Decided once per module by loadTinyc
3046
+ * (see tryMountOpfsBackend). The module filesystem's root is the
3047
+ * WasmFS memory backend in both cases; with 'opfs', the mirrored
3048
+ * compile working set and every path handed to the native module
3049
+ * are rooted at "/opfs" (bridge.moduleFsPrefix), so the working
3050
+ * set lives on disk. */
3051
+ get fsBackend() {
3052
+ return this._fsBackend;
3053
+ }
3054
+ /** Replace the instance IO. out/err are module-level on the native
3055
+ * side (Emscripten print/printErr were bound at load time to the
3056
+ * functions this object delegates to), so swapping the delegates
3057
+ * here reroutes native output for everything created afterwards
3058
+ * and for callMain. */
3059
+ setIO(partial) {
3060
+ this._io = normalizeIO(partial, this._io);
3061
+ return this;
3062
+ }
3063
+ /** Register a custom shim on this instance: a JS function served
3064
+ * as a wasm import for every later run made through this
3065
+ * instance (state.run, callMain "-run"). `name` is a bare
3066
+ * function name (module "env") or "module.name" for any other
3067
+ * import module — including wasi_snapshot_preview1 entries. The
3068
+ * function is called as fn(ctx, ...cArgs); see the runWasmModule
3069
+ * section for the ctx convention and the layer priority.
3070
+ * Registering the same name again replaces the previous shim. */
3071
+ registerShim(name, fn) {
3072
+ setShimEntry(this._shims, name, fn);
3073
+ return this;
3074
+ }
3075
+ /** Bulk form of registerShim: { name: fn, ... }. */
3076
+ registerShims(shims) {
3077
+ for (const [name, fn] of shimEntriesOf(shims)) {
3078
+ setShimEntry(this._shims, name, fn);
3079
+ }
3080
+ return this;
3081
+ }
3082
+ /** Remove an instance shim previously added with registerShim. */
3083
+ unregisterShim(name) {
3084
+ this._shims.delete(canonicalShimKey(name));
3085
+ return this;
3086
+ }
3087
+ // -- virtual FS shortcuts (full API on instance.fs) --
3088
+ addFile(path, content) {
3089
+ return this.fs.addFile(path, content);
3090
+ }
3091
+ addFileSync(path, content) {
3092
+ return this.fs.addFileSync(path, content);
3093
+ }
3094
+ addFileFromUrl(path, url, opts) {
3095
+ return this.fs.addFileFromUrl(path, url, opts);
3096
+ }
3097
+ registerIncludeDir(path) {
3098
+ return this.fs.registerIncludeDir(path);
3099
+ }
3100
+ hasFile(path) {
3101
+ return this.fs.hasFile(path);
3102
+ }
3103
+ readFile(path) {
3104
+ return this.fs.readFile(path);
3105
+ }
3106
+ readTextFile(path) {
3107
+ return this.fs.readTextFile(path);
3108
+ }
3109
+ readFileAsync(path) {
3110
+ return this.fs.readFileAsync(path);
3111
+ }
3112
+ readTextFileAsync(path) {
3113
+ return this.fs.readTextFileAsync(path);
3114
+ }
3115
+ removeFile(path) {
3116
+ return this.fs.removeFile(path);
3117
+ }
3118
+ clearFiles() {
3119
+ return this.fs.clear();
3120
+ }
3121
+ listFiles(prefix) {
3122
+ return this.fs.listFiles(prefix);
3123
+ }
3124
+ /** Resolve once the virtual FS's queued store writes and deletes
3125
+ * (from addFileSync / removeFile / clearFiles) have landed in the
3126
+ * persistent store. */
3127
+ whenIdle() {
3128
+ return this.fs.whenIdle();
3129
+ }
3130
+ /** Read a compiled product (object file, executable, library —
3131
+ * including a Windows PE for the x86_64-windows target) out of
3132
+ * the virtual FS as bytes. This is how compile-to-file results
3133
+ * leave the browser package, for every target. With an Emscripten
3134
+ * module, a file that only exists in the module FS is read from
3135
+ * there and mirrored into the virtual FS. A file restored from
3136
+ * the persistent store that is not in the content cache falls
3137
+ * back to the module FS copy; when there is none either, the
3138
+ * read fails naming exportFileAsync as the alternative. */
3139
+ exportFile(path) {
3140
+ const p = normalizeVfsPath(path);
3141
+ let cacheMiss = null;
3142
+ if (this.fs.hasFile(p)) {
3143
+ try {
3144
+ return this.fs.readFile(p);
3145
+ } catch (err) {
3146
+ cacheMiss = err;
3147
+ }
3148
+ }
3149
+ const FS = this._bridge.native?.FS;
3150
+ if (FS && typeof FS.readFile === "function") {
3151
+ try {
3152
+ const bytes = FS.readFile(this._bridge.modulePath(p));
3153
+ this.fs.addFileSync(p, bytes);
3154
+ return this.fs.readFile(p);
3155
+ } catch {
3156
+ }
3157
+ }
3158
+ if (cacheMiss) {
3159
+ throw new TinycError(
3160
+ `tinyc: ${p} is persisted in the virtual FS store but is not in the in-memory cache; read it with exportFileAsync() instead`
3161
+ );
3162
+ }
3163
+ throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
3164
+ }
3165
+ /** exportFile, reading the content from the persistent store
3166
+ * when it is not in the content cache. */
3167
+ async exportFileAsync(path) {
3168
+ const p = normalizeVfsPath(path);
3169
+ if (this.fs.hasFile(p)) return this.fs.readFileAsync(p);
3170
+ const FS = this._bridge.native?.FS;
3171
+ if (FS && typeof FS.readFile === "function") {
3172
+ try {
3173
+ const bytes = FS.readFile(this._bridge.modulePath(p));
3174
+ this.fs.addFileSync(p, bytes);
3175
+ return bytes;
3176
+ } catch {
3177
+ }
3178
+ }
3179
+ throw new TinycError(`tinyc: no such file in virtual FS: ${p}`);
3180
+ }
3181
+ /** exportFile as a Blob, e.g. for a download link or a File
3182
+ * handed to another tool. */
3183
+ exportBlob(path, type = "application/octet-stream") {
3184
+ return new Blob([this.exportFile(path)], { type });
3185
+ }
3186
+ /** Execute a wasm32 product already sitting in the virtual FS —
3187
+ * a file produced by an earlier compile-to-file callMain, or one
3188
+ * placed there with addFile — without recompiling. The bytes are
3189
+ * read with exportFile and instantiated with runWasmModuleSync,
3190
+ * so the shim stack is exactly the one "-run" uses: default libc
3191
+ * shims, package-global shims, this instance's registered shims,
3192
+ * then options.shims and options.imports. options: { args, entry,
3193
+ * callArgs, env, imports, shims, stdin, heapBase, io } — args
3194
+ * defaults to [path]; io is a text IO partial (default: this
3195
+ * instance's IO). Returns the exit code for a _start module, or
3196
+ * the named entry's return value. */
3197
+ runWasmFile(path, options = {}) {
3198
+ const p = normalizeVfsPath(path);
3199
+ const bytes = this.exportFile(p);
3200
+ const io = normalizeIO(options.io, this._io);
3201
+ const result = runWasmModuleSync(bytes, {
3202
+ args: options.args ?? [p],
3203
+ entry: options.entry,
3204
+ callArgs: options.callArgs,
3205
+ env: options.env,
3206
+ shims: options.shims,
3207
+ imports: options.imports,
3208
+ stdin: options.stdin,
3209
+ heapBase: options.heapBase,
3210
+ _instanceShims: this._shims,
3211
+ io: textIOToByteIO(io)
3212
+ });
3213
+ flushIO(io);
3214
+ if (typeof result === "number") return result;
3215
+ return result?.exitCode ?? 0;
3216
+ }
3217
+ /** Command-line mode: assemble argv exactly like a shell would
3218
+ * (argv[0] filled with the virtual binary path) and call the
3219
+ * exported main / tinyc_main. When the OPFS backend is mounted,
3220
+ * path arguments are relocated under "/opfs" first (see
3221
+ * _moduleArgv). Returns the exit code. main is not
3222
+ * reentrant; a nested call (e.g. from an IO callback) throws.
3223
+ * A "-run" argument on a non-wasm32 target is rejected by the
3224
+ * glue layer with TinycRunNotSupportedError before the native
3225
+ * module is called: that target can only compile to a file here.
3226
+ * On the wasm32 target, "-run" is handled by the glue layer
3227
+ * itself (see _callMainRun): the exported main never sees it.
3228
+ * For "-run", the optional second argument forwards run options
3229
+ * ({ shims, imports, stdin, heapBase }) to that execution. */
3230
+ callMain(args = [], options = {}) {
3231
+ if (!Array.isArray(args)) throw new TinycError("tinyc: callMain expects an array of arguments");
3232
+ if (args.some((a) => a === "-run")) {
3233
+ if (!this.canRun) throw new TinycRunNotSupportedError(this.target);
3234
+ return this._callMainRun(args.map(String), options);
3235
+ }
3236
+ if (this._mainRunning) {
3237
+ throw new TinycError("tinyc: exported main is not reentrant (callMain already running)");
3238
+ }
3239
+ const argv = this._moduleArgv(args.map(String));
3240
+ this._mainRunning = true;
3241
+ try {
3242
+ const rc = this._bridge.callMain(argv);
3243
+ flushIO(this._io);
3244
+ return rc;
3245
+ } finally {
3246
+ this._mainRunning = false;
3247
+ }
3248
+ }
3249
+ /** Assemble the argv handed to the exported main. argv[0] is the
3250
+ * virtual binary path. When the module FS has no prefix (memory
3251
+ * backend) the arguments pass through exactly as given. When the
3252
+ * OPFS backend is mounted (bridge.moduleFsPrefix set), every
3253
+ * argument that names a file inside the module FS — argv[0], the
3254
+ * values of path options in separate and joined form, --sysroot=
3255
+ * values, and bare input-file arguments — is relocated under the
3256
+ * prefix (bridge.modulePath), where the mirrored files actually
3257
+ * live; all other arguments pass through untouched. */
3258
+ _moduleArgv(args) {
3259
+ const bridge = this._bridge;
3260
+ if (!bridge.moduleFsPrefix) return [VIRTUAL_BIN_PATH, ...args];
3261
+ const out = [bridge.modulePath(VIRTUAL_BIN_PATH)];
3262
+ let pathValueNext = false;
3263
+ for (const arg of args) {
3264
+ if (pathValueNext) {
3265
+ pathValueNext = false;
3266
+ out.push(arg.startsWith("-") ? arg : bridge.modulePath(arg));
3267
+ continue;
3268
+ }
3269
+ if (PATH_VALUE_OPTIONS.has(arg)) {
3270
+ pathValueNext = true;
3271
+ out.push(arg);
3272
+ continue;
3273
+ }
3274
+ if (arg.startsWith("--sysroot=")) {
3275
+ out.push("--sysroot=" + bridge.modulePath(arg.slice("--sysroot=".length)));
3276
+ continue;
3277
+ }
3278
+ const joined = PATH_JOINED_OPTIONS.find(
3279
+ (opt) => arg.length > opt.length && arg.startsWith(opt)
3280
+ );
3281
+ if (joined) {
3282
+ out.push(joined + bridge.modulePath(arg.slice(joined.length)));
3283
+ continue;
3284
+ }
3285
+ if (!arg.startsWith("-") && arg.length > 0) {
3286
+ out.push(bridge.modulePath(arg));
3287
+ continue;
3288
+ }
3289
+ out.push(arg);
3290
+ }
3291
+ return out;
3292
+ }
3293
+ /** wasm32 "-run": the arguments before "-run" are compiler
3294
+ * options, the one after it is the source file, and the rest are
3295
+ * the program's arguments. The source is compiled to
3296
+ * DEFAULT_RUN_OUTPUT through the exported main (without "-run"),
3297
+ * then the product bytes are instantiated and executed in the
3298
+ * host by runWasmModuleSync, with the program arguments fed to
3299
+ * _start through the WASI args shim. The instance's registered
3300
+ * shims apply; options.shims / options.imports / options.stdin /
3301
+ * options.heapBase forward per-run. Returns the compiler's exit
3302
+ * code when compilation fails, otherwise the program's. */
3303
+ _callMainRun(args, options = {}) {
3304
+ const runIdx = args.indexOf("-run");
3305
+ const compileArgs = args.slice(0, runIdx);
3306
+ const [src, ...progArgs] = args.slice(runIdx + 1);
3307
+ if (!src) {
3308
+ throw new TinycError('tinyc: callMain: "-run" must be followed by a source file');
3309
+ }
3310
+ const rc = this.callMain([...compileArgs, "-o", DEFAULT_RUN_OUTPUT, src]);
3311
+ if (rc !== 0) return rc;
3312
+ const bytes = this.exportFile(DEFAULT_RUN_OUTPUT);
3313
+ const result = runWasmModuleSync(bytes, {
3314
+ args: [src, ...progArgs],
3315
+ shims: options.shims,
3316
+ imports: options.imports,
3317
+ stdin: options.stdin,
3318
+ heapBase: options.heapBase,
3319
+ _instanceShims: this._shims,
3320
+ io: textIOToByteIO(this._io)
3321
+ });
3322
+ flushIO(this._io);
3323
+ if (typeof result === "number") return result;
3324
+ return result?.exitCode ?? 0;
3325
+ }
3326
+ /** Fine-grained mode: create a TCCState, pre-loaded with the
3327
+ * virtual FS include directories (registration order, ahead of
3328
+ * the sysroot) and the instance error routing. */
3329
+ createState() {
3330
+ this._bridge.requireExport("tcc_new");
3331
+ const handle = this._bridge.call("tcc_new", "number", [], []);
3332
+ if (!handle && this._bridge.mode !== "mock") {
3333
+ throw new TinycError("tinyc: tcc_new returned null");
3334
+ }
3335
+ const state = new TinycState(this, handle ?? {});
3336
+ this._states.add(state);
3337
+ state._installErrorFunc();
3338
+ if (this._bridge.has("tcc_add_include_path")) {
3339
+ for (const dir of this.fs.getIncludeDirs()) state.addIncludePath(dir);
3340
+ }
3341
+ return state;
3342
+ }
3343
+ _forgetState(state) {
3344
+ this._states.delete(state);
3345
+ }
3346
+ /** Convenience: compile one source string in a throwaway state. */
3347
+ compileString(source, { outputType = TCC_OUTPUT.MEMORY } = {}) {
3348
+ const state = this.createState();
3349
+ try {
3350
+ state.setOutputType(outputType);
3351
+ return state.compileString(source);
3352
+ } finally {
3353
+ state.delete();
3354
+ }
3355
+ }
3356
+ };
3357
+ var targetModuleCache = /* @__PURE__ */ new Map();
3358
+ function getLoadedTargets() {
3359
+ return [...targetModuleCache.keys()];
3360
+ }
3361
+ function clearTargetModuleCache() {
3362
+ targetModuleCache.clear();
3363
+ }
3364
+ async function createModuleFromGlue(glueUrl, wasmUrl, io) {
3365
+ let factory;
3366
+ try {
3367
+ factory = (await import(
3368
+ /* @vite-ignore */
3369
+ glueUrl
3370
+ )).default;
3371
+ } catch {
3372
+ throw new TinycError(
3373
+ `tinyc: the Emscripten glue ${glueUrl} could not be loaded. Build it with build.sh, or pass module / createModule / wasmExports / loadModule.`
3374
+ );
3375
+ }
3376
+ if (typeof factory !== "function") {
3377
+ throw new TinycError(`tinyc: Emscripten glue ${glueUrl} does not default-export a module factory`);
3378
+ }
3379
+ return factory({
3380
+ print: (text) => io.out(text + "\n"),
3381
+ printErr: (text) => io.err(text + "\n"),
3382
+ locateFile: (path, prefix) => wasmUrl && path.endsWith(".wasm") ? wasmUrl : prefix + path
3383
+ });
3384
+ }
3385
+ async function loadTargetModule(target, options, io) {
3386
+ const cached = targetModuleCache.get(target);
3387
+ if (cached) return cached;
3388
+ const files = targetModuleFiles(target);
3389
+ const promise = (async () => {
3390
+ if (typeof options.loadModule === "function") {
3391
+ return options.loadModule(target, {
3392
+ ...files,
3393
+ wasmUrl: options.wasmUrl ?? assetUrl(files.wasmFile, options.baseUrl),
3394
+ glueUrl: options.glueUrl ?? assetUrl(files.glueFile, options.baseUrl)
3395
+ });
3396
+ }
3397
+ const glueUrl = options.glueUrl ?? assetUrl(files.glueFile, options.baseUrl);
3398
+ const wasmUrl = options.wasmUrl ?? assetUrl(files.wasmFile, options.baseUrl);
3399
+ return createModuleFromGlue(glueUrl, wasmUrl, io);
3400
+ })();
3401
+ targetModuleCache.set(target, promise);
3402
+ promise.catch(() => {
3403
+ if (targetModuleCache.get(target) === promise) targetModuleCache.delete(target);
3404
+ });
3405
+ return promise;
3406
+ }
3407
+ async function resolveNative(options, io, target) {
3408
+ if (options.module) return options.module;
3409
+ if (options.wasmExports) return options.wasmExports;
3410
+ if (typeof options.createModule === "function") {
3411
+ return await options.createModule({
3412
+ print: (text) => io.out(text + "\n"),
3413
+ printErr: (text) => io.err(text + "\n"),
3414
+ locateFile: (path, prefix) => options.wasmUrl && path.endsWith(".wasm") ? options.wasmUrl : prefix + path
3415
+ });
3416
+ }
3417
+ return loadTargetModule(target, options, io);
3418
+ }
3419
+ async function loadSysrootManifest(target = DEFAULT_TARGET) {
3420
+ assertKnownTarget(target);
3421
+ return SYSROOT_MANIFESTS[target];
3422
+ }
3423
+ async function loadSysroot(instance, sysrootOpt) {
3424
+ if (!sysrootOpt) return;
3425
+ let manifest;
3426
+ let baseUrl = "./sysroot/";
3427
+ let fetchImpl;
3428
+ let includeBinaries = false;
3429
+ if (sysrootOpt === true) {
3430
+ manifest = await loadSysrootManifest(instance.target);
3431
+ } else if (Array.isArray(sysrootOpt.includeFiles)) {
3432
+ manifest = sysrootOpt;
3433
+ } else {
3434
+ manifest = sysrootOpt.manifest ?? await loadSysrootManifest(instance.target);
3435
+ baseUrl = sysrootOpt.baseUrl ?? baseUrl;
3436
+ fetchImpl = sysrootOpt.fetchImpl;
3437
+ includeBinaries = Boolean(sysrootOpt.includeBinaries);
3438
+ }
3439
+ const baseHref = /^[a-z][a-z0-9+.-]*:/i.test(baseUrl) ? baseUrl : assetUrl(baseUrl);
3440
+ const entries = [...manifest.includeFiles ?? [], ...manifest.libFiles ?? []];
3441
+ for (const entry of entries) {
3442
+ if (entry.binary && !includeBinaries) continue;
3443
+ if (instance.fs.hasFile(entry.path)) continue;
3444
+ const url = entry.url ?? new URL(entry.source, baseHref).href;
3445
+ await instance.fs.addFileFromUrl(entry.path, url, { fetchImpl });
3446
+ }
3447
+ if (manifest.includeDir) instance.fs.registerIncludeDir(manifest.includeDir);
3448
+ }
3449
+ var OPFS_MOUNT_POINT = "/opfs";
3450
+ var opfsBackendByModule = /* @__PURE__ */ new WeakMap();
3451
+ async function tryMountOpfsBackend(native, bridge) {
3452
+ const canMemo = native !== null && (typeof native === "object" || typeof native === "function");
3453
+ if (canMemo) {
3454
+ const memo = opfsBackendByModule.get(native);
3455
+ if (memo) return memo;
3456
+ }
3457
+ let result = "memory";
3458
+ try {
3459
+ if (bridge.mode === "emscripten" && typeof native.ccall === "function" && typeof native._wasmfs_create_opfs_backend === "function" && typeof native._wasmfs_create_directory === "function" && typeof WorkerGlobalScope !== "undefined" && typeof self !== "undefined" && self instanceof WorkerGlobalScope) {
3460
+ const backend = await native.ccall(
3461
+ "wasmfs_create_opfs_backend",
3462
+ "number",
3463
+ [],
3464
+ [],
3465
+ { async: true }
3466
+ );
3467
+ if (backend) {
3468
+ const rc = await native.ccall(
3469
+ "wasmfs_create_directory",
3470
+ "number",
3471
+ ["string", "number", "number"],
3472
+ [OPFS_MOUNT_POINT, 511, backend],
3473
+ { async: true }
3474
+ );
3475
+ if (rc === 0) result = "opfs";
3476
+ }
3477
+ }
3478
+ } catch {
3479
+ result = "memory";
3480
+ }
3481
+ if (canMemo) opfsBackendByModule.set(native, result);
3482
+ return result;
3483
+ }
3484
+ async function loadTinyc(options = {}) {
3485
+ const target = options.target ?? DEFAULT_TARGET;
3486
+ assertKnownTarget(target);
3487
+ const io = normalizeIO(options.io);
3488
+ const store = await openFsStore(target, options);
3489
+ const fs = new VirtualFS(store);
3490
+ const native = await resolveNative(options, io, target);
3491
+ const bridge = new NativeBridge(native, io);
3492
+ const instance = new Tinyc(bridge, { fs, io, target });
3493
+ instance._fsBackend = await tryMountOpfsBackend(native, bridge);
3494
+ bridge.moduleFsPrefix = instance._fsBackend === "opfs" ? OPFS_MOUNT_POINT : "";
3495
+ if (native && native.FS) await fs.mountTo(native.FS, bridge.moduleFsPrefix);
3496
+ await loadSysroot(instance, options.sysroot);
3497
+ return instance;
3498
+ }
3499
+ var index_default = loadTinyc;
3500
+ return __toCommonJS(web_entry_exports);
3501
+ })();