src/HOL/Tools/Nitpick/nitpick.ML
author blanchet
Mon Feb 15 12:47:52 2016 +0100 (2016-02-15 ago)
changeset 62319 6b01bff94d87
parent 61365 1190beb20762
child 62519 a564458f94db
permissions -rw-r--r--
rephrased message
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@33192
   172
                                   |> Syntax.pretty_term ctxt,
blanchet@33192
   173
                                 Pretty.str (if j = 1 then "." else ";")])
blanchet@33192
   174
               (length ts downto 1) ts))]
blanchet@33192
   175
blanchet@49024
   176
val isabelle_wrong_message =
blanchet@49024
   177
  "Something appears to be wrong with your Isabelle installation."
blanchet@55889
   178
val java_not_found_message =
blanchet@49024
   179
  "Java could not be launched. " ^ isabelle_wrong_message
blanchet@55889
   180
val java_too_old_message =
blanchet@49024
   181
  "The Java version is too old. " ^ isabelle_wrong_message
blanchet@55889
   182
val kodkodi_not_installed_message =
blanchet@50830
   183
  "Nitpick requires the external Java program Kodkodi."
blanchet@55889
   184
val kodkodi_too_old_message = "The installed Kodkodi version is too old."
blanchet@55889
   185
blanchet@35185
   186
val max_unsound_delay_ms = 200
blanchet@35185
   187
val max_unsound_delay_percent = 2
blanchet@33192
   188
blanchet@54816
   189
fun unsound_delay_for_timeout timeout =
blanchet@54816
   190
  Int.max (0, Int.min (max_unsound_delay_ms,
blanchet@54816
   191
                       Time.toMilliseconds timeout
blanchet@54816
   192
                       * max_unsound_delay_percent div 100))
blanchet@33192
   193
blanchet@34123
   194
fun none_true assigns = forall (not_equal (SOME true) o snd) assigns
blanchet@33192
   195
blanchet@41048
   196
fun has_lonely_bool_var (@{const Pure.conjunction}
blanchet@41048
   197
                         $ (@{const Trueprop} $ Free _) $ _) = true
blanchet@41048
   198
  | has_lonely_bool_var _ = false
blanchet@41048
   199
blanchet@34038
   200
val syntactic_sorts =
haftmann@38857
   201
  @{sort "{default,zero,one,plus,minus,uminus,times,inverse,abs,sgn,ord,equal}"} @
huffman@47108
   202
  @{sort numeral}
blanchet@55889
   203
blanchet@34038
   204
fun has_tfree_syntactic_sort (TFree (_, S as _ :: _)) =
blanchet@34038
   205
    subset (op =) (S, syntactic_sorts)
blanchet@34038
   206
  | has_tfree_syntactic_sort _ = false
blanchet@34038
   207
val has_syntactic_sorts = exists_type (exists_subtype has_tfree_syntactic_sort)
blanchet@33192
   208
wenzelm@59432
   209
fun plazy f = Pretty.para (f ())
blanchet@33568
   210
blanchet@43022
   211
fun pick_them_nits_in_term deadline state (params : params) mode i n step
blanchet@47715
   212
                           subst def_assm_ts nondef_assm_ts orig_t =
blanchet@33192
   213
  let
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 () =
blanchet@54816
   251
      if Time.compare (Time.now (), deadline) <> LESS then
blanchet@54816
   252
        raise TimeLimit.TimeOut
blanchet@54816
   253
      else
blanchet@54816
   254
        ()
blanchet@33192
   255
blanchet@47715
   256
    val (def_assm_ts, nondef_assm_ts) =
blanchet@47715
   257
      if assms orelse mode <> Normal then (def_assm_ts, nondef_assm_ts)
blanchet@47715
   258
      else ([], [])
blanchet@34982
   259
    val _ =
blanchet@34982
   260
      if step = 0 then
blanchet@47560
   261
        print_nt (fn () => "Nitpicking formula...")
blanchet@34982
   262
      else
blanchet@47560
   263
        pprint_nt (fn () => Pretty.chunks (
blanchet@34982
   264
            pretties_for_formulas ctxt ("Nitpicking " ^
blanchet@34982
   265
                (if i <> 1 orelse n <> 1 then
blanchet@34982
   266
                   "subgoal " ^ string_of_int i ^ " of " ^ string_of_int n
blanchet@34982
   267
                 else
blanchet@47715
   268
                   "goal")) [Logic.list_implies (nondef_assm_ts, orig_t)]))
blanchet@53815
   269
    val _ = spying spy (fn () => (state, i, "starting " ^ @{make_string} mode ^ " mode"))
blanchet@41278
   270
    val _ = print_v (enclose "Timestamp: " "." o Date.fmt "%H:%M:%S"
blanchet@41278
   271
                     o Date.fromTimeLocal o Time.now)
blanchet@33192
   272
    val neg_t = if falsify then Logic.mk_implies (orig_t, @{prop False})
blanchet@33192
   273
                else orig_t
blanchet@47715
   274
    val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
blanchet@38169
   275
    val tfree_table =
blanchet@41869
   276
      if merge_type_vars then merged_type_var_table_for_terms thy conj_ts
blanchet@41869
   277
      else []
blanchet@41869
   278
    val merge_tfrees = merge_type_vars_in_term thy merge_type_vars tfree_table
blanchet@41869
   279
    val neg_t = neg_t |> merge_tfrees
blanchet@47715
   280
    val def_assm_ts = def_assm_ts |> map merge_tfrees
blanchet@47715
   281
    val nondef_assm_ts = nondef_assm_ts |> map merge_tfrees
blanchet@41869
   282
    val evals = evals |> map merge_tfrees
blanchet@41876
   283
    val needs = needs |> Option.map (map merge_tfrees)
blanchet@47715
   284
    val conj_ts = neg_t :: def_assm_ts @ nondef_assm_ts @ evals @ these needs
blanchet@33192
   285
    val original_max_potential = max_potential
blanchet@33192
   286
    val original_max_genuine = max_genuine
blanchet@33192
   287
    val max_bisim_depth = fold Integer.max bisim_depths ~1
blanchet@55888
   288
    val case_names = case_const_names ctxt
blanchet@47715
   289
    val defs = def_assm_ts @ all_defs_of thy subst
blanchet@42415
   290
    val nondefs = all_nondefs_of ctxt subst
blanchet@41791
   291
    val def_tables = const_def_tables ctxt subst defs
blanchet@42415
   292
    val nondef_table = const_nondef_table nondefs
blanchet@35335
   293
    val simp_table = Unsynchronized.ref (const_simp_table ctxt subst)
blanchet@35335
   294
    val psimp_table = const_psimp_table ctxt subst
blanchet@35807
   295
    val choice_spec_table = const_choice_spec_table ctxt subst
blanchet@42415
   296
    val nondefs =
wenzelm@59970
   297
      nondefs |> filter_out (is_choice_spec_axiom ctxt choice_spec_table)
blanchet@41791
   298
    val intro_table = inductive_intro_table ctxt subst def_tables
blanchet@33192
   299
    val ground_thm_table = ground_theorem_table thy
blanchet@38240
   300
    val ersatz_table = ersatz_table ctxt
blanchet@41007
   301
    val hol_ctxt as {wf_cache, ...} =
blanchet@33192
   302
      {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
blanchet@55888
   303
       wfs = wfs, user_axioms = user_axioms, debug = debug, whacks = whacks,
blanchet@55888
   304
       binary_ints = binary_ints, destroy_constrs = destroy_constrs,
blanchet@55888
   305
       specialize = specialize, star_linear_preds = star_linear_preds,
blanchet@55888
   306
       total_consts = total_consts, needs = needs, tac_timeout = tac_timeout,
blanchet@55888
   307
       evals = evals, case_names = case_names, def_tables = def_tables,
blanchet@42415
   308
       nondef_table = nondef_table, nondefs = nondefs, simp_table = simp_table,
blanchet@42415
   309
       psimp_table = psimp_table, choice_spec_table = choice_spec_table,
blanchet@42415
   310
       intro_table = intro_table, ground_thm_table = ground_thm_table,
blanchet@42415
   311
       ersatz_table = ersatz_table, skolems = Unsynchronized.ref [],
blanchet@42415
   312
       special_funs = Unsynchronized.ref [],
blanchet@33580
   313
       unrolled_preds = Unsynchronized.ref [], wf_cache = Unsynchronized.ref [],
blanchet@33580
   314
       constr_cache = Unsynchronized.ref []}
blanchet@41789
   315
    val pseudo_frees = []
blanchet@41869
   316
    val real_frees = fold Term.add_frees conj_ts []
blanchet@41869
   317
    val _ = null (fold Term.add_tvars conj_ts []) orelse
blanchet@41869
   318
            error "Nitpick cannot handle goals with schematic type variables."
blanchet@41875
   319
    val (nondef_ts, def_ts, need_ts, got_all_mono_user_axioms,
blanchet@41803
   320
         no_poly_user_axioms, binarize) =
blanchet@47715
   321
      preprocess_formulas hol_ctxt nondef_assm_ts neg_t
blanchet@33192
   322
    val got_all_user_axioms =
blanchet@33192
   323
      got_all_mono_user_axioms andalso no_poly_user_axioms
blanchet@33192
   324
blanchet@33192
   325
    fun print_wf (x, (gfp, wf)) =
blanchet@47560
   326
      pprint_nt (fn () => Pretty.blk (0,
wenzelm@60023
   327
          Pretty.text ("The " ^ (if gfp then "co" else "") ^ "inductive predicate") @
wenzelm@60023
   328
          [Pretty.brk 1, Pretty.quote (Syntax.pretty_term ctxt (Const x)), Pretty.brk 1] @
wenzelm@59432
   329
          Pretty.text (if wf then
wenzelm@60023
   330
                   "was proved well-founded. Nitpick can compute it \
blanchet@33192
   331
                   \efficiently."
blanchet@33192
   332
                 else
wenzelm@60023
   333
                   "could not be proved well-founded. Nitpick might need to \
blanchet@33192
   334
                   \unroll it.")))
blanchet@33192
   335
    val _ = if verbose then List.app print_wf (!wf_cache) else ()
blanchet@38171
   336
    val das_wort_formula = if falsify then "Negated conjecture" else "Formula"
blanchet@33192
   337
    val _ =
blanchet@35386
   338
      pprint_d (fn () => Pretty.chunks
blanchet@38171
   339
          (pretties_for_formulas ctxt das_wort_formula [hd nondef_ts] @
blanchet@35386
   340
           pretties_for_formulas ctxt "Relevant definitional axiom" def_ts @
blanchet@35386
   341
           pretties_for_formulas ctxt "Relevant nondefinitional axiom"
blanchet@35386
   342
                                 (tl nondef_ts)))
blanchet@35386
   343
    val _ = List.app (ignore o Term.type_of) (nondef_ts @ def_ts)
blanchet@33192
   344
            handle TYPE (_, Ts, ts) =>
blanchet@33192
   345
                   raise TYPE ("Nitpick.pick_them_nits_in_term", Ts, ts)
blanchet@33192
   346
blanchet@41801
   347
    val nondef_us = nondef_ts |> map (nut_from_term hol_ctxt Eq)
blanchet@41801
   348
    val def_us = def_ts |> map (nut_from_term hol_ctxt DefEq)
blanchet@41875
   349
    val need_us = need_ts |> map (nut_from_term hol_ctxt Eq)
blanchet@33558
   350
    val (free_names, const_names) =
blanchet@41888
   351
      fold add_free_and_const_names (nondef_us @ def_us @ need_us) ([], [])
blanchet@33558
   352
    val (sel_names, nonsel_names) =
blanchet@33558
   353
      List.partition (is_sel o nickname_of) const_names
blanchet@46114
   354
    val sound_finitizes = none_true finitizes
blanchet@33558
   355
(*
blanchet@41888
   356
    val _ =
blanchet@41888
   357
      List.app (print_g o string_for_nut ctxt) (nondef_us @ def_us @ need_us)
blanchet@33558
   358
*)
blanchet@33558
   359
blanchet@34121
   360
    val unique_scope = forall (curry (op =) 1 o length o snd) cards_assigns
blanchet@35385
   361
    fun monotonicity_message Ts extra =
wenzelm@58928
   362
      let val pretties = map (pretty_maybe_quote keywords o pretty_for_type ctxt) Ts in
blanchet@38188
   363
        Pretty.blk (0,
wenzelm@60023
   364
          Pretty.text ("The type" ^ plural_s_for_list pretties) @ [Pretty.brk 1] @
wenzelm@60023
   365
          pretty_serial_commas "and" pretties @ [Pretty.brk 1] @
wenzelm@60023
   366
          Pretty.text (
blanchet@42959
   367
                 (if none_true monos then
blanchet@42959
   368
                    "passed the monotonicity test"
blanchet@42959
   369
                  else
blanchet@42959
   370
                    (if length pretties = 1 then "is" else "are") ^
blanchet@42959
   371
                    " considered monotonic") ^
blanchet@42959
   372
                 ". " ^ extra))
blanchet@35385
   373
      end
blanchet@35665
   374
    fun is_type_fundamentally_monotonic T =
blanchet@55890
   375
      (is_data_type ctxt T andalso not (is_quot_type ctxt T) andalso
blanchet@37256
   376
       (not (is_pure_typedef ctxt T) orelse is_univ_typedef ctxt T)) orelse
blanchet@38240
   377
      is_number_type ctxt T orelse is_bit_type T
blanchet@35385
   378
    fun is_type_actually_monotonic T =
blanchet@54816
   379
      TimeLimit.timeLimit tac_timeout (formulas_monotonic hol_ctxt binarize T)
blanchet@54816
   380
                          (nondef_ts, def_ts)
blanchet@47716
   381
      handle TimeLimit.TimeOut => false
blanchet@35665
   382
    fun is_type_kind_of_monotonic T =
blanchet@35665
   383
      case triple_lookup (type_match thy) monos T of
blanchet@35665
   384
        SOME (SOME false) => false
blanchet@35665
   385
      | _ => is_type_actually_monotonic T
blanchet@34936
   386
    fun is_type_monotonic T =
blanchet@33192
   387
      unique_scope orelse
blanchet@33192
   388
      case triple_lookup (type_match thy) monos T of
blanchet@33192
   389
        SOME (SOME b) => b
blanchet@35665
   390
      | _ => is_type_fundamentally_monotonic T orelse
blanchet@35665
   391
             is_type_actually_monotonic T
blanchet@55890
   392
    fun is_deep_data_type_finitizable T =
blanchet@41793
   393
      triple_lookup (type_match thy) finitizes T = SOME (SOME true)
blanchet@55890
   394
    fun is_shallow_data_type_finitizable (T as Type (@{type_name fun_box}, _)) =
blanchet@35665
   395
        is_type_kind_of_monotonic T
blanchet@55890
   396
      | is_shallow_data_type_finitizable T =
blanchet@35665
   397
        case triple_lookup (type_match thy) finitizes T of
blanchet@35665
   398
          SOME (SOME b) => b
blanchet@35665
   399
        | _ => is_type_kind_of_monotonic T
blanchet@55890
   400
    fun is_data_type_deep T =
blanchet@55888
   401
      T = @{typ unit} orelse T = nat_T orelse is_word_type T orelse
blanchet@35385
   402
      exists (curry (op =) T o domain_type o type_of) sel_names
blanchet@35386
   403
    val all_Ts = ground_types_in_terms hol_ctxt binarize (nondef_ts @ def_ts)
wenzelm@35408
   404
                 |> sort Term_Ord.typ_ord
blanchet@38214
   405
    val _ =
blanchet@38214
   406
      if verbose andalso binary_ints = SOME true andalso
blanchet@38214
   407
         exists (member (op =) [nat_T, int_T]) all_Ts then
blanchet@38214
   408
        print_v (K "The option \"binary_ints\" will be ignored because of the \
blanchet@38214
   409
                   \presence of rationals, reals, \"Suc\", \"gcd\", or \"lcm\" \
blanchet@55888
   410
                   \in the problem.")
blanchet@38214
   411
      else
blanchet@38214
   412
        ()
blanchet@34982
   413
    val (mono_Ts, nonmono_Ts) = List.partition is_type_monotonic all_Ts
blanchet@33192
   414
    val _ =
blanchet@34936
   415
      if verbose andalso not unique_scope then
blanchet@35665
   416
        case filter_out is_type_fundamentally_monotonic mono_Ts of
blanchet@34936
   417
          [] => ()
blanchet@34936
   418
        | interesting_mono_Ts =>
blanchet@38188
   419
          pprint_v (K (monotonicity_message interesting_mono_Ts
blanchet@38188
   420
                          "Nitpick might be able to skip some scopes."))
blanchet@33192
   421
      else
blanchet@33192
   422
        ()
blanchet@35385
   423
    val (deep_dataTs, shallow_dataTs) =
blanchet@55890
   424
      all_Ts |> filter (is_data_type ctxt)
blanchet@55890
   425
             |> List.partition is_data_type_deep
blanchet@35385
   426
    val finitizable_dataTs =
blanchet@41793
   427
      (deep_dataTs |> filter_out (is_finite_type hol_ctxt)
blanchet@55890
   428
                   |> filter is_deep_data_type_finitizable) @
blanchet@41793
   429
      (shallow_dataTs |> filter_out (is_finite_type hol_ctxt)
blanchet@55890
   430
                      |> filter is_shallow_data_type_finitizable)
blanchet@35385
   431
    val _ =
blanchet@35385
   432
      if verbose andalso not (null finitizable_dataTs) then
blanchet@38188
   433
        pprint_v (K (monotonicity_message finitizable_dataTs
blanchet@38188
   434
                         "Nitpick can use a more precise finite encoding."))
blanchet@35385
   435
      else
blanchet@35385
   436
        ()
blanchet@33192
   437
(*
blanchet@36128
   438
    val _ = print_g "Monotonic types:"
blanchet@36128
   439
    val _ = List.app (print_g o string_for_type ctxt) mono_Ts
blanchet@36128
   440
    val _ = print_g "Nonmonotonic types:"
blanchet@36128
   441
    val _ = List.app (print_g o string_for_type ctxt) nonmono_Ts
blanchet@33192
   442
*)
blanchet@33192
   443
blanchet@36384
   444
    val incremental = Int.max (max_potential, max_genuine) >= 2
blanchet@36384
   445
    val actual_sat_solver =
blanchet@33192
   446
      if sat_solver <> "smart" then
blanchet@36384
   447
        if incremental andalso
blanchet@34936
   448
           not (member (op =) (Kodkod_SAT.configured_sat_solvers true)
blanchet@35333
   449
                       sat_solver) then
blanchet@47560
   450
          (print_nt (K ("An incremental SAT solver is required: \"SAT4J\" will \
blanchet@47560
   451
                        \be used instead of " ^ quote sat_solver ^ "."));
blanchet@33192
   452
           "SAT4J")
blanchet@33192
   453
        else
blanchet@33192
   454
          sat_solver
blanchet@33192
   455
      else
blanchet@36384
   456
        Kodkod_SAT.smart_sat_solver_name incremental
blanchet@33192
   457
    val _ =
blanchet@33192
   458
      if sat_solver = "smart" then
blanchet@36384
   459
        print_v (fn () =>
blanchet@36384
   460
            "Using SAT solver " ^ quote actual_sat_solver ^ ". The following" ^
blanchet@36384
   461
            (if incremental then " incremental " else " ") ^
blanchet@36384
   462
            "solvers are configured: " ^
blanchet@36384
   463
            commas_quote (Kodkod_SAT.configured_sat_solvers incremental) ^ ".")
blanchet@33192
   464
      else
blanchet@33192
   465
        ()
blanchet@33192
   466
blanchet@33192
   467
    val too_big_scopes = Unsynchronized.ref []
blanchet@33192
   468
blanchet@35185
   469
    fun problem_for_scope unsound
blanchet@55890
   470
            (scope as {card_assigns, bits, bisim_depth, data_types, ofs, ...}) =
blanchet@33192
   471
      let
blanchet@33192
   472
        val _ = not (exists (fn other => scope_less_eq other scope)
blanchet@34936
   473
                            (!too_big_scopes)) orelse
blanchet@34936
   474
                raise TOO_LARGE ("Nitpick.pick_them_nits_in_term.\
blanchet@34936
   475
                                 \problem_for_scope", "too large scope")
blanchet@33192
   476
(*
blanchet@36128
   477
        val _ = print_g "Offsets:"
blanchet@33192
   478
        val _ = List.app (fn (T, j0) =>
blanchet@36128
   479
                             print_g (string_for_type ctxt T ^ " = " ^
blanchet@36128
   480
                                    string_of_int j0))
blanchet@33192
   481
                         (Typtab.dest ofs)
blanchet@33192
   482
*)
blanchet@41858
   483
        val effective_total_consts =
blanchet@41856
   484
          case total_consts of
blanchet@41856
   485
            SOME b => b
blanchet@55890
   486
          | NONE => forall (is_exact_type data_types true) all_Ts
blanchet@33192
   487
        val main_j0 = offset_of_type ofs bool_T
blanchet@33192
   488
        val (nat_card, nat_j0) = spec_of_type scope nat_T
blanchet@33192
   489
        val (int_card, int_j0) = spec_of_type scope int_T
blanchet@34936
   490
        val _ = (nat_j0 = main_j0 andalso int_j0 = main_j0) orelse
blanchet@34936
   491
                raise BAD ("Nitpick.pick_them_nits_in_term.problem_for_scope",
blanchet@34936
   492
                           "bad offsets")
blanchet@33192
   493
        val kk = kodkod_constrs peephole_optim nat_card int_card main_j0
blanchet@33192
   494
        val (free_names, rep_table) =
blanchet@38170
   495
          choose_reps_for_free_vars scope pseudo_frees free_names
blanchet@38170
   496
                                    NameTable.empty
blanchet@33192
   497
        val (sel_names, rep_table) = choose_reps_for_all_sels scope rep_table
blanchet@38170
   498
        val (nonsel_names, rep_table) =
blanchet@41858
   499
          choose_reps_for_consts scope effective_total_consts nonsel_names
blanchet@41858
   500
                                 rep_table
blanchet@38182
   501
        val (guiltiest_party, min_highest_arity) =
blanchet@38182
   502
          NameTable.fold (fn (name, R) => fn (s, n) =>
blanchet@38182
   503
                             let val n' = arity_of_rep R in
blanchet@38182
   504
                               if n' > n then (nickname_of name, n') else (s, n)
blanchet@38182
   505
                             end) rep_table ("", 1)
blanchet@33192
   506
        val min_univ_card =
blanchet@36384
   507
          NameTable.fold (Integer.max o min_univ_card_of_rep o snd) rep_table
blanchet@34126
   508
                         (univ_card nat_card int_card main_j0 [] KK.True)
blanchet@52202
   509
        val _ = check_arity guiltiest_party min_univ_card min_highest_arity
blanchet@33192
   510
blanchet@41802
   511
        val def_us =
blanchet@41802
   512
          def_us |> map (choose_reps_in_nut scope unsound rep_table true)
blanchet@41802
   513
        val nondef_us =
blanchet@41802
   514
          nondef_us |> map (choose_reps_in_nut scope unsound rep_table false)
blanchet@41875
   515
        val need_us =
blanchet@41875
   516
          need_us |> map (choose_reps_in_nut scope unsound rep_table false)
blanchet@33745
   517
(*
blanchet@36128
   518
        val _ = List.app (print_g o string_for_nut ctxt)
blanchet@33192
   519
                         (free_names @ sel_names @ nonsel_names @
blanchet@41888
   520
                          nondef_us @ def_us @ need_us)
blanchet@33745
   521
*)
blanchet@33192
   522
        val (free_rels, pool, rel_table) =
blanchet@33192
   523
          rename_free_vars free_names initial_pool NameTable.empty
blanchet@33192
   524
        val (sel_rels, pool, rel_table) =
blanchet@33192
   525
          rename_free_vars sel_names pool rel_table
blanchet@33192
   526
        val (other_rels, pool, rel_table) =
blanchet@33192
   527
          rename_free_vars nonsel_names pool rel_table
blanchet@41802
   528
        val nondef_us = nondef_us |> map (rename_vars_in_nut pool rel_table)
blanchet@41802
   529
        val def_us = def_us |> map (rename_vars_in_nut pool rel_table)
blanchet@41875
   530
        val need_us = need_us |> map (rename_vars_in_nut pool rel_table)
blanchet@35386
   531
        val nondef_fs = map (kodkod_formula_from_nut ofs kk) nondef_us
blanchet@35280
   532
        val def_fs = map (kodkod_formula_from_nut ofs kk) def_us
blanchet@35386
   533
        val formula = fold (fold s_and) [def_fs, nondef_fs] KK.True
blanchet@35185
   534
        val comment = (if unsound then "unsound" else "sound") ^ "\n" ^
wenzelm@37146
   535
                      Print_Mode.setmp [] multiline_string_for_scope scope
blanchet@34998
   536
        val kodkod_sat_solver =
blanchet@36384
   537
          Kodkod_SAT.sat_solver_spec actual_sat_solver |> snd
blanchet@34124
   538
        val bit_width = if bits = 0 then 16 else bits + 1
blanchet@36384
   539
        val delay =
blanchet@36384
   540
          if unsound then
blanchet@54816
   541
            unsound_delay_for_timeout (Time.- (deadline, Time.now ()))
blanchet@36384
   542
          else
blanchet@36384
   543
            0
blanchet@36384
   544
        val settings = [("solver", commas_quote kodkod_sat_solver),
blanchet@34124
   545
                        ("bit_width", string_of_int bit_width),
blanchet@38124
   546
                        ("symmetry_breaking", string_of_int kodkod_sym_break),
blanchet@36386
   547
                        ("sharing", "3"),
blanchet@36386
   548
                        ("flatten", "false"),
blanchet@33192
   549
                        ("delay", signed_string_of_int delay)]
blanchet@33192
   550
        val plain_rels = free_rels @ other_rels
blanchet@33192
   551
        val plain_bounds = map (bound_for_plain_rel ctxt debug) plain_rels
blanchet@33192
   552
        val plain_axioms = map (declarative_axiom_for_plain_rel kk) plain_rels
blanchet@41995
   553
        val need_vals =
blanchet@41995
   554
          map (fn dtype as {typ, ...} =>
blanchet@55890
   555
                  (typ, needed_values_for_data_type need_us ofs dtype))
blanchet@55890
   556
              data_types
blanchet@41995
   557
        val sel_bounds =
blanchet@55890
   558
          map (bound_for_sel_rel ctxt debug need_vals data_types) sel_rels
blanchet@35190
   559
        val dtype_axioms =
blanchet@55890
   560
          declarative_axioms_for_data_types hol_ctxt binarize need_us need_vals
blanchet@55890
   561
              datatype_sym_break bits ofs kk rel_table data_types
blanchet@33192
   562
        val declarative_axioms = plain_axioms @ dtype_axioms
blanchet@35220
   563
        val univ_card = Int.max (univ_card nat_card int_card main_j0
blanchet@35220
   564
                                     (plain_bounds @ sel_bounds) formula,
blanchet@35220
   565
                                 main_j0 |> bits > 0 ? Integer.add (bits + 1))
blanchet@38126
   566
        val (built_in_bounds, built_in_axioms) =
blanchet@39345
   567
          bounds_and_axioms_for_built_in_rels_in_formulas debug univ_card
blanchet@39345
   568
              nat_card int_card main_j0 (formula :: declarative_axioms)
blanchet@33192
   569
        val bounds = built_in_bounds @ plain_bounds @ sel_bounds
blanchet@33192
   570
                     |> not debug ? merge_bounds
blanchet@38126
   571
        val axioms = built_in_axioms @ declarative_axioms
blanchet@33192
   572
        val highest_arity =
blanchet@33192
   573
          fold Integer.max (map (fst o fst) (maps fst bounds)) 0
blanchet@38126
   574
        val formula = fold_rev s_and axioms formula
blanchet@34124
   575
        val _ = if bits = 0 then () else check_bits bits formula
blanchet@52202
   576
        val _ = if formula = KK.False then ()
blanchet@38182
   577
                else check_arity "" univ_card highest_arity
blanchet@33192
   578
      in
blanchet@33192
   579
        SOME ({comment = comment, settings = settings, univ_card = univ_card,
blanchet@33192
   580
               tuple_assigns = [], bounds = bounds,
blanchet@35280
   581
               int_bounds = if bits = 0 then sequential_int_bounds univ_card
blanchet@35280
   582
                            else pow_of_two_int_bounds bits main_j0,
blanchet@33192
   583
               expr_assigns = [], formula = formula},
blanchet@33192
   584
              {free_names = free_names, sel_names = sel_names,
blanchet@33192
   585
               nonsel_names = nonsel_names, rel_table = rel_table,
blanchet@35386
   586
               unsound = unsound, scope = scope})
blanchet@33192
   587
      end
blanchet@34124
   588
      handle TOO_LARGE (loc, msg) =>
blanchet@34936
   589
             if loc = "Nitpick_Kodkod.check_arity" andalso
blanchet@34936
   590
                not (Typtab.is_empty ofs) then
blanchet@35185
   591
               problem_for_scope unsound
blanchet@35190
   592
                   {hol_ctxt = hol_ctxt, binarize = binarize,
blanchet@35190
   593
                    card_assigns = card_assigns, bits = bits,
blanchet@55890
   594
                    bisim_depth = bisim_depth, data_types = data_types,
blanchet@35190
   595
                    ofs = Typtab.empty}
blanchet@33192
   596
             else if loc = "Nitpick.pick_them_nits_in_term.\
blanchet@33192
   597
                           \problem_for_scope" then
blanchet@33192
   598
               NONE
blanchet@33192
   599
             else
blanchet@33192
   600
               (Unsynchronized.change too_big_scopes (cons scope);
blanchet@41992
   601
                print_v (fn () =>
blanchet@41992
   602
                    "Limit reached: " ^ msg ^ ". Skipping " ^
blanchet@41992
   603
                    (if unsound then "potential component of " else "") ^
blanchet@41992
   604
                    "scope.");
blanchet@33192
   605
                NONE)
blanchet@35280
   606
           | TOO_SMALL (_, msg) =>
blanchet@41992
   607
             (print_v (fn () =>
blanchet@41992
   608
                  "Limit reached: " ^ msg ^ ". Skipping " ^
blanchet@41992
   609
                  (if unsound then "potential component of " else "") ^
blanchet@41992
   610
                  "scope.");
blanchet@34124
   611
              NONE)
blanchet@33192
   612
blanchet@55888
   613
    val das_wort_model = if falsify then "counterexample" else "model"
blanchet@33192
   614
blanchet@33192
   615
    val scopes = Unsynchronized.ref []
blanchet@33192
   616
    val generated_scopes = Unsynchronized.ref []
blanchet@35185
   617
    val generated_problems = Unsynchronized.ref ([] : rich_problem list)
blanchet@33192
   618
    val checked_problems = Unsynchronized.ref (SOME [])
blanchet@33192
   619
    val met_potential = Unsynchronized.ref 0
blanchet@33192
   620
blanchet@33192
   621
    fun update_checked_problems problems =
blanchet@33192
   622
      List.app (Unsynchronized.change checked_problems o Option.map o cons
blanchet@33192
   623
                o nth problems)
blanchet@35333
   624
    fun show_kodkod_warning "" = ()
blanchet@47560
   625
      | show_kodkod_warning s = print_nt (fn () => "Kodkod warning: " ^ s ^ ".")
blanchet@33192
   626
blanchet@33192
   627
    fun print_and_check_model genuine bounds
blanchet@33192
   628
            ({free_names, sel_names, nonsel_names, rel_table, scope, ...}
blanchet@33192
   629
             : problem_extension) =
blanchet@33192
   630
      let
blanchet@47752
   631
        val _ =
blanchet@47752
   632
          print_t (fn () =>
blanchet@47752
   633
               "% SZS status " ^
blanchet@47752
   634
               (if genuine then
blanchet@47752
   635
                  if falsify then "CounterSatisfiable" else "Satisfiable"
blanchet@47752
   636
                else
blanchet@61310
   637
                  "GaveUp") ^ "\n" ^
blanchet@47752
   638
               "% SZS output start FiniteModel")
blanchet@33192
   639
        val (reconstructed_model, codatatypes_ok) =
blanchet@41993
   640
          reconstruct_hol_model
blanchet@55889
   641
              {show_types = show_types, show_skolems = show_skolems,
blanchet@41993
   642
               show_consts = show_consts}
blanchet@38170
   643
              scope formats atomss real_frees pseudo_frees free_names sel_names
blanchet@38170
   644
              nonsel_names rel_table bounds
blanchet@35671
   645
        val genuine_means_genuine =
blanchet@35671
   646
          got_all_user_axioms andalso none_true wfs andalso
blanchet@41858
   647
          sound_finitizes andalso total_consts <> SOME true andalso
blanchet@41858
   648
          codatatypes_ok
blanchet@47715
   649
        fun assms_prop () =
blanchet@47715
   650
          Logic.mk_conjunction_list (neg_t :: def_assm_ts @ nondef_assm_ts)
blanchet@33192
   651
      in
blanchet@47752
   652
        (pprint_a (Pretty.chunks
blanchet@35671
   653
             [Pretty.blk (0,
wenzelm@59432
   654
                  (Pretty.text ((if mode = Auto_Try then "Auto " else "") ^
blanchet@43022
   655
                          "Nitpick found a" ^
blanchet@41992
   656
                          (if not genuine then " potentially spurious "
blanchet@35671
   657
                           else if genuine_means_genuine then " "
blanchet@35671
   658
                           else " quasi genuine ") ^ das_wort_model) @
blanchet@35671
   659
                   (case pretties_for_scope scope verbose of
blanchet@35671
   660
                      [] => []
wenzelm@60023
   661
                    | pretties => [Pretty.brk 1, Pretty.str "for", Pretty.brk 1] @ pretties) @
wenzelm@59429
   662
                   [Pretty.str ":", Pretty.fbrk])),
blanchet@35671
   663
              Pretty.indent indent_size reconstructed_model]);
blanchet@47564
   664
         print_t (K "% SZS output end FiniteModel");
blanchet@35671
   665
         if genuine then
blanchet@60310
   666
           (if has_lonely_bool_var orig_t then
blanchet@41048
   667
              print "Hint: Maybe you forgot a colon after the lemma's name?"
blanchet@41048
   668
            else if has_syntactic_sorts orig_t then
blanchet@35671
   669
              print "Hint: Maybe you forgot a type constraint?"
blanchet@35671
   670
            else
blanchet@35671
   671
              ();
blanchet@35671
   672
            if not genuine_means_genuine then
blanchet@35671
   673
              if no_poly_user_axioms then
blanchet@35671
   674
                let
blanchet@35671
   675
                  val options =
blanchet@35671
   676
                    [] |> not got_all_mono_user_axioms
blanchet@35671
   677
                          ? cons ("user_axioms", "\"true\"")
blanchet@35671
   678
                       |> not (none_true wfs)
blanchet@35671
   679
                          ? cons ("wf", "\"smart\" or \"false\"")
blanchet@35671
   680
                       |> not sound_finitizes
blanchet@35671
   681
                          ? cons ("finitize", "\"smart\" or \"false\"")
blanchet@41858
   682
                       |> total_consts = SOME true
blanchet@41858
   683
                          ? cons ("total_consts", "\"smart\" or \"false\"")
blanchet@35671
   684
                       |> not codatatypes_ok
blanchet@35671
   685
                          ? cons ("bisim_depth", "a nonnegative value")
blanchet@35671
   686
                  val ss =
blanchet@35671
   687
                    map (fn (name, value) => quote name ^ " set to " ^ value)
blanchet@35671
   688
                        options
blanchet@35671
   689
                in
blanchet@35671
   690
                  print ("Try again with " ^
blanchet@41872
   691
                         space_implode " " (serial_commas "and" ss) ^
blanchet@35671
   692
                         " to confirm that the " ^ das_wort_model ^
blanchet@35671
   693
                         " is genuine.")
blanchet@35671
   694
                end
blanchet@35671
   695
              else
blanchet@35671
   696
                print ("Nitpick is unable to guarantee the authenticity of \
blanchet@35671
   697
                       \the " ^ das_wort_model ^ " in the presence of \
blanchet@35671
   698
                       \polymorphic axioms.")
blanchet@35671
   699
            else
blanchet@35671
   700
              ();
blanchet@35671
   701
            NONE)
blanchet@35671
   702
         else
blanchet@35671
   703
           if not genuine then
blanchet@60310
   704
             (Unsynchronized.inc met_potential; NONE)
blanchet@33192
   705
           else
blanchet@35671
   706
             NONE)
blanchet@35671
   707
        |> pair genuine_means_genuine
blanchet@33192
   708
      end
blanchet@35671
   709
    fun solve_any_problem (found_really_genuine, max_potential, max_genuine,
blanchet@35671
   710
                           donno) first_time problems =
blanchet@33192
   711
      let
blanchet@33192
   712
        val max_potential = Int.max (0, max_potential)
blanchet@33192
   713
        val max_genuine = Int.max (0, max_genuine)
blanchet@33192
   714
        fun print_and_check genuine (j, bounds) =
blanchet@33192
   715
          print_and_check_model genuine bounds (snd (nth problems j))
blanchet@33192
   716
        val max_solutions = max_potential + max_genuine
blanchet@36384
   717
                            |> not incremental ? Integer.min 1
blanchet@33192
   718
      in
blanchet@33192
   719
        if max_solutions <= 0 then
blanchet@35671
   720
          (found_really_genuine, 0, 0, donno)
blanchet@33192
   721
        else
blanchet@41793
   722
          case KK.solve_any_problem debug overlord deadline max_threads
blanchet@41793
   723
                                    max_solutions (map fst problems) of
blanchet@49024
   724
            KK.JavaNotFound =>
blanchet@55889
   725
            (print_nt (K java_not_found_message);
blanchet@35696
   726
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@38516
   727
          | KK.JavaTooOld =>
blanchet@55889
   728
            (print_nt (K java_too_old_message);
blanchet@38516
   729
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@35696
   730
          | KK.KodkodiNotInstalled =>
blanchet@55889
   731
            (print_nt (K kodkodi_not_installed_message);
blanchet@35671
   732
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@50487
   733
          | KK.KodkodiTooOld =>
blanchet@55889
   734
            (print_nt (K kodkodi_too_old_message);
blanchet@50487
   735
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@35333
   736
          | KK.Normal ([], unsat_js, s) =>
blanchet@35333
   737
            (update_checked_problems problems unsat_js; show_kodkod_warning s;
blanchet@35671
   738
             (found_really_genuine, max_potential, max_genuine, donno))
blanchet@35333
   739
          | KK.Normal (sat_ps, unsat_js, s) =>
blanchet@33192
   740
            let
blanchet@33192
   741
              val (lib_ps, con_ps) =
blanchet@35185
   742
                List.partition (#unsound o snd o nth problems o fst) sat_ps
blanchet@33192
   743
            in
blanchet@33192
   744
              update_checked_problems problems (unsat_js @ map fst lib_ps);
blanchet@35333
   745
              show_kodkod_warning s;
blanchet@33192
   746
              if null con_ps then
blanchet@33192
   747
                let
blanchet@35671
   748
                  val genuine_codes =
blanchet@35671
   749
                    lib_ps |> take max_potential
blanchet@35671
   750
                           |> map (print_and_check false)
blanchet@35671
   751
                           |> filter (curry (op =) (SOME true) o snd)
blanchet@35671
   752
                  val found_really_genuine =
blanchet@35671
   753
                    found_really_genuine orelse exists fst genuine_codes
blanchet@35671
   754
                  val num_genuine = length genuine_codes
blanchet@33192
   755
                  val max_genuine = max_genuine - num_genuine
blanchet@33192
   756
                  val max_potential = max_potential
blanchet@33192
   757
                                      - (length lib_ps - num_genuine)
blanchet@33192
   758
                in
blanchet@33192
   759
                  if max_genuine <= 0 then
blanchet@35671
   760
                    (found_really_genuine, 0, 0, donno)
blanchet@33192
   761
                  else
blanchet@33192
   762
                    let
blanchet@35185
   763
                      (* "co_js" is the list of sound problems whose unsound
blanchet@35185
   764
                         pendants couldn't be satisfied and hence that most
blanchet@35185
   765
                         probably can't be satisfied themselves. *)
blanchet@33192
   766
                      val co_js =
blanchet@33192
   767
                        map (fn j => j - 1) unsat_js
blanchet@33192
   768
                        |> filter (fn j =>
blanchet@33192
   769
                                      j >= 0 andalso
blanchet@33192
   770
                                      scopes_equivalent
blanchet@35814
   771
                                          (#scope (snd (nth problems j)),
blanchet@35814
   772
                                           #scope (snd (nth problems (j + 1)))))
blanchet@33192
   773
                      val bye_js = sort_distinct int_ord (map fst sat_ps @
blanchet@33192
   774
                                                          unsat_js @ co_js)
blanchet@33192
   775
                      val problems =
blanchet@33192
   776
                        problems |> filter_out_indices bye_js
blanchet@33192
   777
                                 |> max_potential <= 0
blanchet@35185
   778
                                    ? filter_out (#unsound o snd)
blanchet@33192
   779
                    in
blanchet@35671
   780
                      solve_any_problem (found_really_genuine, max_potential,
blanchet@35671
   781
                                         max_genuine, donno) false problems
blanchet@33192
   782
                    end
blanchet@33192
   783
                end
blanchet@33192
   784
              else
blanchet@33192
   785
                let
blanchet@35671
   786
                  val genuine_codes =
blanchet@35671
   787
                    con_ps |> take max_genuine
blanchet@35671
   788
                           |> map (print_and_check true)
blanchet@35671
   789
                  val max_genuine = max_genuine - length genuine_codes
blanchet@35671
   790
                  val found_really_genuine =
blanchet@35671
   791
                    found_really_genuine orelse exists fst genuine_codes
blanchet@33192
   792
                in
blanchet@33192
   793
                  if max_genuine <= 0 orelse not first_time then
blanchet@35671
   794
                    (found_really_genuine, 0, max_genuine, donno)
blanchet@33192
   795
                  else
blanchet@33192
   796
                    let
blanchet@33192
   797
                      val bye_js = sort_distinct int_ord
blanchet@33192
   798
                                                 (map fst sat_ps @ unsat_js)
blanchet@33192
   799
                      val problems =
blanchet@33192
   800
                        problems |> filter_out_indices bye_js
blanchet@35185
   801
                                 |> filter_out (#unsound o snd)
blanchet@35671
   802
                    in
blanchet@35671
   803
                      solve_any_problem (found_really_genuine, 0, max_genuine,
blanchet@35671
   804
                                         donno) false problems
blanchet@35671
   805
                    end
blanchet@33192
   806
                end
blanchet@33192
   807
            end
blanchet@34126
   808
          | KK.TimedOut unsat_js =>
blanchet@33192
   809
            (update_checked_problems problems unsat_js; raise TimeLimit.TimeOut)
blanchet@34126
   810
          | KK.Error (s, unsat_js) =>
blanchet@33192
   811
            (update_checked_problems problems unsat_js;
blanchet@33192
   812
             print_v (K ("Kodkod error: " ^ s ^ "."));
blanchet@35671
   813
             (found_really_genuine, max_potential, max_genuine, donno + 1))
blanchet@33192
   814
      end
blanchet@33192
   815
blanchet@35671
   816
    fun run_batch j n scopes (found_really_genuine, max_potential, max_genuine,
blanchet@35671
   817
                              donno) =
blanchet@33192
   818
      let
blanchet@33192
   819
        val _ =
blanchet@33192
   820
          if null scopes then
blanchet@47560
   821
            print_nt (K "The scope specification is inconsistent.")
blanchet@33192
   822
          else if verbose then
blanchet@47560
   823
            pprint_nt (fn () => Pretty.chunks
blanchet@33192
   824
                [Pretty.blk (0,
wenzelm@59432
   825
                     Pretty.text ((if n > 1 then
blanchet@33192
   826
                               "Batch " ^ string_of_int (j + 1) ^ " of " ^
blanchet@33192
   827
                               signed_string_of_int n ^ ": "
blanchet@33192
   828
                             else
blanchet@33192
   829
                               "") ^
blanchet@33192
   830
                            "Trying " ^ string_of_int (length scopes) ^
blanchet@33192
   831
                            " scope" ^ plural_s_for_list scopes ^ ":")),
blanchet@33192
   832
                 Pretty.indent indent_size
blanchet@33192
   833
                     (Pretty.chunks (map2
blanchet@33192
   834
                          (fn j => fn scope =>
blanchet@33192
   835
                              Pretty.block (
blanchet@33192
   836
                                  (case pretties_for_scope scope true of
blanchet@33192
   837
                                     [] => [Pretty.str "Empty"]
blanchet@33192
   838
                                   | pretties => pretties) @
blanchet@33192
   839
                                  [Pretty.str (if j = 1 then "." else ";")]))
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@35384
   874
                    \fragment." ^
blanchet@35185
   875
                    (if exists (not o KK.is_problem_trivially_false o fst)
blanchet@35185
   876
                               unsound_problems then
blanchet@41992
   877
                       " Only potentially spurious " ^ das_wort_model ^
blanchet@41992
   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@33192
   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@55888
   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@38123
   943
                             " better " ^ das_wort_model ^ "."
blanchet@38123
   944
                           else
blanchet@38123
   945
                             "ny better " ^ das_wort_model ^ "s.") ^
blanchet@38123
   946
                          " It 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)
blanchet@33192
   961
      handle TimeLimit.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@52031
   965
                "Total time: " ^ string_of_time (Timer.checkRealTimer timer) ^
blanchet@40341
   966
                ".")
blanchet@53815
   967
    val _ = spying spy (fn () => (state, i, "outcome: " ^ outcome_code))
wenzelm@58892
   968
  in (outcome_code, Queue.content (Synchronized.value outcome)) end
blanchet@33192
   969
blanchet@41051
   970
(* Give the inner timeout a chance. *)
blanchet@41772
   971
val timeout_bonus = seconds 1.0
blanchet@41051
   972
blanchet@55539
   973
fun pick_nits_in_term state (params as {timeout, expect, ...}) mode i n step
blanchet@55539
   974
                      subst def_assm_ts nondef_assm_ts orig_t =
blanchet@47670
   975
  let
wenzelm@58843
   976
    val print_nt = if is_mode_nt mode then writeln else K ()
wenzelm@58843
   977
    val print_t = if mode = TPTP then writeln else K ()
blanchet@47670
   978
  in
blanchet@37213
   979
    if getenv "KODKODI" = "" then
blanchet@37497
   980
      (* The "expect" argument is deliberately ignored if Kodkodi is missing so
blanchet@37497
   981
         that the "Nitpick_Examples" can be processed on any machine. *)
blanchet@55889
   982
      (print_nt (Pretty.string_of (plazy (K kodkodi_not_installed_message)));
wenzelm@58892
   983
       ("no_kodkodi", []))
blanchet@37213
   984
    else
blanchet@37213
   985
      let
wenzelm@58892
   986
        val unknown_outcome = (unknownN, [])
blanchet@54816
   987
        val deadline = Time.+ (Time.now (), timeout)
blanchet@37213
   988
        val outcome as (outcome_code, _) =
blanchet@54816
   989
          TimeLimit.timeLimit (Time.+ (timeout, timeout_bonus))
blanchet@43022
   990
              (pick_them_nits_in_term deadline state params mode i n step subst
blanchet@47715
   991
                                      def_assm_ts nondef_assm_ts) orig_t
blanchet@37213
   992
          handle TOO_LARGE (_, details) =>
blanchet@61365
   993
                 (print_t "% SZS status GaveUp";
blanchet@47670
   994
                  print_nt ("Limit reached: " ^ details ^ "."); unknown_outcome)
blanchet@37213
   995
               | TOO_SMALL (_, details) =>
blanchet@61365
   996
                 (print_t "% SZS status GaveUp";
blanchet@47670
   997
                  print_nt ("Limit reached: " ^ details ^ "."); unknown_outcome)
blanchet@37213
   998
               | Kodkod.SYNTAX (_, details) =>
blanchet@61365
   999
                 (print_t "% SZS status GaveUp";
blanchet@47670
  1000
                  print_nt ("Malformed Kodkodi output: " ^ details ^ ".");
blanchet@37213
  1001
                  unknown_outcome)
blanchet@41772
  1002
               | TimeLimit.TimeOut =>
blanchet@47670
  1003
                 (print_t "% SZS status TimedOut";
blanchet@47670
  1004
                  print_nt "Nitpick ran out of time."; unknown_outcome)
blanchet@37213
  1005
      in
blanchet@37213
  1006
        if expect = "" orelse outcome_code = expect then outcome
blanchet@37213
  1007
        else error ("Unexpected outcome: " ^ quote outcome_code ^ ".")
blanchet@37213
  1008
      end
blanchet@37213
  1009
  end
blanchet@33192
  1010
wenzelm@42486
  1011
fun is_fixed_equation ctxt
wenzelm@56245
  1012
                      (Const (@{const_name Pure.eq}, _) $ Free (s, _) $ Const _) =
wenzelm@42486
  1013
    Variable.is_fixed ctxt s
blanchet@35335
  1014
  | is_fixed_equation _ _ = false
blanchet@55889
  1015
blanchet@35335
  1016
fun extract_fixed_frees ctxt (assms, t) =
blanchet@35335
  1017
  let
blanchet@35335
  1018
    val (subst, other_assms) =
wenzelm@42486
  1019
      List.partition (is_fixed_equation ctxt) assms
blanchet@35335
  1020
      |>> map Logic.dest_equals
blanchet@35335
  1021
  in (subst, other_assms, subst_atomic subst t) end
blanchet@35335
  1022
blanchet@43022
  1023
fun pick_nits_in_subgoal state params mode i step =
blanchet@33192
  1024
  let
blanchet@33192
  1025
    val ctxt = Proof.context_of state
wenzelm@59582
  1026
    val t = state |> Proof.raw_goal |> #goal |> Thm.prop_of
blanchet@33192
  1027
  in
blanchet@34982
  1028
    case Logic.count_prems t of
wenzelm@58892
  1029
      0 => (writeln "No subgoal!"; (noneN, []))
blanchet@34982
  1030
    | n =>
blanchet@33192
  1031
      let
blanchet@36406
  1032
        val t = Logic.goal_params t i |> fst
wenzelm@59582
  1033
        val assms = map Thm.term_of (Assumption.all_assms_of ctxt)
blanchet@35335
  1034
        val (subst, assms, t) = extract_fixed_frees ctxt (assms, t)
blanchet@47715
  1035
      in pick_nits_in_term state params mode i n step subst [] assms t end
blanchet@33192
  1036
  end
blanchet@33192
  1037
blanchet@33192
  1038
end;