src/HOL/Tools/Sledgehammer/sledgehammer_filter_mash.ML
author blanchet
Wed, 18 Jul 2012 08:44:04 +0200
changeset 49330 82d6e46c673f
parent 49329 ee33ba3c0e05
child 49331 252f45c04042
permissions -rw-r--r--
fixed order of accessibles + other tweaks to MaSh
blanchet@49263
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_filter_mash.ML
blanchet@49263
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@49263
     3
blanchet@49263
     4
Sledgehammer's machine-learning-based relevance filter (MaSh).
blanchet@49263
     5
*)
blanchet@49263
     6
blanchet@49263
     7
signature SLEDGEHAMMER_FILTER_MASH =
blanchet@49263
     8
sig
blanchet@49266
     9
  type status = ATP_Problem_Generate.status
blanchet@49266
    10
  type stature = ATP_Problem_Generate.stature
blanchet@49311
    11
  type fact = Sledgehammer_Fact.fact
blanchet@49311
    12
  type fact_override = Sledgehammer_Fact.fact_override
blanchet@49266
    13
  type params = Sledgehammer_Provers.params
blanchet@49303
    14
  type relevance_fudge = Sledgehammer_Provers.relevance_fudge
blanchet@49266
    15
  type prover_result = Sledgehammer_Provers.prover_result
blanchet@49266
    16
blanchet@49323
    17
  val trace : bool Config.T
blanchet@49329
    18
  val meshN : string
blanchet@49329
    19
  val iterN : string
blanchet@49329
    20
  val mashN : string
blanchet@49329
    21
  val fact_filters : string list
blanchet@49318
    22
  val escape_meta : string -> string
blanchet@49318
    23
  val escape_metas : string list -> string
blanchet@49323
    24
  val unescape_meta : string -> string
blanchet@49323
    25
  val unescape_metas : string -> string list
blanchet@49326
    26
  val extract_query : string -> string * string list
blanchet@49327
    27
  val suggested_facts : string list -> fact list -> fact list
blanchet@49328
    28
  val mesh_facts : int -> (fact list * int option) list -> fact list
blanchet@49330
    29
  val is_likely_tautology : thm -> bool
blanchet@49330
    30
  val is_too_meta : thm -> bool
blanchet@49266
    31
  val theory_ord : theory * theory -> order
blanchet@49266
    32
  val thm_ord : thm * thm -> order
blanchet@49330
    33
  val thy_map_from_facts : fact list -> (string * string list) list
blanchet@49266
    34
  val has_thy : theory -> thm -> bool
blanchet@49330
    35
  val parent_facts : theory -> (string * string list) list -> string list
blanchet@49317
    36
  val features_of : theory -> status -> term list -> string list
blanchet@49266
    37
  val isabelle_dependencies_of : string list -> thm -> string list
blanchet@49266
    38
  val goal_of_thm : theory -> thm -> thm
blanchet@49311
    39
  val run_prover : Proof.context -> params -> fact list -> thm -> prover_result
blanchet@49319
    40
  val thy_name_of_fact : string -> string
blanchet@49323
    41
  val mash_RESET : Proof.context -> unit
blanchet@49323
    42
  val mash_ADD :
blanchet@49323
    43
    Proof.context -> (string * string list * string list * string list) list
blanchet@49323
    44
    -> unit
blanchet@49323
    45
  val mash_DEL : Proof.context -> string list -> string list -> unit
blanchet@49326
    46
  val mash_QUERY : Proof.context -> string list * string list -> string list
blanchet@49323
    47
  val mash_reset : Proof.context -> unit
blanchet@49323
    48
  val mash_can_suggest_facts : Proof.context -> bool
blanchet@49313
    49
  val mash_suggest_facts :
blanchet@49326
    50
    Proof.context -> params -> string -> term list -> term -> fact list
blanchet@49326
    51
    -> fact list
blanchet@49323
    52
  val mash_learn_thy : Proof.context -> theory -> real -> unit
blanchet@49324
    53
  val mash_learn_proof : Proof.context -> theory -> term -> thm list -> unit
blanchet@49303
    54
  val relevant_facts :
blanchet@49307
    55
    Proof.context -> params -> string -> int -> fact_override -> term list
blanchet@49311
    56
    -> term -> fact list -> fact list
blanchet@49263
    57
end;
blanchet@49263
    58
blanchet@49263
    59
structure Sledgehammer_Filter_MaSh : SLEDGEHAMMER_FILTER_MASH =
blanchet@49263
    60
struct
blanchet@49264
    61
blanchet@49266
    62
open ATP_Util
blanchet@49266
    63
open ATP_Problem_Generate
blanchet@49266
    64
open Sledgehammer_Util
blanchet@49266
    65
open Sledgehammer_Fact
blanchet@49266
    66
open Sledgehammer_Filter_Iter
blanchet@49266
    67
open Sledgehammer_Provers
blanchet@49266
    68
blanchet@49323
    69
val trace =
blanchet@49323
    70
  Attrib.setup_config_bool @{binding sledgehammer_filter_mash_trace} (K false)
blanchet@49323
    71
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@49323
    72
blanchet@49329
    73
val meshN = "mesh"
blanchet@49329
    74
val iterN = "iter"
blanchet@49329
    75
val mashN = "mash"
blanchet@49329
    76
blanchet@49329
    77
val fact_filters = [meshN, iterN, mashN]
blanchet@49329
    78
blanchet@49329
    79
fun mash_home () = getenv "MASH_HOME"
blanchet@49329
    80
fun mash_state_dir () =
blanchet@49324
    81
  getenv "ISABELLE_HOME_USER" ^ "/mash"
blanchet@49324
    82
  |> tap (fn dir => Isabelle_System.mkdir (Path.explode dir))
blanchet@49329
    83
fun mash_state_path () = mash_state_dir () ^ "/state" |> Path.explode
blanchet@49266
    84
blanchet@49266
    85
(*** Isabelle helpers ***)
blanchet@49266
    86
blanchet@49323
    87
fun meta_char c =
blanchet@49266
    88
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse
blanchet@49266
    89
     c = #")" orelse c = #"," then
blanchet@49266
    90
    String.str c
blanchet@49266
    91
  else
blanchet@49266
    92
    (* fixed width, in case more digits follow *)
blanchet@49266
    93
    "\\" ^ stringN_of_int 3 (Char.ord c)
blanchet@49266
    94
blanchet@49323
    95
fun unmeta_chars accum [] = String.implode (rev accum)
blanchet@49323
    96
  | unmeta_chars accum (#"\\" :: d1 :: d2 :: d3 :: cs) =
blanchet@49323
    97
    (case Int.fromString (String.implode [d1, d2, d3]) of
blanchet@49323
    98
       SOME n => unmeta_chars (Char.chr n :: accum) cs
blanchet@49323
    99
     | NONE => "" (* error *))
blanchet@49323
   100
  | unmeta_chars _ (#"\\" :: _) = "" (* error *)
blanchet@49323
   101
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs
blanchet@49323
   102
blanchet@49323
   103
val escape_meta = String.translate meta_char
blanchet@49318
   104
val escape_metas = map escape_meta #> space_implode " "
blanchet@49330
   105
val unescape_meta = String.explode #> unmeta_chars []
blanchet@49330
   106
val unescape_metas =
blanchet@49330
   107
  space_explode " " #> filter_out (curry (op =) "") #> map unescape_meta
blanchet@49266
   108
blanchet@49326
   109
fun extract_query line =
blanchet@49326
   110
  case space_explode ":" line of
blanchet@49330
   111
    [goal_name, suggs] => (unescape_meta goal_name, unescape_metas suggs)
blanchet@49327
   112
  | _ => ("", [])
blanchet@49326
   113
blanchet@49326
   114
fun find_suggested facts sugg =
blanchet@49326
   115
  find_first (fn (_, th) => Thm.get_name_hint th = sugg) facts
blanchet@49326
   116
fun suggested_facts suggs facts = map_filter (find_suggested facts) suggs
blanchet@49326
   117
blanchet@49328
   118
fun sum_avg n xs =
blanchet@49328
   119
  fold (Integer.add o Integer.mult n) xs 0 div (length xs)
blanchet@49328
   120
blanchet@49329
   121
fun mesh_facts max_facts [(facts, _)] = facts |> take max_facts
blanchet@49329
   122
  | mesh_facts max_facts mess =
blanchet@49329
   123
    let
blanchet@49329
   124
      val n = length mess
blanchet@49329
   125
      val fact_eq = Thm.eq_thm o pairself snd
blanchet@49329
   126
      fun score_in fact (facts, def) =
blanchet@49329
   127
        case find_index (curry fact_eq fact) facts of
blanchet@49329
   128
          ~1 => def
blanchet@49329
   129
        | j => SOME j
blanchet@49329
   130
      fun score_of fact = mess |> map_filter (score_in fact) |> sum_avg n
blanchet@49329
   131
      val facts = fold (union fact_eq o take max_facts o fst) mess []
blanchet@49329
   132
    in
blanchet@49329
   133
      facts |> map (`score_of) |> sort (int_ord o pairself fst) |> map snd
blanchet@49329
   134
            |> take max_facts
blanchet@49329
   135
    end
blanchet@49327
   136
blanchet@49318
   137
val thy_feature_prefix = "y_"
blanchet@49266
   138
blanchet@49318
   139
val thy_feature_name_of = prefix thy_feature_prefix
blanchet@49318
   140
val const_name_of = prefix const_prefix
blanchet@49318
   141
val type_name_of = prefix type_const_prefix
blanchet@49318
   142
val class_name_of = prefix class_prefix
blanchet@49266
   143
blanchet@49266
   144
local
blanchet@49266
   145
blanchet@49266
   146
fun has_bool @{typ bool} = true
blanchet@49266
   147
  | has_bool (Type (_, Ts)) = exists has_bool Ts
blanchet@49266
   148
  | has_bool _ = false
blanchet@49266
   149
blanchet@49266
   150
fun has_fun (Type (@{type_name fun}, _)) = true
blanchet@49266
   151
  | has_fun (Type (_, Ts)) = exists has_fun Ts
blanchet@49266
   152
  | has_fun _ = false
blanchet@49266
   153
blanchet@49266
   154
val is_conn = member (op =)
blanchet@49266
   155
  [@{const_name Trueprop}, @{const_name HOL.conj}, @{const_name HOL.disj},
blanchet@49266
   156
   @{const_name HOL.implies}, @{const_name Not},
blanchet@49266
   157
   @{const_name All}, @{const_name Ex}, @{const_name Ball}, @{const_name Bex},
blanchet@49266
   158
   @{const_name HOL.eq}]
blanchet@49266
   159
blanchet@49266
   160
val has_bool_arg_const =
blanchet@49266
   161
  exists_Const (fn (c, T) =>
blanchet@49266
   162
                   not (is_conn c) andalso exists has_bool (binder_types T))
blanchet@49266
   163
blanchet@49266
   164
fun higher_inst_const thy (c, T) =
blanchet@49266
   165
  case binder_types T of
blanchet@49266
   166
    [] => false
blanchet@49266
   167
  | Ts => length (binder_types (Sign.the_const_type thy c)) <> length Ts
blanchet@49266
   168
blanchet@49266
   169
val binders = [@{const_name All}, @{const_name Ex}]
blanchet@49266
   170
blanchet@49266
   171
in
blanchet@49266
   172
blanchet@49266
   173
fun is_fo_term thy t =
blanchet@49266
   174
  let
blanchet@49266
   175
    val t =
blanchet@49266
   176
      t |> Envir.beta_eta_contract
blanchet@49266
   177
        |> transform_elim_prop
blanchet@49266
   178
        |> Object_Logic.atomize_term thy
blanchet@49266
   179
  in
blanchet@49266
   180
    Term.is_first_order binders t andalso
blanchet@49266
   181
    not (exists_subterm (fn Var (_, T) => has_bool T orelse has_fun T
blanchet@49266
   182
                          | _ => false) t orelse
blanchet@49266
   183
         has_bool_arg_const t orelse exists_Const (higher_inst_const thy) t)
blanchet@49266
   184
  end
blanchet@49266
   185
blanchet@49266
   186
end
blanchet@49266
   187
blanchet@49317
   188
fun interesting_terms_types_and_classes term_max_depth type_max_depth ts =
blanchet@49266
   189
  let
blanchet@49266
   190
    val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]
blanchet@49266
   191
    val bad_consts = atp_widely_irrelevant_consts
blanchet@49319
   192
    fun add_classes @{sort type} = I
blanchet@49319
   193
      | add_classes S = union (op =) (map class_name_of S)
blanchet@49266
   194
    fun do_add_type (Type (s, Ts)) =
blanchet@49266
   195
        (not (member (op =) bad_types s) ? insert (op =) (type_name_of s))
blanchet@49266
   196
        #> fold do_add_type Ts
blanchet@49319
   197
      | do_add_type (TFree (_, S)) = add_classes S
blanchet@49319
   198
      | do_add_type (TVar (_, S)) = add_classes S
blanchet@49266
   199
    fun add_type T = type_max_depth >= 0 ? do_add_type T
blanchet@49266
   200
    fun mk_app s args =
blanchet@49266
   201
      if member (op <>) args "" then s ^ "(" ^ space_implode "," args ^ ")"
blanchet@49266
   202
      else s
blanchet@49266
   203
    fun patternify ~1 _ = ""
blanchet@49266
   204
      | patternify depth t =
blanchet@49266
   205
        case strip_comb t of
blanchet@49266
   206
          (Const (s, _), args) =>
blanchet@49266
   207
          mk_app (const_name_of s) (map (patternify (depth - 1)) args)
blanchet@49266
   208
        | _ => ""
blanchet@49266
   209
    fun add_term_patterns ~1 _ = I
blanchet@49266
   210
      | add_term_patterns depth t =
blanchet@49266
   211
        insert (op =) (patternify depth t)
blanchet@49266
   212
        #> add_term_patterns (depth - 1) t
blanchet@49266
   213
    val add_term = add_term_patterns term_max_depth
blanchet@49266
   214
    fun add_patterns t =
blanchet@49266
   215
      let val (head, args) = strip_comb t in
blanchet@49266
   216
        (case head of
blanchet@49266
   217
           Const (s, T) =>
blanchet@49266
   218
           not (member (op =) bad_consts s) ? (add_term t #> add_type T)
blanchet@49266
   219
         | Free (_, T) => add_type T
blanchet@49266
   220
         | Var (_, T) => add_type T
blanchet@49266
   221
         | Abs (_, T, body) => add_type T #> add_patterns body
blanchet@49266
   222
         | _ => I)
blanchet@49266
   223
        #> fold add_patterns args
blanchet@49266
   224
      end
blanchet@49317
   225
  in [] |> fold add_patterns ts |> sort string_ord end
blanchet@49266
   226
blanchet@49266
   227
fun is_likely_tautology th =
blanchet@49317
   228
  null (interesting_terms_types_and_classes 0 ~1 [prop_of th]) andalso
blanchet@49266
   229
  not (Thm.eq_thm_prop (@{thm ext}, th))
blanchet@49266
   230
blanchet@49330
   231
(* ### FIXME: optimize *)
blanchet@49330
   232
fun is_too_meta th =
blanchet@49330
   233
  fastype_of (Object_Logic.atomize_term (theory_of_thm th) (prop_of th))
blanchet@49330
   234
  <> @{typ bool}
blanchet@49266
   235
blanchet@49266
   236
fun theory_ord p =
blanchet@49330
   237
  if Theory.eq_thy p then
blanchet@49330
   238
    EQUAL
blanchet@49330
   239
  else if Theory.subthy p then
blanchet@49330
   240
    LESS
blanchet@49330
   241
  else if Theory.subthy (swap p) then
blanchet@49330
   242
    GREATER
blanchet@49330
   243
  else case int_ord (pairself (length o Theory.ancestors_of) p) of
blanchet@49330
   244
    EQUAL => string_ord (pairself Context.theory_name p)
blanchet@49330
   245
  | order => order
blanchet@49266
   246
blanchet@49266
   247
val thm_ord = theory_ord o pairself theory_of_thm
blanchet@49266
   248
blanchet@49330
   249
fun thy_map_from_facts ths =
blanchet@49330
   250
  ths |> sort (thm_ord o swap o pairself snd)
blanchet@49330
   251
      |> map (snd #> `(theory_of_thm #> Context.theory_name))
blanchet@49330
   252
      |> AList.coalesce (op =)
blanchet@49330
   253
      |> map (apsnd (map Thm.get_name_hint))
blanchet@49266
   254
blanchet@49318
   255
fun has_thy thy th =
blanchet@49318
   256
  Context.theory_name thy = Context.theory_name (theory_of_thm th)
blanchet@49266
   257
blanchet@49330
   258
fun parent_facts thy thy_map =
blanchet@49318
   259
  let
blanchet@49318
   260
    fun add_last thy =
blanchet@49330
   261
      case AList.lookup (op =) thy_map (Context.theory_name thy) of
blanchet@49318
   262
        SOME (last_fact :: _) => insert (op =) last_fact
blanchet@49318
   263
      | _ => add_parent thy
blanchet@49318
   264
    and add_parent thy = fold add_last (Theory.parents_of thy)
blanchet@49318
   265
  in add_parent thy [] end
blanchet@49266
   266
blanchet@49266
   267
fun is_exists (s, _) = (s = @{const_name Ex} orelse s = @{const_name Ex1})
blanchet@49266
   268
blanchet@49312
   269
val term_max_depth = 1
blanchet@49312
   270
val type_max_depth = 1
blanchet@49266
   271
blanchet@49266
   272
(* TODO: Generate type classes for types? *)
blanchet@49317
   273
fun features_of thy status ts =
blanchet@49318
   274
  thy_feature_name_of (Context.theory_name thy) ::
blanchet@49317
   275
  interesting_terms_types_and_classes term_max_depth type_max_depth ts
blanchet@49317
   276
  |> exists (not o is_lambda_free) ts ? cons "lambdas"
blanchet@49317
   277
  |> exists (exists_Const is_exists) ts ? cons "skolems"
blanchet@49317
   278
  |> exists (not o is_fo_term thy) ts ? cons "ho"
blanchet@49317
   279
  |> (case status of
blanchet@49317
   280
        General => I
blanchet@49317
   281
      | Induction => cons "induction"
blanchet@49317
   282
      | Intro => cons "intro"
blanchet@49317
   283
      | Inductive => cons "inductive"
blanchet@49317
   284
      | Elim => cons "elim"
blanchet@49317
   285
      | Simp => cons "simp"
blanchet@49317
   286
      | Def => cons "def")
blanchet@49266
   287
blanchet@49266
   288
fun isabelle_dependencies_of all_facts =
blanchet@49318
   289
  thms_in_proof (SOME all_facts) #> sort string_ord
blanchet@49266
   290
blanchet@49266
   291
val freezeT = Type.legacy_freeze_type
blanchet@49266
   292
blanchet@49266
   293
fun freeze (t $ u) = freeze t $ freeze u
blanchet@49266
   294
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
blanchet@49266
   295
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
blanchet@49266
   296
  | freeze (Const (s, T)) = Const (s, freezeT T)
blanchet@49266
   297
  | freeze (Free (s, T)) = Free (s, freezeT T)
blanchet@49266
   298
  | freeze t = t
blanchet@49266
   299
blanchet@49266
   300
fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init
blanchet@49266
   301
blanchet@49266
   302
fun run_prover ctxt (params as {provers, ...}) facts goal =
blanchet@49266
   303
  let
blanchet@49266
   304
    val problem =
blanchet@49266
   305
      {state = Proof.init ctxt, goal = goal, subgoal = 1, subgoal_count = 1,
blanchet@49304
   306
       facts = facts |> map (apfst (apfst (fn name => name ())))
blanchet@49304
   307
                     |> map Sledgehammer_Provers.Untranslated_Fact}
blanchet@49266
   308
    val prover =
blanchet@49266
   309
      Sledgehammer_Minimize.get_minimizing_prover ctxt
blanchet@49266
   310
          Sledgehammer_Provers.Normal (hd provers)
blanchet@49266
   311
  in prover params (K (K (K ""))) problem end
blanchet@49266
   312
blanchet@49330
   313
fun accessibility_of thy thy_map =
blanchet@49330
   314
  case AList.lookup (op =) thy_map (Context.theory_name thy) of
blanchet@49318
   315
    SOME (fact :: _) => [fact]
blanchet@49330
   316
  | _ => parent_facts thy thy_map
blanchet@49318
   317
blanchet@49319
   318
val thy_name_of_fact = hd o Long_Name.explode
blanchet@49266
   319
blanchet@49266
   320
blanchet@49317
   321
(*** Low-level communication with MaSh ***)
blanchet@49317
   322
blanchet@49326
   323
fun run_mash ctxt save write_cmds read_preds =
blanchet@49326
   324
  let
blanchet@49326
   325
    val temp_dir = getenv "ISABELLE_TMP"
blanchet@49326
   326
    val serial = serial_string ()
blanchet@49326
   327
    val cmd_file = temp_dir ^ "/mash_commands." ^ serial
blanchet@49326
   328
    val cmd_path = Path.explode cmd_file
blanchet@49326
   329
    val pred_file = temp_dir ^ "/mash_preds." ^ serial
blanchet@49326
   330
    val log_file = temp_dir ^ "/mash_log." ^ serial
blanchet@49326
   331
    val command =
blanchet@49329
   332
      mash_home () ^ "/mash.py --quiet --inputFile " ^ cmd_file ^
blanchet@49329
   333
      " --outputDir " ^ mash_state_dir () ^ " --predictions " ^ pred_file ^
blanchet@49328
   334
      " --log " ^ log_file ^ " --numberOfPredictions 1000" ^
blanchet@49329
   335
      (if save then " --saveModel" else "")
blanchet@49326
   336
    val _ = File.write cmd_path ""
blanchet@49326
   337
    val _ = write_cmds (File.append cmd_path)
blanchet@49326
   338
    val _ = trace_msg ctxt (fn () => "  running " ^ command)
blanchet@49326
   339
    val _ = Isabelle_System.bash command
blanchet@49326
   340
  in read_preds (fn () => File.read_lines (Path.explode pred_file)) end
blanchet@49326
   341
blanchet@49326
   342
fun str_of_update (fact, access, feats, deps) =
blanchet@49326
   343
  "! " ^ escape_meta fact ^ ": " ^ escape_metas access ^ "; " ^
blanchet@49326
   344
  escape_metas feats ^ "; " ^ escape_metas deps ^ "\n"
blanchet@49326
   345
blanchet@49326
   346
fun str_of_query (access, feats) =
blanchet@49326
   347
  "? " ^ escape_metas access ^ "; " ^ escape_metas feats
blanchet@49326
   348
blanchet@49323
   349
fun mash_RESET ctxt =
blanchet@49329
   350
  let val path = mash_state_dir () |> Path.explode in
blanchet@49324
   351
    trace_msg ctxt (K "MaSh RESET");
blanchet@49324
   352
    File.fold_dir (fn file => fn () =>
blanchet@49324
   353
                      File.rm (Path.append path (Path.basic file)))
blanchet@49324
   354
                  path ()
blanchet@49324
   355
  end
blanchet@49317
   356
blanchet@49324
   357
fun mash_ADD _ [] = ()
blanchet@49326
   358
  | mash_ADD ctxt upds =
blanchet@49326
   359
    (trace_msg ctxt (fn () => "MaSh ADD " ^ space_implode " " (map #1 upds));
blanchet@49326
   360
     run_mash ctxt true (fn append => List.app (append o str_of_update) upds)
blanchet@49326
   361
              (K ()))
blanchet@49317
   362
blanchet@49323
   363
fun mash_DEL ctxt facts feats =
blanchet@49323
   364
  trace_msg ctxt (fn () =>
blanchet@49323
   365
      "MaSh DEL " ^ escape_metas facts ^ "; " ^ escape_metas feats)
blanchet@49317
   366
blanchet@49326
   367
fun mash_QUERY ctxt (query as (_, feats)) =
blanchet@49329
   368
  (trace_msg ctxt (fn () => "MaSh QUERY " ^ space_implode " " feats);
blanchet@49326
   369
   run_mash ctxt false (fn append => append (str_of_query query))
blanchet@49326
   370
                 (fn preds => snd (extract_query (List.last (preds ()))))
blanchet@49326
   371
   handle List.Empty => [])
blanchet@49317
   372
blanchet@49317
   373
blanchet@49266
   374
(*** High-level communication with MaSh ***)
blanchet@49266
   375
blanchet@49316
   376
type mash_state =
blanchet@49330
   377
  {dirty_thys : string list,
blanchet@49330
   378
   thy_map : (string * string list) list}
blanchet@49264
   379
blanchet@49330
   380
val empty_state = {dirty_thys = [], thy_map = []}
blanchet@49316
   381
blanchet@49316
   382
local
blanchet@49316
   383
blanchet@49316
   384
fun mash_load (state as (true, _)) = state
blanchet@49316
   385
  | mash_load _ =
blanchet@49324
   386
    let val path = mash_state_path () in
blanchet@49317
   387
      (true,
blanchet@49317
   388
       case try File.read_lines path of
blanchet@49323
   389
         SOME (dirty_line :: facts_lines) =>
blanchet@49317
   390
         let
blanchet@49317
   391
           fun add_facts_line line =
blanchet@49323
   392
             case unescape_metas line of
blanchet@49330
   393
               thy :: facts => cons (thy, facts)
blanchet@49317
   394
             | _ => I (* shouldn't happen *)
blanchet@49317
   395
         in
blanchet@49330
   396
           {dirty_thys = unescape_metas dirty_line,
blanchet@49330
   397
            thy_map = fold_rev add_facts_line facts_lines []}
blanchet@49317
   398
         end
blanchet@49319
   399
       | _ => empty_state)
blanchet@49317
   400
    end
blanchet@49316
   401
blanchet@49330
   402
fun mash_save ({dirty_thys, thy_map} : mash_state) =
blanchet@49316
   403
  let
blanchet@49324
   404
    val path = mash_state_path ()
blanchet@49330
   405
    val dirty_line = escape_metas dirty_thys ^ "\n"
blanchet@49318
   406
    fun fact_line_for (thy, facts) = escape_metas (thy :: facts) ^ "\n"
blanchet@49316
   407
  in
blanchet@49323
   408
    File.write path dirty_line;
blanchet@49330
   409
    List.app (File.append path o fact_line_for) thy_map
blanchet@49316
   410
  end
blanchet@49316
   411
blanchet@49317
   412
val global_state =
blanchet@49319
   413
  Synchronized.var "Sledgehammer_Filter_MaSh.global_state" (false, empty_state)
blanchet@49316
   414
blanchet@49316
   415
in
blanchet@49316
   416
blanchet@49321
   417
fun mash_map f =
blanchet@49317
   418
  Synchronized.change global_state (mash_load ##> (f #> tap mash_save))
blanchet@49316
   419
blanchet@49319
   420
fun mash_get () = Synchronized.change_result global_state (mash_load #> `snd)
blanchet@49317
   421
blanchet@49323
   422
fun mash_reset ctxt =
blanchet@49317
   423
  Synchronized.change global_state (fn _ =>
blanchet@49324
   424
      (mash_RESET ctxt; File.write (mash_state_path ()) "";
blanchet@49323
   425
       (true, empty_state)))
blanchet@49316
   426
blanchet@49316
   427
end
blanchet@49316
   428
blanchet@49323
   429
fun mash_can_suggest_facts (_ : Proof.context) =
blanchet@49330
   430
  mash_home () <> "" andalso not (null (#thy_map (mash_get ())))
blanchet@49264
   431
blanchet@49326
   432
fun mash_suggest_facts ctxt params prover hyp_ts concl_t facts =
blanchet@49316
   433
  let
blanchet@49317
   434
    val thy = Proof_Context.theory_of ctxt
blanchet@49330
   435
    val thy_map = #thy_map (mash_get ())
blanchet@49330
   436
    val access = accessibility_of thy thy_map
blanchet@49317
   437
    val feats = features_of thy General (concl_t :: hyp_ts)
blanchet@49326
   438
    val suggs = mash_QUERY ctxt (access, feats)
blanchet@49326
   439
  in suggested_facts suggs facts end
blanchet@49264
   440
blanchet@49330
   441
fun is_fact_in_thy_map thy_map fact =
blanchet@49330
   442
  case AList.lookup (op =) thy_map (thy_name_of_fact fact) of
blanchet@49319
   443
    SOME facts => member (op =) facts fact
blanchet@49319
   444
  | NONE => false
blanchet@49319
   445
blanchet@49321
   446
fun zip_facts news [] = news
blanchet@49321
   447
  | zip_facts [] olds = olds
blanchet@49321
   448
  | zip_facts (new :: news) (old :: olds) =
blanchet@49321
   449
    if new = old then
blanchet@49321
   450
      new :: zip_facts news olds
blanchet@49321
   451
    else if member (op =) news old then
blanchet@49321
   452
      old :: zip_facts (filter_out (curry (op =) old) news) olds
blanchet@49321
   453
    else if member (op =) olds new then
blanchet@49321
   454
      new :: zip_facts news (filter_out (curry (op =) new) olds)
blanchet@49321
   455
    else
blanchet@49321
   456
      new :: old :: zip_facts news olds
blanchet@49321
   457
blanchet@49330
   458
fun add_thy_map_from_thys [] old = old
blanchet@49330
   459
  | add_thy_map_from_thys new old =
blanchet@49330
   460
    let
blanchet@49330
   461
      fun add_thy (thy, new_facts) =
blanchet@49330
   462
        case AList.lookup (op =) old thy of
blanchet@49330
   463
          SOME old_facts =>
blanchet@49330
   464
          AList.update (op =) (thy, zip_facts old_facts new_facts)
blanchet@49330
   465
        | NONE => cons (thy, new_facts)
blanchet@49330
   466
    in old |> fold add_thy new end
blanchet@49321
   467
blanchet@49323
   468
fun mash_learn_thy ctxt thy timeout =
blanchet@49319
   469
  let
blanchet@49319
   470
    val css_table = Sledgehammer_Fact.clasimpset_rule_table_of ctxt
blanchet@49330
   471
    val facts = all_facts_of thy css_table
blanchet@49330
   472
    val {thy_map, ...} = mash_get ()
blanchet@49330
   473
    fun is_old (_, th) = is_fact_in_thy_map thy_map (Thm.get_name_hint th)
blanchet@49319
   474
    val (old_facts, new_facts) =
blanchet@49319
   475
      facts |> List.partition is_old ||> sort (thm_ord o pairself snd)
blanchet@49323
   476
  in
blanchet@49323
   477
    if null new_facts then
blanchet@49323
   478
      ()
blanchet@49323
   479
    else
blanchet@49319
   480
      let
blanchet@49323
   481
        val ths = facts |> map snd
blanchet@49330
   482
        val all_names =
blanchet@49330
   483
          ths |> filter_out (is_likely_tautology orf is_too_meta)
blanchet@49330
   484
              |> map Thm.get_name_hint
blanchet@49326
   485
        fun do_fact ((_, (_, status)), th) (prevs, upds) =
blanchet@49323
   486
          let
blanchet@49323
   487
            val name = Thm.get_name_hint th
blanchet@49323
   488
            val feats = features_of thy status [prop_of th]
blanchet@49323
   489
            val deps = isabelle_dependencies_of all_names th
blanchet@49326
   490
            val upd = (name, prevs, feats, deps)
blanchet@49326
   491
          in ([name], upd :: upds) end
blanchet@49330
   492
        val parents = parent_facts thy thy_map
blanchet@49326
   493
        val (_, upds) = (parents, []) |> fold do_fact new_facts
blanchet@49330
   494
        val new_thy_map = new_facts |> thy_map_from_facts
blanchet@49330
   495
        fun trans {dirty_thys, thy_map} =
blanchet@49326
   496
          (mash_ADD ctxt (rev upds);
blanchet@49323
   497
           {dirty_thys = dirty_thys,
blanchet@49330
   498
            thy_map = thy_map |> add_thy_map_from_thys new_thy_map})
blanchet@49323
   499
      in mash_map trans end
blanchet@49323
   500
  end
blanchet@49319
   501
blanchet@49324
   502
fun mash_learn_proof ctxt thy t ths =
blanchet@49330
   503
  mash_map (fn state as {dirty_thys, thy_map} =>
blanchet@49324
   504
    let val deps = ths |> map Thm.get_name_hint in
blanchet@49330
   505
      if forall (is_fact_in_thy_map thy_map) deps then
blanchet@49324
   506
        let
blanchet@49324
   507
          val fact = ATP_Util.timestamp () (* should be fairly fresh *)
blanchet@49330
   508
          val access = accessibility_of thy thy_map
blanchet@49324
   509
          val feats = features_of thy General [t]
blanchet@49324
   510
        in
blanchet@49324
   511
          mash_ADD ctxt [(fact, access, feats, deps)];
blanchet@49330
   512
          {dirty_thys = dirty_thys, thy_map = thy_map}
blanchet@49324
   513
        end
blanchet@49324
   514
      else
blanchet@49324
   515
        state
blanchet@49324
   516
    end)
blanchet@49264
   517
blanchet@49329
   518
fun relevant_facts ctxt (params as {fact_filter, ...}) prover max_facts
blanchet@49313
   519
        ({add, only, ...} : fact_override) hyp_ts concl_t facts =
blanchet@49329
   520
  if not (subset (op =) (the_list fact_filter, fact_filters)) then
blanchet@49329
   521
    error ("Unknown fact filter: " ^ quote (the fact_filter) ^ ".")
blanchet@49329
   522
  else if only then
blanchet@49304
   523
    facts
blanchet@49308
   524
  else if max_facts <= 0 then
blanchet@49303
   525
    []
blanchet@49303
   526
  else
blanchet@49303
   527
    let
blanchet@49329
   528
      val fact_filter =
blanchet@49329
   529
        case fact_filter of
blanchet@49329
   530
          SOME ff => ff
blanchet@49330
   531
        | NONE => if mash_can_suggest_facts ctxt then meshN else iterN
blanchet@49303
   532
      val add_ths = Attrib.eval_thms ctxt add
blanchet@49307
   533
      fun prepend_facts ths accepts =
blanchet@49303
   534
        ((facts |> filter (member Thm.eq_thm_prop ths o snd)) @
blanchet@49307
   535
         (accepts |> filter_out (member Thm.eq_thm_prop ths o snd)))
blanchet@49308
   536
        |> take max_facts
blanchet@49329
   537
      fun iter () =
blanchet@49313
   538
        iterative_relevant_facts ctxt params prover max_facts NONE hyp_ts
blanchet@49313
   539
                                 concl_t facts
blanchet@49329
   540
        |> (fn facts => (facts, SOME (length facts)))
blanchet@49329
   541
      fun mash () =
blanchet@49329
   542
        (facts |> mash_suggest_facts ctxt params prover hyp_ts concl_t, NONE)
blanchet@49329
   543
      val mess =
blanchet@49329
   544
        [] |> (if fact_filter <> mashN then cons (iter ()) else I)
blanchet@49329
   545
           |> (if fact_filter <> iterN then cons (mash ()) else I)
blanchet@49303
   546
    in
blanchet@49328
   547
      mesh_facts max_facts mess
blanchet@49303
   548
      |> not (null add_ths) ? prepend_facts add_ths
blanchet@49303
   549
    end
blanchet@49303
   550
blanchet@49263
   551
end;