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