Source file Smv.ml
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
open Containers
let nuXmv_default_script = Scripts.nuXmv_default_script
let nuSMV_default_script = Scripts.nuSMV_default_script
let nuXmv_default_bmc_script = Scripts.nuXmv_default_bmc_script
let nuSMV_default_bmc_script = Scripts.nuSMV_default_bmc_script
module Make_SMV_LTL (At : Solver.ATOMIC_PROPOSITION) :
  Solver.LTL with module Atomic = At = struct
  module I = Solver.LTL_from_Atomic (At)
  include I
  module PP = struct
    open Fmtc
    let rainbow =
      let r = ref 0 in
      fun () ->
        let cur = !r in
        incr r;
        match cur with
        | 0 ->
            `Magenta
        | 1 ->
            `Yellow
        | 2 ->
            `Cyan
        | 3 ->
            `Green
        | 4 ->
            `Red
        | 5 ->
            r := 0;
            `Blue
        | _ ->
            assert false
    
    let rainbow_paren ?(paren = false) ?(align_par = true) upper this out pr =
      
      let par = paren || this < upper in
      pecified, they'll be numerous so avoid alignment of
         closing parentheses *)
      gn_par = not paren && align_par in *)
      if par
      then (
        arentheses *)
        let color = rainbow () in
        if align_par then Format.pp_open_box out 0 else Format.pp_open_box out 2;
        styled color string out "(";
        if align_par then Format.pp_open_box out 2;
        ding parentheses so precedence goes back to 0 inside of
           them *)
        pr 0;
        if align_par
        then (
          Format.pp_close_box out ();
          cut out () );
        styled color string out ")";
        Format.pp_close_box out () )
      else 
           
        pr this
    let infixl
        ?(paren = false)
        ?(align_par = true)
        upper
        this
        middle
        left
        right
        out
        (m, l, r) =
      rainbow_paren ~paren ~align_par upper this out
      @@ fun new_this ->
      
      left new_this out l;
      sp out ();
      styled `Bold middle out m;
      sp out ();
      right (new_this + 1) out r
    
    let infixr
        ?(paren = false)
        ?(align_par = true)
        upper
        this
        middle
        left
        right
        out
        (m, l, r) =
      rainbow_paren ~paren ~align_par upper this out
      @@ fun new_this ->
      left (new_this + 1) out l;
      sp out ();
      styled `Bold middle out m;
      sp out ();
      right new_this out r
    let infixn
        ?(paren = false)
        ?(align_par = true)
        upper
        this
        middle
        left
        right
        out
        (m, l, r) =
      rainbow_paren ~paren ~align_par upper this out
      @@ fun new_this ->
      left (new_this + 1) out l;
      sp out ();
      styled `Bold middle out m;
      sp out ();
      right (new_this + 1) out r
    let prefix
        ?(paren = false)
        ?(align_par = true)
        upper
        this
        pprefix
        pbody
        out
        (prefix, body) =
      rainbow_paren ~paren ~align_par upper this out
      @@ fun new_this ->
      styled `Bold pprefix out prefix;
      pbody (new_this + 1) out body
    let pp_atomic = At.pp
    let pp_tcomp out (t : tcomp) =
      pf out "%s"
      @@
      match t with
      | Lte ->
          "<="
      | Lt ->
          "<"
      | Gte ->
          ">="
      | Gt ->
          ">"
      | Eq ->
          "="
      | Neq ->
          "!="
    
    let pp ?(next_is_X = true) variables upper out f =
      let rec pp upper out f =
        assert (upper >= 0);
        match f with
        | True ->
            pf out "TRUE"
        | False ->
            pf out "FALSE"
        | Atomic at ->
            variables := Iter.cons at !variables;
            pf out "%a" pp_atomic at
        
        | Imp (p, q) ->
            infixr ~paren:true upper 1 string pp pp out ("->", p, q)
        | Iff (p, q) ->
            infixl ~paren:true upper 2 string pp pp out ("<->", p, q)
        | Ite (c, t, e) ->
            
            pp upper out
            @@ I.Infix.((c @=> lazy t) +&& lazy (I.not_ c @=> lazy e))
        | Or (p, q) ->
            infixl ~paren:true upper 4 string pp pp out ("|", p, q)
        
        | Xor (p, q) ->
            infixl ~paren:true upper 4 string pp pp out ("xor", p, q)
        | And (p, q) ->
            infixl ~paren:true upper 5 string pp pp out ("&", p, q)
        | Comp (op, t1, t2) ->
            infixn upper 6 pp_tcomp pp_term pp_term out (op, t1, t2)
        | Not p ->
            prefix upper 9 string pp out ("!", p)
        
        | U (p, q) ->
            infixl ~paren:true upper upper string pp pp out ("U", p, q)
        | R (p, q) ->
            infixl ~paren:true upper upper string pp pp out ("V", p, q)
        | S (p, q) ->
            infixl ~paren:true upper upper string pp pp out ("S", p, q)
        | T (p, q) ->
            infixl ~paren:true upper upper string pp pp out ("T", p, q)
        | X p when next_is_X ->
            prefix ~paren:true upper upper string pp out ("X ", p)
        | X p ->
            
            styled `Bold string out "next";
            pf out "@[(%a@])" (pp 0) p
        | F p ->
            prefix ~paren:true upper upper string pp out ("F ", p)
        | G p ->
            prefix ~paren:true upper upper string pp out ("G ", p)
        | Y p ->
            prefix ~paren:true upper upper string pp out ("Y ", p)
        | O p ->
            prefix ~paren:true upper upper string pp out ("O ", p)
        | H p ->
            prefix ~paren:true upper upper string pp out ("H ", p)
      and pp_term upper out (t : term) =
        match t with
        | Num n ->
            pf out "%d" n
        | Plus (t1, t2) ->
            infixl ~paren:true upper 7 string pp_term pp_term out ("+", t1, t2)
        | Minus (t1, t2) ->
            infixl ~paren:true upper 7 string pp_term pp_term out ("-", t1, t2)
        | Neg t ->
            prefix upper 8 string pp_term out ("- ", t)
        | Count ts ->
            styled `Bold string out "count";
            pf out "@[(%a@])" (list ~sep:(const string ", ") (pp 0)) ts
      in
      pp upper out f
  end
  let pp_gather_variables ?(next_is_X = true) variables out f =
    Fmtc.pf out "@[<hov2>%a@]" (PP.pp ~next_is_X variables 0) f
  let pp out f = pp_gather_variables (ref Iter.empty) out f
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
end
module Make_SMV_file_format (Ltl : Solver.LTL) :
  Solver.MODEL with type ltl = Ltl.t and type atomic = Ltl.Atomic.t = struct
  type ltl = Ltl.t
  type atomic = Ltl.Atomic.t
  type t =
    { elo : Elo.t
    ; init : (string * ltl) Iter.t
    ; invariant : (string * ltl) Iter.t
    ; trans : (string * ltl) Iter.t
    ; property : string * ltl
    }
  let make ~elo ~init ~invariant ~trans ~property =
    { elo; init; invariant; trans; property }
  let pp_plain_decl vartype out atomic =
    Fmtc.pf out "%s %a : boolean;" vartype Ltl.Atomic.pp atomic
  
  let pp_enum_decl elo vartype out atoms =
    let module S = Iter in
    let tuple_to_string tuple =
      Fmtc.(strf "%a" @@ list ~sep:minus Atom.pp) (Tuple.to_list tuple)
    in
    let atom_name at = Option.get_exn @@ Ltl.Atomic.split at in
    let pp_one_decl atom =
      let name, _ = atom_name atom in
      let name_str = Name.to_string name in
      
      let may = Domain.may name elo.Elo.domain |> Tuple_set.to_iter in
      
      let dom_ar = Ltl.Atomic.domain_arity atom in
      match dom_ar with
      | None ->
          assert false
      | Some n when n < 0 ->
          assert false
      | Some 0 ->
          
          let may_strings = S.map tuple_to_string may in
          
          let may_strings_with_empty =
            if Ltl.Atomic.is_partial atom
            then
              
              S.snoc may_strings "__NONE__"
            else may_strings
          in
          S.iter
            (fun tuple_str ->
              Fmtc.(
                pf
                  out
                  "DEFINE %s-%s := __%s = %s;@\n"
                  name_str
                  tuple_str
                  name_str
                  tuple_str))
            may_strings;
          Fmtc.(
            pf
              out
              "%s __%s : %a;@\n"
              vartype
              name_str
              (braces_ @@ S.pp_seq string)
              may_strings_with_empty)
      | Some n ->
          
          
          let domains_ranges =
            may
            |> S.map (fun tuple ->
                   Pair.map_same tuple_to_string @@ Tuple.split tuple n)
            |> S.group_by
                 ~hash:(fun (dom, _) -> Hash.string dom)
                 ~eq:(fun (dom1, _) (dom2, _) -> String.equal dom1 dom2)
          in
          
          
          S.iter
            (fun pairs ->
              List.iter
                (fun (dom_str, range_str) ->
                  Fmtc.(
                    pf
                      out
                      "DEFINE %s-%s-%s := __%s-%s = %s;@\n"
                      name_str
                      dom_str
                      range_str
                      name_str
                      dom_str
                      range_str))
                pairs)
            domains_ranges;
          
          S.iter
            (fun pairs ->
              let dom_str = fst @@ List.hd pairs in
              Fmtc.(
                pf
                  out
                  "%s __%s-%s : %a;@\n"
                  vartype
                  name_str
                  dom_str
                  (braces_ @@ box @@ list ~sep:(sp **> comma) string)
                  ( if Ltl.Atomic.is_partial atom
                  then List.rev ("__NONE__" :: List.rev_map snd pairs)
                  else List.map snd pairs )))
            domains_ranges
    in
    atoms
    |> S.sort_uniq 
         ~cmp:(fun at1 at2 ->
           Name.compare (fst @@ atom_name at1) (fst @@ atom_name at2))
    |> S.iter (fun at ->
           Fmtc.hardline out ();
           pp_one_decl at)
  let pp_count_variables
      ?(margin = 80) out { elo; init; invariant; trans; property } =
    let open Fmtc in
    let module S = Iter in
    
    let variables = ref S.empty in
    let old_margin = Format.pp_get_margin out () in
    Format.pp_set_margin out margin;
    pf
      out
      "-- Generated by electrod (C) ONERA 2016-2020@\n\
       MODULE main@\n\
       JUSTICE TRUE;@\n\
       @\n";
    
    Format.pp_open_vbox out 0;
    S.iter
      (fun (elo_str, fml) ->
        pf
          out
          "%s@\nINIT@\n@[<hv2>%a@];@\n@\n"
          elo_str
          (Ltl.pp_gather_variables variables)
          fml)
      init;
    Format.pp_close_box out ();
    
    Format.pp_open_vbox out 0;
    S.iter
      (fun (elo_str, fml) ->
        pf
          out
          "%s@\nINVAR@\n@[<hv2>%a@];@\n@\n"
          elo_str
          (Ltl.pp_gather_variables variables)
          fml)
      invariant;
    Format.pp_close_box out ();
    
    Format.pp_open_vbox out 0;
    S.iter
      (fun (elo_str, fml) ->
        pf
          out
          "%s@\nTRANS@\n@[<hv2>%a@];@\n@\n"
          elo_str
          (Ltl.pp_gather_variables ~next_is_X:false variables)
          fml)
      trans;
    Format.pp_close_box out ();
    
    Format.pp_open_vbox out 0;
    let prop_str, ltlspec = property in
    pf
      out
      "%s@\nLTLSPEC@\n@[<hv2>%a@];@\n@\n"
      prop_str
      (Ltl.pp_gather_variables variables)
      ltlspec;
    Format.pp_close_box out ();
    
    
    let sort_atomics atoms = S.sort_uniq ~cmp:Ltl.Atomic.compare atoms in
    variables := sort_atomics !variables;
    
    let r_plain, r_enum, f_plain, f_enum =
      S.fold
        (fun (acc_rp, acc_re, acc_fp, acc_fe) at ->
          if Ltl.Atomic.is_const at
          then
            
            if Option.is_none @@ Ltl.Atomic.domain_arity at
            then 
              (S.cons at acc_rp, acc_re, acc_fp, acc_fe)
            else 
              (acc_rp, S.cons at acc_re, acc_fp, acc_fe)
          else if 
                  Option.is_none @@ Ltl.Atomic.domain_arity at
          then 
            (acc_rp, acc_re, S.cons at acc_fp, acc_fe)
          else 
            (acc_rp, acc_re, acc_fp, S.cons at acc_fe))
        (S.empty, S.empty, S.empty, S.empty)
        !variables
      |> fun (res_rp, res_re, res_fp, res_fe) ->
      (sort_atomics res_rp, res_re, sort_atomics res_fp, res_fe)
    in
    
    S.iter (fun at -> pf out "%a@\n" (pp_plain_decl "FROZENVAR") at) r_plain;
    
    pp_enum_decl elo "FROZENVAR" out r_enum;
    
    if not (S.is_empty r_plain || S.is_empty f_plain) then hardline out ();
    S.iter (fun at -> pf out "%a@\n" (pp_plain_decl "VAR") at) f_plain;
    
    pp_enum_decl elo "VAR" out f_enum;
    
    Format.pp_print_flush out ();
    Format.pp_set_margin out old_margin;
    
    S.length !variables
  let pp ?(margin = 80) out { elo; init; invariant; trans; property } =
    ignore
      (pp_count_variables ~margin out { elo; init; invariant; trans; property })
  
  let make_model_file dir infile model =
    let src_file = Filename.basename infile in
    let tgt = Filename.temp_file ~temp_dir:dir (src_file ^ "-") ".smv" in
    let nbvars = ref 0 in
    IO.with_out tgt (fun out ->
        nbvars := pp_count_variables (Format.formatter_of_out_channel out) model);
    (tgt, !nbvars)
  let make_script_file bmc dir script =
    let tgt = Filename.temp_file ~temp_dir:dir "electrod-" ".scr" in
    let first_line =
      match bmc with
      | None ->
          ""
      | Some length ->
          "set bmc_length " ^ string_of_int length ^ "; "
    in
    ( match script with
    | Solver.File filename ->
        
        
        IO.with_out tgt (fun out ->
            IO.write_line out first_line;
            IO.with_in filename (fun inp ->
                let chunks = IO.read_chunks_gen inp in
                IO.write_gen out chunks))
    | Solver.Default default ->
        IO.with_out tgt (fun out -> IO.write_line out (first_line ^ default)) );
    tgt
  let analyze
      ~conversion_time
      ~cmd
      ~script
      ~keep_files
      ~no_analysis
      ~elo
      ~file
      ~bmc
      model : Outcome.t =
    let keep_or_remove_files scr smv =
      if keep_files
      then
        if no_analysis
        then
          Logs.app (fun m ->
              m "@[<hv2>Keeping the script and SMV files at:@ %s@\n%s@]" scr smv)
        else Logs.app (fun m -> m "@[<hv2>Keeping the script and SMV files@]")
      else (
        Logs.info (fun m -> m "@[<hv2>Removing files:@ %s@\n%s@]" scr smv);
        ( match script with
        | Solver.Default _ ->
            IO.File.remove_noerr scr
        | Solver.File _ ->
            () );
        IO.File.remove_noerr smv )
    in
    
    let dir = Filename.dirname file in
    let scr = make_script_file bmc dir script in
    let before_generation = Mtime_clock.now () in
    let smv, nbvars = make_model_file dir file model in
    let after_generation = Mtime_clock.now () in
    Msg.info (fun m ->
        let size, unit_ =
          let s = float_of_int @@ Unix.((stat smv).st_size) in
          if Float.(s < 1_024.)
          then (s, "B")
          else if Float.(s < 1_048_576.)
          then (s /. 1_024., "KB")
          else if Float.(s < 1_073_741_824.)
          then (s /. 1_048_576., "MB")
          else (s /. 1_073_741_824., "GB")
        in
        m
          "SMV file (size: %.0f%s) generated in %a"
          (Float.round size)
          unit_
          Mtime.Span.pp
          (Mtime.span before_generation after_generation));
    if no_analysis
    then (
      keep_or_remove_files scr smv;
      Outcome.no_trace nbvars conversion_time Mtime.Span.zero )
    else
      
      let sigterm_handler =
        Sys.Signal_handle
          (fun _ ->
            print_endline "Received termination signal!";
            keep_or_remove_files scr smv;
            print_endline "Exiting";
            Unix.kill 0 Sys.sigterm;
            
            exit 1)
      in
      let previous_handler = Sys.signal Sys.sigterm sigterm_handler in
      
      let to_call = Fmt.strf "%s -source %s %s" cmd scr smv in
      Logs.info (fun m -> m "Starting analysis:@[<h2>@ %s@]" to_call);
      let before_run = Mtime_clock.now () in
      let okout, errout, errcode = CCUnix.call "%s" to_call in
      let after_run = Mtime_clock.now () in
      
      Sys.set_signal Sys.sigterm previous_handler;
      let analysis_time = Mtime.span before_run after_run in
      if errcode <> 0
      then Msg.Fatal.solver_failed (fun args -> args cmd scr smv errcode errout)
      else
        
        Msg.info (fun m -> m "Analysis done in %a" Mtime.Span.pp analysis_time);
      
      let validity_check line =
        match bmc with
        | None ->
            String.suffix ~suf:"is true" line
        | Some length ->
            let valid_bmc_string =
              "-- no counterexample found with bound " ^ string_of_int length
            in
            String.equal valid_bmc_string line
      in
      let spec =
        String.lines_gen okout
        |> Gen.drop_while (fun line ->
               (not @@ String.suffix ~suf:"is false" line)
               && (not @@ validity_check line))
      in
      keep_or_remove_files scr smv;
      let spec_s =
        match Gen.get spec with
        | None ->
            failwith
              ( "Incorrectly handled SMV string:"
              ^ Fmt.to_to_string (Gen.pp String.pp) spec )
        | Some s ->
            s
      in
      if validity_check spec_s
      then Outcome.no_trace nbvars conversion_time analysis_time
      else
        
        
        let module P =
          Smv_trace_parser.Make (struct
            let base = Domain.musts ~with_univ_and_ident:false elo.Elo.domain
          end)
        in
        let trace =
          spec
          
          |> Gen.drop_while (fun line -> not @@ String.prefix ~pre:"Trace" line)
          |> Gen.drop_while (String.prefix ~pre:"Trace")
          |> String.unlines_gen
          
          |> fun trace_str ->
          let lexbuf = Lexing.from_string trace_str in
          P.trace (Smv_trace_scanner.main Ltl.Atomic.split_string) lexbuf
        in
        if not @@ Outcome.loop_is_present trace
        then
          Msg.Fatal.solver_bug (fun args ->
              args cmd "trace is missing a loop state.")
        else
          let atom_back_renaming =
            List.map (fun (x, y) -> (y, x)) elo.atom_renaming
          in
          let name_back_renaming =
            List.map (fun (x, y) -> (y, x)) elo.name_renaming
          in
          Outcome.trace
            (atom_back_renaming, name_back_renaming)
            nbvars
            conversion_time
            analysis_time
            trace
end