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