<commit_before>(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mash.ML
    Author:     <NAME>, <NAME>

Sledgehammer's machine-learning-based relevance filter (MaSh).
*)

signature SLEDGEHAMMER_MASH =
sig
  type stature = ATP_Problem_Generate.stature
  type fact = Sledgehammer_Fact.fact
  type fact_override = Sledgehammer_Fact.fact_override
  type params = Sledgehammer_Provers.params
  type relevance_fudge = Sledgehammer_Provers.relevance_fudge
  type prover_result = Sledgehammer_Provers.prover_result

  val trace : bool Config.T
  val MaShN : string
  val mepoN : string
  val mashN : string
  val meshN : string
  val unlearnN : string
  val learn_isarN : string
  val learn_atpN : string
  val relearn_isarN : string
  val relearn_atpN : string
  val fact_filters : string list
  val escape_meta : string -> string
  val escape_metas : string list -> string
  val unescape_meta : string -> string
  val unescape_metas : string -> string list
  val extract_query : string -> string * (string * real) list
  val mash_CLEAR : Proof.context -> unit
  val mash_ADD :
    Proof.context -> bool
    -> (string * string list * string list * string list) list -> unit
  val mash_REPROVE :
    Proof.context -> bool -> (string * string list) list -> unit
  val mash_QUERY :
    Proof.context -> bool -> int -> string list * string list
    -> (string * real) list
  val mash_unlearn : Proof.context -> unit
  val nickname_of : thm -> string
  val suggested_facts :
    (string * 'a) list -> ('b * thm) list -> (('b * thm) * 'a) list
  val mesh_facts :
    int -> ((('a * thm) * real) list * ('a * thm) list) list -> ('a * thm) list
  val theory_ord : theory * theory -> order
  val thm_ord : thm * thm -> order
  val goal_of_thm : theory -> thm -> thm
  val run_prover_for_mash :
    Proof.context -> params -> string -> fact list -> thm -> prover_result
  val features_of :
    Proof.context -> string -> theory -> stature -> term list -> string list
  val isar_dependencies_of : unit Symtab.table -> thm -> string list option
  val atp_dependencies_of :
    Proof.context -> params -> string -> int -> fact list -> unit Symtab.table
    -> thm -> bool * string list option
  val mash_suggested_facts :
    Proof.context -> params -> string -> int -> term list -> term
    -> fact list -> (fact * real) list * fact list
  val mash_learn_proof :
    Proof.context -> params -> string -> term -> ('a * thm) list -> thm list
    -> unit
  val mash_learn :
    Proof.context -> params -> fact_override -> thm list -> bool -> unit
  val is_mash_enabled : unit -> bool
  val mash_can_suggest_facts : Proof.context -> bool
  val relevant_facts :
    Proof.context -> params -> string -> int -> fact_override -> term list
    -> term -> fact list -> fact list
  val kill_learners : unit -> unit
  val running_learners : unit -> unit
end;

structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
struct

open ATP_Util
open ATP_Problem_Generate
open Sledgehammer_Util
open Sledgehammer_Fact
open Sledgehammer_Provers
open Sledgehammer_Minimize
open Sledgehammer_MePo

val trace =
  Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()

val MaShN = "MaSh"

val mepoN = "mepo"
val mashN = "mash"
val meshN = "mesh"

val fact_filters = [meshN, mepoN, mashN]

val unlearnN = "unlearn"
val learn_isarN = "learn_isar"
val learn_atpN = "learn_atp"
val relearn_isarN = "relearn_isar"
val relearn_atpN = "relearn_atp"

fun mash_model_dir () =
  Path.explode "$ISABELLE_HOME_USER/mash" |> tap Isabelle_System.mkdir
val mash_state_dir = mash_model_dir
fun mash_state_file () = Path.append (mash_state_dir ()) (Path.explode "state")


(*** Low-level communication with MaSh ***)

fun wipe_out_file file = (try (File.rm o Path.explode) file; ())

fun write_file banner (xs, f) path =
  (case banner of SOME s => File.write path s | NONE => ();
   xs |> chunk_list 500
      |> List.app (File.append path o space_implode "" o map f))
  handle IO.Io _ => ()

fun run_mash_tool ctxt overlord save max_suggs write_cmds read_suggs =
  let
    val (temp_dir, serial) =
      if overlord then (getenv "ISABELLE_HOME_USER", "")
      else (getenv "ISABELLE_TMP", serial_string ())
    val log_file = if overlord then temp_dir ^ "/mash_log" else "/dev/null"
    val err_file = temp_dir ^ "/mash_err" ^ serial
    val sugg_file = temp_dir ^ "/mash_suggs" ^ serial
    val sugg_path = Path.explode sugg_file
    val cmd_file = temp_dir ^ "/mash_commands" ^ serial
    val cmd_path = Path.explode cmd_file
    val core =
      "--inputFile " ^ cmd_file ^ " --predictions " ^ sugg_file ^
      " --numberOfPredictions " ^ string_of_int max_suggs ^
      (if save then " --saveModel" else "")
    val command =
      "\"$ISABELLE_SLEDGEHAMMER_MASH/src/mash.py\" --quiet --outputDir " ^
      File.shell_path (mash_model_dir ()) ^ " --log " ^ log_file ^ " " ^ core ^
      " >& " ^ err_file
      |> tap (fn _ => trace_msg ctxt (fn () =>
             case try File.read (Path.explode err_file) of
               NONE => "Done"
             | SOME "" => "Done"
             | SOME s => "Error: " ^ elide_string 1000 s))
    fun run_on () =
      (Isabelle_System.bash command;
       read_suggs (fn () => try File.read_lines sugg_path |> these))
    fun clean_up () =
      if overlord then ()
      else List.app wipe_out_file [err_file, sugg_file, cmd_file]
  in
    write_file (SOME "") ([], K "") sugg_path;
    write_file (SOME "") write_cmds cmd_path;
    trace_msg ctxt (fn () => "Running " ^ command);
    with_cleanup clean_up run_on ()
  end

fun meta_char c =
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse
     c = #")" orelse c = #"," then
    String.str c
  else
    (* fixed width, in case more digits follow *)
    "%" ^ stringN_of_int 3 (Char.ord c)

fun unmeta_chars accum [] = String.implode (rev accum)
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
    (case Int.fromString (String.implode [d1, d2, d3]) of
       SOME n => unmeta_chars (Char.chr n :: accum) cs
     | NONE => "" (* error *))
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs

val escape_meta = String.translate meta_char
val escape_metas = map escape_meta #> space_implode " "
val unescape_meta = String.explode #> unmeta_chars []
val unescape_metas =
  space_explode " " #> filter_out (curry (op =) "") #> map unescape_meta

fun str_of_add (name, parents, feats, deps) =
  "! " ^ escape_meta name ^ ": " ^ escape_metas parents ^ "; " ^
  escape_metas feats ^ "; " ^ escape_metas deps ^ "\n"

fun str_of_reprove (name, deps) =
  "p " ^ escape_meta name ^ ": " ^ escape_metas deps ^ "\n"

fun str_of_query (parents, feats) =
  "? " ^ escape_metas parents ^ "; " ^ escape_metas feats ^ "\n"

fun extract_suggestion sugg =
  case space_explode "=" sugg of
    [name, weight] =>
    SOME (unescape_meta name, Real.fromString weight |> the_default 0.0)
  | _ => NONE

fun extract_query line =
  case space_explode ":" line of
    [goal, suggs] =>
    (unescape_meta goal,
     map_filter extract_suggestion (space_explode " " suggs))
  | _ => ("", [])

fun mash_CLEAR ctxt =
  let val path = mash_model_dir () in
    trace_msg ctxt (K "MaSh CLEAR");
    try (File.fold_dir (fn file => fn _ =>
                           try File.rm (Path.append path (Path.basic file)))
                       path) NONE;
    ()
  end

fun mash_ADD _ _ [] = ()
  | mash_ADD ctxt overlord adds =
    (trace_msg ctxt (fn () => "MaSh ADD " ^
         elide_string 1000 (space_implode " " (map #1 adds)));
     run_mash_tool ctxt overlord true 0 (adds, str_of_add) (K ()))

fun mash_REPROVE _ _ [] = ()
  | mash_REPROVE ctxt overlord reps =
    (trace_msg ctxt (fn () => "MaSh REPROVE " ^
         elide_string 1000 (space_implode " " (map #1 reps)));
     run_mash_tool ctxt overlord true 0 (reps, str_of_reprove) (K ()))

fun mash_QUERY ctxt overlord max_suggs (query as (_, feats)) =
  (trace_msg ctxt (fn () => "MaSh QUERY " ^ space_implode " " feats);
   run_mash_tool ctxt overlord false max_suggs
       ([query], str_of_query)
       (fn suggs =>
           case suggs () of
             [] => []
           | suggs => snd (extract_query (List.last suggs)))
   handle List.Empty => [])


(*** Middle-level communication with MaSh ***)

datatype proof_kind = Isar_Proof | ATP_Proof | Isar_Proof_wegen_ATP_Flop

fun str_of_proof_kind Isar_Proof = "i"
  | str_of_proof_kind ATP_Proof = "a"
  | str_of_proof_kind Isar_Proof_wegen_ATP_Flop = "x"

fun proof_kind_of_str "i" = Isar_Proof
  | proof_kind_of_str "a" = ATP_Proof
  | proof_kind_of_str "x" = Isar_Proof_wegen_ATP_Flop

(* FIXME: Here a "Graph.update_node" function would be useful *)
fun update_fact_graph_node (name, kind) =
  Graph.default_node (name, Isar_Proof)
  #> kind <> Isar_Proof ? Graph.map_node name (K kind)

fun try_graph ctxt when def f =
  f ()
  handle Graph.CYCLES (cycle :: _) =>
         (trace_msg ctxt (fn () =>
              "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
       | Graph.DUP name =>
         (trace_msg ctxt (fn () =>
              "Duplicate fact " ^ quote name ^ " when " ^ when); def)
       | Graph.UNDEF name =>
         (trace_msg ctxt (fn () =>
              "Unknown fact " ^ quote name ^ " when " ^ when); def)
       | exn =>
         if Exn.is_interrupt exn then
           reraise exn
         else
           (trace_msg ctxt (fn () =>
                "Internal error when " ^ when ^ ":\n" ^
                ML_Compiler.exn_message exn); def)

fun graph_info G =
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^
  " edge(s), " ^
  string_of_int (length (Graph.minimals G)) ^ " minimal, " ^
  string_of_int (length (Graph.maximals G)) ^ " maximal"

type mash_state = {fact_G : unit Graph.T, dirty : string list option}

val empty_state = {fact_G = Graph.empty, dirty = SOME []}

local

val version = "*** MaSh 0.1 ***"

fun extract_node line =
  case space_explode ":" line of
    [head, parents] =>
    (case space_explode " " head of
       [kind, name] =>
       SOME (unescape_meta name, unescape_metas parents,
             try proof_kind_of_str kind |> the_default Isar_Proof)
     | _ => NONE)
  | _ => NONE

fun load _ (state as (true, _)) = state
  | load ctxt _ =
    let val path = mash_state_file () in
      (true,
       case try File.read_lines path of
         SOME (version' :: node_lines) =>
         let
           fun add_edge_to name parent =
             Graph.default_node (parent, Isar_Proof)
             #> Graph.add_edge (parent, name)
           fun add_node line =
             case extract_node line of
               NONE => I (* shouldn't happen *)
             | SOME (name, parents, kind) =>
               update_fact_graph_node (name, kind)
               #> fold (add_edge_to name) parents
           val fact_G =
             try_graph ctxt "loading state" Graph.empty (fn () =>
                 Graph.empty |> version' = version ? fold add_node node_lines)
         in
           trace_msg ctxt (fn () =>
               "Loaded fact graph (" ^ graph_info fact_G ^ ")");
           {fact_G = fact_G, dirty = SOME []}
         end
       | _ => empty_state)
    end

fun save _ (state as {dirty = SOME [], ...}) = state
  | save ctxt {fact_G, dirty} =
    let
      fun str_of_entry (name, parents, kind) =
        str_of_proof_kind kind ^ " " ^ escape_meta name ^ ": " ^
        escape_metas parents ^ "\n"
      fun append_entry (name, (kind, (parents, _))) =
        cons (name, Graph.Keys.dest parents, kind)
      val (banner, entries) =
        case dirty of
          SOME names =>
          (NONE, fold (append_entry o Graph.get_entry fact_G) names [])
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry fact_G [])
    in
      write_file banner (entries, str_of_entry) (mash_state_file ());
      trace_msg ctxt (fn () =>
          "Saved fact graph (" ^ graph_info fact_G ^
          (case dirty of
             SOME dirty =>
             "; " ^ string_of_int (length dirty) ^ " dirty fact(s)"
           | _ => "") ^  ")");
      {fact_G = fact_G, dirty = SOME []}
    end

val global_state =
  Synchronized.var "Sledgehammer_MaSh.global_state" (false, empty_state)

in

fun mash_map ctxt f =
  Synchronized.change global_state (load ctxt ##> (f #> save ctxt))

fun mash_peek ctxt f =
  Synchronized.change_result global_state (load ctxt #> `snd #>> f)

fun mash_get ctxt =
  Synchronized.change_result global_state (load ctxt #> `snd)

fun mash_unlearn ctxt =
  Synchronized.change global_state (fn _ =>
      (mash_CLEAR ctxt; (* also removes the state file *)
       (true, empty_state)))

end


(*** Isabelle helpers ***)

fun parent_of_local_thm th =
  let
    val thy = th |> Thm.theory_of_thm
    val facts = thy |> Global_Theory.facts_of
    val space = facts |> Facts.space_of
    fun id_of s = #id (Name_Space.the_entry space s)
    fun max_id (s', _) (s, id) =
      let val id' = id_of s' in if id > id' then (s, id) else (s', id') end
  in ("", ~1) |> Facts.fold_static max_id facts |> fst end

val local_prefix = "local" ^ Long_Name.separator

fun nickname_of th =
  if Thm.has_name_hint th then
    let val hint = Thm.get_name_hint th in
      (* FIXME: There must be a better way to detect local facts. *)
      case try (unprefix local_prefix) hint of
        SOME suf =>
        parent_of_local_thm th ^ Long_Name.separator ^ Long_Name.separator ^ suf
      | NONE => hint
    end
  else
    backquote_thm (Proof_Context.init_global (Thm.theory_of_thm th)) th

fun suggested_facts suggs facts =
  let
    fun add_fact (fact as (_, th)) = Symtab.default (nickname_of th, fact)
    val tab = Symtab.empty |> fold add_fact facts
    fun find_sugg (name, weight) =
      Symtab.lookup tab name |> Option.map (rpair weight)
  in map_filter find_sugg suggs end

fun sum_avg [] = 0
  | sum_avg xs =
    Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs

fun normalize_scores [] = []
  | normalize_scores ((fact, score) :: tail) =
    (fact, 1.0) :: map (apsnd (curry Real.* (1.0 / score))) tail

fun mesh_facts max_facts [(sels, unks)] =
    map fst (take max_facts sels) @ take (max_facts - length sels) unks
  | mesh_facts max_facts mess =
    let
      val mess = mess |> map (apfst (normalize_scores #> `length))
      val fact_eq = Thm.eq_thm o pairself snd
      fun score_at sels = try (nth sels) #> Option.map snd
      fun score_in fact ((sel_len, sels), unks) =
        case find_index (curry fact_eq fact o fst) sels of
          ~1 => (case find_index (curry fact_eq fact) unks of
                   ~1 => score_at sels sel_len
                 | _ => NONE)
        | rank => score_at sels rank
      fun weight_of fact = mess |> map_filter (score_in fact) |> sum_avg
      val facts =
        fold (union fact_eq o map fst o take max_facts o snd o fst) mess []
    in
      facts |> map (`weight_of) |> sort (int_ord o swap o pairself fst)
            |> map snd |> take max_facts
    end

val thy_feature_name_of = prefix "y"
val const_name_of = prefix "c"
val type_name_of = prefix "t"
val class_name_of = prefix "s"

fun theory_ord p =
  if Theory.eq_thy p then
    EQUAL
  else if Theory.subthy p then
    LESS
  else if Theory.subthy (swap p) then
    GREATER
  else case int_ord (pairself (length o Theory.ancestors_of) p) of
    EQUAL => string_ord (pairself Context.theory_name p)
  | order => order

val thm_ord = theory_ord o pairself theory_of_thm

val freezeT = Type.legacy_freeze_type

fun freeze (t $ u) = freeze t $ freeze u
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
  | freeze (Const (s, T)) = Const (s, freezeT T)
  | freeze (Free (s, T)) = Free (s, freezeT T)
  | freeze t = t

fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init

fun run_prover_for_mash ctxt params prover facts goal =
  let
    val problem =
      {state = Proof.init ctxt, goal = goal, subgoal = 1, subgoal_count = 1,
       facts = facts |> map (apfst (apfst (fn name => name ())))
                     |> map Untranslated_Fact}
  in
    get_minimizing_prover ctxt MaSh (K (K ())) prover params (K (K (K "")))
                          problem
  end

val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]

val logical_consts =
  [@{const_name prop}, @{const_name Pure.conjunction}] @ atp_logical_consts

fun interesting_terms_types_and_classes ctxt prover term_max_depth
                                        type_max_depth ts =
  let
    fun is_bad_const (x as (s, _)) args =
      member (op =) logical_consts s orelse
      fst (is_built_in_const_for_prover ctxt prover x args)
    fun add_classes @{sort type} = I
      | add_classes S = union (op =) (map class_name_of S)
    fun do_add_type (Type (s, Ts)) =
        (not (member (op =) bad_types s) ? insert (op =) (type_name_of s))
        #> fold do_add_type Ts
      | do_add_type (TFree (_, S)) = add_classes S
      | do_add_type (TVar (_, S)) = add_classes S
    fun add_type T = type_max_depth >= 0 ? do_add_type T
    fun patternify_term _ ~1 _ = []
      | patternify_term args _ (Const (x as (s, _))) =
        if is_bad_const x args then [] else [const_name_of s]
      | patternify_term _ 0 _ = []
      | patternify_term args depth (t $ u) =
        let
          val ps = patternify_term (u :: args) depth t
          val qs = "" :: patternify_term [] (depth - 1) u
        in map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs end
      | patternify_term _ _ _ = []
    val add_term_pattern = union (op =) oo patternify_term []
    fun add_term_patterns ~1 _ = I
      | add_term_patterns depth t =
        add_term_pattern depth t #> add_term_patterns (depth - 1) t
    val add_term = add_term_patterns term_max_depth
    fun add_patterns t =
      let val (head, args) = strip_comb t in
        (case head of
           Const (_, T) => add_term t #> add_type T
         | Free (_, T) => add_type T
         | Var (_, T) => add_type T
         | Abs (_, T, body) => add_type T #> add_patterns body
         | _ => I)
        #> fold add_patterns args
      end
  in [] |> fold add_patterns ts end

fun is_exists (s, _) = (s = @{const_name Ex} orelse s = @{const_name Ex1})

val term_max_depth = 2
val type_max_depth = 2

(* TODO: Generate type classes for types? *)
fun features_of ctxt prover thy (scope, status) ts =
  thy_feature_name_of (Context.theory_name thy) ::
  interesting_terms_types_and_classes ctxt prover term_max_depth type_max_depth
                                      ts
(* Temporarily disabled: These frequent features can easily dominate the others.
  |> exists (not o is_lambda_free) ts ? cons "lams"
  |> exists (exists_Const is_exists) ts ? cons "skos"
  |> scope <> Global ? cons "local"
*)
  |> (case string_of_status status of "" => I | s => cons s)

(* Too many dependencies is a sign that a crazy decision procedure is at work.
   There isn't much to learn from such proofs. *)
val max_dependencies = 100
val atp_dependency_default_max_facts = 50<commit_msg>promote local facts using a hack (for MaSh)<commit_after>(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_mash.ML
    Author:     <NAME>, <NAME>

Sledgehammer's machine-learning-based relevance filter (MaSh).
*)

signature SLEDGEHAMMER_MASH =
sig
  type stature = ATP_Problem_Generate.stature
  type fact = Sledgehammer_Fact.fact
  type fact_override = Sledgehammer_Fact.fact_override
  type params = Sledgehammer_Provers.params
  type relevance_fudge = Sledgehammer_Provers.relevance_fudge
  type prover_result = Sledgehammer_Provers.prover_result

  val trace : bool Config.T
  val MaShN : string
  val mepoN : string
  val mashN : string
  val meshN : string
  val unlearnN : string
  val learn_isarN : string
  val learn_atpN : string
  val relearn_isarN : string
  val relearn_atpN : string
  val fact_filters : string list
  val escape_meta : string -> string
  val escape_metas : string list -> string
  val unescape_meta : string -> string
  val unescape_metas : string -> string list
  val extract_query : string -> string * (string * real) list
  val mash_CLEAR : Proof.context -> unit
  val mash_ADD :
    Proof.context -> bool
    -> (string * string list * string list * string list) list -> unit
  val mash_REPROVE :
    Proof.context -> bool -> (string * string list) list -> unit
  val mash_QUERY :
    Proof.context -> bool -> int -> string list * string list
    -> (string * real) list
  val mash_unlearn : Proof.context -> unit
  val nickname_of : thm -> string
  val suggested_facts :
    (string * 'a) list -> ('b * thm) list -> (('b * thm) * 'a) list
  val mesh_facts :
    int -> ((('a * thm) * real) list * ('a * thm) list) list -> ('a * thm) list
  val theory_ord : theory * theory -> order
  val thm_ord : thm * thm -> order
  val goal_of_thm : theory -> thm -> thm
  val run_prover_for_mash :
    Proof.context -> params -> string -> fact list -> thm -> prover_result
  val features_of :
    Proof.context -> string -> theory -> stature -> term list -> string list
  val isar_dependencies_of : unit Symtab.table -> thm -> string list option
  val atp_dependencies_of :
    Proof.context -> params -> string -> int -> fact list -> unit Symtab.table
    -> thm -> bool * string list option
  val mash_suggested_facts :
    Proof.context -> params -> string -> int -> term list -> term
    -> fact list -> (fact * real) list * fact list
  val mash_learn_proof :
    Proof.context -> params -> string -> term -> ('a * thm) list -> thm list
    -> unit
  val mash_learn :
    Proof.context -> params -> fact_override -> thm list -> bool -> unit
  val is_mash_enabled : unit -> bool
  val mash_can_suggest_facts : Proof.context -> bool
  val relevant_facts :
    Proof.context -> params -> string -> int -> fact_override -> term list
    -> term -> fact list -> fact list
  val kill_learners : unit -> unit
  val running_learners : unit -> unit
end;

structure Sledgehammer_MaSh : SLEDGEHAMMER_MASH =
struct

open ATP_Util
open ATP_Problem_Generate
open Sledgehammer_Util
open Sledgehammer_Fact
open Sledgehammer_Provers
open Sledgehammer_Minimize
open Sledgehammer_MePo

val trace =
  Attrib.setup_config_bool @{binding sledgehammer_mash_trace} (K false)
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()

val MaShN = "MaSh"

val mepoN = "mepo"
val mashN = "mash"
val meshN = "mesh"

val fact_filters = [meshN, mepoN, mashN]

val unlearnN = "unlearn"
val learn_isarN = "learn_isar"
val learn_atpN = "learn_atp"
val relearn_isarN = "relearn_isar"
val relearn_atpN = "relearn_atp"

fun mash_model_dir () =
  Path.explode "$ISABELLE_HOME_USER/mash" |> tap Isabelle_System.mkdir
val mash_state_dir = mash_model_dir
fun mash_state_file () = Path.append (mash_state_dir ()) (Path.explode "state")


(*** Low-level communication with MaSh ***)

fun wipe_out_file file = (try (File.rm o Path.explode) file; ())

fun write_file banner (xs, f) path =
  (case banner of SOME s => File.write path s | NONE => ();
   xs |> chunk_list 500
      |> List.app (File.append path o space_implode "" o map f))
  handle IO.Io _ => ()

fun run_mash_tool ctxt overlord save max_suggs write_cmds read_suggs =
  let
    val (temp_dir, serial) =
      if overlord then (getenv "ISABELLE_HOME_USER", "")
      else (getenv "ISABELLE_TMP", serial_string ())
    val log_file = if overlord then temp_dir ^ "/mash_log" else "/dev/null"
    val err_file = temp_dir ^ "/mash_err" ^ serial
    val sugg_file = temp_dir ^ "/mash_suggs" ^ serial
    val sugg_path = Path.explode sugg_file
    val cmd_file = temp_dir ^ "/mash_commands" ^ serial
    val cmd_path = Path.explode cmd_file
    val core =
      "--inputFile " ^ cmd_file ^ " --predictions " ^ sugg_file ^
      " --numberOfPredictions " ^ string_of_int max_suggs ^
      (if save then " --saveModel" else "")
    val command =
      "\"$ISABELLE_SLEDGEHAMMER_MASH/src/mash.py\" --quiet --outputDir " ^
      File.shell_path (mash_model_dir ()) ^ " --log " ^ log_file ^ " " ^ core ^
      " >& " ^ err_file
      |> tap (fn _ => trace_msg ctxt (fn () =>
             case try File.read (Path.explode err_file) of
               NONE => "Done"
             | SOME "" => "Done"
             | SOME s => "Error: " ^ elide_string 1000 s))
    fun run_on () =
      (Isabelle_System.bash command;
       read_suggs (fn () => try File.read_lines sugg_path |> these))
    fun clean_up () =
      if overlord then ()
      else List.app wipe_out_file [err_file, sugg_file, cmd_file]
  in
    write_file (SOME "") ([], K "") sugg_path;
    write_file (SOME "") write_cmds cmd_path;
    trace_msg ctxt (fn () => "Running " ^ command);
    with_cleanup clean_up run_on ()
  end

fun meta_char c =
  if Char.isAlphaNum c orelse c = #"_" orelse c = #"." orelse c = #"(" orelse
     c = #")" orelse c = #"," then
    String.str c
  else
    (* fixed width, in case more digits follow *)
    "%" ^ stringN_of_int 3 (Char.ord c)

fun unmeta_chars accum [] = String.implode (rev accum)
  | unmeta_chars accum (#"%" :: d1 :: d2 :: d3 :: cs) =
    (case Int.fromString (String.implode [d1, d2, d3]) of
       SOME n => unmeta_chars (Char.chr n :: accum) cs
     | NONE => "" (* error *))
  | unmeta_chars _ (#"%" :: _) = "" (* error *)
  | unmeta_chars accum (c :: cs) = unmeta_chars (c :: accum) cs

val escape_meta = String.translate meta_char
val escape_metas = map escape_meta #> space_implode " "
val unescape_meta = String.explode #> unmeta_chars []
val unescape_metas =
  space_explode " " #> filter_out (curry (op =) "") #> map unescape_meta

fun str_of_add (name, parents, feats, deps) =
  "! " ^ escape_meta name ^ ": " ^ escape_metas parents ^ "; " ^
  escape_metas feats ^ "; " ^ escape_metas deps ^ "\n"

fun str_of_reprove (name, deps) =
  "p " ^ escape_meta name ^ ": " ^ escape_metas deps ^ "\n"

fun str_of_query (parents, feats) =
  "? " ^ escape_metas parents ^ "; " ^ escape_metas feats ^ "\n"

fun extract_suggestion sugg =
  case space_explode "=" sugg of
    [name, weight] =>
    SOME (unescape_meta name, Real.fromString weight |> the_default 0.0)
  | _ => NONE

fun extract_query line =
  case space_explode ":" line of
    [goal, suggs] =>
    (unescape_meta goal,
     map_filter extract_suggestion (space_explode " " suggs))
  | _ => ("", [])

fun mash_CLEAR ctxt =
  let val path = mash_model_dir () in
    trace_msg ctxt (K "MaSh CLEAR");
    try (File.fold_dir (fn file => fn _ =>
                           try File.rm (Path.append path (Path.basic file)))
                       path) NONE;
    ()
  end

fun mash_ADD _ _ [] = ()
  | mash_ADD ctxt overlord adds =
    (trace_msg ctxt (fn () => "MaSh ADD " ^
         elide_string 1000 (space_implode " " (map #1 adds)));
     run_mash_tool ctxt overlord true 0 (adds, str_of_add) (K ()))

fun mash_REPROVE _ _ [] = ()
  | mash_REPROVE ctxt overlord reps =
    (trace_msg ctxt (fn () => "MaSh REPROVE " ^
         elide_string 1000 (space_implode " " (map #1 reps)));
     run_mash_tool ctxt overlord true 0 (reps, str_of_reprove) (K ()))

fun mash_QUERY ctxt overlord max_suggs (query as (_, feats)) =
  (trace_msg ctxt (fn () => "MaSh QUERY " ^ space_implode " " feats);
   run_mash_tool ctxt overlord false max_suggs
       ([query], str_of_query)
       (fn suggs =>
           case suggs () of
             [] => []
           | suggs => snd (extract_query (List.last suggs)))
   handle List.Empty => [])


(*** Middle-level communication with MaSh ***)

datatype proof_kind = Isar_Proof | ATP_Proof | Isar_Proof_wegen_ATP_Flop

fun str_of_proof_kind Isar_Proof = "i"
  | str_of_proof_kind ATP_Proof = "a"
  | str_of_proof_kind Isar_Proof_wegen_ATP_Flop = "x"

fun proof_kind_of_str "i" = Isar_Proof
  | proof_kind_of_str "a" = ATP_Proof
  | proof_kind_of_str "x" = Isar_Proof_wegen_ATP_Flop

(* FIXME: Here a "Graph.update_node" function would be useful *)
fun update_fact_graph_node (name, kind) =
  Graph.default_node (name, Isar_Proof)
  #> kind <> Isar_Proof ? Graph.map_node name (K kind)

fun try_graph ctxt when def f =
  f ()
  handle Graph.CYCLES (cycle :: _) =>
         (trace_msg ctxt (fn () =>
              "Cycle involving " ^ commas cycle ^ " when " ^ when); def)
       | Graph.DUP name =>
         (trace_msg ctxt (fn () =>
              "Duplicate fact " ^ quote name ^ " when " ^ when); def)
       | Graph.UNDEF name =>
         (trace_msg ctxt (fn () =>
              "Unknown fact " ^ quote name ^ " when " ^ when); def)
       | exn =>
         if Exn.is_interrupt exn then
           reraise exn
         else
           (trace_msg ctxt (fn () =>
                "Internal error when " ^ when ^ ":\n" ^
                ML_Compiler.exn_message exn); def)

fun graph_info G =
  string_of_int (length (Graph.keys G)) ^ " node(s), " ^
  string_of_int (fold (Integer.add o length o snd) (Graph.dest G) 0) ^
  " edge(s), " ^
  string_of_int (length (Graph.minimals G)) ^ " minimal, " ^
  string_of_int (length (Graph.maximals G)) ^ " maximal"

type mash_state = {fact_G : unit Graph.T, dirty : string list option}

val empty_state = {fact_G = Graph.empty, dirty = SOME []}

local

val version = "*** MaSh 0.1 ***"

fun extract_node line =
  case space_explode ":" line of
    [head, parents] =>
    (case space_explode " " head of
       [kind, name] =>
       SOME (unescape_meta name, unescape_metas parents,
             try proof_kind_of_str kind |> the_default Isar_Proof)
     | _ => NONE)
  | _ => NONE

fun load _ (state as (true, _)) = state
  | load ctxt _ =
    let val path = mash_state_file () in
      (true,
       case try File.read_lines path of
         SOME (version' :: node_lines) =>
         let
           fun add_edge_to name parent =
             Graph.default_node (parent, Isar_Proof)
             #> Graph.add_edge (parent, name)
           fun add_node line =
             case extract_node line of
               NONE => I (* shouldn't happen *)
             | SOME (name, parents, kind) =>
               update_fact_graph_node (name, kind)
               #> fold (add_edge_to name) parents
           val fact_G =
             try_graph ctxt "loading state" Graph.empty (fn () =>
                 Graph.empty |> version' = version ? fold add_node node_lines)
         in
           trace_msg ctxt (fn () =>
               "Loaded fact graph (" ^ graph_info fact_G ^ ")");
           {fact_G = fact_G, dirty = SOME []}
         end
       | _ => empty_state)
    end

fun save _ (state as {dirty = SOME [], ...}) = state
  | save ctxt {fact_G, dirty} =
    let
      fun str_of_entry (name, parents, kind) =
        str_of_proof_kind kind ^ " " ^ escape_meta name ^ ": " ^
        escape_metas parents ^ "\n"
      fun append_entry (name, (kind, (parents, _))) =
        cons (name, Graph.Keys.dest parents, kind)
      val (banner, entries) =
        case dirty of
          SOME names =>
          (NONE, fold (append_entry o Graph.get_entry fact_G) names [])
        | NONE => (SOME (version ^ "\n"), Graph.fold append_entry fact_G [])
    in
      write_file banner (entries, str_of_entry) (mash_state_file ());
      trace_msg ctxt (fn () =>
          "Saved fact graph (" ^ graph_info fact_G ^
          (case dirty of
             SOME dirty =>
             "; " ^ string_of_int (length dirty) ^ " dirty fact(s)"
           | _ => "") ^  ")");
      {fact_G = fact_G, dirty = SOME []}
    end

val global_state =
  Synchronized.var "Sledgehammer_MaSh.global_state" (false, empty_state)

in

fun mash_map ctxt f =
  Synchronized.change global_state (load ctxt ##> (f #> save ctxt))

fun mash_peek ctxt f =
  Synchronized.change_result global_state (load ctxt #> `snd #>> f)

fun mash_get ctxt =
  Synchronized.change_result global_state (load ctxt #> `snd)

fun mash_unlearn ctxt =
  Synchronized.change global_state (fn _ =>
      (mash_CLEAR ctxt; (* also removes the state file *)
       (true, empty_state)))

end


(*** Isabelle helpers ***)

fun parent_of_local_thm th =
  let
    val thy = th |> Thm.theory_of_thm
    val facts = thy |> Global_Theory.facts_of
    val space = facts |> Facts.space_of
    fun id_of s = #id (Name_Space.the_entry space s)
    fun max_id (s', _) (s, id) =
      let val id' = id_of s' in if id > id' then (s, id) else (s', id') end
  in ("", ~1) |> Facts.fold_static max_id facts |> fst end

val local_prefix = "local" ^ Long_Name.separator

fun nickname_of th =
  if Thm.has_name_hint th then
    let val hint = Thm.get_name_hint th in
      (* FIXME: There must be a better way to detect local facts. *)
      case try (unprefix local_prefix) hint of
        SOME suf =>
        parent_of_local_thm th ^ Long_Name.separator ^ Long_Name.separator ^ suf
      | NONE => hint
    end
  else
    backquote_thm (Proof_Context.init_global (Thm.theory_of_thm th)) th

fun suggested_facts suggs facts =
  let
    fun add_fact (fact as (_, th)) = Symtab.default (nickname_of th, fact)
    val tab = Symtab.empty |> fold add_fact facts
    fun find_sugg (name, weight) =
      Symtab.lookup tab name |> Option.map (rpair weight)
  in map_filter find_sugg suggs end

fun sum_avg [] = 0
  | sum_avg xs =
    Real.ceil (100000000.0 * fold (curry (op +)) xs 0.0) div length xs

fun normalize_scores [] = []
  | normalize_scores ((fact, score) :: tail) =
    (fact, 1.0) :: map (apsnd (curry Real.* (1.0 / score))) tail

fun mesh_facts max_facts [(sels, unks)] =
    map fst (take max_facts sels) @ take (max_facts - length sels) unks
  | mesh_facts max_facts mess =
    let
      val mess = mess |> map (apfst (normalize_scores #> `length))
      val fact_eq = Thm.eq_thm o pairself snd
      fun score_at sels = try (nth sels) #> Option.map snd
      fun score_in fact ((sel_len, sels), unks) =
        case find_index (curry fact_eq fact o fst) sels of
          ~1 => (case find_index (curry fact_eq fact) unks of
                   ~1 => score_at sels sel_len
                 | _ => NONE)
        | rank => score_at sels rank
      fun weight_of fact = mess |> map_filter (score_in fact) |> sum_avg
      val facts =
        fold (union fact_eq o map fst o take max_facts o snd o fst) mess []
    in
      facts |> map (`weight_of) |> sort (int_ord o swap o pairself fst)
            |> map snd |> take max_facts
    end

val thy_feature_name_of = prefix "y"
val const_name_of = prefix "c"
val type_name_of = prefix "t"
val class_name_of = prefix "s"

fun theory_ord p =
  if Theory.eq_thy p then
    EQUAL
  else if Theory.subthy p then
    LESS
  else if Theory.subthy (swap p) then
    GREATER
  else case int_ord (pairself (length o Theory.ancestors_of) p) of
    EQUAL => string_ord (pairself Context.theory_name p)
  | order => order

val thm_ord = theory_ord o pairself theory_of_thm

val freezeT = Type.legacy_freeze_type

fun freeze (t $ u) = freeze t $ freeze u
  | freeze (Abs (s, T, t)) = Abs (s, freezeT T, freeze t)
  | freeze (Var ((s, _), T)) = Free (s, freezeT T)
  | freeze (Const (s, T)) = Const (s, freezeT T)
  | freeze (Free (s, T)) = Free (s, freezeT T)
  | freeze t = t

fun goal_of_thm thy = prop_of #> freeze #> cterm_of thy #> Goal.init

fun run_prover_for_mash ctxt params prover facts goal =
  let
    val problem =
      {state = Proof.init ctxt, goal = goal, subgoal = 1, subgoal_count = 1,
       facts = facts |> map (apfst (apfst (fn name => name ())))
                     |> map Untranslated_Fact}
  in
    get_minimizing_prover ctxt MaSh (K (K ())) prover params (K (K (K "")))
                          problem
  end

val bad_types = [@{type_name prop}, @{type_name bool}, @{type_name fun}]

val logical_consts =
  [@{const_name prop}, @{const_name Pure.conjunction}] @ atp_logical_consts

fun interesting_terms_types_and_classes ctxt prover term_max_depth
                                        type_max_depth ts =
  let
    fun is_bad_const (x as (s, _)) args =
      member (op =) logical_consts s orelse
      fst (is_built_in_const_for_prover ctxt prover x args)
    fun add_classes @{sort type} = I
      | add_classes S = union (op =) (map class_name_of S)
    fun do_add_type (Type (s, Ts)) =
        (not (member (op =) bad_types s) ? insert (op =) (type_name_of s))
        #> fold do_add_type Ts
      | do_add_type (TFree (_, S)) = add_classes S
      | do_add_type (TVar (_, S)) = add_classes S
    fun add_type T = type_max_depth >= 0 ? do_add_type T
    fun patternify_term _ ~1 _ = []
      | patternify_term args _ (Const (x as (s, _))) =
        if is_bad_const x args then [] else [const_name_of s]
      | patternify_term _ 0 _ = []
      | patternify_term args depth (t $ u) =
        let
          val ps = patternify_term (u :: args) depth t
          val qs = "" :: patternify_term [] (depth - 1) u
        in map_product (fn p => fn "" => p | q => p ^ "(" ^ q ^ ")") ps qs end
      | patternify_term _ _ _ = []
    val add_term_pattern = union (op =) oo patternify_term []
    fun add_term_patterns ~1 _ = I
      | add_term_patterns depth t =
        add_term_pattern depth t #> add_term_patterns (depth - 1) t
    val add_term = add_term_patterns term_max_depth
    fun add_patterns t =
      let val (head, args) = strip_comb t in
        (case head of
           Const (_, T) => add_term t #> add_type T
         | Free (_, T) => add_type T
         | Var (_, T) => add_type T
         | Abs (_, T, body) => add_type T #> add_patterns body
         | _ => I)
        #> fold add_patterns args
      end
  in [] |> fold add_patterns ts end

fun is_exists (s, _) = (s = @{const_name Ex} orelse s = @{const_name Ex1})

val term_max_depth = 2
val type_max_depth = 2

(* TODO: Generate type classes for types? *)
fun features_of ctxt prover thy (scope, status) ts =
  thy_feature_name_of (Context.theory_name thy) ::
  interesting_terms_types_and_classes ctxt prover term_max_depth type_max_depth
                                      ts
(* Temporarily disabled: These frequent features can easily dominate the others.
  |> exists (not o is_lambda_free) ts ? cons "lams"
  |> exists (exists_Const is_exists) ts ? cons "skos"
*)
  |> scope <> Global
     (* temporary hack: give a heavier weight to locality *)
     ? append ["local0", "local1", "local2", "local3", "local4",
               "local5", "local6", "local7", "local8", "local9"]
  |> (case string_of_status status of "" => I | s => cons s)

(* Too many dependencies is a sign that a crazy decision procedure is at work.
   There isn't much to learn from such proofs. *)
val max_dependencies = 100
val atp_dependency_default_max_facts = 50
{'fraction_non_alphanumeric': 0.11597056689812416, 'fraction_numerical': 0.003730956575810965, 'mean_word_length': 2.700575263662512, 'pattern_counts': {'":': 12, '<': 11, '<?xml version=': 0, '>': 407, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '126982', 'n_tokens_mistral': 13744, 'n_tokens_neox': 13258, 'n_words': 3971}