Repository navigation
Expand file tree
/
Copy pathiridium.cpp
More file actions
3962 lines (3490 loc) · 126 KB
/
Copy pathiridium.cpp
File metadata and controls
3962 lines (3490 loc) · 126 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 "quickjs-libc.h"
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
extern "C" {
#include "./cutils.h"
#include "./quickjs-opcode.h"
#include "./quickjs_expose.h"
#include "iridium.h"
}
#include "json.hpp"
#include <fstream>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <ctype.h>
#include <iostream>
#include <iterator>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#define LINKING_DUMP_FUNCTION
using json = nlohmann::json;
enum IridiumDataType { NUMBER, STRING, BOOLEAN, NULLPTR };
struct IridiumFlag {
std::string name;
enum IridiumDataType datatype; // BOOLEAN, NUMBER, STRING, NULLPTR
// Storing values directly (no unions for std::string)
bool boolean_val;
double number_val;
std::string string_val;
};
struct IridiumSEXP {
std::string tag;
int numArgs;
IridiumSEXP **args;
int numFlags;
IridiumFlag **flags;
};
class ScopedTimer {
public:
ScopedTimer(const std::string &name)
: name_(name), start_(std::chrono::high_resolution_clock::now()) {}
~ScopedTimer() {
auto end = std::chrono::high_resolution_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start_);
std::cout << name_ << " took " << duration.count() << " ms\n";
}
private:
std::string name_;
std::chrono::high_resolution_clock::time_point start_;
};
using namespace std;
#define check_dump_flag(ctx, flag) \
((JS_GetDumpFlags(ctx->rt) & (flag + 0)) == (flag + 0))
#define OP_DEFINE_METHOD_METHOD 0
#define OP_DEFINE_METHOD_GETTER 1
#define OP_DEFINE_METHOD_SETTER 2
#define OP_DEFINE_METHOD_ENUMERABLE 4
#define JS_STACK_SIZE_MAX 65534
typedef enum OPCodeFormat {
#define FMT(f) OP_FMT_##f,
#define DEF(id, size, n_pop, n_push, f)
#include "quickjs-opcode.h"
#undef DEF
#undef FMT
} OPCodeFormat;
typedef enum {
/* XXX: add more variable kinds here instead of using bit fields */
JS_VAR_NORMAL,
JS_VAR_FUNCTION_DECL, /* lexical var with function declaration */
JS_VAR_NEW_FUNCTION_DECL, /* lexical var with async/generator
function declaration */
JS_VAR_CATCH,
JS_VAR_FUNCTION_NAME, /* function expression name */
JS_VAR_PRIVATE_FIELD,
JS_VAR_PRIVATE_METHOD,
JS_VAR_PRIVATE_GETTER,
JS_VAR_PRIVATE_SETTER, /* must come after JS_VAR_PRIVATE_GETTER */
JS_VAR_PRIVATE_GETTER_SETTER, /* must come after JS_VAR_PRIVATE_SETTER */
} JSVarKindEnum;
typedef enum OPCodeEnum {
#define FMT(f)
#define DEF(id, size, n_pop, n_push, f) OP_##id,
#define def(id, size, n_pop, n_push, f)
#include "quickjs-opcode.h"
#undef def
#undef DEF
#undef FMT
OP_COUNT, /* excluding temporary opcodes */
/* temporary opcodes : overlap with the short opcodes */
OP_TEMP_START = OP_nop + 1,
OP___dummy = OP_TEMP_START - 1,
#define FMT(f)
#define DEF(id, size, n_pop, n_push, f)
#define def(id, size, n_pop, n_push, f) OP_##id,
#include "quickjs-opcode.h"
#undef def
#undef DEF
#undef FMT
OP_TEMP_END,
} OPCodeEnum;
#define ENABLE_DUMPS
typedef struct JSOpCode {
#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
const char *name;
#endif
uint8_t size; /* in bytes */
/* the opcodes remove n_pop items from the top of the stack, then
pushes n_push items */
uint8_t n_pop;
uint8_t n_push;
uint8_t fmt;
} JSOpCode;
static const JSOpCode opcode_info[OP_COUNT + (OP_TEMP_END - OP_TEMP_START)] = {
#define FMT(f)
#ifdef ENABLE_DUMPS // JS_DUMP_BYTECODE_*
#define DEF(id, size, n_pop, n_push, f) {#id, size, n_pop, n_push, OP_FMT_##f},
#else
#define DEF(id, size, n_pop, n_push, f) {size, n_pop, n_push, OP_FMT_##f},
#endif
#include "quickjs-opcode.h"
#undef DEF
#undef FMT
};
#define short_opcode_info(op) \
opcode_info[(op) >= OP_TEMP_START ? (op) + (OP_TEMP_END - OP_TEMP_START) \
: (op)]
//
// Reading and loading source JSON data
//
char *read_file(const char *filename) {
FILE *file = fopen(filename, "rb");
if (file == NULL) {
perror("File opening failed");
return NULL;
}
fseek(file, 0, SEEK_END);
long length = ftell(file);
rewind(file);
char *data = (char *)malloc(length + 1);
if (data == NULL) {
fclose(file);
return NULL;
}
fread(data, 1, length, file);
data[length] = '\0'; // Null-terminate
fclose(file);
return data;
}
// For convenience
json load_json(const std::string &path) {
std::ifstream file(path);
if (!file.is_open()) {
// Handle file open error (throw exception or return empty JSON object)
throw std::runtime_error("Could not open file: " + path);
}
// The library streams the file directly into the JSON object!
return json::parse(file);
}
IridiumSEXP *parseIridiumSEXP(const json &node);
void populateArgs(IridiumSEXP *res, const json &args) {
res->numArgs = args.size();
// Switch to `new` instead of `malloc` for C++ object initialization
res->args = new IridiumSEXP *[res->numArgs];
int idx = 0;
// Range-based for loop completely eliminates linked-list traversal!
for (const auto &arg : args) {
res->args[idx++] = parseIridiumSEXP(arg);
}
}
void populateFlags(IridiumSEXP *res, const json &flags) {
res->numFlags = flags.size();
res->flags = new IridiumFlag *[res->numFlags];
int idx = 0;
for (const auto &flag : flags) {
if (!flag.is_array() || flag.size() != 2) {
fprintf(stderr, "Expected flag array size to be 2\n");
exit(1);
}
IridiumFlag *currFlag = new IridiumFlag;
res->flags[idx++] = currFlag;
// Array access by index [0] and [1]
currFlag->name = flag[0].get<std::string>();
const auto &flagVal = flag[1];
if (flagVal.is_boolean()) {
currFlag->boolean_val = flagVal.get<bool>();
currFlag->datatype = BOOLEAN;
} else if (flagVal.is_number()) {
currFlag->number_val = flagVal.get<double>();
currFlag->datatype = NUMBER;
} else if (flagVal.is_string()) {
currFlag->string_val =
flagVal.get<std::string>(); // Null-safe extraction!
currFlag->datatype = STRING;
} else if (flagVal.is_null()) {
currFlag->datatype = NULLPTR;
} else {
fprintf(stderr, "Unsupported flag datatype\n");
exit(1);
}
}
}
IridiumSEXP *parseNode(const std::string &tag, const json &args,
const json &flags) {
IridiumSEXP *res = new IridiumSEXP;
res->tag = tag;
populateArgs(res, args);
populateFlags(res, flags);
return res;
}
IridiumSEXP *parseIridiumSEXP(const json &node) {
if (!node.is_array()) {
fprintf(stderr, "Iridium parsing failed, expected an array\n");
exit(1);
}
// Ensure the array has the expected 3 elements: [tag, args, flags]
if (node.size() < 3) {
fprintf(stderr, "Iridium parsing failed, expected at least 3 elements\n");
exit(1);
}
if (!node[0].is_string()) {
fprintf(stderr, "Iridium parsing failed, expected tag to be a string\n");
exit(1);
}
std::string tag = node[0].get<std::string>();
const auto &args = node[1];
const auto &flags = node[2];
// Pre-Assertions
if (!args.is_array()) {
fprintf(stderr, "Expected args to be an array\n");
exit(1);
}
if (!flags.is_array()) {
fprintf(stderr, "Expected flags to be an array\n");
exit(1);
}
// parse node
return parseNode(tag, args, flags);
}
//
// Printing Iridium S-Expression Tree
//
void printSpace(FILE *target, int space) {
while (space-- > 0)
fprintf(target, " ");
}
void dumpFlag(FILE *target, IridiumFlag *flag) {
if (flag->datatype == NUMBER) {
fprintf(target, "%s => %f", flag->name.data(), flag->number_val);
} else if (flag->datatype == STRING) {
fprintf(target, "%s => %s", flag->name.data(), flag->string_val.data());
} else if (flag->datatype == BOOLEAN) {
fprintf(target, "%s => %s", flag->name.data(),
flag->boolean_val ? "TRUE" : "FALSE");
} else {
fprintf(target, "%s", flag->name.data());
}
}
void dumpIridiumSEXP(FILE *target, IridiumSEXP *node, int space) {
printSpace(target, space);
fprintf(target, "%s(", node->tag.data());
IridiumFlag **flags = node->flags;
for (int i = 0; i < node->numFlags; ++i) {
IridiumFlag *currFlag = flags[i];
dumpFlag(target, currFlag);
if (i + 1 != node->numFlags)
fprintf(target, ", ");
}
fprintf(target, ")\n");
IridiumSEXP **args = node->args;
for (int i = 0; i < node->numArgs; ++i) {
IridiumSEXP *currArg = args[i];
dumpIridiumSEXP(target, currArg, space + 2);
}
}
//
// Generate Bytecode
//
typedef struct BCLList {
uint8_t bc;
bool lambdaPoolReference;
bool hasPoolData;
JSValue poolData;
bool presolvedTarget;
union {
int8_t one;
int16_t two;
int32_t four;
} data;
uint8_t valueSize;
bool hasFlags;
uint8_t flags;
// Extend the data structure to accomodate arguments dynamically
} BCInstruction;
enum GOTOCONTEXT {
MULTI,
put_loc0 = 1000,
put_loc1 = 1001,
put_loc2 = 1002,
put_loc3 = 1003,
put_arg0 = 2000,
put_arg1 = 2001,
put_arg2 = 2002,
put_arg3 = 2003,
put_var_ref0 = 3000,
put_var_ref1 = 3001,
put_var_ref2 = 3002,
put_var_ref3 = 3003
};
struct GOTOINFO {
GOTOCONTEXT kind;
std::set<double> putTargets;
GOTOINFO() : kind(GOTOCONTEXT::MULTI) {}
GOTOINFO(vector<BCInstruction> &instructions) {
auto &currInst = instructions.back();
kind = getInstContext(currInst);
if (kind != GOTOCONTEXT::MULTI)
putTargets.insert(instructions.size() - 1);
}
void reduce(double idx) {
if (kind == GOTOCONTEXT::MULTI)
return;
// Collect elements > idx
std::vector<double> toUpdate;
for (double val : putTargets) {
if (val > idx)
toUpdate.push_back(val);
}
// Remove old ones and insert reduced ones
for (double val : toUpdate) {
putTargets.erase(val);
putTargets.insert(val - 1);
}
}
static GOTOCONTEXT getInstContext(BCInstruction currInst) {
if (currInst.bc == OP_put_loc0)
return GOTOCONTEXT::put_loc0;
if (currInst.bc == OP_put_loc1)
return GOTOCONTEXT::put_loc1;
if (currInst.bc == OP_put_loc2)
return GOTOCONTEXT::put_loc2;
if (currInst.bc == OP_put_loc3)
return GOTOCONTEXT::put_loc3;
if (currInst.bc == OP_put_arg0)
return GOTOCONTEXT::put_arg0;
if (currInst.bc == OP_put_arg1)
return GOTOCONTEXT::put_arg1;
if (currInst.bc == OP_put_arg2)
return GOTOCONTEXT::put_arg2;
if (currInst.bc == OP_put_arg3)
return GOTOCONTEXT::put_arg3;
if (currInst.bc == OP_put_var_ref0)
return GOTOCONTEXT::put_var_ref0;
if (currInst.bc == OP_put_var_ref1)
return GOTOCONTEXT::put_var_ref1;
if (currInst.bc == OP_put_var_ref2)
return GOTOCONTEXT::put_var_ref2;
if (currInst.bc == OP_put_var_ref3)
return GOTOCONTEXT::put_var_ref3;
return GOTOCONTEXT::MULTI;
}
void merge(vector<BCInstruction> &instructions) {
if (kind == GOTOCONTEXT::MULTI)
return;
auto &currInst = instructions.back();
if (getInstContext(currInst) != kind)
kind = GOTOCONTEXT::MULTI;
if (kind != GOTOCONTEXT::MULTI)
putTargets.insert(instructions.size() - 1);
}
};
std::unordered_map<double, GOTOINFO> *gotoContextMap = NULL;
std::unordered_map<uint32_t, size_t> *xyzz;
// ============== Push OP ============== //
void pushOP(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 0;
inst.data.four = 0;
inst.hasFlags = false;
inst.flags = 0;
instructions.push_back(inst);
return;
}
void pushOPFlags(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, uint8_t flags) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 0;
inst.data.four = 0;
inst.hasFlags = true;
inst.flags = flags;
instructions.push_back(inst);
return;
}
void pushOP8(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, uint8_t data) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 1;
inst.data.one = data;
inst.hasFlags = false;
inst.flags = 0;
inst.hasFlags = false;
inst.flags = 0;
instructions.push_back(inst);
return;
}
void pushOP16(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, uint16_t data) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 2;
inst.data.two = data;
inst.hasFlags = false;
inst.flags = 0;
instructions.push_back(inst);
return;
}
void pushOP32(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, uint32_t data) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 4;
inst.data.four = data;
inst.hasFlags = false;
inst.flags = 0;
instructions.push_back(inst);
return;
}
void pushOP32Flags(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, uint32_t data, uint8_t flags) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = false;
inst.poolData = JS_UNINITIALIZED;
inst.presolvedTarget = false;
inst.valueSize = 4;
inst.data.four = data;
inst.hasFlags = true;
inst.flags = flags;
instructions.push_back(inst);
return;
}
void pushOPConst(JSContext *ctx, vector<BCInstruction> &instructions,
OPCodeEnum opcode, JSValue cData) {
BCInstruction inst;
inst.bc = opcode;
inst.lambdaPoolReference = false;
inst.hasPoolData = true;
inst.poolData = cData;
inst.presolvedTarget = false;
inst.valueSize = 4;
inst.data.four = 0;
inst.hasFlags = false;
inst.flags = 0;
instructions.push_back(inst);
return;
}
// ============== Push OP ============== //
// ============== Flag Related ============== //
bool isTag(IridiumSEXP *node, const std::string &tag) {
return node->tag == tag;
}
void ensureTag(IridiumSEXP *node, const std::string &tag) {
if (!isTag(node, tag)) {
// std::cerr handles std::string natively, unlike fprintf
std::cerr << "Expected tag " << tag << ", found " << node->tag << "\n";
exit(1);
}
}
bool hasFlag(IridiumSEXP *node, const std::string &flagToCheck) {
for (int i = 0; i < node->numFlags; i++) {
IridiumFlag *flag = node->flags[i];
if (flag->name == flagToCheck) // No more strcmp!
return true;
}
return false;
}
void ensureFlag(IridiumSEXP *node, const std::string &flag) {
if (!hasFlag(node, flag)) {
std::cerr << "Expected flag " << flag << " not found\n";
exit(1);
}
}
IridiumFlag *getFlag(IridiumSEXP *node, const std::string &flagToCheck) {
for (int i = 0; i < node->numFlags; i++) {
IridiumFlag *flag = node->flags[i];
if (flag->name == flagToCheck)
return flag;
}
std::cerr << "Failed to get flag, " << flagToCheck << " not found\n";
throw std::runtime_error("Failed to get flag, " + flagToCheck +
" not found\n");
exit(1);
}
int getFlagNumber(IridiumSEXP *binding, const std::string &flagName) {
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == NUMBER) {
return static_cast<int>(flag->number_val); // Cast double to int
}
std::cerr << "TODO: failed to get NUMBER\n";
exit(1);
}
double getFlagDouble(IridiumSEXP *binding, const std::string &flagName) {
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == NUMBER) {
return flag->number_val;
}
std::cerr << "TODO: failed to get NUMBER(double)\n";
exit(1);
}
// ---------------------------------------------------------
// THE OLD API (Legacy)
// Returns char* so your existing code compiles without changes.
// ---------------------------------------------------------
char *getFlagString(IridiumSEXP *binding, const char *flagName) {
// C++ implicitly converts the const char* to a std::string for getFlag
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == STRING) {
// In C++17 and later, .data() returns a non-const char*
// pointing to the internal string buffer.
return flag->string_val.data();
}
std::cerr << "TODO: failed to get STRING\n";
exit(1);
}
// ---------------------------------------------------------
// THE NEW API (Modern)
// Returns a const reference to the full std::string.
// Use this for RegExp and strings that might contain \0.
// ---------------------------------------------------------
const std::string &getFlagStdString(IridiumSEXP *binding,
const std::string &flagName) {
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == STRING) {
return flag->string_val;
}
std::cerr << "TODO: failed to get STRING\n";
exit(1);
}
bool getFlagBoolean(IridiumSEXP *binding, const std::string &flagName) {
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == BOOLEAN) {
return flag->boolean_val;
}
std::cerr << "TODO: failed to get BOOLEAN\n";
exit(1);
}
int getFlagNull(IridiumSEXP *binding, const std::string &flagName) {
IridiumFlag *flag = getFlag(binding, flagName);
if (flag->datatype == NULLPTR) {
return 0;
}
std::cerr << "TODO: failed to get NULLPTR\n";
exit(1);
}
// ============== Flag Related ============== //
// ============== Code Generation ============== //
int parse_arg_index(const char *str) {
const char *prefix = "ARG";
size_t prefix_len = strlen(prefix);
if (strncmp(str, prefix, prefix_len) != 0)
return -1;
// Ensure remaining characters are digits
const char *number_part = str + prefix_len;
for (const char *p = number_part; *p != '\0'; ++p) {
if (!isdigit((unsigned char)*p))
return -1;
}
return atoi(number_part);
}
// ============== Misc ============== //
void storeWhatevesOnTheStack(JSContext *ctx, IridiumSEXP *loc,
vector<BCInstruction> &instructions, bool safe,
bool thisInit, bool isStrict,
bool saveResToStack) {
if (saveResToStack)
pushOP(ctx, instructions, OP_dup);
// is lval global?
if (isTag(loc, "GlobalBinding")) {
char *name = getFlagString(loc, "NAME");
if (safe) {
pushOP32(ctx, instructions, OP_put_var_init, JS_NewAtom(ctx, name));
} else if (isStrict) {
pushOP32(ctx, instructions, OP_check_var, JS_NewAtom(ctx, name));
pushOP(ctx, instructions, OP_swap);
pushOP32(ctx, instructions, OP_put_var_strict, JS_NewAtom(ctx, name));
} else {
pushOP32(ctx, instructions, OP_put_var, JS_NewAtom(ctx, name));
}
} else {
if (isTag(loc, "RemoteEnvBinding")) {
if (!safe) {
// Unsafe writes const results in error...
IridiumSEXP *next = loc->args[0];
while (isTag(next, "RemoteEnvBinding")) {
next = next->args[0];
}
ensureTag(next, "EnvBinding");
if (hasFlag(next, "JSCONST") && !thisInit) {
pushOP(ctx, instructions, OP_drop);
pushOP32Flags(ctx, instructions, OP_throw_error,
JS_NewAtom(ctx, getFlagString(next, "NAME")), 0);
return;
}
}
int refIDX = getFlagNumber(loc, "REFIDX");
// === SPECIALIZATION ===
if (thisInit)
return pushOP16(ctx, instructions, OP_put_var_ref_check_init, refIDX);
if (!safe)
return pushOP16(ctx, instructions, OP_put_var_ref_check, refIDX);
switch (refIDX) {
case 0:
return pushOP(ctx, instructions, OP_put_var_ref0);
break;
case 1:
return pushOP(ctx, instructions, OP_put_var_ref1);
break;
case 2:
return pushOP(ctx, instructions, OP_put_var_ref2);
break;
case 3:
return pushOP(ctx, instructions, OP_put_var_ref3);
break;
}
return pushOP16(ctx, instructions, OP_put_var_ref, refIDX);
} else if (isTag(loc, "EnvBinding")) {
if (hasFlag(loc, "JSARG")) {
int argIdx = getFlagNumber(loc, "REFIDX");
assert(argIdx > -1);
// === SPECIALIZATION ===
switch (argIdx) {
case 0:
return pushOP(ctx, instructions, OP_put_arg0);
break;
case 1:
return pushOP(ctx, instructions, OP_put_arg1);
break;
case 2:
return pushOP(ctx, instructions, OP_put_arg2);
break;
case 3:
return pushOP(ctx, instructions, OP_put_arg3);
break;
default:
return pushOP16(ctx, instructions, OP_put_arg, argIdx);
}
} else if (hasFlag(loc, "JSRESTARG")) {
fprintf(stderr, "TODO: handle stores to JSRESTARG");
exit(1);
}
if (!safe) {
if (hasFlag(loc, "JSCONST") && !thisInit) {
pushOP(ctx, instructions, OP_drop);
pushOP32Flags(ctx, instructions, OP_throw_error,
JS_NewAtom(ctx, getFlagString(loc, "NAME")), 0);
return;
}
}
int refIdx = getFlagNumber(loc, "REFIDX");
if (thisInit) {
pushOP16(ctx, instructions, OP_put_loc_check_init, refIdx);
} else if (safe) {
// === SPECIALIZATION ===
switch (refIdx) {
case 0:
pushOP(ctx, instructions, OP_put_loc0);
break;
case 1:
pushOP(ctx, instructions, OP_put_loc1);
break;
case 2:
pushOP(ctx, instructions, OP_put_loc2);
break;
case 3:
pushOP(ctx, instructions, OP_put_loc3);
break;
default: {
if (refIdx < 256) {
pushOP8(ctx, instructions, OP_put_loc8, refIdx);
} else {
pushOP16(ctx, instructions, OP_put_loc, refIdx);
}
break;
}
}
} else {
pushOP16(ctx, instructions, OP_put_loc_check, refIdx);
}
} else {
fprintf(stderr, "TODO: store on stack, unhandled loc kind!!");
exit(1);
}
}
return;
}
// Gemini 2.5 pro, got it right, maybe...
void keepNDropM(JSContext *ctx, vector<BCInstruction> &instructions, int N,
int M) {
// If M is zero or negative, no elements need to be dropped.
if (M <= 0)
return;
// If N is negative, it's an invalid input. Do nothing.
if (N < 0) {
fprintf(stderr, "TODO: keepMDropN, invalid input !!");
exit(1);
}
if (N == 2 && M == 1) {
pushOP(ctx, instructions, OP_nip1);
return;
} else if (N == 1 && M == 2) {
pushOP(ctx, instructions, OP_nip);
pushOP(ctx, instructions, OP_nip);
return;
}
fprintf(stderr, "TODO: keepMDropN, handle general case, validate code!!");
exit(1);
return;
}
void lowerToStack(JSContext *ctx, vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool safeRead = false);
// Field access with an explicit receiver (super.x): [[Get]]/[[Set]] on obj with
// `this` = receiver, i.e. get_super_value / put_super_value.
void handleReceiverFieldRead(JSContext *ctx, vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool retainContext) {
if (retainContext) {
fprintf(stderr, "TODO: retained context on a field read with a receiver\n");
exit(1);
}
lowerToStack(ctx, instructions, rval->args[2]); // receiver
lowerToStack(ctx, instructions, rval->args[0]); // obj
lowerToStack(ctx, instructions, rval->args[1]); // key
pushOP(ctx, instructions, OP_get_super_value);
}
void handleReceiverFieldWrite(JSContext *ctx, vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool toPropKey, bool retainContext) {
lowerToStack(ctx, instructions, rval->args[3]); // receiver
lowerToStack(ctx, instructions, rval->args[0]); // obj
lowerToStack(ctx, instructions, rval->args[1]); // key
if (toPropKey)
pushOP(ctx, instructions, OP_to_propkey);
lowerToStack(ctx, instructions, rval->args[2]); // value
if (retainContext) {
// receiver obj key value -> value receiver obj key value
pushOP(ctx, instructions, OP_insert4);
}
pushOP(ctx, instructions, OP_put_super_value);
}
void handleFieldRead(JSContext *ctx, vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool retainContext = false) {
if (rval->numArgs == 3)
return handleReceiverFieldRead(ctx, instructions, rval, retainContext);
IridiumSEXP *receiver = rval->args[0];
lowerToStack(ctx, instructions, receiver);
IridiumSEXP *field = rval->args[1];
ensureTag(field, "String");
auto fieldNameString = getFlagString(field, "IridiumPrimitive");
if (!retainContext && std::string(fieldNameString) == "length") {
pushOP(ctx, instructions, OP_get_length);
} else {
JSAtom fieldAtom = JS_NewAtom(ctx, fieldNameString);
pushOP32(ctx, instructions, retainContext ? OP_get_field2 : OP_get_field,
fieldAtom);
}
}
void handleFieldWrite(JSContext *ctx, vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool retainContext = false) {
if (rval->numArgs == 4)
return handleReceiverFieldWrite(ctx, instructions, rval, false, retainContext);
// Receiver
IridiumSEXP *receiver = rval->args[0];
lowerToStack(ctx, instructions, receiver);
// Rval
IridiumSEXP *valToPush = rval->args[2];
lowerToStack(ctx, instructions, valToPush);
if (retainContext) {
// rcvr rval -> rval rcvr rval
pushOP(ctx, instructions, OP_insert2);
}
// Field
IridiumSEXP *field = rval->args[1];
ensureTag(field, "String");
JSAtom fieldAtom = JS_NewAtom(ctx, getFlagString(field, "IridiumPrimitive"));
pushOP32(ctx, instructions, OP_put_field, fieldAtom);
}
void handleComputedFieldRead(JSContext *ctx,
vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool retainContext = false) {
if (rval->numArgs == 3)
return handleReceiverFieldRead(ctx, instructions, rval, retainContext);
IridiumSEXP *receiver = rval->args[0];
lowerToStack(ctx, instructions, receiver);
IridiumSEXP *field = rval->args[1];
lowerToStack(ctx, instructions, field);
return pushOP(ctx, instructions,
retainContext ? OP_get_array_el2 : OP_get_array_el);
}
// Opt this...
// obj.#[symbol] = value (PrivateSet) / := value (isDefine: PrivateFieldAdd);
// leaves value on the stack
void handleJSPrivateFieldWrite(JSContext *ctx,
vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool isDefine) {
if (isDefine) {
lowerToStack(ctx, instructions, rval->args[0]); // obj
lowerToStack(ctx, instructions, rval->args[1]); // obj prop
lowerToStack(ctx, instructions, rval->args[2]); // obj prop value
pushOP(ctx, instructions, OP_insert3); // value obj prop value
pushOP(ctx, instructions, OP_define_private_field); // value obj
pushOP(ctx, instructions, OP_drop); // value
} else {
lowerToStack(ctx, instructions, rval->args[0]); // obj
lowerToStack(ctx, instructions, rval->args[2]); // obj value
pushOP(ctx, instructions, OP_insert2); // value obj value
lowerToStack(ctx, instructions, rval->args[1]); // value obj value prop
pushOP(ctx, instructions, OP_put_private_field); // value
}
}
void handleComputedFieldWrite(JSContext *ctx,
vector<BCInstruction> &instructions,
IridiumSEXP *rval, bool retainContext = false) {
if (rval->numArgs == 4)
return handleReceiverFieldWrite(ctx, instructions, rval,
!hasFlag(rval, "SAFE"), retainContext);
// Receiver
IridiumSEXP *receiver = rval->args[0];
lowerToStack(ctx, instructions, receiver);
// Field
IridiumSEXP *field = rval->args[1];
lowerToStack(ctx, instructions, field);
if (!hasFlag(rval, "SAFE"))
pushOP(ctx, instructions, OP_to_propkey);
// Rval
IridiumSEXP *assnVal = rval->args[2];
lowerToStack(ctx, instructions, assnVal);
if (retainContext) {