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