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