-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdefinition_processor.sml
executable file
·3484 lines (3269 loc) · 215 KB
/
definition_processor.sml
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
(*======================================================================
Code for dealing with definitions (of structures, symbols, functions, and
so on). This file also contains code for processing top-level phrases and
assertions.
=======================================================================*)
structure DefinitionProcessor =
struct
structure N = Names
structure D = Data
structure MS = ModSymbol
structure SV = SemanticValues
type mod_symbol = MS.mod_symbol
open StructureAnalysis
exception LoadedFileEx
val processString = Semantics.processString
val getValAndModMaps = Semantics.getValAndModMaps
fun debugPrint(str) = ()
fun setVal([],sym,v,SV.valEnv({val_map,mod_map})) =
SV.valEnv({val_map=Symbol.enter(val_map,sym,v),mod_map=mod_map})
| setVal(m::rest,sym,v,given_env as SV.valEnv({val_map,mod_map})) =
let val _ = debugPrint("\nTrying to look up module name "^(Symbol.name m)^" on the mod_map of the given environment...\n")
in
(case Symbol.lookUp(mod_map,m) of
SOME(module:SV.module as {mod_name,env=e',open_mod_directives}) =>
let val _ = if null(rest) then debugPrint("\nUpdating module: "^(MS.name mod_name)^" on an empty path.\n")
else debugPrint("\nUpdating module: "^(MS.name mod_name)^" on an non-empty path.\n")
val e'' = setVal(rest,sym,v,e')
val module':SV.module = {mod_name=mod_name,env=e'',open_mod_directives=open_mod_directives}
in
SV.valEnv({val_map=val_map,mod_map=Symbol.enter(mod_map,m,module')})
end
| _ => given_env)
end
fun forceSetVal([],sym,v,SV.valEnv({val_map,mod_map})) =
let val _ = ()
in
SV.valEnv({val_map=Symbol.enter(val_map,sym,v),mod_map=mod_map})
end
| forceSetVal(m::rest,sym,v,given_env as SV.valEnv({val_map,mod_map})) =
let val _ = debugPrint("\nTrying to look up module name "^(Symbol.name m)^" on the mod_map of the given environment...\n")
in
(case Symbol.lookUp(mod_map,m) of
SOME(module:SV.module as {mod_name,env=e',open_mod_directives}) =>
let val _ = if null(rest) then debugPrint("\nUpdating module: "^(MS.name mod_name)^" on an empty path.\n")
else debugPrint("\nUpdating module: "^(MS.name mod_name)^" on an non-empty path.\n")
val e'' = forceSetVal(rest,sym,v,e')
val module':SV.module = {mod_name=mod_name,open_mod_directives=open_mod_directives,env=e''}
in
SV.valEnv({val_map=val_map,mod_map=Symbol.enter(mod_map,m,module')})
end
| _ => let val empty_mod = SV.makeEmptyModule(m)
val given_env' = SV.valEnv({val_map=val_map,mod_map=Symbol.enter(mod_map,m,empty_mod)})
in
forceSetVal(m::rest,sym,v,given_env')
end)
end
structure Pos = Position
fun myPrint(msg) = if !(Options.silent_mode) then () else print(msg)
fun alwaysPrint(msg) = print(msg)
val pprint = TopEnv.pprint
val top_assum_base = ABase.top_assum_base
fun addPropToGlobalAb(p,mod_path,string_opt) =
(top_assum_base := ABase.insert(p,!top_assum_base);
P.addToModuleAb(mod_path,p,string_opt);
top_assum_base := ABase.addAssertion(p,!top_assum_base))
fun addPropsToGlobalAb(props,mod_path,string_opt) = List.app (fn p => addPropToGlobalAb(p,mod_path,string_opt)) props
val top_val_env = SV.top_val_env
fun ok() = myPrint("\nOK.\n")
fun error(position,msg) = genEx(msg,SOME(position),"")
exception DecError of string
val makeWord = Data.makeWord
fun decError(msg,SOME(pos)) = raise DecError("Error, "^A.posToString(pos)^": "^msg^".")
| decError(msg,NONE) = raise DecError("Error:, "^msg^".")
val evError = Semantics.evError
val primError = Semantics.primError
fun evWarning(str,SOME(pos)) = myPrint("\nWarning, " ^ A.posToString(pos) ^ ": "^str^".\n")
| evWarning(str,NONE) = myPrint("\nWarning, "^str^".\n")
val num_ops_defined: Symbol.symbol option option ref = ref(NONE)
val dum_pos = Position.dummy_pos
fun checkStrucOrDomainReDefinition(name,pos) =
if MS.exists(structure_table,name) then
(evWarning("the name "^MS.name(name)^" already refers to a structure",SOME(pos));true)
else
if MS.exists(sort_table,name) then
(evWarning("the name "^MS.name(name)^" already refers to a domain",SOME(pos));true)
else
false
fun printDefinitionMessage(name,v,mod_path,is_private) =
if not(is_private) then
let val val_type = Semantics.getType(v)
in
myPrint "\n";
myPrint (val_type^" ");
(myPrint (SV.qualifyNameStr(name,mod_path)));
myPrint " defined.";
myPrint "\n"
end
else ()
fun checkStrucConOrFSymRedef(name:MS.mod_symbol,pos:A.position) =
case MS.find(constructor_table,name) of
SOME(c' as {mother_structure=msym,...}) =>
evError("Duplicate symbol---the name "^MS.name(name)^" is already used as a "^
"constructor of "^MS.name(msym),SOME(pos))
| NONE => if MS.exists(fsym_table,name) then
evError("Duplicate symbol---the name "^MS.name(name)^" is already used as "^
"a function symbol",SOME(pos))
else ()
fun checkFSymRedef(name:MS.mod_symbol,pos:A.position) =
case MS.find(constructor_table,name) of
SOME(c' as {mother_structure=msym,...}) =>
(evWarning("Duplicate symbol---the name "^MS.name(name)^" is already used as a "^
"constructor of "^MS.name(msym),SOME(pos));true)
| NONE => if MS.exists(fsym_table,name) then
(evWarning("Duplicate symbol---the name "^MS.name(name)^" is already used as "^
"a function symbol",SOME(pos));true)
else false
fun checkDistinctConstructors(con_names,con_positions) =
let fun f([],[]) = ()
| f(name::more,pos::rest) =
if Basic.isMemberEq(name,more,MS.modSymEq) then
evError("Duplicate constructor: "^MS.name(name)^
"---constructors must have unique names",SOME(pos))
else
f(more,rest)
| f(_,_) = ()
in
f(con_names,con_positions)
end
fun checkDistinctNames(names,positions,msg1,msg2) =
let fun f([],[],_) = ()
| f(name::more,pos::rest,members) =
if Basic.isMemberEq(name,members,MS.modSymEq) then
evError(msg1^MS.name(name)^msg2,SOME(pos))
else
f(more,rest,name::members)
| f(_,_,_) = ()
in
f(names,positions,[])
end
fun checkDistinctSNames(names,positions,msg1,msg2) =
let fun f([],[],_) = ()
| f(name::more,pos::rest,members) =
if Basic.isMemberEq(name,members,Symbol.symEq) then
evError(msg1^Symbol.name(name)^msg2,SOME(pos))
else
f(more,rest,name::members)
| f(_,_,_) = ()
in
f(names,positions,[])
end
fun areInhabited(new_structures) =
let val structure_number = length(new_structures)
val bit_array = Array.array(structure_number,0)
fun ithStructure(i) = List.nth(new_structures,i)
fun ithStrucName(i) =
(case List.nth(new_structures,i) of
struc:ath_structure as {name,...} => name)
val struc_names = map #name new_structures
fun isReflexive(c:ath_struc_constructor as {absyn_argument_types,...}) =
Basic.exists(struc_names,(fn struc_name => Basic.exists(absyn_argument_types,
fn t => SymTerm.fsymOccursInTagged(struc_name,t))))
val doFirstIteration =
let val i = ref(0)
in
while (!i < structure_number) do
(case List.nth(new_structures,!i) of
struc:ath_structure as {constructors,...} =>
(if Basic.exists(constructors,
(fn c:ath_struc_constructor =>
not(isReflexive(c)))) then
Array.update(bit_array,!i,1)
else ();
Basic.inc(i)))
end
fun checkIthStructure(i) =
let fun checkCon(c:ath_struc_constructor as {absyn_argument_types,...}) =
let val i = ref(0)
val con_passes = ref(true)
in
((while ((!i < structure_number) andalso !con_passes) do
if (Array.sub(bit_array,!i) = 0) andalso
Basic.exists(absyn_argument_types,(fn t =>
SymTerm.fsymOccursInTagged(ithStrucName(!i),t)))
then
con_passes := false
else Basic.inc(i));
!con_passes)
end
in
(case ithStructure(i) of
struc:ath_structure as {name,arity,obtype_params,constructors,free,option_valued_selectors} =>
if Array.sub(bit_array,i) = 0 andalso
Basic.exists(constructors,checkCon) then
(Array.update(bit_array,i,1);true)
else
false)
end
fun loop() =
let val iterations = ref(1)
val done = ref(false)
fun iterate() =
let val change = ref(false)
fun doSub(i) =
if i >= structure_number then ()
else
let val r_i_promoted = checkIthStructure(i)
in
(if r_i_promoted then
change := true
else ();
doSub(i+1))
end
in
(doSub(0);
Basic.inc(iterations);
if !iterations >= structure_number orelse
not(!change) then done := true else ())
end
in
while not(!done) do
iterate()
end
fun getRes() =
let val j = ref(0)
val res = ref(true)
in
(loop();
while ((!j < structure_number) andalso (!res = true)) do
if Array.sub(bit_array,!j) = 0 then
res := false
else Basic.inc(j);
!res)
end
in
getRes()
end
fun expandSortAbbreviationsInStrucDef(absyn_struc:A.absyn_structure as {name,pos,obtype_params,constructors,free},mod_path) =
let fun expandConstructorSorts(con:A.absyn_structure_constructor as {name,pos,selectors,argument_types}) =
let val res:A.absyn_structure_constructor =
{name=name,pos=pos,selectors=selectors,argument_types =
map (fn tt => Terms.replaceTaggedSymTermConstants(
tt,fn sym => MS.find(Data.sort_abbreviations,sym),A.dum_pos))
argument_types}
in
res
end
val res:A.absyn_structure = {name=name,pos=pos,obtype_params=obtype_params,
constructors = map expandConstructorSorts constructors,free=free}
in
res
end
fun expandSortAbbreviationsInStrucDefLst(absyn_struc_list,mod_path) =
map (fn a => expandSortAbbreviationsInStrucDef(a,mod_path)) absyn_struc_list
fun expandSortAbbreviationsInFSymDecl(absyn_fsym:A.absyn_fsym as {name,pos,obtype_params,input_transformer,
argument_types,range_type,prec,assoc,overload_sym,...},mod_path) =
let fun f sym = let val full_name = (case MS.split(sym) of
(mod_path',sym_name) => (case mod_path' of
[] => SV.qualifyName(sym_name,mod_path)
| _ => sym))
val _ = ()
in
MS.find(Data.sort_abbreviations,full_name)
end
val res:A.absyn_fsym = {name=name,pos=pos,obtype_params=obtype_params,input_transformer=input_transformer,
argument_types = map (fn tt => Terms.replaceTaggedSymTermConstants(
tt,f,A.dum_pos))
argument_types,prec=prec,assoc=assoc,overload_sym=overload_sym,
range_type = Terms.replaceTaggedSymTermConstants(range_type,f,A.dum_pos)}
in
res
end
fun checkNewFunSym(sym,pos) =
let val str = Symbol.name(sym)
fun f1() = (case A.getAthNumber(str) of
SOME(ath_num) => evError("Duplicate symbol---the name "^str^
" is already used as a "^"function symbol",SOME(pos))
| _ => ())
in f1() end
fun checkConNames(con_names_and_positions) =
List.app (fn (name,pos) => checkNewFunSym(name,pos)) con_names_and_positions
fun makeUniqueDTName(length) =
let val prefix = "TTuple-"^(Int.toString(length))
fun trySuffix(i) = let val new_name_sym = A.makeMS(prefix^"_"^(Int.toString(i)),NONE)
in
if Data.isStructure(new_name_sym) then trySuffix(i+1) else new_name_sym
end
val first_try = A.makeMS(prefix,NONE)
in
if Data.isStructure(first_try) then trySuffix(0) else first_try
end
fun makeUniqueConName(length) =
let val prefix = "ttuple-"^(Int.toString(length))
fun trySuffix(i) = let val new_name_sym = A.makeMS(prefix^"_"^(Int.toString(i)),NONE)
in
if Data.isStructureConstructorBool(new_name_sym) then trySuffix(i+1) else new_name_sym
end
val first_try = A.makeMS(prefix,NONE)
in
if Data.isStructureConstructorBool(first_try) then trySuffix(0) else first_try
end
fun addTempDT(len) =
let val dt_name = makeUniqueDTName(len)
val con_name = makeUniqueConName(len)
fun makeParam(i) = {name=Symbol.symbol("S"^(Int.toString(i))),pos=A.dum_pos}
fun makeNParams(n,res) = if n = 0 then rev res else makeNParams(n-1,(makeParam n)::res)
val obtype_params = makeNParams(len,[])
val obtype_params_as_symbols = map #name obtype_params
val obtype_params_as_SymTerms = map SymTerm.makeVar obtype_params_as_symbols
val arg_types = List.map (fn t => Terms.putBogusTags(t,A.dum_pos)) obtype_params_as_SymTerms
val arg_types_as_SymTerms = map SymTerm.stripTags arg_types
val range_type_as_SymTerm = SymTerm.makeApp(dt_name,obtype_params_as_SymTerms)
val range_type_as_AbSynTerm:A.absyn_term = Terms.putBogusTags(range_type_as_SymTerm,A.dum_pos)
val types_as_FTerms = Terms.SymTermsToFTerms(range_type_as_SymTerm::arg_types_as_SymTerms)
val argument_types_as_FTerms = tl types_as_FTerms
val range_type_as_FTerm = hd types_as_FTerms
val c:Data.ath_struc_constructor =
{name=con_name,arity=len,mother_structure=dt_name,reflexive=false,bits=makeWord({poly=true,pred_based_sig=false}),
argument_types=argument_types_as_FTerms,range_type=range_type_as_FTerm,prec=ref(110),
absyn_argument_types=arg_types,assoc=ref(SOME(true)),selectors=List.map (fn _ => NONE) arg_types,
sym_range_type=range_type_as_SymTerm}
val _ = (Data.addFSym(Data.struc_con(c));Data.addConstructor(c))
val res:Data.ath_structure = {name=dt_name,arity=len,obtype_params=obtype_params_as_symbols,option_valued_selectors=false,
constructors=[c],free=true}
val _ = MS.insert(Data.structure_table,dt_name,res)
in
(dt_name,con_name,res)
end
fun removeDT(dt:Data.ath_structure as {name=dt_name,constructors,...}) =
let fun handleSelector(NONE) = ()
| handleSelector(SOME(ms)) = (Data.removeFSymByName(ms);
MS.removeHT(Data.selector_table,ms);
Semantics.removeTopValEnvBinding(ModSymbol.lastName(ms)))
fun removeConstructor(c:Data.ath_struc_constructor as {name,selectors,...}) =
(List.map handleSelector selectors;
Data.deleteConstructor(c);
Data.removeFSymByName(name);
Semantics.removeTopValEnvBinding(MS.lastName name))
in
((List.app removeConstructor constructors);Data.deleteStructure(dt))
end
fun fdCondition(g,args,right,right_fsyms) =
let val left_syms = AT.termSymbolsLst(args)
val cond1 = List.all isStructureConstructorBool left_syms
in
if cond1 andalso (not(List.null(left_syms)) orelse not(Basic.isMemberEq(g,right_fsyms,AT.fsymEq)))
then SOME(g) else NONE
end
fun fdConditionNew(g,left_args,right_opt,right_syms,guards,all_args) =
let val left_syms = AT.termSymbolsLst(left_args)
val left_vars = Basic.flatten(List.map AT.getVars left_args)
val guard_vars = Basic.flatten(List.map Prop.freeVars guards)
val right_vars = (case right_opt of
SOME(right) =>AT.getVars(right)
| _ => [])
val cond0 = true (* not(Basic.hasDuplicates(left_vars,ATV.nameEq)) *)
val cond1 = List.all isStructureConstructorBool left_syms
val cond2 = Basic.subsetEq(right_vars,left_vars@guard_vars,ATV.nameEq)
val cond3 = (not(null(guards)) orelse (not(List.null(left_syms)) orelse not(Basic.isMemberEq(g,right_syms,AT.fsymEq))))
val ok = cond0 andalso cond1 andalso cond2 andalso cond3
in
if ok then 1 else
(if not(cond1) then ~1
else if not(cond2) then ~2 else ~3)
end
fun fdConditionNewRelaxed(g,left_args,right_opt,right_syms,guards,all_args) =
let
val left_syms = AT.termSymbolsLst(left_args)
val left_vars = Basic.flatten(List.map AT.getVars left_args)
val right_vars = (case right_opt of
SOME(right) =>AT.getVars(right)
| _ => [])
val guard_vars = Basic.flatten(List.map Prop.freeVars guards)
val cond2 = Basic.subsetEq(right_vars,left_vars@guard_vars,ATV.nameEq)
val cond3 = (not(null(guards)) orelse (not(List.null(left_syms)) orelse not(Basic.isMemberEq(g,right_syms,AT.fsymEq))))
val ok = cond2 andalso cond3
in
if ok then 1 else (if not(cond2) then ~2 else ~3)
end
fun isDefiningBody0(p) =
(case Prop.isEquality(p) of
SOME(left,right) =>
(case AT.isApp(left) of
SOME(g,args) => fdCondition(g,args,right,AT.termSymbols(right))
| _ => NONE)
| _ => (case Prop.isCond(p) of
SOME(_,p2) => isDefiningBody0(p2)
| _ => NONE))
val isDefiningBody = isDefiningBody0
fun makeProp(uvars,guards,left,right,eq_opt:Prop.prop option) =
let fun makeConjunction([guard]) = guard
| makeConjunction(guard::guards) = let val prop = makeConjunction guards
in
Prop.makeConjunction([guard,prop])
end
in
if null(guards) then
(case eq_opt of
SOME(e) => Prop.makeUGen(uvars,e)
| NONE => Prop.makeUGen(uvars,Prop.makeEquality(left,right)))
else
(case eq_opt of
SOME(e) => let val guard = makeConjunction(rev guards)
in Prop.makeUGen(uvars,Prop.makeConditional(guard,e))
end
| NONE => let val guard = makeConjunction(rev guards)
in Prop.makeUGen(uvars,Prop.makeConditional(guard,Prop.makeEquality(left,right)))
end)
end
fun getTermSymbols(t) = Basic.filterOut(AT.termSymbols t,Data.isStructureConstructorBool)
fun getTermSymbols'(t) = AT.termSymbols(t)
fun getTermSymbolsLst(props) =
let val term_syms = AT.termSymbolsLst(Basic.flatten(map P.allAtoms props))
in
Basic.filterOut(term_syms,Data.isStructureConstructorBool)
end
fun isIdentity(p) = (case Prop.isEquality(p) of
NONE => false
| _ => true)
fun isVarEquality(p) =
(case Prop.isAtom(p) of
SOME(t) => (case AT.isApp(t) of
SOME(f,args) =>
if MS.modSymEq(N.mequal_logical_symbol,f) then
let val left = hd(args)
val right = hd(tl(args))
in
AT.isVar(left) andalso AT.isVar(right)
end
else false
| _ => false)
| _ => (case Prop.isConj(p) of
SOME(props) => Basic.forall(props,isVarEquality)
| _ => false))
(*****
allVarEqualities below is meant to detect a conditional identity all
of whose guards are equalities of the form x1 = y1, ..., xn = yn.
Often, the conclusion of such a rule is of the form
(= (C x1 ... xn) (C y1 ... yn)) for a constructor C, and we want
to avoid treating such a congruence rule as a "defining" axiom for
the constructor C. This is avoided in the part of isDefiningBodyNew
that applies allVarEqualities; see the line
if MS.modSymEq(g,h) andalso Data.isStructureConstructorBool(g) andalso allVarEqualities(guards)
where g and h are the top function symbols of the left and right sides
of the consequent identity.
****)
fun allVarEqualities(guards) = Basic.forall(guards,isVarEquality)
fun isDefiningBodyNew(p,uvars,guards,must_be_a_defining_equation) =
let val fdCondition = if must_be_a_defining_equation then fdConditionNew else fdConditionNewRelaxed
in
(case Prop.isAtom(p) of
SOME(t) => (case AT.isApp(t) of
SOME(f,args) =>
if MS.modSymEq(N.mequal_logical_symbol,f) then
let val left = hd(args)
in
(case AT.isApp(left) of
SOME(g,args') => let val right = hd(tl(args))
val right_syms = getTermSymbols(right)
val left_syms = getTermSymbols'(left)
val guard_syms = (getTermSymbolsLst guards)
val fd_cond = fdCondition(g,args',SOME right,right_syms,guards,args)
val res = {fsym=g,defining_props=[makeProp(uvars,guards,left,right,SOME(p))],
guard_syms=guard_syms,left_syms=left_syms,right_syms=right_syms}
in
(case AT.isApp(right) of
SOME(h,args) => if MS.modSymEq(g,h) andalso
Data.isStructureConstructorBool(g) andalso
let val res = allVarEqualities(guards)
in
res
end
then NONE
else
if (fd_cond > 0) then SOME(res) else NONE
| _ => if (fd_cond > 0) then SOME(res) else NONE)
end
| _ => let val right = hd(tl(args))
in
(case (AT.isVarOpt(left),AT.isVarOpt(right)) of
(SOME(v1),SOME(v2)) =>
let val sort = ATV.getSort(v1)
in
(case FTerm.isApp(sort) of
SOME(sort_con,_) =>
if Data.isNonFreeDT(sort_con) then
let val guard_conj = Prop.makeConjunction(guards)
val guard_fvs = Prop.freeVarsSet(guard_conj)
val S = ATV.addLst([v1,v2],ATV.empty)
val cond = ATV.equal(S,guard_fvs)
in
if cond then
let fun f(t1,t2) = Prop.replace(v2,t2,Prop.replace(v1,t1,guard_conj))
val _ = MS.insert(Prop.structure_equality_table,sort_con,f)
in
NONE
end
else NONE
end
else NONE
| _ => NONE)
end
| _ => NONE)
end)
end
else let val fd_cond = fdCondition(f,args,NONE,[],guards,args)
in (if fd_cond >0 then
SOME({defining_props=[makeProp(uvars,guards,t,AT.true_term,NONE)],fsym=f,guard_syms=(getTermSymbolsLst guards),left_syms=[],right_syms=[]})
else NONE)
end
| _ => NONE)
| _ => (case Prop.isCond(p) of
SOME(p1,p2) => isDefiningBodyNew(p2,uvars,p1::guards,must_be_a_defining_equation)
| _ => (case Prop.isNeg(p) of
SOME(q) => (case Prop.isAtom(q) of
SOME(t) => (case AT.isApp(t) of
SOME(f,args) => let val fd_cond = fdCondition(f,args,NONE,[],guards,args)
in
if fd_cond > 0
then SOME({defining_props=[makeProp(uvars,guards,t,AT.false_term,NONE)],
fsym=f,guard_syms=(getTermSymbolsLst guards),left_syms=[],right_syms=[]})
else NONE
end
| _ => NONE)
| _ => NONE)
| _ => (case Prop.isBiCond(p) of
SOME(p1,p2) => (case Prop.isAtom(p1) of
SOME(t1) =>
(case Prop.isAtom(p2) of
SOME(t2) => if isIdentity(p1) then
(if ATV.isSubset(P.freeVarsSet(p2),P.freeVarsSet(p1))
then (case isDefiningBodyNew(p1,uvars,p2::guards,must_be_a_defining_equation) of
NONE => isDefiningBodyNew(p2,uvars,p1::guards,must_be_a_defining_equation)
| res => res)
else NONE)
else
if isIdentity(p2) then isDefiningBodyNew(Prop.makeEquality(t1,t2),uvars,guards,must_be_a_defining_equation)
else
isDefiningBodyNew(Prop.makeEquality(t1,t2),uvars,guards,must_be_a_defining_equation)
| _ => (case (isDefiningBodyNew(p1,uvars,p2::guards,must_be_a_defining_equation),
isDefiningBodyNew(Prop.makeNegation(p1),uvars,(Prop.makeNegation p2)::guards,
must_be_a_defining_equation)) of
(SOME({defining_props=dp1,fsym=f1,guard_syms=gs,right_syms=rs1,left_syms=ls1,...}),
SOME({defining_props=dp2,...})) =>
(if ATV.isSubset(P.freeVarsSet(p2),P.freeVarsSet(p1))
then SOME({defining_props=dp1@dp2,fsym=f1,guard_syms=gs,right_syms=rs1,left_syms=ls1})
else NONE)
| _ => NONE)
)
| _ => NONE)
| _ => NONE))))
end
fun isDefiningBody(p) =
(case Prop.isEquality(p) of
SOME(left,right) =>
(case AT.isApp(left) of
SOME(g,args) =>
let val left_syms = AT.termSymbolsLst(args)
val cond1 = List.all isStructureConstructorBool left_syms
val cond2 = not(List.null(left_syms)) orelse not(Basic.isMemberEq(g,AT.termSymbols(right),AT.fsymEq))
in
if cond1 andalso cond2 then SOME(g) else NONE
end
| _ => NONE)
| _ => (case Prop.isCond(p) of
SOME(antecedent,p2) => if ATV.isSubset(P.freeVarsSet(antecedent),P.freeVarsSet(p2)) then isDefiningBody(p2) else NONE
| _ => NONE))
fun isDefiningEquationForSomeFunSym(p) =
(case P.splitVars(p) of
(SOME(A.forallCon),_,body) => isDefiningBody(body)
| _ => isDefiningBody(p))
fun isDefiningEquationForSomeFunSymNew(p,must_be_a_defining_equation) =
(case P.splitVars(p) of
(SOME(A.forallCon),uvars,body) => isDefiningBodyNew(body,uvars,[],must_be_a_defining_equation)
| _ => isDefiningBodyNew(p,[],[],must_be_a_defining_equation))
fun isDefiningEquation(p,f) =
(case isDefiningEquationForSomeFunSym(p) of
SOME(g) => AT.fsymEq(f,g)
| _ => false)
fun getDefiningEquations(f,ab) =
let val assertions = ABase.getAssertions(ab)
fun allConstructors(_) = true
fun test(p) = isDefiningEquation(p,f)
in
List.filter test assertions
end
fun checkFunDef(f,new_equation,ab,pos,file,which_check) =
let val arity = (case Data.isTermConstructor(f) of
SOME(i) => i)
val (dt_name,con_name,dt) = addTempDT(arity)
val cname = MS.name(con_name)
val sym_name = MS.name(f)
fun getLeftSide(p,inside_cond) =
(case Prop.splitVars(p) of
(SOME(A.forallCon),vars,body) =>
(case Prop.isEquality(body) of
SOME(l,_) => (l,false)
| _ => (case Prop.isCond(body) of
SOME(_,p2) => (getLeftSide(p2,true))))
| _ => (case Prop.isEquality(p) of
SOME(l,_) => (l,inside_cond)
| _ => (case Prop.isCond(p) of
SOME(_,p2) => getLeftSide(p2,true))))
val old_equations = getDefiningEquations(f,ab)
val equations = new_equation::old_equations
val old_left_sides = List.map (fn eq => getLeftSide(eq,false)) old_equations
val new as (new_left_side,is_new_cond) = getLeftSide(new_equation,false)
val left_sides = new::old_left_sides
fun makeConTerm(left) = AT.makeApp(con_name,AT.getChildren left)
fun checkDisjointness() = List.map
(fn (old_left_side,is_old_cond) => if is_old_cond orelse is_new_cond then () else
(case AT.unify(old_left_side,new_left_side) of
SOME(sub) =>
myPrint("\n[Warning, "^(A.posToString pos)^": "^
"this new equational axiom\ndefining "^sym_name^
" is not disjoint from previous axioms. For example,\nboth it"^
" and at least one previous axiom apply to every instance of this term:\n"^
(AT.toStringDefault(AT.applySub(sub,new_left_side)))^".]\n")
| _ => ()))
old_left_sides
val at_least_one_conditional_equation = List.exists (fn (_,b) => b = true) left_sides
fun checkExaustiveness() =
let
val (param_sorts,result_sort,is_poly,has_pred_based_sorts) = Data.getSignature(con_name)
handle _ => (print("\nCan't get the signature of "^cname);raise Basic.Never)
val left_patterns = (List.map (fn (side,is_cond) => makeConTerm side) left_sides)
val arg_sorts = (case (Data.getSignature f) of
(asorts,_,_,has_pred_based_sorts) => asorts)
val uvar = ATV.freshWithSort(FTerm.makeApp(dt_name,arg_sorts))
val uvar_sort = ATV.getSort(uvar)
val str = if at_least_one_conditional_equation then " should be " else " are "
in
(case StructureAnalysis.exhaustStructure(left_patterns,uvar_sort) of
SOME(t) => let val t' = (case AT.isApp(t) of
SOME(_,args) => AT.makeApp(f,args))
in
myPrint("\n[Warning: The current equational axioms for "^sym_name^" are not\nexhaustive. "^
"For example, the value of every ground instance of:\n"^(AT.toStringDefault t')^
"\nis currently unspecified.]\n")
end
| _ => myPrint("\nDefinition of "^sym_name^" is complete; the current equational axioms"^str^"exhaustive.\n"))
end
val _ = (case which_check of
"disjoint" => (checkDisjointness();())
| "exhaust" => checkExaustiveness()
| "both" => (checkDisjointness();checkExaustiveness()))
val _ = removeDT(dt)
in
()
end
fun getAllRemainingPatterns(patterns) =
let val first_pattern = hd(patterns)
val arg_sorts = map AT.getSort (AT.getChildren first_pattern)
val f = (case AT.isApp(first_pattern) of
SOME(g,_) => g)
val arity = (case Data.isTermConstructor(f) of
SOME(i) => i)
val (dt_name,con_name,dt) = addTempDT(arity)
val uvar = ATV.freshWithSort(FTerm.makeApp(dt_name,arg_sorts))
val uvar_sort = ATV.getSort(uvar)
val cname = MS.name(con_name)
val sym_name = MS.name(f)
fun makeConTerm(left) = AT.makeApp(con_name,AT.getChildren left)
fun loop(patterns) =
let val (param_sorts,result_sort,is_poly,has_pred_based_sorts) = Data.getSignature(con_name)
handle _ => (print("\nCan't find the signature of "^cname);raise Basic.Never)
val patterns' = (List.map makeConTerm patterns)
in
(case StructureAnalysis.exhaustStructure(patterns',uvar_sort) of
SOME(t) => (case AT.isApp(t) of
SOME(_,args) => loop(patterns@[AT.makeApp(f,args)]))
| _ => patterns)
end
val res = loop(patterns)
val _ = removeDT(dt)
in
res
end
fun getPatternsPrimUFun(SV.listVal(tvals),env,_) =
let val terms = TopEnv.getTermsNoPos(tvals,"the first argument of "^N.getPatternsFun_name,NONE)
val res = getAllRemainingPatterns(terms)
in
SV.listVal(map SV.termVal res)
end
| getPatternsPrimUFun(v2,env,_) = primError(TopEnv.wrongArgKind(N.getPatternsFun_name,2,SV.listLCType,v2))
val _ = TopEnv.updateTopValEnvLstOldAndFast([(N.getPatternsFun_symbol,SV.primUFunVal(getPatternsPrimUFun,TopEnv.default_ufv_pa_for_procs N.getPatternsFun_name))])
fun getLeftSide(p,inside_cond) =
(case Prop.splitVars(p) of
(SOME(A.forallCon),vars,body) =>
(case Prop.isEquality(body) of
SOME(l,_) => (l,false)
| _ => (case Prop.isCond(body) of
SOME(_,p2) => (getLeftSide(p2,true))))
| _ => (case Prop.isEquality(p) of
SOME(l,_) => (l,inside_cond)
| _ => (case Prop.isCond(p) of
SOME(_,p2) => getLeftSide(p2,true))))
fun checkFunDef(f,equations,pos_option) =
let val arity = (case Data.isTermConstructor(f) of
SOME(i) => i)
val (dt_name,con_name,dt) = addTempDT(arity)
val cname = MS.name(con_name)
val sym_name = MS.name(f)
val all_left_sides = List.map (fn eq => getLeftSide(eq,false)) equations
fun makeConTerm(left) = AT.makeApp(con_name,AT.getChildren left)
val error = ref(false)
val at_least_one_conditional_equation = List.exists (fn (_,b) => b = true) all_left_sides
val myPrint0 = myPrint
fun noPrint(_) = ()
fun myPrint(s) = if at_least_one_conditional_equation then noPrint(s) else myPrint0(s)
fun checkDisjointness() =
let fun loop([],_) = ()
| loop((x as (left_side,is_cond))::remaining_left_sides,left_sides_to_be_examined) =
let val _ = List.map
(fn (old_left_side,is_old_cond) => if is_old_cond orelse is_cond then () else
(case AT.unify(old_left_side,left_side) of
SOME(sub) =>
(case pos_option of
SOME(pos) =>
let val _ = error := true
in
myPrint("\n[Warning, "^(A.posToString(pos))^": "^
"the equational axioms defining "^sym_name^
" are not disjoint.\nFor example, at least "^
" two distinct axioms apply to every instance of this term:\n"^
(AT.toStringDefault(AT.applySub(sub,left_side)))^".]\n")
end
| _ => let val _ = error := true
in
myPrint("\n[Warning: " ^
"the equational axioms defining "^sym_name^
" are not disjoint.\nFor example, at least "^
" two distinct axioms apply to every instance of this term:\n"^
(AT.toStringDefault(AT.applySub(sub,left_side)))^".]\n")
end)
| _ => ()))
left_sides_to_be_examined
in
loop(remaining_left_sides,x::left_sides_to_be_examined)
end
in
loop(all_left_sides,[])
end
fun checkExaustiveness() =
let val (param_sorts,result_sort,is_poly,has_pred_based_sorts) = Data.getSignature(con_name)
handle _ => (print("\nCan't find the signature of "^cname);raise Basic.Never)
val left_patterns = (List.map (fn (side,is_cond) => makeConTerm side) all_left_sides)
val arg_sorts = (case (Data.getSignature f) of
(asorts,_,_,has_pred_based_sorts) => asorts)
val uvar = ATV.freshWithSort(FTerm.makeApp(dt_name,arg_sorts))
val uvar_sort = ATV.getSort(uvar)
val str = if at_least_one_conditional_equation then " should be " else " are "
in
(case StructureAnalysis.exhaustStructure(left_patterns,uvar_sort) of
SOME(t) => let val t' = (case AT.isApp(t) of
SOME(_,args) => AT.makeApp(f,args))
val _ = error := true
in
myPrint("\n[Warning: The current equational axioms for "^sym_name^" are not\nexhaustive. "^
"For example, the value of every ground instance of:\n"^(AT.toStringDefault t')^
"\nis currently unspecified.]\n")
end
| _ => noPrint("\nDefinition of "^sym_name^" is complete; the given equational axioms"^str^"exhaustive.\n"))
end
in
(checkDisjointness();checkExaustiveness();removeDT(dt);(!error,at_least_one_conditional_equation))
end
(**
The following is a very conservative approximation of whether or not
a set of equations completely and unambiguously define a function symbol f.
If there is even one conditional equation in the given axioms, the
result will automatically be false, since the problem is undecidable
in the presence of general conditional equational axioms.
**)
fun isFunDefExhaustive(f,equations) =
let val arity = (case Data.isTermConstructor(f) of
SOME(i) => i)
val (dt_name,con_name,dt) = addTempDT(arity)
val cname = MS.name(con_name)
val sym_name = MS.name(f)
val all_left_sides = List.map (fn eq => getLeftSide(eq,false)) equations
fun makeConTerm(left) = AT.makeApp(con_name,AT.getChildren left)
val at_least_one_conditional_equation = List.exists (fn (_,b) => b = true) all_left_sides
in
if at_least_one_conditional_equation then false
else
let fun checkExaustiveness() =
let val (param_sorts,result_sort,is_poly,has_pred_based_sorts) = Data.getSignature(con_name)
handle _ => (print("\nCan't find the signature of "^cname);raise Basic.Never)
val left_patterns = (List.map (fn (side,is_cond) => makeConTerm side) all_left_sides)
val arg_sorts = (case (Data.getSignature f) of
(asorts,_,_,has_pred_based_sorts) => asorts)
val uvar = ATV.freshWithSort(FTerm.makeApp(dt_name,arg_sorts))
val uvar_sort = ATV.getSort(uvar)
in
(case StructureAnalysis.exhaustStructure(left_patterns,uvar_sort) of
SOME(t) => false
| _ => true)
end
val res = checkExaustiveness()
val _ = removeDT(dt)
in
res
end
end
val qualifyName = SV.qualifyName
val qualifySort = SV.qualifySort
val qualifyFSym = SV.qualifyFSym
fun addSelectorAxioms({name,...}:ath_structure,mod_path,env,eval_env) =
let val name_str = MS.name(name)
val axioms_str = "make-selector-axioms"
val quote = "\""
val cmd = "(assert* (" ^ axioms_str ^ " " ^ quote ^ name_str ^ quote ^ "))"
val process = (!Semantics.processString)
in
process(cmd,mod_path,env,eval_env)
end
fun processStructuresDefinition0(absyn_structure_list: A.absyn_structure list,env,eval_env,mod_path) =
let val struc_names: symbol list = map #name absyn_structure_list
val option_valued_selectors_currently = (!(Options.option_valued_selectors_option))
val positions = map #pos absyn_structure_list
val (keyword_singular,keyword_plural) = (case hd(absyn_structure_list) of
{free=true,...} => ("datatype","datatypes")
| _ => ("structure","structures"))
val _ = List.app (fn (name:symbol,pos) =>
let val str = Symbol.name(name)
in
if illegalSortName(str) then
evError("A structure name cannot begin with "^Names.sort_variable_prefix,SOME(pos))
else A.checkNoDots(str,pos)
end)
(ListPair.zip(struc_names,positions))
val one_struc_only = case absyn_structure_list of
[_] => true | _ => false
fun loopReDefs([]) = false
| loopReDefs(({name,pos,...}:A.absyn_structure)::rest) =
let val name' = qualifyName(name,mod_path)
in
if checkStrucOrDomainReDefinition(name',pos) then true else loopReDefs(rest)
end
in
if loopReDefs(absyn_structure_list) then () else
let val _ = checkDistinctSNames(struc_names,map #pos absyn_structure_list,
"Duplicate occurence of ","---structure names must be unique")
val all_constructor_names_and_positions =
let fun get_cons(some_absyn_structure:A.absyn_structure as
{name=struc_name,pos,obtype_params,constructors,free}) =
constructors
fun get_name(some_absyn_constructor:A.absyn_structure_constructor as
{name,pos,...}) = (name,pos);
fun g([]:A.absyn_structure list,names_and_positions) = names_and_positions
| g(ab_struc::more,names) =
let val constructors:A.absyn_structure_constructor list = get_cons(ab_struc)
val con_names_and_positions = map get_name constructors
in
g(more,names@con_names_and_positions)
end
in
g(absyn_structure_list,[])
end
val struc_names_and_arities = List.map (fn (ab_struc) => let val struc_name = #name(ab_struc)
val qualified_name = qualifyName(struc_name,mod_path)
in
(qualified_name,length(#obtype_params(ab_struc)))
end)
absyn_structure_list
val new_struc_and_domain_arities =
let fun f([],arities) = arities
| f((struc_name,arity)::more,arities) =
f(more,MS.enter(arities,struc_name,arity))
in
f(struc_names_and_arities,!structure_and_domain_arities)
end
val _ = structure_and_domain_arities := new_struc_and_domain_arities
fun processStructureDefinition(some_absyn_structure:A.absyn_structure as
{name=struc_name,pos,obtype_params,constructors,free=is_free}) =
let val _ = let val str = Symbol.name(struc_name)
in
if illegalSortName(str) then
evError("A structure name cannot begin with "^Names.sort_variable_prefix,SOME(pos))
else A.checkNoDots(str,pos)
end
val full_struc_name = qualifyName(struc_name,mod_path)
val _ = debugPrint("\nProcessing the definition of this structure: "^(MS.name full_struc_name)^"\n")
val obtype_params_as_symbols = map #name obtype_params
val obtype_params_as_SymTerms = map SymTerm.makeVar obtype_params_as_symbols
val range_type_as_SymTerm = SymTerm.makeApp(full_struc_name,obtype_params_as_SymTerms)
val range_type_as_AbSynTerm:A.absyn_term = Terms.putBogusTags(range_type_as_SymTerm,A.dum_pos)
val con_count = List.length constructors
fun makeStrucCon({name=con_name,pos,selectors,argument_types}:A.absyn_structure_constructor) =
let val con_arity = length(argument_types)
val argument_types' = map qualifySort argument_types
val argument_types = argument_types'
val is_poly = not(null(obtype_params))
val argument_types_as_SymTerms = map SymTerm.stripTags argument_types
val types_as_FTerms =
Terms.SymTermsToFTerms(range_type_as_SymTerm::argument_types_as_SymTerms)
val argument_types_as_FTerms = tl types_as_FTerms
val involves_pred_based_sorts = F.findOutDynamicallyIfAnySortsHavePredicateBasedSortSymbols(argument_types_as_FTerms)
val range_type_as_FTerm = hd types_as_FTerms
fun decideOption(t) = t
fun declareSelectors([],_,_) = ()
| declareSelectors(NONE::rest,_,_) = ()
| declareSelectors(SOME({name=sel_name,pos}:A.param)::rest,
(ith_arg_type:FTerm.term)::more_arg_types,
ith_absynterm_arg_type::more_absynterm_arg_types) =
let val bits_val = makeWord({poly=is_poly,pred_based_sig=false})
val full_sel_name = qualifyName(sel_name,mod_path)
val range_sort = if option_valued_selectors_currently then
FTerm.makeApp(Names.moption_structure_symbol,[ith_arg_type])
else ith_arg_type
val sel_sym:declared_fun_sym = {name=full_sel_name,obtype_params=obtype_params_as_symbols,
bits=bits_val,argument_types=[range_type_as_FTerm], arity=1,
range_type=range_sort,prec=ref(Options.lowest_fsymbol_precedence),
absyn_argument_types=[range_type_as_AbSynTerm],assoc=ref(NONE),
absyn_range_type=ith_absynterm_arg_type}
val (lifted_name,lifted_sym_version) = addFSym(declared(sel_sym))