forked from jsiek/deduce
-
Notifications
You must be signed in to change notification settings - Fork 0
/
abstract_syntax.py
2955 lines (2432 loc) · 79.2 KB
/
abstract_syntax.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
from dataclasses import dataclass, field
from lark.tree import Meta
from typing import Any, Tuple, List
from error import error, set_verbose, get_verbose
from pathlib import Path
import os
infix_precedence = {'+': 6, '-': 6, '*': 7, '/': 7, '%': 7,
'=': 1, '<': 1, '≤': 1, '≥': 1, '>': 1, 'and': 2, 'or': 3,
'++': 6, '⨄': 6}
prefix_precedence = {'-': 5, 'not': 4}
def copy_dict(d):
return {k:v for k,v in d.items()}
name_id = 0
def generate_name(name):
global name_id
ls = name.split('.')
new_id = name_id
name_id += 1
return ls[0] + '.' + str(new_id)
def base_name(name):
ls = name.split('.')
return ls[0]
import_directories = ["."]
def get_import_directories():
global import_directories
return import_directories
def add_import_directory(dir):
global import_directories
import_directories.append(dir)
recursive_descent = True
def get_recursive_descent():
global recursive_descent
return recursive_descent
def set_recursive_descent(b):
global recursive_descent
recursive_descent = b
@dataclass
class AST:
location: Meta
@dataclass
class Type(AST):
pass
@dataclass
class Term(AST):
typeof: Type
@dataclass
class Formula(Term):
pass
@dataclass
class Proof(AST):
pass
@dataclass
class Statement(AST):
pass
################ Types ######################################
@dataclass
class IntType(Type):
def copy(self):
return IntType(self.location)
def __str__(self):
return 'int'
# def __repr__(self):
# return str(self)
def __eq__(self, other):
return isinstance(other, IntType)
def free_vars(self):
return set()
def substitute(self, sub):
return self
def uniquify(self, env):
pass
@dataclass
class BoolType(Type):
def copy(self):
return BoolType(self.location)
def __str__(self):
return 'bool'
# def __repr__(self):
# return str(self)
def __eq__(self, other):
return isinstance(other, BoolType)
def free_vars(self):
return set()
def substitute(self, sub):
return self
def uniquify(self, env):
pass
def reduce(self, env):
return self
@dataclass
class TypeType(Type):
def copy(self):
return TypeType(self.location)
def __str__(self):
return 'type'
def __eq__(self, other):
return isinstance(other, TypeType)
def free_vars(self):
return set()
def substitute(self, sub):
return self
def uniquify(self, env):
pass
def reduce(self, env):
return self
@dataclass
class OverloadType(Type):
types: List[Tuple[str,Type]]
def __str__(self):
return '(' + ' & '.join([base_name(x) + ': ' + str(ty) for (x,ty) in self.types]) + ')'
def __eq__(self, other):
match other:
case OverloadType(l2, types2):
ret = True
for ((x,t1), (y,t2)) in zip(self.types, types2):
ret = ret and t1 == t2
return ret
case _:
return False
def free_vars(self):
fvs = [t.free_vars() for (x,t) in self.types]
return set().union(*fvs)
def substitute(self, sub):
return OverloadType(self.location, [(x, t.substitute(sub)) for (x,t) in self.types])
def uniquify(self, env):
for (x,t) in self.types:
t.uniquify(env)
def reduce(self, env):
return OverloadType(self.location, [(x, ty.reduce(env)) for (x,ty) in self.types])
@dataclass
class FunctionType(Type):
type_params: List[str]
param_types: List[Type]
return_type: Type
def copy(self):
return FunctionType(self.location,
[p for p in self.type_params],
[ty.copy() for ty in self.param_types],
self.return_type.copy())
def __str__(self):
if len(self.type_params) > 0:
typarams = '<' + ','.join([(x if get_verbose() else base_name(x)) for x in self.type_params]) + '> '
else:
typarams = ''
return '(' + 'fn ' + typarams + ', '.join([str(ty) for ty in self.param_types]) \
+ ' -> ' + str(self.return_type) + ')'
def __eq__(self, other):
match other:
case FunctionType(l2, tv2, pts2, rt2):
ret = True
for (pt1, pt2) in zip(self.param_types, pts2):
ret = ret and pt1 == pt2
return ret and self.return_type == rt2
case _:
return False
def free_vars(self):
fvs = [pt.free_vars() for pt in self.param_types] \
+ [self.return_type.free_vars()]
return set().union(*fvs) - set(self.type_params)
def substitute(self, sub):
n = len(self.type_params)
new_sub = {k:v for (k,v) in sub.items() }
return FunctionType(self.location, self.type_params,
[pt.substitute(new_sub) for pt in self.param_types],
self.return_type.substitute(new_sub))
def uniquify(self, env):
body_env = {x:y for (x,y) in env.items()}
new_type_params = [generate_name(t) for t in self.type_params]
for (old,new) in zip(self.type_params, new_type_params):
body_env[old] = [new]
self.type_params = new_type_params
for p in self.param_types:
p.uniquify(body_env)
self.return_type.uniquify(body_env)
def reduce(self, env):
return FunctionType(self.location, self.type_params,
[ty.reduce(env) for ty in self.param_types],
self.return_type.reduce(env))
@dataclass
class TypeInst(Type):
typ: Type
arg_types: List[Type]
def copy(self):
return TypeInst(self.location,
self.typ.copy(),
[ty.copy() for ty in self.arg_types])
def __str__(self):
return str(self.typ) + \
'<' + ','.join([str(arg) for arg in self.arg_types]) + '>'
def __eq__(self, other):
match other:
case TypeInst(l, typ, arg_types):
return self.typ == typ and \
all([t1 == t2 for (t1, t2) in zip(self.arg_types, arg_types)])
# case GenericUnknownInst(loc, typ):
# return self.typ == typ
case _:
return False
def free_vars(self):
return set().union(*[at.free_vars() for at in self.arg_types])
def substitute(self, sub):
return TypeInst(self.location, self.typ.substitute(sub),
[ty.substitute(sub) for ty in self.arg_types])
def uniquify(self, env):
self.typ.uniquify(env)
for ty in self.arg_types:
ty.uniquify(env)
def reduce(self, env):
return TypeInst(self.location,
self.typ.reduce(env),
[ty.reduce(env) for ty in self.arg_types])
# This is the type of a constructor such as 'empty' of a generic union
# when we do not yet know the type arguments.
@dataclass
class GenericUnknownInst(Type):
typ: Type
def copy(self):
return GenericUnknownInst(self.location, self.typ.copy())
def __str__(self):
return str(self.typ) + '<?>'
def __eq__(self, other):
match other:
# case TypeInst(l, typ, arg_types):
# return self.typ == typ
case GenericUnknownInst(l, typ):
return self.typ == typ
case _:
return False
def free_vars(self):
return set()
def substitute(self, sub):
return self
def uniquify(self, env):
self.typ.uniquify(env)
################ Patterns ######################################
@dataclass
class Pattern(AST):
pass
@dataclass
class PatternBool(Pattern):
value : bool
def __str__(self):
return "true" if self.value else "false"
# def __repr__(self):
# return str(self)
def uniquify(self, env):
pass
def bindings(self):
return []
def set_bindings(self, new_bindings):
pass
@dataclass
class PatternCons(Pattern):
constructor : Term # typically a Var
parameters : List[str]
def bindings(self):
return self.parameters
def set_bindings(self, params):
self.parameters = params
def copy(self):
return PatternCons(self.location,
self.constructor.copy(),
[p for p in self.parameters])
def __str__(self):
if len(self.parameters) > 0:
return str(self.constructor) \
+ '(' + ",".join([base_name(p) for p in self.parameters]) + ')'
else:
return str(self.constructor)
# def __repr__(self):
# return str(self)
def uniquify(self, env):
self.constructor.uniquify(env)
################ Terms ######################################
@dataclass
class Generic(Term):
type_params: List[str]
body: Term
def copy(self):
return Generic(self.location, self.typeof,
[T for T in self.type_params],
self.body.copy())
def __str__(self):
return "generic " + ",".join([(t if get_verbose() else base_name(t)) for t in self.type_params]) \
+ "{" + str(self.body) + "}"
# def __repr__(self):
# return str(self)
def __eq__(self, other):
if not isinstance(other, Generic):
return False
ren = {x: Var(self.location, None, y, [y]) \
for (x,y) in zip(self.type_params, other.type_params) }
new_body = self.body.substitute(ren)
return new_body == other.body
def reduce(self, env):
return Generic(self.location, self.typeof, self.type_params,
self.body.reduce(env))
def substitute(self, sub):
n = len(self.type_params)
new_sub = {k: v for (k,v) in sub.items()}
return Generic(self.location, self.typeof, self.type_params, self.body.substitute(new_sub))
def uniquify(self, env):
body_env = {x:y for (x,y) in env.items()}
new_type_params = [generate_name(x) for x in self.type_params]
for (old,new) in zip(self.type_params, new_type_params):
body_env[old] = [new]
self.type_params = new_type_params
self.body.uniquify(body_env)
@dataclass
class Conditional(Term):
cond: Term
thn: Term
els: Term
def copy(self):
return Conditional(self.location, self.typeof,
self.cond.copy(),
self.thn.copy(), self.els.copy())
def __str__(self):
return '(if ' + str(self.cond) \
+ ' then ' + str(self.thn) \
+ ' else ' + str(self.els) + ')'
def __eq__(self, other):
if not isinstance(other, Conditional):
return False
return self.cond == other.cond and self.thn == other.thn and self.els == other.els
def reduce(self, env):
cond = self.cond.reduce(env)
thn = self.thn.reduce(env)
els = self.els.reduce(env)
match cond:
case Bool(l1, tyof, True):
return thn
case Bool(l1, tyof, False):
return els
case _:
return Conditional(self.location, self.typeof, cond, thn, els)
def substitute(self, sub):
return Conditional(self.location, self.typeof, self.cond.substitute(sub),
self.thn.substitute(sub), self.els.substitute(sub))
def uniquify(self, env):
self.cond.uniquify(env)
self.thn.uniquify(env)
self.els.uniquify(env)
@dataclass
class TAnnote(Term):
subject: Term
typ: Type
def copy(self):
return TAnnote(self.location, self.typeof, self.subject.copy(),
self.typ.copy())
def __str__(self):
return str(self.subject) + ':' + str(self.typ)
def reduce(self, env):
return self.subject.reduce(env)
def substitute(self, sub):
return TAnnote(self.location, self.typeof, self.subject.substitute(sub),
self.typ.substitute(sub))
def uniquify(self, env):
self.subject.uniquify(env)
self.typ.uniquify(env)
@dataclass
class Var(Term):
# name is established upon creation in the parser,
# then updated during type checking
name: str
# filled in during uniquify, list because of overloading
resolved_names: list[str] = field(default_factory=list)
def free_vars(self):
return set([self.name])
def copy(self):
return Var(self.location, self.typeof, self.name, self.resolved_names)
def __eq__(self, other):
if isinstance(other, RecFun):
return self.name == other.name
if not isinstance(other, Var):
return False
return self.name == other.name
def __str__(self):
if isinstance(self.resolved_names, str):
error(self.location, 'resolved_names is a string but should be a list: ' \
+ self.resolved_names)
if base_name(self.name) == 'zero' and not get_verbose():
return '0'
elif base_name(self.name) == 'empty' and not get_verbose():
return '[]'
elif get_verbose():
return self.name + '{' + ','.join(self.resolved_names) + '}'
else:
return base_name(self.name)
def reduce(self, env):
if get_reduce_all() or (self in get_reduce_only()):
res = env.get_value_of_term_var(self)
if res:
if get_verbose():
print('\t var ' + self.name + ' ===> ' + str(res))
return res.reduce(env)
else:
return self
else:
return self
def substitute(self, sub):
if self.name in sub:
trm = sub[self.name]
if not isinstance(trm, RecFun):
add_reduced_def(self.name)
return trm
else:
return self
def uniquify(self, env):
if self.name not in env.keys():
if get_verbose():
keys = '\nenvironment: ' + ', '.join(env.keys())
else:
keys = ''
error(self.location, "undefined variable `" + self.name + "`\t(uniquify)" + keys)
self.resolved_names = env[self.name]
@dataclass
class Int(Term):
value: int
def copy(self):
return Int(self.location, self.typeof, self.value)
def __eq__(self, other):
if not isinstance(other, Int):
return False
return self.value == other.value
def __str__(self):
return str(self.value)
def reduce(self, env):
return self
def substitute(self, sub):
return self
def uniquify(self, env):
pass
@dataclass
class Lambda(Term):
vars: List[Tuple[str,Type]]
body: Term
def copy(self):
return Lambda(self.location, self.typeof,
self.vars,
self.body.copy())
def __str__(self):
if get_verbose():
params = self.vars
else:
params = [(base_name(x), t)for (x,t) in self.vars]
return "λ" + ",".join([x + ':' + str(t) if t else x\
for (x,t) in params]) \
+ "{" + str(self.body) + "}"
def __eq__(self, other):
if not isinstance(other, Lambda):
return False
ren = {x: Var(self.location, t2, y) \
for ((x,t1),(y,t2)) in zip(self.vars, other.vars) }
new_body = self.body.substitute(ren)
return new_body == other.body
def reduce(self, env):
return Lambda(self.location, self.typeof, self.vars, self.body.reduce(env))
def substitute(self, sub):
n = len(self.vars)
new_vars = [(x, t.substitute(sub) if t else None) for (x,t) in self.vars]
return Lambda(self.location, self.typeof, new_vars,
self.body.substitute(sub))
def uniquify(self, env):
body_env = {x:y for (x,y) in env.items()}
for (x,t) in self.vars:
if t:
t.uniquify(env)
new_vars = [(generate_name(x),t) for (x,t) in self.vars]
for ((old,t1),(new,t2)) in zip(self.vars, new_vars):
body_env[old] = [new]
self.vars = new_vars
self.body.uniquify(body_env)
def is_match(pattern, arg, subst):
ret = False
match pattern:
case PatternBool(loc1, value):
match arg:
case Bool(loc2, tyof, arg_value):
ret = arg_value == value
case Var(loc2, ty2, name, rs2):
ret = False
case _:
error(loc1, 'Boolean pattern expected boolean argument, not\n\t' \
+ str(arg))
case PatternCons(loc1, constr, []):
match arg:
case Var(loc2, ty2, name, rs2):
ret = constr == arg
case TermInst(loc3, tyof, arg2, tyargs):
ret = is_match(pattern, arg2, subst)
case _:
ret = False
case PatternCons(loc1, constr, params):
match arg:
case Call(loc2, cty, rator, args, infix):
match rator:
case Var(loc3, ty3, name, rs):
if constr == Var(loc3, ty3, name, rs) and len(params) == len(args):
for (k,v) in zip(params, args):
subst[k] = v
ret = True
else:
ret = False
case TermInst(loc4, tyof, Var(loc3, ty3, name, rs), tyargs):
if constr == Var(loc3, ty3, name, rs) and len(params) == len(args):
for (k,v) in zip(params, args):
subst[k] = v
ret = True
else:
ret = False
case _:
ret = False
case _:
ret = False
case _:
ret = False
if get_verbose():
print('is_match(' + str(pattern) + ', ' + str(arg) + ') = ' + str(ret))
return ret
# The variables that should be reduced.
reduce_only = []
def set_reduce_only(defs):
global reduce_only
reduce_only = defs
def get_reduce_only():
global reduce_only
return reduce_only
reduce_all = False
def get_reduce_all():
global reduce_all
return reduce_all
def set_reduce_all(b):
global reduce_all
reduce_all = b
# Definitions that were reduced.
reduced_defs = set()
def reset_reduced_defs():
global reduced_defs
reduced_defs = set()
def get_reduced_defs():
global reduced_defs
return reduced_defs
def add_reduced_def(df):
global reduced_defs
reduced_defs.add(df)
def is_operator(trm):
match trm:
case Var(loc, tyof, name):
return base_name(name) in infix_precedence.keys() \
or base_name(name) in prefix_precedence.keys()
case RecFun(loc, name, typarams, params, returns, cases):
return base_name(name) in infix_precedence.keys() \
or base_name(name) in prefix_precedence.keys()
case TermInst(loc, tyof, subject, tyargs, inferred):
return is_operator(subject)
case _:
return False
def operator_name(trm):
match trm:
case Var(loc, tyof, name):
return base_name(name)
case RecFun(loc, name, typarams, params, returns, cases):
return base_name(name)
case TermInst(loc, tyof, subject, tyargs):
return operator_name(subject)
case _:
raise Exception('operator_name, unexpected term ' + str(trm))
def precedence(trm):
match trm:
case Call(loc1, tyof, rator, args, infix) if is_operator(rator):
op_name = operator_name(rator)
if len(args) == 2:
return infix_precedence.get(op_name, None)
elif len(args) == 1:
return prefix_precedence.get(op_name, None)
else:
return None
case _:
return None
def op_arg_str(trm, arg):
if precedence(trm) != None and precedence(arg) != None:
if precedence(arg) <= precedence(trm):
return "(" + str(arg) + ")"
return str(arg)
@dataclass
class Call(Term):
rator: Term
args: list[Term]
infix: bool
def copy(self):
ret = Call(self.location, self.typeof,
self.rator.copy(),
[arg.copy() for arg in self.args],
self.infix)
if hasattr(self, 'type_args'):
ret.type_args = self.type_args
return ret
def __str__(self):
if self.infix:
return op_arg_str(self, self.args[0]) + " " + str(self.rator) \
+ " " + op_arg_str(self, self.args[1])
elif isNat(self) and not get_verbose():
return str(natToInt(self))
elif isDeduceInt(self):
return deduceIntToInt(self)
elif isNodeList(self):
return '[' + nodeListToList(self)[:-2] + ']'
elif isEmptySet(self) and not get_verbose():
return '∅'
else:
return str(self.rator) + "(" \
+ ", ".join([str(arg) for arg in self.args])\
+ ")"
def __eq__(self, other):
if not isinstance(other, Call):
return False
eq_rators = self.rator == other.rator
eq_rands = all([arg1 == arg2 for arg1,arg2 in zip(self.args, other.args)])
return eq_rators and eq_rands
def reduce(self, env):
fun = self.rator.reduce(env)
args = [arg.reduce(env) for arg in self.args]
if get_verbose():
print('reduce call ' + str(self))
if get_verbose():
print('rator => ' + str(fun))
if get_verbose():
print('args => ' + ', '.join([str(arg) for arg in args]))
ret = None
match fun:
case Var(loc, ty, '='):
if args[0] == args[1]:
ret = Bool(loc, BoolType(loc), True)
elif constructor_conflict(args[0], args[1], env):
ret = Bool(loc, BoolType(loc), False)
else:
ret = Call(self.location, self.typeof, fun, args, self.infix)
case Lambda(loc, ty, vars, body):
subst = {k: v for ((k,t),v) in zip(vars, args)}
body_env = env
new_body = body.substitute(subst)
old_defs = get_reduce_only()
set_reduce_only(old_defs + [Var(loc, t, x, []) for (x,t) in vars])
ret = new_body.reduce(body_env)
set_reduce_only(old_defs)
case TermInst(loc, tyof, RecFun(loc2, name, typarams, params, returns, cases), type_args):
if get_verbose():
print('call to instantiated generic recursive function')
first_arg = args[0]
rest_args = args[1:]
for fun_case in cases:
subst = {}
if is_match(fun_case.pattern, first_arg, subst):
body_env = env
for (x,ty) in zip(typarams, type_args):
subst[x] = ty
for (k,v) in zip(fun_case.parameters, rest_args):
subst[k] = v
# print('calling ' + name)
# print('call site ' + str(self))
# print('fun_case.body = ' + str(fun_case.body))
# print('subst = ' + ', '.join([k + ': ' + str(v) for (k,v) in subst.items()]))
new_fun_case_body = fun_case.body.substitute(subst)
#print('new_fun_case_body = ' + str(new_fun_case_body))
old_defs = get_reduce_only()
reduce_defs = [x for x in old_defs]
if Var(loc, None, name, []) in reduce_defs:
reduce_defs.remove(Var(loc, None, name, []))
else:
pass
reduce_defs += [Var(loc, None, x, []) \
for x in fun_case.pattern.parameters \
+ fun_case.parameters]
set_reduce_only(reduce_defs)
ret = new_fun_case_body.reduce(body_env)
set_reduce_only(old_defs)
add_reduced_def(name)
result = ret
return result
else:
pass
ret = Call(self.location, self.typeof, fun, args, self.infix)
case RecFun(loc, name, [], params, returns, cases):
if get_verbose():
print('call to recursive function')
first_arg = args[0]
rest_args = args[1:]
for fun_case in cases:
subst = {}
if is_match(fun_case.pattern, first_arg, subst):
body_env = env
for (k,v) in zip(fun_case.parameters, rest_args):
subst[k] = v
new_fun_case_body = fun_case.body.substitute(subst)
old_defs = get_reduce_only()
reduce_defs = [x for x in old_defs]
if Var(loc, None, name, []) in reduce_defs:
reduce_defs.remove(Var(loc, None, name, []))
else:
pass
reduce_defs += [Var(loc, None, x, []) \
for x in fun_case.pattern.parameters \
+ fun_case.parameters]
set_reduce_only(reduce_defs)
ret = new_fun_case_body.reduce(body_env)
set_reduce_only(old_defs)
add_reduced_def(name)
result = ret
return result
else:
pass
ret = Call(self.location, self.typeof, fun, args, self.infix)
case Generic(loc2, tyof, typarams, body):
error(self.location, 'in reduction, call to generic\n\t' + str(self))
case _:
if get_verbose():
print('not reducing call because neutral function: ' + str(fun))
ret = Call(self.location, self.typeof, fun, args, self.infix)
if hasattr(self, 'type_args'):
ret.type_args = self.type_args
if get_verbose():
print('\tcall ' + str(self) + ' returns ' + str(ret))
return ret
def substitute(self, sub):
ret = Call(self.location, self.typeof, self.rator.substitute(sub),
[arg.substitute(sub) for arg in self.args],
self.infix)
if hasattr(self, 'type_args'):
ret.type_args = self.type_args
return ret
def uniquify(self, env):
if False and get_verbose():
print("uniquify call: " + str(self))
self.rator.uniquify(env)
for arg in self.args:
arg.uniquify(env)
if False and get_verbose():
print("uniquify call result: " + str(self))
@dataclass
class SwitchCase(AST):
pattern: Pattern
body: Term
def copy(self):
return SwitchCase(self.location,
self.pattern.copy(),
self.body.copy())
def __str__(self):
return 'case ' + str(self.pattern) + '{' + str(self.body) + '}'
def reduce(self, env):
n = len(self.pattern.parameters)
return SwitchCase(self.location,
PatternCons(self.pattern.location,
self.pattern.constructor,
self.pattern.parameters),
self.body.reduce(env))
def substitute(self, sub):
new_sub = {k: v for (k,v) in sub.items()}
return SwitchCase(self.location,
self.pattern,
self.body.substitute(new_sub))
def uniquify(self, env):
self.pattern.uniquify(env)
body_env = {x:y for (x,y) in env.items()}
match self.pattern:
case PatternBool(loc, value):
pass
case PatternCons(loc, constr, params):
new_params = [generate_name(x) for x in params]
for (old,new) in zip(params, new_params):
body_env[old] = [new]
self.pattern.parameters = new_params
self.body.uniquify(body_env)
def __eq__(self, other):
if not isinstance(other, SwitchCase):
return False
return self.pattern.constructor == other.pattern.constructor \
and self.body == other.body
@dataclass
class Switch(Term):
subject: Term
cases: List[SwitchCase]
def copy(self):
return Switch(self.location, self.typeof,
self.subject.copy(),
[c.copy() for c in self.cases])
def __str__(self):
return 'switch ' + str(self.subject) + ' { ' \
+ ' '.join([str(c) for c in self.cases]) \
+ ' }'
def reduce(self, env):
new_subject = self.subject.reduce(env)
for c in self.cases:
subst = {}
if is_match(c.pattern, new_subject, subst):
if get_verbose():
print('switch, matched ' + str(c.pattern) + ' and ' \
+ str(new_subject))
new_body = c.body.substitute(subst)
new_env = env
old_defs = get_reduce_only()
set_reduce_only(old_defs + [Var(self.location, None, x, []) \
for x in subst.keys()])
ret = new_body.reduce(new_env)
set_reduce_only(old_defs)
return ret
ret = Switch(self.location, self.typeof, new_subject, self.cases)
return ret
def substitute(self, sub):
return Switch(self.location, self.typeof,
self.subject.substitute(sub),
[c.substitute(sub) for c in self.cases])
def uniquify(self, env):
self.subject.uniquify(env)
for c in self.cases:
c.uniquify(env)
def __eq__(self, other):
if not isinstance(other, Switch):
return False