-
Notifications
You must be signed in to change notification settings - Fork 0
/
ast.py
2210 lines (1766 loc) · 74.8 KB
/
ast.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/python3
# Slang AST
import abc
from . import sld
from .lexer import *
from utils import *
DEFAULT_OLEVEL = 0
TAB_SIZE = 4
DEBUG_PRECEDENCE = False
def warn(class_, msg, node, ns):
if (ns.warnclasses and class_ not in ns.warnclasses): return
logexception(Warning(f"{msg} \033[2m(at line {node.lineno}, offset {node.offset})\033[0m \033[8m({class_})\033[0m"), raw=True, once=True)
def eval_literal(x):
return eval(literal_repr(x))
def literal_repr(x):
return (str if (isinstance(x, ASTNode)) else repr)(x)
def literal_type(x):
r = eval(str(x))
if (isinstance(r, str) and len(r) == 1 and re.match(r"'.+?'", x.strip())): return stdlib.char
return type(r)
def common_type(l, ns): # TODO
r = Slist(Signature.build(i, ns) for i in l).uniquize()
r.reverse(); r = r.uniquize()
if (not r): return None
r = [i for i in r if not isinstance(i, stdlib.auto)]
if (len(r) > 1): raise TODO(r)
return first(r)
class ASTNode(ABCSlots):
lineno: ...
offset: ...
flags: ...
@abc.abstractmethod
@init_defaults
def __init__(self, *, lineno, offset, flags: paramset):
self.lineno, self.offset, self.flags = lineno, offset, flags
def __repr__(self):
return f"<{self.typename} `{self.__str__()}' on line {self.lineno}, offset {self.offset}>"
@abc.abstractmethod
def __str__(self):
return ''
@abc.abstractclassmethod
def build(cls, tl):
if (not tl): raise SlSyntaxNoToken()
def validate(self, ns):
for i in allslots(self):
v = getattr(self, i)
if (isiterablenostr(v)):
for jj, j in enumerate(v):
if (hasattr(j, 'validate')):
j.validate(ns)
elif (hasattr(v, 'validate') and not isinstance(v, ASTCodeNode)):
v.validate(ns)
def optimize(self, ns):
for i in allslots(self):
v = getattr(self, i)
if (isiterablenostr(v)):
for jj, j in enumerate(v.copy()):
if (hasattr(j, 'optimize')):
r = j.optimize(ns)
if (r is not None): v[jj] = r
if (v[jj].flags.optimized_out): del v[jj]
elif (hasattr(v, 'optimize') and not isinstance(v, ASTCodeNode)):
r = v.optimize(ns)
if (r is not None): setattr(self, i, r)
if (getattr(self, i).flags.optimized_out): setattr(self, i, None)
self.flags.optimized = 1
@classproperty
def typename(cls):
return cls.__name__[3:-4]
@property
def length(self):
#dlog(max((getattr(self, i) for i in allslots(self) if hasattr(getattr(self, i), 'offset')), key=lambda x: (x.lineno, x.offset)
return sum(getattr(self, i).length for i in allslots(self) if hasattr(getattr(self, i), 'length'))
class ASTRootNode(ASTNode):
code: ...
def __init__(self, code, **kwargs):
super().__init__(**kwargs)
self.code = code
def __repr__(self):
return '<Root>'
def __str__(self):
return '<Root>'
@classmethod
def build(cls, name=None):
code = (yield from ASTCodeNode.build([], name=name))
return cls(code, lineno=code.lineno, offset=code.offset)
def validate(self, ns=None):
if (ns is None): ns = Namespace(self.code.name)
super().validate(ns)
self.code.validate(ns)
return ns
def optimize(self, ns, level=DEFAULT_OLEVEL):
ns.olevel = level
super().optimize(ns)
self.code.optimize(ns)
class ASTCodeNode(ASTNode):
nodes: ...
name: ...
def __init__(self, nodes, *, name='<code>', **kwargs):
super().__init__(**kwargs)
self.nodes, self.name = nodes, name
def __repr__(self):
return f"""<Code{f" `{self.name}'" if (self.name and self.name != '<code>') else ''}>"""
def __str__(self):
return (S('\n').join(map(lambda x: x.join('\n\n') if ('\n' in x) else x, map(str, self.nodes))).indent().replace('\n\n\n', '\n\n').strip('\n').join('\n\n') if (self.nodes) else '').join('{}')
@classmethod
def build(cls, tl, *, name):
if (tl):
cdef = ASTSpecialNode.build(tl)
if (cdef.special != '{'): raise SlSyntaxExpectedError("'{'", cdef)
lineno, offset = cdef.lineno, cdef.offset
else: lineno = offset = None
yield name
nodes = list()
while (True):
c = yield
if (c is None): break
if (lineno is None): lineno, offset = c.lineno, c.offset
nodes.append(c)
return cls(nodes, name=name, lineno=lineno, offset=offset)
#def validate(self, ns): # super
# for i in self.nodes:
# i.validate(ns)
def optimize(self, ns):
for ii, i in enumerate(self.nodes):
r = i.optimize(ns)
if (r is not None): self.nodes[ii] = r
self.nodes = [i for i in self.nodes if not i.flags.optimized_out]
class ASTTokenNode(ASTNode):
length: ...
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.length = sum(len(getattr(self, i)) for i in allslots(self) if isinstance(getattr(self, i, None), str))
@abc.abstractclassmethod
def build(cls, tl):
super().build(tl)
off = int()
for ii, i in enumerate(tl.copy()):
if (i.typename == 'SPECIAL' and (i.token[0] == '#' or i.token == '\\')): del tl[ii-off]; off += 1
if (not tl): raise SlSyntaxEmpty()
class ASTIdentifierNode(ASTTokenNode):
identifier: ...
def __init__(self, identifier, **kwargs):
self.identifier = identifier
super().__init__(**kwargs)
def __str__(self):
return str(self.identifier)
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename != 'IDENTIFIER'): raise SlSyntaxExpectedError('IDENTIFIER', tl[0])
identifier = tl.pop(0).token
return cls(identifier, lineno=lineno, offset=offset)
class ASTKeywordNode(ASTTokenNode):
keyword: ...
def __init__(self, keyword, **kwargs):
self.keyword = keyword
super().__init__(**kwargs)
def __str__(self):
return str(self.keyword)
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename != 'KEYWORD'): raise SlSyntaxExpectedError('KEYWORD', tl[0])
keyword = tl.pop(0).token
return cls(keyword, lineno=lineno, offset=offset)
class ASTLiteralNode(ASTTokenNode):
literal: ...
def __init__(self, literal, **kwargs):
self.literal = literal
super().__init__(**kwargs)
def __str__(self):
return str(self.literal)
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename != 'LITERAL'): raise SlSyntaxExpectedError('LITERAL', tl[0])
literal = tl.pop(0).token
return cls(literal, lineno=lineno, offset=offset)
class ASTOperatorNode(ASTTokenNode):
operator: ...
def __init__(self, operator, **kwargs):
self.operator = operator
super().__init__(**kwargs)
def __str__(self):
return str(self.operator)
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename != 'OPERATOR'): raise SlSyntaxExpectedError('OPERATOR', tl[0])
operator = tl.pop(0).token
return cls(operator, lineno=lineno, offset=offset)
class ASTUnaryOperatorNode(ASTOperatorNode):
@classmethod
def build(cls, tl):
operator = super().build(tl)
if (not isinstance(operator.operator, UnaryOperator)): raise SlSyntaxExpectedError('UnaryOperator', operator)
operator.operator = UnaryOperator(operator.operator)
return operator
class ASTBinaryOperatorNode(ASTOperatorNode):
@classmethod
def build(cls, tl):
operator = super().build(tl)
if (not isinstance(operator.operator, BinaryOperator)): raise SlSyntaxExpectedError('BinaryOperator', operator)
operator.operator = BinaryOperator(operator.operator)
return operator
class ASTSpecialNode(ASTTokenNode):
special: ...
def __init__(self, special, **kwargs):
self.special = special
super().__init__(**kwargs)
def __str__(self):
return str(self.special)
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename != 'SPECIAL'): raise SlSyntaxExpectedError('SPECIAL', tl[0])
special = tl.pop(0).token
if (special == '\\'): raise SlSyntaxEmpty()
return cls(special, lineno=lineno, offset=offset)
class ASTPrimitiveNode(ASTNode): pass
class ASTValueNode(ASTPrimitiveNode):
value: ...
def __init__(self, value, **kwargs):
super().__init__(**kwargs)
self.value = value
def __str__(self):
return str(self.value)
@classmethod
def build(cls, tl, *, fcall=False, attrget=False):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
types = [*allsubclasses(ASTUnaryOperationNode), ASTFunccallNode, ASTItemgetNode, ASTAttrgetNode, ASTIdentifierNode, ASTLambdaNode, ASTLiteralNode, *allsubclasses(ASTLiteralStructNode)]
if (fcall): types.remove(ASTFunccallNode); types.remove(ASTLambdaNode) # XXX lambda too?
if (attrget): types.remove(ASTAttrgetNode)
err = set()
for i in types:
tll = tl.copy()
try: value = i.build(tll, **{'attrget': attrget} if (i in (ASTFunccallNode,)) else {})
except SlSyntaxExpectedError as ex: err.add(ex); continue
except SlSyntaxException: continue
else: tl[:] = tll; break
else: raise SlSyntaxMultiExpectedError.from_list(err)
return cls(value, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
if (isinstance(self.value, ASTIdentifierNode)):
if (self.value.identifier not in ns): raise SlValidationNotDefinedError(self.value, self, scope=ns.scope)
if (ns.values.get(self.value.identifier) is None): raise SlValidationError(f"{self.value.identifier} is not initialized", self.value, self, scope=ns.scope)
def optimize(self, ns):
super().optimize(ns)
if (isinstance(self.value, ASTIdentifierNode) and ns.values.get(self.value) not in (None, ...)): self.value = ns.values[self.value] if (isinstance(ns.values[self.value], ASTNode)) else ASTLiteralNode(literal_repr(ns.values[self.value]), lineno=self.lineno, offset=self.offset) # TODO FIXME in functions
class ASTItemgetNode(ASTPrimitiveNode):
value: ...
key: ...
def __init__(self, value, key, **kwargs):
super().__init__(**kwargs)
self.value, self.key = value, key
def __str__(self):
return f"{self.value}[{self.key}]"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
value = ASTIdentifierNode.build(tl) # TODO: value/expr
bracket = ASTSpecialNode.build(tl)
if (bracket.special != '['): raise SlSyntaxExpectedError("'['", bracket)
start = None
stop = None
step = None
if (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token == ':')): start = ASTExprNode.build(tl)
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ':'):
ASTSpecialNode.build(tl)
if (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token in ']:')): stop = ASTExprNode.build(tl)
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ':'):
ASTSpecialNode.build(tl)
if (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token == ']')): step = ASTExprNode.build(tl)
key = slice(start, stop, step)
else: key = start
bracket = ASTSpecialNode.build(tl)
if (bracket.special != ']'): raise SlSyntaxExpectedError("']'", bracket)
return cls(value, key, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
valsig = Signature.build(self.value, ns)
keysig = Signature.build(self.key, ns)
if ((keysig, self.key) not in valsig.itemget): raise SlValidationError(f"`{valsig}' does not support itemget by key of type `{keysig}'", self.key, self, scope=ns.scope)
class ASTAttrgetNode(ASTPrimitiveNode):
value: ...
optype: ...
attr: ...
def __init__(self, value, optype, attr, **kwargs):
super().__init__(**kwargs)
self.value, self.optype, self.attr = value, optype, attr
def __str__(self):
return f"{self.value}{self.optype}{self.attr}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
value = ASTValueNode.build(tl, attrget=True)
optype = ASTSpecialNode.build(tl)
if (optype.special not in attrops): raise SlSyntaxExpectedError(f"one of {attrops}", optype)
attr = ASTIdentifierNode.build(tl)
return cls(value, optype, attr, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
valsig = Signature.build(self.value, ns)
if ((self.optype.special, self.attr.identifier) not in valsig.attrops): raise SlValidationError(f"`{valsig}' does not support attribute operation `{self.optype}' with attr `{self.attr}'", self.optype, self, scope=ns.scope)
class ASTExprNode(ASTPrimitiveNode):
@classmethod
def build(cls, tl, *, fcall=False, attrget=False):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
for ii, p in enumerate(operators[::-1]):
tll = tl.copy()
try: value = ASTBinaryExprNode.build(tll, p)
except SlSyntaxException: continue
else: tl[:] = tll; return value
for i in allsubclasses(ASTUnaryOperationNode):
tll = tl.copy()
try: value = i.build(tll)
except SlSyntaxException: pass
else: tl[:] = tll; return value
tll = tl.copy()
try: value = ASTUnaryExprNode.build(tll)
except SlSyntaxException: pass
else: tl[:] = tll; return value
tll = tl.copy()
try: value = ASTValueNode.build(tll, fcall=fcall, attrget=attrget)
except SlSyntaxException as ex: pass
else: tl[:] = tll; return value
try:
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != '('): raise SlSyntaxExpectedError('Expr', parenthesis)
parenthesized = list()
lvl = 1
while (tl):
if (tl[0].typename == 'SPECIAL'): lvl += 1 if (tl[0].token == '(') else -1 if (tl[0].token == ')') else 0
if (lvl == 0):
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != ')'): raise SlSyntaxExpectedError("')'", parenthesis)
break
assert (lvl > 0)
parenthesized.append(tl.pop(0))
value = ASTExprNode.build(parenthesized)
if (parenthesized): raise SlSyntaxExpectedNothingError(parenthesized[0])
except SlSyntaxException: pass # TODO
else: return value
raise SlSyntaxExpectedError('Expr', lineno=lineno, offset=offset)
class ASTUnaryExprNode(ASTExprNode):
operator: ...
value: ...
def __init__(self, operator, value, **kwargs):
super().__init__(**kwargs)
self.operator, self.value = operator, value
def __str__(self):
return f"{self.operator}{' ' if (self.operator.operator.isalpha()) else ''}{str(self.value).join('()') if (DEBUG_PRECEDENCE or isinstance(self.value, ASTBinaryExprNode) and operator_precedence(self.value.operator.operator) >= operator_precedence(self.operator.operator)) else self.value}"
@classmethod
def build(cls, tl):
ASTPrimitiveNode.build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
operator = ASTUnaryOperatorNode.build(tl)
value = ASTExprNode.build(tl)
return cls(operator, value, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
valsig = Signature.build(self.value, ns)
op = self.operator.operator
if (op not in valsig.operators): raise SlValidationError(f"`{valsig}' does not support unary operator `{op}'", self.operator, self, scope=ns.scope)
def optimize(self, ns):
super().optimize(ns)
if (isinstance(self.value, ASTUnaryExprNode)): return self.value.value
elif (ns.values.get(self.value) not in (None, ...)): return ASTValueNode(ASTLiteralNode(literal_repr(eval(f"{'not' if (self.operator.operator == '!') else self.operator} ({literal_repr(ns.values[self.value])})")), lineno=self.lineno, offset=self.offset), lineno=self.lineno, offset=self.offset)
class ASTBinaryExprNode(ASTExprNode):
lvalue: ...
operator: ...
rvalue: ...
def __init__(self, lvalue, operator, rvalue, **kwargs):
super().__init__(**kwargs)
self.lvalue, self.operator, self.rvalue = lvalue, operator, rvalue
def __str__(self):
opp = operator_precedence(self.operator.operator)
return f"{str(self.lvalue).join('()') if (DEBUG_PRECEDENCE or isinstance(self.lvalue, ASTBinaryExprNode) and operator_precedence(self.lvalue.operator.operator) > opp) else self.lvalue}{str(self.operator).join(' ') if (self.operator.operator not in '+-**/') else self.operator}{str(self.rvalue).join('()') if (DEBUG_PRECEDENCE or isinstance(self.rvalue, ASTBinaryExprNode) and operator_precedence(self.rvalue.operator.operator) > opp) else self.rvalue}"
@classmethod
def build(cls, tl, opset):
ASTPrimitiveNode.build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
lasti = list()
lvl = int()
for ii, i in enumerate(tl):
if (i.typename == 'SPECIAL'): lvl += 1 if (i.token == '(') else -1 if (i.token == ')') else 0
if (lvl > 0): continue
if (i.typename == 'OPERATOR' and isinstance(i.token, BinaryOperator) and i.token in opset): lasti.append(ii)
for i in lasti[::-1]:
tlr, tll = tl[:i], tl[i:]
err = set()
try:
lvalue = ASTExprNode.build(tlr)
if (tlr): raise SlSyntaxExpectedNothingError(tlr[0])
operator = ASTBinaryOperatorNode.build(tll)
rvalue = ASTExprNode.build(tll)
except SlSyntaxException: pass
else: tl[:] = tll; break
else: raise SlSyntaxExpectedError('BinaryOperator', tl[0])
return cls(lvalue, operator, rvalue, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
lsig = Signature.build(self.lvalue, ns)
rsig = Signature.build(self.rvalue, ns)
op = self.operator.operator
if ((op, rsig) not in lsig.operators): raise SlValidationError(f"`{lsig}' does not support operator `{op}' with operand of type `{rsig}'", self.operator, self, scope=ns.scope)
def optimize(self, ns):
super().optimize(ns)
if (self.operator.operator == '**' and ns.values.get(self.lvalue) == 2 and ns.values.get(self.rvalue) is not ... and (ns.values.get(self.rvalue) or 0) > 0): self.operator.operator, self.lvalue.value = BinaryOperator('<<'), ASTLiteralNode('1', lineno=self.lvalue.value.lineno, offset=self.lvalue.value.offset)
if (ns.values.get(self.lvalue) not in (None, ...) and ns.values.get(self.rvalue) not in (None, ...) and self.operator.operator != 'to'): return ASTValueNode(ASTLiteralNode(literal_repr(eval(f"({literal_repr(ns.values[self.lvalue])}) {self.operator} ({literal_repr(ns.values[self.rvalue])})")), lineno=self.lineno, offset=self.offset), lineno=self.lineno, offset=self.offset)
class ASTLiteralStructNode(ASTNode): pass
class ASTListNode(ASTLiteralStructNode):
type: ...
values: ...
def __init__(self, type, values, **kwargs):
super().__init__(**kwargs)
self.type, self.values = type, values
def __repr__(self):
return f"<List of `{self.type}'>"
def __str__(self):
return f"[{self.type}{': ' if (self.values) else ''}{S(', ').join(self.values)}]"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
bracket = ASTSpecialNode.build(tl)
if (bracket.special != '['): raise SlSyntaxExpectedError("'['", bracket)
type = ASTIdentifierNode.build(tl)
values = list()
if (not (tl[0].typename == 'SPECIAL' and tl[0].token == ']')):
colon = ASTSpecialNode.build(tl)
if (colon.special != ':'): raise SlSyntaxExpectedError("':'", colon)
while (tl and tl[0].typename != 'SPECIAL'):
values.append(ASTExprNode.build(tl))
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ','): ASTSpecialNode.build(tl)
bracket = ASTSpecialNode.build(tl)
if (bracket.special != ']'): raise SlSyntaxExpectedError("']'", bracket)
return cls(type, values, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
typesig = Signature.build(self.type, ns)
for i in self.values:
if (Signature.build(i, ns) != typesig): raise SlValidationError(f"List item `{i}' does not match list type `{self.type}'", i, self, scope=ns.scope)
class ASTTupleNode(ASTLiteralStructNode):
types: ...
values: ...
def __init__(self, types, values, **kwargs):
super().__init__(**kwargs)
self.types, self.values = types, values
def __repr__(self):
return f"<Tuple ({S(', ').join(self.types)})>"
def __str__(self):
return f"({S(', ').join((str(self.types[i])+' ' if (self.types[i] is not None) else '')+str(self.values[i]) for i in range(len(self.values)))}{','*(len(self.values) == 1)})"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != '('): raise SlSyntaxExpectedError("'('", parenthesis)
types = list()
values = list()
while (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token == ')')):
types.append(ASTIdentifierNode.build(tl) if (len(tl) >= 2 and tl[0].typename == 'IDENTIFIER' and tl[1].token != ',') else None)
values.append(ASTExprNode.build(tl))
if (len(values) < 2 or tl and tl[0].typename == 'SPECIAL' and tl[0].token == ','): ASTSpecialNode.build(tl)
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != ')'): raise SlSyntaxExpectedError("')'", parenthesis)
return cls(types, values, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
for i in range(len(self.values)):
if (Signature.build(self.values[i], ns) != Signature.build(self.types[i], ns)): raise SlValidationError(f"Tuple item `{self.values[i]}' does not match its type `{self.types[i]}'", self.values[i], self, scope=ns.scope)
class ASTNonFinalNode(ASTNode): pass
class ASTTypedefNode(ASTNonFinalNode):
modifiers: ...
type: ...
def __init__(self, modifiers, type, **kwargs):
super().__init__(**kwargs)
self.modifiers, self.type = modifiers, type
def __str__(self):
return f"{S(' ').join(self.modifiers)}{' ' if (self.modifiers and self.type) else ''}{self.type or ''}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
modifiers = list()
while (tl and tl[0].typename == 'KEYWORD'):
if (not isinstance(tl[0].token, Modifier)): raise SlSyntaxExpectedError('Modifier', tl[0])
modifiers.append(ASTKeywordNode.build(tl))
type = ASTIdentifierNode.build(tl)
return cls(modifiers, type, lineno=lineno, offset=offset)
class ASTArgdefNode(ASTNonFinalNode):
type: ...
name: ...
modifier: ...
defvalue: ...
def __init__(self, type, name, modifier, defvalue, **kwargs):
super().__init__(**kwargs)
self.type, self.name, self.modifier, self.defvalue = type, name, modifier, defvalue
def __str__(self):
return f"{f'{self.type} ' if (self.type) else ''}{self.name}{self.modifier or ''}{f'={self.defvalue}' if (self.defvalue is not None) else ''}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
type = ASTTypedefNode.build(tl)
name = ASTIdentifierNode.build(tl)
modifier = ASTOperatorNode.build(tl) if (tl and tl[0].typename == 'OPERATOR' and tl[0].token in '+**') else ASTSpecialNode.build(tl) if (tl and tl[0].typename == 'SPECIAL' and tl[0].token in '?=') else None
defvalue = ASTExprNode.build(tl) if (isinstance(modifier, ASTSpecialNode) and modifier.special == '=') else None
return cls(type, name, modifier, defvalue, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
assert (self.modifier != '=' or self.defvalue is not None)
if (isinstance(Signature.build(self.type, ns), stdlib.void)): raise SlValidationError(f"Argument cannot have type `{self.type}'", self.type, self, scope=ns.scope)
@property
def mandatory(self):
return not (self.modifier is not None and self.modifier in '?=')
class ASTCallargsNode(ASTNonFinalNode):
callargs: ...
starargs: ...
def __init__(self, callargs, starargs, **kwargs):
super().__init__(**kwargs)
self.callargs, self.starargs = callargs, starargs
def __str__(self):
return S(', ').join((*self.callargs, *(f'*{i}' for i in self.starargs)))
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
callargs = list()
starargs = list()
if (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token == ')')):
while (tl):
if (tl[0].typename == 'OPERATOR' and tl[0].token == '*'):
ASTOperatorNode.build(tl)
starargs.append(ASTExprNode.build(tl))
elif (len(tl) >= 2 and tl[1].typename == 'SPECIAL' and tl[1].token in '=:'): break
else: callargs.append(ASTExprNode.build(tl))
if (not tl or tl[0].typename != 'SPECIAL' or tl[0].token == ')'): break
comma = ASTSpecialNode.build(tl)
if (comma.special != ','): raise SlSyntaxExpectedError("','", comma)
return cls(callargs, starargs, lineno=lineno, offset=offset)
class ASTCallkwargsNode(ASTNonFinalNode):
callkwargs: ...
starkwargs: ...
def __init__(self, callkwargs, starkwargs, **kwargs):
super().__init__(**kwargs)
self.callkwargs, self.starkwargs = callkwargs, starkwargs
def __str__(self):
return S(', ').join((*(f'{k}={v}' for k, v in self.callkwargs), *(f'**{i}' for i in self.starkwargs)))
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
callkwargs = list()
starkwargs = list()
if (tl and not (tl[0].typename == 'SPECIAL' and tl[0].token == ')')):
while (tl):
if (tl[0].typename == 'OPERATOR' and tl[0].token == '**'):
ASTOperatorNode.build(tl)
starkwargs.append(ASTExprNode.build(tl))
else:
key = ASTIdentifierNode.build(tl)
eq = ASTSpecialNode.build(tl)
if (eq.special not in '=:'): raise SlSyntaxExpectedError("'=' or ':'", eq)
value = ASTExprNode.build(tl)
callkwargs.append((key, value))
if (not tl or tl[0].typename != 'SPECIAL' or tl[0].token == ')'): break
comma = ASTSpecialNode.build(tl)
if (comma.special != ','): raise SlSyntaxExpectedError("','", comma)
return cls(callkwargs, starkwargs, lineno=lineno, offset=offset)
class ASTCallableNode(ASTNode):
def validate(self, ns): # XXX.
super().validate(ns)
code_ns = ns.derive(self.code.name)
if (hasattr(self, 'name')):
code_ns.define(self, redefine=True)
code_ns.values[self.name] = ...
for i in self.argdefs:
code_ns.define(i, redefine=True)
code_ns.values[i.name] = ...
self.code.validate(code_ns)
def optimize(self, ns):
super().optimize(ns)
code_ns = ns.derive(self.code.name)
for i in self.argdefs:
code_ns.values[i.name] = ...
code_ns.values.parent = None # XXX
self.code.optimize(code_ns)
class ASTFunctionNode(ASTCallableNode):
def validate(self, ns): # XXX.
super().validate(ns)
code_ns = ns.derive(self.code.name)
rettype = Signature.build(self.type, ns)
return_nodes = tuple(i.value for i in self.code.nodes if (isinstance(i, ASTKeywordExprNode) and i.keyword.keyword == 'return'))
if (not return_nodes and rettype != stdlib.void()): raise SlValidationError(f"Not returning value from function with return type `{rettype}'", self.code, self, scope=ns.scope)
for i in return_nodes:
fsig = Signature.build(i, code_ns)
if (rettype == stdlib.void() and fsig != rettype): raise SlValidationError(f"Returning value from function with return type `{rettype}'", i, self, scope=ns.scope)
if (common_type((fsig, rettype), code_ns) is None): raise SlValidationError(f"Returning value of incompatible type `{fsig}' from function with return type `{rettype}'", i, self, scope=ns.scope)
class ASTLambdaNode(ASTNonFinalNode, ASTFunctionNode):
argdefs: ...
type: ...
code: ...
def __init__(self, argdefs, type, code, **kwargs):
super().__init__(**kwargs)
self.argdefs, self.type, self.code = argdefs, type, code
def __fsig__(self):
return f"({S(', ').join(self.argdefs)}) -> {self.type}"
def __repr__(self):
return f"<Lambda `{self.__fsig__()} {{...}}' on line {self.lineno}, offset {self.offset}>"
def __str__(self):
return f"{self.__fsig__()} {f'= {self.code.nodes[0].value}' if (len(self.code.nodes) == 1 and isinstance(self.code.nodes[0], ASTKeywordExprNode) and self.code.nodes[0].keyword.keyword == 'return') else self.code}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != '('): raise SlSyntaxExpectedError("'('", parenthesis)
argdefs = list()
while (tl and tl[0].typename != 'SPECIAL'):
argdef = ASTArgdefNode.build(tl)
if (argdefs and argdef.defvalue is None and argdefs[-1].defvalue is not None): raise SlSyntaxError(f"Non-default argument {argdef} follows default argument {argdefs[-1]}")
argdefs.append(argdef)
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ','): ASTSpecialNode.build(tl)
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != ')'): raise SlSyntaxExpectedError("')'", parenthesis)
arrow = ASTSpecialNode.build(tl)
if (arrow.special != '->'): raise SlSyntaxExpectedError("'->'", arrow)
type = ASTTypedefNode.build(tl)
if (tl and (tl[0].typename != 'SPECIAL' or tl[0].token not in (*'={',))): raise SlSyntaxExpectedError("'=' or '{'", tl[0])
cdef = ASTSpecialNode.build(tl)
if (cdef.special != '='): raise SlSyntaxExpectedError('=', cdef)
code = ASTCodeNode([ASTKeywordExprNode(ASTKeywordNode('return', lineno=lineno, offset=offset), ASTExprNode.build(tl), lineno=lineno, offset=offset)], name='<lambda>', lineno=lineno, offset=offset)
return cls(argdefs, type, code, lineno=lineno, offset=offset)
class ASTBlockNode(ASTNonFinalNode):
code: ...
def __init__(self, code, **kwargs):
super().__init__(**kwargs)
self.code = code
def __str__(self):
return str(self.code) if (len(self.code.nodes) > 1) else str(self.code)[1:-1].strip()
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
if (tl[0].typename == 'SPECIAL' and tl[0].token == '{'): code = (yield from ASTCodeNode.build(tl, name='<block>'))
else:
yield '<expr>'
expr = ASTExprNode.build(tl)
code = ASTCodeNode([expr], name='', lineno=expr.lineno, offset=expr.offset)
return cls(code, lineno=lineno, offset=offset)
def validate(self, ns):
super().validate(ns)
self.code.validate(ns)
def optimize(self, ns):
super().optimize(ns)
self.code.optimize(ns)
class ASTFinalNode(ASTNode): pass
class ASTDefinitionNode(ASTNode):
def validate(self, ns): # XXX.
Signature.build(self, ns)
ns.define(self)
super().validate(ns)
class ASTFuncdefNode(ASTFinalNode, ASTDefinitionNode, ASTFunctionNode):
type: ...
name: ...
argdefs: ...
code: ...
def __init__(self, type, name, argdefs, code, **kwargs):
super().__init__(**kwargs)
self.type, self.name, self.argdefs, self.code = type, name, argdefs, code
def __fsig__(self):
return f"{self.type or 'def'} {self.name}({S(', ').join(self.argdefs)})"
def __repr__(self):
return f"<Funcdef `{self.__fsig__()} {{...}}' on line {self.lineno}, offset {self.offset}>"
def __str__(self):
isexpr = (len(self.code.nodes) == 1 and isinstance(self.code.nodes[0], ASTKeywordExprNode) and self.code.nodes[0].keyword.keyword == 'return')
r = f"{self.__fsig__()} {f'= {self.code.nodes[0].value}' if (isexpr) else self.code}"
return r
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
type = ASTTypedefNode.build(tl)
name = ASTIdentifierNode.build(tl)
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != '('): raise SlSyntaxExpectedError("'('", parenthesis)
argdefs = list()
while (tl and tl[0].typename != 'SPECIAL'):
argdef = ASTArgdefNode.build(tl)
if (argdefs and argdef.defvalue is None and argdefs[-1].defvalue is not None): raise SlSyntaxError(f"Non-default argument {argdef} follows default argument {argdefs[-1]}")
argdefs.append(argdef)
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ','): ASTSpecialNode.build(tl)
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != ')'): raise SlSyntaxExpectedError("')'", parenthesis)
if (not tl): raise SlSyntaxExpectedError("'=' or '{'", lineno=lineno, offset=-1)
if (tl[0].typename != 'SPECIAL' or tl[0].token not in (*'={',)): raise SlSyntaxExpectedError("'=' or '{'", tl[0])
if (tl[0].token == '{'): code = (yield from ASTCodeNode.build(tl, name=name.identifier))
else:
cdef = ASTSpecialNode.build(tl)
assert (cdef.special == '=')
yield name.identifier
code = ASTCodeNode([ASTKeywordExprNode(ASTKeywordNode('return', lineno=lineno, offset=offset), ASTExprNode.build(tl), lineno=lineno, offset=offset)], name=name.identifier, lineno=lineno, offset=offset)
return cls(type, name, argdefs, code, lineno=lineno, offset=offset)
class ASTClassdefNode(ASTFinalNode, ASTDefinitionNode, ASTCallableNode):
name: ...
bases: ...
code: ...
type: ...
argdefs = ()
def __init__(self, name, bases, code, **kwargs):
super().__init__(**kwargs)
self.name, self.bases, self.code = name, bases, code
self.type = ASTTypedefNode([], self.name, lineno=self.lineno, offset=self.offset)
def __repr__(self):
return f"<Classdef `{self.name}' on line {self.lineno}, offset {self.offset}>"
def __str__(self):
return f"class {self.name}{S(', ').join(self.bases).join('()') if (self.bases) else ''} {self.code}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
class_ = ASTKeywordNode.build(tl)
if (class_.keyword != 'class'): raise SlSyntaxExpectedError("'class'", class_)
name = ASTIdentifierNode.build(tl)
bases = list()
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == '('):
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != '('): raise SlSyntaxExpectedError("'('", parenthesis)
while (tl and tl[0].typename != 'SPECIAL'):
bases.append(ASTIdentifierNode.build(tl))
if (tl and tl[0].typename == 'SPECIAL' and tl[0].token == ','): ASTSpecialNode.build(tl)
parenthesis = ASTSpecialNode.build(tl)
if (parenthesis.special != ')'): raise SlSyntaxExpectedError("')'", parenthesis)
if (not tl or tl[0].typename != 'SPECIAL' or tl[0].token != '{'): raise SlSyntaxExpectedError("'{'", tl[0])
code = (yield from ASTCodeNode.build(tl, name=name.identifier))
return cls(name, bases, code, lineno=lineno, offset=offset)
class ASTKeywordExprNode(ASTFinalNode):
keyword: ...
value: ...
def __init__(self, keyword, value, **kwargs):
super().__init__(**kwargs)
self.keyword, self.value = keyword, value
def __str__(self):
return f"{self.keyword}{f' {self.value}' if (self.value is not None) else ''}"
@classmethod
def build(cls, tl):
super().build(tl)
lineno, offset = tl[0].lineno, tl[0].offset
keyword = ASTKeywordNode.build(tl)
if (not isinstance(keyword.keyword, ExprKeyword)): raise SlSyntaxExpectedError('ExprKeyword', keyword)
if (keyword.keyword == 'import'):
if (not tl): raise SlSyntaxExpectedMoreTokensError('import', lineno=lineno)
lineno_, offset_ = tl[0].lineno, tl[0].offset
value = ASTIdentifierNode(str().join(tl.pop(0).token for _ in range(len(tl))), lineno=lineno_, offset=offset_) # TODO Identifier? (or document it)
elif (keyword.keyword == 'delete'): value = ASTIdentifierNode.build(tl)
elif (tl): value = ASTExprNode.build(tl)
else: value = None
return cls(keyword, value, lineno=lineno, offset=offset)
def validate(self, ns):
if (self.keyword.keyword == 'import'):
m = re.fullmatch(r'(?:(?:(\w+):)?(?:([\w./]+)/)?([\w.]+):)?([\w*]+)', self.value.identifier)
assert (m is not None)
namespace, path, pkg, name = m.groups()
if (namespace is None): namespace = 'sl'
if (path is None): path = '.'
if (pkg is None): pkg = name
pkg = pkg.replace('.', '/')
if (namespace != 'sl'):
filename = f"{os.path.join(path, pkg)}.sld"
f = sld.parse(open(filename).read())
module_ns = f.namespace
else:
filename = f"{os.path.join(path, pkg)}.sl"
src = open(filename, 'r').read()
try:
tl = parse_string(src)
ast = build_ast(tl, filename)
optimize_ast(ast, validate_ast(ast))
module_ns = validate_ast(ast)
except (SlSyntaxError, SlValidationError) as ex:
ex.srclines = src.split('\n')
raise SlValidationError(f"Error importing {self.value}", self.value, self, scope=ns.scope) from ex
if (name != '*'): ns.define(ASTIdentifierNode(name, lineno=self.value.lineno, offset=self.value.offset)) # TODO object
else: ns.signatures.update(module_ns.signatures) # TODO?
elif (self.keyword.keyword == 'delete'):
if (self.value.identifier not in ns): raise SlValidationNotDefinedError(self.value, self, scope=ns.scope)
ns.delete(self.value)