-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathArnold.ml
More file actions
1421 lines (1307 loc) · 48.9 KB
/
Arnold.ml
File metadata and controls
1421 lines (1307 loc) · 48.9 KB
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
let printPos ppf (pos : Lexing.position) =
let file = pos.Lexing.pos_fname in
let line = pos.Lexing.pos_lnum in
Format.fprintf ppf "@{<filename>%s@} @{<dim>%i@}"
(file |> Filename.basename)
line
module StringSet = Set.Make (String)
(** Type Definitions *)
module FunctionName = struct
type t = string
end
module FunctionArgs = struct
type arg = {label: string; functionName: FunctionName.t}
type t = arg list
let empty = []
let argToString {label; functionName} = label ^ ":" ^ functionName
let toString functionArgs =
match functionArgs = [] with
| true -> ""
| false ->
"<" ^ (functionArgs |> List.map argToString |> String.concat ",") ^ ">"
let find (t : t) ~label =
match t |> List.find_opt (fun arg -> arg.label = label) with
| Some {functionName} -> Some functionName
| None -> None
let compareArg a1 a2 =
let n = compare a1.label a2.label in
if n <> 0 then n else compare a1.functionName a2.functionName
let rec compare l1 l2 =
match (l1, l2) with
| [], [] -> 0
| [], _ :: _ -> -1
| _ :: _, [] -> 1
| x1 :: l1, x2 :: l2 ->
let n = compareArg x1 x2 in
if n <> 0 then n else compare l1 l2
end
module FunctionCall = struct
type t = {functionName: FunctionName.t; functionArgs: FunctionArgs.t}
let substituteName ~sub name =
match sub |> FunctionArgs.find ~label:name with
| Some functionName -> functionName
| None -> name
let applySubstitution ~(sub : FunctionArgs.t) (t : t) =
if sub = [] then t
else
{
functionName = t.functionName |> substituteName ~sub;
functionArgs =
t.functionArgs
|> List.map (fun (arg : FunctionArgs.arg) ->
{
arg with
functionName = arg.functionName |> substituteName ~sub;
});
}
let noArgs functionName = {functionName; functionArgs = []}
let toString {functionName; functionArgs} =
functionName ^ FunctionArgs.toString functionArgs
let compare (x1 : t) x2 =
let n = compare x1.functionName x2.functionName in
if n <> 0 then n else FunctionArgs.compare x1.functionArgs x2.functionArgs
end
module FunctionCallSet = Set.Make (FunctionCall)
module Stats = struct
let nCacheChecks = ref 0
let nCacheHits = ref 0
let nFiles = ref 0
let nFunctions = ref 0
let nHygieneErrors = ref 0
let nInfiniteLoops = ref 0
let nRecursiveBlocks = ref 0
let print ppf () =
Format.fprintf ppf "@[<v 2>@,@{<warning>Termination Analysis Stats@}@,";
Format.fprintf ppf "Files:@{<dim>%d@}@," !nFiles;
Format.fprintf ppf "Recursive Blocks:@{<dim>%d@}@," !nRecursiveBlocks;
Format.fprintf ppf "Functions:@{<dim>%d@}@," !nFunctions;
Format.fprintf ppf "Infinite Loops:@{<dim>%d@}@," !nInfiniteLoops;
Format.fprintf ppf "Hygiene Errors:@{<dim>%d@}@," !nHygieneErrors;
Format.fprintf ppf "Cache Hits:@{<dim>%d@}/@{<dim>%d@}@," !nCacheHits
!nCacheChecks;
Format.fprintf ppf "@]"
let dump ~ppf = Format.fprintf ppf "%a@." print ()
let newFile () = incr nFiles
let newRecursiveFunctions ~numFunctions =
incr nRecursiveBlocks;
nFunctions := !nFunctions + numFunctions
let logLoop () = incr nInfiniteLoops
let logCache ~functionCall ~hit ~loc =
incr nCacheChecks;
if hit then incr nCacheHits;
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf "Cache %s for @{<info>%s@}"
(match hit with
| true -> "hit"
| false -> "miss")
(FunctionCall.toString functionCall);
})
let logResult ~functionCall ~loc ~resString =
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf "@{<info>%s@} returns %s"
(FunctionCall.toString functionCall)
resString;
})
let logHygieneParametric ~functionName ~loc =
incr nHygieneErrors;
Log_.error ~loc
(Termination
{
termination = ErrorHygiene;
message =
Format.asprintf
"@{<error>%s@} cannot be analyzed directly as it is parametric"
functionName;
})
let logHygieneOnlyCallDirectly ~path ~loc =
incr nHygieneErrors;
Log_.error ~loc
(Termination
{
termination = ErrorHygiene;
message =
Format.asprintf
"@{<error>%s@} can only be called directly, or passed as \
labeled argument"
(Path.name path);
})
let logHygieneMustHaveNamedArgument ~label ~loc =
incr nHygieneErrors;
Log_.error ~loc
(Termination
{
termination = ErrorHygiene;
message =
Format.asprintf "Call must have named argument @{<error>%s@}" label;
})
let logHygieneNamedArgValue ~label ~loc =
incr nHygieneErrors;
Log_.error ~loc
(Termination
{
termination = ErrorHygiene;
message =
Format.asprintf
"Named argument @{<error>%s@} must be passed a recursive \
function"
label;
})
let logHygieneNoNestedLetRec ~loc =
incr nHygieneErrors;
Log_.error ~loc
(Termination
{
termination = ErrorHygiene;
message = Format.asprintf "Nested multiple let rec not supported yet";
})
end
module Progress = struct
type t = Progress | NoProgress
let toString progress =
match progress = Progress with
| true -> "Progress"
| false -> "NoProgress"
end
module Call = struct
type progressFunction = Path.t
type t =
| FunctionCall of FunctionCall.t
| ProgressFunction of progressFunction
let toString call =
match call with
| ProgressFunction progressFunction -> "+" ^ Path.name progressFunction
| FunctionCall functionCall -> FunctionCall.toString functionCall
end
module Trace = struct
type retOption = Rsome | Rnone
type t =
| Tcall of Call.t * Progress.t
| Tnondet of t list
| Toption of retOption
| Tseq of t list
let empty = Tseq []
let nd (t1 : t) (t2 : t) : t =
match (t1, t2) with
| Tnondet l1, Tnondet l2 -> Tnondet (l1 @ l2)
| _, Tnondet l2 -> Tnondet (t1 :: l2)
| Tnondet l1, _ -> Tnondet (l1 @ [t2])
| _ -> Tnondet [t1; t2]
let seq (t1 : t) (t2 : t) : t =
match (t1, t2) with
| Tseq l1, Tseq l2 -> Tseq (l1 @ l2)
| _, Tseq l2 -> Tseq (t1 :: l2)
| Tseq l1, _ -> Tseq (l1 @ [t2])
| _ -> Tseq [t1; t2]
let some = Toption Rsome
let none = Toption Rnone
let retOptionToString r =
match r = Rsome with
| true -> "Some"
| false -> "None"
let rec toString trace =
match trace with
| Tcall (ProgressFunction progressFunction, progress) ->
Path.name progressFunction ^ ":" ^ Progress.toString progress
| Tcall (FunctionCall functionCall, progress) ->
FunctionCall.toString functionCall ^ ":" ^ Progress.toString progress
| Tnondet traces ->
"[" ^ (traces |> List.map toString |> String.concat " || ") ^ "]"
| Toption retOption -> retOption |> retOptionToString
| Tseq traces -> (
let tracesNotEmpty = traces |> List.filter (( <> ) empty) in
match tracesNotEmpty with
| [] -> "_"
| [t] -> t |> toString
| _ :: _ -> tracesNotEmpty |> List.map toString |> String.concat "; ")
end
module Values : sig
type t
val getNone : t -> Progress.t option
val getSome : t -> Progress.t option
val nd : t -> t -> t
val none : progress:Progress.t -> t
val some : progress:Progress.t -> t
val toString : t -> string
end = struct
type t = {none: Progress.t option; some: Progress.t option}
let getNone {none} = none
let getSome {some} = some
let toString x =
((match x.some with
| None -> []
| Some p -> ["some: " ^ Progress.toString p])
@
match x.none with
| None -> []
| Some p -> ["none: " ^ Progress.toString p])
|> String.concat ", "
let none ~progress = {none = Some progress; some = None}
let some ~progress = {none = None; some = Some progress}
let nd (v1 : t) (v2 : t) : t =
let combine x y =
match (x, y) with
| Some progress1, Some progress2 ->
Some
(match progress1 = Progress.Progress && progress2 = Progress with
| true -> Progress.Progress
| false -> NoProgress)
| None, progressOpt | progressOpt, None -> progressOpt
in
let none = combine v1.none v2.none in
let some = combine v1.some v2.some in
{none; some}
end
module State = struct
type t = {progress: Progress.t; trace: Trace.t; valuesOpt: Values.t option}
let toString {progress; trace; valuesOpt} =
let progressStr =
match valuesOpt with
| None -> progress |> Progress.toString
| Some values -> "{" ^ (values |> Values.toString) ^ "}"
in
progressStr ^ " with trace " ^ Trace.toString trace
let init ?(progress = Progress.NoProgress) ?(trace = Trace.empty)
?(valuesOpt = None) () =
{progress; trace; valuesOpt}
let seq s1 s2 =
let progress =
match s1.progress = Progress || s2.progress = Progress with
| true -> Progress.Progress
| false -> NoProgress
in
let trace = Trace.seq s1.trace s2.trace in
let valuesOpt = s2.valuesOpt in
{progress; trace; valuesOpt}
let sequence states =
match states with
| [] -> assert false
| s :: nextStates -> List.fold_left seq s nextStates
let nd s1 s2 =
let progress =
match s1.progress = Progress && s2.progress = Progress with
| true -> Progress.Progress
| false -> NoProgress
in
let trace = Trace.nd s1.trace s2.trace in
let valuesOpt =
match (s1.valuesOpt, s2.valuesOpt) with
| None, valuesOpt -> (
match s1.progress = Progress with
| true -> valuesOpt
| false -> None)
| valuesOpt, None -> (
match s2.progress = Progress with
| true -> valuesOpt
| false -> None)
| Some values1, Some values2 -> Some (Values.nd values1 values2)
in
{progress; trace; valuesOpt}
let nondet states =
match states with
| [] -> assert false
| s :: nextStates -> List.fold_left nd s nextStates
let unorderedSequence states = {(states |> sequence) with valuesOpt = None}
let none ~progress =
init ~progress ~trace:Trace.none
~valuesOpt:(Some (Values.none ~progress))
()
let some ~progress =
init ~progress ~trace:Trace.some
~valuesOpt:(Some (Values.some ~progress))
()
end
module Command = struct
type progress = Progress.t
type retOption = Trace.retOption
type t =
| Call of Call.t * Location.t
| ConstrOption of retOption
| Nondet of t list
| Nothing
| Sequence of t list
| SwitchOption of {
functionCall: FunctionCall.t;
loc: Location.t;
some: t;
none: t;
}
| UnorderedSequence of t list
let rec toString command =
match command with
| Call (call, _pos) -> call |> Call.toString
| ConstrOption r -> r |> Trace.retOptionToString
| Nondet commands ->
"[" ^ (commands |> List.map toString |> String.concat " || ") ^ "]"
| Nothing -> "_"
| Sequence commands -> commands |> List.map toString |> String.concat "; "
| SwitchOption {functionCall; some = cSome; none = cNone} ->
"switch "
^ FunctionCall.toString functionCall
^ " {some: " ^ toString cSome ^ ", none: " ^ toString cNone ^ "}"
| UnorderedSequence commands ->
"{" ^ (commands |> List.map toString |> String.concat ", ") ^ "}"
let nothing = Nothing
let nondet commands =
let rec loop commands =
match commands with
| [] -> nothing
| Nondet commands :: rest -> loop (commands @ rest)
| [command] -> command
| _ -> Nondet commands
in
loop commands
let sequence commands =
let rec loop acc commands =
match commands with
| [] -> List.rev acc
| Nothing :: cs when cs <> [] -> loop acc cs
| Sequence cs1 :: cs2 -> loop acc (cs1 @ cs2)
| c :: cs -> loop (c :: acc) cs
in
match loop [] commands with
| [c] -> c
| cs -> Sequence cs
let ( +++ ) c1 c2 = sequence [c1; c2]
let unorderedSequence commands =
let relevantCommands = commands |> List.filter (fun x -> x <> nothing) in
match relevantCommands with
| [] -> nothing
| [c] -> c
| _ :: _ :: _ -> UnorderedSequence relevantCommands
end
module Kind = struct
type t = entry list
and entry = {label: string; k: t}
let empty = ([] : t)
let hasLabel ~label (k : t) =
k |> List.exists (fun entry -> entry.label = label)
let rec entryToString {label; k} =
match k = [] with
| true -> label
| false -> label ^ ":" ^ (k |> toString)
and toString (kind : t) =
match kind = [] with
| true -> ""
| false ->
"<" ^ (kind |> List.map entryToString |> String.concat ", ") ^ ">"
let addLabelWithEmptyKind ~label kind =
if not (kind |> hasLabel ~label) then
{label; k = empty} :: kind |> List.sort compare
else kind
end
module FunctionTable = struct
type functionDefinition = {
mutable body: Command.t option;
mutable kind: Kind.t;
}
type t = (FunctionName.t, functionDefinition) Hashtbl.t
let create () : t = Hashtbl.create 1
let print ppf (tbl : t) =
Format.fprintf ppf "@[<v 2>@,@{<warning>Function Table@}";
let definitions =
Hashtbl.fold
(fun functionName {kind; body} definitions ->
(functionName, kind, body) :: definitions)
tbl []
|> List.sort (fun (fn1, _, _) (fn2, _, _) -> String.compare fn1 fn2)
in
definitions
|> List.iteri (fun i (functionName, kind, body) ->
Format.fprintf ppf "@,@{<dim>%d@} @{<info>%s%s@}: %s" (i + 1)
functionName (Kind.toString kind)
(match body with
| Some command -> Command.toString command
| None -> "None"));
Format.fprintf ppf "@]"
let dump tbl = Format.fprintf Format.std_formatter "%a@." print tbl
let initialFunctionDefinition () = {kind = Kind.empty; body = None}
let getFunctionDefinition ~functionName (tbl : t) =
try Hashtbl.find tbl functionName with Not_found -> assert false
let isInFunctionInTable ~functionTable path =
Hashtbl.mem functionTable (Path.name path)
let addFunction ~functionName (tbl : t) =
if Hashtbl.mem tbl functionName then assert false;
Hashtbl.replace tbl functionName (initialFunctionDefinition ())
let addLabelToKind ~functionName ~label (tbl : t) =
let functionDefinition = tbl |> getFunctionDefinition ~functionName in
functionDefinition.kind <-
functionDefinition.kind |> Kind.addLabelWithEmptyKind ~label
let addBody ~body ~functionName (tbl : t) =
let functionDefinition = tbl |> getFunctionDefinition ~functionName in
functionDefinition.body <- body
let functionGetKindOfLabel ~functionName ~label (tbl : t) =
match Hashtbl.find tbl functionName with
| {kind} -> (
match kind |> Kind.hasLabel ~label with
| true -> Some Kind.empty
| false -> None)
| exception Not_found -> None
end
module FindFunctionsCalled = struct
let traverseExpr ~callees =
let super = Tast_mapper.default in
let expr (self : Tast_mapper.mapper) (e : Typedtree.expression) =
(match e.exp_desc with
| Texp_apply ({exp_desc = Texp_ident (callee, _, _)}, _args) ->
let functionName = Path.name callee in
callees := !callees |> StringSet.add functionName
| _ -> ());
super.expr self e
in
{super with Tast_mapper.expr}
let findCallees (expression : Typedtree.expression) =
let isFunction =
match expression.exp_desc with
| Texp_function _ -> true
| _ -> false
in
let callees = ref StringSet.empty in
let traverseExpr = traverseExpr ~callees in
if isFunction then expression |> traverseExpr.expr traverseExpr |> ignore;
!callees
end
module ExtendFunctionTable = struct
(* Add functions passed a recursive function via a labeled argument,
and functions calling progress functions, to the function table. *)
let extractLabelledArgument ?(kindOpt = None)
(argOpt : Typedtree.expression option) =
match argOpt with
| Some {exp_desc = Texp_ident (path, {loc}, _)} -> Some (path, loc)
| Some
{
exp_desc =
Texp_let
( Nonrecursive,
[
{
vb_pat = {pat_desc = Tpat_var (_, _)};
vb_expr = {exp_desc = Texp_ident (path, {loc}, _)};
vb_loc = {loc_ghost = true};
};
],
_ );
} ->
Some (path, loc)
| Some
{exp_desc = Texp_apply ({exp_desc = Texp_ident (path, {loc}, _)}, args)}
when kindOpt <> None ->
let checkArg ((argLabel : Asttypes.arg_label), _argOpt) =
match (argLabel, kindOpt) with
| (Labelled l | Optional l), Some kind ->
kind |> List.for_all (fun {Kind.label} -> label <> l)
| _ -> true
in
if args |> List.for_all checkArg then Some (path, loc) else None
| _ -> None
let traverseExpr ~functionTable ~progressFunctions ~valueBindingsTable =
let super = Tast_mapper.default in
let expr (self : Tast_mapper.mapper) (e : Typedtree.expression) =
(match e.exp_desc with
| Texp_ident (callee, _, _) -> (
let loc = e.exp_loc in
match Hashtbl.find_opt valueBindingsTable (Path.name callee) with
| None -> ()
| Some (id_pos, _, callees) ->
if
not
(StringSet.is_empty
(StringSet.inter (Lazy.force callees) progressFunctions))
then
let functionName = Path.name callee in
if not (callee |> FunctionTable.isInFunctionInTable ~functionTable)
then (
functionTable |> FunctionTable.addFunction ~functionName;
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf
"Extend Function Table with @{<info>%s@} (%a) as it \
calls a progress function"
functionName printPos id_pos;
})))
| Texp_apply ({exp_desc = Texp_ident (callee, _, _)}, args)
when callee |> FunctionTable.isInFunctionInTable ~functionTable ->
let functionName = Path.name callee in
args
|> List.iter (fun ((argLabel : Asttypes.arg_label), argOpt) ->
match (argLabel, argOpt |> extractLabelledArgument) with
| Labelled label, Some (path, loc)
when path |> FunctionTable.isInFunctionInTable ~functionTable
->
functionTable
|> FunctionTable.addLabelToKind ~functionName ~label;
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf
"@{<info>%s@} is parametric \
~@{<info>%s@}=@{<info>%s@}"
functionName label (Path.name path);
})
| _ -> ())
| _ -> ());
super.expr self e
in
{super with Tast_mapper.expr}
let run ~functionTable ~progressFunctions ~valueBindingsTable
(expression : Typedtree.expression) =
let traverseExpr =
traverseExpr ~functionTable ~progressFunctions ~valueBindingsTable
in
expression |> traverseExpr.expr traverseExpr |> ignore
end
module CheckExpressionWellFormed = struct
let traverseExpr ~functionTable ~valueBindingsTable =
let super = Tast_mapper.default in
let checkIdent ~path ~loc =
if path |> FunctionTable.isInFunctionInTable ~functionTable then
Stats.logHygieneOnlyCallDirectly ~path ~loc
in
let expr (self : Tast_mapper.mapper) (e : Typedtree.expression) =
match e.exp_desc with
| Texp_ident (path, {loc}, _) ->
checkIdent ~path ~loc;
e
| Texp_apply ({exp_desc = Texp_ident (functionPath, _, _)}, args) ->
let functionName = Path.name functionPath in
args
|> List.iter (fun ((argLabel : Asttypes.arg_label), argOpt) ->
match argOpt |> ExtendFunctionTable.extractLabelledArgument with
| Some (path, loc) -> (
match argLabel with
| Labelled label -> (
if
functionTable
|> FunctionTable.functionGetKindOfLabel ~functionName
~label
<> None
then ()
else
match Hashtbl.find_opt valueBindingsTable functionName with
| Some (_pos, (body : Typedtree.expression), _)
when path
|> FunctionTable.isInFunctionInTable ~functionTable
->
let inTable =
functionPath
|> FunctionTable.isInFunctionInTable ~functionTable
in
if not inTable then
functionTable
|> FunctionTable.addFunction ~functionName;
functionTable
|> FunctionTable.addLabelToKind ~functionName ~label;
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc:body.exp_loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf
"Extend Function Table with @{<info>%s@} \
as parametric ~@{<info>%s@}=@{<info>%s@}"
functionName label (Path.name path);
})
| _ -> checkIdent ~path ~loc)
| Optional _ | Nolabel -> checkIdent ~path ~loc)
| _ -> ());
e
| _ -> super.expr self e
in
{super with Tast_mapper.expr}
let run ~functionTable ~valueBindingsTable (expression : Typedtree.expression)
=
let traverseExpr = traverseExpr ~functionTable ~valueBindingsTable in
expression |> traverseExpr.expr traverseExpr |> ignore
end
module Compile = struct
type ctx = {
currentFunctionName: FunctionName.t;
functionTable: FunctionTable.t;
innerRecursiveFunctions: (FunctionName.t, FunctionName.t) Hashtbl.t;
isProgressFunction: Path.t -> bool;
}
let rec expression ~ctx (expr : Typedtree.expression) =
let {currentFunctionName; functionTable; isProgressFunction} = ctx in
let loc = expr.exp_loc in
let notImplemented case =
Log_.error ~loc
(Termination
{termination = ErrorNotImplemented; message = Format.asprintf case})
in
match expr.exp_desc with
| Texp_ident _ -> Command.nothing
| Texp_apply
(({exp_desc = Texp_ident (calleeToRename, l, vd)} as expr), argsToExtend)
-> (
let callee, args =
match
Hashtbl.find_opt ctx.innerRecursiveFunctions
(Path.name calleeToRename)
with
| Some innerFunctionName ->
let innerFunctionDefinition =
functionTable
|> FunctionTable.getFunctionDefinition
~functionName:innerFunctionName
in
let argsFromKind =
innerFunctionDefinition.kind
|> List.map (fun (entry : Kind.entry) ->
( Asttypes.Labelled entry.label,
Some
{
expr with
exp_desc =
Texp_ident
(Path.Pident (Ident.create entry.label), l, vd);
} ))
in
( Path.Pident (Ident.create innerFunctionName),
argsFromKind @ argsToExtend )
| None -> (calleeToRename, argsToExtend)
in
if callee |> FunctionTable.isInFunctionInTable ~functionTable then
let functionName = Path.name callee in
let functionDefinition =
functionTable |> FunctionTable.getFunctionDefinition ~functionName
in
let exception ArgError in
let getFunctionArg {Kind.label} =
let argOpt =
args
|> List.find_opt (fun arg ->
match arg with
| Asttypes.Labelled s, Some _ -> s = label
| _ -> false)
in
let argOpt =
match argOpt with
| Some (_, Some e) -> Some e
| _ -> None
in
let functionArg () =
match
argOpt
|> ExtendFunctionTable.extractLabelledArgument
~kindOpt:(Some functionDefinition.kind)
with
| None ->
Stats.logHygieneMustHaveNamedArgument ~label ~loc;
raise ArgError
| Some (path, _pos)
when path |> FunctionTable.isInFunctionInTable ~functionTable ->
let functionName = Path.name path in
{FunctionArgs.label; functionName}
| Some (path, _pos)
when functionTable
|> FunctionTable.functionGetKindOfLabel
~functionName:currentFunctionName
~label:(Path.name path)
= Some []
(* TODO: when kinds are inferred, support and check non-empty kinds *)
->
let functionName = Path.name path in
{FunctionArgs.label; functionName}
| _ ->
Stats.logHygieneNamedArgValue ~label ~loc;
raise ArgError
[@@raises ArgError]
in
functionArg ()
[@@raises ArgError]
in
let functionArgsOpt =
try Some (functionDefinition.kind |> List.map getFunctionArg)
with ArgError -> None
in
match functionArgsOpt with
| None -> Command.nothing
| Some functionArgs ->
Command.Call (FunctionCall {functionName; functionArgs}, loc)
|> evalArgs ~args ~ctx
else if callee |> isProgressFunction then
Command.Call (ProgressFunction callee, loc) |> evalArgs ~args ~ctx
else
match
functionTable
|> FunctionTable.functionGetKindOfLabel
~functionName:currentFunctionName ~label:(Path.name callee)
with
| Some kind when kind = Kind.empty ->
Command.Call
(FunctionCall (Path.name callee |> FunctionCall.noArgs), loc)
|> evalArgs ~args ~ctx
| Some _kind ->
(* TODO when kinds are extended in future: check that args matches with kind
and create a function call with the appropriate arguments *)
assert false
| None -> expr |> expression ~ctx |> evalArgs ~args ~ctx)
| Texp_apply (expr, args) -> expr |> expression ~ctx |> evalArgs ~args ~ctx
| Texp_let
( Recursive,
[{vb_pat = {pat_desc = Tpat_var (id, _); pat_loc}; vb_expr}],
inExpr ) ->
let oldFunctionName = Ident.name id in
let newFunctionName = currentFunctionName ^ "$" ^ oldFunctionName in
functionTable |> FunctionTable.addFunction ~functionName:newFunctionName;
let newFunctionDefinition =
functionTable
|> FunctionTable.getFunctionDefinition ~functionName:newFunctionName
in
let currentFunctionDefinition =
functionTable
|> FunctionTable.getFunctionDefinition ~functionName:currentFunctionName
in
newFunctionDefinition.kind <- currentFunctionDefinition.kind;
let newCtx = {ctx with currentFunctionName = newFunctionName} in
Hashtbl.replace ctx.innerRecursiveFunctions oldFunctionName
newFunctionName;
newFunctionDefinition.body <- Some (vb_expr |> expression ~ctx:newCtx);
if !Common.Cli.debug then
Log_.warning ~forStats:false ~loc:pat_loc
(Termination
{
termination = TerminationAnalysisInternal;
message =
Format.asprintf "Adding recursive definition @{<info>%s@}"
newFunctionName;
});
inExpr |> expression ~ctx
| Texp_let (recFlag, valueBindings, inExpr) ->
if recFlag = Recursive then Stats.logHygieneNoNestedLetRec ~loc;
let commands =
(valueBindings
|> List.map (fun (vb : Typedtree.value_binding) ->
vb.vb_expr |> expression ~ctx))
@ [inExpr |> expression ~ctx]
in
Command.sequence commands
| Texp_sequence (e1, e2) ->
let open Command in
expression ~ctx e1 +++ expression ~ctx e2
| Texp_ifthenelse (e1, e2, eOpt) ->
let c1 = e1 |> expression ~ctx in
let c2 = e2 |> expression ~ctx in
let c3 = eOpt |> expressionOpt ~ctx in
let open Command in
c1 +++ nondet [c2; c3]
| Texp_constant _ -> Command.nothing
| Texp_construct ({loc = {loc_ghost}}, {cstr_name}, expressions) -> (
let c =
expressions
|> List.map (fun e -> e |> expression ~ctx)
|> Command.unorderedSequence
in
match cstr_name with
| "Some" when loc_ghost = false ->
let open Command in
c +++ ConstrOption Rsome
| "None" when loc_ghost = false ->
let open Command in
c +++ ConstrOption Rnone
| _ -> c)
| Texp_function {cases} -> cases |> List.map (case ~ctx) |> Command.nondet
| Texp_match (e, casesOk, casesExn, _partial)
when not
(casesExn
|> List.map (fun (case : Typedtree.case) -> case.c_lhs.pat_desc)
!= []) -> (
(* No exceptions *)
let cases = casesOk @ casesExn in
let cE = e |> expression ~ctx in
let cCases = cases |> List.map (case ~ctx) in
let fail () =
let open Command in
cE +++ nondet cCases
in
match (cE, cases) with
| ( Call (FunctionCall functionCall, loc),
[{c_lhs = pattern1}; {c_lhs = pattern2}] ) -> (
match (pattern1.pat_desc, pattern2.pat_desc) with
| ( Tpat_construct (_, {cstr_name = ("Some" | "None") as name1}, _),
Tpat_construct (_, {cstr_name = "Some" | "None"}, _) ) ->
let casesArr = Array.of_list cCases in
let some, none =
try
match name1 = "Some" with
| true -> (casesArr.(0), casesArr.(1))
| false -> (casesArr.(1), casesArr.(0))
with Invalid_argument _ -> (Nothing, Nothing)
in
Command.SwitchOption {functionCall; loc; some; none}
| _ -> fail ())
| _ -> fail ())
| Texp_match _ -> assert false (* exceptions *)
| Texp_field (e, _lid, _desc) -> e |> expression ~ctx
| Texp_record {fields; extended_expression} ->
extended_expression
:: (fields |> Array.to_list
|> List.map
(fun
( _desc,
(recordLabelDefinition : Typedtree.record_label_definition) )
->
match recordLabelDefinition with
| Kept _typeExpr -> None
| Overridden (_loc, e) -> Some e))
|> List.map (expressionOpt ~ctx)
|> Command.unorderedSequence
| Texp_setfield (e1, _loc, _desc, e2) ->
[e1; e2] |> List.map (expression ~ctx) |> Command.unorderedSequence
| Texp_tuple expressions | Texp_array expressions ->
expressions |> List.map (expression ~ctx) |> Command.unorderedSequence
| Texp_assert _ -> Command.nothing
| Texp_try (e, cases) ->
let cE = e |> expression ~ctx in
let cCases = cases |> List.map (case ~ctx) |> Command.nondet in
let open Command in
cE +++ cCases
| Texp_variant (_label, eOpt) -> eOpt |> expressionOpt ~ctx
| Texp_while _ ->
notImplemented "Texp_while";
assert false
| Texp_for _ ->
notImplemented "Texp_for";
assert false
| Texp_send _ ->
notImplemented "Texp_send";
assert false
| Texp_new _ ->
notImplemented "Texp_new";
assert false
| Texp_instvar _ ->
notImplemented "Texp_instvar";
assert false
| Texp_setinstvar _ ->
notImplemented "Texp_setinstvar";
assert false
| Texp_override _ ->
notImplemented "Texp_override";
assert false
| Texp_letmodule _ ->
notImplemented "Texp_letmodule";
assert false
| Texp_letexception _ ->
notImplemented "Texp_letexception";
assert false
| Texp_lazy _ ->
notImplemented "Texp_lazy";
assert false
| Texp_object _ ->
notImplemented "Texp_letmodule";
assert false