-
Notifications
You must be signed in to change notification settings - Fork 108
/
Copy pathlhs_pars.py
2836 lines (2354 loc) · 86.3 KB
/
lhs_pars.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
#
# Copyright 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#
from __future__ import print_function
from __future__ import absolute_import
import re
import sys
import os
import six
from six.moves import map
from six.moves import range
from six.moves import zip
from functools import reduce
import braces
from msgs import error, warning
class Call(object):
def __init__(self):
self.restr = None
self.decls_only = False
self.instanceproofs = False
self.bodies_only = False
self.bad_type_assignment = False
self.body = False
self.current_context = []
class Def(object):
def __init__(self):
self.type = None
self.defined = None
self.body = None
self.line = None
self.sig = None
self.instance_proofs = []
self.instance_extras = []
self.comments = []
self.primrec = None
self.deriving = []
self.instance_defs = {}
def parse(call):
"""Parses a file."""
set_global(call)
defs = get_defs(call.filename)
lines = get_lines(defs, call)
lines = perform_module_redirects(lines, call)
return ['%s\n' % line for line in lines]
def settings_line(l):
"""Adjusts some global settings."""
bits = l.split(',')
for bit in bits:
bit = bit.strip()
(kind, setting) = bit.split('=')
kind = kind.strip()
if kind == 'keep_constructor':
[cons] = setting.split()
keep_conss[cons] = 1
else:
assert not "setting kind understood", bit
def set_global(_call):
global call
call = _call
global filename
filename = _call.filename
file_defs = {}
def splitList(list, pred):
"""Splits a list according to pred."""
result = []
el = []
for l in list:
if pred(l):
if el != []:
result.append(el)
el = []
else:
el.append(l)
if el != []:
result.append(el)
return result
def takeWhile(list, pred):
"""Returns the initial portion of the list where each
element matches pred"""
limit = 0
for l in list:
if pred(l):
limit = limit + 1
else:
break
return list[0:limit]
def get_defs(filename):
# if filename in file_defs:
# return file_defs[filename]
cmdline = os.environ['L4CPP']
f = os.popen('cpp -Wno-invalid-pp-token -traditional-cpp %s %s' %
(cmdline, filename))
input = [line.rstrip() for line in f]
f.close()
defs = top_transform(input, filename.endswith(".lhs"))
file_defs[filename] = defs
return defs
def top_transform(input, isLhs):
"""Top level transform, deals with lhs artefacts, divides
the code up into a series of seperate definitions, and
passes these definitions through the definition transforms."""
to_process = []
comments = []
for n, line in enumerate(input):
if '\t' in line:
warning('tab in line %d, %s.\n' % (n, filename))
if isLhs:
if line.startswith('> '):
if '--' in line:
line = line.split('--')[0].strip()
if line[2:].strip() == '':
comments.append((n, 'C', ''))
elif line.startswith('> {-#'):
comments.append((n, 'C', '(*' + line + '*)'))
else:
to_process.append((line[2:], n))
else:
if line.strip():
comments.append((n, 'C', '(*' + line + '*)'))
else:
comments.append((n, 'C', ''))
else:
if '--' in line:
line = line.split('--')[0].rstrip()
if line.strip() == '':
comments.append((n, 'C', ''))
elif line.strip().startswith('{-'):
# single-line {- -} comments only
comments.append((n, 'C', '(*' + line + '*)'))
elif line.startswith('#'):
# preprocessor directives
comments.append((n, 'C', '(*' + line + '*)'))
else:
to_process.append((line, n))
def_tree = offside_tree(to_process)
defs = create_defs(def_tree)
defs = group_defs(defs)
# Forget about the comments for now
# defs_plus_comments = [d.line, d) for d in defs] + comments
# defs_plus_comments.sort()
# defs = []
# prev_comments = []
# for term in defs_plus_comments:
# if term[1] == 'C':
# prev_comments.append(term[2])
# else:
# d = term[1]
# d.comments = prev_comments
# defs.append(d)
# prev_comments = []
# apply def_transform and cut out any None return values
defs = [defs_transform(d) for d in defs]
defs = [d for d in defs if d is not None]
defs = ensure_type_ordering(defs)
return defs
def get_lines(defs, call):
"""Gets the output lines needed for this call from
all the potential output generated at parse time."""
if call.restr:
defs = [d for d in defs if d.type == 'comments'
or call.restr(d)]
output = []
for d in defs:
lines = def_lines(d, call)
if lines:
output.extend(lines)
output.append('')
return output
def offside_tree(input):
"""Breaks lines up into a tree based on the offside rule.
Each line gets as children the lines following it up until
the next line whose indent is less or equal."""
if input == []:
return []
head, head_n = input[0]
head_indent = len(head) - len(head.lstrip())
children = []
result = []
for line, n in input[1:]:
indent = len(line) - len(line.lstrip())
if indent <= head_indent:
result.append((head, head_n, offside_tree(children)))
head, head_n, head_indent = (line, n, indent)
children = []
else:
children.append((line, n))
result.append((head, head_n, offside_tree(children)))
return result
def discard_line_numbers(tree):
"""Takes a tree containing tuples (line, n, children) and
discards the n terms, returning a tree with tuples
(line, children)"""
result = []
for (line, _, children) in tree:
result.append((line, discard_line_numbers(children)))
return result
def flatten_tree(tree):
"""Returns a tree to the set of numbered lines it was
drawn from."""
result = []
for (line, children) in tree:
result.append(line)
result.extend(flatten_tree(children))
return result
def create_defs(tree):
defs = [create_def(elt) for elt in tree]
defs = [d for d in defs if d is not None]
return defs
def group_defs(defs):
"""Takes a file broken into a series of definitions, and locates
multiple definitions of constants, caused by type signatures or
pattern matching, and accumulates to a single object per genuine
definition"""
defgroups = []
defined = ''
for d in defs:
this_defines = d.defined
if d.type != 'definitions':
this_defines = ''
if this_defines == defined and this_defines:
defgroups[-1].body.extend(d.body)
else:
defgroups.append(d)
defined = this_defines
return defgroups
def create_def(elt):
"""Takes an element of an offside tree and creates
a definition object."""
(line, n, children) = elt
children = discard_line_numbers(children)
return create_def_2(line, children, n)
def create_def_2(line, children, n):
d = Def()
d.body = [(line, children)]
d.line = n
lead = line.split(None, 3)
if lead[0] in ['import', 'module', 'class']:
return
elif lead[0] == 'instance':
type = 'instance'
defined = lead[2]
elif lead[0] in ['type', 'newtype', 'data']:
type = 'newtype'
defined = lead[1]
else:
type = 'definitions'
defined = lead[0]
d.type = type
d.defined = defined
return d
def get_primrecs():
f = open('primrecs')
keys = [line.strip() for line in f]
return set(key for key in keys if key != '')
primrecs = get_primrecs()
def defs_transform(d):
"""Transforms the set of definitions for a function. This
may include its type signature, and may include the special
case of multiple definitions."""
# the first tokens of the first line in the first definition
if d.type == 'newtype':
return newtype_transform(d)
elif d.type == 'instance':
return instance_transform(d)
lead = d.body[0][0].split(None, 2)
if lead[1] == '::':
d.sig = type_sig_transform(d.body[0])
d.body.pop(0)
if d.defined in primrecs:
return primrec_transform(d)
if len(d.body) > 1:
d.body = pattern_match_transform(d.body)
if len(d.body) == 0:
print()
print(d)
assert 0
d.body = body_transform(d.body, d.defined, d.sig)
return d
def wrap_qualify(lines, deep=True):
if len(lines) == 0:
return lines
"""Close and then re-open a locale so instantiations can go through"""
if deep:
asdfextra = ""
else:
asdfextra = ""
if call.current_context:
lines.insert(0, 'end\nqualify {} (in Arch) {}'.format(call.current_context[-1],
asdfextra))
lines.append('end_qualify\ncontext Arch begin global_naming %s' % call.current_context[-1])
return lines
def def_lines(d, call):
"""Produces the set of lines associated with a definition."""
if call.all_bits:
L = []
if d.comments:
L.extend(flatten_tree(d.comments))
L.append('')
if d.type == 'definitions':
L.append('definition')
if d.sig:
L.extend(flatten_tree([d.sig]))
L.append('where')
L.extend(flatten_tree(d.body))
elif d.type == 'newtype':
L.extend(flatten_tree(d.body))
if d.instance_proofs:
L.extend(wrap_qualify(flatten_tree(d.instance_proofs)))
L.append('')
if d.instance_extras:
L.extend(flatten_tree(d.instance_extras))
L.append('')
return L
if call.instanceproofs:
if not call.bodies_only:
instance_proofs = wrap_qualify(flatten_tree(d.instance_proofs))
else:
instance_proofs = []
if not call.decls_only:
instance_extras = flatten_tree(d.instance_extras)
else:
instance_extras = []
newline_needed = len(instance_proofs) > 0 and len(instance_extras) > 0
return instance_proofs + (['']
if newline_needed else []) + instance_extras
if call.body:
return get_lambda_body_lines(d)
comments = d.comments
try:
typesig = flatten_tree([d.sig])
except:
typesig = []
body = flatten_tree(d.body)
type = d.type
if type == 'definitions':
if call.decls_only:
if typesig:
return comments + ["consts'"] + typesig
else:
return []
elif call.bodies_only:
if d.sig:
defname = '%s_def' % d.defined
if d.primrec:
warning('body-only primrec:\n' + body[0], call.filename)
return comments + ['primrec'] + body
return comments + ['defs %s:' % defname] + body
else:
return comments + ['definition'] + body
else:
if d.primrec:
return comments + ['primrec'] + typesig \
+ ['where'] + body
if typesig:
return comments + ['definition'] + typesig + ['where'] + body
else:
return comments + ['definition'] + body
elif type == 'comments':
return comments
elif type == 'newtype':
if not call.bodies_only:
return body
def type_sig_transform(tree_element):
"""Performs transformations on a type signature line
preceding a function declaration or some such."""
line = reduce_to_single_line(tree_element)
(pre, post) = line.split('::')
result = type_transform(post)
if '[pp' in result:
print(line)
print(pre)
print(post)
print(result)
assert 0
line = pre + ':: "' + result + '"'
return (line, [])
ignore_classes = {'Error': 1}
hand_classes = {'Bits': ['HS_bit'],
'Num': ['minus', 'one', 'zero', 'plus', 'numeral'],
'FiniteBits': ['finiteBit']}
def type_transform(string):
"""Performs transformations on a type signature, whether
part of a type signature line or occuring in a function."""
# deal with type classes by recursion
bits = string.split('=>', 1)
if len(bits) == 2:
lhs = bits[0].strip()
if lhs.startswith('(') and lhs.endswith(')'):
instances = lhs[1:-1].split(',')
string = ' => '.join(instances + [bits[1]])
else:
instances = [lhs]
var_annotes = {}
for instance in instances:
(name, var) = instance.split()
if name in ignore_classes:
continue
if name in hand_classes:
names = hand_classes[name]
else:
names = [type_conv(name)]
var = "'" + var
var_annotes.setdefault(var, [])
var_annotes[var].extend(names)
transformed = type_transform(bits[1])
for (var, insts) in six.iteritems(var_annotes):
if len(insts) == 1:
newvar = '(%s :: %s)' % (var, insts[0])
else:
newvar = '(%s :: {%s})' % (var, ', '.join(insts))
transformed = newvar.join(transformed.split(var, 1))
return transformed
# get rid of (), insert Unit, which converts to unit
string = 'Unit'.join(string.split('()'))
# divide up by -> or by , then divide on space.
# apply everything locally then work back up
bstring = braces.str(string, '(', ')')
bits = bstring.split('->')
r = r' \<Rightarrow> '
if len(bits) == 1:
bits = bstring.split(',')
r = ' * '
result = [type_bit_transform(bit) for bit in bits]
return r.join(result)
def type_bit_transform(bit):
s = str(bit).strip()
if s.startswith('['):
# handling this properly is hard.
assert s.endswith(']')
bit2 = braces.str(s[1:-1], '(', ')')
return '%s list' % type_bit_transform(bit2)
bits = bit.split(None, braces=True)
if str(bits[0]) == 'PPtr':
assert len(bits) == 2
return 'machine_word'
if len(bits) > 1 and bits[1].startswith('['):
assert bits[-1].endswith(']')
arg = ' '.join([str(bit) for bit in bits[1:]])[1:-1]
arg = type_transform(arg)
return ' '.join([arg, 'list', str(type_conv(bits[0]))])
bits = [type_conv(bit) for bit in bits]
bits = constructor_reversing(bits)
bits = [bit.map(type_transform) for bit in bits]
strs = [str(bit) for bit in bits]
return ' '.join(strs)
def reduce_to_single_line(tree_element):
def inner(tree_element, acc):
(line, children) = tree_element
acc.append(line)
for child in children:
inner(child, acc)
return acc
return ' '.join(inner(tree_element, []))
type_conv_table = {
'Maybe': 'option',
'Bool': 'bool',
'Word': 'machine_word',
'Int': 'nat',
'String': 'unit list'}
def type_conv(string):
"""Converts a type used in Haskell to our equivalent"""
if string.startswith('('):
# ignore compound types, type_transform will descend into em
result = string
elif '.' in string:
# qualified references
bits = string.split('.')
typename = bits[-1]
module = reduce(lambda x, y: x + '.' + y, bits[:-1])
typename = type_conv(typename)
result = module + '.' + typename
elif string[0].islower():
# type variable
result = "'%s" % string
elif string[0] == '[' and string[-1] == ']':
# list
inner = type_conv(string[1:-1])
result = '%s list' % inner
elif str(string) in type_conv_table:
result = type_conv_table[str(string)]
else:
# convert StudlyCaps to lower_with_underscores
was_lower = False
s = ''
for c in string:
if c.isupper() and was_lower:
s = s + '_' + c.lower()
else:
s = s + c.lower()
was_lower = c.islower()
result = s
type_conv_table[str(string)] = result
return braces.clone(result, string)
def constructor_reversing(tokens):
if len(tokens) < 2:
return tokens
elif len(tokens) == 2:
return [tokens[1], tokens[0]]
elif tokens[0] == '[' and tokens[2] == ']':
return [tokens[1], braces.str('list', '(', ')')]
elif len(tokens) == 4 and tokens[1] == '[' and tokens[3] == ']':
listToken = braces.str('(List %s)' % tokens[2], '(', ')')
return [listToken, tokens[0]]
elif tokens[0] == 'array':
arrow_token = braces.str(r'\<Rightarrow>', '(', ')')
return [tokens[1], arrow_token, tokens[2]]
elif tokens[0] == 'either':
plus_token = braces.str('+', '(', ')')
return [tokens[1], plus_token, tokens[2]]
elif len(tokens) == 5 and tokens[2] == '[' and tokens[4] == ']':
listToken = braces.str('(List %s)' % tokens[3], '(', ')')
lbrack = braces.str('(', '+', '+')
rbrack = braces.str(')', '+', '+')
comma = braces.str(',', '+', '+')
return [lbrack, tokens[1], comma, listToken, rbrack, tokens[0]]
elif len(tokens) == 3:
# here comes a fudge
lbrack = braces.str('(', '+', '+')
rbrack = braces.str(')', '+', '+')
comma = braces.str(',', '+', '+')
return [lbrack, tokens[1], comma, tokens[2], rbrack, tokens[0]]
else:
error(f"error parsing {filename}\n"
f"Can't deal with {tokens}")
sys.exit(1)
def newtype_transform(d):
"""Takes a Haskell style newtype/data type declaration, whose
options are divided with | and each of whose options has named
elements, and forms a datatype statement and definitions for
the named extractors and their update functions."""
if len(d.body) != 1:
print('--- newtype long body ---')
print(d)
[(line, children)] = d.body
if children and children[-1][0].lstrip().startswith('deriving'):
l = reduce_to_single_line(children[-1])
children = children[:-1]
r = re.compile(r"[,\s\(\)]+")
bits = r.split(l)
bits = [bit for bit in bits if bit and bit != 'deriving']
d.deriving = bits
line = reduce_to_single_line((line, children))
bits = line.split(None, 1)
op = bits[0]
line = bits[1]
bits = line.split('=', 1)
header = type_conv(bits[0].strip())
d.typename = header
d.typedeps = set()
if len(bits) == 1:
# line of form 'data Blah' introduces unknown type?
d.body = [('typedecl %s' % header, [])]
all_type_arities[header] = [] # HACK
return d
line = bits[1]
if op == 'type':
# type synonym
return typename_transform(line, header, d)
elif line.find('{') == -1:
# not a record
return simple_newtype_transform(line, header, d)
else:
return named_newtype_transform(line, header, d)
# parameterised types of which we know that they are already defined in Isabelle
known_type_assignments = [
'domain_schedule',
'kernel',
'kernel_f',
'kernel_f f', # there is a KernelF instance that gets transformed into this
'kernel_init',
'kernel_init_state',
'machine_data',
'machine_monad',
'ready_queue',
'user_monad'
]
def typename_transform(line, header, d):
try:
[oldtype] = line.split()
except:
if header not in known_type_assignments:
warning('type assignment with parameters not supported %s' % d.body, filename)
call.bad_type_assignment = True
return
if oldtype.startswith('Data.Word.Word'):
# take off the prefix, leave Word32 or Word64 etc
oldtype = oldtype[10:]
oldtype = type_conv(oldtype)
bits = oldtype.split()
for bit in bits:
d.typedeps.add(bit)
lines = [
'type_synonym %s = "%s"' % (header, oldtype),
# translations (* TYPE 1 *)',
# "%s" <=(type) "%s"' % (oldtype, header)
]
d.body = [(line, []) for line in lines]
return d
keep_conss = {}
def simple_newtype_transform(line, header, d):
lines = []
arities = []
for i, bit in enumerate(line.split('|')):
braced = braces.str(bit, '(', ')')
bits = braced.split()
if len(bits) == 2:
last_lhs = bits[0]
if i == 0:
l = ' %s' % bits[0]
else:
l = ' | %s' % bits[0]
for bit in bits[1:]:
if bit.startswith('('):
bit = bit[1:-1]
typename = type_transform(str(bit))
if len(bits) == 2:
last_rhs = typename
if ' ' in typename:
typename = '"%s"' % typename
l = l + ' ' + typename
d.typedeps.add(typename)
lines.append(l)
arities.append((str(bits[0]), len(bits[1:])))
if list((dict(arities)).values()) == [1] and header not in keep_conss:
return type_wrapper_type(header, last_lhs, last_rhs, d)
d.body = [('datatype %s =' % header, [(line, []) for line in lines])]
set_instance_proofs(header, arities, d)
return d
all_constructor_args = {}
def named_newtype_transform(line, header, d):
bits = line.split('|')
constructors = [get_type_map(bit) for bit in bits]
all_constructor_args.update(dict(constructors))
lines = []
for i, (name, map) in enumerate(constructors):
if i == 0:
l = ' %s' % name
else:
l = ' | %s' % name
oname = name
for name, type in map:
if type is None:
print("ERR: None snuck into constructor list for %s" % name)
print(line, header, oname)
assert False
if name is None:
opt_name = ""
opt_close = ""
else:
opt_name = " (" + name + " :"
opt_close = ")"
if len(type.split()) == 1 and '(' not in type:
the_type = type
else:
the_type = '"' + type + '"'
l = l + opt_name + ' ' + the_type + opt_close
for bit in type.split():
d.typedeps.add(bit)
lines.append(l)
names = {}
types = {}
for cons, map in constructors:
for i, (name, type) in enumerate(map):
names.setdefault(name, {})
names[name][cons] = i
types[name] = type
for name, map in six.iteritems(names):
lines.append('')
lines.extend(named_update_definitions(name, map, types[name], header,
dict(constructors)))
for name, map in constructors:
if map == []:
continue
lines.append('')
lines.extend(named_constructor_translation(name, map, header))
if len(constructors) > 1:
for name, map in constructors:
lines.append('')
check = named_constructor_check(name, map, header)
lines.extend(check)
if len(constructors) == 1:
for ex_name, _ in six.iteritems(names):
for up_name, _ in six.iteritems(names):
lines.append('')
lines.extend(named_extractor_update_lemma(ex_name, up_name))
arities = [(name, len(map)) for (name, map) in constructors]
if list((dict(arities)).values()) == [1] and header not in keep_conss:
[(cons, map)] = constructors
[(name, type)] = map
return type_wrapper_type(header, cons, type, d, decons=(name, type))
set_instance_proofs(header, arities, d)
d.body = [('datatype %s =' % header, [(line, []) for line in lines])]
return d
def named_extractor_update_lemma(ex_name, up_name):
lines = []
lines.append('lemma %s_%s_update [simp]:' % (ex_name, up_name))
if up_name == ex_name:
lines.append(' "%s (%s_update f v) = f (%s v)"' %
(ex_name, up_name, ex_name))
else:
lines.append(' "%s (%s_update f v) = %s v"' %
(ex_name, up_name, ex_name))
lines.append(' by (cases v) simp')
return lines
def named_extractor_definitions(name, map, type, header, constructors):
lines = []
lines.append('primrec')
lines.append(' %s :: "%s \\<Rightarrow> %s"'
% (name, header, type))
lines.append('where')
is_first = True
for cons, i in six.iteritems(map):
if is_first:
l = ' "%s (%s' % (name, cons)
is_first = False
else:
l = '| "%s (%s' % (name, cons)
num = len(constructors[cons])
for k in range(num):
l = l + ' v%d' % k
l = l + ') = v%d"' % i
lines.append(l)
return lines
def named_update_definitions(name, map, type, header, constructors):
lines = []
lines.append('primrec')
ra = r'\<Rightarrow>'
if len(type.split()) > 1:
type = '(%s)' % type
lines.append(' %s_update :: "(%s %s %s) %s %s %s %s"'
% (name, type, ra, type, ra, header, ra, header))
lines.append('where')
is_first = True
for cons, i in six.iteritems(map):
if is_first:
l = ' "%s_update f (%s' % (name, cons)
is_first = False
else:
l = '| "%s_update f (%s' % (name, cons)
num = len(constructors[cons])
for k in range(num):
l = l + ' v%d' % k
l = l + ') = %s' % cons
for k in range(num):
if k == i:
l = l + ' (f v%d)' % k
else:
l = l + ' v%d' % k
l = l + '"'
lines.append(l)
return lines
def named_constructor_translation(name, map, header):
lines = []
lines.append('abbreviation (input)')
l = ' %s_trans :: "' % name
for n, type in map:
l = l + '(' + type + r') \<Rightarrow> '
l = l + '%s" ("%s\'_ \\<lparr> %s= _' % (header, name, map[0][0])
for n, type in map[1:]:
l = l + ', %s= _' % n.replace("_", "'_")
l = l + r' \<rparr>")'
lines.append(l)
lines.append('where')
l = ' "%s_ \\<lparr> %s= v0' % (name, map[0][0])
for i, (n, type) in enumerate(map[1:]):
l = l + ', %s= v%d' % (n, i + 1)
l = l + ' \\<rparr> == %s' % name
for i in range(len(map)):
l = l + ' v%d' % i
l = l + '"'
lines.append(l)
return lines
def named_constructor_check(name, map, header):
lines = []
lines.append('definition')
lines.append(' is%s :: "%s \\<Rightarrow> bool"' % (name, header))
lines.append('where')
lines.append(' "is%s v \\<equiv> case v of' % name)
l = ' %s ' % name
for i, _ in enumerate(map):
l = l + 'v%d ' % i
l = l + r'\<Rightarrow> True'
lines.append(l)
lines.append(r' | _ \<Rightarrow> False"')
return lines
def type_wrapper_type(header, cons, rhs, d, decons=None):
if '\\<Rightarrow>' in d.typedeps:
d.body = [('(* type declaration of %s omitted *)' % header, [])]
return d
lines = [
'type_synonym %s = "%s"' % (header, rhs),
# translations (* TYPE 2 *)',
# "%s" <=(type) "%s"' % (header, rhs),
'',
'definition',
' %s :: "%s \\<Rightarrow> %s"' % (cons, header, header),
'where %s_def[simp]:' % cons,
' "%s \\<equiv> id"' % cons,
]
if decons:
(decons, decons_type) = decons
lines.extend([
'',
'definition',
' %s :: "%s \\<Rightarrow> %s"' % (decons, header, header),
'where',
' %s_def[simp]:' % decons,
' "%s \\<equiv> id"' % decons,
'',
'definition'
' %s_update :: "(%s \\<Rightarrow> %s) \\<Rightarrow> %s \\<Rightarrow> %s"'
% (decons, header, header, header, header),
'where',
' %s_update_def[simp]:' % decons,
' "%s_update f y \\<equiv> f y"' % decons,
''
])
lines.extend(named_constructor_translation(cons, [(decons, decons_type)
], header))
d.body = [(line, []) for line in lines]
return d
def instance_transform(d):
[(line, children)] = d.body
bits = line.split(None, 3)
assert bits[0] == 'instance'
classname = bits[1]
typename = type_conv(bits[2])
if classname == 'Show':
warning("discarding class instance '%s :: Show'" % typename, filename)