Repository navigation
Expand file tree
/
Copy pathmain.ts
More file actions
1661 lines (1655 loc) · 70.6 KB
/
Copy pathmain.ts
File metadata and controls
1661 lines (1655 loc) · 70.6 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
//TODO: work on 1634 `function getDeclarationFromAutoparameter` ; implementing '##' '#@' '#?' get parameters for '\', 'if', 'else' etc..
//1263 build type class for the language's type system
//name suggetions: quad`.qd` (the Quick Unreadable And Dirty programming language), `.cr` Crunch
//TODO: add code to support '::=' making '::' have the same syntax as ':'
import {methods as Public_Object} from "./qualityOfLife.ts";
const {
todo,
unimplemented,
loga,
logData,
match,
pass,
assert,
assume,
forBailOld,
forBailGenerator,
matchFlags,
EnumSymbols,
getFile_expect,
silentError,
} = Public_Object;
Public_Object.printTree = printTree;
const fs = Deno;//require("fs");
//compiles simple lambda calculus
//tokeniser
import {tokeniser_module_method} from "./tokeniser.ts";
const {SyntaxTree, WordSymbol} = tokeniser_module_method(Public_Object);
Object.assign(Public_Object,{
SyntaxTree,
WordSymbol,
});
//parse tokens list into AST
import {parseIntoOperatorSyntaxTree_function} from "./parseOperatorSyntaxTree.ts"//:Function
const parseIntoOperatorSyntaxTree:Function =
parseIntoOperatorSyntaxTree_function(Public_Object);
//main compiler logic
//const InferedProperty = Symbol("`.b` ; infered")//`.b`
function getNumberOfWords(rootPattern:Expression[]){
return !rootPattern[0]?0:rootPattern[0].wordSymbol.errorData.file.words.length;
}
function parseAST(rootPattern:Expression[]):Expression[]{//static code parsing to add extra info ; handles function parameter indexes
const {Expression} = parseIntoOperatorSyntaxTree;
const numberOfWords = getNumberOfWords(rootPattern);
link_up_auto_parameters:{//links '#' patterns with their respective function/statement
class Context_parseAST{
function?:{
autoParameterIndex:uint,
isObscuredByInnerClass:bool,//for `exp` in `\{/exp}`
functionExp:Expression,
};
statementData?:{//operators that use '#@'; each '#@' refers to a different one
statementExp:Expression<SyntaxTree.subtype.Statement|Any>,
nextAutoParameterIndex:uint,//`#@`
nextArgumentIndex:uint,//`in exp`
params:Expression[],//used to address params for errors in `for in` statements (when not enough parameters)
};
forIn_statement?:&Context_parseAST.statementData;//reference to the last for statement
parameters:{
"#?"?:(&Expression)[],
"#!"?:(&Expression)[],
"#/"?:(&Expression)[],
"#\\"?:(&Expression)[],
"#.."?:(&Expression)[],
} = {};
};
const getParameterIsSingleUse = (word:String)=>match(word,[//if e.g. `#@ == #@` is always true
["#?",()=>true],
["#@",()=>true],
["#!",()=>true],
["#/",()=>true],
["#\\",()=>true],
["#..",()=>true],
[["##","#"],()=>true],
["#.",()=>true],
]);
interface Expression{//Expression<SyntaxTree.subtype.autoParameter>
autoParameterIndex?:Number&Index;//for '#name' and '##'
paramRef?:&Expression;//for '#?', '#@', etc...
}
function forEachExp(exps:Expression[],context:Context_parseAST,paramPath?:ParamPath){//`...` in `(...)`
for(let exp of exps)if(!!exp)forEachExpSingle(exp,context,paramPath)
}
function forEachExpSingle(exp:Expression,context:Context_parseAST,paramPath?:ParamPath){
function throwMissingPropertyError(dotExpression){//`(a.b.c).`
dotExpression.wordSymbol.throwError("syntax","missing property at the end of property chain",e=>Error(e));
}
match(exp.wordSymbol.type,[
[[SyntaxTree.type.value,SyntaxTree.type.label],_=>{}],
[[SyntaxTree.type.bracket],_=>{
const bracket = exp;
forEachExp(exp.contence,context,paramPath)
if(exp.args)forEachExp(exp.args,context,paramPath)
}],
[[SyntaxTree.type.operator],_=>{
if(exp.wordSymbol.subtype == SyntaxTree.subtype.autoParameter || exp.wordSymbol.word == "in"){
let parentExp = match(exp.wordSymbol.word,[
[["#@"],_=>{
if(!context.statementData)return undefined;//throws error later
exp.autoParameterIndex = context.statementData.nextAutoParameterIndex++;
context.statementData.params.push(exp);
return exp.paramRef = context.statementData.statementExp;
}],
[["#","##"],_=>{
if(context.function?context.function?.isObscuredByInnerClass:!!context.parameters["#/"])return exp.paramRef = context.parameters["#/"];
if(!context.function)return undefined;
exp.autoParameterIndex = context.function.autoParameterIndex++;
return exp.paramRef = context.function.functionExp;
}],
[["#/","#\\","#..","#?","#!","#."],_=>{//non-single use parameters ;
if(getParameterIsSingleUse(exp.wordSymbol.word)){
exp.paramRef = context.parameters[exp.wordSymbol.word]?.pop?.();
exp.autoParameterIndex = context.parameters[exp.wordSymbol.word]?.length;
}
else{
exp.paramRef = context.parameters[exp.wordSymbol.word]?.[0];
exp.autoParameterIndex = context.parameters[exp.wordSymbol.word]?.length-1;
}
return exp.paramRef;
}],
["in",()=>{
if(!context.forIn_statement)return undefined;
exp.paramRef = context.forIn_statement.statementExp++;
exp.autoParameterIndex = context.forIn_statement.nextArgumentIndex++;
}],
]);
if(!exp.paramRef){
let missingStatementName = match(exp.wordSymbol.word,[
[["#", "##", "#\\", "#.."],()=>"function"],
[["#?"],()=>"if expression"],
[["#\\"],()=>"class"],
[["in"],()=>"for-in expression"]
],()=>"expression");
exp.wordSymbol.throwError("syntax",`missing ${missingStatementName} for parameter`,e=>Error(e));
}
}
function addStatementParameter(parameterName,isForLoop){
let newParmaters = {...(context.parameters??{})};//deep clone parameters
let newContext = {...context,parameters:newParmaters};
if(isForLoop){
newContext.forIn_statement = newContext.statementData
newContext.statementData = {
statementExp:exp,
nextAutoParameterIndex:0,
nextArgumentIndex:0,
params:[],
};
}
if([].includes(parameterName)){
newContext.parameters[parameterName]=[exp];
}
else {//stackable
newContext.parameters[parameterName]??=[];
newContext.parameters[parameterName].push(exp);
}
if(parameterName == "#\\"){
newContext.function = {
autoParameterIndex:0,
functionExp:exp,
isObscuredByInnerClass:false,
};
newContext.parameters["#.."] = [exp];
}
else if(parameterName == "#/"){
if(newContext.function)newContext.function.isObscuredByInnerClass = true;
newContext.parameters["#."] = [exp];
}
forEachExp(exp.args,newContext,paramPath);
}
match(exp.wordSymbol.word,[
["\\",()=>addStatementParameter("#\\")],
[word=>word == "/" && exp.afix == Expression.AfixType.prefix,()=>addStatementParameter("#/")],
[["if", "else"],()=>addStatementParameter("#?")],
["for",()=>addStatementParameter("#@",true)],
["match",()=>addStatementParameter("#@")],
["if",()=>addStatementParameter("#?")],
],()=>{forEachExp(exp.args,context,paramPath);})
}],
[[SyntaxTree.type.sepparator],()=>assert.impossibleCase("is removed by AST generator")],
])
}
forEachExp(rootPattern,new Context_parseAST(),null)
}
return rootPattern;
}
javascript_mods:{
Object.assign(Array.prototype,{
call(index){return this[arg]},
})
for(let i of [
"E" , "LN10" , "LN2" , "LOG10E" , "LOG2E" , "PI" , "SQRT1_2" , "SQRT2" , "TAU" , "abs" , "acos" , "acosh" , "asin" , "asinh" , "atan" , "atan2" , "atanh" , "cbrt" , "ceil" , "clz32" , "cos" , "cosh" , "exp" , "expm1" , "floor" , "fround" , "hypot" , "imul" , "log" , "log10" , "log1p" , "log2" , "max" , "min" , "pow" , "random" , "round" , "sign" , "sin" , "sinh" , "sqrt" , "tan" , "tanh" , "tau" , "trunc"
]){
if(typeof Math[i] == "function"){
if(Math[i].length == 1)
Object.defineProperty(Number.prototype,i,{
get(){return Math[i](this)},
enumerable: false,
configurable: true,
});
else
Number.prototype[i] = function(...args){
return Math[i](this,...args);
};
}
globalThis[i] = Math[i];//Object.assign(window,Math);
}
}
function runAST(rootPattern:Expression[]):Expression[]{
const {Expression} = parseIntoOperatorSyntaxTree;
const numberOfWords = getNumberOfWords(rootPattern);
//classes:
interface Expression{
typeAnnotation?:Expression<"::"> & Tree<Expression>;
}
const defualtFunctionsInternal = {
map(self:Array,mapFunc){
assert(self instanceof Array);
return self.map((v,i,a)=>functionCall(mapFunc,[v,i,a]))
},
reduce(self:Array,start,foo){
assert(self instanceof Array);
let innerFunction = arguments.length>2?foo:start;
let reduceFunction = (s,v,i,a)=>functionCall(innerFunction,[s,v,i,a]);
return self.reduce(
...([[reduceFunction],[reduceFunction,start]][+(arguments.length>2)])
);
},
reduceForNumber(self:Number,start,foo){
assert(typeof self == "number");
let innerFunction = arguments.length>2?foo:start;
let reduceFunction = (s,v,i,a)=>functionCall(innerFunction,[s,i,a]);
return new Array(self).fill().reduce(
...([[reduceFunction,null],[reduceFunction,start]][+(arguments.length>2)])
);
},
iterate(self:Number,foo):Array{
return new Array(self).fill().map((_,i)=>functionCall(foo,[i]))
},
repeat(self:Number,foo):void{
for(let i=0;i<self;i++)functionCall(foo,[i]);
},
};
const commonDefaultProperties = {
"js":{get(self):Value_Derefed{return toJSValue(self)}},//to javascript object
"log"(v){console.log(...arguments);return v},
};
const defaultFunctions_ObjectValue = {
"="():Array{return defualtFunctionsInternal.map(this.array,...arguments)},
">"():Value{return defualtFunctionsInternal.reduce(this.array,...arguments)},
"||":{get(self):Value{return self.array.length}},//length
...commonDefaultProperties,
};
const defaultFunctions_Array = {
"="():Array{return defualtFunctionsInternal.map(this,...arguments)},
">"():Value{return defualtFunctionsInternal.reduce(this,...arguments)},
"||":{get(self):Value{return self.length}},//length
...commonDefaultProperties,
};
const defaultFunctions_number = {
"<"():Array{return defualtFunctionsInternal.iterate(+this,...arguments)},
"="():Array{return defualtFunctionsInternal.repeat(+this,...arguments)},
">"():Value{return defualtFunctionsInternal.reduceForNumber(+this,...arguments)},
"r"():Value{return Math.random()*this},
...commonDefaultProperties,
};
const defaultFunctions_all = {};
type Name = String|Symbol|Index;
type Index = Number∬
type Index<array> = Number∬//index on object `array`
//where: array[index] : Valid
type Value =
ValueWrapper|
PropertyRef|PropertyRef<isReturnable<true>>|
ValueRef|
Value_Derefed
;
type Value_Assignable =
ValueWrapper|
Value_Returnable
;
type Value_Unwraped =
PropertyRef|
Value_Returnable
;
type Value_Returnable =//can pass through functions ; is derefed when storing or
PropertyRef<isReturnable<true>>|
Value_Storable
;
type Value_Storable =
ValueRef|
Value_Derefed
;
type Value_Derefed =//used when getting actual value for operators `a+b`
ObjectValue|
Name|
Index|
Value_Javascript
;
type PropertyRef<isReturnable=true|false> = PropertyRef & {isReturnable};
type Value_Javascript = Any & (
Number|
String|
Array<Any>|
Object|//JSON-like object
Function|
null
);
type ArgumentObj = ObjectValue | Array&Value_Storable[] | Object&{[Any]:Value_Storable}
const isSearched = Symbol("searched");
class PropertyDataInternal{//internal class, cannot be returned by an expression
constructor(data={}){Object.assign(this,data);}
parentValueObject?:ObjectValue;//owner of this.parent used for 'this' in function calls
parent:Object|Array;
name:Name|Index;
value:Option<Value>;//where: value == parent[name]
errorWordSymbol?:WordSymbol;
valueExists:bool = true;//used by Namespace
//:false --> `a:...` can only be declared ; true --> variable already exists
canAssignToValueRef:bool = false;//set true by `&a`; allows `b = &a`
get(){//: this:Invalid ; note if it returned a ValueRef then it would always link variables ; e.g. `a:0;b:&a;b++;c:b;c++;assert a==b!=c`
if(this.value instanceof ValueRef)
return this.value.get();
return this.value;
}
set(value:Value_Storable,isDeclaration):Value&consumes<this>{//: this:Invalid
if(!isDeclaration && this.parent[this.name] instanceof ValueRef && !(value instanceof ValueRef)){//allows for linked variables
this.parent[this.name].set(value);
}
else this.parent[this.name] = value;
return new this.constructor({...this,value})
}
}
class PropertyRef extends PropertyDataInternal{//:Value ; used in expressions
constructor(data={}){super();Object.assign(this,data);}
isReturnable:bool = false;//`foo() = exp` ; allows returning assignable properties through functions
static new(data:Option<PropertyDataInternal>):Option<PropertyRef>{
return data && new PropertyRef(data);
}
deref(){
if(this.isReturnable){
return new PropertyRef({...this,isReturnable:false});
}
else return this.get();
}
derefFully(){return derefValueFully(this.get());}//ignores storable PropertyRefs
}
class ValueRef{//value wrapper ; similar to PropertyRef but for shared variables
constructor(data={}){Object.assign(this,data);assert(!(this.value instanceof PropertyDataInternal),)}
value:Value_Derefed;
static fromValue(value:Value|ValueRef):ValueRef{
value = derefValue(value);
if(value instanceof PropertyRef)value = value.get();//BODGED: use a function for (Value)->Value_Derefed|ValueRef
//assert value:Value_Derefed | ValueRef
return value instanceof ValueRef?value:
new ValueRef({value:derefValue(value)})
;
}
deref(){return this;}
derefFully(){return derefValueFully(this.value);}//ignores storable PropertyRefs
get(){return this.value}
set(value){return this.value = value}
}
class ValueWrapper{//for passing extra data between statements
constructor(data={}){Object.assign(this,data);}
value:Value;
unwrap(){return unwrapValue(this.value);}
deref(){return derefValue(this.value);}
derefFully(){return derefValueFully(this.value);}//ignores storable PropertyRefs
static Typed = class Typed{
type:Expression|Value;
}
}
class ValueStatementWrapper{//UNUSED
constructor(data={}){Object.assign(this,data);}
value:Value;
statementReturnValue?:{value:Value};//e.g. `a` in `if a=>a else 0` ; used by statements like 'if'/'else' to pass data between them; stores the return value of a statement
}
class ValueWrapperReturnValue extends ValueWrapper{//returned by `a>b` ; `if 3>2 #?` == 3
constructor(data={}){super();Object.assign(this,data);}
value:Value;
boolReturnValue:Value;
}
class FunctionObj{
constructor(data={}){Object.assign(this,data);}
toTree(){return this.exp.toTree();}
toString(){return "\\ function";}
context:Context;
exp:Expression<"\\",[":"&{args:params&Expression[]}]|[body_exp]>;
//function tree structure: `"\"[":"[...params],body]` || `"\"[_,body]`
}
class ClassObj extends FunctionObj{
constructor(data={}){super();Object.assign(this,data);}
toString(){return "/ class";}
toTree(){return this.exp.args.slice(1)}
context:Context;
exp:Expression<"/",{args:[parameters,body,Option<"\\" & constructor>]}>;
}
class ParameterData{
}
class Break{
constructor(data={}){Object.assign(this,data);}
returnValue:Value;//re
ownerScopeObject:ObjectValue&Item<Namespace.variables>;//valueObject from namespace representing the scope to return to
}
class Context{
static ContextType = EnumSymbols("default","if","else","for","while","match","case");
static ParameterSymbol = EnumSymbols("#@","#?","#!","##","#/","#\\","#..");
namespace:Namespace = new Namespace();
module:&Module;
contextType:ContextType = Context.ContextType.default;
arguments:Map<ParameterSymbol,Value[]> = {};
functionInstance?:&ObjectValue|Object;//points to the function instance; used for decaring `#name`
forLoopExp?:{index:Number,exp:Expression<"for">,args:Value_Derefed[]};//index is the current iteration index
constructor(data={}){Object.assign(this,data)}
new_child(data={}){
return new Context({...this,...data});
}
new_child_statement(data={}){// for statements e.g. `if` statements
let arguments_clone = {};
Object.getOwnPropertySymbols(this.arguments).forEach(key=>arguments_clone[key]=[...this.arguments[key]]);
return new Context({...this,arguments:arguments_clone,...data});
}
new_child_namespace(data={},namespaceData={}){//for inner blocks `{...}` ; use this one if in doubt
return new Context({...this,namespace:new Namespace({parent:this.namespace,...namespaceData}),...data});
}
static new_root(){
return new Context({
namespace:new Namespace({variables:{
"inspect":(value,javascript_string)=>new Function("v,value",`return ${javascript_string}`)(value,value),
"r":Math.random,
"l"(v){console.log(...arguments);return v},
"log"(v){console.log(...arguments);return v},
...{
prompt,
confirm,
global,
globalThis,
Math
},
}}),
});
}
set_parameterSymbols(symbols:{[ParameterSymbol]:Value[]}){
Object.assign(this.arguments,symbols);
return this;
}
add_parameterSymbols(symbols:{[ParameterSymbol]:Value[]}){
getAllowedSymbols(symbols).forEach(symbol=>(this.arguments[symbol]??=[]).push(...symbols[symbol]));
return this;
}
clone(){
return new Context(this);
}
}
class ObjectValue{
constructor(data={}){Object.assign(this,data);}
properties:Object&Map<Name,Value> = {};
array:Value[] = [];
prototypes?:ObjectValue = null;
class?:ClassObj;
call(_self,arg_name:Value):Value{//same use as method 'Function.prototype.call' ; used for function calls
let name = try_getPropertyValue(this,arg_name);
if(typeof name == "number")return this.array[name];
return PropertyRef.new(try_getPropertyData(this,derefValue(name)));
}
clone(){
return new ObjectValue({
properties:{...this.properties},
array:[...this.array],
prototypes:this.prototypes,
});
}
static fromObjectOrObjectValue(value:ObjectValue|Array|Object):ObjectValue{
return match(value,[
[()=>value instanceof ObjectValue,()=>value],
[()=>value instanceof Array,()=>new ObjectValue({array:value})],
[()=>Object.getPrototypeOf(value) == Object.prototype,()=>new ObjectValue({properties:value})],
]);
}
toJS(){
return this.isArrayType?this.toJSArray():this.toJSObject();
}
toJSObject():&Object{
return this.properties;
}
toJSArray():&Array{
return this.array;
}
}
class Namespace{
constructor(data={}){Object.assign(this,data)}
parent?:Namespace&Tree<Namespace> = null;
variables:ObjectValue | Object&Map<Name,Value> = {};
new_child(data={}){
return new Namespace({parent:this,...data});
}
getVariableRef(name:Name,isDeclaration):Option<PropertyDataInternal> & PropertyDataInternal|null{
//assume: this.parent:Tree<Namespace> ; it will stack overflow otherwise (i.e. will not crash computer from RAM use)
let propertyData:PropertyDataInternal = this.getVariableSelf(name);
assert(!!propertyData && propertyData instanceof PropertyDataInternal);
if(!isDeclaration && propertyData?.valueExists === false)
return this.parent?.getVariableRef(name)??null;
return propertyData;
}
getVariableRefOrDeclareData(name:Name):PropertyDataInternal{
return this.getVariableRef(name)??try_getPropertyData(this.variables,name);
}
getVariableSelf(name):PropertyDataInternal{
assume(!!this.variables)
//assume:namespace cannot contain cycles
let data = try_getPropertyData(this.variables,name);
assert(!!data,"should return Some<PropertyDataInternal> since: 1. namespaces are trees so cannot contain cycles; 2. this.variables always exists");
return data;
}
assignVariable(name:Name,value:Value,isDeclaration:bool=false):Option<PropertyRef>{//note: returns Some<...> if isDeclaration
let propertyData = this.getVariableRef(name,isDeclaration)?.set?.(value??null,isDeclaration);
if(isDeclaration)todo.silent("handle declaration");
return propertyData?new PropertyRef(propertyData):null;
}
declareVariable(name:Name,value?:Value):PropertyRef{
todo.silent("handle modules");
todo.silent("allow `a:(b:2);a.b=4;assert a[0]==a.b`; linking property and tuple index; maybe add a index<-->name' map")
let propertyRef = this.assignVariable(name,value,true);
assert(!!propertyRef);
return propertyRef;
}
}
class FunctionData{//used for external arguments `a:>foo(b)<:c|>bar`; stored as an argument in evalCode.statement
constructor(data={}){Object.assign(this,data)}
arguments:ArgumentObj;
function:Value;
}
class ModuleObj{
privateSymbolMap:Map<String,Symbol>;
}
//----
const AllPrivateSymbols = Symbol("a.$*");
const AllSymbols = Symbol("a.*");
const NullSymbol = Symbol("$null");
const ObjectAsSymbol = Symbol("$obj");
const InvalidValueSymbolError = Symbol("syntax error invalid");
const JavascriptFunctionUseRawValues_symbol = Symbol("use Value");
const compilerOnlySymbols = [isSearched,ObjectAsSymbol];//symbols that can both be {added to variables} and {that should not be accessable by the language user}
const ErrorSettings = {
allowPropertyOfUndefined:true,
};
const evalCode = {
forEach_exps(exps:Expression[],context:Context,forEachFunction?:(value)=>void):Option<Value>{//`...` in `{...}`
let lastValue;
let hasSepparator = false;
for(let exp of exps){
let value = evalCode.statement(exp,context);
if(exp.wordSymbol.word == "£" && !exp.args[0])continue;
hasSepparator = exp.hasSepparator;
lastValue = value;
forEachFunction?.(value,exp);
}
return hasSepparator?null:lastValue;
},
statement(exp:Option<Expression>,context:Context,functionData?:FunctionData):Value{
assert(!!context)
if(!exp)return undefined;
let value;
try{
value = match(exp.wordSymbol.type,[
[SyntaxTree.type.value,()=>match(exp.wordSymbol.subtype,[
[[
SyntaxTree.subtype.string,
SyntaxTree.subtype.number,
SyntaxTree.subtype.bool,
SyntaxTree.subtype.object,
SyntaxTree.subtype.null,
],()=>exp.wordSymbol.value],
[SyntaxTree.subtype.formatString,()=>todo("handle format strings")],
])],
[SyntaxTree.type.label,()=>PropertyRef.new(context.namespace.getVariableRef(exp.wordSymbol.word))],
[SyntaxTree.type.bracket,()=>match(exp.wordSymbol.word,[
["{",()=>{
let i=0;
const firstStatement:Option<Expression> = exp.contence[0];
const blockExp = exp;
let lastStatementToEval:Option<Expression> = null;//executes expression at the end ; `{=last_exp;...}` ; e.g. `{=c;a;b}`
const innerContext = context.new_child_namespace();
if(!firstStatement?.args?.[0]&&[":", "::", "="].includes(firstStatement?.wordSymbol?.word)){//'{=exp;}'
match(firstStatement?.wordSymbol?.word,[
["::",()=>{blockExp.typeAnnotation = firstStatement}],
[":",()=>{
if(":=".includes(firstStatement.args[1]?.wordSymbol?.word)){
lastStatementToEval = firstStatement.args[1];
}
evalCode.declareVariables_OBSILETE(firstStatement.args[1],undefined,innerContext);
}],
["=",()=>{
lastStatementToEval = firstStatement;
}],
],()=>{});
i+=1;
}
let lastValue = evalCode.forEach_exps(blockExp.contence,innerContext);
if(lastStatementToEval)lastValue = evalCode.statement(lastStatementToEval,innerContext);
return lastValue;
}],
[["[","("],()=>{
let functionObj:Option<Value> = undefined;
let isFunctionCall = false;
if(exp.afix == Expression.AfixType.postfix){//function call
isFunctionCall = true;
functionObj = evalCode.statement(exp.args[0],context);
}
let variable = new ObjectValue();
if(exp.wordSymbol.word == "[")variable.isArrayType = true;
let innerContext = context.new_child_namespace({},{variables:variable});
const bracket_exp = exp;
void evalCode.forEach_exps(bracket_exp.contence,innerContext,(value,exp)=>{
if(!(bracket_exp.wordSymbol.word=="("&&exp.wordSymbol.word==":")){//for tuples, pattern `a:b` does not add item
let valueToPush:Value_Storable;
if(bracket_exp.wordSymbol.word=="["&&exp.wordSymbol.word==":"){
let property:Value = value;
let valueRef = ValueRef.fromValue(property);
assignToValue(property,valueRef,exp);
valueToPush = valueRef;
}
else{
valueToPush = derefValueToStorable(value);
}
match(Object.getPrototypeOf(variable).constructor,[
[()=>ObjectValue,()=>variable.array.push(valueToPush)],
[()=>Array,()=>variable.push(valueToPush)],
[()=>Object,()=>todo()],
])
}
});
if(isFunctionCall){
todo.silent("BODGED; handle pipe operators");
return functionCall(functionObj,variable);
}
return variable;
}],
])],
[SyntaxTree.type.operator,()=>{
const args = exp.args;
const [x,y] = args;//for numeric operators
function numericOperator(foo:(x:Value_Derefed,y:Value_Derefed)=>Value_Derefed):Value_Derefed{
return foo(
derefValueFully(evalCode.statement(x,context)),
derefValueFully(evalCode.statement(y,context)),
);
}
let get_x = ()=>evalCode.statement(exp.args[0],context);
let get_y = ()=>evalCode.statement(exp.args[1],context);
function getArgFromDoubleExpStatement(statement_exp):Expression[2]{//`if a=>b` --> `if a b` --> [a,b]
assume(exp.args[1].wordSymbol.word == "=>" || exp.args[2],"e.g. 'if name;' is not defined in the syntax spec")
const arrowExpArgs:Expression[2] = exp.args[2]?[exp.args[1],exp.args[2]]:exp.args[1].args;
return arrowExpArgs;
}
return match(exp.wordSymbol.word,[
["\\",()=>new FunctionObj({exp,context})],//function `\exp`
[word=>word=="/"&&exp.afix == Expression.AfixType.prefix,()=>new ClassObj({exp,context})],//class `/exp`
[":",()=>{
let value = evalCode.declareVariables_OBSILETE(exp.args[0],exp.args[1],context);
return value;
}],
["=",()=>{
let assignValue = evalCode.statement(exp.args[1],context);
if(exp.wordSymbol.subWord){//`a+=b`
todo("handle pattern 'a+=b'");
}
let assignedValues = evalCode.assignVariables(exp.args[0],assignValue,context);
return assignedValues;
}],
["::",()=>{
todo.silent("handle semi-type evaluation and comment-like type annotations propperly");
return new ValueWrapper.Typed({
value:evalCode.statement(exp.args[0],context),
type:exp.wordSymbol.word,
})
}],
[".",()=>{
let parent = derefValue(evalCode.statement(exp.args[0],context));
let value;
let propertyNameValue:Name|Value;
assume(!!exp.args[1]);
propertyNameValue = exp.args[1].wordSymbol.type == SyntaxTree.type.label?
exp.args[1].wordSymbol.word:
derefValue(evalCode.statement(exp.args[1],context))
;
if(parent == null){
if(!ErrorSettings.allowPropertyOfUndefined)exp.wordSymbol.throwError("null",`unable to get properties on '${parent}'`,e=>Error(e));
}
value = try_getPropertyRef(parent,propertyNameValue);
if(!!exp.args[2]){//`array.= \exp`
let arg = evalCode.statement(exp.args[2],context);
value = functionCall(value,[arg],todo.silent("handle methods; get `#.` (i.e. self) from namespace's class instance object"));
}
return value;
}],
...[//function calls
[",",()=>{//function call
todo.silent("handle arguments");
const args = functionData?.args ?? [];
if(exp.args[1])args.push(evalCode.statement(exp.args[1],context));
return functionCall(evalCode.statement(exp.args[0],context),args);
}],
[[":>"],()=>{//external argument
todo(`pipe arguments. got '${exp.wordSymbol.word}'`);
const args = functionData?.args ?? [];
let arg = evalCode.statement(exp.args[0],context,args);
args.push(arg);
evalCode.statement(exp.args[1],context,args)
//[["<:"],()=>{}],
//[["|>","<|",","],()=>{}],
}],
],
[["$$","$"],()=>evalCode.getName(exp,context)],
["£",()=>{//`a£b` --> `a`
const isReverseOrder = exp.isReverseOrder;
const evaluationOrder:Expression[2] = isReverseOrder?[exp.args[1],exp.args[0]]:exp.args;
const values = evaluationOrder.map(arg_exp=>evalCode.statement(arg_exp,context));
return isReverseOrder?values[1]:values[0];
}],
[word=>word == "&" && exp.afix == Expression.AfixType.postfix,()=>{//'a&' reference
let value:Value = evalCode.statement(exp.args[0]??exp.args[1],context);
if(value instanceof PropertyRef)value.isReturnable = true;
return value;//BODGED
}],
[word=>word == "&" && exp.afix == Expression.AfixType.prefix,()=>{//'&a' linked property similar to the C code `&int a = &b`
let value:Value = evalCode.statement(exp.args[0]??exp.args[1],context);
todo.silent("handle `&a` references properly");
let valueRef = ValueRef.fromValue(value);
if(value instanceof PropertyRef && value != valueRef){//turns variable into a reference if it was not already
value.set(valueRef);
}
return valueRef;//BODGED
}],
["¬",()=>evalCode.statement(exp.args[0],context)],
["?",()=>{
let returnValue = evalCode.statement(exp.args[0],context);
let value_for_owner:Value = evalCode.statement(exp.args[1],context)??null;
value_for_owner = unwrapValue(value_for_owner);
let ownerScopeObject:ObjectValue;
if(value_for_owner instanceof PropertyRef){
ownerScopeObject = value_for_owner.parent;
function checkNamespace(namespace){
if(namespace.variables == ownerScopeObject)return namespace;
if(!!namespace.parent)return checkNamespace(namespace.parent)
return null;
}
let foundNamespace:Namespace|null = checkNamespace(context.namespace);
if(!foundNamespace){
exp.args[1].wordSymbol.throwError("return",`variable's owner namespace is not in the current scope. Looking for variable '${value_for_owner.name}' `,e=>Error(e))
}
}else {
if(exp.args[1])
exp.args[1].wordSymbol.throwError("return",`expected value belonging to a parent scope. got:'${value_for_owner}'`,e=>Error(e))
}
throw new Break({
returnValue,
ownerScopeObject,
});
}],
...[//parameters
[()=>exp.wordSymbol.subtype == SyntaxTree.subtype.autoParameter,//`##` `#?` `#@` etc...
()=>{
const contextParameterSymbol:Context.ParameterSymbol = Context.ParameterSymbol[
exp.wordSymbol.word.replace(/^#$/,"##")
];
const args:Value[] = context.arguments[contextParameterSymbol] ?? [];
assume(args instanceof Array);
let value = args[exp.autoParameterIndex]??null;
if(exp.args[1]){
let name:Name = evalCode.getName(exp.args[1],context);
if(["##","#"].includes(exp.wordSymbol.word)){
let propertyData:PropertyDataInternal = try_getPropertyData(context.functionInstance,name);
assert(!!propertyData)
propertyData.set(value);
}
else{
context.namespace.declareVariable(name,value);//TODO: do this staticly to work in conditional code
}
}
return value;
}
]
],
...[//numeric and logical operators:
["%%%",()=>numericOperator((x,y)=>((x)%y+y)%y)],//positive modulo
["%%",()=>numericOperator((x,y)=>!exp.args[1]?Math.log(x):Math.log2(x)/Math.log2(y))],//log
[
word=>exp.afix == Expression.AfixType.infix &&
word.match(/^[+\-&|^%\/*]$|\*\*|>{2,3}|<{2}/),
()=>numericOperator(
new Function("x,y",`return x ${exp.wordSymbol.word} y`)
)
],
[//nor `a~b` == `{a|b}`
word=>exp.afix == Expression.AfixType.infix && word == "~",
()=>numericOperator((x,y)=>~(x|y))
],
["~~",()=>{//logical nor
let x = get_x();
let y = get_y();
[
[true,x],//x=0
[y,false],//x=1
][!derefValueFully(x)][!derefValueFully(y)]
//00 1 true
//01 0 X
//10 0 Y
//11 0 false
}
],
["^^",()=>{//logical xor
let x = get_x();
let y = get_y();
let get_x_derefed = ()=>derefValueFully(x);
let get_y_derefed = ()=>derefValueFully(y);
let value = !get_x_derefed()?y: !get_y_derefed()?x: false;
return new ValueWrapperReturnValue({value,boolReturnValue:x});
}],
["&&",()=>{//logical and
let x;
return !derefValueFully(x = get_x())?x:get_y();
}],
["||",()=>{//logical or
let x;
return derefValueFully(x = get_x())?x:get_y();
}],
[//comparisons ; `a==b==c` --> `{a==b} && {b==c}`
word=>exp.afix == Expression.AfixType.infix &&
word.match(/^(?:[<>]=?|[!=]==?)$/),
()=>{
function equality(x:Value_Derefed,y:Value_Derefed){//`a==b`
if(x == y)return true;
if(!(x instanceof Object && y instanceof Object))return false;
if(x[isSearched]||y[isSearched])return false;
x[isSearched] = true;
y[isSearched] = true;
let bool = false;getBool:{
if(x instanceof ObjectValue && y instanceof ObjectValue){//BODGED
bool = equality(x.array,y.array) && equality(x.properties,y.properties);
break getBool;
}
if(x instanceof Array && y instanceof Array){
if(x.length != y.length){break getBool;}
for(let i=0;i<x.length;i++){
if(!(i in x) && !(i in y))continue;//handles gaps in array
if(!equality(x[i],y[i]))break getBool;
}
bool = true;
break getBool;
}
if(x instanceof Object && y instanceof Object){
let keys:Name[][2] = [x,y].map(obj=>[
...Object.keys(obj),
...getAllowedSymbols(obj)
]);
if(keys[0].length != keys[1].length)break getBool;
keys = new Set([...keys[0],...keys[1]]);
for(let keyX of keys){
if(!Object.hasOwn(y,keyX))break getBool;
if(!equality(x[keyX],y[keyX]))break getBool;
}
bool = true;
break getBool;
}
}
delete x[isSearched];
delete y[isSearched];
return bool ?? false;
};
function handleComparisonChain(exp):{value:Value&bool,args:Value[2],isSingleArg:bool}{
if(exp.afix == Expression.AfixType.infix && exp.wordSymbol.word.match(/[<>]=?|[!=]==?/)){
const foo:(x,y)=>bool =
exp.wordSymbol.word == "=="?equality:
exp.wordSymbol.word == "!="?(x,y)=>!equality(x,y):
new Function("x,y",`return x ${exp.wordSymbol.word} y`)
;
let arg0 = handleComparisonChain(exp.args[0]);
if(!arg0.isSingleArg && !arg0.value)return arg0;//implements `&&` ; `a>b>c` --> `a>b&&b>c`
let arg1 = handleComparisonChain(exp.args[1]);
let args:Value_Returnable[] = [
derefValueFully(arg0.args[1]),
derefValueFully(arg1.args[0]),
];
return {value:foo(args[0],args[1]),args};
}else{
let arg = evalCode.statement(exp,context);
return {value:undefined,args:[arg,arg],isSingleArg:true};
}
}
let {value,args} = handleComparisonChain(exp);
return new ValueWrapperReturnValue({value,boolReturnValue:args[0]})
},
],
[
"++",
()=>{
assert(!(!!exp.args[0] && !!exp.args[1]),"should not be infix");
let arg = exp.args[0] ?? exp.args[1];
let afix:u2&Expression.AfixType = exp.afix;
assert(!!arg);
assume(!(!!exp.args[0]&&!!exp.args[1]),"there is only one argument for `i++` or `++i`")
let property = unwrapValue(evalCode.statement(exp.args[0]||exp.args[1],context));
let value:Number|Value_Derefed = derefValueFully(property);
if(typeof value != "number")value = 0;
return match(afix,[
[Expression.AfixType.prefix,()=>{assignToValue(property,value+1,exp);return +value}],//i++
[Expression.AfixType.postfix,()=>assignToValue(property,value+1,exp)],//++i
]);
}
],
[
word=>exp.afix == Expression.AfixType.prefix &&
word.match(/^[+\-~!]$/),
()=>numericOperator(
new Function("_,x",`return ${exp.wordSymbol.word} x`)
)
],
[
word=>exp.afix == Expression.AfixType.postfix &&
word.match(/^[+~!]$/),
()=>numericOperator(
new Function("x,_",`return ${exp.wordSymbol.word} x`)
)
],
],//----
...[//ternary operators
["&?",()=>{
let value = unwrapValue(evalCode.statement(exp.args[0],context));
if(!!derefValueFully(value))
return new ValueWrapperReturnValue({value:evalCode.statement(exp.args[1],context),boolReturnValue:value});
else return new ValueWrapperReturnValue({value:null,boolReturnValue:value});
}],
["?&",()=>{//python-like reversed if statement`
let value = unwrapValue(evalCode.statement(exp.args[1],context));
if(!!derefValueFully(value))
return new ValueWrapperReturnValue({value:evalCode.statement(exp.args[0],context),boolReturnValue:value});
else return new ValueWrapperReturnValue({value,boolReturnValue:value});
}],
["|?",()=>{//`a&?b|?c` very similar to else but without `#?`
let value = evalCode.statement(exp.args[0],context);
if(!(value instanceof ValueWrapperReturnValue))
exp.wordSymbol.throwError("syntax","missing if statement in pattern 'exp&&exp|?exp'",e=>Error(e))
let boolValue:Value = value.boolReturnValue;
if(!!derefValueFully(boolValue)){
return unwrapValue(value);
}
else {//else
return evalCode.statement(exp.args[1],context);
}
}],
],
//keyword operators
["=>",()=>{
let innerContext = context.new_child_statement();
return match(context.contextType,[
[[Context.ContextType.default],()=>todo("use argument as #@ in right exp")],
[[Context.ContextType.if],()=>{assert.impossibleCase("handled elsewhere")}]
]);
}],
["if",()=>{//`if a => b` or `if a b`
let innerContext = context.new_child_statement({contextType:Context.ContextType.if});
const arrowExpArgs:Expression[2] = getArgFromDoubleExpStatement(exp);
let argument = evalCode.statement(arrowExpArgs[0],innerContext);
const bool = derefValueFully(argument);
argument = argument instanceof ValueWrapperReturnValue?
argument.boolReturnValue:
derefValue(argument)
;
innerContext.add_parameterSymbols({[Context.ParameterSymbol["#?"]]:[argument]});
let value = bool? unwrapValue(evalCode.statement(arrowExpArgs[1],innerContext)):null;
value = new ValueWrapper({value,statementReturnValue:{value:argument}});
return value;
}],
["else",()=>{
let value:ValueWrapper<{statementReturnValue}>|Value = evalCode.statement(exp.args[0],context);//from if statement
if(!(value instanceof ValueWrapper) || !value.statementReturnValue)
exp.wordSymbol.throwError("syntax","missing if statement in pattern 'if exp=>exp else exp'",e=>Error(e))
let boolValue:Value = value.value;
let statementReturnValue:Value = value.statementReturnValue.value;
if(!!derefValueFully(boolValue)){
return unwrapValue(value);
}
else {//else
let innerContext = context.new_child_statement({contextType:Context.ContextType.else});
const argument = value.statementReturnValue.value;
innerContext.add_parameterSymbols({[Context.ParameterSymbol["#?"]]:[argument]});
return evalCode.statement(exp.args[1],innerContext);
}
}],
["assert",()=>{//TODO allow `assert exp=>message_exp`
let value = evalCode.statement(exp.args[1],context);
if(!derefValueFully(value))exp.wordSymbol.throwError("assertion",`assertion failed${value instanceof ValueWrapperReturnValue?`: found '${value.boolReturnValue}'`:""}`,e=>Error(e))
return value instanceof ValueWrapperReturnValue?value.boolReturnValue:value;
}],
["while",()=>{
const [condition_exp,body_exp]:Expression[2] = getArgFromDoubleExpStatement(exp);
let returnValue:Value;