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