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