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