src/HOL/Tools/Nitpick/nitpick.ML
author wenzelm
Tue Sep 26 20:54:40 2017 +0200 (23 months ago)
changeset 66695 91500c024c7f
parent 63693 5b02f7757a4c
child 69593 3dda49e08b9d
permissions -rw-r--r--
tuned;
blanchet@33982
     1
(*  Title:      HOL/Tools/Nitpick/nitpick.ML
blanchet@33192
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@34982
     3
    Copyright   2008, 2009, 2010
blanchet@33192
     4
blanchet@33192
     5
Finite model generation for HOL formulas using Kodkod.
blanchet@33192
     6
*)
blanchet@33192
     7
blanchet@33192
     8
signature NITPICK =
blanchet@33192
     9
sig
blanchet@35711
    10
  type term_postprocessor = Nitpick_Model.term_postprocessor
blanchet@43022
    11
blanchet@47560
    12
  datatype mode = Auto_Try | Try | Normal | TPTP
blanchet@43022
    13
blanchet@36390
    14
  type params =
blanchet@36390
    15
    {cards_assigns: (typ option * int list) list,
blanchet@55889
    16
     maxes_assigns: ((string * typ) option * int list) list,
blanchet@55889
    17
     iters_assigns: ((string * typ) option * int list) list,
blanchet@36390
    18
     bitss: int list,
blanchet@36390
    19
     bisim_depths: int list,
blanchet@36390
    20
     boxes: (typ option * bool option) list,
blanchet@36390
    21
     finitizes: (typ option * bool option) list,
blanchet@36390
    22
     monos: (typ option * bool option) list,
blanchet@55889
    23
     wfs: ((string * typ) option * bool option) list,
blanchet@36390
    24
     sat_solver: string,
blanchet@36390
    25
     falsify: bool,
blanchet@36390
    26
     debug: bool,
blanchet@36390
    27
     verbose: bool,
blanchet@36390
    28
     overlord: bool,
blanchet@53802
    29
     spy: bool,
blanchet@36390
    30
     user_axioms: bool option,
blanchet@36390
    31
     assms: bool,
blanchet@38209
    32
     whacks: term list,
blanchet@36390
    33
     merge_type_vars: bool,
blanchet@36390
    34
     binary_ints: bool option,
blanchet@36390
    35
     destroy_constrs: bool,
blanchet@36390
    36
     specialize: bool,
blanchet@36390
    37
     star_linear_preds: bool,
blanchet@41856
    38
     total_consts: bool option,
blanchet@41876
    39
     needs: term list option,
blanchet@36390
    40
     peephole_optim: bool,
blanchet@38124
    41
     datatype_sym_break: int,
blanchet@38124
    42
     kodkod_sym_break: int,
blanchet@54816
    43
     timeout: Time.time,
blanchet@54816
    44
     tac_timeout: Time.time,
blanchet@36390
    45
     max_threads: int,
blanchet@55889
    46
     show_types: bool,
blanchet@41993
    47
     show_skolems: bool,
blanchet@36390
    48
     show_consts: bool,
blanchet@36390
    49
     evals: term list,
blanchet@36390
    50
     formats: (term option * int list) list,
blanchet@37260
    51
     atomss: (typ option * string list) list,
blanchet@36390
    52
     max_potential: int,
blanchet@36390
    53
     max_genuine: int,
blanchet@36390
    54
     batch_size: int,
blanchet@36390
    55
     expect: string}
blanchet@33192
    56
blanchet@43020
    57
  val genuineN : string
blanchet@43020
    58
  val quasi_genuineN : string
blanchet@43020
    59
  val potentialN : string
blanchet@43020
    60
  val noneN : string
blanchet@43020
    61
  val unknownN : string
blanchet@33192
    62
  val register_frac_type : string -> (string * string) list -> theory -> theory
blanchet@33192
    63
  val unregister_frac_type : string -> theory -> theory
blanchet@55889
    64
  val register_codatatype : typ -> string -> (string * typ) list -> theory ->
blanchet@55889
    65
    theory
blanchet@33192
    66
  val unregister_codatatype : typ -> theory -> theory
blanchet@35711
    67
  val register_term_postprocessor :
blanchet@35711
    68
    typ -> term_postprocessor -> theory -> theory
blanchet@35711
    69
  val unregister_term_postprocessor : typ -> theory -> theory
blanchet@33192
    70
  val pick_nits_in_term :
blanchet@43022
    71
    Proof.state -> params -> mode -> int -> int -> int -> (term * term) list
wenzelm@58892
    72
    -> term list -> term list -> term -> string * string list
blanchet@33192
    73
  val pick_nits_in_subgoal :
wenzelm@58892
    74
    Proof.state -> params -> mode -> int -> int -> string * string list
blanchet@33192
    75
end;
blanchet@33192
    76
blanchet@33192
    77
structure Nitpick : NITPICK =
blanchet@33192
    78
struct
blanchet@33192
    79
blanchet@33232
    80
open Nitpick_Util
blanchet@33232
    81
open Nitpick_HOL
blanchet@35070
    82
open Nitpick_Preproc
blanchet@33232
    83
open Nitpick_Mono
blanchet@33232
    84
open Nitpick_Scope
blanchet@33232
    85
open Nitpick_Peephole
blanchet@33232
    86
open Nitpick_Rep
blanchet@33232
    87
open Nitpick_Nut
blanchet@33232
    88
open Nitpick_Kodkod
blanchet@33232
    89
open Nitpick_Model
blanchet@33192
    90
blanchet@34126
    91
structure KK = Kodkod
blanchet@34126
    92
blanchet@47560
    93
datatype mode = Auto_Try | Try | Normal | TPTP
blanchet@47560
    94
blanchet@47560
    95
fun is_mode_nt mode = (mode = Normal orelse mode = TPTP)
blanchet@43022
    96
blanchet@36390
    97
type params =
blanchet@36390
    98
  {cards_assigns: (typ option * int list) list,
blanchet@55889
    99
   maxes_assigns: ((string * typ) option * int list) list,
blanchet@55889
   100
   iters_assigns: ((string * typ) option * int list) list,
blanchet@36390
   101
   bitss: int list,
blanchet@36390
   102
   bisim_depths: int list,
blanchet@36390
   103
   boxes: (typ option * bool option) list,
blanchet@36390
   104
   finitizes: (typ option * bool option) list,
blanchet@36390
   105
   monos: (typ option * bool option) list,
blanchet@55889
   106
   wfs: ((string * typ) option * bool option) list,
blanchet@36390
   107
   sat_solver: string,
blanchet@36390
   108
   falsify: bool,
blanchet@36390
   109
   debug: bool,
blanchet@36390
   110
   verbose: bool,
blanchet@36390
   111
   overlord: bool,
blanchet@53802
   112
   spy: bool,
blanchet@36390
   113
   user_axioms: bool option,
blanchet@36390
   114
   assms: bool,
blanchet@38209
   115
   whacks: term list,
blanchet@36390
   116
   merge_type_vars: bool,
blanchet@36390
   117
   binary_ints: bool option,
blanchet@36390
   118
   destroy_constrs: bool,
blanchet@36390
   119
   specialize: bool,
blanchet@36390
   120
   star_linear_preds: bool,
blanchet@41856
   121
   total_consts: bool option,
blanchet@41876
   122
   needs: term list option,
blanchet@36390
   123
   peephole_optim: bool,
blanchet@38124
   124
   datatype_sym_break: int,
blanchet@38124
   125
   kodkod_sym_break: int,
blanchet@54816
   126
   timeout: Time.time,
blanchet@54816
   127
   tac_timeout: Time.time,
blanchet@36390
   128
   max_threads: int,
blanchet@55889
   129
   show_types: bool,
blanchet@41993
   130
   show_skolems: bool,
blanchet@36390
   131
   show_consts: bool,
blanchet@36390
   132
   evals: term list,
blanchet@36390
   133
   formats: (term option * int list) list,
blanchet@37260
   134
   atomss: (typ option * string list) list,
blanchet@36390
   135
   max_potential: int,
blanchet@36390
   136
   max_genuine: int,
blanchet@36390
   137
   batch_size: int,
blanchet@36390
   138
   expect: string}
blanchet@33192
   139
blanchet@43020
   140
val genuineN = "genuine"
blanchet@43020
   141
val quasi_genuineN = "quasi_genuine"
blanchet@43020
   142
val potentialN = "potential"
blanchet@43020
   143
val noneN = "none"
blanchet@43020
   144
val unknownN = "unknown"
blanchet@43020
   145
blanchet@38240
   146
(* TODO: eliminate these historical aliases *)
blanchet@38240
   147
val register_frac_type = Nitpick_HOL.register_frac_type_global
blanchet@38240
   148
val unregister_frac_type = Nitpick_HOL.unregister_frac_type_global
blanchet@38240
   149
val register_codatatype = Nitpick_HOL.register_codatatype_global
blanchet@38240
   150
val unregister_codatatype = Nitpick_HOL.unregister_codatatype_global
blanchet@38240
   151
val register_term_postprocessor =
blanchet@38240
   152
  Nitpick_Model.register_term_postprocessor_global
blanchet@38240
   153
val unregister_term_postprocessor =
blanchet@38240
   154
  Nitpick_Model.unregister_term_postprocessor_global
blanchet@38240
   155
blanchet@36390
   156
type problem_extension =
blanchet@36390
   157
  {free_names: nut list,
blanchet@36390
   158
   sel_names: nut list,
blanchet@36390
   159
   nonsel_names: nut list,
blanchet@36390
   160
   rel_table: nut NameTable.table,
blanchet@36390
   161
   unsound: bool,
blanchet@36390
   162
   scope: scope}
blanchet@39316
   163
blanchet@34126
   164
type rich_problem = KK.problem * problem_extension
blanchet@33192
   165
blanchet@33192
   166
fun pretties_for_formulas _ _ [] = []
blanchet@33192
   167
  | pretties_for_formulas ctxt s ts =
blanchet@33192
   168
    [Pretty.str (s ^ plural_s_for_list ts ^ ":"),
blanchet@33192
   169
     Pretty.indent indent_size (Pretty.chunks
blanchet@33192
   170
         (map2 (fn j => fn t =>
blanchet@34121
   171
                   Pretty.block [t |> shorten_names_in_term
blanchet@63693
   172
                                   |> Syntax.pretty_term ctxt])
blanchet@33192
   173
               (length ts downto 1) ts))]
blanchet@33192
   174
blanchet@49024
   175
val isabelle_wrong_message =
blanchet@63693
   176
  "something appears to be wrong with your Isabelle installation"
blanchet@55889
   177
val java_not_found_message =
blanchet@63693
   178
  "Java could not be launched -- " ^ isabelle_wrong_message
blanchet@55889
   179
val java_too_old_message =
blanchet@63693
   180
  "The Java version is too old -- " ^ isabelle_wrong_message
blanchet@55889
   181
val kodkodi_not_installed_message =
blanchet@63693
   182
  "Nitpick requires the external Java program Kodkodi"
blanchet@63693
   183
val kodkodi_too_old_message = "The installed Kodkodi version is too old"
blanchet@55889
   184
blanchet@35185
   185
val max_unsound_delay_ms = 200
blanchet@35185
   186
val max_unsound_delay_percent = 2
blanchet@33192
   187
blanchet@54816
   188
fun unsound_delay_for_timeout timeout =
blanchet@54816
   189
  Int.max (0, Int.min (max_unsound_delay_ms,
blanchet@54816
   190
                       Time.toMilliseconds timeout
blanchet@54816
   191
                       * max_unsound_delay_percent div 100))
blanchet@33192
   192
blanchet@34123
   193
fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
blanchet@33192
   194
blanchet@41048
   195
fun has_lonely_bool_var (@{const Pure.conjunction}
blanchet@41048
   196
                         $ (@{const Trueprop} $ Free _) $ _) = true
blanchet@41048
   197
  | has_lonely_bool_var _ = false
blanchet@41048
   198
blanchet@34038
   199
val syntactic_sorts =
haftmann@38857
   200
  @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,equal}"} @
huffman@47108
   201
  @{sort numeral}
blanchet@55889
   202
blanchet@34038
   203
fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
blanchet@34038
   204
    subset (op =) (S, syntactic_sorts)
blanchet@34038
   205
  | has_tfree_syntactic_sort _ = false
blanchet@34038
   206
val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
blanchet@33192
   207
wenzelm@59432
   208
fun plazy f = Pretty.para (f ())
blanchet@33568
   209
blanchet@43022
   210
fun pick_them_nits_in_term deadline state (params : params) mode i n step
blanchet@47715
   211
                           subst def_assm_ts nondef_assm_ts orig_t =
blanchet@33192
   212
  let
wenzelm@62519
   213
    val time_start = Time.now ()
blanchet@33192
   214
    val timer = Timer.startRealTimer ()
blanchet@34935
   215
    val thy = Proof.theory_of state
blanchet@34935
   216
    val ctxt = Proof.context_of state
wenzelm@58928
   217
    val keywords = Thy_Header.get_keywords thy
blanchet@35386
   218
(* FIXME: reintroduce code before new release:
blanchet@35386
   219
wenzelm@37216
   220
    val nitpick_thy = Thy_Info.get_theory "Nitpick"
wenzelm@60948
   221
    val _ = Context.subthy (nitpick_thy, thy) orelse
blanchet@34936
   222
            error "You must import the theory \"Nitpick\" to use Nitpick"
blanchet@34982
   223
*)
blanchet@34124
   224
    val {cards_assigns, maxes_assigns, iters_assigns, bitss, bisim_depths,
blanchet@55888
   225
         boxes, finitizes, monos, wfs, sat_solver, falsify, debug, verbose,
blanchet@55888
   226
         overlord, spy, user_axioms, assms, whacks, merge_type_vars,
blanchet@38209
   227
         binary_ints, destroy_constrs, specialize, star_linear_preds,
blanchet@41875
   228
         total_consts, needs, peephole_optim, datatype_sym_break,
blanchet@55889
   229
         kodkod_sym_break, tac_timeout, max_threads, show_types, show_skolems,
blanchet@55889
   230
         show_consts, evals, formats, atomss, max_potential, max_genuine,
blanchet@60310
   231
         batch_size, ...} = params
wenzelm@58892
   232
    val outcome = Synchronized.var "Nitpick.outcome" (Queue.empty: string Queue.T)
wenzelm@58892
   233
    fun pprint print prt =
blanchet@43022
   234
      if mode = Auto_Try then
wenzelm@59184
   235
        Synchronized.change outcome (Queue.enqueue (Pretty.string_of prt))
blanchet@33192
   236
      else
wenzelm@58892
   237
        print (Pretty.string_of prt)
wenzelm@58843
   238
    val pprint_a = pprint writeln
wenzelm@58843
   239
    fun pprint_nt f = () |> is_mode_nt mode ? pprint writeln o f
wenzelm@58843
   240
    fun pprint_v f = () |> verbose ? pprint writeln o f
blanchet@46086
   241
    fun pprint_d f = () |> debug ? pprint tracing o f
wenzelm@59432
   242
    val print = pprint writeln o Pretty.para
blanchet@47560
   243
    fun print_t f = () |> mode = TPTP ? print o f
blanchet@39345
   244
(*
blanchet@46086
   245
    val print_g = pprint tracing o Pretty.str
blanchet@39345
   246
*)
blanchet@47560
   247
    val print_nt = pprint_nt o K o plazy
blanchet@33568
   248
    val print_v = pprint_v o K o plazy
blanchet@33192
   249
blanchet@33192
   250
    fun check_deadline () =
wenzelm@62519
   251
      let val t = Time.now () in
wenzelm@62519
   252
        if Time.compare (t, deadline) <> LESS
wenzelm@62826
   253
        then raise Timeout.TIMEOUT (t - time_start)
wenzelm@62519
   254
        else ()
wenzelm@62519
   255
      end
blanchet@33192
   256
blanchet@47715
   257
    val (def_assm_ts, nondef_assm_ts) =
blanchet@47715
   258
      if assms orelse mode <> Normal then (def_assm_ts, nondef_assm_ts)
blanchet@47715
   259
      else ([], [])
blanchet@34982
   260
    val _ =
blanchet@34982
   261
      if step = 0 then
blanchet@47560
   262
        print_nt (fn () => "Nitpicking formula...")
blanchet@34982
   263
      else
blanchet@47560
   264
        pprint_nt (fn () => Pretty.chunks (
blanchet@34982
   265
            pretties_for_formulas ctxt ("Nitpicking " ^
blanchet@34982
   266
                (if i <> 1 orelse n <> 1 then
blanchet@34982
   267
                   "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
blanchet@34982
   268
                 else
blanchet@47715
   269
                   "goal")) [Logic.list_implies (nondef_assm_ts, orig_t)]))
blanchet@53815
   270
    val _ = spying spy (fn () => (state, i, "starting " ^ @{make_string} mode ^ " mode"))
blanchet@63693
   271
    val _ = print_v (prefix "Timestamp: " o Date.fmt "%H:%M:%S"
blanchet@41278
   272
                     o Date.fromTimeLocal o Time.now)
blanchet@33192
   273
    val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
blanchet@33192
   274
                else orig_t
blanchet@47715
   275
    val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
blanchet@38169
   276
    val tfree_table =
blanchet@41869
   277
      if merge_type_vars then merged_type_var_table_for_terms thy conj_ts
blanchet@41869
   278
      else []
blanchet@41869
   279
    val merge_tfrees = merge_type_vars_in_term thy merge_type_vars tfree_table
blanchet@41869
   280
    val neg_t = neg_t |> merge_tfrees
blanchet@47715
   281
    val def_assm_ts = def_assm_ts |> map merge_tfrees
blanchet@47715
   282
    val nondef_assm_ts = nondef_assm_ts |> map merge_tfrees
blanchet@41869
   283
    val evals = evals |> map merge_tfrees
blanchet@41876
   284
    val needs = needs |> Option.map (map merge_tfrees)
blanchet@47715
   285
    val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
blanchet@33192
   286
    val original_max_potential = max_potential
blanchet@33192
   287
    val original_max_genuine = max_genuine
blanchet@33192
   288
    val max_bisim_depth = fold Integer.max bisim_depths ~1
blanchet@55888
   289
    val case_names = case_const_names ctxt
blanchet@47715
   290
    val defs = def_assm_ts @ all_defs_of thy subst
blanchet@42415
   291
    val nondefs = all_nondefs_of ctxt subst
blanchet@41791
   292
    val def_tables = const_def_tables ctxt subst defs
blanchet@42415
   293
    val nondef_table = const_nondef_table nondefs
blanchet@35335
   294
    val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
blanchet@35335
   295
    val psimp_table = const_psimp_table ctxt subst
blanchet@35807
   296
    val choice_spec_table = const_choice_spec_table ctxt subst
blanchet@42415
   297
    val nondefs =
wenzelm@59970
   298
      nondefs |> filter_out (is_choice_spec_axiom ctxt choice_spec_table)
blanchet@41791
   299
    val intro_table = inductive_intro_table ctxt subst def_tables
blanchet@33192
   300
    val ground_thm_table = ground_theorem_table thy
blanchet@38240
   301
    val ersatz_table = ersatz_table ctxt
blanchet@41007
   302
    val hol_ctxt as {wf_cache, ...} =
blanchet@33192
   303
      {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
blanchet@55888
   304
       wfs = wfs, user_axioms = user_axioms, debug = debug, whacks = whacks,
blanchet@55888
   305
       binary_ints = binary_ints, destroy_constrs = destroy_constrs,
blanchet@55888
   306
       specialize = specialize, star_linear_preds = star_linear_preds,
blanchet@55888
   307
       total_consts = total_consts, needs = needs, tac_timeout = tac_timeout,
blanchet@55888
   308
       evals = evals, case_names = case_names, def_tables = def_tables,
blanchet@42415
   309
       nondef_table = nondef_table, nondefs = nondefs, simp_table = simp_table,
blanchet@42415
   310
       psimp_table = psimp_table, choice_spec_table = choice_spec_table,
blanchet@42415
   311
       intro_table = intro_table, ground_thm_table = ground_thm_table,
blanchet@42415
   312
       ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
blanchet@42415
   313
       special_funs = Unsynchronized.ref [],
blanchet@33580
   314
       unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
blanchet@33580
   315
       constr_cache = Unsynchronized.ref []}
blanchet@41789
   316
    val pseudo_frees = []
blanchet@41869
   317
    val real_frees = fold Term.add_frees conj_ts []
blanchet@41869
   318
    val _ = null (fold Term.add_tvars conj_ts []) orelse
blanchet@63693
   319
            error "Nitpick cannot handle goals with schematic type variables"
blanchet@41875
   320
    val (nondef_ts, def_ts, need_ts, got_all_mono_user_axioms,
blanchet@41803
   321
         no_poly_user_axioms, binarize) =
blanchet@47715
   322
      preprocess_formulas hol_ctxt nondef_assm_ts neg_t
blanchet@33192
   323
    val got_all_user_axioms =
blanchet@33192
   324
      got_all_mono_user_axioms andalso no_poly_user_axioms
blanchet@33192
   325
blanchet@33192
   326
    fun print_wf (x, (gfp, wf)) =
blanchet@47560
   327
      pprint_nt (fn () => Pretty.blk (0,
wenzelm@60023
   328
          Pretty.text ("The " ^ (if gfp then "co" else "") ^ "inductive predicate") @
wenzelm@60023
   329
          [Pretty.brk 1, Pretty.quote (Syntax.pretty_term ctxt (Const x)), Pretty.brk 1] @
wenzelm@59432
   330
          Pretty.text (if wf then
blanchet@63693
   331
                   "was proved well-founded; Nitpick can compute it \
blanchet@63693
   332
                   \efficiently"
blanchet@33192
   333
                 else
blanchet@63693
   334
                   "could not be proved well-founded; Nitpick might need to \
blanchet@63693
   335
                   \unroll it")))
blanchet@33192
   336
    val _ = if verbose then List.app print_wf (!wf_cache) else ()
blanchet@38171
   337
    val das_wort_formula = if falsify then "Negated conjecture" else "Formula"
blanchet@33192
   338
    val _ =
blanchet@35386
   339
      pprint_d (fn () => Pretty.chunks
blanchet@38171
   340
          (pretties_for_formulas ctxt das_wort_formula [hd nondef_ts] @
blanchet@35386
   341
           pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
blanchet@35386
   342
           pretties_for_formulas ctxt "Relevant nondefinitional axiom"
blanchet@35386
   343
                                 (tl nondef_ts)))
blanchet@35386
   344
    val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
blanchet@33192
   345
            handle TYPE (_, Ts, ts) =>
blanchet@33192
   346
                   raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
blanchet@33192
   347
blanchet@41801
   348
    val nondef_us = nondef_ts |> map (nut_from_term hol_ctxt Eq)
blanchet@41801
   349
    val def_us = def_ts |> map (nut_from_term hol_ctxt DefEq)
blanchet@41875
   350
    val need_us = need_ts |> map (nut_from_term hol_ctxt Eq)
blanchet@33558
   351
    val (free_names, const_names) =
blanchet@41888
   352
      fold add_free_and_const_names (nondef_us @ def_us @ need_us) ([], [])
blanchet@33558
   353
    val (sel_names, nonsel_names) =
blanchet@33558
   354
      List.partition (is_sel o nickname_of) const_names
blanchet@46114
   355
    val sound_finitizes = none_true finitizes
blanchet@33558
   356
(*
blanchet@41888
   357
    val _ =
blanchet@41888
   358
      List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us @ need_us)
blanchet@33558
   359
*)
blanchet@33558
   360
blanchet@34121
   361
    val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
blanchet@35385
   362
    fun monotonicity_message Ts extra =
wenzelm@58928
   363
      let val pretties = map (pretty_maybe_quote keywords o pretty_for_type ctxt) Ts in
blanchet@38188
   364
        Pretty.blk (0,
wenzelm@60023
   365
          Pretty.text ("The type" ^ plural_s_for_list pretties) @ [Pretty.brk 1] @
wenzelm@60023
   366
          pretty_serial_commas "and" pretties @ [Pretty.brk 1] @
wenzelm@60023
   367
          Pretty.text (
blanchet@42959
   368
                 (if none_true monos then
blanchet@42959
   369
                    "passed the monotonicity test"
blanchet@42959
   370
                  else
blanchet@42959
   371
                    (if length pretties = 1 then "is" else "are") ^
blanchet@42959
   372
                    " considered monotonic") ^
blanchet@63693
   373
                 "; " ^ extra))
blanchet@35385
   374
      end
blanchet@35665
   375
    fun is_type_fundamentally_monotonic T =
blanchet@55890
   376
      (is_data_type ctxt T andalso not (is_quot_type ctxt T) andalso
blanchet@37256
   377
       (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
blanchet@38240
   378
      is_number_type ctxt T orelse is_bit_type T
blanchet@35385
   379
    fun is_type_actually_monotonic T =
wenzelm@62519
   380
      Timeout.apply tac_timeout (formulas_monotonic hol_ctxt binarize T)
blanchet@54816
   381
                          (nondef_ts, def_ts)
wenzelm@62519
   382
        handle Timeout.TIMEOUT _ => false
blanchet@35665
   383
    fun is_type_kind_of_monotonic T =
blanchet@35665
   384
      case triple_lookup (type_match thy) monos T of
blanchet@35665
   385
        SOME (SOME false) => false
blanchet@35665
   386
      | _ => is_type_actually_monotonic T
blanchet@34936
   387
    fun is_type_monotonic T =
blanchet@33192
   388
      unique_scope orelse
blanchet@33192
   389
      case triple_lookup (type_match thy) monos T of
blanchet@33192
   390
        SOME (SOME b) => b
blanchet@35665
   391
      | _ => is_type_fundamentally_monotonic T orelse
blanchet@35665
   392
             is_type_actually_monotonic T
blanchet@55890
   393
    fun is_deep_data_type_finitizable T =
blanchet@41793
   394
      triple_lookup (type_match thy) finitizes T = SOME (SOME true)
blanchet@55890
   395
    fun is_shallow_data_type_finitizable (T as Type (@{type_name fun_box}, _)) =
blanchet@35665
   396
        is_type_kind_of_monotonic T
blanchet@55890
   397
      | is_shallow_data_type_finitizable T =
blanchet@35665
   398
        case triple_lookup (type_match thy) finitizes T of
blanchet@35665
   399
          SOME (SOME b) => b
blanchet@35665
   400
        | _ => is_type_kind_of_monotonic T
blanchet@55890
   401
    fun is_data_type_deep T =
blanchet@55888
   402
      T = @{typ unit} orelse T = nat_T orelse is_word_type T orelse
blanchet@35385
   403
      exists (curry (op =) T o domain_type o type_of) sel_names
blanchet@35386
   404
    val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
wenzelm@35408
   405
                 |> sort Term_Ord.typ_ord
blanchet@38214
   406
    val _ =
blanchet@38214
   407
      if verbose andalso binary_ints = SOME true andalso
blanchet@38214
   408
         exists (member (op =) [nat_T, int_T]) all_Ts then
blanchet@38214
   409
        print_v (K "The option \"binary_ints\" will be ignored because of the \
blanchet@38214
   410
                   \presence of rationals, reals, \"Suc\", \"gcd\", or \"lcm\" \
blanchet@63693
   411
                   \in the problem")
blanchet@38214
   412
      else
blanchet@38214
   413
        ()
blanchet@34982
   414
    val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
blanchet@33192
   415
    val _ =
blanchet@34936
   416
      if verbose andalso not unique_scope then
blanchet@35665
   417
        case filter_out is_type_fundamentally_monotonic mono_Ts of
blanchet@34936
   418
          [] => ()
blanchet@34936
   419
        | interesting_mono_Ts =>
blanchet@38188
   420
          pprint_v (K (monotonicity_message interesting_mono_Ts
blanchet@63693
   421
                          "Nitpick might be able to skip some scopes"))
blanchet@33192
   422
      else
blanchet@33192
   423
        ()
blanchet@35385
   424
    val (deep_dataTs, shallow_dataTs) =
blanchet@55890
   425
      all_Ts |> filter (is_data_type ctxt)
blanchet@55890
   426
             |> List.partition is_data_type_deep
blanchet@35385
   427
    val finitizable_dataTs =
blanchet@41793
   428
      (deep_dataTs |> filter_out (is_finite_type hol_ctxt)
blanchet@55890
   429
                   |> filter is_deep_data_type_finitizable) @
blanchet@41793
   430
      (shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
blanchet@55890
   431
                      |> filter is_shallow_data_type_finitizable)
blanchet@35385
   432
    val _ =
blanchet@35385
   433
      if verbose andalso not (null finitizable_dataTs) then
blanchet@38188
   434
        pprint_v (K (monotonicity_message finitizable_dataTs
blanchet@63693
   435
                         "Nitpick can use a more precise finite encoding"))
blanchet@35385
   436
      else
blanchet@35385
   437
        ()
blanchet@33192
   438
(*
blanchet@36128
   439
    val _ = print_g "Monotonic types:"
blanchet@36128
   440
    val _ = List.app (print_g o string_for_type ctxt) mono_Ts
blanchet@36128
   441
    val _ = print_g "Nonmonotonic types:"
blanchet@36128
   442
    val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
blanchet@33192
   443
*)
blanchet@33192
   444
blanchet@36384
   445
    val incremental = Int.max (max_potential, max_genuine) >= 2
blanchet@36384
   446
    val actual_sat_solver =
blanchet@33192
   447
      if sat_solver <> "smart" then
blanchet@36384
   448
        if incremental andalso
blanchet@34936
   449
           not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
blanchet@35333
   450
                       sat_solver) then
blanchet@47560
   451
          (print_nt (K ("An incremental SAT solver is required: \"SAT4J\" will \
blanchet@63693
   452
                        \be used instead of " ^ quote sat_solver));
blanchet@33192
   453
           "SAT4J")
blanchet@33192
   454
        else
blanchet@33192
   455
          sat_solver
blanchet@33192
   456
      else
blanchet@36384
   457
        Kodkod_SAT.smart_sat_solver_name incremental
blanchet@33192
   458
    val _ =
blanchet@33192
   459
      if sat_solver = "smart" then
blanchet@36384
   460
        print_v (fn () =>
blanchet@63693
   461
            "Using SAT solver " ^ quote actual_sat_solver ^ "\nThe following" ^
blanchet@36384
   462
            (if incremental then " incremental " else " ") ^
blanchet@36384
   463
            "solvers are configured: " ^
blanchet@63693
   464
            commas_quote (Kodkod_SAT.configured_sat_solvers incremental))
blanchet@33192
   465
      else
blanchet@33192
   466
        ()
blanchet@33192
   467
blanchet@33192
   468
    val too_big_scopes = Unsynchronized.ref []
blanchet@33192
   469
blanchet@35185
   470
    fun problem_for_scope unsound
blanchet@55890
   471
            (scope as {card_assigns, bits, bisim_depth, data_types, ofs, ...}) =
blanchet@33192
   472
      let
blanchet@33192
   473
        val _ = not (exists (fn other => scope_less_eq other scope)
blanchet@34936
   474
                            (!too_big_scopes)) orelse
blanchet@34936
   475
                raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
blanchet@34936
   476
                                 \problem_for_scope", "too large scope")
blanchet@33192
   477
(*
blanchet@36128
   478
        val _ = print_g "Offsets:"
blanchet@33192
   479
        val _ = List.app (fn (T, j0) =>
blanchet@36128
   480
                             print_g (string_for_type ctxt T ^ " = " ^
blanchet@36128
   481
                                    string_of_int j0))
blanchet@33192
   482
                         (Typtab.dest ofs)
blanchet@33192
   483
*)
blanchet@41858
   484
        val effective_total_consts =
blanchet@41856
   485
          case total_consts of
blanchet@41856
   486
            SOME b => b
blanchet@55890
   487
          | NONE => forall (is_exact_type data_types true) all_Ts
blanchet@33192
   488
        val main_j0 = offset_of_type ofs bool_T
blanchet@33192
   489
        val (nat_card, nat_j0) = spec_of_type scope nat_T
blanchet@33192
   490
        val (int_card, int_j0) = spec_of_type scope int_T
blanchet@34936
   491
        val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
blanchet@34936
   492
                raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
blanchet@34936
   493
                           "bad offsets")
blanchet@33192
   494
        val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
blanchet@33192
   495
        val (free_names, rep_table) =
blanchet@38170
   496
          choose_reps_for_free_vars scope pseudo_frees free_names
blanchet@38170
   497
                                    NameTable.empty
blanchet@33192
   498
        val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
blanchet@38170
   499
        val (nonsel_names, rep_table) =
blanchet@41858
   500
          choose_reps_for_consts scope effective_total_consts nonsel_names
blanchet@41858
   501
                                 rep_table
blanchet@38182
   502
        val (guiltiest_party, min_highest_arity) =
blanchet@38182
   503
          NameTable.fold (fn (name, R) => fn (s, n) =>
blanchet@38182
   504
                             let val n' = arity_of_rep R in
blanchet@38182
   505
                               if n' > n then (nickname_of name, n') else (s, n)
blanchet@38182
   506
                             end) rep_table ("", 1)
blanchet@33192
   507
        val min_univ_card =
blanchet@36384
   508
          NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
blanchet@34126
   509
                         (univ_card nat_card int_card main_j0 [] KK.True)
blanchet@52202
   510
        val _ = check_arity guiltiest_party min_univ_card min_highest_arity
blanchet@33192
   511
blanchet@41802
   512
        val def_us =
blanchet@41802
   513
          def_us |> map (choose_reps_in_nut scope unsound rep_table true)
blanchet@41802
   514
        val nondef_us =
blanchet@41802
   515
          nondef_us |> map (choose_reps_in_nut scope unsound rep_table false)
blanchet@41875
   516
        val need_us =
blanchet@41875
   517
          need_us |> map (choose_reps_in_nut scope unsound rep_table false)
blanchet@33745
   518
(*
blanchet@36128
   519
        val _ = List.app (print_g o string_for_nut ctxt)
blanchet@33192
   520
                         (free_names @ sel_names @ nonsel_names @
blanchet@41888
   521
                          nondef_us @ def_us @ need_us)
blanchet@33745
   522
*)
blanchet@33192
   523
        val (free_rels, pool, rel_table) =
blanchet@33192
   524
          rename_free_vars free_names initial_pool NameTable.empty
blanchet@33192
   525
        val (sel_rels, pool, rel_table) =
blanchet@33192
   526
          rename_free_vars sel_names pool rel_table
blanchet@33192
   527
        val (other_rels, pool, rel_table) =
blanchet@33192
   528
          rename_free_vars nonsel_names pool rel_table
blanchet@41802
   529
        val nondef_us = nondef_us |> map (rename_vars_in_nut pool rel_table)
blanchet@41802
   530
        val def_us = def_us |> map (rename_vars_in_nut pool rel_table)
blanchet@41875
   531
        val need_us = need_us |> map (rename_vars_in_nut pool rel_table)
blanchet@35386
   532
        val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
blanchet@35280
   533
        val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
blanchet@35386
   534
        val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
blanchet@35185
   535
        val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
wenzelm@37146
   536
                      Print_Mode.setmp [] multiline_string_for_scope scope
blanchet@34998
   537
        val kodkod_sat_solver =
blanchet@36384
   538
          Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
blanchet@34124
   539
        val bit_width = if bits = 0 then 16 else bits + 1
blanchet@36384
   540
        val delay =
blanchet@36384
   541
          if unsound then
wenzelm@62826
   542
            unsound_delay_for_timeout (deadline - Time.now ())
blanchet@36384
   543
          else
blanchet@36384
   544
            0
blanchet@36384
   545
        val settings = [("solver", commas_quote kodkod_sat_solver),
blanchet@34124
   546
                        ("bit_width", string_of_int bit_width),
blanchet@38124
   547
                        ("symmetry_breaking", string_of_int kodkod_sym_break),
blanchet@36386
   548
                        ("sharing", "3"),
blanchet@36386
   549
                        ("flatten", "false"),
blanchet@33192
   550
                        ("delay", signed_string_of_int delay)]
blanchet@33192
   551
        val plain_rels = free_rels @ other_rels
blanchet@33192
   552
        val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
blanchet@33192
   553
        val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
blanchet@41995
   554
        val need_vals =
blanchet@41995
   555
          map (fn dtype as {typ, ...} =>
blanchet@55890
   556
                  (typ, needed_values_for_data_type need_us ofs dtype))
blanchet@55890
   557
              data_types
blanchet@41995
   558
        val sel_bounds =
blanchet@55890
   559
          map (bound_for_sel_rel ctxt debug need_vals data_types) sel_rels
blanchet@35190
   560
        val dtype_axioms =
blanchet@55890
   561
          declarative_axioms_for_data_types hol_ctxt binarize need_us need_vals
blanchet@55890
   562
              datatype_sym_break bits ofs kk rel_table data_types
blanchet@33192
   563
        val declarative_axioms = plain_axioms @ dtype_axioms
blanchet@35220
   564
        val univ_card = Int.max (univ_card nat_card int_card main_j0
blanchet@35220
   565
                                     (plain_bounds @ sel_bounds) formula,
blanchet@35220
   566
                                 main_j0 |> bits > 0 ? Integer.add (bits + 1))
blanchet@38126
   567
        val (built_in_bounds, built_in_axioms) =
blanchet@39345
   568
          bounds_and_axioms_for_built_in_rels_in_formulas debug univ_card
blanchet@39345
   569
              nat_card int_card main_j0 (formula :: declarative_axioms)
blanchet@33192
   570
        val bounds = built_in_bounds @ plain_bounds @ sel_bounds
blanchet@33192
   571
                     |> not debug ? merge_bounds
blanchet@38126
   572
        val axioms = built_in_axioms @ declarative_axioms
blanchet@33192
   573
        val highest_arity =
blanchet@33192
   574
          fold Integer.max (map (fst o fst) (maps fst bounds)) 0
blanchet@38126
   575
        val formula = fold_rev s_and axioms formula
blanchet@34124
   576
        val _ = if bits = 0 then () else check_bits bits formula
blanchet@52202
   577
        val _ = if formula = KK.False then ()
blanchet@38182
   578
                else check_arity "" univ_card highest_arity
blanchet@33192
   579
      in
blanchet@33192
   580
        SOME ({comment = comment, settings = settings, univ_card = univ_card,
blanchet@33192
   581
               tuple_assigns = [], bounds = bounds,
blanchet@35280
   582
               int_bounds = if bits = 0 then sequential_int_bounds univ_card
blanchet@35280
   583
                            else pow_of_two_int_bounds bits main_j0,
blanchet@33192
   584
               expr_assigns = [], formula = formula},
blanchet@33192
   585
              {free_names = free_names, sel_names = sel_names,
blanchet@33192
   586
               nonsel_names = nonsel_names, rel_table = rel_table,
blanchet@35386
   587
               unsound = unsound, scope = scope})
blanchet@33192
   588
      end
blanchet@34124
   589
      handle TOO_LARGE (loc, msg) =>
blanchet@34936
   590
             if loc = "Nitpick_Kodkod.check_arity" andalso
blanchet@34936
   591
                not (Typtab.is_empty ofs) then
blanchet@35185
   592
               problem_for_scope unsound
blanchet@35190
   593
                   {hol_ctxt = hol_ctxt, binarize = binarize,
blanchet@35190
   594
                    card_assigns = card_assigns, bits = bits,
blanchet@55890
   595
                    bisim_depth = bisim_depth, data_types = data_types,
blanchet@35190
   596
                    ofs = Typtab.empty}
blanchet@33192
   597
             else if loc = "Nitpick.pick_them_nits_in_term.\
blanchet@33192
   598
                           \problem_for_scope" then
blanchet@33192
   599
               NONE
blanchet@33192
   600
             else
blanchet@33192
   601
               (Unsynchronized.change too_big_scopes (cons scope);
blanchet@41992
   602
                print_v (fn () =>
blanchet@63693
   603
                    "Limit reached: " ^ msg ^ "; skipping " ^
blanchet@41992
   604
                    (if unsound then "potential component of " else "") ^
blanchet@63693
   605
                    "scope");
blanchet@33192
   606
                NONE)
blanchet@35280
   607
           | TOO_SMALL (_, msg) =>
blanchet@41992
   608
             (print_v (fn () =>
blanchet@63693
   609
                  "Limit reached: " ^ msg ^ "; skipping " ^
blanchet@41992
   610
                  (if unsound then "potential component of " else "") ^
blanchet@63693
   611
                  "scope");
blanchet@34124
   612
              NONE)
blanchet@33192
   613
blanchet@55888
   614
    val das_wort_model = if falsify then "counterexample" else "model"
blanchet@33192
   615
blanchet@33192
   616
    val scopes = Unsynchronized.ref []
blanchet@33192
   617
    val generated_scopes = Unsynchronized.ref []
blanchet@35185
   618
    val generated_problems = Unsynchronized.ref ([] : rich_problem list)
blanchet@33192
   619
    val checked_problems = Unsynchronized.ref (SOME [])
blanchet@33192
   620
    val met_potential = Unsynchronized.ref 0
blanchet@33192
   621
blanchet@33192
   622
    fun update_checked_problems problems =
blanchet@33192
   623
      List.app (Unsynchronized.change checked_problems o Option.map o cons
blanchet@33192
   624
                o nth problems)
blanchet@35333
   625
    fun show_kodkod_warning "" = ()
blanchet@63693
   626
      | show_kodkod_warning s = print_nt (fn () => "Kodkod warning: " ^ s)
blanchet@33192
   627
blanchet@33192
   628
    fun print_and_check_model genuine bounds
blanchet@33192
   629
            ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
blanchet@33192
   630
             : problem_extension) =
blanchet@33192
   631
      let
blanchet@47752
   632
        val _ =
blanchet@47752
   633
          print_t (fn () =>
blanchet@47752
   634
               "% SZS status " ^
blanchet@47752
   635
               (if genuine then
blanchet@47752
   636
                  if falsify then "CounterSatisfiable" else "Satisfiable"
blanchet@47752
   637
                else
blanchet@61310
   638
                  "GaveUp") ^ "\n" ^
blanchet@47752
   639
               "% SZS output start FiniteModel")
blanchet@33192
   640
        val (reconstructed_model, codatatypes_ok) =
blanchet@41993
   641
          reconstruct_hol_model
blanchet@55889
   642
              {show_types = show_types, show_skolems = show_skolems,
blanchet@41993
   643
               show_consts = show_consts}
blanchet@38170
   644
              scope formats atomss real_frees pseudo_frees free_names sel_names
blanchet@38170
   645
              nonsel_names rel_table bounds
blanchet@35671
   646
        val genuine_means_genuine =
blanchet@35671
   647
          got_all_user_axioms andalso none_true wfs andalso
blanchet@41858
   648
          sound_finitizes andalso total_consts <> SOME true andalso
blanchet@41858
   649
          codatatypes_ok
blanchet@47715
   650
        fun assms_prop () =
blanchet@47715
   651
          Logic.mk_conjunction_list (neg_t :: def_assm_ts @ nondef_assm_ts)
blanchet@33192
   652
      in
blanchet@47752
   653
        (pprint_a (Pretty.chunks
blanchet@35671
   654
             [Pretty.blk (0,
wenzelm@59432
   655
                  (Pretty.text ((if mode = Auto_Try then "Auto " else "") ^
blanchet@43022
   656
                          "Nitpick found a" ^
blanchet@41992
   657
                          (if not genuine then " potentially spurious "
blanchet@35671
   658
                           else if genuine_means_genuine then " "
blanchet@35671
   659
                           else " quasi genuine ") ^ das_wort_model) @
blanchet@35671
   660
                   (case pretties_for_scope scope verbose of
blanchet@35671
   661
                      [] => []
wenzelm@60023
   662
                    | pretties => [Pretty.brk 1, Pretty.str "for", Pretty.brk 1] @ pretties) @
wenzelm@59429
   663
                   [Pretty.str ":", Pretty.fbrk])),
blanchet@35671
   664
              Pretty.indent indent_size reconstructed_model]);
blanchet@47564
   665
         print_t (K "% SZS output end FiniteModel");
blanchet@35671
   666
         if genuine then
blanchet@60310
   667
           (if has_lonely_bool_var orig_t then
blanchet@41048
   668
              print "Hint: Maybe you forgot a colon after the lemma's name?"
blanchet@41048
   669
            else if has_syntactic_sorts orig_t then
blanchet@35671
   670
              print "Hint: Maybe you forgot a type constraint?"
blanchet@35671
   671
            else
blanchet@35671
   672
              ();
blanchet@35671
   673
            if not genuine_means_genuine then
blanchet@35671
   674
              if no_poly_user_axioms then
blanchet@35671
   675
                let
blanchet@35671
   676
                  val options =
blanchet@35671
   677
                    [] |> not got_all_mono_user_axioms
blanchet@35671
   678
                          ? cons ("user_axioms", "\"true\"")
blanchet@35671
   679
                       |> not (none_true wfs)
blanchet@35671
   680
                          ? cons ("wf", "\"smart\" or \"false\"")
blanchet@35671
   681
                       |> not sound_finitizes
blanchet@35671
   682
                          ? cons ("finitize", "\"smart\" or \"false\"")
blanchet@41858
   683
                       |> total_consts = SOME true
blanchet@41858
   684
                          ? cons ("total_consts", "\"smart\" or \"false\"")
blanchet@35671
   685
                       |> not codatatypes_ok
blanchet@35671
   686
                          ? cons ("bisim_depth", "a nonnegative value")
blanchet@35671
   687
                  val ss =
blanchet@35671
   688
                    map (fn (name, value) => quote name ^ " set to " ^ value)
blanchet@35671
   689
                        options
blanchet@35671
   690
                in
blanchet@35671
   691
                  print ("Try again with " ^
blanchet@41872
   692
                         space_implode " " (serial_commas "and" ss) ^
blanchet@35671
   693
                         " to confirm that the " ^ das_wort_model ^
blanchet@63693
   694
                         " is genuine")
blanchet@35671
   695
                end
blanchet@35671
   696
              else
blanchet@35671
   697
                print ("Nitpick is unable to guarantee the authenticity of \
blanchet@35671
   698
                       \the " ^ das_wort_model ^ " in the presence of \
blanchet@63693
   699
                       \polymorphic axioms")
blanchet@35671
   700
            else
blanchet@35671
   701
              ();
blanchet@35671
   702
            NONE)
blanchet@35671
   703
         else
blanchet@35671
   704
           if not genuine then
blanchet@60310
   705
             (Unsynchronized.inc met_potential; NONE)
blanchet@33192
   706
           else
blanchet@35671
   707
             NONE)
blanchet@35671
   708
        |> pair genuine_means_genuine
blanchet@33192
   709
      end
blanchet@35671
   710
    fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
blanchet@35671
   711
                           donno) first_time problems =
blanchet@33192
   712
      let
blanchet@33192
   713
        val max_potential = Int.max (0, max_potential)
blanchet@33192
   714
        val max_genuine = Int.max (0, max_genuine)
blanchet@33192
   715
        fun print_and_check genuine (j, bounds) =
blanchet@33192
   716
          print_and_check_model genuine bounds (snd (nth problems j))
blanchet@33192
   717
        val max_solutions = max_potential + max_genuine
blanchet@36384
   718
                            |> not incremental ? Integer.min 1
blanchet@33192
   719
      in
blanchet@33192
   720
        if max_solutions <= 0 then
blanchet@35671
   721
          (found_really_genuine, 0, 0, donno)
blanchet@33192
   722
        else
blanchet@41793
   723
          case KK.solve_any_problem debug overlord deadline max_threads
blanchet@41793
   724
                                    max_solutions (map fst problems) of
blanchet@49024
   725
            KK.JavaNotFound =>
blanchet@55889
   726
            (print_nt (K java_not_found_message);
blanchet@35696
   727
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@38516
   728
          | KK.JavaTooOld =>
blanchet@55889
   729
            (print_nt (K java_too_old_message);
blanchet@38516
   730
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@35696
   731
          | KK.KodkodiNotInstalled =>
blanchet@55889
   732
            (print_nt (K kodkodi_not_installed_message);
blanchet@35671
   733
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@50487
   734
          | KK.KodkodiTooOld =>
blanchet@55889
   735
            (print_nt (K kodkodi_too_old_message);
blanchet@50487
   736
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@35333
   737
          | KK.Normal ([], unsat_js, s) =>
blanchet@35333
   738
            (update_checked_problems problems unsat_js; show_kodkod_warning s;
blanchet@35671
   739
             (found_really_genuine, max_potential, max_genuine, donno))
blanchet@35333
   740
          | KK.Normal (sat_ps, unsat_js, s) =>
blanchet@33192
   741
            let
blanchet@33192
   742
              val (lib_ps, con_ps) =
blanchet@35185
   743
                List.partition (#unsound o snd o nth problems o fst) sat_ps
blanchet@33192
   744
            in
blanchet@33192
   745
              update_checked_problems problems (unsat_js @ map fst lib_ps);
blanchet@35333
   746
              show_kodkod_warning s;
blanchet@33192
   747
              if null con_ps then
blanchet@33192
   748
                let
blanchet@35671
   749
                  val genuine_codes =
blanchet@35671
   750
                    lib_ps |> take max_potential
blanchet@35671
   751
                           |> map (print_and_check false)
blanchet@35671
   752
                           |> filter (curry (op =) (SOME true) o snd)
blanchet@35671
   753
                  val found_really_genuine =
blanchet@35671
   754
                    found_really_genuine orelse exists fst genuine_codes
blanchet@35671
   755
                  val num_genuine = length genuine_codes
blanchet@33192
   756
                  val max_genuine = max_genuine - num_genuine
blanchet@33192
   757
                  val max_potential = max_potential
blanchet@33192
   758
                                      - (length lib_ps - num_genuine)
blanchet@33192
   759
                in
blanchet@33192
   760
                  if max_genuine <= 0 then
blanchet@35671
   761
                    (found_really_genuine, 0, 0, donno)
blanchet@33192
   762
                  else
blanchet@33192
   763
                    let
blanchet@35185
   764
                      (* "co_js" is the list of sound problems whose unsound
blanchet@35185
   765
                         pendants couldn't be satisfied and hence that most
blanchet@35185
   766
                         probably can't be satisfied themselves. *)
blanchet@33192
   767
                      val co_js =
blanchet@33192
   768
                        map (fn j => j - 1) unsat_js
blanchet@33192
   769
                        |> filter (fn j =>
blanchet@33192
   770
                                      j >= 0 andalso
blanchet@33192
   771
                                      scopes_equivalent
blanchet@35814
   772
                                          (#scope (snd (nth problems j)),
blanchet@35814
   773
                                           #scope (snd (nth problems (j + 1)))))
blanchet@33192
   774
                      val bye_js = sort_distinct int_ord (map fst sat_ps @
blanchet@33192
   775
                                                          unsat_js @ co_js)
blanchet@33192
   776
                      val problems =
blanchet@33192
   777
                        problems |> filter_out_indices bye_js
blanchet@33192
   778
                                 |> max_potential <= 0
blanchet@35185
   779
                                    ? filter_out (#unsound o snd)
blanchet@33192
   780
                    in
blanchet@35671
   781
                      solve_any_problem (found_really_genuine, max_potential,
blanchet@35671
   782
                                         max_genuine, donno) false problems
blanchet@33192
   783
                    end
blanchet@33192
   784
                end
blanchet@33192
   785
              else
blanchet@33192
   786
                let
blanchet@35671
   787
                  val genuine_codes =
blanchet@35671
   788
                    con_ps |> take max_genuine
blanchet@35671
   789
                           |> map (print_and_check true)
blanchet@35671
   790
                  val max_genuine = max_genuine - length genuine_codes
blanchet@35671
   791
                  val found_really_genuine =
blanchet@35671
   792
                    found_really_genuine orelse exists fst genuine_codes
blanchet@33192
   793
                in
blanchet@33192
   794
                  if max_genuine <= 0 orelse not first_time then
blanchet@35671
   795
                    (found_really_genuine, 0, max_genuine, donno)
blanchet@33192
   796
                  else
blanchet@33192
   797
                    let
blanchet@33192
   798
                      val bye_js = sort_distinct int_ord
blanchet@33192
   799
                                                 (map fst sat_ps @ unsat_js)
blanchet@33192
   800
                      val problems =
blanchet@33192
   801
                        problems |> filter_out_indices bye_js
blanchet@35185
   802
                                 |> filter_out (#unsound o snd)
blanchet@35671
   803
                    in
blanchet@35671
   804
                      solve_any_problem (found_really_genuine, 0, max_genuine,
blanchet@35671
   805
                                         donno) false problems
blanchet@35671
   806
                    end
blanchet@33192
   807
                end
blanchet@33192
   808
            end
blanchet@34126
   809
          | KK.TimedOut unsat_js =>
wenzelm@62519
   810
            (update_checked_problems problems unsat_js; raise Timeout.TIMEOUT Time.zeroTime)
blanchet@34126
   811
          | KK.Error (s, unsat_js) =>
blanchet@33192
   812
            (update_checked_problems problems unsat_js;
blanchet@63693
   813
             print_v (K ("Kodkod error: " ^ s));
blanchet@35671
   814
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@33192
   815
      end
blanchet@33192
   816
blanchet@35671
   817
    fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
blanchet@35671
   818
                              donno) =
blanchet@33192
   819
      let
blanchet@33192
   820
        val _ =
blanchet@33192
   821
          if null scopes then
blanchet@63693
   822
            print_nt (K "The scope specification is inconsistent")
blanchet@33192
   823
          else if verbose then
blanchet@47560
   824
            pprint_nt (fn () => Pretty.chunks
blanchet@33192
   825
                [Pretty.blk (0,
wenzelm@59432
   826
                     Pretty.text ((if n > 1 then
blanchet@33192
   827
                               "Batch " ^ string_of_int (j + 1) ^ " of " ^
blanchet@33192
   828
                               signed_string_of_int n ^ ": "
blanchet@33192
   829
                             else
blanchet@33192
   830
                               "") ^
blanchet@33192
   831
                            "Trying " ^ string_of_int (length scopes) ^
blanchet@33192
   832
                            " scope" ^ plural_s_for_list scopes ^ ":")),
blanchet@33192
   833
                 Pretty.indent indent_size
blanchet@33192
   834
                     (Pretty.chunks (map2
blanchet@33192
   835
                          (fn j => fn scope =>
blanchet@33192
   836
                              Pretty.block (
blanchet@33192
   837
                                  (case pretties_for_scope scope true of
blanchet@33192
   838
                                     [] => [Pretty.str "Empty"]
blanchet@63693
   839
                                   | pretties => pretties)))
blanchet@33192
   840
                          (length scopes downto 1) scopes))])
blanchet@33192
   841
          else
blanchet@33192
   842
            ()
blanchet@35280
   843
        fun add_problem_for_scope (scope, unsound) (problems, donno) =
blanchet@33192
   844
          (check_deadline ();
blanchet@35185
   845
           case problem_for_scope unsound scope of
blanchet@33192
   846
             SOME problem =>
blanchet@33192
   847
             (problems
blanchet@33192
   848
              |> (null problems orelse
blanchet@35814
   849
                  not (KK.problems_equivalent (fst problem, fst (hd problems))))
blanchet@33192
   850
                  ? cons problem, donno)
blanchet@33192
   851
           | NONE => (problems, donno + 1))
blanchet@33192
   852
        val (problems, donno) =
blanchet@33192
   853
          fold add_problem_for_scope
blanchet@33192
   854
               (map_product pair scopes
blanchet@33192
   855
                    ((if max_genuine > 0 then [false] else []) @
blanchet@33192
   856
                     (if max_potential > 0 then [true] else [])))
blanchet@33192
   857
               ([], donno)
blanchet@33192
   858
        val _ = Unsynchronized.change generated_problems (append problems)
blanchet@33192
   859
        val _ = Unsynchronized.change generated_scopes (append scopes)
blanchet@35185
   860
        val _ =
blanchet@35185
   861
          if j + 1 = n then
blanchet@35185
   862
            let
blanchet@35185
   863
              val (unsound_problems, sound_problems) =
blanchet@35185
   864
                List.partition (#unsound o snd) (!generated_problems)
blanchet@35185
   865
            in
blanchet@35185
   866
              if not (null sound_problems) andalso
blanchet@35185
   867
                 forall (KK.is_problem_trivially_false o fst)
blanchet@35185
   868
                        sound_problems then
blanchet@47560
   869
                print_nt (fn () =>
blanchet@44395
   870
                    "Warning: The conjecture " ^
blanchet@44395
   871
                    (if falsify then "either trivially holds"
blanchet@44395
   872
                     else "is either trivially unsatisfiable") ^
blanchet@44395
   873
                    " for the given scopes or lies outside Nitpick's supported \
blanchet@63693
   874
                    \fragment" ^
blanchet@35185
   875
                    (if exists (not o KK.is_problem_trivially_false o fst)
blanchet@35185
   876
                               unsound_problems then
blanchet@63693
   877
                       "; only potentially spurious " ^ das_wort_model ^
blanchet@63693
   878
                       "s may be found"
blanchet@35185
   879
                     else
blanchet@35185
   880
                       ""))
blanchet@35185
   881
              else
blanchet@35185
   882
                ()
blanchet@35185
   883
            end
blanchet@35185
   884
          else
blanchet@35185
   885
            ()
blanchet@33192
   886
      in
blanchet@35671
   887
        solve_any_problem (found_really_genuine, max_potential, max_genuine,
blanchet@35671
   888
                           donno) true (rev problems)
blanchet@33192
   889
      end
blanchet@33192
   890
blanchet@33192
   891
    fun scope_count (problems : rich_problem list) scope =
blanchet@35814
   892
      length (filter (curry scopes_equivalent scope o #scope o snd) problems)
blanchet@33192
   893
    fun excipit did_so_and_so =
blanchet@33192
   894
      let
blanchet@33192
   895
        val do_filter =
blanchet@35185
   896
          if !met_potential = max_potential then filter_out (#unsound o snd)
blanchet@33192
   897
          else I
blanchet@33192
   898
        val total = length (!scopes)
blanchet@33192
   899
        val unsat =
blanchet@33192
   900
          fold (fn scope =>
blanchet@33192
   901
                   case scope_count (do_filter (!generated_problems)) scope of
blanchet@33192
   902
                     0 => I
blanchet@33192
   903
                   | n =>
blanchet@33556
   904
                     scope_count (do_filter (these (!checked_problems)))
blanchet@33556
   905
                                 scope = n
blanchet@33556
   906
                     ? Integer.add 1) (!generated_scopes) 0
blanchet@33192
   907
      in
blanchet@61365
   908
        (if mode = TPTP then "% SZS status GaveUp\n" else "") ^
blanchet@33192
   909
        "Nitpick " ^ did_so_and_so ^
blanchet@33192
   910
        (if is_some (!checked_problems) andalso total > 0 then
blanchet@39361
   911
           " " ^ string_of_int unsat ^ " of " ^ string_of_int total ^ " scope"
blanchet@39361
   912
           ^ plural_s total
blanchet@33192
   913
         else
blanchet@63693
   914
           "")
blanchet@33192
   915
      end
blanchet@33192
   916
blanchet@37704
   917
    val (skipped, the_scopes) =
blanchet@37704
   918
      all_scopes hol_ctxt binarize cards_assigns maxes_assigns iters_assigns
blanchet@37704
   919
                 bitss bisim_depths mono_Ts nonmono_Ts deep_dataTs
blanchet@37704
   920
                 finitizable_dataTs
blanchet@37704
   921
    val _ = if skipped > 0 then
blanchet@62319
   922
              print_nt (fn () => "Skipping " ^ string_of_int skipped ^
blanchet@62319
   923
                                 " scope" ^ plural_s skipped ^
blanchet@47560
   924
                                 ". (Consider using \"mono\" or \
blanchet@47560
   925
                                 \\"merge_type_vars\" to prevent this.)")
blanchet@37704
   926
            else
blanchet@37704
   927
              ()
blanchet@37704
   928
    val _ = scopes := the_scopes
blanchet@37704
   929
blanchet@35671
   930
    fun run_batches _ _ []
blanchet@35671
   931
                    (found_really_genuine, max_potential, max_genuine, donno) =
blanchet@33192
   932
        if donno > 0 andalso max_genuine > 0 then
blanchet@47560
   933
          (print_nt (fn () => excipit "checked"); unknownN)
blanchet@33192
   934
        else if max_genuine = original_max_genuine then
blanchet@33192
   935
          if max_potential = original_max_potential then
blanchet@61365
   936
            (print_t (K "% SZS status GaveUp");
blanchet@63693
   937
             print_nt (fn () => "Nitpick found no " ^ das_wort_model);
blanchet@55888
   938
             if skipped > 0 then unknownN else noneN)
blanchet@33192
   939
          else
blanchet@47560
   940
            (print_nt (fn () =>
blanchet@38123
   941
                 excipit ("could not find a" ^
blanchet@38123
   942
                          (if max_genuine = 1 then
blanchet@63693
   943
                             " better " ^ das_wort_model
blanchet@38123
   944
                           else
blanchet@63693
   945
                             "ny better " ^ das_wort_model ^ "s") ^
blanchet@63693
   946
                          "\nIt checked"));
blanchet@43020
   947
             potentialN)
blanchet@35671
   948
        else if found_really_genuine then
blanchet@43020
   949
          genuineN
blanchet@33192
   950
        else
blanchet@43020
   951
          quasi_genuineN
blanchet@33192
   952
      | run_batches j n (batch :: batches) z =
blanchet@35671
   953
        let val (z as (_, _, max_genuine, _)) = run_batch j n batch z in
blanchet@33192
   954
          run_batches (j + 1) n (if max_genuine > 0 then batches else []) z
blanchet@33192
   955
        end
blanchet@33192
   956
blanchet@48323
   957
    val batches = chunk_list batch_size (!scopes)
blanchet@33192
   958
    val outcome_code =
blanchet@40411
   959
      run_batches 0 (length batches) batches
blanchet@40411
   960
                  (false, max_potential, max_genuine, 0)
wenzelm@62519
   961
      handle Timeout.TIMEOUT _ =>
blanchet@47560
   962
             (print_nt (fn () => excipit "ran out of time after checking");
blanchet@43020
   963
              if !met_potential > 0 then potentialN else unknownN)
blanchet@40341
   964
    val _ = print_v (fn () =>
blanchet@63693
   965
                "Total time: " ^ string_of_time (Timer.checkRealTimer timer))
blanchet@53815
   966
    val _ = spying spy (fn () => (state, i, "outcome: " ^ outcome_code))
wenzelm@58892
   967
  in (outcome_code, Queue.content (Synchronized.value outcome)) end
blanchet@33192
   968
blanchet@41051
   969
(* Give the inner timeout a chance. *)
blanchet@41772
   970
val timeout_bonus = seconds 1.0
blanchet@41051
   971
blanchet@55539
   972
fun pick_nits_in_term state (params as {timeout, expect, ...}) mode i n step
blanchet@55539
   973
                      subst def_assm_ts nondef_assm_ts orig_t =
blanchet@47670
   974
  let
wenzelm@58843
   975
    val print_nt = if is_mode_nt mode then writeln else K ()
wenzelm@58843
   976
    val print_t = if mode = TPTP then writeln else K ()
blanchet@47670
   977
  in
blanchet@37213
   978
    if getenv "KODKODI" = "" then
blanchet@37497
   979
      (* The "expect" argument is deliberately ignored if Kodkodi is missing so
blanchet@37497
   980
         that the "Nitpick_Examples" can be processed on any machine. *)
blanchet@55889
   981
      (print_nt (Pretty.string_of (plazy (K kodkodi_not_installed_message)));
wenzelm@58892
   982
       ("no_kodkodi", []))
blanchet@37213
   983
    else
blanchet@37213
   984
      let
wenzelm@58892
   985
        val unknown_outcome = (unknownN, [])
wenzelm@62826
   986
        val deadline = Time.now () + timeout
blanchet@37213
   987
        val outcome as (outcome_code, _) =
wenzelm@62826
   988
          Timeout.apply (timeout + timeout_bonus)
blanchet@43022
   989
              (pick_them_nits_in_term deadline state params mode i n step subst
blanchet@47715
   990
                                      def_assm_ts nondef_assm_ts) orig_t
blanchet@37213
   991
          handle TOO_LARGE (_, details) =>
blanchet@61365
   992
                 (print_t "% SZS status GaveUp";
blanchet@63693
   993
                  print_nt ("Limit reached: " ^ details); unknown_outcome)
blanchet@37213
   994
               | TOO_SMALL (_, details) =>
blanchet@61365
   995
                 (print_t "% SZS status GaveUp";
blanchet@63693
   996
                  print_nt ("Limit reached: " ^ details); unknown_outcome)
blanchet@37213
   997
               | Kodkod.SYNTAX (_, details) =>
blanchet@61365
   998
                 (print_t "% SZS status GaveUp";
blanchet@63693
   999
                  print_nt ("Malformed Kodkodi output: " ^ details);
blanchet@37213
  1000
                  unknown_outcome)
wenzelm@62519
  1001
               | Timeout.TIMEOUT _ =>
blanchet@47670
  1002
                 (print_t "% SZS status TimedOut";
blanchet@63693
  1003
                  print_nt "Nitpick ran out of time"; unknown_outcome)
blanchet@37213
  1004
      in
blanchet@37213
  1005
        if expect = "" orelse outcome_code = expect then outcome
blanchet@63693
  1006
        else error ("Unexpected outcome: " ^ quote outcome_code)
blanchet@37213
  1007
      end
blanchet@37213
  1008
  end
blanchet@33192
  1009
wenzelm@42486
  1010
fun is_fixed_equation ctxt
wenzelm@56245
  1011
                      (Const (@{const_name Pure.eq}, _) $ Free (s, _) $ Const _) =
wenzelm@42486
  1012
    Variable.is_fixed ctxt s
blanchet@35335
  1013
  | is_fixed_equation _ _ = false
blanchet@55889
  1014
blanchet@35335
  1015
fun extract_fixed_frees ctxt (assms, t) =
blanchet@35335
  1016
  let
blanchet@35335
  1017
    val (subst, other_assms) =
wenzelm@42486
  1018
      List.partition (is_fixed_equation ctxt) assms
blanchet@35335
  1019
      |>> map Logic.dest_equals
blanchet@35335
  1020
  in (subst, other_assms, subst_atomic subst t) end
blanchet@35335
  1021
blanchet@43022
  1022
fun pick_nits_in_subgoal state params mode i step =
blanchet@33192
  1023
  let
blanchet@33192
  1024
    val ctxt = Proof.context_of state
wenzelm@59582
  1025
    val t = state |> Proof.raw_goal |> #goal |> Thm.prop_of
blanchet@33192
  1026
  in
blanchet@34982
  1027
    case Logic.count_prems t of
wenzelm@58892
  1028
      0 => (writeln "No subgoal!"; (noneN, []))
blanchet@34982
  1029
    | n =>
blanchet@33192
  1030
      let
blanchet@36406
  1031
        val t = Logic.goal_params t i |> fst
wenzelm@59582
  1032
        val assms = map Thm.term_of (Assumption.all_assms_of ctxt)
blanchet@35335
  1033
        val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
blanchet@47715
  1034
      in pick_nits_in_term state params mode i n step subst [] assms t end
blanchet@33192
  1035
  end
blanchet@33192
  1036
blanchet@33192
  1037
end;