-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathast.py
919 lines (717 loc) · 24.4 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
#: vim set encoding=utf-8 :
##
# Coal
# Python implementation of the Coal language
#
# Module: Abstract syntax-tree
# version 0.21
##
import sys
# import copy
from stdlib import *
Builtins = CoalBuiltin()
# Globals
returned = False
ret_value = CoalVoid(obj_type='Void')
local_scope = []
current_scope = 0
local_scope.append({
'types': dict(Builtins.types),
'methods': {},
'names': dict(Builtins.names)
})
class Globals(object):
scope_depth = 0
self_ = None
scope = None
flow = False
flow_next = False
flow_break = False
g = Globals()
# Utils
def throwError(p, pos, message):
'''
Throw an error. (Do I need to explain more?)
'''
print('{}.'.format(message))
sys.exit(1)
# Parse a statement
def ExecuteCoal(stmt, scope=local_scope[current_scope]):
# Call
if isinstance(stmt, LocalMethodCall):
selectors = stmt.selectors
selector_args = list(stmt.selector_args)
for i in range(len(selector_args)):
selector_args[i] = ExecuteCoal(selector_args[i], scope)
if selectors in Builtins.public:
return Builtins.call(selectors, selector_args)
elif selectors in scope['methods']:
if g.scope_depth == 0:
n_scope = {
'types': dict(Builtins.types),
'methods': {},
'names': dict(Builtins.names)
}
else:
n_scope = scope
g.scope_depth += 1
defs = scope['methods'][selectors](n_scope,
selector_args)
suite, n_scope, rtype = defs
for st in suite:
result = ExecuteCoal(st, n_scope)
if isinstance(st, FuncRet):
if result.object_type != rtype:
throwError(0, 0,
'TypeError: Invalid return type for "{}": '
'"{}"'
.format(rtype, result.object_type))
g.scope_depth -= 1
return result
g.scope_depth -= 1
elif isinstance(stmt, ObjectMethodCall):
obj = ExecuteCoal(stmt.object, scope)
selectors = stmt.selectors
selector_args = list(stmt.selector_args)
for i in range(len(selector_args)):
selector_args[i] = ExecuteCoal(selector_args[i], scope)
return obj.call(selectors, selector_args)
elif isinstance(stmt, TypeCall):
_type = stmt.type
selectors = stmt.selectors
selector_args = []
if stmt.selector_args is not None:
selector_args = list(stmt.selector_args)
for i in range(len(selector_args)):
selector_args[i] = ExecuteCoal(selector_args[i], scope)
n_scope = {
'types': dict(Builtins.types),
'methods': {},
'names': dict(Builtins.names)
}
# TODO: Currently, an empty instance of "_type_{...}" is created to
# call an internal CoalTypeInit and do the "add arguments to scope"
# thing, then the "real" new CoalObject instance is created and the
# suite is called. Perhaps that's not the right way to do it, as it
# creates an extra, unneeded(?), object. I think I should change
# the structure of user-created types (and instances).
defs = scope['types'][_type](selectors, n_scope, selector_args)
suite, nscope = defs
if _type in scope['types']:
new_obj = scope['types'][_type]
for st in suite:
g.self_ = new_obj
if isinstance(st, SelfAssign):
new_obj.attributes[st.name] = ExecuteCoal(st.value, nscope)
else:
ExecuteCoal(st, scope)
g.self_ = None
return new_obj
elif isinstance(stmt, NameFromSelf):
if g.self_ is None:
throwError(0, 0, 'Call to "self" from outside a type constructor.')
if stmt.name not in g.self_.public:
throwError(0, 0,
'NameError: Unknown name "{}"'
.format(stmt.name))
return g.self_.public[stmt.name]
# Name
elif isinstance(stmt, NameDef):
value = ExecuteCoal(stmt.value, scope)
builtin_types = Builtins.types
if stmt.type in builtin_types:
scope['names'][stmt.name] =\
builtin_types[stmt.type]['init'](value.value,
value.object_type)
elif stmt.type in scope['types']:
if value.object_type != stmt.type:
throwError(0, 0, 'TypeError: Unknown value type for "{}": {}'
.format(stmt.type, value.object_type))
scope['names'][stmt.name] = value
elif isinstance(stmt, NameDefEmpty):
if stmt.type in scope['types']\
or stmt.type == 'Any':
scope['names'][stmt.name] = CoalVoid(obj_type=stmt.type)
else:
throwError(0, 4, 'TypeError: Unknown type "{}"'.format(stmt.type))
# Assignment
elif isinstance(stmt, NameAssign):
value = ExecuteCoal(stmt.value, scope)
if stmt.name not in scope['names']:
throwError(0, 1, 'NameError: Unknown name "{}"'.format(stmt.name))
if isinstance(scope['names'][stmt.name], CoalVoid):
var_type = scope['names'][stmt.name].value
if var_type != 'Any'\
and var_type != value.object_type:
throwError(0, 3, 'TypeError: Wrong value type for Void({}): {}'
.format(var_type, stmt.value.object_type))
else:
var_type = scope['names'][stmt.name].object_type
if var_type != value.object_type:
throwError(0, 3, 'TypeError: Wrong value type for {}: {}'
.format(var_type, value.object_type))
if stmt.mode == '=':
scope['names'][stmt.name] = value
elif stmt.mode == '+=':
scope['names'][stmt.name].value += value.value
elif stmt.mode == '-=':
scope['names'][stmt.name].value -= value.value
elif stmt.mode == '*=':
scope['names'][stmt.name].value *= value.value
elif stmt.mode == '/=':
scope['names'][stmt.name].value /= value.value
elif isinstance(stmt, IterableItemAssign):
index = ExecuteCoal(stmt.index, scope)
value = ExecuteCoal(stmt.value, scope)
if stmt.name not in scope['names']:
throwError(0, 0,
'NameError: Unknown name "{}"'
.format(stmt.name))
name = scope['names'][stmt.name]
if not isinstance(name, CoalIterableObject):
throwError(0, 0, 'Exception: "{}" object is not a writable'
' iterable'.format(name.object_type))
name.assign(index, value)
# Type
# TODO: Lists are fun!
# [ ] Implement private properties.
# [ ] Implement protected properties.
elif isinstance(stmt, TypeDef):
inits = {}
public = {}
protected = {}
private = {}
for st in stmt.suite:
if isinstance(st, TypeInitDef):
inits[st.selectors] = CoalTypeInit(
st.selectors,
st.selector_names,
st.selector_types,
st.selector_aliases,
st.suite
)
# elif isinstance(st, TypePublicDecl):
# for pst in st.suite:
# if isinstance(pst, NameDef):
# public[stmt.name] = ExecuteCoal(stmt.value, scope)
# elif isinstance(pst, FuncDef):
# public[stmt.selectors] = CoalFunction(
# stmt.selectors,
# stmt.selector_names,
# stmt.selector_types,
# stmt.selector_aliases,
# stmt.return_type,
# stmt.suite,
# stmt.simple
# )
# else:
# throwError(0, 0, 'Exception: What are you trying to'
# ' do inside a type definition besides...'
# ' A type definition?')
scope['types'][stmt.name] = CoalType(
stmt.name,
inits,
public,
protected,
private
)
# Function
elif isinstance(stmt, FuncDef):
scope['methods'][stmt.selectors] = CoalFunction(
stmt.selectors,
stmt.selector_names,
stmt.selector_types,
stmt.selector_aliases,
stmt.return_type,
stmt.suite,
stmt.simple
)
elif isinstance(stmt, FuncRet):
return ExecuteCoal(stmt.value, scope)
# Conditional
elif isinstance(stmt, IfBlock):
test = ExecuteCoal(stmt.test, scope)
if test.value and not isinstance(test.value, CoalVoid):
for st in stmt.suite:
ExecuteCoal(st, scope)
return
if stmt.elif_blocks is not None:
for block in stmt.elif_blocks:
test = ExecuteCoal(block[0], scope)
if test.value and not isinstance(test.value, CoalVoid):
for st in block[1]:
ExecuteCoal(st, scope)
return
if stmt.else_suite is not None:
for st in stmt.else_suite:
ExecuteCoal(st, scope)
# Loop
elif isinstance(stmt, ForBlock):
g.flow = True
start = ExecuteCoal(stmt.start, scope)
end = ExecuteCoal(stmt.end, scope)
if stmt.interval is not None:
interval = ExecuteCoal(stmt.interval, scope)
else:
interval = CoalInt(1)
if not isinstance(start, CoalInt)\
or not isinstance(end, CoalInt)\
or (stmt.interval is not None
and not isinstance(interval, CoalInt)):
throwError(0, 0, 'TypeError: The values for "start", '
'"end" and "interval" must be "Int".')
if stmt.name in scope['names']:
var_type = scope['names'][stmt.name].object_type
if var_type != 'Void(Any)' and var_type != 'Int':
throwError(0, 3, 'TypeError: Wrong value type for {}: Int'
.format(var_type))
else:
i = CoalInt(start.value)
scope['names'][stmt.name] = i
while i.value <= end.value:
scope['names'][stmt.name].value = i.value
for st in stmt.suite:
if g.flow_next:
g.flow_next = False
break
elif g.flow_break:
g.flow_break = False
return
ExecuteCoal(st, scope)
i.value += interval.value
del scope['names'][stmt.name]
g.flow = False
elif isinstance(stmt, EachBlock):
g.flow = True
iterable = ExecuteCoal(stmt.iterable, scope)
if not isinstance(iterable, CoalIterableObject):
throwError('TypeError: "{}" object is not iterable.'
.format(iterable.object_type))
if stmt.name in scope['names']:
var_type = scope['names'][stmt.name].object_type
else:
scope['names'][stmt.name] = CoalVoid(obj_type='Any')
length = iterable.call('length:', []).value
i = CoalInt(0)
while i.value < length:
scope['names'][stmt.name] = iterable.iter(i)
for st in stmt.suite:
if g.flow_next:
g.flow_next = False
break
elif g.flow_break:
g.flow_break = False
return
ExecuteCoal(st, scope)
i.value += 1
del scope['names'][stmt.name]
g.flow = False
elif isinstance(stmt, WhileBlock):
g.flow = True
test = ExecuteCoal(stmt.test, scope)
while test.value:
for st in stmt.suite:
if g.flow_next:
g.flow_next = False
break
elif g.flow_break:
g.flow_break = False
return
ExecuteCoal(st, scope)
test = ExecuteCoal(stmt.test, scope)
g.flow = False
elif isinstance(stmt, FlowBreak):
if not g.flow:
throwError('SyntaxError: Invalid syntax: "break".')
g.flow_break = True
elif isinstance(stmt, FlowNext):
if not g.flow:
throwError('SyntaxError: Invalid syntax: "next".')
g.flow_next = True
# Expression
elif type(stmt).__name__ in ['ExprAddition',
'ExprSubtraction',
'ExprMultiplication',
'ExprDivision',
'ExprModulo',
'ExprBitAnd',
'ExprBitOr',
'ExprBitXor',
'ExprBitShiftR',
'ExprBitShiftL',
'ExprEqual',
'ExprNotEqual',
'ExprGreater',
'ExprLess',
'ExprEqualGreater',
'ExprEqualLess']:
a = ExecuteCoal(stmt.a, scope)
b = ExecuteCoal(stmt.b, scope)
# a_type = a.object_type
# b_type = b.object_type
# if all(a_type != t for t in ('Int', 'Float'))\
# or all(b_type != t for t in ('Int', 'Float')):
# throwError(0, 0, 'TypeError: Invalid types for "+": {}, {}'
# .format(a_type, b_type))
expr_type = type(stmt).__name__
if expr_type == 'ExprAddition':
result = a.value + b.value
elif expr_type == 'ExprSubtraction':
result = a.value - b.value
elif expr_type == 'ExprMultiplication':
result = a.value * b.value
elif expr_type == 'ExprDivision':
result = a.value / b.value
elif expr_type == 'ExprModulo':
result = a.value % b.value
elif expr_type == 'ExprBitAnd':
result = a.value & b.value
elif expr_type == 'ExprBitOr':
result = a.value | b.value
elif expr_type == 'ExprBitXor':
result = a.value ^ b.value
elif expr_type == 'ExprBitShiftR':
result = a.value >> b.value
elif expr_type == 'ExprBitShiftL':
result = a.value << b.value
elif expr_type == 'ExprEqual':
result = 'true' if a.value == b.value else 'false'
elif expr_type == 'ExprNotEqual':
result = 'false' if a.value == b.value else 'true'
elif expr_type == 'ExprGreater':
result = 'true' if a.value > b.value else 'false'
elif expr_type == 'ExprLess':
result = 'true' if a.value < b.value else 'false'
elif expr_type == 'ExprEqualGreater':
result = 'true' if a.value >= b.value else 'false'
elif expr_type == 'ExprEqualLess':
result = 'true' if a.value <= b.value else 'false'
if type(result) == int:
return CoalInt(result)
elif type(result) == float:
return CoalFloat(result)
else:
return CoalBool(result)
# Value
elif isinstance(stmt, Value):
if isinstance(stmt, Name):
if stmt.name not in scope['names']:
throwError(0, 0,
'NameError: Unknown name "{}"'
.format(stmt.name))
return scope['names'][stmt.name]
elif isinstance(stmt, ItemFromIterable):
iter_name = ExecuteCoal(stmt.name, scope)
iter_start = ExecuteCoal(stmt.index, scope)
if stmt.end is None:
iter_end = None
else:
iter_end = ExecuteCoal(stmt.end, scope)
return iter_name.iter(iter_start, iter_end)
elif isinstance(stmt, Void):
return CoalVoid(stmt.value)
elif isinstance(stmt, Bool):
return CoalBool(stmt.value)
elif isinstance(stmt, Int):
return CoalInt(stmt.value)
elif isinstance(stmt, Float):
return CoalFloat(stmt.value)
elif isinstance(stmt, String):
return CoalString(stmt.value)
elif isinstance(stmt, List):
value = []
for i in range(len(stmt.value)):
value.append(ExecuteCoal(stmt.value[i], scope))
return CoalList(value)
# Exit the program
elif isinstance(stmt, Exit):
result = ExecuteCoal(stmt.value, scope)
if not isinstance(result, CoalInt) and\
not isinstance(result, CoalBool):
throwError(0, 0,
'TypeError: The program must return "Int" or "Bool".')
sys.exit(result.value)
# Empty return
return CoalVoid()
# For organization sake
class CoalAST(object):
pass
# Call
class LocalMethodCall(CoalAST):
def __init__(self,
selectors,
selector_args):
self.selectors = selectors
self.selector_args = selector_args
class ObjectMethodCall(CoalAST):
def __init__(self,
_object,
selectors,
selector_args):
self.object = _object
self.selectors = selectors
self.selector_args = selector_args
class ObjectPropertyCall(CoalAST):
def __init__(self,
_object,
_property):
self.object = _object
self.property = _property
class TypeCall(CoalAST):
def __init__(self,
_type,
selectors=None,
selector_args=None):
self.type = _type
self.selectors = selectors
self.selector_args = selector_args
# Name
class NameDef(CoalAST):
def __init__(self,
name,
_type,
value):
self.name = name
self.type = _type
self.value = value
class NameDefEmpty(CoalAST):
def __init__(self,
name,
_type):
self.name = name
self.type = _type
class NameAssign(CoalAST):
def __init__(self,
name,
mode,
value):
self.name = name
self.mode = mode
self.value = value
class IterableItemAssign(CoalAST):
def __init__(self,
name,
index,
value):
self.name = name
self.index = index
self.value = value
# Function
class FuncDef(CoalAST):
def __init__(self,
selector_names,
selector_types,
selector_aliases,
return_type,
suite,
simple=False):
self.selectors = ''
self.selector_names = selector_names
self.selector_types = selector_types
self.selector_aliases = selector_aliases
self.return_type = return_type
self.suite = suite
self.simple = simple
for selector in selector_names:
self.selectors += '{}:'.format(selector)
class FuncRet(CoalAST):
def __init__(self,
value):
self.value = value
# Type (TODO)
class TypeDef(CoalAST):
def __init__(self,
name,
extends,
suite):
self.name = name
self.extends = extends
self.suite = suite
class TypeInitDef(CoalAST):
def __init__(self,
selector_names,
selector_types,
selector_aliases,
suite):
self.selectors = ''
self.selector_names = selector_names
self.selector_types = selector_types
self.selector_aliases = selector_aliases
self.suite = suite
for selector in selector_names:
self.selectors += '{}:'.format(selector)
class SelfAssign(CoalAST):
def __init__(self,
name,
value):
self.name = name
self.value = value
class NameFromSelf(CoalAST):
def __init__(self,
name):
self.name = name
class SelfRet(CoalAST):
pass
class NameAsSelector(CoalAST):
def __init__(self,
name):
self.name = name
# Conditional
class IfBlock(CoalAST):
def __init__(self,
test,
suite,
elif_blocks=None,
else_suite=None):
self.test = test
self.suite = suite
self.elif_blocks = elif_blocks
self.else_suite = else_suite
# Loop
class ForBlock(CoalAST):
def __init__(self,
start,
end,
interval,
name,
suite):
self.start = start
self.end = end
self.interval = interval
self.name = name
self.suite = suite
class EachBlock(CoalAST):
def __init__(self,
iterable,
name,
suite):
self.iterable = iterable
self.name = name
self.suite = suite
class WhileBlock(CoalAST):
def __init__(self,
test,
suite):
self.test = test
self.suite = suite
class FlowBreak(CoalAST):
pass
class FlowNext(CoalAST):
pass
# Expression
class ExprAddition(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprSubtraction(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprMultiplication(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprDivision(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprModulo(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprEqual(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprExact(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprNotEqual(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprGreater(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprEqualGreater(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprLess(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
class ExprEqualLess(CoalAST):
def __init__(self,
a,
b):
self.a = a
self.b = b
# Value
class Value(CoalAST):
pass
class Name(Value):
def __init__(self,
name):
self.name = name
class ItemFromIterable(Value):
def __init__(self,
name,
index,
end=None):
self.name = name
self.index = index
self.end = end
class Void(Value):
def __init__(self,
value):
self.value = value
class Bool(Value):
def __init__(self,
value):
self.value = value
class Int(Value):
def __init__(self,
value):
self.value = int(value)
class Float(Value):
def __init__(self,
value):
self.value = float(value)
class String(Value):
def __init__(self,
value):
self.value = str(value)
class List(Value):
def __init__(self,
value):
self.value = list(value)
# Exit
class Exit(CoalAST):
def __init__(self,
value):
self.value = value