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