-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
2131 lines (2125 loc) · 89.7 KB
/
Copy pathmain.ts
File metadata and controls
2131 lines (2125 loc) · 89.7 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 ':'
const words_regex = /\/\*[\s\S]*?\*\/|\/\/.*|[rf]?(?:r(#+)"[\s\S]*?"\1|"(?:\\u....|\\x..|\\.|[^"\n])*?")|[@$#]\*|(?:\?&|&\?|\|\?|\?!)|[|:]>|<[|:]|>:|::?|\\|(?:!<|!>)|=>|->|[!=]==|[><!=]=?|>{1,3}|<{1,2}|([+\-*%&|^~])\2?|#(?:\.\.|[#@?/\\])|\${1,2}|[¬\\]|\s+|[\(\[\{]|[\)\]\}]|\b(?:(?:\d|[1-9][_\d]*)(?:\.[_\d]+)?|0[box][_\dA-Fa-f]+(?:\.[_\dA-Fa-f]+)?)\b|!!!|\.\.\.|\.\.=?|\.|\b\w+\b|\S/g;//TODO: add back '#.'
//note: float numbers are handed during syntax parting to allow for '3.<' aswell as '3.2'
//TODO:handle format strings: need to combine words together when a format string is encountered
//currently cannot embed format strings in other format strings
//{//quality of life, macro-like functions
function loga(...a){console.log(...a);return a[0]}
function logData(...a){
console.log(...a.map(v=>v.toLog?.()??v))
}//log data emmits surtain information
/**
* void let loga = [...a] -> void console.log <| ...a a<|0]
* void let logData = [...a] -> {void console.log[...a.map <| v->traitof v >= trait[toLog=\(void)]? v.toLog?.():v}
* void let debugMode = true
* void let assert = [condision msg ??= "" errorFunc ??= a->Error[e]] -> void:(
* void
* )
* */
const debugMode = true;
function assert(condision,msg = "",errorFunc = e=>Error(e)):true|Error{
if(debugMode){
msg ??= "";//msg:String|()->String
if(!condision)throw errorFunc("ASSERTION FAILLED:" + (typeof msg == "function"?msg():msg));
}
return true
}
function assume(condision,msg = "",errorFunc = e=>Error(e)):()=>any{
if(debugMode){
msg ??= "";
if(!condision)throw errorFunc("ASSUMPTION FAILLED:" + msg);
}
return (fooUsingAssumption:Fn|any)=>typeof fooUsingAssumption == "function" ? fooUsingAssumption(condision) : fooUsingAssumption;
}
assert.fail = function(msg = undefined,errorFunc = e=>Error(e)){
if(debugMode){
msg ??= "impossible case found";
assert(false,msg,errorFunc);
}
}
assert.impossibleCase = function(msg = "",errorFunc = e=>Error(e)){
if(debugMode){
assert(false,"impossible case: " + msg,errorFunc);
}
}
assert.expect = function(condision,msg = "",errorFunc = e=>Error(e)){
if(debugMode){
assert(condision,"expected: " + msg,errorFunc);
}
}
function unimplemented(msg = "",errorFunc = e=>Error(e)){
if(debugMode){
throw errorFunc("UNIMPLEMENTED:" + msg);
}
}
function todo(msg = "",errorFunc:(e)=>Error<e>){
if(debugMode){
throw (errorFunc??Error)("TODO:" + msg);
}
}
todo.flaggedErrors = {};
todo.silent = function(name?:String,returnValue,state?:Any,errorFunc = e=>Error(e)){
todo.flaggedErrors[name] ??= {state,error:errorFunc};
return returnValue;
}
function silentError(name?:String,state?:Any,errorFunc = e=>Error(e)){
silentError.flaggedErrors[name] ??= {state,error:errorFunc};
}
silentError.flaggedErrors = {};
function pass(v?:Any){return v}//marks a block as not meant to contain any code
function forBailOld(length,onError_default=undefined){
//example: let n=forBailOld(array.length);while(true){n();}
let i_bail = 0;
return function next(onError=onError_default){
if(debugMode)if(i_bail++>length){
if(onError)onError(i_bail);
throw Error("BAILED");
}
}
}
function* forBailGenerator(length,onError_default=undefined){
//example: for(let _ of forBailGenerator(array.length)){...}
for(let i = 0; i < length;i++)yield i;
if(debugMode){
if(onError_default)onError_default(i_bail);
throw Error("BAILED");
}
}
function match<V,B,T>(value:V,setOfCases:MatchCase[],defaultCase:(v)=>T):T{
"use strict";
//type MatchCase=[(V[]|V->B|bool), B|V->T]
let i = -1;
let tryNext = forBailOld(setOfCases.length);
while(++i < setOfCases.length){
let _case:MatchCase;
tryNext();
_case = setOfCases[i];
if(!(_case instanceof Array))throw Error(`missing case at index ${i}, got '${_case}'. May have missed a comma between cases.`)
let condition = _case[0];
let then = _case[1];
let input:V|B = value;
if(typeof then != "function")throw Error("compiler syntax error: case "+i+" is missing `V->T`");
if(
typeof condition == "function"?input=condition(value):
condition instanceof Array?input=condition.includes(value):
value == condition
//(()=>{
//console.error(_case[0])
//throw Error("compiler syntax error: case " + i + " is missing `V[]|V->bool`");
//})()
)return then(input,value);
}
if(defaultCase)return defaultCase(value,setOfCases);
else throw Error("compiler error: unhandled case: '"+value?.toString()+"'");
}
function matchFlags<F,T>(flags:F,setOfCases:MatchCase[],defaultCase:(v)=>T):T{//UNFINISHED
"use strict";
//where Flags:bool[]|(Number&uint)|{[Symbol]:any}
type F = Flags;
//type MatchCase=[(F|F->bool), F->T]
let i = -1;
let _case:MatchCase;
let unhandledFlags = [];
let tryNext = forBailOld(setOfCases.length);
unimplemented("need to convert the code to match flags instead of cases");
unimplemented("while loop should run all of the valid cases, unlike")
//while(++i < setOfCases.length){
// tryNext();
// _case = setOfCases[i];
// if(typeof _case[1] != "function")throw Error("compiler syntax error: case "+i+" is missing `V->T`");
// if(
// typeof _case[0] == "function"?_case[0](flags):
// _case[0] instanceof Array?_case[0].includes(flags):
// (()=>{
// console.error(_case[0])
// throw Error("compiler syntax error: case " + i + " is missing `V[]|V->bool`");
// })()
// )return _case[1](flags);
//}
if(defaultCase)return defaultCase(flags,setOfCases);
else throw Error("compiler error: unhandled flag: '"+unhandledFlags[0]?.toString()+"'");
}
function EnumSymbols(...list:String[]):{[Item<list>]:Symbol}{
return Object.freeze(list.reduce((s,v)=>[s,s[v]=Symbol(v)][0],{}));
}
type Option<T> = T|null;
function getFile(fileName):Option<String>{
let file;
try {
file = Deno.readTextFileSync(fileName);
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
//Error("file does not exist");
return null;
}
return file;
}
function getFile_expect(fileName,throwError):String{
let result = getFile(fileName);
if(result instanceof Error)throwError();
return result;
}
const closingBracketMap = {"{": "}", "[": "]", "(": ")"};
//}//----
const fs = Deno;//require("fs");
//compiles simple lambda calculus
//classes:
class Language{//base class
//external interface
constructor({compile,syntaxTree}={}){
this.#compile = compile ?? this.compile;
this.syntaxTree = syntaxTree ?? this.syntaxTree;
}
compile(text,throwError,fileName){
fileName ??= "";
throwError ??= e => {throw e}
this.currentContext = {text,throwError,fileName};
return this.#compile(this.currentContext);
}
//SyntaxTreeData
syntaxTree_regex = /\s+|[\w_]+|[()\[\]{}]|\S/g;//:Regex ; main regex for passing raw file into words
syntaxTree_getData = function(word){
return {type:"symbol",subtype:"symbol"};
}
//----
#compile(){}//:using(currentContext)->compiled object
currentContext;
getSyntaxTree(text,throwError,fileName){
return new SyntaxTree(this.syntaxTree);
}
//internal interface
}
class Errors{//for error messages that need to mark multiple words
constructor(data={}){Object.assign(this,data)}
static new(type,message,comments:[WordSymbol,String][]){
return new Errors({
type,
message,
errors:comments.map(([wordSymbol,message])=>({wordSymbol,message})),
})
}
type:String;
message:String;
errors:{wordSymbol:WordSymbol,message:String}[];//words to be underlines
getErrorString(extraIndentation = 0):String{
let lines = new Map();
for(let {wordSymbol,message} of this.errors){
lines.getOrInsert(wordSymbol.errorData.line,[]).push({wordSymbol,message});
}
todo()
}
intoError(error=e=>Error(e)):Error{
return error(this.getErrorString());
}
throwError(error=e=>Error(e)){
throw this.intoError(error);
}
}
//Syntax tree:
class WordSymbol extends String{
constructor(data={}){
super(data.word);
if(data instanceof WordSymbol){
data = {...data};
for(let i=0;i<data.length;i++)delete data[i];
}
Object.assign(this,data);
this.errorData = Object.assign(new this.constructor.ErrorData(),data.errorData);
}
clone(name?:String){
return new WordSymbol({
word:name??this.word,
afix:this.afix,
type:this.type,
subtype:this.subtype,
patternType:this.patternType,
indent:this.indent,
errorData:this.#errorData,
});
}
//
word;//:string
afix;//:Int & (!!left_arg * 2) + !!right_arg
type;//:Symbol
subtype;//:Symbol
patternType;//:((Object & Class())|string)? ; used to contain pattern data ; UNUSED
indent;//:Number ; counts from 0 ; used for parsing multiline-strings
isAfterWhiteSpace;//:bool
//when type == (number|string)
//value//:number|string ; is the evaluated version of 'word'
//valueType
//used with type == "bracket" && subtype == "open" || for many patterns in the syntax tree like 'a + b'
//contence;//:Tree(WordSymbol?)? & (when type == "parameterPattern": [WordSymbol&"bracket"]) | when 'a' from 'a=' assignmentPatturn.arguments.contence: (WordSymbol & type=="keyword")[]
//endBracket;//:WordSymbol & close bracket ; used when type == bracket open
//error data
#errorData:ErrorData;//is private so it does not show up when debugging compiler
get errorData(){return this.#errorData}
set errorData(value){this.#errorData = value}
//errorData;
throwError(...args){this.errorData.throwError(...args)}
static ErrorData = class ErrorData{
file;//:SourceFile
line;//:Number ; counts from 1
column;//:Number ; counts from 1
indent;//:Number ; counts from 0
word;
static throwError;//is message=>throw Error(message)
getErrorMsg(errorType,errorMessage,stack=undefined){
return " ERROR:\n"
+ this.display_location() + "\n"
// " ".repeat(lineLen)+" |\n"
+ this.display_markWordInLine(" " + errorType + " error") + "\n"
+ "error" + ": " + errorMessage + "\n"
;
}
throw(msg,errorFunc){
this.constructor.throwError(errorFunc(msg));
}
throwError(errorType,errorMessage,errorFunc,stack=undefined){
this.constructor.throwError(errorFunc(this.getErrorMsg(errorType,errorMessage,stack)));
}
display_location(){
return this.file.name+":"+this.line+":"+this.column;
}
display_markWordInLine(lineRaw){
let line = this.file.lines[this.line-1].substr(this.indent);
return line+"\n"+line.substr(0,(this.column-1) - this.indent).replaceAll(/./g," ")+"^".repeat(this.word.length) + lineRaw;
}
}
toString(){
return this.word;
}
}
class SyntaxTree extends Array{
//types and subtypes for the 2nd phase of building syntax tree
static type = EnumSymbols(
"whiteSpace",
"comment",
"value",//bool|number|string|special
"label",
"bracket",// '(' ')'
"operator",
"sepparator",//';'
"constant",
);
static subtype = EnumSymbols(
// whitespace
"whiteSpace",
"comment",
// bracket
"open",
"closed",
// value
"string",
"formatString",
"number",
"bool",
"object",
"null",// 'null', ';' in ';;'
//UNUSED: "undefined",//'undefined' == '{}'
// label
"operator",//operators e.g. '>' '=' in '.>' '.=' ; allows for 'a.>foo' --> 'b.>,foo'
// operator
"comparitor",
"pipeline",// '|>' '<|' ':>' '<:'
"interval",// 'a..b' , 'a..=b'
"ternary",// 'a ?& b |? c', 'b &? a |? c' for 'if a=>b else c'
"declaration",// ':' ; used for ':=' syntaxes
"assignment",// '='
"typeAnnotation",
"return",// '?' '?!'
"statement",// 'if' 'while' etc... ; statements with 'statement exp => exp'
"autoParameter",// '#' e.g. '#', '#@', '#?' etc...
);
static subtype2 = EnumSymbols(//misc operators
"regex",// 'r"..."'
"dot",// '.' '#.'
// bracket
"struct",// `(`
"array",// `[`
"block",// `(`
// statement
"allowsDoubleExp"//statement that allow for `statement exp exp`
);
static AfixType = {//e.g. '!a' is prefix --> '0b01'
nofix:0b00,//'a'
postfix:0b10,//'a++'
prefix:0b01,//'++a'
infix:0b11,//'a+b'
operatorWithBothArgs:0b11,//default value
operatorWithLeftArg:0b10,//'a++'
operatorWithRightArg:0b01,//'++a'
};
constructor(text,throwError,fileName = "",regexs = {},addExtraWordData){
if(typeof text == "number"){super(text);return;}//for .forEach calls
let {allRegex, types} = regexs;
throwError ??= (msg = "", errorFunction = a => Error(a)) => {throw errorFunction(msg)};
allRegex ??= words_regex;
if(0)types ??= [
{match:"",name:""},
{match:/\s+/,name:"whiteSpace"},
{match:/^\/[/*]/,name:"comment"},
{match:/^[()\[\]{}]$/,name:"bracket"},
{match:/^(?:[+\-*^&~|]{1,2}|[/!%]|\w+|\S|={1,2})$/,name:"label"},
];
addExtraWordData ??= (wordSymbol,wordString,wordSymbols)=>wordSymbol;
//classes
//WordSymbol
//----
const file = new SourceFile(fileName);
const words = ((text,regex,file)=>{
"use strict";
let words = [];
let column = 1, line = 1, indent = 0;
let isIndenting = true;
let isAfterWhiteSpace = true;//is symbol separated by white space e.g. for '+ =' vs '+='
for(let v of text.matchAll(regex)){
let word = v[0];
let type;//:string
let wordSymbol = addExtraWordData(
new WordSymbol({
word,
errorData:{column,line,file,word,indent,match:v},
//
...((v)=>{if(!v.type)throw Error("property {type} is found but it is referencing undefined value in the SyntaxTree.type enum, for '"+word+"'");return v})(
word.match(/^\s/) ? {type:SyntaxTree.type.whiteSpace,subtype:SyntaxTree.subtype.whiteSpace}:
word.match(/^\/[/*]/) ? {type:SyntaxTree.type.whiteSpace,subtype:SyntaxTree.subtype.comment} :
word.match(/^\($/) ? {type:SyntaxTree.type.bracket,subtype:SyntaxTree.subtype.open,subtype2:SyntaxTree.subtype2.struct} :
word.match(/^\[$/) ? {type:SyntaxTree.type.bracket,subtype:SyntaxTree.subtype.open,subtype2:SyntaxTree.subtype2.array} :
word.match(/^\{$/) ? {type:SyntaxTree.type.bracket,subtype:SyntaxTree.subtype.open,subtype2:SyntaxTree.subtype2.block} :
word.match(/^[)\]}]$/) ? {type:SyntaxTree.type.bracket,subtype:SyntaxTree.subtype.closed} :
word.match(/^r(?:"|r#+")/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.string,subtype2:SyntaxTree.subtype2.regex,afix:SyntaxTree.AfixType.nofix}:
word.match(/^f(?:"|r#+")/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.formatString,afix:SyntaxTree.AfixType.nofix}:
word.match(/^"|^r#+"/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.string,afix:SyntaxTree.AfixType.nofix}:
word.match(/^(?:0[xo]?|[0-9])/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.number,afix:SyntaxTree.AfixType.nofix} :
word.match(/^(?:NaN|Infinity)$/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.number,afix:SyntaxTree.AfixType.nofix} :
word.match(/^(?:true|false)$/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.bool,afix:SyntaxTree.AfixType.nofix} :
word.match(/^null$/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.null,afix:SyntaxTree.AfixType.nofix} :
//word.match(/^undefined$/) ? {type:SyntaxTree.type.value,subtype:SyntaxTree.subtype.undefined,afix:SyntaxTree.AfixType.nofix} :
word.match(/^(?:([+\-*%&|^~])\1?|>{1,3}|<{1,2}|[!\/<>])$/) ? {type:SyntaxTree.type.operator} ://numerical operators
word.match(/^([!<>]=?|[!=]?==)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:\?&|[&|]\?)$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.ternary} ://ternary operators
word.match(/^(?:=>|->)$/) ? {type:SyntaxTree.type.operator} :
word.match(/=$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.assignment} ://e.g. '=' '+='
word.match(/^:$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.declaration} :
word.match(/^::$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.typeAnnotation} ://type operator
word.match(/^(?:[|:]>)$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.pipeline,isReversed:false} ://'|>' or ':>'
word.match(/^(?:<[|:])$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.pipeline,isReversed:true} ://'<|' or '<:'
word.match(/^,$/) ? {type:SyntaxTree.type.operator} ://','
word.match(/^¬$/) ? {type:SyntaxTree.type.operator} ://'¬'
word.match(/^\?!?$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.return} ://
word.match(/^£$/) ? {type:SyntaxTree.type.operator}://void operator
word.match(/^\.$/) ? {type:SyntaxTree.type.operator,subtype2:SyntaxTree.subtype2.dot} ://dot operator
word.match(/^#\.$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.autoParameter,subtype2:SyntaxTree.subtype2.dot} ://dot operator
word.match(/^\.\.=?$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.interval} ://interval '1..3'
word.match(/^(?:ref)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^@$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:\\)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:\$\$)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:\.\.\*)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^`$/) ? {type:SyntaxTree.type.operator}:
word.match(/^#(?:\.\.|[#@!?/\\])?$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.autoParameter,afix:SyntaxTree.AfixType.nofix} ://'#' or '##' or '#@' in: '#name' '##'
word.match(/^\$$/) ? {type:SyntaxTree.type.operator} ://'$type' '$key'
word.match(/^[$@*]\*$/) ? {type:SyntaxTree.type.operator,afix:SyntaxTree.AfixType.prefix}://'@*' in '@* = (a=1,b=2,c=3)'
word.match(/^\.\.\.$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:if|while|match)$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.statement,subtype2:SyntaxTree.subtype2.allowsDoubleExp} :
word.match(/^for$/) ? {type:SyntaxTree.type.operator,subtype:SyntaxTree.subtype.statement} :
word.match(/^(?:break|continue|return|catch|assert|as|is)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:mod)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^in$/) ? {type:SyntaxTree.type.operator} :
word.match(/^(?:else|do)$/) ? {type:SyntaxTree.type.operator} :
word.match(/^\w+$/) ? {type:SyntaxTree.type.label,afix:SyntaxTree.AfixType.nofix} :
word.match(/^[;]$/) ? {type:SyntaxTree.type.sepparator} :
word.match(/^"$/) ? {type:SyntaxTree.type.symbol} ://extra '"'s are caught and are handled later on
//word.match(/^\S+$/) ? "symbol":
(()=>{throw Error(`compiler error: unhandled symbol: '${word}' on line ${line}. Either add a case using 'type:SyntaxTree.type.symbol' for this or add a proper error for this case`)})()
),
indent,
isAfterWhiteSpace,//'+ ='
//parent:undefined,//assigned later, after the expression AST is constructed
}),
word,
words
);
isAfterWhiteSpace = [SyntaxTree.type.whiteSpace,SyntaxTree.type.comment].includes(wordSymbol.type);
if(word.match("\n")){
column = word.match(/(?<=\n)[^\n]*$/)[0].length+1;
line+=[...word.matchAll("\n")].length;
indent = word.match(/(?<=\n)[\t ]*(?=\N*$)/)?.[0]?.length??0;//note '\t \t' => 3 indents
isIndenting = !!word.match(/[\t ]*$/);
}else {
if(isIndenting){
indent+=word.match(/^[\t ]/);
if(word.match(/\S/))isIndenting = false;
}
column+=word.length;
}
words.push(wordSymbol);
};
file.words = words;
return words;
})(text,allRegex,file);//:WordSymbol[]
const NumberType = EnumSymbols("int","uint","float");
interface NumberLiteral {
type:NumberType,
value:Number|Number[],//where Number:i32|f32
}
const getNumber = wordSymbol => {//:NumberType
if("Inf" == wordSymbol.word)
return {valueType:NumberType,value:Infinity};
if("NaN" == wordSymbol.word)
return {valueType:NumberType,value:NaN};
const javascriptIntSize = 32;
assert((1 << javascriptIntSize) == 1);
let numberString = wordSymbol.replaceAll("_","");
let numberMatches = numberString.match(/(^.*?)(?:([IUF])([8|16|32|64|128|size])?)?$/)??[];
assert(numberMatches.length >= 2,"invalid number '" + wordSymbol + "'");
let valueString = numberMatches[1];
let type:""|"I"|"U"|"F" = numberMatches[2] ?? "";
let size:null|Number = numberMatches[3] ? +numberMatches[2] : null;
if(type[0] == "I" && numberString.includes("."))wordSymbol.throwError("syntax", "integers cannot have a decimal point", e=>Error(e));
if(type[0] == "U" && numberString.includes("."))wordSymbol.throwError("syntax", "unsigned integers cannot have a decimal point", e=>Error(e));
let value;
if(size == null || size <= javascriptIntSize)value = +valueString;
else {todo("remove this `else`branch. this untyped language does not have(or need) number types")
let [_,base,numberString] = valueString.match(/(0[box])?(.*)/);
let numbers = [];
for(let i = 0; i < numberString.length; i += javascriptIntSize){
numbers.push(+(base+numberString.substr(i,javascriptIntSize)));
}
value = numbers;
}
return {value,valueType:type};
}
const getString = wordSymbol => {//assume: string is valid
let isExtraLiteralString = !!wordSymbol.word.match(/^r?r#/);
let isRegex = wordSymbol.subtype2 == SyntaxTree.subtype2.regex;
let string = wordSymbol.word.match(/^r?(?:r#+)?"([\s\S]*)"#*/)[1]
.replace(/^\n/,"")
.replace(/\n\t*$/,"")
.replaceAll(/(\n|^)(\t+)/g,(_,m1,m2)=>m1+m2.substr(wordSymbol.indent+1))
.replaceAll("\n","\\n")
.replaceAll("\t","\\t")
;
if(isExtraLiteralString||isRegex){
string = string.replaceAll(/\\(?![nt])/g,"\\\\");
}
string = "\"" + string + "\"";
try{
string = JSON.parse(string);
}catch(err){
wordSymbol.throwError("syntax",`invalid ${isRegex?"regex":"string"} got error:"${err}"`,a=>Error(a))
}
return string;
}
const syntaxTree = ((words)=>{//()->syntaxTree:WordSymbol
let treePartList = [[]];//:(WordSymbol[] & WordSymbol().contence & Tree<WordSymbols>)[]
let bracketLevel = 0;
file.lines = text.split("\n");
let syntaxTree = words.forEach(wordSymbol=>{
let lastTree:WordSymbol[] = treePartList[treePartList.length-2];
if(wordSymbol=="\"")wordSymbol.throwError("syntax", "missing closing quote in string",a=>Error(a));
if(wordSymbol.type == SyntaxTree.type.comment || wordSymbol.type == SyntaxTree.type.whiteSpace)return;
if(wordSymbol.type == SyntaxTree.type.bracket){
if(wordSymbol.subtype == SyntaxTree.subtype.open){
treePartList[treePartList.length-1].push(wordSymbol);
treePartList.push([]);
}
else if(wordSymbol.subtype == SyntaxTree.subtype.closed){
if(!lastTree)
wordSymbol.throwError("syntax",
"extra closing bracket",
a=>Error(a))
;
let openBracket = lastTree[lastTree.length-1];//:WordSymbol ; corresponding open bracket
if({"{": "}", "[": "]", "(": ")"}[openBracket] != wordSymbol.word){
wordSymbol.throwError("syntax",
"unmatching brackets '" + openBracket.word + "' '" + wordSymbol.word + "'"
+"\nopened at: "+openBracket.errorData.display_location()+"\n"
//+openBracket.errorData.display_markWordInLine(" bracket opened", "")+"\n"
,
a=>Error(a));
}
if(treePartList.length == 1)wordSymbol.throwError("syntax", "too many closing brackets",a=>Error(a));
lastTree[lastTree.length-1].contence = treePartList.pop();
lastTree[lastTree.length-1].endBracket = wordSymbol;
}
else throw Error("compiler error: impossible case '"+wordSymbol+"'");
}
else treePartList[treePartList.length-1].push(wordSymbol);
if(wordSymbol.subtype == SyntaxTree.subtype.string || wordSymbol.subtype == SyntaxTree.subtype.formatString)
wordSymbol.value = getString(wordSymbol);
if(wordSymbol.subtype == SyntaxTree.subtype.number)Object.assign(wordSymbol,getNumber(wordSymbol));
});
let tree;//temporty variable
if(treePartList.length > 1)(tree=treePartList[0])[tree.length-1].throwError("syntax", "unclosed bracket",a=>Error(a));
return treePartList[0];
})(words);
super(...syntaxTree);
}
}
class SourceFile{//used for error data
constructor(name){
this.name = name;
}
name;//:string
words;//:WordSymbol[]
lines;//:string[]
};
//----
//----
//main compiler logic
const Public_Object = {
todo,
unimplemented,
loga,
logData,
match,
pass,
assert,
assume,
forBailOld,
forBailGenerator,
matchFlags,
printTree,
EnumSymbols,
SyntaxTree,
WordSymbol,
};
import {parseIntoOperatorSyntaxTree_function} from "./parseOperatorSyntaxTree.ts"//:Function
const parseIntoOperatorSyntaxTree:Function =
parseIntoOperatorSyntaxTree_function(Public_Object);
//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,
};
statements:Expression<SyntaxTree.subtype.Statement|Any>[] = [];//operators that use '#@'; each '#@' refers to a different one
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){
let parentExp = match(exp.wordSymbol.word,[
[["#@"],_=>{
exp.paramRef = context?.statements?.pop();
exp.autoParameterIndex = context?.statements?.length;
}],
[["#","##"],_=>{
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;
}],
]);
if(!exp.paramRef){
let missingStatementName = match(exp.wordSymbol.word,[
[["#", "##", "#\\", "#.."],()=>"function"],
[["#?"],()=>"if statement"],
[["#\\"],()=>"class"],
],()=>"statement");
exp.wordSymbol.throwError("syntax",`missing ${missingStatementName} for parameter`,e=>Error(e));
}
}
function addStatementParameter(parameterName,numOfParameters = 1){
let newParmaters = {...(context.parameters??{})};
let newContext = {...context,parameters:newParmaters};
if(parameterName == "#@"){
context.statements = [];
for(let i=0;i<numOfParameters;i++)context.statements.push(exp)
}
else{
newContext.parameters[parameterName] = [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("#@")],
["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 defaultFunctions_ObjectValue = {
"="():Array{return defualtFunctionsInternal.map(this.array,...arguments)},
">"():Value{return defualtFunctionsInternal.reduce(this.array,...arguments)},
"||":{get(self):Value{return self.array.length}},//length
};
const defaultFunctions_Array = {
"="():Array{return defualtFunctionsInternal.map(this,...arguments)},
">"():Value{return defualtFunctionsInternal.reduce(this,...arguments)},
"||":{get(self):Value{return self.length}},//length
};
const defaultFunctions_number = {
"<"():Array{return defualtFunctionsInternal.iterate(+this,...arguments)},
"="():Array{return defualtFunctionsInternal.repeat(+this,...arguments)},
">"():Value{return defualtFunctionsInternal.reduceForNumber(+this,...arguments)},
};
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|
JavascriptValue
;
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
}
class ValueStatementWrapper{
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<"\\">;
}
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<"\\">;
}
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`
constructor(data={}){Object.assign(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,
Deno,
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,
});
}
fromObjectOrObjectValue(value:ObjectValue|Array|Object):ObjectValue{
return match(value,[
[()=>value instanceof ObjectValue,()=>value],
[()=>value instanceof Array,()=>new ObjectValue({array:value})],