-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompile.js
More file actions
2088 lines (2084 loc) · 80.1 KB
/
compile.js
File metadata and controls
2088 lines (2084 loc) · 80.1 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
//TEST IMPURE UNTESTED TODO
const TEST = false;
//TODO:
//- Make NameSpace an instance of Exp_Array, where nameSpace[0] is its expression
//- Implement replace `nameSpace .exp` with `namespace[0]`
//- Make Constext contain an array of all the parent contexts referenced by the Lazy expressions.
//- Replace evalFully() with a partial evaluation system.
//- Fix bug: allow '[f1 a, f2 b]' -> '[(f1 a) (f2 b)]' instead of '[f1 a (f2 b)]'
//BODGED
{//compile,files,JSintervace
//classes
//Exp: Lambda'λ' | Lazy'()' | Recur'::'
//OutExp: Lazy
class Exp{
//id:WordData
call(arg,context,stack){return stack.doOnStack(this,arg,stack=>this.eval(stack).call(arg,context,stack))}
eval(stack){return this}//lazy evaluatuation
evalFully(stack){return (this instanceof Lazy?this:new Lazy(this)).evalFully(stack)}//non-lazy evaluation
toJS(){return Object.assign((...args)=>args.reduce((s,v)=>s.call(v),this),{})}
static eval(exp,ownerExp,stack=new Stack,reps=1){
for(let i=0;i<reps;i++)
exp=exp?.[Exp.symbol]?stack?stack.doOnStack(ownerExp,exp,stack=>exp.eval(stack)):exp.eval():exp;
return exp;
};
static evalFully(exp,stack=new Stack){
return new Lazy(exp).evalFully(stack);
};
static isTypeReducible(exp){//returns to if exp.eval() != exp ; note doesn't include `(&& !exp.labels)`
//isLazyEvalType
return exp instanceof Lazy || exp instanceof Reference || exp instanceof RecurSetter;
}
static isReducible(exp){
return !exp?.[Exp.symbol]?false:
exp instanceof NameSpace?exp.exp instanceof NameSpace||exp.exp instanceof JSWrapper||this.isReducible(exp.exp):
//exp?.constructor == Array?(!exp.isList && !exp?.labels):
exp instanceof AsyncExp?exp.isReducible():
exp instanceof Lazy?!(exp.length==1 && exp[0] instanceof Lambda && !exp.isList && !exp.labels):
exp instanceof RecurSetter||this.isTypeReducible(exp);
}
static isSearched = Symbol();
static toJS(exp){return exp?.[Exp.symbol]?exp.toJS():exp}
static fromJS(value,recursiveLevel=-1,fileName){//:Exp
const addId = v=>Object.assign(v,{id:new WordData({fileName})});
let ans;
switch(typeof value){
case"function":ans = new Func(value);break;
case"number":ans = value===(value|0)?new Int(value):new Float(value);break;
case"string":ans = new StringExp(value);break;
case"undefined":ans = Lambda.null;break;
case"boolean":return new Lambda(new Lambda(value?1:0));break;
case"object":
if(value==null)return Lambda.null;
if(recursiveLevel>0)value[this.isSearched]=true;
ans =
value[Exp.symbol]?value:
recursiveLevel-- <= 0?new JSWrapper(value):
value instanceof Array?new List(...(recursiveLevel>0?value.map(v=>Exp.fromJS(v,recursiveLevel-1,fileName)):value)):
new NameSpace((obj=>{
let newMap=new Map;
for(let i in obj)newMap.set(i,!obj[i]?.[this.isSearched]&&recursiveLevel>0?this.fromJS(obj[i],recursiveLevel-1,fileName):obj[i]);
return newMap;
})(value))
;
if(ans.id==undefined)ans.id = addId(ans);
if(recursiveLevel>0)if(value)delete value[this.isSearched];
break;
}
if(ans == undefined)throw new CompilerError("compiler error: undefined value");
return ans == Lambda.null?ans:addId(ans);
}
static symbol = Symbol("is expression");
//labels:Map(string=>Exp);
}
class Exp_Array extends Array{
//note without this custom map method: this.map would first call 'new Lazy(this.length)', which is only overwriten if there is at least 1 item in the expression.
map(foo){return this.length==0?new this.constructor():Array.prototype.map.call(this,foo);}
}
class Exp_Number extends Number{}
class Exp_String extends String{}
Exp.prototype[Exp.symbol] = true;
for(let i of ["call", "eval", "evalFully", "toJS","symbol",Exp.symbol]){
Exp_Array.prototype[i]??=Exp.prototype[i];
Exp_Number.prototype[i]??=Exp.prototype[i];
Exp_String.prototype[i]??=Exp.prototype[i];
}
var files={
list:new Map([]),//Map(fileName => FileData)
FileData:class FileData extends Exp{//data for errors
constructor(data){super();Object.assign(this,data);}
//note these properties are not used in the Expression classes.
text;//:string
words;//:string[]
tree;//:tree([string,id,FileData])
lines;//:string[]
context;//:BracketPattern
expression;//:Lazy
get value(){return this.expression}//:Exp
call(arg,context = new Context,stack = new Stack){return this.value.call(arg,context,stack)??Lambda.null}
eval(stack = new Stack,context = new Context(undefined,undefined,1)){return this.value.eval(stack,context)??Lambda.null}
evalFully(stack = new Stack){return this.value.evalFully(stack)}
},
addInbuilt(exp,name="SOURCE"){
let word = "SOURCE:[ "+name+" ]";
exp.id = new WordData({
line:1,column:1,fileName:["SOURCE"],
word,
maxRecur:Infinity,
file:new this.FileData({expression:exp,lines:[word]}),
});
return exp;
},
reset(){},
};
//type ID : WordData
class WordData{
constructor(data){
Object.assign(this,data);
this.file=data.file;
}
//getter and setter used to make console logs look neater
get file(){return this.#file}
set file(v){this.#file=v}
#file;
maxRecur = Infinity;
//line:1,column:1,lines,file,word:"",maxRecur:Infinity
throwError(type,errorMessage,error,stack){//error = str=>Error(str)
//note: lines and colums are counted from 1
if(!TEST)error=a=>a;
throw error(
"lc++ ERROR:\n"
//"l:"+data.line+" c:"+data.column+"\n"
// " ".repeat(lineLen)+" |\n"
+this.displayWordInLine(type+" error")+"\n"
+"error"+": "+errorMessage+"\n"
+(!stack?"":
"stack:\n"
+stack.map(id=>id?.displayWordInLine?.("at")??"").join("\n")
)
);
}
displayWordInLine(msg){
let line = this.file.lines[this.line-1];
let whiteSpace = line.match(/^[\t ]*/)?.[0]??"";
let whiteLen = whiteSpace.length;
line = line.substr(whiteLen)//[whiteSpace,line]
let lineLen = (""+this.line).length;
return ""
+this.line+" |" +line+"\n"
+" ".repeat(lineLen)+" |" +" ".repeat(this.column-1-whiteLen)+"^".repeat(this.word.length)+" "+msg
;
}
}
class FilelessWordData extends WordData{
//word
displayWordInLine(){
return "SOURCE: "+this.word;
}
}
class CompilerError extends Error{}
function evalFully_step(startLazyExp,onSuccess=lazy=>lazy,onFail=lazy=>lazy,stack){//UNFINISHED
//startLazyExp:Lazy,onSuccess:Lazy->Exp,onFail:Lazy->Exp,stack:Stack
let isReducible=false;
let newExp = Object.assign(new Lazy(),startLazyExp);
startLazyExp.eval_mapCodeToExpresstions(stack).forEach((exp,i)=>{
newExp[i]=stack.doOnStack(newExp,exp,stack=>exp=Exp.eval(exp,stack));
if(Exp.isReducible(exp))isReducible=true;
});
if(isReducible)return onFail(newExp);
else return onSuccess(newExp);
}
class Lazy extends Exp_Array{//:Exp ; lazy evaluation
//Lazy : Exp[]
context;//:Context
labels;//:Map(string=>Reference)? ; if this exists then namespace-like labels are added to the expressiong when evaluated.
isList;//:bool; true=>'[]' , false=>'()'
constructor(...exps){
//if(exps.includes(undefined))throw Error("compiler error");
super(exps.length);
Object.assign(this,exps);
}
//note: all arguments are optional in curtain cases.
call(arg,context,stack){//(arg:Lazy,Stack)->Lazy
if(this.length == 1 && this[0] instanceof Lambda)return this[0].call(arg,this.context,stack);
else return this.eval(stack).call(arg,this.context,stack);
}//(a>a)(a>a a)
isSimplyReducible(exp){//exp:Exp|Array|any ; returns true if exp is valid to be parsed as `ans` in the `ans.map` part of `Lazy.prototype.eval``.
return (exp?.constructor == Array||exp instanceof Lazy) && exp.length==1 && (!exp.isList && !exp.labels) && (exp[0]?.constructor == Array||exp[0] instanceof Lazy);
}
//static isReducible(exp){return (exp instanceof Lazy || exp.constructor==Array &&!exp.labels)}
eval_mapCodeToExpresstions(exp,context=this.context){//:Lazy|(Array&([]Lazy)[])->Exp[]
return exp.map(v=>//[]->{call:(arg:Lazy,Stack)->Combinator|Lazy&{call:(Exp,Context,Stack,Number)->Lazy}}[]
typeof v == "number"?context.getValue(v):
typeof v == "string"?v://simple raw string cannot be called
//typeof v == "string"?:
v instanceof Lambda?Object.assign(new Lazy(v),{context,id:v.id}):
v instanceof RecurSetter?v.context?v:Object.assign(new RecurSetter(...v),{...v,context,id:v.id}):
v instanceof Reference?Object.assign(new Lazy(...v),{id:v.id,context:context.getContext(v.levelDif)}):
v instanceof Lazy?v.context?v:Object.assign(new Lazy(...v),{...v,context}):
v instanceof Exp||
v instanceof Exp_Array||
v instanceof Exp_String||
v instanceof Exp_Number?v:
v instanceof Array?Object.assign(new Lazy(...v),{context,id:v.id??this.id,isList:v.isList,labels:v.labels}):
/*v instanceof Object?(v=>{
let labels=new Map();
for(let i in v){
labels.set(i,Object.assign(new Lazy(v[i]),{}));
}
return new NameSpace(labels);
})(v):*/
v//uncallable object
);
}
eval(stack=new Stack()){
let context = this.context??new Context();
let startExp = this;
let ans = this;
{
//[x],Lazy(x),1::x -> x; where x:Lazy|Array|RecurSetter
while(this.isSimplyReducible(startExp))startExp=startExp[0];//assume: startExp is Tree
//startExp:Lazy|Array
context = startExp.context??context;
if(startExp.length == 0 && !startExp.labels&&!startExp.isList){
if(1)throw Error("compiler error: all null values should be delt with at compile time");
else return Lambda.null;
}
}
ans = this.eval_mapCodeToExpresstions(startExp,context);//ans:Lazy
//if(!startExp.id)throw Error("compiler error: list or lazy expression without an id");
ans = startExp.isList?Object.assign(new List(...ans),{id:ans.id||this.id}):
startExp.labels&&ans.length==0?undefined:
ans.reduce((s,v,i)=>stack.doOnStack(s,v,stack=>s.call(v,context,stack)))
;
if(startExp.labels){
let newLabels = new Map();
for(let [i,v] of startExp.labels){
newLabels.set(i,Object.assign(new Lazy(v),{context}).eval(stack));
}
ans = Object.assign(new NameSpace(newLabels,ans),{id:startExp.id});
}
if(0)if(ans!=this){//optimise for next time.
this.splice(0,this.length,ans);
this.labels = undefined;
this.isList = undefined;
}
return ans;
}
//; Lazy.evalFully
evalFully(stack=new Stack()){
let ans = this;
let bail =100000;
while(Exp.isReducible(ans)&&bail-->0)
ans = ans.eval(stack);
if(bail<=0)throw Error("possible compiler error: bailled. may be caused by:"
+"1. A compiler bug: probably within the Exp.isReducible function, or somethere else in the code"
+"2. An expression that takes many steps to evaluate;"
+"3. An expression that cannot be fully reduced (i.e. one that does not have a reduced form)"
);
return ans;
}
}
class Lambda extends Exp_Array{//:Exp
constructor(...exps){
super(exps.length);
Object.assign(this,exps);
}
id;//:WordData
static null = new class Null extends Exp{
call(arg){return arg}
toJS(){return null}
};
call(arg=undefined,context=new Context(),stack){
context = new Context(context,arg);
return Object.assign(new Lazy(...this),{context,id:this.id}).eval(stack);
}
}
class RecurSetter extends Exp_Array{//'value::recur'
constructor(...list){
super(list.length);
Object.assign(this,list);
}
recur;//:Lazy
context;//:Context?
id;//:WordData
getRecursLeft(stack){//()-> finite Number | Infinity
if(this.recur.length==1 && this.recur[0] == RecurSetter.forever)return Infinity;
let ans = stack.doOnStack(this,this.recur,stack=>Float.toInt(Object.assign(new Lazy(...this.recur),{id:this.recur.id,context:this.context}),stack));
if(+ans == Infinity||+ans<0||isNaN(+ans))ans = 0;//make finite
return ans;
}
eval(stack=new Stack){
return Object.assign(new Lazy(...this),{
context:new Context(this.context,undefined,this.getRecursLeft(stack)),
id:this.id,
}
).eval(stack);
}
toJS(){return this[0].toJS?.()}
static forever = new Lambda(new Lambda(0));
}
class Reference extends Exp_Array{//wrapper for Lazy
constructor(value){
super(1);
this[0]=value;
}
//value:Exp
levelDif//:Number
id//:WordData
get value(){return this[0]}
set value(v){this[0]=v}
call(arg,context=new Context,stack){
//context??= new Context();
stack.unshift(this.id);
let value = new Lazy(...this);
value.id = this.id;
value.context=context.getContext(this.levelDif);
let ans = value.call(arg,context,stack);
stack.shift();
return ans;
}
eval(stack){return this[0].eval(stack);}
toJS(){return this[0].toJS?.()}
};
class Context{
static null;//:Context
constructor(parent,argument,maxRecur){
Object.assign(this,{
parent,//:Context?
argument,//:Lazy|{String->Lazy}|Lazy[]
maxRecur,//:maxRecur
});
this.chainLen=(parent?.level??-1)+1;//:Number
}
get maxRecur(){
return this.maxRecurValue??this.parent?.maxRecur;
}
set maxRecur(value){
this.maxRecurValue = value;
}
getContext(num){
let context = this;
for(let i=0;i<num;i++){
context = context.parent;
}
return context;
}
getValue(num){
return this.getContext(num).argument;
}
}
Context.null = new Context();
class Stack extends Array{
currentMaxRecur = 1;//:Number ; mutable by RecurSetter.prototype.eval
constructor(...exps){
super(exps.length);
Object.assign(this,exps);
}
doOnStack(foo,arg,func){//arg:Exp|Any,foo:Exp|Any
let stackableObjects = [foo,arg];//expression that will be added onto the stack.
const data = foo.id;
let oldMaxRecur = data?.maxRecur;
let recurs = {value:0};//
if(!this.#add(foo,arg,recurs)){//recurs:mut
recurs = recurs.value;
//note: stack.add already removes the lambda from the stack, so it does not need to be done here.
//recursion detected
if(1){
data.throwError("recursion", "unbounded recursion detected. Recursion level: "+recurs+"",a=>Error(a),this);
}else return Lambda.null;
}else {}
let ans = func(this);
this.#remove(foo,arg);
if(data)data.maxRecur = oldMaxRecur;
return ans;
}
#add(exp,arg,recurs_out){
this.unshift(arg?.[Exp.symbol]?arg.id:undefined);
let id = exp.id;
if(id!=undefined){
this.unshift(id);
}
else return true;
if(1)return true;//TESTING: stack system sometimes doesn't work for unknown reasons
const stack = this;
let recursLeft= exp.context?.maxRecur ?? 1;
let data = id;
let [isValid,recurs] = this.stackCheck(data.maxRecur);
let newRecursLeft = recursLeft + recurs;
let isLen1 = exp instanceof Exp_Array?exp.length == 1:false;
//assume length 1 expressions can't recur infinitely since they don't call their parts
if(recurs <= 1 || isLen1 || newRecursLeft<data.maxRecur) data.maxRecur = newRecursLeft;
if(isLen1)isValid = true;
if(!isValid){
this.shift();
}
recurs_out.value = recurs;
return isValid;
}
#remove(lambda){
if(lambda.id==undefined)return;
this.shift();
this.shift();
}
stackCheck(maxRecur){//only checks last item
//:Number->[bool,Number]
if(maxRecur==Infinity||maxRecur>this.length)return [true,0];
let recurs=1;
let id = this.shift();
let lastId=this.indexOf(id);
if(this.length-lastId<maxRecur){
this.unshift(id);
return[true,2];//BODGED
}
let stackStr = this.join(",")+",";
let matchStackStr = this.map(v=>v).splice(0,lastId).join(",")+",";
this.unshift(id);
//recurs = [...stackStr.matchAll(matchStackStr)].length;
if(1){
if(lastId==-1)return [true,recurs];
for(let i=lastId+1;i<this.length;){
let isMatch=true;
if(this[i]!=id){i++;continue}
else i++;
if(i+lastId>this.length){return [true,recurs]}
if(lastId>0)
for(let i1=0;i1<lastId;[i1++,i++]){
if(this[i]!=this[i1+1]){isMatch=false;break;}
}
if(isMatch){
recurs++;
if(recurs>=maxRecur)return [false,recurs];
}
}
return [true,recurs];
}
return [recurs<=maxRecur,recurs];
}
}
//js functions:
class ArrowFunc extends Exp{//arraw function
constructor(func,id=new FilelessWordData({word:"function"})){
super();
this.func=func;
}
//isOperater:bool&Operator?
call(arg,context,stack){//Int->Int-> ... Int-> Int
return this.func(arg,context,stack);
}
toJS(){return this.func}
}
class MultiArgLambdaFunc extends Exp{//arraw function
constructor(func,len,args=[],id=new FilelessWordData({word:"function"})){
super()
this.func = func;//:(...Number[])->Number
this.len = len;
this.args = args;//:Lazy[]
this.id = id;
}
//isOperater:bool&Operator?
call(arg,context,stack){//Int->Int-> ... Int-> Int
if(this.args.length>=this.len-1)
return this.func([...this.args,arg],context,stack);
else return Object.assign(new this.constructor(),{...this,args:[...this.args,arg]});//TODO: add separate id's for different parts of the function.
}
toJS(){return (...args)=>this.func([...args])}
}
class Func extends MultiArgLambdaFunc{
constructor(func,len,args=[],stack=undefined){
super(func,func?.length);
}
call(arg,context,stack){//Int->Int-> ... Int-> Int
if(this.args.length>=this.len-1)
return Exp.fromJS(this.func(...[...this.args,arg].map(v=>Exp.toJS(Exp.evalFully(v,stack))),context,stack));
else return Object.assign(new this.constructor(),{...this,args:[...this.args,arg]});//TODO: add separate id's for different parts of the function.
}
toJS(){return this.func}
}
class JSWrapper extends Exp{//for getting properties from
constructor(value){super();this.value = value}
#value;
get value(){return this.#value};//:Object
set value(v){this.#value = v}
call(arg,context,stack){
return typeof this.value=="function"?Exp.fromJS(this.value(arg)):Lambda.null;
}
toJS(){return this.value}
}
class NameSpace extends Exp{//'{a b c}' and '{a<=1,b<=2,c<=3}'
constructor(labels,exp,id){//labels:Map(string,Exp)|JSON-like object
super();
if(!(labels instanceof Map)){
this.labels=new Map();
for(let i in labels){
this.labels.set(i,labels[i]);
}
}
else this.labels = labels;
this.exp = exp;
}
labels;//labels:Map(string,Exp)
exp;//: Exp?
call(arg,context,stack){
if(Exp.isReducible(this))return this.evalFully().call(arg,context,stack);
if(this.exp)return this.exp.call(arg,context,stack);//{a>a a} x -> (a>a a) x
if(arg instanceof NameSpace)return new NameSpace(new Map([...this.labels,...arg.labels]),arg.exp);
else return new NameSpace(this.labels,arg);
}
eval(stack){
stack??=new Stack();
//if(!Exp.isReducible(this.exp))return this;
let exp=stack.doOnStack(this,undefined,stack=>Exp.eval(this.exp,stack));
if(exp instanceof NameSpace)return new NameSpace(new Map([...this.labels,...exp.labels]),this.exp.exp);
if(exp instanceof JSWrapper){if(exp.value!=undefined)this.labels.forEach((v,i)=>exp.value[i]=Exp.toJS(Exp.evalFully(v,this,stack)));return exp}
return new NameSpace(this.labels,exp);
}
toJS(){
let newObj = {};
for(let [i,v] of this.labels){
newObj[i]=!v?.[Exp.symbol]?v:v.evalFully().toJS()??v;
}
let value = this.exp?.[Exp.symbol]?this.exp.evalFully().toJS():this.exp;
if(this.exp==undefined||this.exp==Lambda.null)return newObj;
else return Object.assign(value,newObj)
}
static get = new class NameSpace_Get extends MultiArgLambdaFunc{}(function get([obj,property],context,stack){
stack.doOnStack(this,obj,stack=>{
obj = obj.evalFully(stack);
});
stack.doOnStack(this,property,stack=>{
property = property.evalFully(stack);
});
getIndex:if(property instanceof Float){
if(obj instanceof List)return obj[property|0]??List.null;
if(obj instanceof NameSpace)break getIndex;
}
else if(!(property instanceof StringExp))return Lambda.null;
let propertyStr = ""+property;
if(!obj[Exp.symbol]){
return Exp.fromJS(obj[propertyStr]);
}
if(obj instanceof Func){
if(propertyStr=="length"){
return new Int(obj.len);
}
else return Lambda.null;
}
else if(obj instanceof NameSpace){
let ans = obj.labels.get(propertyStr);
if(ans)return ans;
if(obj.exp)return get([obj.exp,property],context,stack);
if(!ans)return Lambda.null;
}
else if(obj instanceof List){
if(propertyStr=="length"){
return new Int(obj.length);
}
if(List.methods.has(propertyStr))return List.methods.get(propertyStr).call(obj,context,stack);
}
else if(obj instanceof JSWrapper){
let ans = obj.value?.[propertyStr];
if(typeof ans == "function")ans = ans.bind(obj.value);
return Exp.fromJS(ans);
}
return Lambda.null;
obj instanceof List ||
obj instanceof Float ||
obj instanceof StringExp
Lambda.null
},2);
static assign_id = new FilelessWordData({word:"assign part"});
static set = new class NameSpace_Set extends MultiArgLambdaFunc{}(function([nameSpace,property,value],context,stack){
return stack.doOnStack(new Exp({id:NameSpace.assign_id}),undefined,stack=>{
const tryAgain = ()=>new Lazy(new this.constructor(this.func,this.len,[nameSpace,property],this.id),value);
if(Exp.isReducible(property))property = stack.doOnStack(NameSpace.assign_id,property,stack=>property.eval(stack));
if(!(property instanceof StringExp || property instanceof Float))return nameSpace;
if(Exp.isReducible(property))return tryAgain();
else {
if(property instanceof Float && !(nameSpace instanceof NameSpace)){
property = +property;
if(Exp.isReducible(nameSpace))nameSpace = stack.doOnStack(NameSpace.assign_id,nameSpace,stack=>nameSpace.eval(stack));
if(Exp.isReducible(nameSpace))return tryAgain();
if(nameSpace instanceof List){
let newList = Object.assign(new List(...nameSpace),{id:nameSpace.id});
if(!isNaN(property)&&Math.abs(property)!=Infinity&&property>=0)newList[property|0] = value;
return newList;
}
else return Lambda.null;
}
else if(property instanceof StringExp){
//asseert: nameSpace:NameSpace|reducable expression
let propertyStr = ""+property;
nameSpace = Exp.evalFully(nameSpace,stack);
if(!(nameSpace instanceof NameSpace))return new NameSpace(new Map([[propertyStr,value]]),nameSpace,property.id);
let newObj = new NameSpace(new Map(nameSpace.labels),nameSpace.exp,property.id);
newObj.labels.set(propertyStr,value);
return newObj;
}
return Lambda.null;
}
});
},3)
static dot = this.get;
}
class Float extends Exp_Number{
constructor(value){
super(value);
}
toJS(){return+this}
static Part1 = class IntPart extends Exp{
constructor(value,arg_f){
super();
this.value = value;//:Number|Int
this.arg_f = arg_f;//:Lazy
}
call(arg_x,context,stack){//(f>x>n f x,arg_f,arg_x)
if(this.arg_f == Float.increment && arg_x instanceof Float)//optimises 'n ++ 0'
return new (arg_x instanceof Int?Int:Float)(1+arg_x);
let ans = arg_x;
for(let i = 0;i<this.value&&i<1000000;i++){
ans = this.arg_f.call(ans,context,stack);
if(i+1>=1000000)throw Error("bailed");
}
return ans;
}
};
static increment = new class Increment extends Exp{
//n> f>x>f(n f x)
call(arg,context,stack){return new Int(arg+1)??this.lazyExpVersion.call(arg)};
eval(stack){return this};
lazyExpVersion=new Lambda(new Lambda(new Lambda(1,[2,1,0])));
};
toInt(foo,stack){//foo:{call(inc)->{call(0)->Number}}
return this.constructor.toInt(foo,stack);
}
call(arg_f){//f>x>
if(Exp.eval(arg_f,this) instanceof Float)return new this.constructor(arg_f**this);
return new this.constructor.Part1(this,arg_f);
}
static toInt(foo,stack=new Stack){//foo:{call(inc)->{call(0)->Number}}
//if(Exp.isReducible(foo))return new Lazy(Exp.eval(foo,foo,stack,1));
foo = Exp.fromJS(foo);
foo = foo.evalFully(stack);
if(foo instanceof Float)return foo;
const inc = Int.increment;
const zero = new Int(0);
let ans = foo.call(inc,undefined,stack).call(zero,undefined,stack);
return ans?.eval?.(stack)??ans;
}
}
class Int extends Float{
constructor(value){
super(value|0);
}
}
class Calc extends ArrowFunc{//calculation
constructor(func,fallBackExp,args=[]){
super(func)//func:(...Number[])->Number
this.fallBackExp = fallBackExp;//:Exp
this.args = args;//:Lazy[]
}
//isOperater:bool&Operator?
call(arg,context,stack){//Int->Int-> ... Int-> Int
let args = [...this.args,arg];
if(args.length>=this.func.length){
const ans = this.func(...args.map(v=>+Float.toInt(v,stack)));
const nullValue = Lambda.null;
return typeof ans == "number"?
isNaN(ans)?
this.fallBackExp?
args.reduce((s,v)=>s.call(v),this.fallBackExp)
:nullValue//args.reduce((s,v)=>s.call(v,context,stack),this.fallBackExp)
:(ans|0)==ans?new Int(ans):new Float(ans)
:ans??nullValue
;//can return custom Exp objects.
}
return new this.constructor(this.func,this.fallBackExp,[...this.args,arg],stack)
}
eval(stack){return this}
}
class List extends Exp_Array{
//linked list. '[x y]' -> 'end> bool>a x bool>bool y end'
constructor(...list){
super(list.length);
Object.assign(this,list);
}
end;//:Exp?
static falseExp = Object.assign(new Lambda(Object.assign(new Lambda(0),new FilelessWordData({word:"const"}))),new FilelessWordData({word:"false"}));//TODO: add IDs
static getTailExp = new MultiArgLambdaFunc(([list],c,s)=>list.call(this.falseExp,c,s),2,[],new FilelessWordData({word:"list.getTail"}));
getItem(index,context,stack){
let end;
const defaultExp = ()=>index.call(List.getTailExp,context,stack);
return stack.doOnStack(this,stack=>
index instanceof Float?
index|0<this.length?this[index|0]:
(this.end=end.evalFully()) instanceof List?end.getItem(new Int(index-this.length),context,stack):
defaultExp()
:defaultExp()
);
}
static #ListWithEnd = class extends Exp{
constructor(list,end,id){
super();
this.#list=list;
this.#end = end;
this.id = id;
if(this.#list.length<1)throw Error("compiler error");
}
#list;//:List|Array
#end;//:Exp
id;//:ID
call(arg,context,stack){
let bool = arg;
let head = this.#list[0];
let tail;
if(this.#list.length == 1)tail = this.#end;
else{
tail = new this.constructor([...this.#list],this.#end,this.id);
tail.#list.shift();
}
return bool.call(head,context,stack).call(tail,context,stack);
}
}
call(arg,context,stack){
let id = this.id;
return new this.constructor.#ListWithEnd(this,arg,id);
//this.constructor.concat.call(this,context,stack).call(arg,context,stack);
}
eval(){return this}
toJS(){return [...this.map(v=>v[Exp.symbol]?v.evalFully().eval().toJS():v)]}
static null = new class EndOfList extends Exp{
toJS(){return null};
call(){return this}
}//a>(a>b>a a,a>b>a a)
static toList(exp,stack){
exp = Exp.evalFully(exp,stack);
if(exp instanceof List)return exp;
return Object.assign(new List(),exp.id);
}
static get = new class List_Get extends MultiArgLambdaFunc{}(([array,index],context,stack)=>{
let ans;
array=array.evalFully(stack);
if(array instanceof List)ans = array[index.evalFully(stack)|0];
return ans??Lambda.null;
},2);//is defined later
static concat = new class List_Concat extends MultiArgLambdaFunc{}(([listA,listB],context,stack)=>{
listA=listA.evalFully(stack);
listB=listB.evalFully(stack);
return Object.assign(
listB instanceof List?new List(...listA,...listB)
:listA instanceof List?new List(...this,listB)
:new List(listA,listB)//'[1 2] 3' => '[1 2] [3]' => '[1 2 3]'
,{id:listA.id})
},2);
static #spairIDs = {
int:new FilelessWordData({word:"List_int"}),
list:new FilelessWordData({word:"List_list"})
};
static map = new class List_Map extends MultiArgLambdaFunc{}(
([list,foo],context,stack)=>stack.doOnStack(List.map,foo,stack=>
(list=this.toList(list,stack)) instanceof List?
Object.assign(
list.map(
(v,i,a)=>foo.call(
Object.assign(new List(v,Object.assign(new Int(i),this.#spairIDs.int),a),this.#spairIDs.list),
context,
stack
),
),
{id:list.id}
)
:Lambda.null
)
,2);
//similar to Int(), same as 'l>f>x>l.length ([s i a]>[f[s l.(i) i a] ++i a])[x 0 l]'
static forEach = new class List_Map extends MultiArgLambdaFunc{}(
([list,foo,startingState],context,stack)=>stack.doOnStack(List.forEach,foo,stack=>
(list=this.toList(list,stack)) instanceof List?list.reduce(
(s,v,i,a)=>foo.call(
Object.assign(new List(s,v,Object.assign(new Int(i),this.#spairIDs.int),a),this.#spairIDs.list),
context,stack),
startingState)
:Lambda.null
)
,3);
//same as 'l>f>l.length ([s i a]>[f[s l.(i) i a] ++i a])[l.(0) 0 l]'
static reduce = new class List_Map extends MultiArgLambdaFunc{}(
([list,foo],context,stack)=>stack.doOnStack(List.map,foo,stack=>
(list=this.toList(list,stack)) instanceof List?list.reduce(
(s,v,i,a)=>foo.call(
Object.assign(new List(s,v,Object.assign(new Int(i),this.#spairIDs.int),a),this.#spairIDs.list),
context,stack),
):Lambda.null
)
,2);
static methods = new Map([
["get",this.get],
["concat",this.concat],
["map",this.map],
["forEach",this.forEach],
["reduce",this.reduce],
]);
}
class StringExp extends Exp_String{
constructor(string){
super(string);
}
call(arg,context,stack){
if(arg instanceof StringExp)return new StringExp(this+arg);
else return List.concat.call(this,context,stack).call(arg,context,stack);
}
toJS(){return""+this}
}
class AsyncExp extends Exp{
//may be UNFINISHED
//mainly for importing files
constructor(promise,callList,id){
super();
this.id = id??undefined;
this.promise = promise;
promise.then(value=>{
this.value = value;
this.isReducible = true;
});
this.callList = callList??[];
}
id;//:ID
value = undefined;//:Exp?
isReducible=false;//:bool ; is set to true when the promise resolves.
call(arg,context,stack){
if(this.isReducible)return stack.doOnStack(this,arg,stack=>[...this.callList,arg].reduce((s,v)=>s.call(v,context,stack),this.value));
else return new this.constructor(this.promise,[...this.callList,arg]);
}
eval(stack){
if(this.isReducible)return stack.doOnStack(this,arg,stack=>value.call());
else return this;
}
}
{
let globals = (()=>{
let obj = {};
try {obj["window"]=window;} catch(e){}
try {obj["process"]=process;} catch(e){}
try {obj["global"]=global;} catch(e){}
for(let i in obj)obj[i]=Exp.fromJS(obj[i]);
return obj;
})();
var JSintervace = new NameSpace({
...globals,
//"new":new MultiArgLambdaFunc(()),
});
}
for(let [i,v] of JSintervace.labels)
if(v!=Lambda.null)v.id = new FilelessWordData({word:"SOURCE: JS intervace: "+i});
{//old unued code
//const Y = new Lambda(new Lambda(0,0),new Lambda(new Lambda(2,0),[0,0]));
let Y = new Lambda(new Lambda(1,[0,0]),new Lambda(1,[0,0]));
let vec2 = new Lambda(new Lambda({x:1,y:0}));//x>y>{x y}
let recur = new Lambda();
}
//----
function loga(...logs){console.log(...logs);return logs[0]};
let files_startId;
{
[
[Int.prototype,"Int"],
[Calc.prototype,"Calc"],
[ArrowFunc.prototype,"Function"],
[Int.increment,"increment"],
...[...List.methods].map(v=>[v[1],[v[0]]]),
[RecurSetter.forever,"forever"],
[RecurSetter.forever[0],"forever"],
[NameSpace.get,"get"],
[NameSpace.set,"set"],
].forEach(v=>files.addInbuilt(...v));
}
{
//compiler classes
class Pattern{
constructor(data){
Object.assign(this,data);
}
id;//:WordData
type="operator";//:"operator"|"word"|"number"|"symbol"|"function"|"assignment"
parent;//:BracketPattern
isFirst;//:bool ; Is true if this is the start of a list, or can be used as the starting function.
typeAnnotation;//:?Type
//optionals
pattern;//:?String & word
options;//:?String & joined words
params;//:?(String & word) | Tree<String>
publicLabels;//:?Param[]
list;
//
usingLabels;//:?string[] if '()>'|Map(String,Param) if '()=>'; for '()>' and '()=>'
}
class Type{
properties = new Map();//:Map(string|number => Type|Pattern)
}
let num=0;//is for TESTING and debugging only
class BracketPattern extends Pattern{
constructor(data){super();this.num = num++;Object.assign(this,data);}
num=0;
parent;
pattern='()';//'()'|'[]'|'{}'
list=[];//:Tree<Pattern> ; brackets only
id;//:WordData
}
class Simple extends Pattern{
constructor(data){super();Object.assign(this,data)}
//pattern:undefined;
set parent(v){this.#parent=v}
get parent(){return this.#parent}
#parent;
arg;//:String
type;
value;//:Code
ref;//:Param?
}
class Pattern_extra{
//BracketPattern
startLabels;//:Map(String,Ref)
currentLabels;//:Map(String,Ref)
publicLabels;//:Map(String,Ref)?
refs;//:Set(Pattern) & Tree(Pattern)
refLevel;//:Number
funcLevel;//:Number ; number of nested lambdas
//on '=' only
isUsed;//:bool ; For assignment patterns only. Is true if at least one reference to this label exists.
//on 'a.b=' only
firstValue;//:simple|null
//on '()=' only
withBlock_isLeftArg;//:bool ;
//used by the `refs` object only
//refs:Map(Pattern&!Simple => Simple[])
//isSearched:bool,
//pathNumber:Number,
}
class Param{
constructor(data){Object.assign(this,data)}
name;//:[String,ID] ; name of the parameter or label, where `name[0]==name[1].word`
index;//:number ; if a pattern has muli parameters it shows which one it is.
owner;//: Pattern & context with a {list:Array} ; is the expression that the label bellongs to
value;//: Lazy? ; only for assignment patterns
}
class Operator extends Param{
static owner = new BracketPattern({id:new FilelessWordData({word:"operator"})});
constructor(name,priority,foo,length=2){
//assume this.name[1] is not used
super({name:[name,undefined],priority,owner:Operator.owner,value:foo});
this.value.operatorParamObj = this;//:truthy
this.length = length;
}
toJSON(){return "operator:"+this.name};
isParsed=false;
//name:[String,Number]
//index:Number
//owner:Pattern
//value:Lazy
//priority:Number
//length:Number
}
//----
const globalContext = new BracketPattern;
let maxPriority;
assignGlobal:{
//applies to Patterns with type = "operator"
const bool_true = new class True extends Lambda{}(new Lambda(1));
const bool_false = new class False extends Lambda{}(new Lambda(0));//new Int(0);
const equality = (a,b)=>//(Exp,Exp)-> Lambda bool
(a=a.eval())==(b=b.eval())?bool_true
:a instanceof Array?
!(b instanceof Array)?bool_false
:!(a.constructor == b.constructor)?bool_false
:a.length != b.length?bool_false
:a.reduce((s,v,i)=>s==bool_false?s:equality(a[i],b[i]),bool_true)
:b instanceof Array?equality(b,a)
:+a==+b?bool_true//assume: NaN!=NaN
:bool_false
;
let i=0;
const assign_id = new FilelessWordData({word:"="});
Operator.owner.startLabels=Operator.owner.publicLabels = new Map([
["!" , i,new Lambda(0,bool_false,bool_true)],//new ArrowFunc((a,globalContext,stack)=>Float.toInt(a,stack)==0||a==Lambda.null?bool_true:bool_false),1],
["~" , i,new Calc((a)=>~a),1],
["++", i,new Calc((a)=>a+1,new MultiArgLambdaFunc(([a,f,x],c,s)=>f.call(a.call(f,c,s).call(x,c,s),c,s),3)),1],
["--", i,new Calc((a)=>a-1),1],
["&" ,++i,new Calc((a,b)=>a&b),2],
["|" , i,new Calc((a,b)=>a|b),2],
["^" , i,new Calc((a,b)=>a^b),2],
["%" , i,new Calc((a,b)=>a%b),2],
["**", i,new Calc((a,b)=>a**b,new MultiArgLambdaFunc(([a,b],context,stack)=>b.call(a,context,stack),2)),2],
["*" ,++i,new MultiArgLambdaFunc(([a,b],c,s)=>//a>b>f>a (b f)
(a=Exp.evalFully(a,s)) instanceof List && (b=Exp.evalFully(b,s)) instanceof List ?Object.assign(new List(...a,...b),{id:a.id}):
a instanceof StringExp && b instanceof StringExp ?Object.assign(new StringExp(a+b),{id:a.id}):
a instanceof Float && b instanceof Float?new Calc((a,b)=>a*b):
new ArrowFunc((f,c,s)=>a.call(b.call(f,c,s),c,s),{id:a.id})
,2),2],
["/" , i,new Calc((a,b)=>a/b),2],