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