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