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