src/HOL/Tools/ATP/atp_proof_reconstruct.ML
author blanchet
Thu, 26 Jan 2012 20:49:54 +0100
changeset 47168 cac402c486b0
parent 47148 0b8b73b49848
child 47170 c59b8560eb48
permissions -rw-r--r--
separate orthogonal components
     1 (*  Title:      HOL/Tools/ATP/atp_proof_reconstruct.ML
     2     Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory
     3     Author:     Claire Quigley, Cambridge University Computer Laboratory
     4     Author:     Jasmin Blanchette, TU Muenchen
     5 
     6 Proof reconstruction from ATP proofs.
     7 *)
     8 
     9 signature ATP_PROOF_RECONSTRUCT =
    10 sig
    11   type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
    12   type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
    13   type 'a proof = 'a ATP_Proof.proof
    14   type stature = ATP_Problem_Generate.stature
    15 
    16   datatype reconstructor =
    17     Metis of string * string |
    18     SMT
    19 
    20   datatype play =
    21     Played of reconstructor * Time.time |
    22     Trust_Playable of reconstructor * Time.time option |
    23     Failed_to_Play of reconstructor
    24 
    25   type minimize_command = string list -> string
    26   type one_line_params =
    27     play * string * (string * stature) list * minimize_command * int * int
    28   type isar_params =
    29     bool * int * string Symtab.table * (string * stature) list vector
    30     * int Symtab.table * string proof * thm
    31 
    32   val metisN : string
    33   val smtN : string
    34   val full_typesN : string
    35   val partial_typesN : string
    36   val no_typesN : string
    37   val really_full_type_enc : string
    38   val full_type_enc : string
    39   val partial_type_enc : string
    40   val no_type_enc : string
    41   val full_type_encs : string list
    42   val partial_type_encs : string list
    43   val metis_default_lam_trans : string
    44   val metis_call : string -> string -> string
    45   val string_for_reconstructor : reconstructor -> string
    46   val used_facts_in_atp_proof :
    47     Proof.context -> (string * stature) list vector -> string proof
    48     -> (string * stature) list
    49   val lam_trans_from_atp_proof : string proof -> string -> string
    50   val is_typed_helper_used_in_atp_proof : string proof -> bool
    51   val used_facts_in_unsound_atp_proof :
    52     Proof.context -> (string * stature) list vector -> 'a proof
    53     -> string list option
    54   val unalias_type_enc : string -> string list
    55   val one_line_proof_text : one_line_params -> string
    56   val make_tvar : string -> typ
    57   val make_tfree : Proof.context -> string -> typ
    58   val term_from_atp :
    59     Proof.context -> bool -> int Symtab.table -> typ option
    60     -> (string, string) ho_term -> term
    61   val prop_from_atp :
    62     Proof.context -> bool -> int Symtab.table
    63     -> (string, string, (string, string) ho_term) formula -> term
    64   val isar_proof_text :
    65     Proof.context -> bool -> isar_params -> one_line_params -> string
    66   val proof_text :
    67     Proof.context -> bool -> isar_params -> one_line_params -> string
    68 end;
    69 
    70 structure ATP_Proof_Reconstruct : ATP_PROOF_RECONSTRUCT =
    71 struct
    72 
    73 open ATP_Util
    74 open ATP_Problem
    75 open ATP_Proof
    76 open ATP_Problem_Generate
    77 
    78 structure String_Redirect = ATP_Proof_Redirect(
    79     type key = step_name
    80     val ord = fn ((s, _ : string list), (s', _)) => fast_string_ord (s, s')
    81     val string_of = fst)
    82 
    83 open String_Redirect
    84 
    85 datatype reconstructor =
    86   Metis of string * string |
    87   SMT
    88 
    89 datatype play =
    90   Played of reconstructor * Time.time |
    91   Trust_Playable of reconstructor * Time.time option |
    92   Failed_to_Play of reconstructor
    93 
    94 type minimize_command = string list -> string
    95 type one_line_params =
    96   play * string * (string * stature) list * minimize_command * int * int
    97 type isar_params =
    98   bool * int * string Symtab.table * (string * stature) list vector
    99   * int Symtab.table * string proof * thm
   100 
   101 val metisN = "metis"
   102 val smtN = "smt"
   103 
   104 val full_typesN = "full_types"
   105 val partial_typesN = "partial_types"
   106 val no_typesN = "no_types"
   107 
   108 val really_full_type_enc = "mono_tags"
   109 val full_type_enc = "poly_guards_query"
   110 val partial_type_enc = "poly_args"
   111 val no_type_enc = "erased"
   112 
   113 val full_type_encs = [full_type_enc, really_full_type_enc]
   114 val partial_type_encs = partial_type_enc :: full_type_encs
   115 
   116 val type_enc_aliases =
   117   [(full_typesN, full_type_encs),
   118    (partial_typesN, partial_type_encs),
   119    (no_typesN, [no_type_enc])]
   120 
   121 fun unalias_type_enc s =
   122   AList.lookup (op =) type_enc_aliases s |> the_default [s]
   123 
   124 val metis_default_lam_trans = combinatorsN
   125 
   126 fun metis_call type_enc lam_trans =
   127   let
   128     val type_enc =
   129       case AList.find (fn (enc, encs) => enc = hd encs) type_enc_aliases
   130                       type_enc of
   131         [alias] => alias
   132       | _ => type_enc
   133     val opts = [] |> type_enc <> partial_typesN ? cons type_enc
   134                   |> lam_trans <> metis_default_lam_trans ? cons lam_trans
   135   in metisN ^ (if null opts then "" else " (" ^ commas opts ^ ")") end
   136 
   137 fun string_for_reconstructor (Metis (type_enc, lam_trans)) =
   138     metis_call type_enc lam_trans
   139   | string_for_reconstructor SMT = smtN
   140 
   141 fun find_first_in_list_vector vec key =
   142   Vector.foldl (fn (ps, NONE) => AList.lookup (op =) ps key
   143                  | (_, value) => value) NONE vec
   144 
   145 val unprefix_fact_number = space_implode "_" o tl o space_explode "_"
   146 
   147 fun resolve_one_named_fact fact_names s =
   148   case try (unprefix fact_prefix) s of
   149     SOME s' =>
   150     let val s' = s' |> unprefix_fact_number |> unascii_of in
   151       s' |> find_first_in_list_vector fact_names |> Option.map (pair s')
   152     end
   153   | NONE => NONE
   154 fun resolve_fact fact_names = map_filter (resolve_one_named_fact fact_names)
   155 fun is_fact fact_names = not o null o resolve_fact fact_names
   156 
   157 fun resolve_one_named_conjecture s =
   158   case try (unprefix conjecture_prefix) s of
   159     SOME s' => Int.fromString s'
   160   | NONE => NONE
   161 
   162 val resolve_conjecture = map_filter resolve_one_named_conjecture
   163 val is_conjecture = not o null o resolve_conjecture
   164 
   165 fun is_axiom_used_in_proof pred =
   166   exists (fn Inference ((_, ss), _, _, []) => exists pred ss | _ => false)
   167 
   168 val is_combinator_def = String.isPrefix (helper_prefix ^ combinator_prefix)
   169 
   170 val ascii_of_lam_fact_prefix = ascii_of lam_fact_prefix
   171 
   172 (* overapproximation (good enough) *)
   173 fun is_lam_lifted s =
   174   String.isPrefix fact_prefix s andalso
   175   String.isSubstring ascii_of_lam_fact_prefix s
   176 
   177 fun lam_trans_from_atp_proof atp_proof default =
   178   if is_axiom_used_in_proof is_combinator_def atp_proof then combinatorsN
   179   else if is_axiom_used_in_proof is_lam_lifted atp_proof then lam_liftingN
   180   else default
   181 
   182 val is_typed_helper_name =
   183   String.isPrefix helper_prefix andf String.isSuffix typed_helper_suffix
   184 fun is_typed_helper_used_in_atp_proof atp_proof =
   185   is_axiom_used_in_proof is_typed_helper_name atp_proof
   186 
   187 val leo2_ext = "extcnf_equal_neg"
   188 val isa_ext = Thm.get_name_hint @{thm ext}
   189 val isa_short_ext = Long_Name.base_name isa_ext
   190 
   191 fun ext_name ctxt =
   192   if Thm.eq_thm_prop (@{thm ext},
   193          singleton (Attrib.eval_thms ctxt) (Facts.named isa_short_ext, [])) then
   194     isa_short_ext
   195   else
   196     isa_ext
   197 
   198 fun add_fact _ fact_names (Inference ((_, ss), _, _, [])) =
   199     union (op =) (resolve_fact fact_names ss)
   200   | add_fact ctxt _ (Inference (_, _, rule, _)) =
   201     if rule = leo2_ext then insert (op =) (ext_name ctxt, (Global, General))
   202     else I
   203   | add_fact _ _ _ = I
   204 
   205 fun used_facts_in_atp_proof ctxt fact_names atp_proof =
   206   if null atp_proof then Vector.foldl (uncurry (union (op =))) [] fact_names
   207   else fold (add_fact ctxt fact_names) atp_proof []
   208 
   209 fun used_facts_in_unsound_atp_proof _ _ [] = NONE
   210   | used_facts_in_unsound_atp_proof ctxt fact_names atp_proof =
   211     let
   212       val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
   213     in
   214       if forall (fn (_, (sc, _)) => sc = Global) used_facts andalso
   215          not (is_axiom_used_in_proof (is_conjecture o single) atp_proof) then
   216         SOME (map fst used_facts)
   217       else
   218         NONE
   219     end
   220 
   221 
   222 (** Soft-core proof reconstruction: one-liners **)
   223 
   224 fun string_for_label (s, num) = s ^ string_of_int num
   225 
   226 fun show_time NONE = ""
   227   | show_time (SOME ext_time) = " (" ^ string_from_ext_time ext_time ^ ")"
   228 
   229 fun apply_on_subgoal _ 1 = "by "
   230   | apply_on_subgoal 1 _ = "apply "
   231   | apply_on_subgoal i n =
   232     "prefer " ^ string_of_int i ^ " " ^ apply_on_subgoal 1 n
   233 fun command_call name [] =
   234     name |> not (Lexicon.is_identifier name) ? enclose "(" ")"
   235   | command_call name args = "(" ^ name ^ " " ^ space_implode " " args ^ ")"
   236 fun try_command_line banner time command =
   237   banner ^ ": " ^ Markup.markup Isabelle_Markup.sendback command ^ show_time time ^ "."
   238 fun using_labels [] = ""
   239   | using_labels ls =
   240     "using " ^ space_implode " " (map string_for_label ls) ^ " "
   241 fun reconstructor_command reconstr i n (ls, ss) =
   242   using_labels ls ^ apply_on_subgoal i n ^
   243   command_call (string_for_reconstructor reconstr) ss
   244 fun minimize_line _ [] = ""
   245   | minimize_line minimize_command ss =
   246     case minimize_command ss of
   247       "" => ""
   248     | command =>
   249       "\nTo minimize: " ^ Markup.markup Isabelle_Markup.sendback command ^ "."
   250 
   251 val split_used_facts =
   252   List.partition (fn (_, (sc, _)) => sc = Chained)
   253   #> pairself (sort_distinct (string_ord o pairself fst))
   254 
   255 fun one_line_proof_text (preplay, banner, used_facts, minimize_command,
   256                          subgoal, subgoal_count) =
   257   let
   258     val (chained, extra) = split_used_facts used_facts
   259     val (failed, reconstr, ext_time) =
   260       case preplay of
   261         Played (reconstr, time) => (false, reconstr, (SOME (false, time)))
   262       | Trust_Playable (reconstr, time) =>
   263         (false, reconstr,
   264          case time of
   265            NONE => NONE
   266          | SOME time =>
   267            if time = Time.zeroTime then NONE else SOME (true, time))
   268       | Failed_to_Play reconstr => (true, reconstr, NONE)
   269     val try_line =
   270       ([], map fst extra)
   271       |> reconstructor_command reconstr subgoal subgoal_count
   272       |> (if failed then enclose "One-line proof reconstruction failed: " "."
   273           else try_command_line banner ext_time)
   274   in try_line ^ minimize_line minimize_command (map fst (extra @ chained)) end
   275 
   276 (** Hard-core proof reconstruction: structured Isar proofs **)
   277 
   278 fun forall_of v t = HOLogic.all_const (fastype_of v) $ lambda v t
   279 fun exists_of v t = HOLogic.exists_const (fastype_of v) $ lambda v t
   280 
   281 fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS)
   282 fun make_tfree ctxt w =
   283   let val ww = "'" ^ w in
   284     TFree (ww, the_default HOLogic.typeS (Variable.def_sort ctxt (ww, ~1)))
   285   end
   286 
   287 val indent_size = 2
   288 val no_label = ("", ~1)
   289 
   290 val raw_prefix = "x"
   291 val assum_prefix = "a"
   292 val have_prefix = "f"
   293 
   294 fun raw_label_for_name (num, ss) =
   295   case resolve_conjecture ss of
   296     [j] => (conjecture_prefix, j)
   297   | _ => case Int.fromString num of
   298            SOME j => (raw_prefix, j)
   299          | NONE => (raw_prefix ^ num, 0)
   300 
   301 (**** INTERPRETATION OF TSTP SYNTAX TREES ****)
   302 
   303 exception HO_TERM of (string, string) ho_term list
   304 exception FORMULA of (string, string, (string, string) ho_term) formula list
   305 exception SAME of unit
   306 
   307 (* Type variables are given the basic sort "HOL.type". Some will later be
   308    constrained by information from type literals, or by type inference. *)
   309 fun typ_from_atp ctxt (u as ATerm (a, us)) =
   310   let val Ts = map (typ_from_atp ctxt) us in
   311     case unprefix_and_unascii type_const_prefix a of
   312       SOME b => Type (invert_const b, Ts)
   313     | NONE =>
   314       if not (null us) then
   315         raise HO_TERM [u]  (* only "tconst"s have type arguments *)
   316       else case unprefix_and_unascii tfree_prefix a of
   317         SOME b => make_tfree ctxt b
   318       | NONE =>
   319         (* Could be an Isabelle variable or a variable from the ATP, say "X1"
   320            or "_5018". Sometimes variables from the ATP are indistinguishable
   321            from Isabelle variables, which forces us to use a type parameter in
   322            all cases. *)
   323         (a |> perhaps (unprefix_and_unascii tvar_prefix), HOLogic.typeS)
   324         |> Type_Infer.param 0
   325   end
   326 
   327 (* Type class literal applied to a type. Returns triple of polarity, class,
   328    type. *)
   329 fun type_constraint_from_term ctxt (u as ATerm (a, us)) =
   330   case (unprefix_and_unascii class_prefix a, map (typ_from_atp ctxt) us) of
   331     (SOME b, [T]) => (b, T)
   332   | _ => raise HO_TERM [u]
   333 
   334 (* Accumulate type constraints in a formula: negative type literals. *)
   335 fun add_var (key, z)  = Vartab.map_default (key, []) (cons z)
   336 fun add_type_constraint false (cl, TFree (a ,_)) = add_var ((a, ~1), cl)
   337   | add_type_constraint false (cl, TVar (ix, _)) = add_var (ix, cl)
   338   | add_type_constraint _ _ = I
   339 
   340 fun repair_variable_name f s =
   341   let
   342     fun subscript_name s n = s ^ nat_subscript n
   343     val s = String.map f s
   344   in
   345     case space_explode "_" s of
   346       [_] => (case take_suffix Char.isDigit (String.explode s) of
   347                 (cs1 as _ :: _, cs2 as _ :: _) =>
   348                 subscript_name (String.implode cs1)
   349                                (the (Int.fromString (String.implode cs2)))
   350               | (_, _) => s)
   351     | [s1, s2] => (case Int.fromString s2 of
   352                      SOME n => subscript_name s1 n
   353                    | NONE => s)
   354     | _ => s
   355   end
   356 
   357 (* The number of type arguments of a constant, zero if it's monomorphic. For
   358    (instances of) Skolem pseudoconstants, this information is encoded in the
   359    constant name. *)
   360 fun num_type_args thy s =
   361   if String.isPrefix skolem_const_prefix s then
   362     s |> space_explode Long_Name.separator |> List.last |> Int.fromString |> the
   363   else if String.isPrefix lam_lifted_prefix s then
   364     if String.isPrefix lam_lifted_poly_prefix s then 2 else 0
   365   else
   366     (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
   367 
   368 fun slack_fastype_of t = fastype_of t handle TERM _ => HOLogic.typeT
   369 
   370 (* First-order translation. No types are known for variables. "HOLogic.typeT"
   371    should allow them to be inferred. *)
   372 fun term_from_atp ctxt textual sym_tab =
   373   let
   374     val thy = Proof_Context.theory_of ctxt
   375     (* For Metis, we use 1 rather than 0 because variable references in clauses
   376        may otherwise conflict with variable constraints in the goal. At least,
   377        type inference often fails otherwise. See also "axiom_inference" in
   378        "Metis_Reconstruct". *)
   379     val var_index = if textual then 0 else 1
   380     fun do_term extra_ts opt_T u =
   381       case u of
   382         ATerm (s, us) =>
   383         if String.isPrefix simple_type_prefix s then
   384           @{const True} (* ignore TPTP type information *)
   385         else if s = tptp_equal then
   386           let val ts = map (do_term [] NONE) us in
   387             if textual andalso length ts = 2 andalso
   388               hd ts aconv List.last ts then
   389               (* Vampire is keen on producing these. *)
   390               @{const True}
   391             else
   392               list_comb (Const (@{const_name HOL.eq}, HOLogic.typeT), ts)
   393           end
   394         else case unprefix_and_unascii const_prefix s of
   395           SOME s' =>
   396           let
   397             val ((s', s''), mangled_us) =
   398               s' |> unmangled_const |>> `invert_const
   399           in
   400             if s' = type_tag_name then
   401               case mangled_us @ us of
   402                 [typ_u, term_u] =>
   403                 do_term extra_ts (SOME (typ_from_atp ctxt typ_u)) term_u
   404               | _ => raise HO_TERM us
   405             else if s' = predicator_name then
   406               do_term [] (SOME @{typ bool}) (hd us)
   407             else if s' = app_op_name then
   408               let val extra_t = do_term [] NONE (List.last us) in
   409                 do_term (extra_t :: extra_ts)
   410                         (case opt_T of
   411                            SOME T => SOME (slack_fastype_of extra_t --> T)
   412                          | NONE => NONE)
   413                         (nth us (length us - 2))
   414               end
   415             else if s' = type_guard_name then
   416               @{const True} (* ignore type predicates *)
   417             else
   418               let
   419                 val new_skolem = String.isPrefix new_skolem_const_prefix s''
   420                 val num_ty_args =
   421                   length us - the_default 0 (Symtab.lookup sym_tab s)
   422                 val (type_us, term_us) =
   423                   chop num_ty_args us |>> append mangled_us
   424                 val term_ts = map (do_term [] NONE) term_us
   425                 val T =
   426                   (if not (null type_us) andalso
   427                       num_type_args thy s' = length type_us then
   428                      let val Ts = type_us |> map (typ_from_atp ctxt) in
   429                        if new_skolem then
   430                          SOME (Type_Infer.paramify_vars (tl Ts ---> hd Ts))
   431                        else if textual then
   432                          try (Sign.const_instance thy) (s', Ts)
   433                        else
   434                          NONE
   435                      end
   436                    else
   437                      NONE)
   438                   |> (fn SOME T => T
   439                        | NONE => map slack_fastype_of term_ts --->
   440                                  (case opt_T of
   441                                     SOME T => T
   442                                   | NONE => HOLogic.typeT))
   443                 val t =
   444                   if new_skolem then
   445                     Var ((new_skolem_var_name_from_const s'', var_index), T)
   446                   else
   447                     Const (unproxify_const s', T)
   448               in list_comb (t, term_ts @ extra_ts) end
   449           end
   450         | NONE => (* a free or schematic variable *)
   451           let
   452             val term_ts = map (do_term [] NONE) us
   453             val ts = term_ts @ extra_ts
   454             val T =
   455               case opt_T of
   456                 SOME T => map slack_fastype_of term_ts ---> T
   457               | NONE => map slack_fastype_of ts ---> HOLogic.typeT
   458             val t =
   459               case unprefix_and_unascii fixed_var_prefix s of
   460                 SOME s => Free (s, T)
   461               | NONE =>
   462                 case unprefix_and_unascii schematic_var_prefix s of
   463                   SOME s => Var ((s, var_index), T)
   464                 | NONE =>
   465                   Var ((s |> textual ? repair_variable_name Char.toLower,
   466                         var_index), T)
   467           in list_comb (t, ts) end
   468   in do_term [] end
   469 
   470 fun term_from_atom ctxt textual sym_tab pos (u as ATerm (s, _)) =
   471   if String.isPrefix class_prefix s then
   472     add_type_constraint pos (type_constraint_from_term ctxt u)
   473     #> pair @{const True}
   474   else
   475     pair (term_from_atp ctxt textual sym_tab (SOME @{typ bool}) u)
   476 
   477 val combinator_table =
   478   [(@{const_name Meson.COMBI}, @{thm Meson.COMBI_def_raw}),
   479    (@{const_name Meson.COMBK}, @{thm Meson.COMBK_def_raw}),
   480    (@{const_name Meson.COMBB}, @{thm Meson.COMBB_def_raw}),
   481    (@{const_name Meson.COMBC}, @{thm Meson.COMBC_def_raw}),
   482    (@{const_name Meson.COMBS}, @{thm Meson.COMBS_def_raw})]
   483 
   484 fun uncombine_term thy =
   485   let
   486     fun aux (t1 $ t2) = betapply (pairself aux (t1, t2))
   487       | aux (Abs (s, T, t')) = Abs (s, T, aux t')
   488       | aux (t as Const (x as (s, _))) =
   489         (case AList.lookup (op =) combinator_table s of
   490            SOME thm => thm |> prop_of |> specialize_type thy x
   491                            |> Logic.dest_equals |> snd
   492          | NONE => t)
   493       | aux t = t
   494   in aux end
   495 
   496 (* Update schematic type variables with detected sort constraints. It's not
   497    totally clear whether this code is necessary. *)
   498 fun repair_tvar_sorts (t, tvar_tab) =
   499   let
   500     fun do_type (Type (a, Ts)) = Type (a, map do_type Ts)
   501       | do_type (TVar (xi, s)) =
   502         TVar (xi, the_default s (Vartab.lookup tvar_tab xi))
   503       | do_type (TFree z) = TFree z
   504     fun do_term (Const (a, T)) = Const (a, do_type T)
   505       | do_term (Free (a, T)) = Free (a, do_type T)
   506       | do_term (Var (xi, T)) = Var (xi, do_type T)
   507       | do_term (t as Bound _) = t
   508       | do_term (Abs (a, T, t)) = Abs (a, do_type T, do_term t)
   509       | do_term (t1 $ t2) = do_term t1 $ do_term t2
   510   in t |> not (Vartab.is_empty tvar_tab) ? do_term end
   511 
   512 fun quantify_over_var quant_of var_s t =
   513   let
   514     val vars = [] |> Term.add_vars t |> filter (fn ((s, _), _) => s = var_s)
   515                   |> map Var
   516   in fold_rev quant_of vars t end
   517 
   518 (* Interpret an ATP formula as a HOL term, extracting sort constraints as they
   519    appear in the formula. *)
   520 fun prop_from_atp ctxt textual sym_tab phi =
   521   let
   522     fun do_formula pos phi =
   523       case phi of
   524         AQuant (_, [], phi) => do_formula pos phi
   525       | AQuant (q, (s, _) :: xs, phi') =>
   526         do_formula pos (AQuant (q, xs, phi'))
   527         (* FIXME: TFF *)
   528         #>> quantify_over_var (case q of
   529                                  AForall => forall_of
   530                                | AExists => exists_of)
   531                               (s |> textual ? repair_variable_name Char.toLower)
   532       | AConn (ANot, [phi']) => do_formula (not pos) phi' #>> s_not
   533       | AConn (c, [phi1, phi2]) =>
   534         do_formula (pos |> c = AImplies ? not) phi1
   535         ##>> do_formula pos phi2
   536         #>> (case c of
   537                AAnd => s_conj
   538              | AOr => s_disj
   539              | AImplies => s_imp
   540              | AIff => s_iff
   541              | ANot => raise Fail "impossible connective")
   542       | AAtom tm => term_from_atom ctxt textual sym_tab pos tm
   543       | _ => raise FORMULA [phi]
   544   in repair_tvar_sorts (do_formula true phi Vartab.empty) end
   545 
   546 fun infer_formula_types ctxt =
   547   Type.constraint HOLogic.boolT
   548   #> Syntax.check_term
   549          (Proof_Context.set_mode Proof_Context.mode_schematic ctxt)
   550 
   551 fun uncombined_etc_prop_from_atp ctxt textual sym_tab =
   552   let val thy = Proof_Context.theory_of ctxt in
   553     prop_from_atp ctxt textual sym_tab
   554     #> textual ? uncombine_term thy #> infer_formula_types ctxt
   555   end
   556 
   557 (**** Translation of TSTP files to Isar proofs ****)
   558 
   559 fun unvarify_term (Var ((s, 0), T)) = Free (s, T)
   560   | unvarify_term t = raise TERM ("unvarify_term: non-Var", [t])
   561 
   562 fun decode_line sym_tab (Definition (name, phi1, phi2)) ctxt =
   563     let
   564       val thy = Proof_Context.theory_of ctxt
   565       val t1 = prop_from_atp ctxt true sym_tab phi1
   566       val vars = snd (strip_comb t1)
   567       val frees = map unvarify_term vars
   568       val unvarify_args = subst_atomic (vars ~~ frees)
   569       val t2 = prop_from_atp ctxt true sym_tab phi2
   570       val (t1, t2) =
   571         HOLogic.eq_const HOLogic.typeT $ t1 $ t2
   572         |> unvarify_args |> uncombine_term thy |> infer_formula_types ctxt
   573         |> HOLogic.dest_eq
   574     in
   575       (Definition (name, t1, t2),
   576        fold Variable.declare_term (maps Misc_Legacy.term_frees [t1, t2]) ctxt)
   577     end
   578   | decode_line sym_tab (Inference (name, u, rule, deps)) ctxt =
   579     let val t = u |> uncombined_etc_prop_from_atp ctxt true sym_tab in
   580       (Inference (name, t, rule, deps),
   581        fold Variable.declare_term (Misc_Legacy.term_frees t) ctxt)
   582     end
   583 fun decode_lines ctxt sym_tab lines =
   584   fst (fold_map (decode_line sym_tab) lines ctxt)
   585 
   586 fun is_same_inference _ (Definition _) = false
   587   | is_same_inference t (Inference (_, t', _, _)) = t aconv t'
   588 
   589 (* No "real" literals means only type information (tfree_tcs, clsrel, or
   590    clsarity). *)
   591 val is_only_type_information = curry (op aconv) @{term True}
   592 
   593 fun replace_one_dependency (old, new) dep =
   594   if is_same_atp_step dep old then new else [dep]
   595 fun replace_dependencies_in_line _ (line as Definition _) = line
   596   | replace_dependencies_in_line p (Inference (name, t, rule, deps)) =
   597     Inference (name, t, rule,
   598                fold (union (op =) o replace_one_dependency p) deps [])
   599 
   600 (* Discard facts; consolidate adjacent lines that prove the same formula, since
   601    they differ only in type information.*)
   602 fun add_line _ (line as Definition _) lines = line :: lines
   603   | add_line fact_names (Inference (name as (_, ss), t, rule, [])) lines =
   604     (* No dependencies: fact, conjecture, or (for Vampire) internal facts or
   605        definitions. *)
   606     if is_fact fact_names ss then
   607       (* Facts are not proof lines. *)
   608       if is_only_type_information t then
   609         map (replace_dependencies_in_line (name, [])) lines
   610       (* Is there a repetition? If so, replace later line by earlier one. *)
   611       else case take_prefix (not o is_same_inference t) lines of
   612         (_, []) => lines (* no repetition of proof line *)
   613       | (pre, Inference (name', _, _, _) :: post) =>
   614         pre @ map (replace_dependencies_in_line (name', [name])) post
   615       | _ => raise Fail "unexpected inference"
   616     else if is_conjecture ss then
   617       Inference (name, s_not t, rule, []) :: lines
   618     else
   619       map (replace_dependencies_in_line (name, [])) lines
   620   | add_line _ (Inference (name, t, rule, deps)) lines =
   621     (* Type information will be deleted later; skip repetition test. *)
   622     if is_only_type_information t then
   623       Inference (name, t, rule, deps) :: lines
   624     (* Is there a repetition? If so, replace later line by earlier one. *)
   625     else case take_prefix (not o is_same_inference t) lines of
   626       (* FIXME: Doesn't this code risk conflating proofs involving different
   627          types? *)
   628        (_, []) => Inference (name, t, rule, deps) :: lines
   629      | (pre, Inference (name', t', rule, _) :: post) =>
   630        Inference (name, t', rule, deps) ::
   631        pre @ map (replace_dependencies_in_line (name', [name])) post
   632      | _ => raise Fail "unexpected inference"
   633 
   634 (* Recursively delete empty lines (type information) from the proof. *)
   635 fun add_nontrivial_line (line as Inference (name, t, _, [])) lines =
   636     if is_only_type_information t then delete_dependency name lines
   637     else line :: lines
   638   | add_nontrivial_line line lines = line :: lines
   639 and delete_dependency name lines =
   640   fold_rev add_nontrivial_line
   641            (map (replace_dependencies_in_line (name, [])) lines) []
   642 
   643 (* ATPs sometimes reuse free variable names in the strangest ways. Removing
   644    offending lines often does the trick. *)
   645 fun is_bad_free frees (Free x) = not (member (op =) frees x)
   646   | is_bad_free _ _ = false
   647 
   648 fun add_desired_line _ _ _ (line as Definition (name, _, _)) (j, lines) =
   649     (j, line :: map (replace_dependencies_in_line (name, [])) lines)
   650   | add_desired_line isar_shrink_factor fact_names frees
   651                      (Inference (name as (_, ss), t, rule, deps)) (j, lines) =
   652     (j + 1,
   653      if is_fact fact_names ss orelse
   654         is_conjecture ss orelse
   655         (* the last line must be kept *)
   656         j = 0 orelse
   657         (not (is_only_type_information t) andalso
   658          null (Term.add_tvars t []) andalso
   659          not (exists_subterm (is_bad_free frees) t) andalso
   660          length deps >= 2 andalso j mod isar_shrink_factor = 0 andalso
   661          (* kill next to last line, which usually results in a trivial step *)
   662          j <> 1) then
   663        Inference (name, t, rule, deps) :: lines  (* keep line *)
   664      else
   665        map (replace_dependencies_in_line (name, deps)) lines)  (* drop line *)
   666 
   667 (** Isar proof construction and manipulation **)
   668 
   669 type label = string * int
   670 type facts = label list * string list
   671 
   672 datatype isar_qualifier = Show | Then | Moreover | Ultimately
   673 
   674 datatype isar_step =
   675   Fix of (string * typ) list |
   676   Let of term * term |
   677   Assume of label * term |
   678   Prove of isar_qualifier list * label * term * byline
   679 and byline =
   680   By_Metis of facts |
   681   Case_Split of isar_step list list * facts
   682 
   683 fun add_fact_from_dependency fact_names (name as (_, ss)) =
   684   if is_fact fact_names ss then
   685     apsnd (union (op =) (map fst (resolve_fact fact_names ss)))
   686   else
   687     apfst (insert (op =) (raw_label_for_name name))
   688 
   689 fun repair_name "$true" = "c_True"
   690   | repair_name "$false" = "c_False"
   691   | repair_name "$$e" = tptp_equal (* seen in Vampire proofs *)
   692   | repair_name s =
   693     if is_tptp_equal s orelse
   694        (* seen in Vampire proofs *)
   695        (String.isPrefix "sQ" s andalso String.isSuffix "_eqProxy" s) then
   696       tptp_equal
   697     else
   698       s
   699 
   700 (* FIXME: Still needed? Try with SPASS proofs perhaps. *)
   701 val kill_duplicate_assumptions_in_proof =
   702   let
   703     fun relabel_facts subst =
   704       apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
   705     fun do_step (step as Assume (l, t)) (proof, subst, assums) =
   706         (case AList.lookup (op aconv) assums t of
   707            SOME l' => (proof, (l, l') :: subst, assums)
   708          | NONE => (step :: proof, subst, (t, l) :: assums))
   709       | do_step (Prove (qs, l, t, by)) (proof, subst, assums) =
   710         (Prove (qs, l, t,
   711                 case by of
   712                   By_Metis facts => By_Metis (relabel_facts subst facts)
   713                 | Case_Split (proofs, facts) =>
   714                   Case_Split (map do_proof proofs,
   715                               relabel_facts subst facts)) ::
   716          proof, subst, assums)
   717       | do_step step (proof, subst, assums) = (step :: proof, subst, assums)
   718     and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
   719   in do_proof end
   720 
   721 fun used_labels_of_step (Prove (_, _, _, by)) =
   722     (case by of
   723        By_Metis (ls, _) => ls
   724      | Case_Split (proofs, (ls, _)) =>
   725        fold (union (op =) o used_labels_of) proofs ls)
   726   | used_labels_of_step _ = []
   727 and used_labels_of proof = fold (union (op =) o used_labels_of_step) proof []
   728 
   729 fun kill_useless_labels_in_proof proof =
   730   let
   731     val used_ls = used_labels_of proof
   732     fun do_label l = if member (op =) used_ls l then l else no_label
   733     fun do_step (Assume (l, t)) = Assume (do_label l, t)
   734       | do_step (Prove (qs, l, t, by)) =
   735         Prove (qs, do_label l, t,
   736                case by of
   737                  Case_Split (proofs, facts) =>
   738                  Case_Split (map (map do_step) proofs, facts)
   739                | _ => by)
   740       | do_step step = step
   741   in map do_step proof end
   742 
   743 fun prefix_for_depth n = replicate_string (n + 1)
   744 
   745 val relabel_proof =
   746   let
   747     fun aux _ _ _ [] = []
   748       | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
   749         if l = no_label then
   750           Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
   751         else
   752           let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
   753             Assume (l', t) ::
   754             aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
   755           end
   756       | aux subst depth (next_assum, next_fact)
   757             (Prove (qs, l, t, by) :: proof) =
   758         let
   759           val (l', subst, next_fact) =
   760             if l = no_label then
   761               (l, subst, next_fact)
   762             else
   763               let
   764                 val l' = (prefix_for_depth depth have_prefix, next_fact)
   765               in (l', (l, l') :: subst, next_fact + 1) end
   766           val relabel_facts =
   767             apfst (maps (the_list o AList.lookup (op =) subst))
   768           val by =
   769             case by of
   770               By_Metis facts => By_Metis (relabel_facts facts)
   771             | Case_Split (proofs, facts) =>
   772               Case_Split (map (aux subst (depth + 1) (1, 1)) proofs,
   773                           relabel_facts facts)
   774         in
   775           Prove (qs, l', t, by) :: aux subst depth (next_assum, next_fact) proof
   776         end
   777       | aux subst depth nextp (step :: proof) =
   778         step :: aux subst depth nextp proof
   779   in aux [] 0 (1, 1) end
   780 
   781 fun string_for_proof ctxt0 type_enc lam_trans i n =
   782   let
   783     val ctxt =
   784       ctxt0 |> Config.put show_free_types false
   785             |> Config.put show_types true
   786             |> Config.put show_sorts true
   787     fun fix_print_mode f x =
   788       Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
   789                                (print_mode_value ())) f x
   790     fun do_indent ind = replicate_string (ind * indent_size) " "
   791     fun do_free (s, T) =
   792       maybe_quote s ^ " :: " ^
   793       maybe_quote (fix_print_mode (Syntax.string_of_typ ctxt) T)
   794     fun do_label l = if l = no_label then "" else string_for_label l ^ ": "
   795     fun do_have qs =
   796       (if member (op =) qs Moreover then "moreover " else "") ^
   797       (if member (op =) qs Ultimately then "ultimately " else "") ^
   798       (if member (op =) qs Then then
   799          if member (op =) qs Show then "thus" else "hence"
   800        else
   801          if member (op =) qs Show then "show" else "have")
   802     val do_term = maybe_quote o fix_print_mode (Syntax.string_of_term ctxt)
   803     val reconstr = Metis (type_enc, lam_trans)
   804     fun do_facts (ls, ss) =
   805       reconstructor_command reconstr 1 1
   806           (ls |> sort_distinct (prod_ord string_ord int_ord),
   807            ss |> sort_distinct string_ord)
   808     and do_step ind (Fix xs) =
   809         do_indent ind ^ "fix " ^ space_implode " and " (map do_free xs) ^ "\n"
   810       | do_step ind (Let (t1, t2)) =
   811         do_indent ind ^ "let " ^ do_term t1 ^ " = " ^ do_term t2 ^ "\n"
   812       | do_step ind (Assume (l, t)) =
   813         do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
   814       | do_step ind (Prove (qs, l, t, By_Metis facts)) =
   815         do_indent ind ^ do_have qs ^ " " ^
   816         do_label l ^ do_term t ^ " " ^ do_facts facts ^ "\n"
   817       | do_step ind (Prove (qs, l, t, Case_Split (proofs, facts))) =
   818         implode (map (prefix (do_indent ind ^ "moreover\n") o do_block ind)
   819                      proofs) ^
   820         do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ " " ^
   821         do_facts facts ^ "\n"
   822     and do_steps prefix suffix ind steps =
   823       let val s = implode (map (do_step ind) steps) in
   824         replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
   825         String.extract (s, ind * indent_size,
   826                         SOME (size s - ind * indent_size - 1)) ^
   827         suffix ^ "\n"
   828       end
   829     and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
   830     (* One-step proofs are pointless; better use the Metis one-liner
   831        directly. *)
   832     and do_proof [Prove (_, _, _, By_Metis _)] = ""
   833       | do_proof proof =
   834         (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
   835         do_indent 0 ^ "proof -\n" ^ do_steps "" "" 1 proof ^ do_indent 0 ^
   836         (if n <> 1 then "next" else "qed")
   837   in do_proof end
   838 
   839 fun isar_proof_text ctxt isar_proof_requested
   840         (debug, isar_shrink_factor, pool, fact_names, sym_tab, atp_proof, goal)
   841         (one_line_params as (_, _, _, _, subgoal, subgoal_count)) =
   842   let
   843     val isar_shrink_factor =
   844       (if isar_proof_requested then 1 else 2) * isar_shrink_factor
   845     val (params, hyp_ts, concl_t) = strip_subgoal ctxt goal subgoal
   846     val frees = fold Term.add_frees (concl_t :: hyp_ts) []
   847     val one_line_proof = one_line_proof_text one_line_params
   848     val type_enc =
   849       if is_typed_helper_used_in_atp_proof atp_proof then full_typesN
   850       else partial_typesN
   851     val lam_trans = lam_trans_from_atp_proof atp_proof metis_default_lam_trans
   852 
   853     fun isar_proof_of () =
   854       let
   855         val atp_proof =
   856           atp_proof
   857           |> clean_up_atp_proof_dependencies
   858           |> nasty_atp_proof pool
   859           |> map_term_names_in_atp_proof repair_name
   860           |> decode_lines ctxt sym_tab
   861           |> rpair [] |-> fold_rev (add_line fact_names)
   862           |> rpair [] |-> fold_rev add_nontrivial_line
   863           |> rpair (0, [])
   864           |-> fold_rev (add_desired_line isar_shrink_factor fact_names frees)
   865           |> snd
   866         val conj_name = conjecture_prefix ^ string_of_int (length hyp_ts)
   867         val conjs =
   868           atp_proof
   869           |> map_filter (fn Inference (name as (_, ss), _, _, []) =>
   870                             if member (op =) ss conj_name then SOME name else NONE
   871                           | _ => NONE)
   872         fun dep_of_step (Definition _) = NONE
   873           | dep_of_step (Inference (name, _, _, from)) = SOME (from, name)
   874         val ref_graph = atp_proof |> map_filter dep_of_step |> make_ref_graph
   875         val axioms = axioms_of_ref_graph ref_graph conjs
   876         val tainted = tainted_atoms_of_ref_graph ref_graph conjs
   877         val props =
   878           Symtab.empty
   879           |> fold (fn Definition _ => I (* FIXME *)
   880                     | Inference ((s, _), t, _, _) =>
   881                       Symtab.update_new (s,
   882                           t |> member (op = o apsnd fst) tainted s ? s_not))
   883                   atp_proof
   884         (* FIXME: add "fold_rev forall_of (map Var (Term.add_vars t []))"? *)
   885         fun prop_of_clause c =
   886           fold (curry s_disj) (map_filter (Symtab.lookup props o fst) c)
   887                @{term False}
   888         fun label_of_clause c = (space_implode "___" (map fst c), 0)
   889         fun maybe_show outer c =
   890           (outer andalso length c = 1 andalso subset (op =) (c, conjs))
   891           ? cons Show
   892         fun do_have outer qs (gamma, c) =
   893           Prove (maybe_show outer c qs, label_of_clause c, prop_of_clause c,
   894                  By_Metis (fold (add_fact_from_dependency fact_names
   895                                  o the_single) gamma ([], [])))
   896         fun do_inf outer (Have z) = do_have outer [] z
   897           | do_inf outer (Hence z) = do_have outer [Then] z
   898           | do_inf outer (Cases cases) =
   899             let val c = succedent_of_cases cases in
   900               Prove (maybe_show outer c [Ultimately], label_of_clause c,
   901                      prop_of_clause c,
   902                      Case_Split (map (do_case false) cases, ([], [])))
   903             end
   904         and do_case outer (c, infs) =
   905           Assume (label_of_clause c, prop_of_clause c) ::
   906           map (do_inf outer) infs
   907         val isar_proof =
   908           (if null params then [] else [Fix params]) @
   909           (ref_graph
   910            |> redirect_graph axioms tainted
   911            |> chain_direct_proof
   912            |> map (do_inf true)
   913            |> kill_duplicate_assumptions_in_proof
   914            |> kill_useless_labels_in_proof
   915            |> relabel_proof)
   916           |> string_for_proof ctxt type_enc lam_trans subgoal subgoal_count
   917       in
   918         case isar_proof of
   919           "" =>
   920           if isar_proof_requested then
   921             "\nNo structured proof available (proof too short)."
   922           else
   923             ""
   924         | _ =>
   925           "\n\n" ^ (if isar_proof_requested then "Structured proof"
   926                     else "Perhaps this will work") ^
   927           ":\n" ^ Markup.markup Isabelle_Markup.sendback isar_proof
   928       end
   929     val isar_proof =
   930       if debug then
   931         isar_proof_of ()
   932       else case try isar_proof_of () of
   933         SOME s => s
   934       | NONE => if isar_proof_requested then
   935                   "\nWarning: The Isar proof construction failed."
   936                 else
   937                   ""
   938   in one_line_proof ^ isar_proof end
   939 
   940 fun proof_text ctxt isar_proof isar_params
   941                (one_line_params as (preplay, _, _, _, _, _)) =
   942   (if case preplay of Failed_to_Play _ => true | _ => isar_proof then
   943      isar_proof_text ctxt isar_proof isar_params
   944    else
   945      one_line_proof_text) one_line_params
   946 
   947 end;