-
Notifications
You must be signed in to change notification settings - Fork 2
/
compile.js
4654 lines (4178 loc) · 151 KB
/
compile.js
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
'use strict';
var ELECTRON_WORKER = (typeof alert === 'undefined') && (typeof process !== 'undefined');
var PLATFORM_ELECTRON = typeof window !== 'undefined' && window.process && window.process.type === "renderer";
PLATFORM_ELECTRON |= ELECTRON_WORKER;
var STACK_DEBUG = false;
Error.stackTraceLimit=undefined;
/** @constructor */
function RequireLoopError(msg) {
this.name = 'RequireLoopError';
this.message = msg;
}
/** @constructor */
function AlreadyInformedError(msg) {
this.name = 'AlreadyInformedError';
this.message = msg;
}
function fail(thing, info) {
if (typeof thing == 'object' && thing
&& 'fail' in thing && typeof thing.fail === 'function'
) thing.fail(info);
if (typeof log != "undefined") log(info);
throw "broken "+typeof thing+": "+info+" at "+new Error().stack;
}
function assert_src(thing, test) {
if (!test) fail(thing, "assert failed");
}
var idcounter = 0;
function unique_id(name) {
return name+(idcounter++);
}
function unique_id_for(thing, name) {
if (!thing.hasOwnProperty("uniqid")) {
thing.uniqid = unique_id(name);
}
return thing.uniqid;
}
function js_type_to_c(type) {
if (type == "float") return "double";
if (type == "bool") return "int";
return type;
}
function filter_string(str) {
var res = "";
var reg = /[a-z0-9_]+/gi;
var result;
while (result = reg.exec(str)) res += result;
return res;
}
// thanks https://github.com/joliss/js-string-escape/blob/master/index.js
function jsStringEscape(string) {
return ('' + string).replace(/["'\\\n\r\u2028\u2029]/g, function (character) {
// Escape all characters not included in SingleStringCharacters and
// DoubleStringCharacters on
// http://www.ecma-international.org/ecma-262/5.1/#sec-7.8.4
switch (character) {
case '"': case "'": case '\\': return '\\' + character
// Four possible LineTerminator characters need to be escaped:
case '\n': return '\\n'
case '\r': return '\\r'
case '\u2028': return '\\u2028'
case '\u2029': return '\\u2029'
}
});
}
function js_tag_init(type, value) {
if (type == "float") {
if (typeof value == "number" && value == (value|0)) {
return value+".0";
// return "fround("+value+")";
} else if (""+parseFloat(value) == value) {
value = parseFloat(value).toFixed(20);
return value;
// if (value == "Infinity") return; // Double, not Float
// return "fround("+value+")";
}
}
if (type == "int") {
if (typeof value == "number") return value;
}
}
function suspect(text) {
if (text.search("undefined") !== -1 || text.search("object Object") !== -1 || text.search("null") !== -1) {
throw ("this seems suspicious. "+text);
}
}
function list() {
var value = [];
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
if (typeof arg == "string") value.push({
kind: "atom",
value: arg
});
else value.push(arg);
}
return {
kind: "list",
value: value
};
}
function tagf_init(arg) { return js_tag_init("float", arg); }
function isFloat(arg) {
if (""+parseFloat(arg) == arg ||
""+parseFloat(arg)+".0" == arg)
{
return true;
}
if (arg != arg) return true; // special: NaN
return false;
}
function str_is_int(arg) {
return ""+parseInt(arg, 10) == arg;
}
function coerce_int(arg) {
if (typeof arg === "string" && arg.slice(0, 2) == "__") { /* replaced with integer later */
return arg;
}
// like fround(1)
if (typeof arg === "string" && arg.slice(0, 7) == "fround(" && arg.slice(-1) == ")" && isFloat(arg.slice(7, -1))) {
arg = arg.slice(7, -1);
}
if (isFloat(arg)) {
return ""+(~~(parseFloat(arg, 10)));
}
if (PLATFORM_ELECTRON) {
return "(int)"+paren_maybe(arg);
}
return "~~"+paren_maybe(arg, "~");
}
function lit_float(thing) {
if (thing.kind != "expr") return false;
return typeof thing.value == "number";
}
function lit_int(thing) {
if (!lit_float(thing)) return false;
if (thing.type != "int") return false;
if (thing.value != thing.value|0) throw "bad int";
return true;
}
function lit_bool(thing) {
if (thing.kind != "expr") return false;
if (thing.type != "bool") return false;
return thing.value == true || thing.value == false;
}
function coerce_double(thing) {
return js_tag("double", js_tag(thing));
}
function paren_maybe(ex, op) {
ex = ""+ex;
suspect(ex);
var is_simple_identifier = function(text) {
return !!text.match(/^[a-zA-Z_][0-9a-zA-Z_]*$/);
};
var is_number = function(text) {
if (str_is_int(text)) return true;
if (""+parseFloat(text) == text) return true;
if (parseFloat(text).toFixed(20) == text) return true;
if (""+parseFloat(text)+".0" == text) return true; // forced double
return false;
};
var is_basic = function(text) {
return is_simple_identifier(text) || is_number(text);
};
if (is_basic(ex)) return ex;
if (ex.slice(0, 6) == "fround") return ex;
/*if ("+./*&|^~<=>=".indexOf(op) != -1) {
if (ex.slice(0,1) == "+" && is_basic(ex.slice(1))) return " "+ex;
}*/
return "("+ex+")";
}
function js_tag(type, value) {
if (typeof value == "undefined") {
value = type;
if (typeof value != "object") throw "what is "+typeof value+" "+value;
if (value.kind == "frame") value = value.base;
if (value.kind == "expr") {
/*if (!lit_float(value)) {
return value.value;
}*/
type = value.type;
value = value.value;
} else throw "how tag '"+value.kind+"'";
}
if (PLATFORM_ELECTRON) {
if (type == "float") return "(double)"+paren_maybe(value);
if (type == "double") return "(double)"+paren_maybe(value);
if (type == "int") return "(int)"+paren_maybe(value);
if (type == "bool") {
if (typeof value == "boolean") {
if (value) return "1";
else return "0";
}
return "(int)"+paren_maybe(value);
}
}
if (type == "float") return "+"+paren_maybe(value, "+");
// if (type == "float") return "fround("+value+")";
if (type == "double") return "+"+paren_maybe(value, "+");
if (type == "int") return paren_maybe(value, "|")+"|0";
if (type == "bool") {
if (typeof value == "boolean") {
if (value) return "1";
else return "0";
}
return paren_maybe(value, "|")+"|0";
}
throw "how tag "+type;
// return value;
}
function js_as_type(type, value) {
if (lit_int(value)) return value.value;
if (value.kind == "expr" && value.type == type) {
return js_tag(value);
}
if (type == "float" && value.kind == "expr" && value.type == "int") {
return js_tag("float", js_tag(value));
}
// return null;
if (type == "int" && value.kind == "expr" && value.type == "float") return null;
fail(value, "as_type? <"+type+"> "+JSON.stringify(value));
}
// for unification
function js_typelist(thing) {
if (thing.kind == "expr") {
if (thing.type == "int")
return ["int", "float", "double"];
if (thing.type == "float")
return ["float", "double"];
return [thing.type];
} else throw "what is typelist of "+thing.kind;
}
function first_common(array1, array2) {
for (var i = 0; i < array1.length; ++i) {
var entry = array1[i];
for (var k = 0; k < array2.length; ++k) {
if (array2[k] == entry) return entry;
}
}
return null;
}
function js_unify_vars(left, right) {
var packtag = function(type, thing) {
return {kind: "expr", type: type, value: js_as_type(type, thing)};
};
var ltypes = js_typelist(left), rtypes = js_typelist(right);
var shared = first_common(ltypes, rtypes);
if (shared) return {left: packtag(shared, left), right: packtag(shared, right)};
fail(left, "unsure how to unify "+JSON.stringify(left)+", "+JSON.stringify(right)+", types "+JSON.stringify(ltypes)+", "+JSON.stringify(rtypes));
return {left: left, right: right};
}
/** @constructor */
function ClosurePointer(type, base, offset) {
var sign = flatten_type_array(["int"].concat(type.args)).signature;
var fntype = closureTypeToFnType(type);
return {
kind: "closure-pointer",
type: type,
signature: sign,
base: base,
fnptr: {
kind: "function-pointer",
type: fntype,
signature: sign,
offset: offset,
call: function(ctx, thing, args) {
if (args.length != this.type.args.length) {
fail(thing, "invalid number of parameters: expected "+(this.type.args.length - 1)+", got "+(args.length - 1));
}
return js_call_fnptr(ctx.js, this, thing, args);
}
}
};
}
function js_get_at(type, base, offs) {
offs = offs || 0;
if (type.kind == "vector") {
var parts = [];
var elemsize = js_type_size(type.base);
for (var i = 0; i < type.size; ++i) {
parts.push(js_get_at(type.base, base, offs + elemsize * i));
}
var res = mkVec_direct(type, parts);
res.base = base;
return res;
}
if (typeof type == "object") {
if (type.kind == "pointer") {
return {kind: "pointer", base: js_get_at("int", base, offs), type: type.type};
}
if (type.kind == "array-type") {
return new RLArray(type, js_get_at("int", base, offs), js_get_at("int", base, offs + 4));
}
if (type.kind == "struct") {
var value = {};
for (var key in type.types) if (type.types.hasOwnProperty(key)) {
var mtype = type.types[key];
var moffset = type.offsets[key];
value[key] = js_get_at(mtype, base, offs + moffset);
}
var offbase = {kind: "expr", type: "int", value: js_op(null, "+", js_tag(base), offs)};
return {
kind: "struct",
type: type,
base: offbase,
value: value
};
}
if (type.kind == "frame") {
var res = flatclone(type);
if (res.hasOwnProperty("base")) {
res.base = js_get_at("int", base, offs + 0);
}
return res;
}
if (type.kind == "closure-poly") {
var res = flatclone(type); // one of those tricksy "value = type" thingses
res.base = flatclone(res.base);
if (res.base.hasOwnProperty("base")) {
res.base.base = js_get_at("int", base, offs + 0);
}
return res;
}
if (type.kind == "function-poly") {
return type;
}
if (type.kind == "closure") {
return new ClosurePointer(
type,
{kind: "frame", base: js_get_at("int", base, offs + 0)},
js_get_at("int", base, offs + 4)
);
}
}
var target = null;
if (PLATFORM_ELECTRON) {
var c_type = type;
if (type == "bool") c_type = "int";
if (offs === 0) {
target = "*("+c_type+"*) (memory + "+js_tag(base)+")";
} else if (typeof offs == "number") {
target = "*("+c_type+"*) (memory + "+paren_maybe(js_op(null, "+", js_tag(base), offs), "+")+")";
} else {
target = "*("+c_type+"*) (memory + "+paren_maybe(js_op(null, "+", js_tag(base), js_tag(offs)), "+")+")";
}
} else {
var shift = null, stackvar = null;
if (type == "float") {
shift = 2;
stackvar = "mem_f32";
} else if (type == "int" || type == "bool") {
shift = 2;
stackvar = "mem_i32";
} else fail(null, "unimplemented js_get_at(type="+JSON.stringify(type)+", base="+JSON.stringify(base)+", offs="+offs+")");
if (offs === 0) {
target = stackvar+"["+paren_maybe(js_tag(base), ">>")+" >> "+shift+"]";
} else if (typeof offs == "number") {
target = stackvar+"["+paren_maybe(js_op(null, "+", js_tag(base), offs), ">>")+" >> "+shift+"]";
} else {
target = stackvar+"["+paren_maybe(js_op(null, "+", js_tag(base), js_tag(offs)), ">>")+" >> "+shift+"]";
}
}
suspect(target);
return {
kind: "expr",
type: type,
value: target
};
};
function js_tag_cast(type, thing) {
if (type == "float") {
if (thing.kind == "expr" && thing.type == "float") {
return js_tag(thing);
}
}
return js_tag(type, js_tag(thing));
}
function js_op(type, op, a, b) {
// int ops
if (op == "<<" || op == ">>" || op == ">>>" || op == "&" || op == "|" || op == "^") {
a = coerce_int(a);
b = coerce_int(b);
}
a = paren_maybe(a, op);
b = paren_maybe(b, op);
if (op == "%") {
// TODO mkVar?
return js_op(type, "%%", js_op(type, "+", js_op(type, "%%", a, b), b), b);
}
if (op == "%%") {
op = "%";
if (type != "int") {
a = "+("+a+")"; // coerce, if float
b = "+("+b+")";
type = "float"; // coerce back
}
}
var res = null;
if (op == "%" && type == "float" && PLATFORM_ELECTRON) {
res = "fmod("+a+", "+b+")";
} else if (op == ">>>" && PLATFORM_ELECTRON) {
res = "(unsigned int)("+a+") >> "+b;
} else if (type == "int" && op == "*" && !PLATFORM_ELECTRON) {
res = "imul("+a+", "+b+")";
} else {
res = a+" "+op+" "+b;
}
if (!type) return res;
return js_tag(type, res);
}
// turn a compound expression into an array of primitives
function flatten(base, thing) {
if (thing == null)
throw "flatten null?";
if (typeof thing == "function-poly")
return [thing]; // hopeless
if (thing.kind == "struct") {
fail(base, "cannot pass struct as parameter (must be pointer) - internal issue");
}
if (thing.kind == "pointer") {
return [thing.base];
}
if (thing.kind == "frame") {
if (!thing.hasOwnProperty("base")) {
// this can happen if we pass an interpreted
// stackframe to a compiled function
// in this case, because we're passing the context as constants,
// each frame must uniquely specialize the target function.
return [];
}
return [thing.base];
}
if (thing.kind == "expr") {
return [thing]; // all "variables" are primitive
}
if (thing.kind == "vector") {
var vars = [];
for (var i = 0; i < thing.type.size; ++i) {
vars.push({kind: "expr", type: thing.type.base, value: thing.value[i]});
}
return vars;
}
if (thing.kind == "array") {
return [thing.ptr, thing.size];
}
if (thing.kind == "closure-pointer") {
return [thing.base.base, thing.fnptr.offset];
}
if (thing.kind == "closure-poly") {
return flatten(base, thing.base);
}
if (thing.kind == "function-poly") {
return [];
}
if (thing.kind == "closure") {
if (!thing.hasOwnProperty("value")) {
// see above - interpreted closure to compiled function
return [];
}
}
fail(base, "how to flatten "+typeof thing+" "+thing.kind);
}
function flatten_type(type) {
// types provided in-repl
if (typeof type == "object" && type.hasOwnProperty('kind') && type.kind == "atom") {
type = type.value;
}
if (type == "float" || type == "int" || type == "bool") return [type];
if (type.kind == "vector") {
var types = [];
for (var i = 0; i < type.size; ++i) types.push(type.base);
return types;
}
if (type.kind == "array-type") {
return ["int", "int"]; // ptr, size
}
if (type.kind == "closure-poly") {
if (type.base.hasOwnProperty("base")) return ["int"]; // base pointer
else return []; // baseless closure (interpreted frinstance)
}
if (type.kind == "function-poly") {
return [];
}
// type of frame is just frame - frames are special snowflakes
if (type.kind == "frame") {
if (!type.hasOwnProperty("base")) { // see above
return []; // already got a special signature in flatten(), don't need a special call table
}
return [type.base.type];
}
if (type.kind == "struct") {
fail(null, "how to flatten struct - internal issue");
}
if (type.kind == "pointer") {
return ["int"];
}
if (type.kind == "closure") { // type of value.kind="closure-pointer"
return ["int", "int"];
}
fail(null, "how to flatten "+typeof type+" "+JSON.stringify(type));
}
function get_type_signature(thing) {
if (thing == null) return "null";
if (typeof thing == "string") return thing;
if (thing.kind == "expr") return get_type_signature(thing.type);
if (thing.kind == "vector" && 'type' in thing) return get_type_signature(thing.type);
if (thing.kind == "vector") return "vector_"+thing.size+"_"+thing.base;
if (thing.kind == "array") return get_type_signature(thing.type);
if (thing.kind == "array-type") return "array_"+get_type_signature(thing.base);
if (thing.kind == "pointer" && thing.type.kind == "struct") {
return "p_" + get_type_signature(thing.type);
}
if (thing.kind == "struct") {
if (thing.hasOwnProperty("type")) thing = thing.type;
var types = thing.types;
var parts = [];
for (var key in types) if (types.hasOwnProperty(key)) {
parts.push(get_type_signature(types[key]));
}
return "struct_" + parts.join("_") + "_";
}
if (thing.kind == "closure-poly") {
return unique_id_for(thing, "closure_poly"); // each poly-closure is "unique"
}
if (thing.kind == "function-poly") {
return unique_id_for(thing, "function_poly"); // each poly-function is "unique"
}
if (thing.kind == "closure") {
var parts = [];
for (var i = 0; i < thing.args.length; ++i) {
parts.push(get_type_signature(thing.args[i]));
}
return "closure_ret_"+get_type_signature(thing.ret)+"_args_"+parts.join("_")+"_";
}
if (thing.kind == "closure-pointer") {
return "closure_pointer_"+get_type_signature(thing.base.base)+"_"+get_type_signature(thing.fnptr.offset)+"_";
}
if (thing.kind == "frame") {
if (!thing.hasOwnProperty("base")) {
// just constants in the frame (interp passed to compiled lambda)
// so specialize the function
// (TODO do this better somehow?)
return unique_id_for(thing, "frame_pointer");
}
return "frame_pointer"; // cause lambdas are already "unique", there's no need to specialize further
}
fail(thing, "unimplemented: type signature for "+JSON.stringify(thing));
}
function flatten_array(thing, args) {
var array = [];
var sigparts = [];
var types = [];
for (var i = 0; i < args.length; ++i) {
var sub = flatten(thing, args[i]);
var signature = get_type_signature(args[i]);
var subtypes = flatten_type(js_type(args[i]));
if (subtypes.length != sub.length)
throw ("internal error - flatten and flatten_type mismatch for "+JSON.stringify(js_type(args[i]))+" of "+JSON.stringify(args[i]));
sigparts.push(signature);
for (var k = 0; k < sub.length; ++k) {
array.push(sub[k]);
}
for (var k = 0; k < subtypes.length; ++k) {
types.push(subtypes[k]);
}
}
// alert("flatten_array("+JSON.stringify(args)+") => "+JSON.stringify(array));
var signature = sigparts.join("_");
return {signature: signature, array: array, types: types};
}
function flatten_type_array(types) {
var js_types = [];
for (var i = 0; i < types.length; ++i) {
var sub = flatten_type(types[i]);
for (var k = 0; k < sub.length; ++k) {
js_types.push(sub[k]);
}
}
return {signature: js_types.join("_"), js_types: js_types};
}
function reconstruct_by_types(js, types, vars) {
var take = function(i) {
if (vars.length < i) throw "reconstruct failure: vars ran out";
var res = vars.slice(0, i);
vars = vars.slice(i);
return res;
};
var array = [];
for (var i = 0; i < types.length; ++i) {
var type = types[i];
// type provided in-repl
if (typeof type == "object" && type.hasOwnProperty('kind') && type.kind == "atom") {
type = type.value;
}
if (type == "int" || type == "float" || type == "bool") {
array.push(take(1)[0]);
continue;
}
if (type.kind == "frame") {
array.push({kind: "frame", entries: type.entries, base: take(1)[0]});
continue;
}
if (type.kind == "pointer") {
array.push({kind: "pointer", base: take(1)[0], type: type.type});
continue;
}
if (type.kind == "struct") {
fail(null, "internal error - reconstruct struct");
// array.push(js_get_at(type, take(1)[0], 0));
continue;
}
if (type.kind == "vector") {
var comps = take(type.size);
var names = new Array(comps.length);
for (var i = 0; i < comps.length; ++i) {
var comp = comps[i];
if (comp.kind != "expr") throw "todo";
if (comp.type != type.base) throw ("invalid argument type for reconstructing "+type.base+": "+comp.type);
names[i] = comp.value;
}
array.push({kind: "vector", type: type, value: names});
continue;
}
if (type.kind == "array-type") {
var comps = take(2);
array.push(new RLArray(type, comps[0], comps[1]));
continue;
}
fail(null, "unimplemented: reconstruct "+JSON.stringify(type));
}
if (vars.length) throw "reconstruct failure: vars left over!";
return array;
}
function js_type(thing) {
if (thing.kind == "expr" || thing.kind == "struct"
|| thing.kind == "vector" || thing.kind == "array"
|| thing.kind == "function" || thing.kind == "closure"
) return thing.type;
if (thing.kind == "pointer") return {kind: "pointer", type: thing.type};
if (thing.kind == "frame") return thing; // eesh
if (thing.kind == "function-poly" || thing.kind == "closure-poly"
|| thing.kind == "function-pointer" || thing.kind == "closure-pointer") {
if (thing.hasOwnProperty("type")) return thing.type;
return thing; // Eeesh.
}
fail(thing, "what's its type?? "+JSON.stringify(thing));
}
function js_type_size(type) {
if (type == "float" || type == "int" || type == "bool") return 4;
if (typeof type == "object") {
if (type.kind == "vector") {
var res = js_type_size(type.base) * type.size;
if (res == 12) res = 16; // vec3 are vec4-sized for 16-alignment reasons
return res;
}
if (type.kind == "struct") return type.size;
if (type.kind == "array-type") {
return 8; // two pointers
}
}
fail(type, "what's this type's size?? "+typeof type+" "+JSON.stringify(type));
}
function js_size(thing) {
if (thing.kind == "expr" || thing.kind == "struct"
|| thing.kind == "vector" || thing.kind == "array"
|| thing.kind == "function" || thing.kind == "closure"
) return js_type_size(thing.type);
if (thing.kind == "pointer") return 4;
if (thing.kind == "closure-pointer") return 8; // function table offset, heap offset
if (thing.kind == "function-poly") return 0; // poly function cannot be stored, so encode in type
if (thing.kind == "closure-poly") {
// (type closure ...)'d
if (thing.hasOwnProperty("type") && thing.type.kind == "closure") return 8;
return 4; // heap offset still
}
if (thing.kind == "frame" && thing.hasOwnProperty("base")) return 4;
fail(thing, "what's its size?? "+typeof thing+" "+JSON.stringify(thing));
}
// turn an array of primitives into a structurally
// equivalent reconstruction of a compound expression
function reconstruct(js, thing, array) {
if (thing.kind == "expr") {
var type = thing.type;
if (type == "float" || type == "int" || type == "bool") {
if (array.length < 1) fail(thing, "reconstruct:1 internal error");
if (array[0].kind != "expr" || array[0].type != type) throw ("can't reconstruct "+type+" from "+JSON.stringify(array[0]));
return {
value: array[0],
rest: array.slice(1)};
}
}
if (thing.kind == "vector") {
if (array.length < thing.type.size) fail(thing, "reconstruct:2 internal error");
var vars = array.slice(0, thing.type.size);
for (var i = 0; i < vars.length; ++i) {
var v = vars[i];
if (v.kind != "expr" || v.type != thing.type.base) throw ("can't reconstruct vector from "+JSON.stringify(v));
}
return {
value: mkVec_direct(thing.type, vars),
rest: array.slice(thing.type.size)};
}
if (thing.kind == "array") {
var res = new RLArray(thing.type, array[0], array[1]);
return { value: res, rest: array.slice(2) };
}
if (thing.kind == "frame") {
if (!thing.hasOwnProperty("base")) {
// the interpreted-to-compiled case
return {value: thing, rest: array};
}
var base = array[0];
return {
value: {
kind: "frame",
base: base,
entries: thing.entries
},
rest: array.slice(1)
};
}
if (thing.kind == "closure") {
if (!thing.hasOwnProperty("value")) {
// interpreted-to-compiled
return {value: thing, rest: array};
}
fail(thing, "unimplemented: runtime closure");
}
if (thing.kind == "closure-pointer") {
var res = flatclone(thing);
res.fnptr = flatclone(res.fnptr);
res.base = {kind: "frame", base: array[0]};
res.fnptr.offset = array[1];
if (!res.fnptr.offset) throw "what";
return {value: res, rest: array.slice(2)};
}
if (thing.kind == "function-poly") {
var res = flatclone(thing);
return {value: res, rest: array};
}
if (thing.kind == "closure-poly") {
var res = flatclone(thing);
res.base = flatclone(thing.base);
if (res.base.hasOwnProperty("base")) {
res.base.base = array[0];
return {value: res, rest: array.slice(1)};
} else {
return {value: res, rest: array};
}
}
if (thing.kind == "struct") {
fail(thing, "internal issue - cannot pass struct as parameter");
}
if (thing.kind == "pointer" && thing.type.kind == "struct") {
var base = array[0], rest = array.slice(1);
var type = thing.type;
if (base == null) throw "internal error";
var value = {kind: "pointer", base: base, type: type};
return { rest: rest, value: value };
}
fail(thing, "unimplemented: reconstruct "+thing.kind);
}
function reconstruct_array(js, args, array) {
// log("reconstruct_array("+JSON.stringify(args)+", array "+JSON.stringify(array)+")");
var inside = [];
for (var i = 0; i < args.length; ++i) {
var ret = reconstruct(js, args[i], array);
inside.push(ret.value);
array = ret.rest;
}
if (array.length > 0) fail(args[0], "internal logic error");
return inside;
}
/** @constructor */
function Parser(text, fulltext_or_rowbase) {
var rowbase = 0;
var fulltext = null;
if (typeof fulltext_or_rowbase == "number") rowbase = fulltext_or_rowbase;
else fulltext = fulltext_or_rowbase;
if (!fulltext) fulltext = text;
this.text = text;
this.fulltext = fulltext;
this.rowbase = rowbase;
this.fulltext_lines = this.fulltext.split("\n");
this.clean = function() {
// eat leading space or comments
this.text = this.text.replace(/^(\s+|;[^\n]*\n)+/g, '');
};
this.getLocation = function(text) {
var left_lines = text.split("\n"); // TODO figure out a way to make faster??
var line = this.fulltext_lines.length - left_lines.length;
var full_line = this.fulltext_lines[line];
var column = full_line.length - left_lines[0].length;
return {row: line + this.rowbase, column: column};
};
this.getLineBefore = function(text) {
var loc = this.getLocation(text);
return this.fulltext_lines[loc.row - this.rowbase].slice(0, loc.column);
};
this.fail = function(info) {
var where = this.getLocation(this.text);
log((where.row+1)+":"+where.column+": "+info);
throw info;
};
this.accept = function(str) {
this.clean();
if (this.text.substr(0, Math.min(this.text.length, str.length)) == str) {
this.text = this.text.substr(str.length);
return true;
}
return false;
};
this.expect = function(str) {
if (!this.accept(str)) {
this.fail("Expected '"+str+"'");
}
};
this.gotIdentifier = function() {
this.clean();
var hit = this.text.match(/^([^()\s]+)(\s|[)])/);
if (!hit) return false;
this.text = this.text.substr(hit[1].length);
return hit[1];
};
this.gotNumber = function(only_int) {
this.clean();
var hit = this.text.match(/^([+-]?(0x[0-9a-fA-F]+|[0-9]+|[0-9]*\.[0-9]*))(\s|[)])/);
if (!hit) return false;
var match = hit[1];
var removed = 0;
if (match.slice(0,1) == "+") {
match = match.slice(1);
removed += 1;
}
if (match.slice(0,2) == "0x") {
// hex literal
this.text = this.text.substr(match.length + removed);
return parseInt(match.slice(2), 16);
}
if (only_int) {
var res = parseInt(match, 10);
if (""+res == match) {
this.text = this.text.substr(match.length + removed);
return res;
}
return false;
}
this.text = this.text.substr(match.length + removed);
return parseFloat(match, 10);
};
this.gotInt = function() { return this.gotNumber(true); };
this.eof = function() {
this.clean();
return this.text.length === 0;
};
}
/** @constructor */
function IndentChecker() {
this.depth = 0;
this.leads = {};
this.checkOpen = function(text_at, parser, failHere) {
var linehead = parser.getLineBefore(text_at);
if (/^\s*$/.test(linehead)) {
if (this.leads.hasOwnProperty(this.depth)) {
var lead = this.leads[this.depth];
if (lead.length != linehead.length) {
failHere("Wrong indentation: At col "+linehead.length+" but previous col was "+lead.length+"! Did you forget to close a bracket?");
}
} else {
this.leads[this.depth] = linehead;
}
}
};
this.open = function() { this.depth++; };
this.close = function() { delete this.leads[this.depth]; this.depth--; };
}
function sexpr_parse(context, parser, indentchecker) {
if (typeof indentchecker == "undefined") indentchecker = new IndentChecker;
var thing = {};
parser.clean(); // remove detritus for text_at
var text_at = parser.text;
var text_post = text_at;
var failHere = function(info) {
var loc1 = parser.getLocation(text_at);
var loc2 = parser.getLocation(text_post);
log((loc1.row+1)+":"+loc1.column+": "+info);
window.setErrorAt(loc1, loc2, info);
throw new AlreadyInformedError(info);
};
thing.fail = failHere;
var quoted = false;
if (parser.accept("'")) quoted = true;
var quasiquoted = false;
if (parser.accept("`")) quasiquoted = true;
var unquoted = false;
if (parser.accept(",")) unquoted = true;
if (quoted + quasiquoted + unquoted > 1) {
parser.fail("what are you even doing here man");
}
var makething = function(args) {
for (var key in args) if (args.hasOwnProperty(key)) {
thing[key] = args[key];
}
if (quoted) {
thing = {kind: "quote", value: thing, fail: thing.fail};
}
if (quasiquoted) {
thing = {kind: "list", fail: thing.fail, value: [
{kind: "atom", fail: thing.fail, value: "quasiquote"},
thing
]};
}
if (unquoted) {
thing = {kind: "list", fail: thing.fail, value: [
{kind: "atom", fail: thing.fail, value: "unquote"},
thing
]};
}
return thing;
};
if (parser.accept("(")) {
text_post = parser.text;
indentchecker.checkOpen(text_at, parser, failHere);
indentchecker.open();
var sexpr = [];
while (true) {
if (parser.accept(")")) break;
sexpr.push(sexpr_parse(context, parser, indentchecker));