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