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