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