src/HOL/Tools/Sledgehammer/sledgehammer_reconstruct.ML
author blanchet
Tue Sep 14 23:01:29 2010 +0200 (2010-09-14)
changeset 39373 fe95c860434c
parent 39372 2fd8a9a7080d
child 39374 4b35206e6360
permissions -rw-r--r--
finish support for E 1.2 proof reconstruction;
this involves picking up the axiom and conjecture names specified using a "file" annotation in the TSTP file, since we cannot rely anymore on formula numbers (E 1.2 adds a strange offset)
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@37578
    29
open Metis_Clauses
blanchet@36478
    30
open Sledgehammer_Util
blanchet@38988
    31
open Sledgehammer_Filter
blanchet@38282
    32
open Sledgehammer_Translate
paulson@21978
    33
blanchet@36281
    34
type minimize_command = string list -> string
blanchet@38818
    35
type metis_params =
blanchet@39327
    36
  string * bool * minimize_command * string * (string * locality) list vector
blanchet@39327
    37
  * thm * int
blanchet@38818
    38
type isar_params =
blanchet@38818
    39
  string Symtab.table * bool * int * Proof.context * int list list
blanchet@38818
    40
type text_result = string * (string * locality) list
blanchet@36281
    41
blanchet@38014
    42
(* Simple simplifications to ensure that sort annotations don't leave a trail of
blanchet@38014
    43
   spurious "True"s. *)
blanchet@38014
    44
fun s_not @{const False} = @{const True}
blanchet@38014
    45
  | s_not @{const True} = @{const False}
blanchet@38014
    46
  | s_not (@{const Not} $ t) = t
blanchet@38014
    47
  | s_not t = @{const Not} $ t
blanchet@38014
    48
fun s_conj (@{const True}, t2) = t2
blanchet@38014
    49
  | s_conj (t1, @{const True}) = t1
blanchet@38014
    50
  | s_conj p = HOLogic.mk_conj p
blanchet@38014
    51
fun s_disj (@{const False}, t2) = t2
blanchet@38014
    52
  | s_disj (t1, @{const False}) = t1
blanchet@38014
    53
  | s_disj p = HOLogic.mk_disj p
blanchet@38014
    54
fun s_imp (@{const True}, t2) = t2
blanchet@38014
    55
  | s_imp (t1, @{const False}) = s_not t1
blanchet@38014
    56
  | s_imp p = HOLogic.mk_imp p
blanchet@38014
    57
fun s_iff (@{const True}, t2) = t2
blanchet@38014
    58
  | s_iff (t1, @{const True}) = t1
blanchet@38014
    59
  | s_iff (t1, t2) = HOLogic.eq_const HOLogic.boolT $ t1 $ t2
blanchet@38014
    60
blanchet@38014
    61
fun mk_anot (AConn (ANot, [phi])) = phi
blanchet@38014
    62
  | mk_anot phi = AConn (ANot, [phi])
blanchet@37991
    63
fun mk_aconn c (phi1, phi2) = AConn (c, [phi1, phi2])
blanchet@37991
    64
blanchet@39372
    65
datatype raw_step_name = Str of string * string | Num of string
blanchet@39372
    66
blanchet@39373
    67
fun raw_step_num (Str (num, _)) = num
blanchet@39373
    68
  | raw_step_num (Num num) = num
blanchet@39373
    69
blanchet@39373
    70
fun same_raw_step s t = raw_step_num s = raw_step_num t
blanchet@39372
    71
blanchet@39372
    72
fun raw_step_name_ord p =
blanchet@39373
    73
  let val q = pairself raw_step_num p in
blanchet@39372
    74
    case pairself Int.fromString q of
blanchet@39372
    75
      (NONE, NONE) => string_ord q
blanchet@39372
    76
    | (NONE, SOME _) => LESS
blanchet@39372
    77
    | (SOME _, NONE) => GREATER
blanchet@39372
    78
    | (SOME i, SOME j) => int_ord (i, j)
blanchet@39372
    79
  end
blanchet@39368
    80
blanchet@38066
    81
fun index_in_shape x = find_index (exists (curry (op =) x))
blanchet@39373
    82
fun resolve_axiom axiom_names (Str (_, s)) =
blanchet@39373
    83
    (case strip_prefix_and_unascii axiom_prefix s of
blanchet@39373
    84
       SOME s' => (case find_first_in_list_vector axiom_names s' of
blanchet@39373
    85
                     SOME x => [(s', x)]
blanchet@39373
    86
                   | NONE => [])
blanchet@39368
    87
     | NONE => [])
blanchet@39368
    88
  | resolve_axiom axiom_names (Num num) =
blanchet@39370
    89
    case Int.fromString num of
blanchet@39370
    90
      SOME j =>
blanchet@39370
    91
      if j > 0 andalso j <= Vector.length axiom_names then
blanchet@39370
    92
        Vector.sub (axiom_names, j - 1)
blanchet@39370
    93
      else
blanchet@39370
    94
        []
blanchet@39370
    95
    | NONE => []
blanchet@39370
    96
val is_axiom = not o null oo resolve_axiom
blanchet@39370
    97
blanchet@39370
    98
fun resolve_conjecture conjecture_shape (Str (num, s)) =
blanchet@39370
    99
    let
blanchet@39373
   100
      val k = case try (unprefix conjecture_prefix) s of
blanchet@39373
   101
                SOME s => Int.fromString s |> the_default ~1
blanchet@39373
   102
              | NONE => case Int.fromString num of
blanchet@39373
   103
                          SOME j => index_in_shape j conjecture_shape
blanchet@39373
   104
                        | NONE => ~1
blanchet@39370
   105
    in if k >= 0 then [k] else [] end
blanchet@39370
   106
  | resolve_conjecture conjecture_shape (Num num) =
blanchet@39370
   107
    resolve_conjecture conjecture_shape (Str (num, "")) (* HACK *)
blanchet@39370
   108
val is_conjecture = not o null oo resolve_conjecture
blanchet@36291
   109
blanchet@37991
   110
fun negate_term (Const (@{const_name All}, T) $ Abs (s, T', t')) =
blanchet@37991
   111
    Const (@{const_name Ex}, T) $ Abs (s, T', negate_term t')
blanchet@37991
   112
  | negate_term (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
blanchet@37991
   113
    Const (@{const_name All}, T) $ Abs (s, T', negate_term t')
haftmann@38786
   114
  | negate_term (@{const HOL.implies} $ t1 $ t2) =
haftmann@38795
   115
    @{const HOL.conj} $ t1 $ negate_term t2
haftmann@38795
   116
  | negate_term (@{const HOL.conj} $ t1 $ t2) =
haftmann@38795
   117
    @{const HOL.disj} $ negate_term t1 $ negate_term t2
haftmann@38795
   118
  | negate_term (@{const HOL.disj} $ t1 $ t2) =
haftmann@38795
   119
    @{const HOL.conj} $ negate_term t1 $ negate_term t2
blanchet@37991
   120
  | negate_term (@{const Not} $ t) = t
blanchet@37991
   121
  | negate_term t = @{const Not} $ t
blanchet@37991
   122
blanchet@39368
   123
datatype ('a, 'b, 'c) raw_step =
blanchet@39372
   124
  Definition of raw_step_name * 'a * 'b |
blanchet@39372
   125
  Inference of raw_step_name * 'c * raw_step_name list
blanchet@36491
   126
blanchet@38035
   127
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
   128
paulson@21978
   129
(*Strings enclosed in single quotes, e.g. filenames*)
blanchet@39370
   130
val scan_general_id =
blanchet@39370
   131
  $$ "'" |-- Scan.repeat (~$$ "'") --| $$ "'" >> implode
blanchet@39370
   132
  || Scan.repeat ($$ "$") -- Scan.many1 Symbol.is_letdig
blanchet@39370
   133
     >> (fn (ss1, ss2) => implode ss1 ^ implode ss2)
blanchet@36548
   134
blanchet@36548
   135
fun repair_name _ "$true" = "c_True"
blanchet@36548
   136
  | repair_name _ "$false" = "c_False"
blanchet@38007
   137
  | repair_name _ "$$e" = "c_equal" (* seen in Vampire proofs *)
blanchet@38035
   138
  | repair_name _ "equal" = "c_equal" (* needed by SPASS? *)
blanchet@38035
   139
  | repair_name pool s =
blanchet@38035
   140
    case Symtab.lookup pool s of
blanchet@38035
   141
      SOME s' => s'
blanchet@38035
   142
    | NONE =>
blanchet@38035
   143
      if String.isPrefix "sQ" s andalso String.isSuffix "_eqProxy" s then
blanchet@38035
   144
        "c_equal" (* seen in Vampire proofs *)
blanchet@38035
   145
      else
blanchet@38035
   146
        s
blanchet@36392
   147
(* Generalized first-order terms, which include file names, numbers, etc. *)
blanchet@39372
   148
fun parse_annotation strict x =
blanchet@39372
   149
  ((scan_general_id ::: Scan.repeat ($$ " " |-- scan_general_id)
blanchet@39372
   150
      >> (strict ? filter (is_some o Int.fromString)))
blanchet@39373
   151
   -- Scan.optional (parse_annotation strict) [] >> op @
blanchet@39372
   152
   || $$ "(" |-- parse_annotations strict --| $$ ")"
blanchet@39372
   153
   || $$ "[" |-- parse_annotations strict --| $$ "]") x
blanchet@39372
   154
and parse_annotations strict x =
blanchet@39372
   155
  (Scan.optional (parse_annotation strict
blanchet@39372
   156
                  ::: Scan.repeat ($$ "," |-- parse_annotation strict)) []
blanchet@39373
   157
   >> flat) x
blanchet@38035
   158
blanchet@38035
   159
(* Vampire proof lines sometimes contain needless information such as "(0:3)",
blanchet@38035
   160
   which can be hard to disambiguate from function application in an LL(1)
blanchet@38035
   161
   parser. As a workaround, we extend the TPTP term syntax with such detritus
blanchet@38035
   162
   and ignore it. *)
blanchet@38066
   163
fun parse_vampire_detritus x =
blanchet@39370
   164
  (scan_general_id |-- $$ ":" --| scan_general_id >> K []) x
blanchet@38035
   165
blanchet@36393
   166
fun parse_term pool x =
blanchet@39370
   167
  ((scan_general_id >> repair_name pool)
blanchet@38035
   168
    -- Scan.optional ($$ "(" |-- (parse_vampire_detritus || parse_terms pool)
blanchet@38035
   169
                      --| $$ ")") []
blanchet@38035
   170
    --| Scan.optional ($$ "(" |-- parse_vampire_detritus --| $$ ")") []
blanchet@38035
   171
   >> ATerm) x
blanchet@36393
   172
and parse_terms pool x =
blanchet@36393
   173
  (parse_term pool ::: Scan.repeat ($$ "," |-- parse_term pool)) x
paulson@21978
   174
blanchet@38034
   175
fun parse_atom pool =
blanchet@36393
   176
  parse_term pool -- Scan.option (Scan.option ($$ "!") --| $$ "="
blanchet@36393
   177
                                  -- parse_term pool)
blanchet@38035
   178
  >> (fn (u1, NONE) => AAtom u1
blanchet@38034
   179
       | (u1, SOME (NONE, u2)) => AAtom (ATerm ("c_equal", [u1, u2]))
blanchet@37991
   180
       | (u1, SOME (SOME _, u2)) =>
blanchet@38034
   181
         mk_anot (AAtom (ATerm ("c_equal", [u1, u2]))))
blanchet@37991
   182
blanchet@37991
   183
fun fo_term_head (ATerm (s, _)) = s
blanchet@36291
   184
blanchet@37991
   185
(* TPTP formulas are fully parenthesized, so we don't need to worry about
blanchet@37991
   186
   operator precedence. *)
blanchet@37991
   187
fun parse_formula pool x =
blanchet@37991
   188
  (($$ "(" |-- parse_formula pool --| $$ ")"
blanchet@37991
   189
    || ($$ "!" >> K AForall || $$ "?" >> K AExists)
blanchet@37991
   190
       --| $$ "[" -- parse_terms pool --| $$ "]" --| $$ ":"
blanchet@37991
   191
       -- parse_formula pool
blanchet@37991
   192
       >> (fn ((q, ts), phi) => AQuant (q, map fo_term_head ts, phi))
blanchet@37991
   193
    || $$ "~" |-- parse_formula pool >> mk_anot
blanchet@38034
   194
    || parse_atom pool)
blanchet@37991
   195
   -- Scan.option ((Scan.this_string "=>" >> K AImplies
blanchet@37991
   196
                    || Scan.this_string "<=>" >> K AIff
blanchet@37991
   197
                    || Scan.this_string "<~>" >> K ANotIff
blanchet@37991
   198
                    || Scan.this_string "<=" >> K AIf
blanchet@37991
   199
                    || $$ "|" >> K AOr || $$ "&" >> K AAnd)
blanchet@37991
   200
                   -- parse_formula pool)
blanchet@37991
   201
   >> (fn (phi1, NONE) => phi1
blanchet@37991
   202
        | (phi1, SOME (c, phi2)) => mk_aconn c (phi1, phi2))) x
blanchet@37991
   203
blanchet@38035
   204
val parse_tstp_extra_arguments =
blanchet@39372
   205
  Scan.optional ($$ "," |-- parse_annotation false
blanchet@39372
   206
                 --| Scan.option ($$ "," |-- parse_annotations false)) []
blanchet@36486
   207
blanchet@38035
   208
(* Syntax: (fof|cnf)\(<num>, <formula_role>, <formula> <extra_arguments>\).
blanchet@36486
   209
   The <num> could be an identifier, but we assume integers. *)
blanchet@37991
   210
 fun parse_tstp_line pool =
blanchet@37991
   211
   ((Scan.this_string "fof" || Scan.this_string "cnf") -- $$ "(")
blanchet@39370
   212
     |-- scan_general_id --| $$ "," -- Symbol.scan_id --| $$ ","
blanchet@38035
   213
     -- parse_formula pool -- parse_tstp_extra_arguments --| $$ ")" --| $$ "."
blanchet@37991
   214
    >> (fn (((num, role), phi), deps) =>
blanchet@39373
   215
           let
blanchet@39373
   216
             val (name, deps) =
blanchet@39373
   217
               case deps of
blanchet@39373
   218
                 ["file", _, s] => (Str (num, s), [])
blanchet@39373
   219
               | _ => (Num num, deps)
blanchet@39373
   220
           in
blanchet@39373
   221
             case role of
blanchet@39373
   222
               "definition" =>
blanchet@39373
   223
               (case phi of
blanchet@39373
   224
                  AConn (AIff, [phi1 as AAtom _, phi2]) =>
blanchet@39373
   225
                  Definition (name, phi1, phi2)
blanchet@39373
   226
                | AAtom (ATerm ("c_equal", _)) =>
blanchet@39373
   227
                  (* Vampire's equality proxy axiom *)
blanchet@39373
   228
                  Inference (name, phi, map Num deps)
blanchet@39373
   229
                | _ => raise Fail "malformed definition")
blanchet@39373
   230
             | _ => Inference (name, phi, map Num deps)
blanchet@39373
   231
           end)
blanchet@36291
   232
blanchet@38035
   233
(**** PARSING OF VAMPIRE OUTPUT ****)
blanchet@38035
   234
blanchet@38035
   235
(* Syntax: <num>. <formula> <annotation> *)
blanchet@38035
   236
fun parse_vampire_line pool =
blanchet@39372
   237
  scan_general_id --| $$ "." -- parse_formula pool -- parse_annotation true
blanchet@39368
   238
  >> (fn ((num, phi), deps) => Inference (Num num, phi, map Num deps))
blanchet@38035
   239
blanchet@36291
   240
(**** PARSING OF SPASS OUTPUT ****)
blanchet@36291
   241
blanchet@36392
   242
(* SPASS returns clause references of the form "x.y". We ignore "y", whose role
blanchet@36392
   243
   is not clear anyway. *)
blanchet@39370
   244
val parse_dot_name = scan_general_id --| $$ "." --| scan_general_id
paulson@21978
   245
blanchet@36392
   246
val parse_spass_annotations =
blanchet@36392
   247
  Scan.optional ($$ ":" |-- Scan.repeat (parse_dot_name
blanchet@36392
   248
                                         --| Scan.option ($$ ","))) []
blanchet@36291
   249
blanchet@36574
   250
(* It is not clear why some literals are followed by sequences of stars and/or
blanchet@36574
   251
   pluses. We ignore them. *)
blanchet@38034
   252
fun parse_decorated_atom pool =
blanchet@38034
   253
  parse_atom pool --| Scan.repeat ($$ "*" || $$ "+" || $$ " ")
blanchet@36291
   254
blanchet@38034
   255
fun mk_horn ([], []) = AAtom (ATerm ("c_False", []))
blanchet@37991
   256
  | mk_horn ([], pos_lits) = foldr1 (mk_aconn AOr) pos_lits
blanchet@37991
   257
  | mk_horn (neg_lits, []) = mk_anot (foldr1 (mk_aconn AAnd) neg_lits)
blanchet@37991
   258
  | mk_horn (neg_lits, pos_lits) =
blanchet@37991
   259
    mk_aconn AImplies (foldr1 (mk_aconn AAnd) neg_lits,
blanchet@37991
   260
                       foldr1 (mk_aconn AOr) pos_lits)
blanchet@37991
   261
blanchet@36393
   262
fun parse_horn_clause pool =
blanchet@38034
   263
  Scan.repeat (parse_decorated_atom pool) --| $$ "|" --| $$ "|"
blanchet@38034
   264
    -- Scan.repeat (parse_decorated_atom pool) --| $$ "-" --| $$ ">"
blanchet@38034
   265
    -- Scan.repeat (parse_decorated_atom pool)
blanchet@37991
   266
  >> (mk_horn o apfst (op @))
paulson@21978
   267
blanchet@36558
   268
(* Syntax: <num>[0:<inference><annotations>]
blanchet@38034
   269
   <atoms> || <atoms> -> <atoms>. *)
blanchet@36402
   270
fun parse_spass_line pool =
blanchet@39370
   271
  scan_general_id --| $$ "[" --| $$ "0" --| $$ ":" --| Symbol.scan_id
blanchet@38035
   272
    -- parse_spass_annotations --| $$ "]" -- parse_horn_clause pool --| $$ "."
blanchet@39368
   273
  >> (fn ((num, deps), u) => Inference (Num num, u, map Num deps))
blanchet@36291
   274
blanchet@38035
   275
fun parse_line pool =
blanchet@38035
   276
  parse_tstp_line pool || parse_vampire_line pool || parse_spass_line pool
blanchet@36548
   277
fun parse_lines pool = Scan.repeat1 (parse_line pool)
blanchet@36548
   278
fun parse_proof pool =
blanchet@36548
   279
  fst o Scan.finite Symbol.stopper
blanchet@36548
   280
            (Scan.error (!! (fn _ => raise Fail "unrecognized ATP output")
blanchet@36548
   281
                            (parse_lines pool)))
blanchet@38738
   282
  o explode o strip_spaces_except_between_ident_chars
paulson@21978
   283
blanchet@39373
   284
fun clean_up_dependencies _ [] = []
blanchet@39373
   285
  | clean_up_dependencies seen ((step as Definition (name, _, _)) :: steps) =
blanchet@39373
   286
    step :: clean_up_dependencies (name :: seen) steps
blanchet@39373
   287
  | clean_up_dependencies seen (Inference (name, u, deps) :: steps) =
blanchet@39373
   288
    Inference (name, u,
blanchet@39373
   289
             map_filter (fn dep => find_first (same_raw_step dep) seen) deps) ::
blanchet@39373
   290
    clean_up_dependencies (name :: seen) steps
blanchet@39373
   291
paulson@21978
   292
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   293
blanchet@37991
   294
exception FO_TERM of string fo_term list
blanchet@37994
   295
exception FORMULA of (string, string fo_term) formula list
blanchet@37991
   296
exception SAME of unit
paulson@21978
   297
blanchet@36909
   298
(* Type variables are given the basic sort "HOL.type". Some will later be
blanchet@37991
   299
   constrained by information from type literals, or by type inference. *)
blanchet@37991
   300
fun type_from_fo_term tfrees (u as ATerm (a, us)) =
blanchet@37991
   301
  let val Ts = map (type_from_fo_term tfrees) us in
blanchet@38748
   302
    case strip_prefix_and_unascii type_const_prefix a of
blanchet@37991
   303
      SOME b => Type (invert_const b, Ts)
blanchet@37991
   304
    | NONE =>
blanchet@37991
   305
      if not (null us) then
blanchet@37991
   306
        raise FO_TERM [u]  (* only "tconst"s have type arguments *)
blanchet@38748
   307
      else case strip_prefix_and_unascii tfree_prefix a of
blanchet@37991
   308
        SOME b =>
blanchet@37991
   309
        let val s = "'" ^ b in
blanchet@37991
   310
          TFree (s, AList.lookup (op =) tfrees s |> the_default HOLogic.typeS)
blanchet@37991
   311
        end
blanchet@36486
   312
      | NONE =>
blanchet@38748
   313
        case strip_prefix_and_unascii tvar_prefix a of
blanchet@37991
   314
          SOME b => TVar (("'" ^ b, 0), HOLogic.typeS)
blanchet@36486
   315
        | NONE =>
blanchet@37991
   316
          (* Variable from the ATP, say "X1" *)
blanchet@37991
   317
          Type_Infer.param 0 (a, HOLogic.typeS)
blanchet@37991
   318
  end
paulson@21978
   319
blanchet@38014
   320
(* Type class literal applied to a type. Returns triple of polarity, class,
blanchet@38014
   321
   type. *)
blanchet@38014
   322
fun type_constraint_from_term pos tfrees (u as ATerm (a, us)) =
blanchet@38748
   323
  case (strip_prefix_and_unascii class_prefix a,
blanchet@38014
   324
        map (type_from_fo_term tfrees) us) of
blanchet@38014
   325
    (SOME b, [T]) => (pos, b, T)
blanchet@38014
   326
  | _ => raise FO_TERM [u]
blanchet@38014
   327
blanchet@38085
   328
(** Accumulate type constraints in a formula: negative type literals **)
blanchet@38014
   329
fun add_var (key, z)  = Vartab.map_default (key, []) (cons z)
blanchet@38014
   330
fun add_type_constraint (false, cl, TFree (a ,_)) = add_var ((a, ~1), cl)
blanchet@38014
   331
  | add_type_constraint (false, cl, TVar (ix, _)) = add_var (ix, cl)
blanchet@38014
   332
  | add_type_constraint _ = I
blanchet@38014
   333
blanchet@38490
   334
fun repair_atp_variable_name f s =
blanchet@36486
   335
  let
blanchet@36486
   336
    fun subscript_name s n = s ^ nat_subscript n
blanchet@38488
   337
    val s = String.map f s
blanchet@36486
   338
  in
blanchet@36486
   339
    case space_explode "_" s of
blanchet@36486
   340
      [_] => (case take_suffix Char.isDigit (String.explode s) of
blanchet@36486
   341
                (cs1 as _ :: _, cs2 as _ :: _) =>
blanchet@36486
   342
                subscript_name (String.implode cs1)
blanchet@36486
   343
                               (the (Int.fromString (String.implode cs2)))
blanchet@36486
   344
              | (_, _) => s)
blanchet@36486
   345
    | [s1, s2] => (case Int.fromString s2 of
blanchet@36486
   346
                     SOME n => subscript_name s1 n
blanchet@36486
   347
                   | NONE => s)
blanchet@36486
   348
    | _ => s
blanchet@36486
   349
  end
blanchet@36486
   350
blanchet@36909
   351
(* First-order translation. No types are known for variables. "HOLogic.typeT"
blanchet@38014
   352
   should allow them to be inferred. *)
blanchet@38014
   353
fun raw_term_from_pred thy full_types tfrees =
blanchet@36909
   354
  let
blanchet@37643
   355
    fun aux opt_T extra_us u =
blanchet@36909
   356
      case u of
blanchet@37991
   357
        ATerm ("hBOOL", [u1]) => aux (SOME @{typ bool}) [] u1
blanchet@37991
   358
      | ATerm ("hAPP", [u1, u2]) => aux opt_T (u2 :: extra_us) u1
blanchet@37991
   359
      | ATerm (a, us) =>
blanchet@36909
   360
        if a = type_wrapper_name then
blanchet@36909
   361
          case us of
blanchet@37643
   362
            [typ_u, term_u] =>
blanchet@37991
   363
            aux (SOME (type_from_fo_term tfrees typ_u)) extra_us term_u
blanchet@37991
   364
          | _ => raise FO_TERM us
blanchet@38748
   365
        else case strip_prefix_and_unascii const_prefix a of
blanchet@36909
   366
          SOME "equal" =>
blanchet@39106
   367
          let val ts = map (aux NONE []) us in
blanchet@39106
   368
            if length ts = 2 andalso hd ts aconv List.last ts then
blanchet@39106
   369
              (* Vampire is keen on producing these. *)
blanchet@39106
   370
              @{const True}
blanchet@39106
   371
            else
blanchet@39106
   372
              list_comb (Const (@{const_name HOL.eq}, HOLogic.typeT), ts)
blanchet@39106
   373
          end
blanchet@36909
   374
        | SOME b =>
blanchet@36909
   375
          let
blanchet@36909
   376
            val c = invert_const b
blanchet@36909
   377
            val num_type_args = num_type_args thy c
blanchet@37643
   378
            val (type_us, term_us) =
blanchet@37643
   379
              chop (if full_types then 0 else num_type_args) us
blanchet@37643
   380
            (* Extra args from "hAPP" come after any arguments given directly to
blanchet@37643
   381
               the constant. *)
blanchet@37643
   382
            val term_ts = map (aux NONE []) term_us
blanchet@37643
   383
            val extra_ts = map (aux NONE []) extra_us
blanchet@36909
   384
            val t =
blanchet@36909
   385
              Const (c, if full_types then
blanchet@36909
   386
                          case opt_T of
blanchet@37643
   387
                            SOME T => map fastype_of term_ts ---> T
blanchet@36909
   388
                          | NONE =>
blanchet@36909
   389
                            if num_type_args = 0 then
blanchet@36909
   390
                              Sign.const_instance thy (c, [])
blanchet@36909
   391
                            else
blanchet@36909
   392
                              raise Fail ("no type information for " ^ quote c)
blanchet@36909
   393
                        else
blanchet@37998
   394
                          Sign.const_instance thy (c,
blanchet@37998
   395
                              map (type_from_fo_term tfrees) type_us))
blanchet@37643
   396
          in list_comb (t, term_ts @ extra_ts) end
blanchet@36909
   397
        | NONE => (* a free or schematic variable *)
blanchet@36909
   398
          let
blanchet@37643
   399
            val ts = map (aux NONE []) (us @ extra_us)
blanchet@36909
   400
            val T = map fastype_of ts ---> HOLogic.typeT
blanchet@36909
   401
            val t =
blanchet@38748
   402
              case strip_prefix_and_unascii fixed_var_prefix a of
blanchet@36909
   403
                SOME b => Free (b, T)
blanchet@36909
   404
              | NONE =>
blanchet@38748
   405
                case strip_prefix_and_unascii schematic_var_prefix a of
blanchet@36967
   406
                  SOME b => Var ((b, 0), T)
blanchet@36909
   407
                | NONE =>
blanchet@38017
   408
                  if is_tptp_variable a then
blanchet@38490
   409
                    Var ((repair_atp_variable_name Char.toLower a, 0), T)
blanchet@38017
   410
                  else
blanchet@38488
   411
                    (* Skolem constants? *)
blanchet@38490
   412
                    Var ((repair_atp_variable_name Char.toUpper a, 0), T)
blanchet@36909
   413
          in list_comb (t, ts) end
blanchet@38014
   414
  in aux (SOME HOLogic.boolT) [] end
paulson@21978
   415
blanchet@38014
   416
fun term_from_pred thy full_types tfrees pos (u as ATerm (s, _)) =
blanchet@38014
   417
  if String.isPrefix class_prefix s then
blanchet@38014
   418
    add_type_constraint (type_constraint_from_term pos tfrees u)
blanchet@38014
   419
    #> pair @{const True}
blanchet@38014
   420
  else
blanchet@38014
   421
    pair (raw_term_from_pred thy full_types tfrees u)
blanchet@36402
   422
blanchet@36555
   423
val combinator_table =
blanchet@36555
   424
  [(@{const_name COMBI}, @{thm COMBI_def_raw}),
blanchet@36555
   425
   (@{const_name COMBK}, @{thm COMBK_def_raw}),
blanchet@36555
   426
   (@{const_name COMBB}, @{thm COMBB_def_raw}),
blanchet@36555
   427
   (@{const_name COMBC}, @{thm COMBC_def_raw}),
blanchet@36555
   428
   (@{const_name COMBS}, @{thm COMBS_def_raw})]
blanchet@36555
   429
blanchet@36555
   430
fun uncombine_term (t1 $ t2) = betapply (pairself uncombine_term (t1, t2))
blanchet@36555
   431
  | uncombine_term (Abs (s, T, t')) = Abs (s, T, uncombine_term t')
blanchet@36555
   432
  | uncombine_term (t as Const (x as (s, _))) =
blanchet@36555
   433
    (case AList.lookup (op =) combinator_table s of
blanchet@36555
   434
       SOME thm => thm |> prop_of |> specialize_type @{theory} x |> Logic.dest_equals |> snd
blanchet@36555
   435
     | NONE => t)
blanchet@36555
   436
  | uncombine_term t = t
blanchet@36555
   437
blanchet@37991
   438
(* Update schematic type variables with detected sort constraints. It's not
blanchet@37991
   439
   totally clear when this code is necessary. *)
blanchet@38014
   440
fun repair_tvar_sorts (t, tvar_tab) =
blanchet@36909
   441
  let
blanchet@37991
   442
    fun do_type (Type (a, Ts)) = Type (a, map do_type Ts)
blanchet@37991
   443
      | do_type (TVar (xi, s)) =
blanchet@37991
   444
        TVar (xi, the_default s (Vartab.lookup tvar_tab xi))
blanchet@37991
   445
      | do_type (TFree z) = TFree z
blanchet@37991
   446
    fun do_term (Const (a, T)) = Const (a, do_type T)
blanchet@37991
   447
      | do_term (Free (a, T)) = Free (a, do_type T)
blanchet@37991
   448
      | do_term (Var (xi, T)) = Var (xi, do_type T)
blanchet@37991
   449
      | do_term (t as Bound _) = t
blanchet@37991
   450
      | do_term (Abs (a, T, t)) = Abs (a, do_type T, do_term t)
blanchet@37991
   451
      | do_term (t1 $ t2) = do_term t1 $ do_term t2
blanchet@37991
   452
  in t |> not (Vartab.is_empty tvar_tab) ? do_term end
blanchet@37991
   453
blanchet@39370
   454
(* ### TODO: looks broken; see forall_of below *)
blanchet@37991
   455
fun quantify_over_free quant_s free_s body_t =
blanchet@37991
   456
  case Term.add_frees body_t [] |> filter (curry (op =) free_s o fst) of
blanchet@37991
   457
    [] => body_t
blanchet@37991
   458
  | frees as (_, free_T) :: _ =>
blanchet@37991
   459
    Abs (free_s, free_T, fold (curry abstract_over) (map Free frees) body_t)
blanchet@37991
   460
blanchet@38085
   461
(* Interpret an ATP formula as a HOL term, extracting sort constraints as they
blanchet@38085
   462
   appear in the formula. *)
blanchet@38014
   463
fun prop_from_formula thy full_types tfrees phi =
blanchet@38014
   464
  let
blanchet@38014
   465
    fun do_formula pos phi =
blanchet@37991
   466
      case phi of
blanchet@38014
   467
        AQuant (_, [], phi) => do_formula pos phi
blanchet@37991
   468
      | AQuant (q, x :: xs, phi') =>
blanchet@38014
   469
        do_formula pos (AQuant (q, xs, phi'))
blanchet@38014
   470
        #>> quantify_over_free (case q of
blanchet@38014
   471
                                  AForall => @{const_name All}
blanchet@38490
   472
                                | AExists => @{const_name Ex})
blanchet@38490
   473
                               (repair_atp_variable_name Char.toLower x)
blanchet@38014
   474
      | AConn (ANot, [phi']) => do_formula (not pos) phi' #>> s_not
blanchet@37991
   475
      | AConn (c, [phi1, phi2]) =>
blanchet@38014
   476
        do_formula (pos |> c = AImplies ? not) phi1
blanchet@38014
   477
        ##>> do_formula pos phi2
blanchet@38014
   478
        #>> (case c of
blanchet@38014
   479
               AAnd => s_conj
blanchet@38014
   480
             | AOr => s_disj
blanchet@38014
   481
             | AImplies => s_imp
blanchet@38038
   482
             | AIf => s_imp o swap
blanchet@38038
   483
             | AIff => s_iff
blanchet@38038
   484
             | ANotIff => s_not o s_iff)
blanchet@38034
   485
      | AAtom tm => term_from_pred thy full_types tfrees pos tm
blanchet@37991
   486
      | _ => raise FORMULA [phi]
blanchet@38014
   487
  in repair_tvar_sorts (do_formula true phi Vartab.empty) end
blanchet@37991
   488
blanchet@36556
   489
fun check_formula ctxt =
wenzelm@39288
   490
  Type.constraint HOLogic.boolT
blanchet@36486
   491
  #> Syntax.check_term (ProofContext.set_mode ProofContext.mode_schematic ctxt)
paulson@21978
   492
paulson@21978
   493
paulson@21978
   494
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   495
blanchet@36486
   496
fun unvarify_term (Var ((s, 0), T)) = Free (s, T)
blanchet@36486
   497
  | unvarify_term t = raise TERM ("unvarify_term: non-Var", [t])
paulson@21978
   498
blanchet@39368
   499
fun decode_line full_types tfrees (Definition (name, phi1, phi2)) ctxt =
blanchet@36486
   500
    let
blanchet@37991
   501
      val thy = ProofContext.theory_of ctxt
blanchet@37991
   502
      val t1 = prop_from_formula thy full_types tfrees phi1
blanchet@36551
   503
      val vars = snd (strip_comb t1)
blanchet@36486
   504
      val frees = map unvarify_term vars
blanchet@36486
   505
      val unvarify_args = subst_atomic (vars ~~ frees)
blanchet@37991
   506
      val t2 = prop_from_formula thy full_types tfrees phi2
blanchet@36551
   507
      val (t1, t2) =
blanchet@36551
   508
        HOLogic.eq_const HOLogic.typeT $ t1 $ t2
blanchet@36556
   509
        |> unvarify_args |> uncombine_term |> check_formula ctxt
blanchet@36555
   510
        |> HOLogic.dest_eq
blanchet@36486
   511
    in
blanchet@39368
   512
      (Definition (name, t1, t2),
blanchet@36551
   513
       fold Variable.declare_term (maps OldTerm.term_frees [t1, t2]) ctxt)
blanchet@36486
   514
    end
blanchet@39368
   515
  | decode_line full_types tfrees (Inference (name, u, deps)) ctxt =
blanchet@36551
   516
    let
blanchet@37991
   517
      val thy = ProofContext.theory_of ctxt
blanchet@37991
   518
      val t = u |> prop_from_formula thy full_types tfrees
blanchet@37998
   519
                |> uncombine_term |> check_formula ctxt
blanchet@36551
   520
    in
blanchet@39368
   521
      (Inference (name, t, deps),
blanchet@36551
   522
       fold Variable.declare_term (OldTerm.term_frees t) ctxt)
blanchet@36486
   523
    end
blanchet@36967
   524
fun decode_lines ctxt full_types tfrees lines =
blanchet@36967
   525
  fst (fold_map (decode_line full_types tfrees) lines ctxt)
paulson@21978
   526
blanchet@38035
   527
fun is_same_inference _ (Definition _) = false
blanchet@38035
   528
  | is_same_inference t (Inference (_, t', _)) = t aconv t'
blanchet@36486
   529
blanchet@36486
   530
(* No "real" literals means only type information (tfree_tcs, clsrel, or
blanchet@36486
   531
   clsarity). *)
blanchet@36486
   532
val is_only_type_information = curry (op aconv) HOLogic.true_const
blanchet@36486
   533
blanchet@39373
   534
fun replace_one_dependency (old, new) dep =
blanchet@39373
   535
  if raw_step_num dep = raw_step_num old then new else [dep]
blanchet@39373
   536
fun replace_dependencies_in_line _ (line as Definition _) = line
blanchet@39373
   537
  | replace_dependencies_in_line p (Inference (name, t, deps)) =
blanchet@39373
   538
    Inference (name, t, fold (union (op =) o replace_one_dependency p) deps [])
paulson@21978
   539
blanchet@38085
   540
(* Discard axioms; consolidate adjacent lines that prove the same formula, since
blanchet@38085
   541
   they differ only in type information.*)
blanchet@36551
   542
fun add_line _ _ (line as Definition _) lines = line :: lines
blanchet@39368
   543
  | add_line conjecture_shape axiom_names (Inference (name, t, [])) lines =
blanchet@38085
   544
    (* No dependencies: axiom, conjecture, or (for Vampire) internal axioms or
blanchet@38085
   545
       definitions. *)
blanchet@39370
   546
    if is_axiom axiom_names name then
blanchet@36486
   547
      (* Axioms are not proof lines. *)
blanchet@36486
   548
      if is_only_type_information t then
blanchet@39373
   549
        map (replace_dependencies_in_line (name, [])) lines
blanchet@36486
   550
      (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   551
      else case take_prefix (not o is_same_inference t) lines of
blanchet@39373
   552
        (_, []) => lines (* no repetition of proof line *)
blanchet@39368
   553
      | (pre, Inference (name', _, _) :: post) =>
blanchet@39373
   554
        pre @ map (replace_dependencies_in_line (name', [name])) post
blanchet@39370
   555
    else if is_conjecture conjecture_shape name then
blanchet@39368
   556
      Inference (name, negate_term t, []) :: lines
blanchet@36551
   557
    else
blanchet@39373
   558
      map (replace_dependencies_in_line (name, [])) lines
blanchet@39368
   559
  | add_line _ _ (Inference (name, t, deps)) lines =
blanchet@36486
   560
    (* Type information will be deleted later; skip repetition test. *)
blanchet@36486
   561
    if is_only_type_information t then
blanchet@39368
   562
      Inference (name, t, deps) :: lines
blanchet@36486
   563
    (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   564
    else case take_prefix (not o is_same_inference t) lines of
blanchet@36486
   565
      (* FIXME: Doesn't this code risk conflating proofs involving different
blanchet@38035
   566
         types? *)
blanchet@39368
   567
       (_, []) => Inference (name, t, deps) :: lines
blanchet@39368
   568
     | (pre, Inference (name', t', _) :: post) =>
blanchet@39368
   569
       Inference (name, t', deps) ::
blanchet@39373
   570
       pre @ map (replace_dependencies_in_line (name', [name])) post
paulson@22044
   571
blanchet@36486
   572
(* Recursively delete empty lines (type information) from the proof. *)
blanchet@39368
   573
fun add_nontrivial_line (Inference (name, t, [])) lines =
blanchet@39373
   574
    if is_only_type_information t then delete_dependency name lines
blanchet@39368
   575
    else Inference (name, t, []) :: lines
blanchet@36486
   576
  | add_nontrivial_line line lines = line :: lines
blanchet@39373
   577
and delete_dependency name lines =
blanchet@39373
   578
  fold_rev add_nontrivial_line
blanchet@39373
   579
           (map (replace_dependencies_in_line (name, [])) lines) []
blanchet@36486
   580
blanchet@37323
   581
(* ATPs sometimes reuse free variable names in the strangest ways. Removing
blanchet@37323
   582
   offending lines often does the trick. *)
blanchet@36560
   583
fun is_bad_free frees (Free x) = not (member (op =) frees x)
blanchet@36560
   584
  | is_bad_free _ _ = false
paulson@22470
   585
blanchet@39368
   586
fun add_desired_line _ _ _ _ (line as Definition (name, _, _)) (j, lines) =
blanchet@39373
   587
    (j, line :: map (replace_dependencies_in_line (name, [])) lines)
blanchet@38282
   588
  | add_desired_line isar_shrink_factor conjecture_shape axiom_names frees
blanchet@39368
   589
                     (Inference (name, t, deps)) (j, lines) =
blanchet@36402
   590
    (j + 1,
blanchet@39370
   591
     if is_axiom axiom_names name orelse
blanchet@39370
   592
        is_conjecture conjecture_shape name orelse
blanchet@39373
   593
        (* the last line must be kept *)
blanchet@39373
   594
        j = 0 orelse
blanchet@36570
   595
        (not (is_only_type_information t) andalso
blanchet@36570
   596
         null (Term.add_tvars t []) andalso
blanchet@36570
   597
         not (exists_subterm (is_bad_free frees) t) andalso
blanchet@39373
   598
         length deps >= 2 andalso j mod isar_shrink_factor = 0 andalso
blanchet@39373
   599
         (* kill next to last line, which usually results in a trivial step *)
blanchet@39373
   600
         j <> 1) then
blanchet@39368
   601
       Inference (name, t, deps) :: lines  (* keep line *)
blanchet@36402
   602
     else
blanchet@39373
   603
       map (replace_dependencies_in_line (name, deps)) lines)  (* drop line *)
paulson@21978
   604
blanchet@36402
   605
(** EXTRACTING LEMMAS **)
paulson@21979
   606
blanchet@38599
   607
(* Like "split_line", but ignores "\n" that follow a comma (as in SNARK's
blanchet@38599
   608
   output). *)
blanchet@38599
   609
val split_proof_lines =
blanchet@38599
   610
  let
blanchet@38599
   611
    fun aux [] [] = []
blanchet@38599
   612
      | aux line [] = [implode (rev line)]
blanchet@38599
   613
      | aux line ("," :: "\n" :: rest) = aux ("," :: line) rest
blanchet@38599
   614
      | aux line ("\n" :: rest) = aux line [] @ aux [] rest
blanchet@38599
   615
      | aux line (s :: rest) = aux (s :: line) rest
blanchet@38599
   616
  in aux [] o explode end
blanchet@38599
   617
blanchet@37991
   618
(* A list consisting of the first number in each line is returned. For TSTP,
blanchet@37991
   619
   interesting lines have the form "fof(108, axiom, ...)", where the number
blanchet@37991
   620
   (108) is extracted. For SPASS, lines have the form "108[0:Inp] ...", where
blanchet@38033
   621
   the first number (108) is extracted. For Vampire, we look for
blanchet@38033
   622
   "108. ... [input]". *)
blanchet@38282
   623
fun used_facts_in_atp_proof axiom_names atp_proof =
blanchet@35865
   624
  let
blanchet@38039
   625
    val tokens_of =
blanchet@38039
   626
      String.tokens (fn c => not (Char.isAlphaNum c) andalso c <> #"_")
blanchet@38599
   627
    fun do_line (tag :: num :: "axiom" :: (rest as _ :: _)) =
blanchet@38599
   628
        if tag = "cnf" orelse tag = "fof" then
blanchet@38748
   629
          (case strip_prefix_and_unascii axiom_prefix (List.last rest) of
blanchet@38599
   630
             SOME name =>
blanchet@38698
   631
             if member (op =) rest "file" then
blanchet@38818
   632
               ([(name, name |> find_first_in_list_vector axiom_names |> the)]
blanchet@38818
   633
                handle Option.Option =>
blanchet@38818
   634
                       error ("No such fact: " ^ quote name ^ "."))
blanchet@38698
   635
             else
blanchet@39370
   636
               resolve_axiom axiom_names (Num num)
blanchet@39370
   637
           | NONE => resolve_axiom axiom_names (Num num))
blanchet@38599
   638
        else
blanchet@38818
   639
          []
blanchet@39370
   640
      | do_line (num :: "0" :: "Inp" :: _) = resolve_axiom axiom_names (Num num)
blanchet@38039
   641
      | do_line (num :: rest) =
blanchet@39370
   642
        (case List.last rest of
blanchet@39370
   643
           "input" => resolve_axiom axiom_names (Num num)
blanchet@39370
   644
         | _ => [])
blanchet@38818
   645
      | do_line _ = []
blanchet@38818
   646
  in atp_proof |> split_proof_lines |> maps (do_line o tokens_of) end
blanchet@37399
   647
blanchet@37399
   648
val indent_size = 2
blanchet@37399
   649
val no_label = ("", ~1)
blanchet@37399
   650
blanchet@37399
   651
val raw_prefix = "X"
blanchet@37399
   652
val assum_prefix = "A"
blanchet@37399
   653
val fact_prefix = "F"
blanchet@37399
   654
blanchet@37399
   655
fun string_for_label (s, num) = s ^ string_of_int num
blanchet@37399
   656
blanchet@39370
   657
fun raw_label_for_name conjecture_shape name =
blanchet@39370
   658
  case resolve_conjecture conjecture_shape name of
blanchet@39370
   659
    [j] => (conjecture_prefix, j)
blanchet@39373
   660
  | _ => case Int.fromString (raw_step_num name) of
blanchet@39370
   661
           SOME j => (raw_prefix, j)
blanchet@39373
   662
         | NONE => (raw_prefix ^ raw_step_num name, 0)
blanchet@39368
   663
blanchet@37399
   664
fun metis_using [] = ""
blanchet@37399
   665
  | metis_using ls =
blanchet@37399
   666
    "using " ^ space_implode " " (map string_for_label ls) ^ " "
blanchet@37399
   667
fun metis_apply _ 1 = "by "
blanchet@37399
   668
  | metis_apply 1 _ = "apply "
blanchet@37399
   669
  | metis_apply i _ = "prefer " ^ string_of_int i ^ " apply "
blanchet@37479
   670
fun metis_name full_types = if full_types then "metisFT" else "metis"
blanchet@37479
   671
fun metis_call full_types [] = metis_name full_types
blanchet@37479
   672
  | metis_call full_types ss =
blanchet@37479
   673
    "(" ^ metis_name full_types ^ " " ^ space_implode " " ss ^ ")"
blanchet@37479
   674
fun metis_command full_types i n (ls, ss) =
blanchet@37479
   675
  metis_using ls ^ metis_apply i n ^ metis_call full_types ss
blanchet@39327
   676
fun metis_line banner full_types i n ss =
blanchet@39327
   677
  banner ^ ": " ^
blanchet@38597
   678
  Markup.markup Markup.sendback (metis_command full_types i n ([], ss)) ^ "."
blanchet@36281
   679
fun minimize_line _ [] = ""
blanchet@38696
   680
  | minimize_line minimize_command ss =
blanchet@38696
   681
    case minimize_command ss of
blanchet@36281
   682
      "" => ""
blanchet@36281
   683
    | command =>
blanchet@38597
   684
      "\nTo minimize the number of lemmas, try this: " ^
blanchet@38597
   685
      Markup.markup Markup.sendback command ^ "."
immler@31840
   686
blanchet@38282
   687
fun used_facts axiom_names =
blanchet@38282
   688
  used_facts_in_atp_proof axiom_names
blanchet@38752
   689
  #> List.partition (curry (op =) Chained o snd)
blanchet@38752
   690
  #> pairself (sort_distinct (string_ord o pairself fst))
blanchet@38015
   691
blanchet@39327
   692
fun metis_proof_text (banner, full_types, minimize_command, atp_proof,
blanchet@39327
   693
                      axiom_names, goal, i) =
blanchet@36063
   694
  let
blanchet@38282
   695
    val (chained_lemmas, other_lemmas) = used_facts axiom_names atp_proof
blanchet@36063
   696
    val n = Logic.count_prems (prop_of goal)
blanchet@37171
   697
  in
blanchet@39327
   698
    (metis_line banner full_types i n (map fst other_lemmas) ^
blanchet@38752
   699
     minimize_line minimize_command (map fst (other_lemmas @ chained_lemmas)),
blanchet@38752
   700
     other_lemmas @ chained_lemmas)
blanchet@37171
   701
  end
immler@31037
   702
blanchet@36486
   703
(** Isar proof construction and manipulation **)
blanchet@36486
   704
blanchet@36486
   705
fun merge_fact_sets (ls1, ss1) (ls2, ss2) =
blanchet@36486
   706
  (union (op =) ls1 ls2, union (op =) ss1 ss2)
blanchet@36402
   707
blanchet@36402
   708
type label = string * int
blanchet@36402
   709
type facts = label list * string list
blanchet@36402
   710
blanchet@36402
   711
datatype qualifier = Show | Then | Moreover | Ultimately
blanchet@36291
   712
blanchet@36402
   713
datatype step =
blanchet@36478
   714
  Fix of (string * typ) list |
blanchet@36486
   715
  Let of term * term |
blanchet@36402
   716
  Assume of label * term |
blanchet@36402
   717
  Have of qualifier list * label * term * byline
blanchet@36402
   718
and byline =
blanchet@36564
   719
  ByMetis of facts |
blanchet@36402
   720
  CaseSplit of step list list * facts
blanchet@36402
   721
blanchet@36574
   722
fun smart_case_split [] facts = ByMetis facts
blanchet@36574
   723
  | smart_case_split proofs facts = CaseSplit (proofs, facts)
blanchet@36574
   724
blanchet@39373
   725
fun add_fact_from_dependency conjecture_shape axiom_names name =
blanchet@39370
   726
  if is_axiom axiom_names name then
blanchet@39368
   727
    apsnd (union (op =) (map fst (resolve_axiom axiom_names name)))
blanchet@36475
   728
  else
blanchet@39370
   729
    apfst (insert (op =) (raw_label_for_name conjecture_shape name))
blanchet@36402
   730
blanchet@37998
   731
fun forall_of v t = HOLogic.all_const (fastype_of v) $ lambda v t
blanchet@36491
   732
fun forall_vars t = fold_rev forall_of (map Var (Term.add_vars t [])) t
blanchet@36491
   733
blanchet@39370
   734
fun step_for_line _ _ _ (Definition (_, t1, t2)) = Let (t1, t2)
blanchet@39370
   735
  | step_for_line conjecture_shape _ _ (Inference (name, t, [])) =
blanchet@39370
   736
    Assume (raw_label_for_name conjecture_shape name, t)
blanchet@39370
   737
  | step_for_line conjecture_shape axiom_names j (Inference (name, t, deps)) =
blanchet@39370
   738
    Have (if j = 1 then [Show] else [],
blanchet@39370
   739
          raw_label_for_name conjecture_shape name, forall_vars t,
blanchet@39373
   740
          ByMetis (fold (add_fact_from_dependency conjecture_shape axiom_names)
blanchet@39373
   741
                        deps ([], [])))
blanchet@36291
   742
blanchet@39372
   743
fun raw_step_name (Definition (name, _, _)) = name
blanchet@39372
   744
  | raw_step_name (Inference (name, _, _)) = name
blanchet@39372
   745
blanchet@36967
   746
fun proof_from_atp_proof pool ctxt full_types tfrees isar_shrink_factor
blanchet@38282
   747
                         atp_proof conjecture_shape axiom_names params frees =
blanchet@36402
   748
  let
blanchet@36486
   749
    val lines =
blanchet@38035
   750
      atp_proof ^ "$" (* the $ sign acts as a sentinel (FIXME: needed?) *)
blanchet@36548
   751
      |> parse_proof pool
blanchet@39372
   752
      |> sort (raw_step_name_ord o pairself raw_step_name)
blanchet@39373
   753
      |> clean_up_dependencies []
blanchet@36967
   754
      |> decode_lines ctxt full_types tfrees
blanchet@38282
   755
      |> rpair [] |-> fold_rev (add_line conjecture_shape axiom_names)
blanchet@36486
   756
      |> rpair [] |-> fold_rev add_nontrivial_line
blanchet@37498
   757
      |> rpair (0, []) |-> fold_rev (add_desired_line isar_shrink_factor
blanchet@38282
   758
                                             conjecture_shape axiom_names frees)
blanchet@36486
   759
      |> snd
blanchet@36402
   760
  in
blanchet@36909
   761
    (if null params then [] else [Fix params]) @
blanchet@39370
   762
    map2 (step_for_line conjecture_shape axiom_names) (length lines downto 1)
blanchet@39370
   763
         lines
blanchet@36402
   764
  end
blanchet@36402
   765
blanchet@36402
   766
(* When redirecting proofs, we keep information about the labels seen so far in
blanchet@36402
   767
   the "backpatches" data structure. The first component indicates which facts
blanchet@36402
   768
   should be associated with forthcoming proof steps. The second component is a
blanchet@37322
   769
   pair ("assum_ls", "drop_ls"), where "assum_ls" are the labels that should
blanchet@37322
   770
   become assumptions and "drop_ls" are the labels that should be dropped in a
blanchet@37322
   771
   case split. *)
blanchet@36402
   772
type backpatches = (label * facts) list * (label list * label list)
blanchet@36402
   773
blanchet@36556
   774
fun used_labels_of_step (Have (_, _, _, by)) =
blanchet@36402
   775
    (case by of
blanchet@36564
   776
       ByMetis (ls, _) => ls
blanchet@36556
   777
     | CaseSplit (proofs, (ls, _)) =>
blanchet@36556
   778
       fold (union (op =) o used_labels_of) proofs ls)
blanchet@36556
   779
  | used_labels_of_step _ = []
blanchet@36556
   780
and used_labels_of proof = fold (union (op =) o used_labels_of_step) proof []
blanchet@36402
   781
blanchet@36402
   782
fun new_labels_of_step (Fix _) = []
blanchet@36486
   783
  | new_labels_of_step (Let _) = []
blanchet@36402
   784
  | new_labels_of_step (Assume (l, _)) = [l]
blanchet@36402
   785
  | new_labels_of_step (Have (_, l, _, _)) = [l]
blanchet@36402
   786
val new_labels_of = maps new_labels_of_step
blanchet@36402
   787
blanchet@36402
   788
val join_proofs =
blanchet@36402
   789
  let
blanchet@36402
   790
    fun aux _ [] = NONE
blanchet@36402
   791
      | aux proof_tail (proofs as (proof1 :: _)) =
blanchet@36402
   792
        if exists null proofs then
blanchet@36402
   793
          NONE
blanchet@36402
   794
        else if forall (curry (op =) (hd proof1) o hd) (tl proofs) then
blanchet@36402
   795
          aux (hd proof1 :: proof_tail) (map tl proofs)
blanchet@36402
   796
        else case hd proof1 of
blanchet@37498
   797
          Have ([], l, t, _) => (* FIXME: should we really ignore the "by"? *)
blanchet@36402
   798
          if forall (fn Have ([], l', t', _) :: _ => (l, t) = (l', t')
blanchet@36402
   799
                      | _ => false) (tl proofs) andalso
blanchet@36402
   800
             not (exists (member (op =) (maps new_labels_of proofs))
blanchet@36556
   801
                         (used_labels_of proof_tail)) then
blanchet@36402
   802
            SOME (l, t, map rev proofs, proof_tail)
blanchet@36402
   803
          else
blanchet@36402
   804
            NONE
blanchet@36402
   805
        | _ => NONE
blanchet@36402
   806
  in aux [] o map rev end
blanchet@36402
   807
blanchet@36402
   808
fun case_split_qualifiers proofs =
blanchet@36402
   809
  case length proofs of
blanchet@36402
   810
    0 => []
blanchet@36402
   811
  | 1 => [Then]
blanchet@36402
   812
  | _ => [Ultimately]
blanchet@36402
   813
blanchet@39372
   814
fun redirect_proof hyp_ts concl_t proof =
wenzelm@33310
   815
  let
blanchet@37324
   816
    (* The first pass outputs those steps that are independent of the negated
blanchet@37324
   817
       conjecture. The second pass flips the proof by contradiction to obtain a
blanchet@37324
   818
       direct proof, introducing case splits when an inference depends on
blanchet@37324
   819
       several facts that depend on the negated conjecture. *)
blanchet@39372
   820
     val concl_l = (conjecture_prefix, length hyp_ts)
blanchet@38040
   821
     fun first_pass ([], contra) = ([], contra)
blanchet@38040
   822
       | first_pass ((step as Fix _) :: proof, contra) =
blanchet@38040
   823
         first_pass (proof, contra) |>> cons step
blanchet@38040
   824
       | first_pass ((step as Let _) :: proof, contra) =
blanchet@38040
   825
         first_pass (proof, contra) |>> cons step
blanchet@39370
   826
       | first_pass ((step as Assume (l as (_, j), _)) :: proof, contra) =
blanchet@39372
   827
         if l = concl_l then first_pass (proof, contra ||> cons step)
blanchet@39372
   828
         else first_pass (proof, contra) |>> cons (Assume (l, nth hyp_ts j))
blanchet@38040
   829
       | first_pass (Have (qs, l, t, ByMetis (ls, ss)) :: proof, contra) =
blanchet@39372
   830
         let val step = Have (qs, l, t, ByMetis (ls, ss)) in
blanchet@38040
   831
           if exists (member (op =) (fst contra)) ls then
blanchet@38040
   832
             first_pass (proof, contra |>> cons l ||> cons step)
blanchet@38040
   833
           else
blanchet@38040
   834
             first_pass (proof, contra) |>> cons step
blanchet@38040
   835
         end
blanchet@38040
   836
       | first_pass _ = raise Fail "malformed proof"
blanchet@36402
   837
    val (proof_top, (contra_ls, contra_proof)) =
blanchet@39372
   838
      first_pass (proof, ([concl_l], []))
blanchet@36402
   839
    val backpatch_label = the_default ([], []) oo AList.lookup (op =) o fst
blanchet@36402
   840
    fun backpatch_labels patches ls =
blanchet@36402
   841
      fold merge_fact_sets (map (backpatch_label patches) ls) ([], [])
blanchet@36402
   842
    fun second_pass end_qs ([], assums, patches) =
blanchet@37324
   843
        ([Have (end_qs, no_label, concl_t,
blanchet@36564
   844
                ByMetis (backpatch_labels patches (map snd assums)))], patches)
blanchet@36402
   845
      | second_pass end_qs (Assume (l, t) :: proof, assums, patches) =
blanchet@36402
   846
        second_pass end_qs (proof, (t, l) :: assums, patches)
blanchet@36564
   847
      | second_pass end_qs (Have (qs, l, t, ByMetis (ls, ss)) :: proof, assums,
blanchet@36402
   848
                            patches) =
blanchet@39373
   849
        (if member (op =) (snd (snd patches)) l andalso
blanchet@39373
   850
            not (member (op =) (fst (snd patches)) l) andalso
blanchet@39373
   851
            not (AList.defined (op =) (fst patches) l) then
blanchet@39373
   852
           second_pass end_qs (proof, assums, patches ||> apsnd (append ls))
blanchet@39373
   853
         else case List.partition (member (op =) contra_ls) ls of
blanchet@39373
   854
           ([contra_l], co_ls) =>
blanchet@39373
   855
           if member (op =) qs Show then
blanchet@39373
   856
             second_pass end_qs (proof, assums,
blanchet@39373
   857
                                 patches |>> cons (contra_l, (co_ls, ss)))
blanchet@39373
   858
           else
blanchet@39373
   859
             second_pass end_qs
blanchet@39373
   860
                         (proof, assums,
blanchet@39373
   861
                          patches |>> cons (contra_l, (l :: co_ls, ss)))
blanchet@39373
   862
             |>> cons (if member (op =) (fst (snd patches)) l then
blanchet@39373
   863
                         Assume (l, negate_term t)
blanchet@39373
   864
                       else
blanchet@39373
   865
                         Have (qs, l, negate_term t,
blanchet@39373
   866
                               ByMetis (backpatch_label patches l)))
blanchet@39373
   867
         | (contra_ls as _ :: _, co_ls) =>
blanchet@39373
   868
           let
blanchet@39373
   869
             val proofs =
blanchet@39373
   870
               map_filter
blanchet@39373
   871
                   (fn l =>
blanchet@39373
   872
                       if l = concl_l then
blanchet@39373
   873
                         NONE
blanchet@39373
   874
                       else
blanchet@39373
   875
                         let
blanchet@39373
   876
                           val drop_ls = filter (curry (op <>) l) contra_ls
blanchet@39373
   877
                         in
blanchet@39373
   878
                           second_pass []
blanchet@39373
   879
                               (proof, assums,
blanchet@39373
   880
                                patches ||> apfst (insert (op =) l)
blanchet@39373
   881
                                        ||> apsnd (union (op =) drop_ls))
blanchet@39373
   882
                           |> fst |> SOME
blanchet@39373
   883
                         end) contra_ls
blanchet@39373
   884
             val (assumes, facts) =
blanchet@39373
   885
               if member (op =) (fst (snd patches)) l then
blanchet@39373
   886
                 ([Assume (l, negate_term t)], (l :: co_ls, ss))
blanchet@39373
   887
               else
blanchet@39373
   888
                 ([], (co_ls, ss))
blanchet@39373
   889
           in
blanchet@39373
   890
             (case join_proofs proofs of
blanchet@39373
   891
                SOME (l, t, proofs, proof_tail) =>
blanchet@39373
   892
                Have (case_split_qualifiers proofs @
blanchet@39373
   893
                      (if null proof_tail then end_qs else []), l, t,
blanchet@39373
   894
                      smart_case_split proofs facts) :: proof_tail
blanchet@39373
   895
              | NONE =>
blanchet@39373
   896
                [Have (case_split_qualifiers proofs @ end_qs, no_label,
blanchet@39373
   897
                       concl_t, smart_case_split proofs facts)],
blanchet@39373
   898
              patches)
blanchet@39373
   899
             |>> append assumes
blanchet@39373
   900
           end
blanchet@39373
   901
         | _ => raise Fail "malformed proof")
blanchet@36402
   902
       | second_pass _ _ = raise Fail "malformed proof"
blanchet@36486
   903
    val proof_bottom =
blanchet@36486
   904
      second_pass [Show] (contra_proof, [], ([], ([], []))) |> fst
blanchet@36402
   905
  in proof_top @ proof_bottom end
blanchet@36402
   906
blanchet@38490
   907
(* FIXME: Still needed? Probably not. *)
blanchet@36402
   908
val kill_duplicate_assumptions_in_proof =
blanchet@36402
   909
  let
blanchet@36402
   910
    fun relabel_facts subst =
blanchet@36402
   911
      apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
blanchet@36491
   912
    fun do_step (step as Assume (l, t)) (proof, subst, assums) =
blanchet@36402
   913
        (case AList.lookup (op aconv) assums t of
blanchet@36967
   914
           SOME l' => (proof, (l, l') :: subst, assums)
blanchet@36491
   915
         | NONE => (step :: proof, subst, (t, l) :: assums))
blanchet@36402
   916
      | do_step (Have (qs, l, t, by)) (proof, subst, assums) =
blanchet@36402
   917
        (Have (qs, l, t,
blanchet@36402
   918
               case by of
blanchet@36564
   919
                 ByMetis facts => ByMetis (relabel_facts subst facts)
blanchet@36402
   920
               | CaseSplit (proofs, facts) =>
blanchet@36402
   921
                 CaseSplit (map do_proof proofs, relabel_facts subst facts)) ::
blanchet@36402
   922
         proof, subst, assums)
blanchet@36491
   923
      | do_step step (proof, subst, assums) = (step :: proof, subst, assums)
blanchet@36402
   924
    and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
blanchet@36402
   925
  in do_proof end
blanchet@36402
   926
blanchet@36402
   927
val then_chain_proof =
blanchet@36402
   928
  let
blanchet@36402
   929
    fun aux _ [] = []
blanchet@36491
   930
      | aux _ ((step as Assume (l, _)) :: proof) = step :: aux l proof
blanchet@36402
   931
      | aux l' (Have (qs, l, t, by) :: proof) =
blanchet@36402
   932
        (case by of
blanchet@36564
   933
           ByMetis (ls, ss) =>
blanchet@36402
   934
           Have (if member (op =) ls l' then
blanchet@36402
   935
                   (Then :: qs, l, t,
blanchet@36564
   936
                    ByMetis (filter_out (curry (op =) l') ls, ss))
blanchet@36402
   937
                 else
blanchet@36564
   938
                   (qs, l, t, ByMetis (ls, ss)))
blanchet@36402
   939
         | CaseSplit (proofs, facts) =>
blanchet@36402
   940
           Have (qs, l, t, CaseSplit (map (aux no_label) proofs, facts))) ::
blanchet@36402
   941
        aux l proof
blanchet@36491
   942
      | aux _ (step :: proof) = step :: aux no_label proof
blanchet@36402
   943
  in aux no_label end
blanchet@36402
   944
blanchet@36402
   945
fun kill_useless_labels_in_proof proof =
blanchet@36402
   946
  let
blanchet@36556
   947
    val used_ls = used_labels_of proof
blanchet@36402
   948
    fun do_label l = if member (op =) used_ls l then l else no_label
blanchet@36556
   949
    fun do_step (Assume (l, t)) = Assume (do_label l, t)
blanchet@36556
   950
      | do_step (Have (qs, l, t, by)) =
blanchet@36402
   951
        Have (qs, do_label l, t,
blanchet@36402
   952
              case by of
blanchet@36402
   953
                CaseSplit (proofs, facts) =>
blanchet@36556
   954
                CaseSplit (map (map do_step) proofs, facts)
blanchet@36402
   955
              | _ => by)
blanchet@36556
   956
      | do_step step = step
blanchet@36556
   957
  in map do_step proof end
blanchet@36402
   958
blanchet@36402
   959
fun prefix_for_depth n = replicate_string (n + 1)
blanchet@36402
   960
blanchet@36402
   961
val relabel_proof =
blanchet@36402
   962
  let
blanchet@36402
   963
    fun aux _ _ _ [] = []
blanchet@36402
   964
      | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
blanchet@36402
   965
        if l = no_label then
blanchet@36402
   966
          Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   967
        else
blanchet@36402
   968
          let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
blanchet@36402
   969
            Assume (l', t) ::
blanchet@36402
   970
            aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
blanchet@36402
   971
          end
blanchet@36402
   972
      | aux subst depth (next_assum, next_fact) (Have (qs, l, t, by) :: proof) =
blanchet@36402
   973
        let
blanchet@36402
   974
          val (l', subst, next_fact) =
blanchet@36402
   975
            if l = no_label then
blanchet@36402
   976
              (l, subst, next_fact)
blanchet@36402
   977
            else
blanchet@36402
   978
              let
blanchet@36402
   979
                val l' = (prefix_for_depth depth fact_prefix, next_fact)
blanchet@36402
   980
              in (l', (l, l') :: subst, next_fact + 1) end
blanchet@36570
   981
          val relabel_facts =
blanchet@39370
   982
            apfst (maps (the_list o AList.lookup (op =) subst))
blanchet@36402
   983
          val by =
blanchet@36402
   984
            case by of
blanchet@36564
   985
              ByMetis facts => ByMetis (relabel_facts facts)
blanchet@36402
   986
            | CaseSplit (proofs, facts) =>
blanchet@36402
   987
              CaseSplit (map (aux subst (depth + 1) (1, 1)) proofs,
blanchet@36402
   988
                         relabel_facts facts)
blanchet@36402
   989
        in
blanchet@36402
   990
          Have (qs, l', t, by) ::
blanchet@36402
   991
          aux subst depth (next_assum, next_fact) proof
blanchet@36402
   992
        end
blanchet@36491
   993
      | aux subst depth nextp (step :: proof) =
blanchet@36491
   994
        step :: aux subst depth nextp proof
blanchet@36402
   995
  in aux [] 0 (1, 1) end
blanchet@36402
   996
wenzelm@39115
   997
fun string_for_proof ctxt0 full_types i n =
blanchet@36402
   998
  let
wenzelm@39134
   999
    val ctxt = ctxt0
wenzelm@39134
  1000
      |> Config.put show_free_types false
wenzelm@39134
  1001
      |> Config.put show_types true
blanchet@37319
  1002
    fun fix_print_mode f x =
wenzelm@39134
  1003
      Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
wenzelm@39134
  1004
                               (print_mode_value ())) f x
blanchet@36402
  1005
    fun do_indent ind = replicate_string (ind * indent_size) " "
blanchet@36478
  1006
    fun do_free (s, T) =
blanchet@36478
  1007
      maybe_quote s ^ " :: " ^
blanchet@36478
  1008
      maybe_quote (fix_print_mode (Syntax.string_of_typ ctxt) T)
blanchet@36570
  1009
    fun do_label l = if l = no_label then "" else string_for_label l ^ ": "
blanchet@36402
  1010
    fun do_have qs =
blanchet@36402
  1011
      (if member (op =) qs Moreover then "moreover " else "") ^
blanchet@36402
  1012
      (if member (op =) qs Ultimately then "ultimately " else "") ^
blanchet@36402
  1013
      (if member (op =) qs Then then
blanchet@36402
  1014
         if member (op =) qs Show then "thus" else "hence"
blanchet@36402
  1015
       else
blanchet@36402
  1016
         if member (op =) qs Show then "show" else "have")
blanchet@36478
  1017
    val do_term = maybe_quote o fix_print_mode (Syntax.string_of_term ctxt)
blanchet@36570
  1018
    fun do_facts (ls, ss) =
blanchet@38698
  1019
      metis_command full_types 1 1
blanchet@38698
  1020
                    (ls |> sort_distinct (prod_ord string_ord int_ord),
blanchet@38698
  1021
                     ss |> sort_distinct string_ord)
blanchet@36478
  1022
    and do_step ind (Fix xs) =
blanchet@36478
  1023
        do_indent ind ^ "fix " ^ space_implode " and " (map do_free xs) ^ "\n"
blanchet@36486
  1024
      | do_step ind (Let (t1, t2)) =
blanchet@36486
  1025
        do_indent ind ^ "let " ^ do_term t1 ^ " = " ^ do_term t2 ^ "\n"
blanchet@36402
  1026
      | do_step ind (Assume (l, t)) =
blanchet@36402
  1027
        do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
blanchet@36564
  1028
      | do_step ind (Have (qs, l, t, ByMetis facts)) =
blanchet@36402
  1029
        do_indent ind ^ do_have qs ^ " " ^
blanchet@36479
  1030
        do_label l ^ do_term t ^ " " ^ do_facts facts ^ "\n"
blanchet@36402
  1031
      | do_step ind (Have (qs, l, t, CaseSplit (proofs, facts))) =
blanchet@36402
  1032
        space_implode (do_indent ind ^ "moreover\n")
blanchet@36402
  1033
                      (map (do_block ind) proofs) ^
blanchet@36479
  1034
        do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ " " ^
blanchet@36478
  1035
        do_facts facts ^ "\n"
blanchet@36402
  1036
    and do_steps prefix suffix ind steps =
blanchet@36402
  1037
      let val s = implode (map (do_step ind) steps) in
blanchet@36402
  1038
        replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
blanchet@36402
  1039
        String.extract (s, ind * indent_size,
blanchet@36402
  1040
                        SOME (size s - ind * indent_size - 1)) ^
blanchet@36402
  1041
        suffix ^ "\n"
blanchet@36402
  1042
      end
blanchet@36402
  1043
    and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
blanchet@36564
  1044
    (* One-step proofs are pointless; better use the Metis one-liner
blanchet@36564
  1045
       directly. *)
blanchet@36564
  1046
    and do_proof [Have (_, _, _, ByMetis _)] = ""
blanchet@36564
  1047
      | do_proof proof =
blanchet@36480
  1048
        (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
blanchet@36480
  1049
        do_indent 0 ^ "proof -\n" ^
blanchet@36480
  1050
        do_steps "" "" 1 proof ^
blanchet@38599
  1051
        do_indent 0 ^ (if n <> 1 then "next" else "qed")
blanchet@36488
  1052
  in do_proof end
blanchet@36402
  1053
blanchet@37479
  1054
fun isar_proof_text (pool, debug, isar_shrink_factor, ctxt, conjecture_shape)
blanchet@39327
  1055
                    (other_params as (_, full_types, _, atp_proof, axiom_names,
blanchet@38282
  1056
                                      goal, i)) =
blanchet@36402
  1057
  let
blanchet@36909
  1058
    val (params, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@36909
  1059
    val frees = fold Term.add_frees (concl_t :: hyp_ts) []
blanchet@36967
  1060
    val tfrees = fold Term.add_tfrees (concl_t :: hyp_ts) []
blanchet@36402
  1061
    val n = Logic.count_prems (prop_of goal)
blanchet@37479
  1062
    val (one_line_proof, lemma_names) = metis_proof_text other_params
blanchet@36283
  1063
    fun isar_proof_for () =
blanchet@36967
  1064
      case proof_from_atp_proof pool ctxt full_types tfrees isar_shrink_factor
blanchet@38282
  1065
                                atp_proof conjecture_shape axiom_names params
blanchet@36924
  1066
                                frees
blanchet@39372
  1067
           |> redirect_proof hyp_ts concl_t
blanchet@36402
  1068
           |> kill_duplicate_assumptions_in_proof
blanchet@36402
  1069
           |> then_chain_proof
blanchet@36402
  1070
           |> kill_useless_labels_in_proof
blanchet@36402
  1071
           |> relabel_proof
blanchet@37479
  1072
           |> string_for_proof ctxt full_types i n of
blanchet@38599
  1073
        "" => "\nNo structured proof available."
blanchet@38599
  1074
      | proof => "\n\nStructured proof:\n" ^ Markup.markup Markup.sendback proof
blanchet@35868
  1075
    val isar_proof =
blanchet@36402
  1076
      if debug then
blanchet@36283
  1077
        isar_proof_for ()
blanchet@36283
  1078
      else
blanchet@36283
  1079
        try isar_proof_for ()
blanchet@38599
  1080
        |> the_default "\nWarning: The Isar proof construction failed."
blanchet@36283
  1081
  in (one_line_proof ^ isar_proof, lemma_names) end
paulson@21978
  1082
blanchet@36557
  1083
fun proof_text isar_proof isar_params other_params =
blanchet@36557
  1084
  (if isar_proof then isar_proof_text isar_params else metis_proof_text)
blanchet@36557
  1085
      other_params
blanchet@36223
  1086
immler@31038
  1087
end;