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