src/HOL/Tools/Sledgehammer/sledgehammer_reconstruct.ML
author blanchet
Thu Sep 16 13:44:41 2010 +0200 (2010-09-16)
changeset 39454 acb25e9cf6fb
parent 39453 1740a2d6bef9
child 39455 c6b21584f336
permissions -rw-r--r--
factor out the inverse of "nice_atp_problem"
blanchet@38988
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_reconstruct.ML
blanchet@38027
     2
    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory
blanchet@38027
     3
    Author:     Claire Quigley, Cambridge University Computer Laboratory
blanchet@36392
     4
    Author:     Jasmin Blanchette, TU Muenchen
paulson@21978
     5
wenzelm@33310
     6
Transfer of proofs from external provers.
wenzelm@33310
     7
*)
wenzelm@33310
     8
blanchet@38988
     9
signature SLEDGEHAMMER_RECONSTRUCT =
paulson@24425
    10
sig
blanchet@38988
    11
  type locality = Sledgehammer_Filter.locality
blanchet@36281
    12
  type minimize_command = string list -> string
blanchet@38818
    13
  type metis_params =
blanchet@39327
    14
    string * bool * minimize_command * string * (string * locality) list vector
blanchet@39327
    15
    * thm * int
blanchet@38818
    16
  type isar_params =
blanchet@38040
    17
    string Symtab.table * bool * int * Proof.context * int list list
blanchet@38818
    18
  type text_result = string * (string * locality) list
blanchet@38818
    19
blanchet@38818
    20
  val metis_proof_text : metis_params -> text_result
blanchet@38818
    21
  val isar_proof_text : isar_params -> metis_params -> text_result
blanchet@38818
    22
  val proof_text : bool -> isar_params -> metis_params -> text_result
paulson@24425
    23
end;
paulson@21978
    24
blanchet@38988
    25
structure Sledgehammer_Reconstruct : SLEDGEHAMMER_RECONSTRUCT =
paulson@21978
    26
struct
paulson@21978
    27
blanchet@38028
    28
open ATP_Problem
blanchet@39452
    29
open ATP_Proof
blanchet@37578
    30
open Metis_Clauses
blanchet@36478
    31
open Sledgehammer_Util
blanchet@38988
    32
open Sledgehammer_Filter
blanchet@38282
    33
open Sledgehammer_Translate
paulson@21978
    34
blanchet@36281
    35
type minimize_command = string list -> string
blanchet@38818
    36
type metis_params =
blanchet@39327
    37
  string * bool * minimize_command * string * (string * locality) list vector
blanchet@39327
    38
  * thm * int
blanchet@38818
    39
type isar_params =
blanchet@38818
    40
  string Symtab.table * bool * int * Proof.context * int list list
blanchet@38818
    41
type text_result = string * (string * locality) list
blanchet@36281
    42
blanchet@39453
    43
blanchet@39453
    44
(** Soft-core proof reconstruction: Metis one-liner **)
blanchet@39453
    45
blanchet@39453
    46
fun string_for_label (s, num) = s ^ string_of_int num
blanchet@39453
    47
blanchet@39453
    48
fun metis_using [] = ""
blanchet@39453
    49
  | metis_using ls =
blanchet@39453
    50
    "using " ^ space_implode " " (map string_for_label ls) ^ " "
blanchet@39453
    51
fun metis_apply _ 1 = "by "
blanchet@39453
    52
  | metis_apply 1 _ = "apply "
blanchet@39453
    53
  | metis_apply i _ = "prefer " ^ string_of_int i ^ " apply "
blanchet@39453
    54
fun metis_name full_types = if full_types then "metisFT" else "metis"
blanchet@39453
    55
fun metis_call full_types [] = metis_name full_types
blanchet@39453
    56
  | metis_call full_types ss =
blanchet@39453
    57
    "(" ^ metis_name full_types ^ " " ^ space_implode " " ss ^ ")"
blanchet@39453
    58
fun metis_command full_types i n (ls, ss) =
blanchet@39453
    59
  metis_using ls ^ metis_apply i n ^ metis_call full_types ss
blanchet@39453
    60
fun metis_line banner full_types i n ss =
blanchet@39453
    61
  banner ^ ": " ^
blanchet@39453
    62
  Markup.markup Markup.sendback (metis_command full_types i n ([], ss)) ^ "."
blanchet@39453
    63
fun minimize_line _ [] = ""
blanchet@39453
    64
  | minimize_line minimize_command ss =
blanchet@39453
    65
    case minimize_command ss of
blanchet@39453
    66
      "" => ""
blanchet@39453
    67
    | command =>
blanchet@39453
    68
      "\nTo minimize the number of lemmas, try this: " ^
blanchet@39453
    69
      Markup.markup Markup.sendback command ^ "."
blanchet@39453
    70
blanchet@39453
    71
fun resolve_axiom axiom_names (Str (_, s)) =
blanchet@39453
    72
    (case strip_prefix_and_unascii axiom_prefix s of
blanchet@39453
    73
       SOME s' => (case find_first_in_list_vector axiom_names s' of
blanchet@39453
    74
                     SOME x => [(s', x)]
blanchet@39453
    75
                   | NONE => [])
blanchet@39453
    76
     | NONE => [])
blanchet@39453
    77
  | resolve_axiom axiom_names (Num num) =
blanchet@39453
    78
    case Int.fromString num of
blanchet@39453
    79
      SOME j =>
blanchet@39453
    80
      if j > 0 andalso j <= Vector.length axiom_names then
blanchet@39453
    81
        Vector.sub (axiom_names, j - 1)
blanchet@39453
    82
      else
blanchet@39453
    83
        []
blanchet@39453
    84
    | NONE => []
blanchet@39453
    85
blanchet@39453
    86
fun add_fact axiom_names (Inference (name, _, [])) =
blanchet@39453
    87
    append (resolve_axiom axiom_names name)
blanchet@39453
    88
  | add_fact _ _ = I
blanchet@39453
    89
blanchet@39453
    90
fun used_facts_in_tstplike_proof axiom_names =
blanchet@39454
    91
  atp_proof_from_tstplike_string #> rpair [] #-> fold (add_fact axiom_names)
blanchet@39453
    92
blanchet@39453
    93
fun used_facts axiom_names =
blanchet@39453
    94
  used_facts_in_tstplike_proof axiom_names
blanchet@39453
    95
  #> List.partition (curry (op =) Chained o snd)
blanchet@39453
    96
  #> pairself (sort_distinct (string_ord o pairself fst))
blanchet@39453
    97
blanchet@39453
    98
fun metis_proof_text (banner, full_types, minimize_command,
blanchet@39453
    99
                      tstplike_proof, axiom_names, goal, i) =
blanchet@39453
   100
  let
blanchet@39453
   101
    val (chained_lemmas, other_lemmas) =
blanchet@39453
   102
      used_facts axiom_names tstplike_proof
blanchet@39453
   103
    val n = Logic.count_prems (prop_of goal)
blanchet@39453
   104
  in
blanchet@39453
   105
    (metis_line banner full_types i n (map fst other_lemmas) ^
blanchet@39453
   106
     minimize_line minimize_command (map fst (other_lemmas @ chained_lemmas)),
blanchet@39453
   107
     other_lemmas @ chained_lemmas)
blanchet@39453
   108
  end
blanchet@39453
   109
blanchet@39453
   110
blanchet@39453
   111
(** Hard-core proof reconstruction: structured Isar proofs **)
blanchet@39453
   112
blanchet@38014
   113
(* Simple simplifications to ensure that sort annotations don't leave a trail of
blanchet@38014
   114
   spurious "True"s. *)
blanchet@38014
   115
fun s_not @{const False} = @{const True}
blanchet@38014
   116
  | s_not @{const True} = @{const False}
blanchet@38014
   117
  | s_not (@{const Not} $ t) = t
blanchet@38014
   118
  | s_not t = @{const Not} $ t
blanchet@38014
   119
fun s_conj (@{const True}, t2) = t2
blanchet@38014
   120
  | s_conj (t1, @{const True}) = t1
blanchet@38014
   121
  | s_conj p = HOLogic.mk_conj p
blanchet@38014
   122
fun s_disj (@{const False}, t2) = t2
blanchet@38014
   123
  | s_disj (t1, @{const False}) = t1
blanchet@38014
   124
  | s_disj p = HOLogic.mk_disj p
blanchet@38014
   125
fun s_imp (@{const True}, t2) = t2
blanchet@38014
   126
  | s_imp (t1, @{const False}) = s_not t1
blanchet@38014
   127
  | s_imp p = HOLogic.mk_imp p
blanchet@38014
   128
fun s_iff (@{const True}, t2) = t2
blanchet@38014
   129
  | s_iff (t1, @{const True}) = t1
blanchet@38014
   130
  | s_iff (t1, t2) = HOLogic.eq_const HOLogic.boolT $ t1 $ t2
blanchet@38014
   131
blanchet@39425
   132
fun forall_of v t = HOLogic.all_const (fastype_of v) $ lambda v t
blanchet@39425
   133
fun exists_of v t = HOLogic.exists_const (fastype_of v) $ lambda v t
blanchet@39425
   134
blanchet@39452
   135
fun negate_term (Const (@{const_name All}, T) $ Abs (s, T', t')) =
blanchet@39452
   136
    Const (@{const_name Ex}, T) $ Abs (s, T', negate_term t')
blanchet@39452
   137
  | negate_term (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
blanchet@39452
   138
    Const (@{const_name All}, T) $ Abs (s, T', negate_term t')
blanchet@39452
   139
  | negate_term (@{const HOL.implies} $ t1 $ t2) =
blanchet@39452
   140
    @{const HOL.conj} $ t1 $ negate_term t2
blanchet@39452
   141
  | negate_term (@{const HOL.conj} $ t1 $ t2) =
blanchet@39452
   142
    @{const HOL.disj} $ negate_term t1 $ negate_term t2
blanchet@39452
   143
  | negate_term (@{const HOL.disj} $ t1 $ t2) =
blanchet@39452
   144
    @{const HOL.conj} $ negate_term t1 $ negate_term t2
blanchet@39452
   145
  | negate_term (@{const Not} $ t) = t
blanchet@39452
   146
  | negate_term t = @{const Not} $ t
blanchet@39368
   147
blanchet@39453
   148
val indent_size = 2
blanchet@39453
   149
val no_label = ("", ~1)
blanchet@39453
   150
blanchet@39453
   151
val raw_prefix = "X"
blanchet@39453
   152
val assum_prefix = "A"
blanchet@39453
   153
val fact_prefix = "F"
blanchet@39370
   154
blanchet@39370
   155
fun resolve_conjecture conjecture_shape (Str (num, s)) =
blanchet@39370
   156
    let
blanchet@39373
   157
      val k = case try (unprefix conjecture_prefix) s of
blanchet@39373
   158
                SOME s => Int.fromString s |> the_default ~1
blanchet@39373
   159
              | NONE => case Int.fromString num of
blanchet@39453
   160
                          SOME j => find_index (exists (curry (op =) j))
blanchet@39453
   161
                                               conjecture_shape
blanchet@39373
   162
                        | NONE => ~1
blanchet@39370
   163
    in if k >= 0 then [k] else [] end
blanchet@39370
   164
  | resolve_conjecture conjecture_shape (Num num) =
blanchet@39370
   165
    resolve_conjecture conjecture_shape (Str (num, "")) (* HACK *)
blanchet@39453
   166
blanchet@39453
   167
val is_axiom = not o null oo resolve_axiom
blanchet@39370
   168
val is_conjecture = not o null oo resolve_conjecture
blanchet@36291
   169
blanchet@39453
   170
fun raw_label_for_name conjecture_shape name =
blanchet@39453
   171
  case resolve_conjecture conjecture_shape name of
blanchet@39453
   172
    [j] => (conjecture_prefix, j)
blanchet@39453
   173
  | _ => case Int.fromString (step_num name) of
blanchet@39453
   174
           SOME j => (raw_prefix, j)
blanchet@39453
   175
         | NONE => (raw_prefix ^ step_num name, 0)
blanchet@39453
   176
paulson@21978
   177
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   178
blanchet@37991
   179
exception FO_TERM of string fo_term list
blanchet@37994
   180
exception FORMULA of (string, string fo_term) formula list
blanchet@37991
   181
exception SAME of unit
paulson@21978
   182
blanchet@36909
   183
(* Type variables are given the basic sort "HOL.type". Some will later be
blanchet@37991
   184
   constrained by information from type literals, or by type inference. *)
blanchet@37991
   185
fun type_from_fo_term tfrees (u as ATerm (a, us)) =
blanchet@37991
   186
  let val Ts = map (type_from_fo_term tfrees) us in
blanchet@38748
   187
    case strip_prefix_and_unascii type_const_prefix a of
blanchet@37991
   188
      SOME b => Type (invert_const b, Ts)
blanchet@37991
   189
    | NONE =>
blanchet@37991
   190
      if not (null us) then
blanchet@37991
   191
        raise FO_TERM [u]  (* only "tconst"s have type arguments *)
blanchet@38748
   192
      else case strip_prefix_and_unascii tfree_prefix a of
blanchet@37991
   193
        SOME b =>
blanchet@37991
   194
        let val s = "'" ^ b in
blanchet@37991
   195
          TFree (s, AList.lookup (op =) tfrees s |> the_default HOLogic.typeS)
blanchet@37991
   196
        end
blanchet@36486
   197
      | NONE =>
blanchet@38748
   198
        case strip_prefix_and_unascii tvar_prefix a of
blanchet@37991
   199
          SOME b => TVar (("'" ^ b, 0), HOLogic.typeS)
blanchet@36486
   200
        | NONE =>
blanchet@37991
   201
          (* Variable from the ATP, say "X1" *)
blanchet@37991
   202
          Type_Infer.param 0 (a, HOLogic.typeS)
blanchet@37991
   203
  end
paulson@21978
   204
blanchet@38014
   205
(* Type class literal applied to a type. Returns triple of polarity, class,
blanchet@38014
   206
   type. *)
blanchet@38014
   207
fun type_constraint_from_term pos tfrees (u as ATerm (a, us)) =
blanchet@38748
   208
  case (strip_prefix_and_unascii class_prefix a,
blanchet@38014
   209
        map (type_from_fo_term tfrees) us) of
blanchet@38014
   210
    (SOME b, [T]) => (pos, b, T)
blanchet@38014
   211
  | _ => raise FO_TERM [u]
blanchet@38014
   212
blanchet@38085
   213
(** Accumulate type constraints in a formula: negative type literals **)
blanchet@38014
   214
fun add_var (key, z)  = Vartab.map_default (key, []) (cons z)
blanchet@38014
   215
fun add_type_constraint (false, cl, TFree (a ,_)) = add_var ((a, ~1), cl)
blanchet@38014
   216
  | add_type_constraint (false, cl, TVar (ix, _)) = add_var (ix, cl)
blanchet@38014
   217
  | add_type_constraint _ = I
blanchet@38014
   218
blanchet@38490
   219
fun repair_atp_variable_name f s =
blanchet@36486
   220
  let
blanchet@36486
   221
    fun subscript_name s n = s ^ nat_subscript n
blanchet@38488
   222
    val s = String.map f s
blanchet@36486
   223
  in
blanchet@36486
   224
    case space_explode "_" s of
blanchet@36486
   225
      [_] => (case take_suffix Char.isDigit (String.explode s) of
blanchet@36486
   226
                (cs1 as _ :: _, cs2 as _ :: _) =>
blanchet@36486
   227
                subscript_name (String.implode cs1)
blanchet@36486
   228
                               (the (Int.fromString (String.implode cs2)))
blanchet@36486
   229
              | (_, _) => s)
blanchet@36486
   230
    | [s1, s2] => (case Int.fromString s2 of
blanchet@36486
   231
                     SOME n => subscript_name s1 n
blanchet@36486
   232
                   | NONE => s)
blanchet@36486
   233
    | _ => s
blanchet@36486
   234
  end
blanchet@36486
   235
blanchet@36909
   236
(* First-order translation. No types are known for variables. "HOLogic.typeT"
blanchet@38014
   237
   should allow them to be inferred. *)
blanchet@38014
   238
fun raw_term_from_pred thy full_types tfrees =
blanchet@36909
   239
  let
blanchet@37643
   240
    fun aux opt_T extra_us u =
blanchet@36909
   241
      case u of
blanchet@37991
   242
        ATerm ("hBOOL", [u1]) => aux (SOME @{typ bool}) [] u1
blanchet@37991
   243
      | ATerm ("hAPP", [u1, u2]) => aux opt_T (u2 :: extra_us) u1
blanchet@37991
   244
      | ATerm (a, us) =>
blanchet@36909
   245
        if a = type_wrapper_name then
blanchet@36909
   246
          case us of
blanchet@37643
   247
            [typ_u, term_u] =>
blanchet@37991
   248
            aux (SOME (type_from_fo_term tfrees typ_u)) extra_us term_u
blanchet@37991
   249
          | _ => raise FO_TERM us
blanchet@38748
   250
        else case strip_prefix_and_unascii const_prefix a of
blanchet@36909
   251
          SOME "equal" =>
blanchet@39106
   252
          let val ts = map (aux NONE []) us in
blanchet@39106
   253
            if length ts = 2 andalso hd ts aconv List.last ts then
blanchet@39106
   254
              (* Vampire is keen on producing these. *)
blanchet@39106
   255
              @{const True}
blanchet@39106
   256
            else
blanchet@39106
   257
              list_comb (Const (@{const_name HOL.eq}, HOLogic.typeT), ts)
blanchet@39106
   258
          end
blanchet@36909
   259
        | SOME b =>
blanchet@36909
   260
          let
blanchet@36909
   261
            val c = invert_const b
blanchet@36909
   262
            val num_type_args = num_type_args thy c
blanchet@37643
   263
            val (type_us, term_us) =
blanchet@37643
   264
              chop (if full_types then 0 else num_type_args) us
blanchet@37643
   265
            (* Extra args from "hAPP" come after any arguments given directly to
blanchet@37643
   266
               the constant. *)
blanchet@37643
   267
            val term_ts = map (aux NONE []) term_us
blanchet@37643
   268
            val extra_ts = map (aux NONE []) extra_us
blanchet@36909
   269
            val t =
blanchet@36909
   270
              Const (c, if full_types then
blanchet@36909
   271
                          case opt_T of
blanchet@37643
   272
                            SOME T => map fastype_of term_ts ---> T
blanchet@36909
   273
                          | NONE =>
blanchet@36909
   274
                            if num_type_args = 0 then
blanchet@36909
   275
                              Sign.const_instance thy (c, [])
blanchet@36909
   276
                            else
blanchet@36909
   277
                              raise Fail ("no type information for " ^ quote c)
blanchet@36909
   278
                        else
blanchet@37998
   279
                          Sign.const_instance thy (c,
blanchet@37998
   280
                              map (type_from_fo_term tfrees) type_us))
blanchet@37643
   281
          in list_comb (t, term_ts @ extra_ts) end
blanchet@36909
   282
        | NONE => (* a free or schematic variable *)
blanchet@36909
   283
          let
blanchet@37643
   284
            val ts = map (aux NONE []) (us @ extra_us)
blanchet@36909
   285
            val T = map fastype_of ts ---> HOLogic.typeT
blanchet@36909
   286
            val t =
blanchet@38748
   287
              case strip_prefix_and_unascii fixed_var_prefix a of
blanchet@36909
   288
                SOME b => Free (b, T)
blanchet@36909
   289
              | NONE =>
blanchet@38748
   290
                case strip_prefix_and_unascii schematic_var_prefix a of
blanchet@36967
   291
                  SOME b => Var ((b, 0), T)
blanchet@36909
   292
                | NONE =>
blanchet@39452
   293
                  if is_atp_variable a then
blanchet@38490
   294
                    Var ((repair_atp_variable_name Char.toLower a, 0), T)
blanchet@38017
   295
                  else
blanchet@38488
   296
                    (* Skolem constants? *)
blanchet@38490
   297
                    Var ((repair_atp_variable_name Char.toUpper a, 0), T)
blanchet@36909
   298
          in list_comb (t, ts) end
blanchet@38014
   299
  in aux (SOME HOLogic.boolT) [] end
paulson@21978
   300
blanchet@38014
   301
fun term_from_pred thy full_types tfrees pos (u as ATerm (s, _)) =
blanchet@38014
   302
  if String.isPrefix class_prefix s then
blanchet@38014
   303
    add_type_constraint (type_constraint_from_term pos tfrees u)
blanchet@38014
   304
    #> pair @{const True}
blanchet@38014
   305
  else
blanchet@38014
   306
    pair (raw_term_from_pred thy full_types tfrees u)
blanchet@36402
   307
blanchet@36555
   308
val combinator_table =
blanchet@36555
   309
  [(@{const_name COMBI}, @{thm COMBI_def_raw}),
blanchet@36555
   310
   (@{const_name COMBK}, @{thm COMBK_def_raw}),
blanchet@36555
   311
   (@{const_name COMBB}, @{thm COMBB_def_raw}),
blanchet@36555
   312
   (@{const_name COMBC}, @{thm COMBC_def_raw}),
blanchet@36555
   313
   (@{const_name COMBS}, @{thm COMBS_def_raw})]
blanchet@36555
   314
blanchet@36555
   315
fun uncombine_term (t1 $ t2) = betapply (pairself uncombine_term (t1, t2))
blanchet@36555
   316
  | uncombine_term (Abs (s, T, t')) = Abs (s, T, uncombine_term t')
blanchet@36555
   317
  | uncombine_term (t as Const (x as (s, _))) =
blanchet@36555
   318
    (case AList.lookup (op =) combinator_table s of
blanchet@36555
   319
       SOME thm => thm |> prop_of |> specialize_type @{theory} x |> Logic.dest_equals |> snd
blanchet@36555
   320
     | NONE => t)
blanchet@36555
   321
  | uncombine_term t = t
blanchet@36555
   322
blanchet@37991
   323
(* Update schematic type variables with detected sort constraints. It's not
blanchet@37991
   324
   totally clear when this code is necessary. *)
blanchet@38014
   325
fun repair_tvar_sorts (t, tvar_tab) =
blanchet@36909
   326
  let
blanchet@37991
   327
    fun do_type (Type (a, Ts)) = Type (a, map do_type Ts)
blanchet@37991
   328
      | do_type (TVar (xi, s)) =
blanchet@37991
   329
        TVar (xi, the_default s (Vartab.lookup tvar_tab xi))
blanchet@37991
   330
      | do_type (TFree z) = TFree z
blanchet@37991
   331
    fun do_term (Const (a, T)) = Const (a, do_type T)
blanchet@37991
   332
      | do_term (Free (a, T)) = Free (a, do_type T)
blanchet@37991
   333
      | do_term (Var (xi, T)) = Var (xi, do_type T)
blanchet@37991
   334
      | do_term (t as Bound _) = t
blanchet@37991
   335
      | do_term (Abs (a, T, t)) = Abs (a, do_type T, do_term t)
blanchet@37991
   336
      | do_term (t1 $ t2) = do_term t1 $ do_term t2
blanchet@37991
   337
  in t |> not (Vartab.is_empty tvar_tab) ? do_term end
blanchet@37991
   338
blanchet@39425
   339
fun quantify_over_var quant_of var_s t =
blanchet@39425
   340
  let
blanchet@39425
   341
    val vars = [] |> Term.add_vars t |> filter (fn ((s, _), _) => s = var_s)
blanchet@39425
   342
                  |> map Var
blanchet@39425
   343
  in fold_rev quant_of vars t end
blanchet@37991
   344
blanchet@38085
   345
(* Interpret an ATP formula as a HOL term, extracting sort constraints as they
blanchet@38085
   346
   appear in the formula. *)
blanchet@38014
   347
fun prop_from_formula thy full_types tfrees phi =
blanchet@38014
   348
  let
blanchet@38014
   349
    fun do_formula pos phi =
blanchet@37991
   350
      case phi of
blanchet@38014
   351
        AQuant (_, [], phi) => do_formula pos phi
blanchet@37991
   352
      | AQuant (q, x :: xs, phi') =>
blanchet@38014
   353
        do_formula pos (AQuant (q, xs, phi'))
blanchet@39425
   354
        #>> quantify_over_var (case q of
blanchet@39425
   355
                                 AForall => forall_of
blanchet@39425
   356
                               | AExists => exists_of)
blanchet@39425
   357
                              (repair_atp_variable_name Char.toLower x)
blanchet@38014
   358
      | AConn (ANot, [phi']) => do_formula (not pos) phi' #>> s_not
blanchet@37991
   359
      | AConn (c, [phi1, phi2]) =>
blanchet@38014
   360
        do_formula (pos |> c = AImplies ? not) phi1
blanchet@38014
   361
        ##>> do_formula pos phi2
blanchet@38014
   362
        #>> (case c of
blanchet@38014
   363
               AAnd => s_conj
blanchet@38014
   364
             | AOr => s_disj
blanchet@38014
   365
             | AImplies => s_imp
blanchet@38038
   366
             | AIf => s_imp o swap
blanchet@38038
   367
             | AIff => s_iff
blanchet@38038
   368
             | ANotIff => s_not o s_iff)
blanchet@38034
   369
      | AAtom tm => term_from_pred thy full_types tfrees pos tm
blanchet@37991
   370
      | _ => raise FORMULA [phi]
blanchet@38014
   371
  in repair_tvar_sorts (do_formula true phi Vartab.empty) end
blanchet@37991
   372
blanchet@36556
   373
fun check_formula ctxt =
wenzelm@39288
   374
  Type.constraint HOLogic.boolT
blanchet@36486
   375
  #> Syntax.check_term (ProofContext.set_mode ProofContext.mode_schematic ctxt)
paulson@21978
   376
paulson@21978
   377
paulson@21978
   378
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   379
blanchet@36486
   380
fun unvarify_term (Var ((s, 0), T)) = Free (s, T)
blanchet@36486
   381
  | unvarify_term t = raise TERM ("unvarify_term: non-Var", [t])
paulson@21978
   382
blanchet@39368
   383
fun decode_line full_types tfrees (Definition (name, phi1, phi2)) ctxt =
blanchet@36486
   384
    let
blanchet@37991
   385
      val thy = ProofContext.theory_of ctxt
blanchet@37991
   386
      val t1 = prop_from_formula thy full_types tfrees phi1
blanchet@36551
   387
      val vars = snd (strip_comb t1)
blanchet@36486
   388
      val frees = map unvarify_term vars
blanchet@36486
   389
      val unvarify_args = subst_atomic (vars ~~ frees)
blanchet@37991
   390
      val t2 = prop_from_formula thy full_types tfrees phi2
blanchet@36551
   391
      val (t1, t2) =
blanchet@36551
   392
        HOLogic.eq_const HOLogic.typeT $ t1 $ t2
blanchet@36556
   393
        |> unvarify_args |> uncombine_term |> check_formula ctxt
blanchet@36555
   394
        |> HOLogic.dest_eq
blanchet@36486
   395
    in
blanchet@39368
   396
      (Definition (name, t1, t2),
blanchet@36551
   397
       fold Variable.declare_term (maps OldTerm.term_frees [t1, t2]) ctxt)
blanchet@36486
   398
    end
blanchet@39368
   399
  | decode_line full_types tfrees (Inference (name, u, deps)) ctxt =
blanchet@36551
   400
    let
blanchet@37991
   401
      val thy = ProofContext.theory_of ctxt
blanchet@37991
   402
      val t = u |> prop_from_formula thy full_types tfrees
blanchet@37998
   403
                |> uncombine_term |> check_formula ctxt
blanchet@36551
   404
    in
blanchet@39368
   405
      (Inference (name, t, deps),
blanchet@36551
   406
       fold Variable.declare_term (OldTerm.term_frees t) ctxt)
blanchet@36486
   407
    end
blanchet@36967
   408
fun decode_lines ctxt full_types tfrees lines =
blanchet@36967
   409
  fst (fold_map (decode_line full_types tfrees) lines ctxt)
paulson@21978
   410
blanchet@38035
   411
fun is_same_inference _ (Definition _) = false
blanchet@38035
   412
  | is_same_inference t (Inference (_, t', _)) = t aconv t'
blanchet@36486
   413
blanchet@36486
   414
(* No "real" literals means only type information (tfree_tcs, clsrel, or
blanchet@36486
   415
   clsarity). *)
blanchet@36486
   416
val is_only_type_information = curry (op aconv) HOLogic.true_const
blanchet@36486
   417
blanchet@39373
   418
fun replace_one_dependency (old, new) dep =
blanchet@39452
   419
  if is_same_step (dep, old) then new else [dep]
blanchet@39373
   420
fun replace_dependencies_in_line _ (line as Definition _) = line
blanchet@39373
   421
  | replace_dependencies_in_line p (Inference (name, t, deps)) =
blanchet@39373
   422
    Inference (name, t, fold (union (op =) o replace_one_dependency p) deps [])
paulson@21978
   423
blanchet@38085
   424
(* Discard axioms; consolidate adjacent lines that prove the same formula, since
blanchet@38085
   425
   they differ only in type information.*)
blanchet@36551
   426
fun add_line _ _ (line as Definition _) lines = line :: lines
blanchet@39368
   427
  | add_line conjecture_shape axiom_names (Inference (name, t, [])) lines =
blanchet@38085
   428
    (* No dependencies: axiom, conjecture, or (for Vampire) internal axioms or
blanchet@38085
   429
       definitions. *)
blanchet@39370
   430
    if is_axiom axiom_names name then
blanchet@36486
   431
      (* Axioms are not proof lines. *)
blanchet@36486
   432
      if is_only_type_information t then
blanchet@39373
   433
        map (replace_dependencies_in_line (name, [])) lines
blanchet@36486
   434
      (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   435
      else case take_prefix (not o is_same_inference t) lines of
blanchet@39373
   436
        (_, []) => lines (* no repetition of proof line *)
blanchet@39368
   437
      | (pre, Inference (name', _, _) :: post) =>
blanchet@39373
   438
        pre @ map (replace_dependencies_in_line (name', [name])) post
blanchet@39370
   439
    else if is_conjecture conjecture_shape name then
blanchet@39368
   440
      Inference (name, negate_term t, []) :: lines
blanchet@36551
   441
    else
blanchet@39373
   442
      map (replace_dependencies_in_line (name, [])) lines
blanchet@39368
   443
  | add_line _ _ (Inference (name, t, deps)) lines =
blanchet@36486
   444
    (* Type information will be deleted later; skip repetition test. *)
blanchet@36486
   445
    if is_only_type_information t then
blanchet@39368
   446
      Inference (name, t, deps) :: lines
blanchet@36486
   447
    (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   448
    else case take_prefix (not o is_same_inference t) lines of
blanchet@36486
   449
      (* FIXME: Doesn't this code risk conflating proofs involving different
blanchet@38035
   450
         types? *)
blanchet@39368
   451
       (_, []) => Inference (name, t, deps) :: lines
blanchet@39368
   452
     | (pre, Inference (name', t', _) :: post) =>
blanchet@39368
   453
       Inference (name, t', deps) ::
blanchet@39373
   454
       pre @ map (replace_dependencies_in_line (name', [name])) post
paulson@22044
   455
blanchet@36486
   456
(* Recursively delete empty lines (type information) from the proof. *)
blanchet@39368
   457
fun add_nontrivial_line (Inference (name, t, [])) lines =
blanchet@39373
   458
    if is_only_type_information t then delete_dependency name lines
blanchet@39368
   459
    else Inference (name, t, []) :: lines
blanchet@36486
   460
  | add_nontrivial_line line lines = line :: lines
blanchet@39373
   461
and delete_dependency name lines =
blanchet@39373
   462
  fold_rev add_nontrivial_line
blanchet@39373
   463
           (map (replace_dependencies_in_line (name, [])) lines) []
blanchet@36486
   464
blanchet@37323
   465
(* ATPs sometimes reuse free variable names in the strangest ways. Removing
blanchet@37323
   466
   offending lines often does the trick. *)
blanchet@36560
   467
fun is_bad_free frees (Free x) = not (member (op =) frees x)
blanchet@36560
   468
  | is_bad_free _ _ = false
paulson@22470
   469
blanchet@39368
   470
fun add_desired_line _ _ _ _ (line as Definition (name, _, _)) (j, lines) =
blanchet@39373
   471
    (j, line :: map (replace_dependencies_in_line (name, [])) lines)
blanchet@38282
   472
  | add_desired_line isar_shrink_factor conjecture_shape axiom_names frees
blanchet@39368
   473
                     (Inference (name, t, deps)) (j, lines) =
blanchet@36402
   474
    (j + 1,
blanchet@39370
   475
     if is_axiom axiom_names name orelse
blanchet@39370
   476
        is_conjecture conjecture_shape name orelse
blanchet@39373
   477
        (* the last line must be kept *)
blanchet@39373
   478
        j = 0 orelse
blanchet@36570
   479
        (not (is_only_type_information t) andalso
blanchet@36570
   480
         null (Term.add_tvars t []) andalso
blanchet@36570
   481
         not (exists_subterm (is_bad_free frees) t) andalso
blanchet@39373
   482
         length deps >= 2 andalso j mod isar_shrink_factor = 0 andalso
blanchet@39373
   483
         (* kill next to last line, which usually results in a trivial step *)
blanchet@39373
   484
         j <> 1) then
blanchet@39368
   485
       Inference (name, t, deps) :: lines  (* keep line *)
blanchet@36402
   486
     else
blanchet@39373
   487
       map (replace_dependencies_in_line (name, deps)) lines)  (* drop line *)
paulson@21978
   488
blanchet@36486
   489
(** Isar proof construction and manipulation **)
blanchet@36486
   490
blanchet@36486
   491
fun merge_fact_sets (ls1, ss1) (ls2, ss2) =
blanchet@36486
   492
  (union (op =) ls1 ls2, union (op =) ss1 ss2)
blanchet@36402
   493
blanchet@36402
   494
type label = string * int
blanchet@36402
   495
type facts = label list * string list
blanchet@36402
   496
blanchet@39452
   497
datatype isar_qualifier = Show | Then | Moreover | Ultimately
blanchet@36291
   498
blanchet@39452
   499
datatype isar_step =
blanchet@36478
   500
  Fix of (string * typ) list |
blanchet@36486
   501
  Let of term * term |
blanchet@36402
   502
  Assume of label * term |
blanchet@39452
   503
  Have of isar_qualifier list * label * term * byline
blanchet@36402
   504
and byline =
blanchet@36564
   505
  ByMetis of facts |
blanchet@39452
   506
  CaseSplit of isar_step list list * facts
blanchet@36402
   507
blanchet@36574
   508
fun smart_case_split [] facts = ByMetis facts
blanchet@36574
   509
  | smart_case_split proofs facts = CaseSplit (proofs, facts)
blanchet@36574
   510
blanchet@39373
   511
fun add_fact_from_dependency conjecture_shape axiom_names name =
blanchet@39370
   512
  if is_axiom axiom_names name then
blanchet@39368
   513
    apsnd (union (op =) (map fst (resolve_axiom axiom_names name)))
blanchet@36475
   514
  else
blanchet@39370
   515
    apfst (insert (op =) (raw_label_for_name conjecture_shape name))
blanchet@36402
   516
blanchet@39370
   517
fun step_for_line _ _ _ (Definition (_, t1, t2)) = Let (t1, t2)
blanchet@39370
   518
  | step_for_line conjecture_shape _ _ (Inference (name, t, [])) =
blanchet@39370
   519
    Assume (raw_label_for_name conjecture_shape name, t)
blanchet@39370
   520
  | step_for_line conjecture_shape axiom_names j (Inference (name, t, deps)) =
blanchet@39370
   521
    Have (if j = 1 then [Show] else [],
blanchet@39425
   522
          raw_label_for_name conjecture_shape name,
blanchet@39425
   523
          fold_rev forall_of (map Var (Term.add_vars t [])) t,
blanchet@39373
   524
          ByMetis (fold (add_fact_from_dependency conjecture_shape axiom_names)
blanchet@39373
   525
                        deps ([], [])))
blanchet@36291
   526
blanchet@39454
   527
fun repair_name "$true" = "c_True"
blanchet@39454
   528
  | repair_name "$false" = "c_False"
blanchet@39454
   529
  | repair_name "$$e" = "c_equal" (* seen in Vampire proofs *)
blanchet@39454
   530
  | repair_name "equal" = "c_equal" (* needed by SPASS? *)
blanchet@39454
   531
  | repair_name s =
blanchet@39454
   532
    if String.isPrefix "sQ" s andalso String.isSuffix "_eqProxy" s then
blanchet@39454
   533
      "c_equal" (* seen in Vampire proofs *)
blanchet@39454
   534
    else
blanchet@39454
   535
      s
blanchet@39454
   536
blanchet@39452
   537
fun isar_proof_from_tstplike_proof pool ctxt full_types tfrees isar_shrink_factor
blanchet@39452
   538
        tstplike_proof conjecture_shape axiom_names params frees =
blanchet@36402
   539
  let
blanchet@36486
   540
    val lines =
blanchet@39452
   541
      tstplike_proof
blanchet@39454
   542
      |> atp_proof_from_tstplike_string
blanchet@39454
   543
      |> nasty_atp_proof pool
blanchet@39454
   544
      |> map_term_names_in_atp_proof repair_name
blanchet@36967
   545
      |> decode_lines ctxt full_types tfrees
blanchet@38282
   546
      |> rpair [] |-> fold_rev (add_line conjecture_shape axiom_names)
blanchet@36486
   547
      |> rpair [] |-> fold_rev add_nontrivial_line
blanchet@37498
   548
      |> rpair (0, []) |-> fold_rev (add_desired_line isar_shrink_factor
blanchet@38282
   549
                                             conjecture_shape axiom_names frees)
blanchet@36486
   550
      |> snd
blanchet@36402
   551
  in
blanchet@36909
   552
    (if null params then [] else [Fix params]) @
blanchet@39370
   553
    map2 (step_for_line conjecture_shape axiom_names) (length lines downto 1)
blanchet@39370
   554
         lines
blanchet@36402
   555
  end
blanchet@36402
   556
blanchet@36402
   557
(* When redirecting proofs, we keep information about the labels seen so far in
blanchet@36402
   558
   the "backpatches" data structure. The first component indicates which facts
blanchet@36402
   559
   should be associated with forthcoming proof steps. The second component is a
blanchet@37322
   560
   pair ("assum_ls", "drop_ls"), where "assum_ls" are the labels that should
blanchet@37322
   561
   become assumptions and "drop_ls" are the labels that should be dropped in a
blanchet@37322
   562
   case split. *)
blanchet@36402
   563
type backpatches = (label * facts) list * (label list * label list)
blanchet@36402
   564
blanchet@36556
   565
fun used_labels_of_step (Have (_, _, _, by)) =
blanchet@36402
   566
    (case by of
blanchet@36564
   567
       ByMetis (ls, _) => ls
blanchet@36556
   568
     | CaseSplit (proofs, (ls, _)) =>
blanchet@36556
   569
       fold (union (op =) o used_labels_of) proofs ls)
blanchet@36556
   570
  | used_labels_of_step _ = []
blanchet@36556
   571
and used_labels_of proof = fold (union (op =) o used_labels_of_step) proof []
blanchet@36402
   572
blanchet@36402
   573
fun new_labels_of_step (Fix _) = []
blanchet@36486
   574
  | new_labels_of_step (Let _) = []
blanchet@36402
   575
  | new_labels_of_step (Assume (l, _)) = [l]
blanchet@36402
   576
  | new_labels_of_step (Have (_, l, _, _)) = [l]
blanchet@36402
   577
val new_labels_of = maps new_labels_of_step
blanchet@36402
   578
blanchet@36402
   579
val join_proofs =
blanchet@36402
   580
  let
blanchet@36402
   581
    fun aux _ [] = NONE
blanchet@36402
   582
      | aux proof_tail (proofs as (proof1 :: _)) =
blanchet@36402
   583
        if exists null proofs then
blanchet@36402
   584
          NONE
blanchet@36402
   585
        else if forall (curry (op =) (hd proof1) o hd) (tl proofs) then
blanchet@36402
   586
          aux (hd proof1 :: proof_tail) (map tl proofs)
blanchet@36402
   587
        else case hd proof1 of
blanchet@37498
   588
          Have ([], l, t, _) => (* FIXME: should we really ignore the "by"? *)
blanchet@36402
   589
          if forall (fn Have ([], l', t', _) :: _ => (l, t) = (l', t')
blanchet@36402
   590
                      | _ => false) (tl proofs) andalso
blanchet@36402
   591
             not (exists (member (op =) (maps new_labels_of proofs))
blanchet@36556
   592
                         (used_labels_of proof_tail)) then
blanchet@36402
   593
            SOME (l, t, map rev proofs, proof_tail)
blanchet@36402
   594
          else
blanchet@36402
   595
            NONE
blanchet@36402
   596
        | _ => NONE
blanchet@36402
   597
  in aux [] o map rev end
blanchet@36402
   598
blanchet@36402
   599
fun case_split_qualifiers proofs =
blanchet@36402
   600
  case length proofs of
blanchet@36402
   601
    0 => []
blanchet@36402
   602
  | 1 => [Then]
blanchet@36402
   603
  | _ => [Ultimately]
blanchet@36402
   604
blanchet@39372
   605
fun redirect_proof hyp_ts concl_t proof =
wenzelm@33310
   606
  let
blanchet@37324
   607
    (* The first pass outputs those steps that are independent of the negated
blanchet@37324
   608
       conjecture. The second pass flips the proof by contradiction to obtain a
blanchet@37324
   609
       direct proof, introducing case splits when an inference depends on
blanchet@37324
   610
       several facts that depend on the negated conjecture. *)
blanchet@39372
   611
     val concl_l = (conjecture_prefix, length hyp_ts)
blanchet@38040
   612
     fun first_pass ([], contra) = ([], contra)
blanchet@38040
   613
       | first_pass ((step as Fix _) :: proof, contra) =
blanchet@38040
   614
         first_pass (proof, contra) |>> cons step
blanchet@38040
   615
       | first_pass ((step as Let _) :: proof, contra) =
blanchet@38040
   616
         first_pass (proof, contra) |>> cons step
blanchet@39370
   617
       | first_pass ((step as Assume (l as (_, j), _)) :: proof, contra) =
blanchet@39372
   618
         if l = concl_l then first_pass (proof, contra ||> cons step)
blanchet@39372
   619
         else first_pass (proof, contra) |>> cons (Assume (l, nth hyp_ts j))
blanchet@38040
   620
       | first_pass (Have (qs, l, t, ByMetis (ls, ss)) :: proof, contra) =
blanchet@39372
   621
         let val step = Have (qs, l, t, ByMetis (ls, ss)) in
blanchet@38040
   622
           if exists (member (op =) (fst contra)) ls then
blanchet@38040
   623
             first_pass (proof, contra |>> cons l ||> cons step)
blanchet@38040
   624
           else
blanchet@38040
   625
             first_pass (proof, contra) |>> cons step
blanchet@38040
   626
         end
blanchet@38040
   627
       | first_pass _ = raise Fail "malformed proof"
blanchet@36402
   628
    val (proof_top, (contra_ls, contra_proof)) =
blanchet@39372
   629
      first_pass (proof, ([concl_l], []))
blanchet@36402
   630
    val backpatch_label = the_default ([], []) oo AList.lookup (op =) o fst
blanchet@36402
   631
    fun backpatch_labels patches ls =
blanchet@36402
   632
      fold merge_fact_sets (map (backpatch_label patches) ls) ([], [])
blanchet@36402
   633
    fun second_pass end_qs ([], assums, patches) =
blanchet@37324
   634
        ([Have (end_qs, no_label, concl_t,
blanchet@36564
   635
                ByMetis (backpatch_labels patches (map snd assums)))], patches)
blanchet@36402
   636
      | second_pass end_qs (Assume (l, t) :: proof, assums, patches) =
blanchet@36402
   637
        second_pass end_qs (proof, (t, l) :: assums, patches)
blanchet@36564
   638
      | second_pass end_qs (Have (qs, l, t, ByMetis (ls, ss)) :: proof, assums,
blanchet@36402
   639
                            patches) =
blanchet@39373
   640
        (if member (op =) (snd (snd patches)) l andalso
blanchet@39373
   641
            not (member (op =) (fst (snd patches)) l) andalso
blanchet@39373
   642
            not (AList.defined (op =) (fst patches) l) then
blanchet@39373
   643
           second_pass end_qs (proof, assums, patches ||> apsnd (append ls))
blanchet@39373
   644
         else case List.partition (member (op =) contra_ls) ls of
blanchet@39373
   645
           ([contra_l], co_ls) =>
blanchet@39373
   646
           if member (op =) qs Show then
blanchet@39373
   647
             second_pass end_qs (proof, assums,
blanchet@39373
   648
                                 patches |>> cons (contra_l, (co_ls, ss)))
blanchet@39373
   649
           else
blanchet@39373
   650
             second_pass end_qs
blanchet@39373
   651
                         (proof, assums,
blanchet@39373
   652
                          patches |>> cons (contra_l, (l :: co_ls, ss)))
blanchet@39373
   653
             |>> cons (if member (op =) (fst (snd patches)) l then
blanchet@39373
   654
                         Assume (l, negate_term t)
blanchet@39373
   655
                       else
blanchet@39373
   656
                         Have (qs, l, negate_term t,
blanchet@39373
   657
                               ByMetis (backpatch_label patches l)))
blanchet@39373
   658
         | (contra_ls as _ :: _, co_ls) =>
blanchet@39373
   659
           let
blanchet@39373
   660
             val proofs =
blanchet@39373
   661
               map_filter
blanchet@39373
   662
                   (fn l =>
blanchet@39373
   663
                       if l = concl_l then
blanchet@39373
   664
                         NONE
blanchet@39373
   665
                       else
blanchet@39373
   666
                         let
blanchet@39373
   667
                           val drop_ls = filter (curry (op <>) l) contra_ls
blanchet@39373
   668
                         in
blanchet@39373
   669
                           second_pass []
blanchet@39373
   670
                               (proof, assums,
blanchet@39373
   671
                                patches ||> apfst (insert (op =) l)
blanchet@39373
   672
                                        ||> apsnd (union (op =) drop_ls))
blanchet@39373
   673
                           |> fst |> SOME
blanchet@39373
   674
                         end) contra_ls
blanchet@39373
   675
             val (assumes, facts) =
blanchet@39373
   676
               if member (op =) (fst (snd patches)) l then
blanchet@39373
   677
                 ([Assume (l, negate_term t)], (l :: co_ls, ss))
blanchet@39373
   678
               else
blanchet@39373
   679
                 ([], (co_ls, ss))
blanchet@39373
   680
           in
blanchet@39373
   681
             (case join_proofs proofs of
blanchet@39373
   682
                SOME (l, t, proofs, proof_tail) =>
blanchet@39373
   683
                Have (case_split_qualifiers proofs @
blanchet@39373
   684
                      (if null proof_tail then end_qs else []), l, t,
blanchet@39373
   685
                      smart_case_split proofs facts) :: proof_tail
blanchet@39373
   686
              | NONE =>
blanchet@39373
   687
                [Have (case_split_qualifiers proofs @ end_qs, no_label,
blanchet@39373
   688
                       concl_t, smart_case_split proofs facts)],
blanchet@39373
   689
              patches)
blanchet@39373
   690
             |>> append assumes
blanchet@39373
   691
           end
blanchet@39373
   692
         | _ => raise Fail "malformed proof")
blanchet@36402
   693
       | second_pass _ _ = raise Fail "malformed proof"
blanchet@36486
   694
    val proof_bottom =
blanchet@36486
   695
      second_pass [Show] (contra_proof, [], ([], ([], []))) |> fst
blanchet@36402
   696
  in proof_top @ proof_bottom end
blanchet@36402
   697
blanchet@38490
   698
(* FIXME: Still needed? Probably not. *)
blanchet@36402
   699
val kill_duplicate_assumptions_in_proof =
blanchet@36402
   700
  let
blanchet@36402
   701
    fun relabel_facts subst =
blanchet@36402
   702
      apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
blanchet@36491
   703
    fun do_step (step as Assume (l, t)) (proof, subst, assums) =
blanchet@36402
   704
        (case AList.lookup (op aconv) assums t of
blanchet@36967
   705
           SOME l' => (proof, (l, l') :: subst, assums)
blanchet@36491
   706
         | NONE => (step :: proof, subst, (t, l) :: assums))
blanchet@36402
   707
      | do_step (Have (qs, l, t, by)) (proof, subst, assums) =
blanchet@36402
   708
        (Have (qs, l, t,
blanchet@36402
   709
               case by of
blanchet@36564
   710
                 ByMetis facts => ByMetis (relabel_facts subst facts)
blanchet@36402
   711
               | CaseSplit (proofs, facts) =>
blanchet@36402
   712
                 CaseSplit (map do_proof proofs, relabel_facts subst facts)) ::
blanchet@36402
   713
         proof, subst, assums)
blanchet@36491
   714
      | do_step step (proof, subst, assums) = (step :: proof, subst, assums)
blanchet@36402
   715
    and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
blanchet@36402
   716
  in do_proof end
blanchet@36402
   717
blanchet@36402
   718
val then_chain_proof =
blanchet@36402
   719
  let
blanchet@36402
   720
    fun aux _ [] = []
blanchet@36491
   721
      | aux _ ((step as Assume (l, _)) :: proof) = step :: aux l proof
blanchet@36402
   722
      | aux l' (Have (qs, l, t, by) :: proof) =
blanchet@36402
   723
        (case by of
blanchet@36564
   724
           ByMetis (ls, ss) =>
blanchet@36402
   725
           Have (if member (op =) ls l' then
blanchet@36402
   726
                   (Then :: qs, l, t,
blanchet@36564
   727
                    ByMetis (filter_out (curry (op =) l') ls, ss))
blanchet@36402
   728
                 else
blanchet@36564
   729
                   (qs, l, t, ByMetis (ls, ss)))
blanchet@36402
   730
         | CaseSplit (proofs, facts) =>
blanchet@36402
   731
           Have (qs, l, t, CaseSplit (map (aux no_label) proofs, facts))) ::
blanchet@36402
   732
        aux l proof
blanchet@36491
   733
      | aux _ (step :: proof) = step :: aux no_label proof
blanchet@36402
   734
  in aux no_label end
blanchet@36402
   735
blanchet@36402
   736
fun kill_useless_labels_in_proof proof =
blanchet@36402
   737
  let
blanchet@36556
   738
    val used_ls = used_labels_of proof
blanchet@36402
   739
    fun do_label l = if member (op =) used_ls l then l else no_label
blanchet@36556
   740
    fun do_step (Assume (l, t)) = Assume (do_label l, t)
blanchet@36556
   741
      | do_step (Have (qs, l, t, by)) =
blanchet@36402
   742
        Have (qs, do_label l, t,
blanchet@36402
   743
              case by of
blanchet@36402
   744
                CaseSplit (proofs, facts) =>
blanchet@36556
   745
                CaseSplit (map (map do_step) proofs, facts)
blanchet@36402
   746
              | _ => by)
blanchet@36556
   747
      | do_step step = step
blanchet@36556
   748
  in map do_step proof end
blanchet@36402
   749
blanchet@36402
   750
fun prefix_for_depth n = replicate_string (n + 1)
blanchet@36402
   751
blanchet@36402
   752
val relabel_proof =
blanchet@36402
   753
  let
blanchet@36402
   754
    fun aux _ _ _ [] = []
blanchet@36402
   755
      | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
blanchet@36402
   756
        if l = no_label then
blanchet@36402
   757
          Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   758
        else
blanchet@36402
   759
          let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
blanchet@36402
   760
            Assume (l', t) ::
blanchet@36402
   761
            aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
blanchet@36402
   762
          end
blanchet@36402
   763
      | aux subst depth (next_assum, next_fact) (Have (qs, l, t, by) :: proof) =
blanchet@36402
   764
        let
blanchet@36402
   765
          val (l', subst, next_fact) =
blanchet@36402
   766
            if l = no_label then
blanchet@36402
   767
              (l, subst, next_fact)
blanchet@36402
   768
            else
blanchet@36402
   769
              let
blanchet@36402
   770
                val l' = (prefix_for_depth depth fact_prefix, next_fact)
blanchet@36402
   771
              in (l', (l, l') :: subst, next_fact + 1) end
blanchet@36570
   772
          val relabel_facts =
blanchet@39370
   773
            apfst (maps (the_list o AList.lookup (op =) subst))
blanchet@36402
   774
          val by =
blanchet@36402
   775
            case by of
blanchet@36564
   776
              ByMetis facts => ByMetis (relabel_facts facts)
blanchet@36402
   777
            | CaseSplit (proofs, facts) =>
blanchet@36402
   778
              CaseSplit (map (aux subst (depth + 1) (1, 1)) proofs,
blanchet@36402
   779
                         relabel_facts facts)
blanchet@36402
   780
        in
blanchet@36402
   781
          Have (qs, l', t, by) ::
blanchet@36402
   782
          aux subst depth (next_assum, next_fact) proof
blanchet@36402
   783
        end
blanchet@36491
   784
      | aux subst depth nextp (step :: proof) =
blanchet@36491
   785
        step :: aux subst depth nextp proof
blanchet@36402
   786
  in aux [] 0 (1, 1) end
blanchet@36402
   787
wenzelm@39115
   788
fun string_for_proof ctxt0 full_types i n =
blanchet@36402
   789
  let
wenzelm@39134
   790
    val ctxt = ctxt0
wenzelm@39134
   791
      |> Config.put show_free_types false
wenzelm@39134
   792
      |> Config.put show_types true
blanchet@37319
   793
    fun fix_print_mode f x =
wenzelm@39134
   794
      Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
wenzelm@39134
   795
                               (print_mode_value ())) f x
blanchet@36402
   796
    fun do_indent ind = replicate_string (ind * indent_size) " "
blanchet@36478
   797
    fun do_free (s, T) =
blanchet@36478
   798
      maybe_quote s ^ " :: " ^
blanchet@36478
   799
      maybe_quote (fix_print_mode (Syntax.string_of_typ ctxt) T)
blanchet@36570
   800
    fun do_label l = if l = no_label then "" else string_for_label l ^ ": "
blanchet@36402
   801
    fun do_have qs =
blanchet@36402
   802
      (if member (op =) qs Moreover then "moreover " else "") ^
blanchet@36402
   803
      (if member (op =) qs Ultimately then "ultimately " else "") ^
blanchet@36402
   804
      (if member (op =) qs Then then
blanchet@36402
   805
         if member (op =) qs Show then "thus" else "hence"
blanchet@36402
   806
       else
blanchet@36402
   807
         if member (op =) qs Show then "show" else "have")
blanchet@36478
   808
    val do_term = maybe_quote o fix_print_mode (Syntax.string_of_term ctxt)
blanchet@36570
   809
    fun do_facts (ls, ss) =
blanchet@38698
   810
      metis_command full_types 1 1
blanchet@38698
   811
                    (ls |> sort_distinct (prod_ord string_ord int_ord),
blanchet@38698
   812
                     ss |> sort_distinct string_ord)
blanchet@36478
   813
    and do_step ind (Fix xs) =
blanchet@36478
   814
        do_indent ind ^ "fix " ^ space_implode " and " (map do_free xs) ^ "\n"
blanchet@36486
   815
      | do_step ind (Let (t1, t2)) =
blanchet@36486
   816
        do_indent ind ^ "let " ^ do_term t1 ^ " = " ^ do_term t2 ^ "\n"
blanchet@36402
   817
      | do_step ind (Assume (l, t)) =
blanchet@36402
   818
        do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
blanchet@36564
   819
      | do_step ind (Have (qs, l, t, ByMetis facts)) =
blanchet@36402
   820
        do_indent ind ^ do_have qs ^ " " ^
blanchet@36479
   821
        do_label l ^ do_term t ^ " " ^ do_facts facts ^ "\n"
blanchet@36402
   822
      | do_step ind (Have (qs, l, t, CaseSplit (proofs, facts))) =
blanchet@36402
   823
        space_implode (do_indent ind ^ "moreover\n")
blanchet@36402
   824
                      (map (do_block ind) proofs) ^
blanchet@36479
   825
        do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ " " ^
blanchet@36478
   826
        do_facts facts ^ "\n"
blanchet@36402
   827
    and do_steps prefix suffix ind steps =
blanchet@36402
   828
      let val s = implode (map (do_step ind) steps) in
blanchet@36402
   829
        replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
blanchet@36402
   830
        String.extract (s, ind * indent_size,
blanchet@36402
   831
                        SOME (size s - ind * indent_size - 1)) ^
blanchet@36402
   832
        suffix ^ "\n"
blanchet@36402
   833
      end
blanchet@36402
   834
    and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
blanchet@36564
   835
    (* One-step proofs are pointless; better use the Metis one-liner
blanchet@36564
   836
       directly. *)
blanchet@36564
   837
    and do_proof [Have (_, _, _, ByMetis _)] = ""
blanchet@36564
   838
      | do_proof proof =
blanchet@36480
   839
        (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
blanchet@39452
   840
        do_indent 0 ^ "proof -\n" ^ do_steps "" "" 1 proof ^ do_indent 0 ^
blanchet@39452
   841
        (if n <> 1 then "next" else "qed")
blanchet@36488
   842
  in do_proof end
blanchet@36402
   843
blanchet@37479
   844
fun isar_proof_text (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
blanchet@39452
   845
                    (other_params as (_, full_types, _, tstplike_proof,
blanchet@39452
   846
                                      axiom_names, goal, i)) =
blanchet@36402
   847
  let
blanchet@36909
   848
    val (params, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@36909
   849
    val frees = fold Term.add_frees (concl_t :: hyp_ts) []
blanchet@36967
   850
    val tfrees = fold Term.add_tfrees (concl_t :: hyp_ts) []
blanchet@36402
   851
    val n = Logic.count_prems (prop_of goal)
blanchet@37479
   852
    val (one_line_proof, lemma_names) = metis_proof_text other_params
blanchet@36283
   853
    fun isar_proof_for () =
blanchet@39452
   854
      case isar_proof_from_tstplike_proof pool ctxt full_types tfrees
blanchet@39452
   855
               isar_shrink_factor tstplike_proof conjecture_shape axiom_names
blanchet@39452
   856
               params frees
blanchet@39372
   857
           |> redirect_proof hyp_ts concl_t
blanchet@36402
   858
           |> kill_duplicate_assumptions_in_proof
blanchet@36402
   859
           |> then_chain_proof
blanchet@36402
   860
           |> kill_useless_labels_in_proof
blanchet@36402
   861
           |> relabel_proof
blanchet@37479
   862
           |> string_for_proof ctxt full_types i n of
blanchet@38599
   863
        "" => "\nNo structured proof available."
blanchet@38599
   864
      | proof => "\n\nStructured proof:\n" ^ Markup.markup Markup.sendback proof
blanchet@35868
   865
    val isar_proof =
blanchet@36402
   866
      if debug then
blanchet@36283
   867
        isar_proof_for ()
blanchet@36283
   868
      else
blanchet@36283
   869
        try isar_proof_for ()
blanchet@38599
   870
        |> the_default "\nWarning: The Isar proof construction failed."
blanchet@36283
   871
  in (one_line_proof ^ isar_proof, lemma_names) end
paulson@21978
   872
blanchet@36557
   873
fun proof_text isar_proof isar_params other_params =
blanchet@36557
   874
  (if isar_proof then isar_proof_text isar_params else metis_proof_text)
blanchet@36557
   875
      other_params
blanchet@36223
   876
immler@31038
   877
end;