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