-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutomata.cs
More file actions
1944 lines (1874 loc) · 86.8 KB
/
Automata.cs
File metadata and controls
1944 lines (1874 loc) · 86.8 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
using Automata.Backbone;
using Automata.Utils;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml.Xsl;
namespace Automata
{
namespace Backbone
{
public abstract class BaseValue : IEvaluable
{
public enum ValueType
{
Number,
String,
Object,
Function,
Nil,
AnyType,
}
public ValueType Type;
public object? Value;
public BaseValue Evaluate(Scope currentScope) => this;
public StringValue Stringify() => Stringify(0);
public abstract StringValue Stringify(int indent);
public override bool Equals(object? obj)
{
if (obj is not BaseValue objBV) return false;
return Equals(objBV);
}
public abstract bool Equals(BaseValue other);
public bool HoldsTrue()
{
if (Type == ValueType.Nil) return false;
if (Type != ValueType.Number) return true;
return (double)Value! != 0;
}
public override int GetHashCode() => base.GetHashCode();
public override string ToString() => (string)Stringify().Value!;
public static ValueType ValueTypeFromString(string str)
{
if (str == "number")
return ValueType.Number;
if (str == "string")
return ValueType.String;
if (str == "object")
return ValueType.Object;
if (str == "function")
return ValueType.Function;
throw new Exceptions.InvalidValueType("Invalid value type " + str);
}
}
public class NumberValue : BaseValue
{
public NumberValue(double value)
{
Type = ValueType.Number;
Value = value;
}
public override StringValue Stringify(int _) => new(((double)Value!).ToString(CultureInfo.InvariantCulture));
public override bool Equals(BaseValue other)
{
if (other.Type != ValueType.Number)
return false;
return (double)Value! == (double)other.Value!;
}
}
public class StringValue : BaseValue
{
public StringValue(string value)
{
Type = ValueType.String;
Value = value;
}
public override StringValue Stringify(int _) => this;
public override bool Equals(BaseValue other)
{
if (other.Type != ValueType.String)
return false;
return (string)Value! == (string)other.Value!;
}
public static string EscapeString(string str)
{
StringBuilder sb = new();
for (int i = 0; i < str.Length; i++)
{
if (str[i] != '\\')
{
sb.Append(str[i]);
continue;
}
if (str[i + 1] == '\\' || str[i + 1] == '"')
{
sb.Append(str[i + 1]);
i++;
continue;
}
if (str[i + 1] == 'n')
{
sb.Append('\n');
i++;
continue;
}
if (str[i + 1] == 'x')
{
// check that we have enough characters
if (i + 3 >= str.Length)
throw new Exceptions.InvalidStringFormatException($"Tried escaping ASCII code but string was too short '{str}'");
int asciiCode = Convert.ToInt32(str.Substring(i + 2, 2), 16);
sb.Append(char.ConvertFromUtf32(asciiCode));
i += 3;
continue;
}
throw new Exceptions.InvalidStringFormatException($"Unknown string escape code {str[i + 1]} in string '{str}'");
}
return sb.ToString();
}
}
public class ObjectValue : BaseValue
{
public ObjectValue()
{
Type = ValueType.Object;
Value = new Dictionary<string, BaseValue>();
}
public override StringValue Stringify(int indent)
{
string ret = "{\n";
foreach (var value in (Dictionary<string, BaseValue>)Value!)
ret += (value.Key + ": " + value.Value.Stringify(indent + 2)).Indent(indent + 2) + "\n";
ret += "}".Indent(indent);
return new StringValue(ret);
}
public override bool Equals(BaseValue other)
{
if (other.Type != ValueType.Object)
return false;
var d1 = (Dictionary<string, BaseValue>)Value!;
var d2 = (Dictionary<string, BaseValue>)other.Value!;
return d1 == d2 || d1.Count == d2.Count && !d1.Except(d2).Any();
}
public BaseValue GetChild(string name)
{
var dict = (Dictionary<string, BaseValue>)Value!;
if (!dict.ContainsKey(name))
return NilValue.Nil;
return dict[name];
}
public void SetChild(string name, BaseValue value)
{
var dict = (Dictionary<string, BaseValue>)Value!;
if (value.Type == ValueType.Nil)
dict.Remove(name); // clear memory
else
dict[name] = value;
}
public bool IsArrayConvention()
{
var dict = (Dictionary<string, BaseValue>)Value!;
if (!dict.ContainsKey("length")) return false; // doesn't have length attribute
var len_val = dict["length"];
if (len_val.Type != ValueType.Number) return false; // length value is non-number
var len = (double)len_val.Value!;
if (len < 0 || len != Math.Floor(len)) return false; // length value is negative / not whole
if (dict.Keys.Count != (int)len + 1) return false; // There should be length + 1 keys
var keys = Enumerable.Range(0, (int)len);
return dict.Keys.Where(x => x != "length").All(x => keys.Contains(int.Parse(x)));
}
}
public class FunctionValue : BaseValue
{
public FunctionValue(ICallable value)
{
Type = ValueType.Function;
Value = value;
}
public override StringValue Stringify(int _)
{
string ret = "fun(";
bool firstParam = true;
foreach (var param in ((ICallable)Value!).Head)
{
if (!firstParam)
ret += ", ";
else
firstParam = false;
ret += param.Item1 + " " + param.Item2;
}
return new StringValue(ret + ")");
}
// functions can only be diferentiated by their head
public override bool Equals(BaseValue other)
{
if (other.Type != ValueType.Function)
return false;
var h1 = ((ICallable)Value!).Head;
var h2 = ((ICallable)other.Value!).Head;
return h1 == h2 || h1.Count == h2.Count && !h1.Except(h2).Any();
}
}
public class NilValue : BaseValue
{
public static NilValue Nil => nil;
static readonly NilValue nil = new()
{
Type = ValueType.Nil,
Value = null
};
public override StringValue Stringify(int _) => new("<nil>");
public override bool Equals(BaseValue other)
{
return other.Type == ValueType.Nil;
}
}
public interface ICallable
{
public BaseValue Call(Scope currentScope);
public List<(VarResolver, BaseValue.ValueType)> Head { get; }
}
public class FunctionRunner : ICallable
{
public class ReturnValue : Exception
{
public BaseValue retVal;
public ReturnValue(BaseValue val) => retVal = val;
}
public List<(VarResolver, BaseValue.ValueType)> Head => head;
List<(VarResolver, BaseValue.ValueType)> head;
List<Instruction> body;
public FunctionRunner(List<(VarResolver, BaseValue.ValueType)> head, List<Instruction> body)
{
this.head = head;
this.body = body;
}
public BaseValue Call(Scope currentScope)
{
// use exceptions to handle function return value (it's easier)
try
{
foreach (var instr in body)
instr.Execute(currentScope);
}
catch (ReturnValue retVal)
{
return retVal.retVal;
}
// default return value
return NilValue.Nil;
}
}
public class NativeFunction : ICallable
{
public delegate BaseValue nativeFnScope(BaseValue[] args, Scope scope);
public delegate BaseValue nativeFn(BaseValue[] args);
List<(VarResolver, BaseValue.ValueType)> head;
public List<(VarResolver, BaseValue.ValueType)> Head => head;
nativeFnScope fn;
public NativeFunction(List<(VarResolver, BaseValue.ValueType)> head, nativeFn fn)
{
this.head = head;
this.fn = (args, _) => fn(args);
}
public NativeFunction(List<(VarResolver, BaseValue.ValueType)> head, nativeFnScope fn)
{
this.head = head;
this.fn = fn;
}
public BaseValue Call(Scope currentScope)
{
// extract variables
List<BaseValue> args_eval = [];
foreach(var arg in head)
args_eval.Add(arg.Item1.Evaluate(currentScope));
return fn(args_eval.ToArray(), currentScope);
}
}
public interface IEvaluable
{
public BaseValue Evaluate(Scope currentScope);
}
public class Expression : IEvaluable
{
public IEvaluable lhs;
public IEvaluable? rhs;
public ExpressionOperator op;
public Expression(IEvaluable lhs, ExpressionOperator op, IEvaluable? rhs)
{
this.lhs = lhs;
this.rhs = rhs;
this.op = op;
}
public enum ExpressionOperator
{
Plus,
Minus,
Times,
Div,
Modulo,
Less,
LessEqual,
Greater,
GreaterEqual,
Equal,
NotEqual,
LogicalNot,
LogicalAnd,
LogicalOr,
}
public static ExpressionOperator OperatorFromString(string op)
{
switch(op)
{
case "+":
return ExpressionOperator.Plus;
case "-":
return ExpressionOperator.Minus;
case "*":
return ExpressionOperator.Times;
case "/":
return ExpressionOperator.Div;
case "%":
return ExpressionOperator.Modulo;
case "<":
return ExpressionOperator.Less;
case "<=":
return ExpressionOperator.LessEqual;
case ">":
return ExpressionOperator.Greater;
case ">=":
return ExpressionOperator.GreaterEqual;
case "==":
return ExpressionOperator.Equal;
case "!=":
return ExpressionOperator.NotEqual;
case "!":
return ExpressionOperator.LogicalNot;
case "&&":
return ExpressionOperator.LogicalAnd;
case "||":
return ExpressionOperator.LogicalOr;
default:
throw new Exceptions.UnknownTokenException($"Couldn't convert '{op}' to an operator");
}
}
public BaseValue Evaluate(Scope currentScope)
{
BaseValue lhs_value = lhs.Evaluate(currentScope);
BaseValue? rhs_value = rhs?.Evaluate(currentScope) ?? null;
switch (op)
{
case ExpressionOperator.Plus:
if (rhs == null)
{ // unary operator +
if (lhs_value.Type == BaseValue.ValueType.String)
return new NumberValue(double.Parse((string)lhs_value.Value!, CultureInfo.InvariantCulture));
throw new Exceptions.InvalidOperationException($"Tried converting non-string value {lhs_value.Stringify().Value} to Number");
}
if (lhs_value.Type == BaseValue.ValueType.Number && rhs_value!.Type == BaseValue.ValueType.Number)
return new NumberValue((double)lhs_value.Value! + (double)rhs_value.Value!);
return new StringValue((string)lhs_value.Stringify().Value! + (string)rhs_value!.Stringify().Value!);
case ExpressionOperator.Minus:
if (lhs_value.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"LHS value {lhs_value.Stringify().Value} of operator Minus is not Number");
if (rhs == null) // unary operator -
return new NumberValue(-(double)lhs_value.Value!);
if (rhs_value!.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"RHS value {rhs_value.Stringify().Value} of operator Minus is not Number");
return new NumberValue((double)lhs_value.Value! - (double)rhs_value.Value!);
case ExpressionOperator.Times:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Times");
if (lhs_value.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"LHS value {lhs_value.Stringify().Value} of operator Times is not Number");
if (rhs_value!.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"RHS value {rhs_value!.Stringify().Value} of operator Times is not Number");
return new NumberValue((double)lhs_value.Value! * (double)rhs_value.Value!);
case ExpressionOperator.Div:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Div");
if (lhs_value.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"LHS value {lhs_value.Stringify().Value} of operator Div is not Number");
if (rhs_value!.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"RHS value {rhs_value!.Stringify().Value} of operator Div is not Number");
return new NumberValue((double)lhs_value.Value! / (double)rhs_value.Value!);
case ExpressionOperator.Modulo:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Modulo");
if (lhs_value.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"LHS value {lhs_value.Stringify().Value} of operator Modulo is not Number");
if (rhs_value!.Type != BaseValue.ValueType.Number)
throw new Exceptions.InvalidOperationException($"RHS value {rhs_value!.Stringify().Value} of operator Modulo is not Number");
var val = (double)lhs_value.Value!;
var mod = (double)rhs_value.Value!;
if (mod <= 0) throw new Exceptions.InvalidOperationException($"RHS value {mod} is negative or zero");
while (val < 0) val += mod;
while (val >= mod) val -= mod;
return new NumberValue(val);
case ExpressionOperator.Less:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Less");
if (lhs_value.Type == BaseValue.ValueType.Number && rhs_value!.Type == BaseValue.ValueType.Number)
return new NumberValue(((double)lhs_value.Value! < (double)rhs_value!.Value!) ? 1 : 0);
if (lhs_value.Type == BaseValue.ValueType.String && rhs_value!.Type == BaseValue.ValueType.String)
return new NumberValue(((string)lhs_value.Value!).CompareTo((string)rhs_value!.Value!) < 0 ? 1 : 0);
throw new Exceptions.InvalidOperationException($"Tried comparing {lhs_value.Type} value {lhs_value.Stringify().Value} to {rhs_value!.Type} value {rhs_value!.Stringify().Value}");
case ExpressionOperator.LessEqual:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "LessEqual");
if (lhs_value.Type == BaseValue.ValueType.Number && rhs_value!.Type == BaseValue.ValueType.Number)
return new NumberValue(((double)lhs_value.Value! <= (double)rhs_value!.Value!) ? 1 : 0);
if (lhs_value.Type == BaseValue.ValueType.String && rhs_value!.Type == BaseValue.ValueType.String)
return new NumberValue(((string)lhs_value.Value!).CompareTo((string)rhs_value!.Value!) <= 0 ? 1 : 0);
throw new Exceptions.InvalidOperationException($"Tried comparting {lhs_value.Type} value {lhs_value.Stringify().Value} to {rhs_value!.Type} value {rhs_value!.Stringify().Value}");
case ExpressionOperator.Greater:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Greater");
if (lhs_value.Type == BaseValue.ValueType.Number && rhs_value!.Type == BaseValue.ValueType.Number)
return new NumberValue(((double)lhs_value.Value! > (double)rhs_value!.Value!) ? 1 : 0);
if (lhs_value.Type == BaseValue.ValueType.String && rhs_value!.Type == BaseValue.ValueType.String)
return new NumberValue(((string)lhs_value.Value!).CompareTo((string)rhs_value!.Value!) > 0 ? 1 : 0);
throw new Exceptions.InvalidOperationException($"Tried comparting {lhs_value.Type} value {lhs_value.Stringify().Value} to {rhs_value!.Type} value {rhs_value!.Stringify().Value}");
case ExpressionOperator.GreaterEqual:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "GreaterEqual");
if (lhs_value.Type == BaseValue.ValueType.Number && rhs_value!.Type == BaseValue.ValueType.Number)
return new NumberValue(((double)lhs_value.Value! >= (double)rhs_value!.Value!) ? 1 : 0);
if (lhs_value.Type == BaseValue.ValueType.String && rhs_value!.Type == BaseValue.ValueType.String)
return new NumberValue(((string)lhs_value.Value!).CompareTo((string)rhs_value!.Value!) >= 0 ? 1 : 0);
throw new Exceptions.InvalidOperationException($"Tried comparting {lhs_value.Type} value {lhs_value.Stringify().Value} to {rhs_value!.Type} value {rhs_value!.Stringify().Value}");
case ExpressionOperator.Equal:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "Equal");
return new NumberValue(lhs_value.Equals(rhs_value!) ? 1 : 0);
case ExpressionOperator.NotEqual:
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "NotEqual");
return new NumberValue(lhs_value.Equals(rhs_value!) ? 0 : 1);
case ExpressionOperator.LogicalNot:
return new NumberValue(lhs_value.HoldsTrue() ? 0 : 1);
case ExpressionOperator.LogicalAnd:
{
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "LogicalAnd");
var lhs_eval = lhs_value.HoldsTrue();
var rhs_eval = rhs_value!.HoldsTrue();
return new NumberValue(lhs_eval && rhs_eval ? 1 : 0);
}
case ExpressionOperator.LogicalOr:
{
if (rhs == null)
throw new Exceptions.NullOperandException("RHS", "LogicalOr");
var lhs_eval = lhs_value.HoldsTrue();
var rhs_eval = rhs_value!.HoldsTrue();
return new NumberValue(lhs_eval || rhs_eval ? 1 : 0);
}
}
return NilValue.Nil;
}
}
public class FunctionCall : IEvaluable
{
IEvaluable function;
List<IEvaluable> parameters;
public FunctionCall(IEvaluable function, List<IEvaluable> parameters)
{
this.function = function;
this.parameters = parameters;
}
public BaseValue Evaluate(Scope currentScope)
{
var res = function.Evaluate(currentScope);
if (res.Type != BaseValue.ValueType.Function)
throw new Exceptions.VariableTypeException($"Tried calling non-function value {res.Stringify().Value}");
var fn = (ICallable)res.Value!;
// ensure parameter count
if (fn.Head.Count != parameters.Count)
throw new Exceptions.InvalidParametersException($"Parameter count of {parameters.Count} doesn't match Head of {res.Stringify().Value}");
// evaluate parameters
List<BaseValue> eval = parameters.Select(x => x.Evaluate(currentScope)).ToList();
// ensure parameter type
for (int i = 0; i < parameters.Count; i++)
{
if (fn.Head[i].Item2 == BaseValue.ValueType.AnyType) continue;
if (fn.Head[i].Item2 != eval[i].Type)
throw new Exceptions.InvalidParametersException($"Parameter {i} {eval[i].Stringify().Value} type {eval[i].Type} doesn't match Head {fn.Head[i]}");
}
// scope the function
Scope fnScope = new(currentScope);
// pass the arguments on the scope
for (int i = 0; i < parameters.Count; i++)
fn.Head[i].Item1.Assign(fnScope, eval[i]);
// call the function
return fn.Call(fnScope);
}
}
public class Scope
{
public delegate void logFn(string s);
public delegate string readLineFn();
public logFn LogFunction;
public readLineFn ReadLineFunction;
bool isGlobalScope = false;
Scope parentScope, globalScope;
Dictionary<string, BaseValue> variables = new();
// global scope settings
int maxWhileLoops;
public int MaxWhileLoops => globalScope.maxWhileLoops;
public Scope(int _maxWhileLoops = 10000)
{
isGlobalScope = true;
parentScope = this;
globalScope = this;
maxWhileLoops = _maxWhileLoops;
LogFunction = Console.Write;
ReadLineFunction = Console.ReadLine!;
}
public Scope(Scope outerScope)
{
parentScope = outerScope;
globalScope = outerScope.globalScope;
LogFunction = outerScope.LogFunction;
ReadLineFunction = outerScope.ReadLineFunction;
}
public Scope? GetScopeOfVariable(string var_name)
{
if (var_name.StartsWith('!'))
return this;
if (var_name.StartsWith(':'))
return globalScope;
// try to find variable by traversing scopes
Scope search = this;
while (!search.variables.ContainsKey(var_name) && !search.isGlobalScope)
search = search.parentScope;
if (!search.variables.ContainsKey(var_name))
return null; // couldn't find variable
return search;
}
public BaseValue GetVariable(string var_name)
{
var var_scope = GetScopeOfVariable(var_name);
if (var_scope == null)
return NilValue.Nil;
if (var_name.StartsWith(':') || var_name.StartsWith('!'))
var_name = var_name[1..];
if (!var_scope.variables.ContainsKey(var_name))
return NilValue.Nil;
return var_scope.variables[var_name];
}
public void SetVariable(string var_name, BaseValue value)
{
var var_scope = GetScopeOfVariable(var_name) ?? this;
if (var_name.StartsWith(':') || var_name.StartsWith('!'))
var_name = var_name[1..];
if (value.Type == BaseValue.ValueType.Nil)
var_scope.variables.Remove(var_name); // remove variable to free up memory
else
var_scope.variables[var_name] = value;
}
}
public abstract class VarResolver : IEvaluable
{
public abstract BaseValue Resolve(Scope currentScope);
public abstract void Assign(Scope currentScope, BaseValue value);
public override abstract string ToString();
public BaseValue Evaluate(Scope currentScope) => Resolve(currentScope);
}
public class VarNameResolver : VarResolver
{
string var_name;
public VarNameResolver(string var_name)
{
this.var_name = var_name;
}
public override BaseValue Resolve(Scope currentScope) => currentScope.GetVariable(var_name);
public override void Assign(Scope currentScope, BaseValue value) => currentScope.SetVariable(var_name, value);
public override string ToString() => $"VarNameResolver({var_name})";
}
public class VarObjectResolver : VarResolver
{
VarResolver base_var;
IEvaluable child_name;
public VarObjectResolver(VarResolver base_var, IEvaluable child_name)
{
this.base_var = base_var;
this.child_name = child_name;
}
public override BaseValue Resolve(Scope currentScope)
{
var res = base_var.Resolve(currentScope);
if (res.Type != BaseValue.ValueType.Object)
throw new Exceptions.VariableTypeException($"Base value {res.Value} is not object");
return ((ObjectValue)res).GetChild((string)child_name.Evaluate(currentScope).Stringify().Value!);
}
public override void Assign(Scope currentScope, BaseValue value)
{
var res = base_var.Resolve(currentScope);
if (res.Type != BaseValue.ValueType.Object)
throw new Exceptions.VariableTypeException($"Base value {res.Value} is not object");
((ObjectValue)res).SetChild((string)child_name.Evaluate(currentScope).Stringify().Value!, value);
}
public override string ToString() => $"VarObjectResolver({base_var} -> {child_name})";
}
public class ObjectAccessor : VarResolver
{
public IEvaluable baseExpr;
public IEvaluable accessor;
public ObjectAccessor(IEvaluable baseExpr, IEvaluable accessor)
{
this.baseExpr = baseExpr;
this.accessor = accessor;
}
public override BaseValue Resolve(Scope currentScope)
{
var baseVal = baseExpr.Evaluate(currentScope);
if (baseVal.Type != BaseValue.ValueType.Object)
throw new Exceptions.InvalidOperationException("Tried walking non-object value " + baseVal.Stringify().Value);
var accessVal = accessor.Evaluate(currentScope);
return ((ObjectValue)baseVal).GetChild((string)accessVal.Stringify().Value!);
}
public override void Assign(Scope currentScope, BaseValue value)
{
var baseVal = baseExpr.Evaluate(currentScope);
if (baseVal.Type != BaseValue.ValueType.Object)
throw new Exceptions.InvalidOperationException("Tried walking non-object value " + baseVal.Stringify().Value);
var accessVal = accessor.Evaluate(currentScope);
((ObjectValue)baseVal).SetChild((string)accessVal.Stringify().Value!, value);
}
public override string ToString() => $"ObjectAccessor(({baseExpr}) -> ({accessor}))";
}
public abstract class Instruction
{
public enum InstructionType
{
VarAssign,
FunCall,
IfBlocks,
WhileBlocks,
ForBlocks,
FunctionReturn,
}
public InstructionType Type;
public abstract void Execute(Scope currentScope);
}
public class VarAssignInstruction : Instruction
{
VarResolver var;
IEvaluable value;
public VarAssignInstruction(VarResolver var, IEvaluable value)
{
Type = InstructionType.VarAssign;
this.var = var;
this.value = value;
}
public override void Execute(Scope currentScope) => var.Assign(currentScope, value.Evaluate(currentScope));
}
public class FunCallInstruction : Instruction
{ // this instruction is used when ignoring return type
IEvaluable functionCall;
public FunCallInstruction(IEvaluable functionCall)
{
Type = InstructionType.FunCall;
this.functionCall = functionCall;
}
public override void Execute(Scope currentScope)
{
functionCall.Evaluate(currentScope); // invoke the function
}
}
public class IfBlocksInstruction : Instruction
{
IEvaluable condition;
List<Instruction> trueBlock;
List<Instruction>? falseBlock;
public IfBlocksInstruction(IEvaluable condition, List<Instruction> trueBlock, List<Instruction>? falseBlock)
{
Type = InstructionType.IfBlocks;
this.condition = condition;
this.trueBlock = trueBlock;
this.falseBlock = falseBlock;
}
public override void Execute(Scope currentScope)
{
if(condition.Evaluate(currentScope).HoldsTrue())
{
// scope block
Scope blockScope = new Scope(currentScope);
foreach (var instr in trueBlock)
instr.Execute(blockScope);
}
else if(falseBlock != null)
{
// scope block
Scope blockScope = new Scope(currentScope);
foreach (var instr in falseBlock)
instr.Execute(blockScope);
}
}
}
public class WhileBlocksInstruction : Instruction
{
IEvaluable condition;
List<Instruction> instructions;
public WhileBlocksInstruction(IEvaluable condition, List<Instruction> instructions)
{
Type = InstructionType.WhileBlocks;
this.condition = condition;
this.instructions = instructions;
}
public override void Execute(Scope currentScope)
{
int loopCount = 0;
while(condition.Evaluate(currentScope).HoldsTrue())
{
// scope block
Scope blockScope = new Scope(currentScope);
foreach (var instr in instructions)
instr.Execute(blockScope);
if(++loopCount > currentScope.MaxWhileLoops)
throw new Exceptions.IterationLoopException(currentScope.MaxWhileLoops);
}
}
}
public class ForBlocksInstruction : Instruction
{
VarResolver iter_var;
IEvaluable iter_array;
List<Instruction> instructions;
public ForBlocksInstruction(VarResolver iter_var, IEvaluable iter_array, List<Instruction> instructions)
{
Type = InstructionType.ForBlocks;
this.iter_var = iter_var;
this.iter_array = iter_array;
this.instructions = instructions;
}
public override void Execute(Scope currentScope)
{
// evaluate array which needs to be iterrated
var iter_val = iter_array.Evaluate(currentScope);
// check that the value is object
if (iter_val.Type != BaseValue.ValueType.Object)
throw new Exceptions.VariableTypeException($"Tried running for loop over non-object value {iter_val.Stringify().Value}");
// check that the value is array-convention
var array = (ObjectValue)iter_val;
if(!array.IsArrayConvention())
throw new Exceptions.VariableTypeException($"Tried running for loop over non-array-covention value {iter_val.Stringify().Value}");
var length = (int)(double)array.GetChild("length").Value!;
for(int i = 0; i < length; i++)
{
// scope the block
Scope blockScope = new Scope(currentScope);
// inject iterator variable
iter_var.Assign(blockScope, array.GetChild(i.ToString()));
foreach (var instr in instructions)
instr.Execute(blockScope);
}
}
}
public class FunctionReturnInstruction : Instruction
{
public IEvaluable returnValue;
public FunctionReturnInstruction(IEvaluable returnValue)
{
Type = InstructionType.FunctionReturn;
this.returnValue = returnValue;
}
public override void Execute(Scope currentScope) => throw new FunctionRunner.ReturnValue(returnValue.Evaluate(currentScope));
}
}
namespace Parser
{
public class Token
{
public Token(string val, TokenType type = TokenType.Unknown, uint originalLine = 0)
{
Value = val;
Type = type;
OriginalLine = originalLine;
}
public string Value;
public TokenType Type;
public uint OriginalLine;
public enum TokenType
{
Unknown,
Operator,
Constant,
Variable,
RoundBracket,
SquareBracket,
Comma,
EmptyObject,
Assign,
Keyword,
VarType,
NewLine,
// type used at blocking
UnaryOperator,
}
public static void PrintTokens(List<Token> tokens)
{
Console.WriteLine("--- TOKENS ----");
var maxLen = tokens.MaxBy(x => x.Value.Length)!.Value.Length;
foreach (var token in tokens)
Console.WriteLine(token.Value.PadRight(maxLen) + " " + (token.Type == TokenType.Unknown ? "!! UNKNOWN !!" : token.Type));
Console.WriteLine("---------------");
}
public override string ToString()
{
return $"Token({Type} {Value})";
}
}
public static class ProgramCleaner
{
// prepare the program to be tokenized
public static string CleanProgram(string program)
{
// collapse multi-line instructions
program = program.ReplaceLineEndings("\n").Replace("\\\n", "");
List<string> lines = [];
foreach (var line in program.Split('\n'))
{
var trimmed = line.Trim();
if (trimmed.StartsWith('#'))
continue; // remove comments
if (trimmed.Length == 0)
continue; // remove empty lines
lines.Add(line);
}
// remove in-line comments
for (int i = 0; i < lines.Count; i++)
{
if (!lines[i].Contains('#'))
continue;
int last_comm = lines[i].LastIndexOf('#');
var last_str = lines[i].LastIndexOf('"');
if (last_comm > last_str)
lines[i] = lines[i][..last_comm];
}
return string.Join("\n", [.. lines]);
}
}
public static partial class Tokenizer
{
public static List<Token> Tokenize(string program)
{
List<Token> tokens = [new(program)];
tokens = SplitByLines(tokens);
tokens = ExtractStrings(tokens);
tokens = ExtractVariables(tokens);
tokens = ExtractKeywords(tokens);
tokens = ExtractOperators(tokens);
tokens = ExtractNumbers(tokens);
if (tokens.Where(x => x.Type == Token.TokenType.Unknown).Any())
throw new Exceptions.UnknownTokenException("Found unknown token " + tokens.Where(x => x.Type == Token.TokenType.Unknown).First().Value);
return tokens;
}
static List<Token> CleanTokens(List<Token> oldTokens)
{
List<Token> tokens = [];
foreach (var token in oldTokens)
{
if (token.Type == Token.TokenType.NewLine)
{
// treat new lines separately
tokens.Add(new("", Token.TokenType.NewLine));
continue;
}
if (token.Value.Trim().Length == 0) continue;
tokens.Add(new(token.Value.Trim(), token.Type));
}
return tokens;
}
static List<Token> SplitByLines(List<Token> oldTokens)
{
List<Token> tokens = [];
foreach (var token in oldTokens)
{
if (token.Type != Token.TokenType.Unknown)
{
tokens.Add(token);
continue;
}
var tk = token.Value;
while (tk.Contains('\n'))
{
var idx = tk.IndexOf('\n');
tokens.Add(new(tk[..idx]));
tokens.Add(new("", Token.TokenType.NewLine));
tk = tk[(idx + 1)..];
}
tokens.Add(new(tk));
}
// clean successive line breaks
for (int i = tokens.Count - 1; i > 0; --i)
if (tokens[i].Type == Token.TokenType.NewLine && tokens[i - 1].Type == Token.TokenType.NewLine)
tokens.RemoveAt(i);
return CleanTokens(tokens);
}
static List<Token> ExtractStrings(List<Token> oldTokens)
{
List<Token> tokens = [];
foreach (var token in oldTokens)
{
if (token.Type != Token.TokenType.Unknown)
{
tokens.Add(token);
continue;
}
var tk = token.Value;
while (tk.Contains('"'))
{
var idx = tk.IndexOf('"');
tokens.Add(new(tk[..idx]));
++idx;
while (idx < tk.Length && tk[idx] != '"')
{
if (tk[idx] == '\\')
++idx;
++idx;
}
tokens.Add(new(tk.Substring(tk.IndexOf('"'), idx - tk.IndexOf('"') + 1), Token.TokenType.Constant));
tk = tk[(idx + 1)..];
}
tokens.Add(new(tk));
}
return CleanTokens(tokens);
}
static List<Token> ExtractVariables(List<Token> oldTokens)
{
List<Token> tokens = [];
foreach (var token in oldTokens)
{
if (token.Type != Token.TokenType.Unknown)
{ // token is final
tokens.Add(token);
continue;
}
string tk = token.Value;
while (tk.Contains('$'))
{
var idx = tk.IndexOf('$');
tokens.Add(new(tk[..idx]));
while (idx < tk.Length && tk[idx].IsVarName())
++idx;
tokens.Add(new(tk[tk.IndexOf('$')..idx], Token.TokenType.Variable));
tk = tk[idx..];
}
tokens.Add(new(tk));
}
return CleanTokens(tokens);
}
static readonly string[] VarTypes = ["number", "string", "function", "object", "nil"]; // nil is keyword for NilValue.Nil
static readonly string[] Keywords = ["fun", "nfu", "if", "el", "fi", "while", "ewhil", "for", "rfo", "return", "continue", .. VarTypes];
static List<Token> ExtractKeywords(List<Token> oldTokens)
{
List<Token> tokens = [];
foreach (var token in oldTokens)