forked from bellard/quickjs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhako.c
More file actions
2195 lines (1813 loc) · 62.3 KB
/
Copy pathhako.c
File metadata and controls
2195 lines (1813 loc) · 62.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "hako.h"
#include "cutils.h"
#include "quickjs.h"
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include "version.h"
#include "wasi_version.h"
#include "ts_strip/ts_strip.h"
#define PKG "quickjs-wasi: "
#if defined(__WASI__) || defined(__wasi__)
#define WASM_EXPORT(func) __attribute__((export_name(#func))) func
#define HAKO_IMPORT(name) \
__attribute__((import_module("hako"), import_name(name)))
#else
#define WASM_EXPORT(func) func
#define HAKO_IMPORT(name)
#endif
typedef enum {
HAKO_MODULE_SOURCE_STRING,
HAKO_MODULE_SOURCE_PRECOMPILED,
HAKO_MODULE_SOURCE_ERROR
} HakoModuleSourceType;
typedef struct HakoModuleSource {
uint32_t type;
union {
char *source_code;
JSModuleDef *module_def;
} data;
} HakoModuleSource;
HAKO_IMPORT("call_function")
JSValue *host_call_function(JSContext *ctx, JSValueConst *this_ptr, int32_t argc,
JSValueConst *argv, uint32_t magic_func_id);
HAKO_IMPORT("interrupt_handler")
extern int32_t host_interrupt_handler(JSRuntime *rt, JSContext *ctx, void *opaque);
HAKO_IMPORT("load_module")
extern HakoModuleSource *host_load_module(JSRuntime *rt, JSContext *ctx,
const char *module_name, void *opaque,
JSValueConst *attributes);
HAKO_IMPORT("normalize_module")
extern char *host_normalize_module(JSRuntime *rt, JSContext *ctx,
const char *module_base_name,
const char *module_name, void *opaque);
HAKO_IMPORT("module_init")
extern int32_t host_module_init(JSContext *ctx, JSModuleDef *m);
HAKO_IMPORT("class_constructor")
extern JSValue *host_class_constructor(JSContext *ctx, JSValueConst *new_target,
int32_t argc, JSValueConst *argv,
JSClassID class_id);
HAKO_IMPORT("class_finalizer")
extern void host_class_finalizer(JSRuntime *rt, void *opaque,
JSClassID class_id);
HAKO_IMPORT("class_gc_mark")
extern void host_class_gc_mark(JSRuntime *rt, void *opaque, JSClassID class_id,
JS_MarkFunc *mark_func);
HAKO_IMPORT("promise_rejection_tracker")
extern void host_promise_rejection_tracker(JSContext *ctx,
JSValueConst *promise,
JSValueConst *reason,
JS_BOOL is_handled, void *opaque);
static HakoBuildInfo build_info = {.version = HAKO_VERSION,
.flags = 0x00000001,
.build_date = __DATE__ " " __TIME__,
.quickjs_version = QUICKJS_VERSION,
.wasi_sdk_version = WASI_VERSION,
.wasi_libc = WASI_WASI_LIBC,
.llvm = WASI_LLVM,
.config = WASI_CONFIG};
JSValueConst HAKO_Undefined = JS_UNDEFINED;
JSValueConst HAKO_Null = JS_NULL;
JSValueConst HAKO_False = JS_FALSE;
JSValueConst HAKO_True = JS_TRUE;
static inline JS_BOOL is_static_constant(const JSValue *ptr) {
return ptr == (JSValue *)&HAKO_Undefined || ptr == (JSValue *)&HAKO_Null ||
ptr == (JSValue *)&HAKO_False || ptr == (JSValue *)&HAKO_True;
}
static void* ts_strip_malloc_wrapper(void* user_data, size_t size) {
JSRuntime* rt = (JSRuntime*)user_data;
if (!rt) return NULL;
return js_malloc_rt(rt, size);
}
static void* ts_strip_realloc_wrapper(void* user_data, void* ptr, size_t size) {
JSRuntime* rt = (JSRuntime*)user_data;
if (!rt) return NULL;
return js_realloc_rt(rt, ptr, size);
}
static void ts_strip_free_wrapper(void* user_data, void* ptr) {
JSRuntime* rt = (JSRuntime*)user_data;
if (!rt || !ptr) return;
js_free_rt(rt, ptr);
}
static int32_t ends_with_ts(const char *str) {
size_t len;
if (!str) return 0;
len = strlen(str);
if (len < 3) return 0;
// Check for .ts or .mts
if (len >= 3 && strcmp(str + len - 3, ".ts") == 0) return 1;
if (len >= 4 && strcmp(str + len - 4, ".mts") == 0) return 1;
if (len >= 4 && strcmp(str + len - 4, ".tsx") == 0) return 1;
if (len >= 5 && strcmp(str + len - 5, ".mtsx") == 0) return 1;
return 0;
}
static int32_t ends_with_module_extension(const char *str) {
size_t len;
if (!str) return 0;
len = strlen(str);
// Check for .mjs (JavaScript modules)
if (len >= 4 && strcmp(str + len - 4, ".mjs") == 0) return 1;
// Check for .mts (TypeScript modules)
if (len >= 4 && strcmp(str + len - 4, ".mts") == 0) return 1;
// Check for .mtsx (TypeScript JSX modules)
if (len >= 5 && strcmp(str + len - 5, ".mtsx") == 0) return 1;
return 0;
}
int32_t hako_module_set_import_meta(JSContext *ctx, JSValueConst func_val,
JS_BOOL use_realpath, JS_BOOL is_main) {
JSModuleDef *m;
char buf[1024 + 16];
JSValue meta_obj = JS_UNDEFINED;
JSAtom module_name_atom;
const char *module_name = NULL;
int32_t ret = -1;
m = JS_VALUE_GET_PTR(func_val);
module_name_atom = JS_GetModuleName(ctx, m);
module_name = JS_AtomToCString(ctx, module_name_atom);
JS_FreeAtom(ctx, module_name_atom);
if (!module_name)
goto done;
if (!strchr(module_name, ':')) {
strcpy(buf, "file://");
#if !defined(_WIN32) && !defined(__wasi__)
if (use_realpath) {
char *res = realpath(module_name, buf + strlen(buf));
if (!res) {
JS_ThrowTypeError(ctx, "realpath failure");
goto done;
}
} else
#endif
{
pstrcat(buf, sizeof(buf), module_name);
}
} else {
pstrcpy(buf, sizeof(buf), module_name);
}
meta_obj = JS_GetImportMeta(ctx, m);
if (JS_IsException(meta_obj))
goto done;
JS_DefinePropertyValueStr(ctx, meta_obj, "url", JS_NewString(ctx, buf),
JS_PROP_C_W_E);
JS_DefinePropertyValueStr(ctx, meta_obj, "main", JS_NewBool(ctx, is_main),
JS_PROP_C_W_E);
ret = 0;
done:
if (module_name)
JS_FreeCString(ctx, module_name);
if (!JS_IsUndefined(meta_obj))
JS_FreeValue(ctx, meta_obj);
return ret;
}
static JSModuleDef *hako_compile_module(JSContext *ctx, const char *module_name,
const char *module_body) {
int32_t eval_flags;
JSValue func_val = JS_UNDEFINED;
JSModuleDef *module = NULL;
eval_flags =
JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY | JS_EVAL_FLAG_STRICT;
func_val =
JS_Eval(ctx, module_body, strlen(module_body), module_name, eval_flags);
if (JS_IsException(func_val))
goto done;
if (!JS_VALUE_IS_MODULE(func_val)) {
JS_ThrowTypeError(ctx, "Module '%s' code compiled to non-module object",
module_name);
goto done;
}
if (hako_module_set_import_meta(ctx, func_val, TRUE, FALSE) < 0)
goto done;
module = JS_VALUE_GET_PTR(func_val);
done:
if (!JS_IsUndefined(func_val))
JS_FreeValue(ctx, func_val);
return module;
}
static JSModuleDef *hako_load_module(JSContext *ctx, const char *module_name,
void *user_data, JSValueConst attributes) {
JSRuntime *rt;
HakoModuleSource *module_source = NULL;
JSModuleDef *result = NULL;
char *source_code = NULL;
rt = JS_GetRuntime(ctx);
module_source =
host_load_module(rt, ctx, module_name, user_data, &attributes);
if (module_source == NULL) {
JS_ThrowTypeError(
ctx,
"Module not found: '%s'. Please check that the module name is "
"correct and the module is available in your environment.",
module_name);
goto done;
}
switch (module_source->type) {
case HAKO_MODULE_SOURCE_STRING:
source_code = (char *)module_source->data.source_code;
if (source_code != NULL) {
result = hako_compile_module(ctx, module_name, source_code);
} else {
JS_ThrowTypeError(ctx, "Invalid source code for module '%s'",
module_name);
}
break;
case HAKO_MODULE_SOURCE_PRECOMPILED:
result = (JSModuleDef *)module_source->data.module_def;
if (result == NULL) {
JS_ThrowTypeError(ctx, "Invalid precompiled module for '%s'",
module_name);
}
break;
case HAKO_MODULE_SOURCE_ERROR:
default:
JS_ThrowTypeError(
ctx,
"Module not found: '%s'. Please check that the module name is "
"correct and the module is available in your environment.",
module_name);
break;
}
done:
if (source_code)
js_free(ctx, source_code);
if (module_source)
js_free(ctx, module_source);
return result;
}
static char *hako_normalize_module(JSContext *ctx, const char *module_base_name,
const char *module_name, void *user_data) {
JSRuntime *rt;
char *normalized_module_name = NULL;
char *js_module_name = NULL;
rt = JS_GetRuntime(ctx);
normalized_module_name =
host_normalize_module(rt, ctx, module_base_name, module_name, user_data);
if (!normalized_module_name)
goto done;
js_module_name = js_strdup(ctx, normalized_module_name);
done:
if (normalized_module_name)
js_free(ctx, normalized_module_name);
return js_module_name;
}
static JSValue *jsvalue_to_heap(JSContext *ctx, JSValueConst value) {
JSValue *result = js_malloc(ctx, sizeof(JSValue));
if (result) {
*result = value;
}
return result;
}
JSValue *HAKO_Throw(JSContext *ctx, JSValueConst *error) {
JSValue copy = JS_DupValue(ctx, *error);
return jsvalue_to_heap(ctx, JS_Throw(ctx, copy));
}
JSValue *HAKO_ThrowError(JSContext *ctx, HAKO_ErrorType error_type,
const char *message) {
JSValue result;
switch (error_type) {
case HAKO_ERROR_RANGE:
result = JS_ThrowRangeError(ctx, "%s", message);
break;
case HAKO_ERROR_REFERENCE:
result = JS_ThrowReferenceError(ctx, "%s", message);
break;
case HAKO_ERROR_SYNTAX:
result = JS_ThrowSyntaxError(ctx, "%s", message);
break;
case HAKO_ERROR_TYPE:
result = JS_ThrowTypeError(ctx, "%s", message);
break;
case HAKO_ERROR_INTERNAL:
result = JS_ThrowInternalError(ctx, "%s", message);
break;
case HAKO_ERROR_OUT_OF_MEMORY:
result = JS_ThrowOutOfMemory(ctx);
break;
default:
result = JS_ThrowInternalError(ctx, "Unknown error type (%d): %s",
error_type, message);
break;
}
return jsvalue_to_heap(ctx, result);
}
JSValue *HAKO_NewError(JSContext *ctx) {
return jsvalue_to_heap(ctx, JS_NewError(ctx));
}
void HAKO_RuntimeSetMemoryLimit(JSRuntime *rt, size_t limit) {
JS_SetMemoryLimit(rt, limit);
}
JSValue *HAKO_RuntimeComputeMemoryUsage(JSRuntime *rt, JSContext *ctx) {
JSMemoryUsage s;
JSValue result;
JS_ComputeMemoryUsage(rt, &s);
result = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, result, "malloc_limit",
JS_NewInt64(ctx, s.malloc_limit));
JS_SetPropertyStr(ctx, result, "malloc_size",
JS_NewInt64(ctx, s.malloc_size));
JS_SetPropertyStr(ctx, result, "malloc_count",
JS_NewInt64(ctx, s.malloc_count));
JS_SetPropertyStr(ctx, result, "memory_used_size",
JS_NewInt64(ctx, s.memory_used_size));
JS_SetPropertyStr(ctx, result, "memory_used_count",
JS_NewInt64(ctx, s.memory_used_count));
JS_SetPropertyStr(ctx, result, "atom_count", JS_NewInt64(ctx, s.atom_count));
JS_SetPropertyStr(ctx, result, "atom_size", JS_NewInt64(ctx, s.atom_size));
JS_SetPropertyStr(ctx, result, "str_count", JS_NewInt64(ctx, s.str_count));
JS_SetPropertyStr(ctx, result, "str_size", JS_NewInt64(ctx, s.str_size));
JS_SetPropertyStr(ctx, result, "obj_count", JS_NewInt64(ctx, s.obj_count));
JS_SetPropertyStr(ctx, result, "obj_size", JS_NewInt64(ctx, s.obj_size));
JS_SetPropertyStr(ctx, result, "prop_count", JS_NewInt64(ctx, s.prop_count));
JS_SetPropertyStr(ctx, result, "prop_size", JS_NewInt64(ctx, s.prop_size));
JS_SetPropertyStr(ctx, result, "shape_count",
JS_NewInt64(ctx, s.shape_count));
JS_SetPropertyStr(ctx, result, "shape_size", JS_NewInt64(ctx, s.shape_size));
JS_SetPropertyStr(ctx, result, "js_func_count",
JS_NewInt64(ctx, s.js_func_count));
JS_SetPropertyStr(ctx, result, "js_func_size",
JS_NewInt64(ctx, s.js_func_size));
JS_SetPropertyStr(ctx, result, "js_func_code_size",
JS_NewInt64(ctx, s.js_func_code_size));
JS_SetPropertyStr(ctx, result, "js_func_pc2line_count",
JS_NewInt64(ctx, s.js_func_pc2line_count));
JS_SetPropertyStr(ctx, result, "js_func_pc2line_size",
JS_NewInt64(ctx, s.js_func_pc2line_size));
JS_SetPropertyStr(ctx, result, "c_func_count",
JS_NewInt64(ctx, s.c_func_count));
JS_SetPropertyStr(ctx, result, "array_count",
JS_NewInt64(ctx, s.array_count));
JS_SetPropertyStr(ctx, result, "fast_array_count",
JS_NewInt64(ctx, s.fast_array_count));
JS_SetPropertyStr(ctx, result, "fast_array_elements",
JS_NewInt64(ctx, s.fast_array_elements));
JS_SetPropertyStr(ctx, result, "binary_object_count",
JS_NewInt64(ctx, s.binary_object_count));
JS_SetPropertyStr(ctx, result, "binary_object_size",
JS_NewInt64(ctx, s.binary_object_size));
return jsvalue_to_heap(ctx, result);
}
char *HAKO_RuntimeDumpMemoryUsage(JSRuntime *rt) {
char *result = NULL;
FILE *memfile = NULL;
JSMemoryUsage s;
result = js_malloc_rt(rt, sizeof(char) * 1024);
if (!result)
goto done;
memfile = fmemopen(result, 1024, "w");
if (!memfile) {
js_free_rt(rt, result);
result = NULL;
goto done;
}
JS_ComputeMemoryUsage(rt, &s);
JS_DumpMemoryUsage(memfile, &s, rt);
done:
if (memfile)
fclose(memfile);
return result;
}
void HAKO_RuntimeJSThrow(JSContext *ctx, const char *message) {
JS_ThrowReferenceError(ctx, "%s", message);
}
void HAKO_SetMaxStackSize(JSRuntime *rt, size_t stack_size) {
JS_SetMaxStackSize(rt, stack_size);
}
HAKO_Status HAKO_InitTypeStripper(JSRuntime* rt) {
if (!rt) {
return HAKO_STATUS_ERROR_INVALID_ARGS;
}
if (JS_GetRuntimeOpaque(rt) != NULL) {
return HAKO_STATUS_SUCCESS;
}
ts_strip_allocator_t allocator = {
.malloc_func = ts_strip_malloc_wrapper,
.realloc_func = ts_strip_realloc_wrapper,
.free_func = ts_strip_free_wrapper,
.user_data = rt
};
ts_strip_ctx_t* ctx = ts_strip_ctx_new_with_allocator(&allocator);
if (ctx == NULL) {
return HAKO_STATUS_ERROR_OUT_OF_MEMORY;
}
JS_SetRuntimeOpaque(rt, ctx);
return HAKO_STATUS_SUCCESS;
}
void HAKO_CleanupTypeStripper(JSRuntime* rt) {
if (!rt) {
return;
}
ts_strip_ctx_t* ctx = JS_GetRuntimeOpaque(rt);
if (ctx != NULL) {
ts_strip_ctx_delete(ctx);
JS_SetRuntimeOpaque(rt, NULL);
}
}
HAKO_Status HAKO_StripTypes(JSRuntime* rt, const char* typescript_source,
char** javascript_out,
size_t* javascript_len) {
ts_strip_result_t result;
ts_strip_ctx_t* ctx = JS_GetRuntimeOpaque(rt);
if (ctx == NULL) {
return HAKO_STATUS_ERROR_INVALID_ARGS;
}
result = ts_strip_with_ctx(ctx, typescript_source,
javascript_out, javascript_len);
switch (result) {
case TS_STRIP_SUCCESS:
return HAKO_STATUS_SUCCESS;
case TS_STRIP_ERROR_INVALID_INPUT:
return HAKO_STATUS_ERROR_INVALID_ARGS;
case TS_STRIP_ERROR_PARSE_FAILED:
return HAKO_STATUS_ERROR_PARSE_FAILED;
case TS_STRIP_ERROR_UNSUPPORTED:
return HAKO_STATUS_ERROR_UNSUPPORTED;
case TS_STRIP_ERROR_OUT_OF_MEMORY:
return HAKO_STATUS_ERROR_OUT_OF_MEMORY;
default:
return HAKO_STATUS_ERROR_PARSE_FAILED;
}
}
JSValueConst *HAKO_GetUndefined(void) { return &HAKO_Undefined; }
JSValueConst *HAKO_GetNull(void) { return &HAKO_Null; }
JSValueConst *HAKO_GetFalse(void) { return &HAKO_False; }
JSValueConst *HAKO_GetTrue(void) { return &HAKO_True; }
JSRuntime *HAKO_NewRuntime(void) {
JSRuntime *rt = JS_NewRuntime();
if (rt == NULL)
return NULL;
JS_SetRuntimeInfo(rt, "HakoJS");
return rt;
}
void HAKO_FreeRuntime(JSRuntime *rt) { JS_FreeRuntime(rt); }
void HAKO_SetStripInfo(JSRuntime *rt, int32_t flags) { JS_SetStripInfo(rt, flags); }
int32_t HAKO_GetStripInfo(JSRuntime *rt) { return JS_GetStripInfo(rt); }
JSContext *HAKO_NewContext(JSRuntime *rt, HAKO_Intrinsic intrinsics) {
JSContext *ctx = NULL;
if (intrinsics == 0) {
ctx = JS_NewContext(rt);
return ctx;
}
ctx = JS_NewContextRaw(rt);
if (ctx == NULL)
return NULL;
if (intrinsics & HAKO_Intrinsic_BaseObjects) {
JS_AddIntrinsicBaseObjects(ctx);
}
if (intrinsics & HAKO_Intrinsic_Date) {
JS_AddIntrinsicDate(ctx);
}
if (intrinsics & HAKO_Intrinsic_Eval) {
JS_AddIntrinsicEval(ctx);
}
if (intrinsics & HAKO_Intrinsic_StringNormalize) {
JS_AddIntrinsicStringNormalize(ctx);
}
if (intrinsics & HAKO_Intrinsic_RegExp) {
JS_AddIntrinsicRegExp(ctx);
}
if (intrinsics & HAKO_Intrinsic_RegExpCompiler) {
JS_AddIntrinsicRegExpCompiler(ctx);
}
if (intrinsics & HAKO_Intrinsic_JSON) {
JS_AddIntrinsicJSON(ctx);
}
if (intrinsics & HAKO_Intrinsic_Proxy) {
JS_AddIntrinsicProxy(ctx);
}
if (intrinsics & HAKO_Intrinsic_MapSet) {
JS_AddIntrinsicMapSet(ctx);
}
if (intrinsics & HAKO_Intrinsic_TypedArrays) {
JS_AddIntrinsicTypedArrays(ctx);
}
if (intrinsics & HAKO_Intrinsic_Promise) {
JS_AddIntrinsicPromise(ctx);
}
if (intrinsics & HAKO_Intrinsic_Performance) {
JS_AddIntrinsicPerformance(ctx);
}
if (intrinsics & HAKO_Intrinsic_Crypto) {
JS_AddIntrinsicCrypto(ctx);
}
return ctx;
}
void HAKO_SetContextData(JSContext *ctx, void *data) {
JS_SetContextOpaque(ctx, data);
}
void *HAKO_GetContextData(JSContext *ctx) { return JS_GetContextOpaque(ctx); }
void HAKO_FreeContext(JSContext *ctx) { JS_FreeContext(ctx); }
JSValue *HAKO_DupValuePointer(JSContext *ctx, JSValueConst *val) {
return jsvalue_to_heap(ctx, JS_DupValue(ctx, *val));
}
void HAKO_FreeValuePointer(JSContext *ctx, JSValue *value) {
if (is_static_constant(value)) {
fprintf(stderr, "Attempted to free static constant\n");
__builtin_unreachable();
}
JS_FreeValue(ctx, *value);
js_free(ctx, value);
}
void HAKO_FreeValuePointerRuntime(JSRuntime *rt, JSValue *value) {
if (is_static_constant(value)) {
fprintf(stderr, "Attempted to free static constant\n");
__builtin_unreachable();
}
JS_FreeValueRT(rt, *value);
js_free_rt(rt, value);
}
void *HAKO_Malloc(JSContext *ctx, size_t size) {
void *ptr = NULL;
if (size == 0)
return NULL;
ptr = js_malloc(ctx, size);
if (ptr == NULL) {
JS_ThrowOutOfMemory(ctx);
return NULL;
}
return ptr;
}
void *HAKO_RuntimeMalloc(JSRuntime *rt, size_t size) {
void *ptr = NULL;
if (size == 0)
return NULL;
ptr = js_malloc_rt(rt, size);
if (ptr == NULL) {
__builtin_trap();
return NULL;
}
return ptr;
}
void HAKO_Free(JSContext *ctx, void *ptr) { js_free(ctx, ptr); }
void HAKO_RuntimeFree(JSRuntime *rt, void *ptr) { js_free_rt(rt, ptr); }
void HAKO_FreeCString(JSContext *ctx, const char *str) {
JS_FreeCString(ctx, str);
}
JSValue *HAKO_NewObject(JSContext *ctx) {
return jsvalue_to_heap(ctx, JS_NewObject(ctx));
}
JSValue *HAKO_NewObjectProto(JSContext *ctx, JSValueConst *proto) {
return jsvalue_to_heap(ctx, JS_NewObjectProto(ctx, *proto));
}
JSValue *HAKO_NewArray(JSContext *ctx) {
return jsvalue_to_heap(ctx, JS_NewArray(ctx));
}
void hako_free_buffer(JSRuntime *rt, void *unused_opaque, void *ptr) {
js_free_rt(rt, ptr);
}
JSValue *HAKO_NewArrayBuffer(JSContext *ctx, void *buffer, size_t length) {
if (length == 0) {
return jsvalue_to_heap(ctx, JS_NewArrayBuffer(ctx, NULL, 0, NULL, NULL, 0));
}
return jsvalue_to_heap(ctx, JS_NewArrayBuffer(ctx, (uint8_t *)buffer, length,
hako_free_buffer, NULL, 0));
}
JSValue *HAKO_NewFloat64(JSContext *ctx, double num) {
return jsvalue_to_heap(ctx, JS_NewFloat64(ctx, num));
}
double HAKO_GetFloat64(JSContext *ctx, JSValueConst *value) {
double result = NAN;
JS_ToFloat64(ctx, &result, *value);
return result;
}
JSValue *HAKO_NewString(JSContext *ctx, const char *string) {
return jsvalue_to_heap(ctx, JS_NewString(ctx, string));
}
const char *HAKO_ToCString(JSContext *ctx, JSValueConst *value) {
return JS_ToCString(ctx, *value);
}
void *HAKO_CopyArrayBuffer(JSContext *ctx, JSValueConst *data,
size_t *out_length) {
size_t length = 0;
uint8_t *buffer = NULL;
uint8_t *result = NULL;
buffer = JS_GetArrayBuffer(ctx, &length, *data);
if (!buffer) {
if (out_length)
*out_length = 0;
goto done;
}
result = js_malloc(ctx, length);
if (!result) {
if (out_length)
*out_length = 0;
goto done;
}
memcpy(result, buffer, length);
if (out_length)
*out_length = length;
done:
return result;
}
JSValue hako_get_symbol_key(JSContext *ctx, JSValueConst *value) {
JSValue global = JS_UNDEFINED;
JSValue Symbol = JS_UNDEFINED;
JSValue Symbol_keyFor = JS_UNDEFINED;
JSValue key = JS_UNDEFINED;
global = JS_GetGlobalObject(ctx);
Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
Symbol_keyFor = JS_GetPropertyStr(ctx, Symbol, "keyFor");
key = JS_Call(ctx, Symbol_keyFor, Symbol, 1, value);
JS_FreeValue(ctx, Symbol_keyFor);
JS_FreeValue(ctx, Symbol);
JS_FreeValue(ctx, global);
return key;
}
JSValue hako_resolve_func_data(JSContext *ctx, JSValueConst this_val, int32_t argc,
JSValueConst *argv, int32_t magic,
JSValue *func_data) {
return JS_DupValue(ctx, func_data[0]);
}
JSValue *HAKO_Eval(JSContext *ctx, const char *js_code, size_t js_code_length,
const char *filename, JS_BOOL detect_module,
int32_t eval_flags) {
JSModuleDef *module = NULL;
JSValue func_obj = JS_UNDEFINED;
JSValue eval_result = JS_UNDEFINED;
JSValue module_namespace = JS_UNDEFINED;
JSValue then_resolve_module_namespace = JS_UNDEFINED;
JSValue new_promise = JS_UNDEFINED;
JSAtom then_atom = JS_ATOM_NULL;
JSValueConst then_args[1];
int32_t is_module;
JSValue *result = NULL;
char *stripped_js = NULL;
size_t stripped_len = 0;
const char *code_to_eval = js_code;
size_t code_len = js_code_length;
int32_t should_strip = 0;
// Check if we should strip TypeScript types
should_strip =
(eval_flags & JS_EVAL_FLAG_STRIP_TYPES) || ends_with_ts(filename);
if (should_strip) {
HAKO_Status strip_status =
HAKO_StripTypes(JS_GetRuntime(ctx), js_code, &stripped_js, &stripped_len);
if (strip_status == HAKO_STATUS_SUCCESS) {
code_to_eval = stripped_js;
code_len = stripped_len;
} else if (strip_status == HAKO_STATUS_ERROR_UNSUPPORTED) {
// Unsupported syntax - use stripped output anyway (it's returned even on
// error)
if (stripped_js != NULL) {
code_to_eval = stripped_js;
code_len = stripped_len;
}
} else {
// Fatal stripping error - return exception
if (stripped_js != NULL) {
js_free_rt(JS_GetRuntime(ctx), stripped_js);
}
return jsvalue_to_heap(
ctx,
JS_ThrowSyntaxError(ctx, "Failed to strip TypeScript types: %s",
strip_status == HAKO_STATUS_ERROR_PARSE_FAILED
? "parse failed"
: strip_status == HAKO_STATUS_ERROR_OUT_OF_MEMORY
? "out of memory"
: "invalid input"));
}
}
if (detect_module && (eval_flags & JS_EVAL_TYPE_MODULE) == 0) {
// Check for module extensions (.mjs, .mts, .mtsx) or ES module syntax
if (ends_with_module_extension(filename) ||
JS_DetectModule(code_to_eval, code_len)) {
eval_flags |= JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_STRICT;
}
}
is_module = (eval_flags & JS_EVAL_TYPE_MODULE) != 0;
if (is_module && (eval_flags & JS_EVAL_FLAG_COMPILE_ONLY) == 0) {
func_obj = JS_Eval(ctx, code_to_eval, code_len, filename,
eval_flags | JS_EVAL_FLAG_COMPILE_ONLY);
if (JS_IsException(func_obj)) {
result = jsvalue_to_heap(ctx, func_obj);
func_obj = JS_UNDEFINED;
goto done;
}
if (!JS_VALUE_IS_MODULE(func_obj)) {
JS_FreeValue(ctx, func_obj);
result = jsvalue_to_heap(
ctx,
JS_ThrowTypeError(ctx, "Module code compiled to non-module object"));
func_obj = JS_UNDEFINED;
goto done;
}
module = JS_VALUE_GET_PTR(func_obj);
if (module == NULL) {
JS_FreeValue(ctx, func_obj);
result = jsvalue_to_heap(
ctx, JS_ThrowTypeError(ctx, "Module compiled to null"));
func_obj = JS_UNDEFINED;
goto done;
}
eval_result = JS_EvalFunction(ctx, func_obj);
func_obj = JS_UNDEFINED;
} else {
eval_result = JS_Eval(ctx, code_to_eval, code_len, filename, eval_flags);
}
if (JS_IsException(eval_result)) {
result = jsvalue_to_heap(ctx, eval_result);
eval_result = JS_UNDEFINED;
goto done;
}
if (!JS_IsPromise(eval_result)) {
if (is_module) {
module_namespace = JS_GetModuleNamespace(ctx, module);
result = jsvalue_to_heap(ctx, module_namespace);
module_namespace = JS_UNDEFINED;
} else {
result = jsvalue_to_heap(ctx, eval_result);
eval_result = JS_UNDEFINED;
}
goto done;
}
// eval_result is a promise - return it regardless of state (pending,
// fulfilled, or rejected)
if (is_module) {
// For modules, always return a promise that resolves to the namespace
module_namespace = JS_GetModuleNamespace(ctx, module);
if (JS_IsException(module_namespace)) {
result = jsvalue_to_heap(ctx, module_namespace);
module_namespace = JS_UNDEFINED;
goto done;
}
then_resolve_module_namespace = JS_NewCFunctionData(
ctx, &hako_resolve_func_data, 0, 0, 1, &module_namespace);
JS_FreeValue(ctx, module_namespace);
module_namespace = JS_UNDEFINED;
if (JS_IsException(then_resolve_module_namespace)) {
result = jsvalue_to_heap(ctx, then_resolve_module_namespace);
then_resolve_module_namespace = JS_UNDEFINED;
goto done;
}
then_atom = JS_NewAtom(ctx, "then");
then_args[0] = then_resolve_module_namespace;
new_promise = JS_Invoke(ctx, eval_result, then_atom, 1, then_args);
result = jsvalue_to_heap(ctx, new_promise);
new_promise = JS_UNDEFINED;
} else {
// For non-modules, return the promise as-is (including rejected promises)
result = jsvalue_to_heap(ctx, eval_result);
eval_result = JS_UNDEFINED;
}
done:
if (stripped_js != NULL) {
js_free_rt(JS_GetRuntime(ctx), stripped_js);
}
if (!JS_IsUndefined(func_obj))
JS_FreeValue(ctx, func_obj);
if (!JS_IsUndefined(eval_result))
JS_FreeValue(ctx, eval_result);
if (!JS_IsUndefined(module_namespace))
JS_FreeValue(ctx, module_namespace);
if (!JS_IsUndefined(then_resolve_module_namespace))
JS_FreeValue(ctx, then_resolve_module_namespace);
if (!JS_IsUndefined(new_promise))
JS_FreeValue(ctx, new_promise);
if (then_atom != JS_ATOM_NULL)
JS_FreeAtom(ctx, then_atom);
return result;
}
JSValue *HAKO_NewSymbol(JSContext *ctx, const char *description, int32_t isGlobal) {
JSValue global = JS_UNDEFINED;
JSValue Symbol = JS_UNDEFINED;
JSValue descriptionValue = JS_UNDEFINED;
JSValue Symbol_for = JS_UNDEFINED;
JSValue symbol = JS_UNDEFINED;
JSValue *result = NULL;
global = JS_GetGlobalObject(ctx);
Symbol = JS_GetPropertyStr(ctx, global, "Symbol");
descriptionValue = JS_NewString(ctx, description);
if (isGlobal != 0) {
Symbol_for = JS_GetPropertyStr(ctx, Symbol, "for");
symbol = JS_Call(ctx, Symbol_for, Symbol, 1, &descriptionValue);
result = jsvalue_to_heap(ctx, symbol);
symbol = JS_UNDEFINED;
goto done;
}
symbol = JS_Call(ctx, Symbol, JS_UNDEFINED, 1, &descriptionValue);
result = jsvalue_to_heap(ctx, symbol);
symbol = JS_UNDEFINED;
done:
if (!JS_IsUndefined(Symbol_for))
JS_FreeValue(ctx, Symbol_for);
if (!JS_IsUndefined(descriptionValue))
JS_FreeValue(ctx, descriptionValue);
if (!JS_IsUndefined(Symbol))
JS_FreeValue(ctx, Symbol);
if (!JS_IsUndefined(global))
JS_FreeValue(ctx, global);
if (!JS_IsUndefined(symbol))
JS_FreeValue(ctx, symbol);
return result;
}
const char *HAKO_GetSymbolDescriptionOrKey(JSContext *ctx,
JSValueConst *value) {
JSValue key = JS_UNDEFINED;
JSValue description = JS_UNDEFINED;
const char *result = NULL;
key = hako_get_symbol_key(ctx, value);
if (!JS_IsUndefined(key)) {
result = JS_ToCString(ctx, key);
goto done;
}
description = JS_GetPropertyStr(ctx, *value, "description");
result = JS_ToCString(ctx, description);
done:
if (!JS_IsUndefined(key))
JS_FreeValue(ctx, key);
if (!JS_IsUndefined(description))
JS_FreeValue(ctx, description);
return result;
}
JS_BOOL HAKO_IsGlobalSymbol(JSContext *ctx, JSValueConst *value) {
JSValue key = JS_UNDEFINED;
int32_t undefined;
key = hako_get_symbol_key(ctx, value);
undefined = JS_IsUndefined(key);
JS_FreeValue(ctx, key);
return undefined ? 0 : 1;
}
JS_BOOL HAKO_IsJobPending(JSRuntime *rt) { return JS_IsJobPending(rt); }
int32_t HAKO_ExecutePendingJob(JSRuntime *rt, int32_t maxJobsToExecute,
JSContext **lastJobContext) {
JSContext *pctx = NULL;
int32_t status = 1;
int32_t executed = 0;
while (executed != maxJobsToExecute && status == 1) {
status = JS_ExecutePendingJob(rt, &pctx);
if (status == -1) {
*lastJobContext = pctx;