-
Notifications
You must be signed in to change notification settings - Fork 0
/
lumpy.py
executable file
·4557 lines (3840 loc) · 151 KB
/
lumpy.py
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
#!/usr/bin/env python3
from abc import ABC, abstractmethod
from argparse import ArgumentParser
from collections import UserDict, UserList
from dataclasses import dataclass
from pathlib import Path
from string import ascii_letters, digits, printable, whitespace
from typing import (
Any,
Callable,
Iterable,
Optional,
Self,
SupportsFloat,
Tuple,
Type,
TypeVar,
Union,
final,
)
import code
import enum
import math
import os
import random
import re
import sys
import traceback
def escape(text: str) -> str:
MAPPING = {
"\t": "\\t",
"\n": "\\n",
'"': '\\"',
"\\": "\\\\",
}
return "".join([MAPPING.get(c, c) for c in text])
class InvalidFieldAccess(KeyError):
def __init__(self, value: "Value", field: "Value"):
self.value = value.copy()
self.field = field.copy()
super().__init__(str(self))
def __str__(self) -> str:
return (
f"invalid access into value {self.value} with field {self.field}"
)
class SharedVectorData(UserList["Value"]):
def __init__(self, data: Optional[Iterable["Value"]] = None):
self.uses: int = 0
super().__init__(data)
def copy(self) -> "SharedVectorData":
return SharedVectorData([x.copy() for x in self])
class SharedMapData(UserDict["Value", "Value"]):
def __init__(self, data: Optional[dict["Value", "Value"]] = None):
self.uses: int = 0
super().__init__(data)
def copy(self) -> "SharedMapData":
return SharedMapData(
{k.copy(): v.copy() for k, v in self.data.items()}
)
class SharedSetData(UserDict["Value", None]):
def __init__(self, data: Optional[Iterable["Value"]] = None):
self.uses: int = 0
if data is not None:
super().__init__({k: None for k in data})
else:
super().__init__(None)
def insert(self, element: "Value") -> None:
super().__setitem__(element, None)
def remove(self, element: "Value") -> None:
del self[element]
def copy(self) -> "SharedSetData":
return SharedSetData([k.copy() for k in self.data.keys()])
ValueType = TypeVar("ValueType", bound="Value")
class Value(ABC):
meta: Optional["Map"]
@abstractmethod
def __hash__(self) -> int:
raise NotImplementedError()
@abstractmethod
def __eq__(self, other) -> bool:
raise NotImplementedError()
@abstractmethod
def __str__(self) -> str:
raise NotImplementedError()
def __setitem__(self, key: "Value", value: "Value") -> None:
raise NotImplementedError() # optionally overridden by subclasses
def __getitem__(self, key: "Value") -> "Value":
raise NotImplementedError() # optionally overridden by subclasses
def __delitem__(self, key: "Value") -> None:
raise NotImplementedError() # optionally overridden by subclasses
def __copy__(self):
return self.copy()
def metavalue(self, name: "Value") -> Optional["Value"]:
if self.meta is None:
return None
if name not in self.meta:
return None
return self.meta[name]
def metafunction(
self, name: "Value"
) -> Optional[Union["Function", "Builtin"]]:
if self.meta is None:
return None
if name not in self.meta:
return None
function = self.meta[name]
if not isinstance(function, (Builtin, Function)):
return None
return function
@staticmethod
@abstractmethod
def type() -> str:
raise NotImplementedError()
@abstractmethod
def copy(self) -> Self:
raise NotImplementedError()
@abstractmethod
def cow(self) -> None:
raise NotImplementedError()
@final
@dataclass
class Null(Value):
meta: Optional["Map"] = None
@staticmethod
def new() -> "Null":
# Null values are explicitly not given a metamap by default.
return Null(meta=None)
def __hash__(self) -> int:
return 0
def __eq__(self, other) -> bool:
return type(self) is type(other)
def __str__(self) -> str:
return "null"
@staticmethod
def type() -> str:
return "null"
def copy(self) -> "Null":
return Null(self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@final
@dataclass
class Boolean(Value):
data: bool
meta: Optional["Map"] = None
@staticmethod
def new(data: bool) -> "Boolean":
return Boolean(data, BOOLEAN_META.copy())
def __hash__(self) -> int:
return hash(self.data)
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return self.data == other.data
def __str__(self) -> str:
return "true" if self.data else "false"
@staticmethod
def type() -> str:
return "boolean"
def copy(self) -> "Boolean":
return Boolean(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@final
@dataclass
class Number(Value):
data: SupportsFloat
meta: Optional["Map"]
def __init__(
self, data: SupportsFloat, meta: Optional["Map"] = None
) -> None:
# PEP 484 specifies that when an argument is annotated as having type
# `float`, an argument of type `int` is accepted by the type checker.
# The Lumpy number type is specifically an IEEE-754 double precision
# floating point number, so a float cast is used to ensure the typed
# data is actually a Python float.
self.data = float(data)
self.meta = meta
@staticmethod
def new(data: SupportsFloat) -> "Number":
return Number(data, NUMBER_META.copy())
def __hash__(self) -> int:
return hash(self.data)
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return self.data == other.data
def __int__(self) -> int:
return int(float(self.data))
def __float__(self) -> float:
return float(self.data)
def __str__(self) -> str:
if math.isnan(self.data):
return "NaN"
if self.data == +math.inf:
return "Inf"
if self.data == -math.inf:
return "-Inf"
string = str(self.data)
dot = string.find(".")
end = len(string)
while string[end - 1] == "0":
end -= 1 # Remove trailing zeros.
if dot == end - 1:
end -= 1 # Remove trailing dot.
return string[0:end]
@staticmethod
def type() -> str:
return "number"
def copy(self) -> "Number":
return Number(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@final
@dataclass
class String(Value):
data: str
meta: Optional["Map"] = None
@staticmethod
def new(data: str) -> "String":
return String(data, STRING_META.copy())
def __hash__(self) -> int:
return hash(self.data)
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return self.data == other.data
def __str__(self) -> str:
return f'"{escape(self.data)}"'
def __contains__(self, item) -> bool:
return item in self.data
def __setitem__(self, key: Value, value: Value) -> None:
if not isinstance(key, Number):
raise KeyError("attempted string access using non-number key")
index = float(key.data)
if not index.is_integer():
raise KeyError("attempted string access using non-integer number")
index = int(index)
if index < 0:
raise KeyError("attempted string access using a negative index")
if not (isinstance(value, String) and len(value.data) == 1):
raise KeyError(
f"attempted string assignment with non-character value {value}"
)
characters = list(self.data)
characters[index] = value.data
self.data = "".join(characters)
def __getitem__(self, key: Value) -> Value:
if not isinstance(key, Number):
raise KeyError("attempted string access using non-number key")
index = float(key.data)
if not index.is_integer():
raise KeyError("attempted string access using non-integer number")
index = int(index)
if index < 0:
raise KeyError("attempted string access using a negative index")
index = int(index)
return String(self.data[index])
@staticmethod
def type() -> str:
return "string"
def copy(self) -> "String":
return String(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@final
@dataclass
class Vector(Value):
data: SharedVectorData
meta: Optional["Map"]
def __init__(
self,
data: Optional[Union[SharedVectorData, Iterable[Value]]] = None,
meta: Optional["Map"] = None,
) -> None:
if data is not None and not isinstance(data, SharedVectorData):
data = SharedVectorData(data)
self.data = data if data is not None else SharedVectorData()
self.data.uses += 1
self.meta = meta
@staticmethod
def new(
data: Optional[Union[SharedVectorData, Iterable[Value]]] = None
) -> "Vector":
return Vector(data, VECTOR_META.copy())
def __del__(self):
assert self.data.uses >= 1
self.data.uses -= 1
def __hash__(self) -> int:
return hash(str(self.data))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
if len(self.data) != len(other.data):
return False
for i in range(len(self.data)):
if self.data[i] != other.data[i]:
return False
return True
def __str__(self) -> str:
elements = ", ".join([str(x) for x in self.data])
return f"[{elements}]"
def __contains__(self, item) -> bool:
return item in self.data
def __setitem__(self, key: Value, value: Value) -> None:
if not isinstance(key, Number):
raise KeyError("attempted vector access using non-number key")
index = float(key.data)
if not index.is_integer():
raise KeyError("attempted vector access using non-integer number")
index = int(index)
if index < 0:
raise KeyError("attempted vector access using a negative index")
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
self.data.__setitem__(index, value)
def __getitem__(self, key: Value) -> Value:
if not isinstance(key, Number):
raise KeyError("attempted vector access using non-number key")
index = float(key.data)
if not index.is_integer():
raise KeyError("attempted vector access using non-integer number")
index = int(index)
if index < 0:
raise KeyError("attempted vector access using a negative index")
return self.data.__getitem__(index)
def __delitem__(self, key: Value) -> None:
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
super().__delitem__(key)
@staticmethod
def type() -> str:
return "vector"
def copy(self) -> "Vector":
return Vector(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
self.meta = self.meta.copy() if self.meta else None
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
@final
@dataclass
class Map(Value):
data: SharedMapData
meta: Optional["Map"]
def __init__(
self,
data: Optional[Union[SharedMapData, dict[Value, Value]]] = None,
meta: Optional["Map"] = None,
) -> None:
if data is not None and not isinstance(data, SharedMapData):
data = SharedMapData(data)
self.data = data if data is not None else SharedMapData()
self.data.uses += 1
self.meta = meta
@staticmethod
def new(
data: Optional[Union[SharedMapData, dict[Value, Value]]] = None
) -> "Map":
return Map(data, MAP_META.copy())
def __del__(self):
assert self.data.uses >= 1
self.data.uses -= 1
def __hash__(self) -> int:
return hash(str(self.data))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
if len(self.data) != len(other.data):
return False
for k, v in self.data.items():
if k not in other.data or other.data[k] != v:
return False
return True
def __str__(self) -> str:
if len(self.data) == 0:
return "map{}"
elements = ", ".join(
[f"{str(k)}: {str(v)}" for k, v in self.data.items()]
)
return f"{{{elements}}}"
def __contains__(self, item) -> bool:
return item in self.data
def __setitem__(self, key: Value, value: Value) -> None:
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
try:
self.data.__setitem__(key, value)
except KeyError:
raise InvalidFieldAccess(self, key)
def __getitem__(self, key: Value) -> Value:
try:
return self.data.__getitem__(key)
except KeyError:
raise InvalidFieldAccess(self, key)
def __delitem__(self, key: Value) -> None:
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
try:
self.data.__delitem__(key)
except KeyError:
raise InvalidFieldAccess(self, key)
@staticmethod
def type() -> str:
return "map"
def copy(self) -> "Map":
return Map(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
@final
@dataclass
class Set(Value):
data: SharedSetData
meta: Optional["Map"]
def __init__(
self,
data: Optional[Union[SharedSetData, Iterable[Value]]] = None,
meta: Optional["Map"] = None,
) -> None:
if data is not None and not isinstance(data, SharedSetData):
data = SharedSetData(data)
self.data = data if data is not None else SharedSetData()
self.data.uses += 1
self.meta = meta
@staticmethod
def new(
data: Optional[Union[SharedSetData, Iterable[Value]]] = None
) -> "Set":
return Set(data, SET_META.copy())
def __del__(self):
assert self.data.uses >= 1
self.data.uses -= 1
def __hash__(self) -> int:
return hash(str(self.data))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
if len(self.data) != len(other.data):
return False
for k in self.data.keys():
if k not in other.data:
return False
return True
def __str__(self):
if len(self.data) == 0:
return "set{}"
elements = ", ".join([f"{str(k)}" for k in self.data.keys()])
return f"{{{elements}}}"
def __contains__(self, item) -> bool:
return item in self.data
def insert(self, element: "Value") -> None:
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
self.data.insert(element)
def remove(self, element: "Value") -> None:
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
self.data.remove(element)
@staticmethod
def type() -> str:
return "set"
def copy(self) -> "Set":
return Set(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
if self.data.uses > 1:
self.data.uses -= 1
self.data = self.data.copy() # copy-on-write
self.data.uses += 1
@final
@dataclass
class Reference(Value):
data: Value
meta: Optional["Map"] = None
@staticmethod
def new(data: Value) -> "Reference":
return Reference(data, REFERENCE_META.copy())
def __hash__(self) -> int:
return hash(id(self.data))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return id(self.data) == id(other.data)
def __str__(self):
return f"reference@{hex(id(self.data))}"
@staticmethod
def type() -> str:
return "reference"
def copy(self) -> "Reference":
return Reference(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
# We explicitly do *not* copy self.data as the copied data should still
# point to the original referenced value (the Python `Value` object).
if self.meta is not None:
self.meta.cow()
@final
@dataclass
class Function(Value):
ast: "AstFunction"
env: "Environment"
meta: Optional["Map"] = None
@staticmethod
def new(ast: "AstFunction", env: "Environment") -> "Function":
return Function(ast, env, FUNCTION_META.copy())
def __hash__(self) -> int:
return hash(id(self.ast)) + hash(id(self.env))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return id(self.ast) == id(other.ast)
def __str__(self):
name = self.ast.name.data if self.ast.name is not None else "function"
ugly = any(c not in ascii_letters + digits + "_" + ":" for c in name)
name = f'"{escape(name)}"' if ugly else name
if self.ast.location is not None:
return f"{name}@[{self.ast.location}]"
return f"{name}"
@staticmethod
def type() -> str:
return "function"
def copy(self) -> "Function":
return Function(
self.ast, self.env, self.meta.copy() if self.meta else None
)
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@dataclass
class Builtin(Value):
meta: Optional["Map"] = None
def __post_init__(self):
# Builtins should the name of the builtin as a class property.
self.name: String
def __hash__(self) -> int:
return hash(id(self.function))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return self.function == other.function
def __str__(self):
return f"{self.name.data}@builtin"
@staticmethod
def type() -> str:
return "function"
def copy(self) -> "Builtin":
return self
def call(self, arguments: list[Value]) -> Union[Value, "Error"]:
try:
result = self.function(arguments)
return Null.new() if result is None else result
except Exception as e:
message = f"{e}"
if len(message) == 0:
message = f"encountered exception {type(e).__name__}"
return Error(None, String(message))
@staticmethod
def expect_argument_count(arguments: list[Value], count: int) -> None:
if len(arguments) != count:
raise Exception(
f"invalid argument count (expected {count}, received {len(arguments)})"
)
@staticmethod
def typed_argument(
arguments: list[Value], index: int, ty: Type[ValueType]
) -> ValueType:
argument = arguments[index]
if not isinstance(argument, ty):
raise Exception(
f"expected {ty.type()}-like value for argument {index}, received {typename(argument)}"
)
return argument
@staticmethod
def typed_argument_reference(
arguments: list[Value], index: int, ty: Type[ValueType]
) -> Tuple[Reference, ValueType]:
argument = arguments[index]
if not (
isinstance(argument, Reference) and isinstance(argument.data, ty)
):
raise Exception(
f"expected reference to {ty.type()}-like value for argument {index}, received {typename(argument)}"
)
return (argument, argument.data)
@abstractmethod
def function(self, arguments: list[Value]) -> Union[Value, "Error"]:
raise NotImplementedError()
def cow(self) -> None:
if self.meta is not None:
self.meta.cow()
@dataclass
class BuiltinFromSource(Builtin):
env: Optional["Environment"] = None
def __post_init__(self) -> None:
self.evaled = eval_source(self.source(), self.env)
assert isinstance(self.evaled, Function)
def __hash__(self) -> int:
return hash(id(self.evaled))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return self.evaled == other.evaled
def function(self, arguments: list[Value]) -> Union[Value, "Error"]:
assert isinstance(self.evaled, Function)
return call(None, self.evaled, arguments)
@staticmethod
@abstractmethod
def source() -> str:
raise NotImplementedError()
@dataclass
class External(Value):
data: Any
meta: Optional["Map"] = None
@staticmethod
def new(data: Any) -> "External":
return External(data, meta=None)
def __hash__(self) -> int:
return hash(id(self.data))
def __eq__(self, other) -> bool:
if type(self) is not type(other):
return False
return id(self.data) == id(other.data)
def __str__(self):
return f"external({repr(self.data)})"
@staticmethod
def type() -> str:
return f"external"
def copy(self) -> "External":
# External values are explicitly not given a metamap by default.
return External(self.data, self.meta.copy() if self.meta else None)
def cow(self) -> None:
# We explicitly do *not* copy self.data as the copied data should still
# point to the original external Python object.
if self.meta is not None:
self.meta.cow()
@dataclass
class SourceLocation:
filename: Optional[str]
line: int
def __str__(self) -> str:
if self.filename is None:
return f"line {self.line}"
return f"{self.filename}, line {self.line}"
class TokenKind(enum.Enum):
# Meta
ILLEGAL = "illegal"
EOF = "eof"
# Identifiers and Literals
IDENTIFIER = "identifier"
NUMBER = "number"
STRING = "string"
# Operators
ADD = "+"
SUB = "-"
MUL = "*"
DIV = "/"
REM = "%"
EQ = "=="
NE = "!="
LE = "<="
GE = ">="
LT = "<"
GT = ">"
MKREF = ".&"
DEREF = ".*"
DOT = "."
SCOPE = "::"
ASSIGN = "="
# Delimiters
COMMA = ","
COLON = ":"
SEMICOLON = ";"
LPAREN = "("
RPAREN = ")"
LBRACE = "{"
RBRACE = "}"
LBRACKET = "["
RBRACKET = "]"
# Keywords
NULL = "null"
TRUE = "true"
FALSE = "false"
MAP = "map"
SET = "set"
NOT = "not"
AND = "and"
OR = "or"
LET = "let"
IF = "if"
ELIF = "elif"
ELSE = "else"
FOR = "for"
IN = "in"
WHILE = "while"
BREAK = "break"
CONTINUE = "continue"
TRY = "try"
ERROR = "error"
RETURN = "return"
FUNCTION = "function"
def __str__(self) -> str:
return self.value
@dataclass
class Token:
KEYWORDS = {
# fmt: off
str(TokenKind.NULL): TokenKind.NULL,
str(TokenKind.TRUE): TokenKind.TRUE,
str(TokenKind.FALSE): TokenKind.FALSE,
str(TokenKind.MAP): TokenKind.MAP,
str(TokenKind.SET): TokenKind.SET,
str(TokenKind.NOT): TokenKind.NOT,
str(TokenKind.AND): TokenKind.AND,
str(TokenKind.OR): TokenKind.OR,
str(TokenKind.LET): TokenKind.LET,
str(TokenKind.IF): TokenKind.IF,
str(TokenKind.ELIF): TokenKind.ELIF,
str(TokenKind.ELSE): TokenKind.ELSE,
str(TokenKind.FOR): TokenKind.FOR,
str(TokenKind.IN): TokenKind.IN,
str(TokenKind.WHILE): TokenKind.WHILE,
str(TokenKind.BREAK): TokenKind.BREAK,
str(TokenKind.CONTINUE): TokenKind.CONTINUE,
str(TokenKind.TRY): TokenKind.TRY,
str(TokenKind.ERROR): TokenKind.ERROR,
str(TokenKind.RETURN): TokenKind.RETURN,
str(TokenKind.FUNCTION): TokenKind.FUNCTION,
# fmt: on
}
kind: TokenKind
literal: str
location: Optional[SourceLocation] = None
number: Optional[float] = None
string: Optional[str] = None
def __str__(self) -> str:
if self.kind == TokenKind.EOF:
return f"end-of-file"
if self.kind == TokenKind.ILLEGAL:
prettyable = lambda c: c in printable and c not in whitespace
prettyrepr = lambda c: c if prettyable(c) else f"{ord(c):#04x}"
return "".join(map(prettyrepr, self.literal))
if self.kind == TokenKind.IDENTIFIER:
return f"{self.literal}"
if self.kind == TokenKind.NUMBER:
return f"{self.literal}"
if self.kind == TokenKind.STRING:
return f"{self.literal}"
if self.kind.value in Token.KEYWORDS:
return self.kind.value
return f"{self.kind.value}"
@staticmethod
def lookup_identifier(identifier: str) -> TokenKind:
return Token.KEYWORDS.get(identifier, TokenKind.IDENTIFIER)
class Lexer:
EOF_LITERAL = ""
RE_IDENTIFIER = re.compile(r"^[a-zA-Z_]\w*", re.ASCII)
RE_NUMBER_HEX = re.compile(r"^0x[0-9a-fA-F]+", re.ASCII)
RE_NUMBER_DEC = re.compile(r"^\d+(\.\d+)?", re.ASCII)
def __init__(
self, source: str, location: Optional[SourceLocation] = None
) -> None:
self.source: str = source
# What position does the source "start" being parsed from.
# None if the source is being lexed in a location-independent manner.
self.location: Optional[SourceLocation] = location
self.position: int = 0
@staticmethod
def _is_letter(ch: str) -> bool:
return ch.isalpha() or ch == "_"
def _current_character(self) -> str:
if self.position >= len(self.source):
return Lexer.EOF_LITERAL
return self.source[self.position]
def _peek_character(self) -> str:
if self.position + 1 >= len(self.source):
return Lexer.EOF_LITERAL
return self.source[self.position + 1]
def _is_eof(self) -> bool:
return self.position >= len(self.source)
def _advance_character(self) -> None:
if self._is_eof():
return
if self.location is not None:
self.location.line += self.source[self.position] == "\n"
self.position += 1
def _expect_character(self, character: str) -> None:
assert len(character) == 1
current = self._current_character()
escaped = escape(current)