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