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