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