src/HOL/Tools/ATP/atp_proof_reconstruct.ML
author blanchet
Mon Jan 23 17:40:32 2012 +0100 (2012-01-23)
changeset 46320 0b8b73b49848
parent 45887 src/HOL/Tools/ATP/atp_reconstruct.ML@bfb5234a70ba
child 46340 cac402c486b0
permissions -rw-r--r--
renamed two files to make room for a new file
blanchet@46320
     1
(*  Title:      HOL/Tools/ATP/atp_proof_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@43085
     6
Proof reconstruction from ATP proofs.
wenzelm@33310
     7
*)
wenzelm@33310
     8
blanchet@46320
     9
signature ATP_PROOF_RECONSTRUCT =
paulson@24425
    10
sig
nik@43678
    11
  type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
blanchet@43127
    12
  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
blanchet@42449
    13
  type 'a proof = 'a ATP_Proof.proof
blanchet@46320
    14
  type locality = ATP_Problem_Generate.locality
blanchet@43033
    15
blanchet@43033
    16
  datatype reconstructor =
blanchet@45519
    17
    Metis of string * string |
blanchet@45379
    18
    SMT
blanchet@43033
    19
blanchet@43050
    20
  datatype play =
blanchet@43050
    21
    Played of reconstructor * Time.time |
blanchet@44773
    22
    Trust_Playable of reconstructor * Time.time option |
blanchet@43166
    23
    Failed_to_Play of reconstructor
blanchet@43033
    24
blanchet@36281
    25
  type minimize_command = string list -> string
blanchet@43033
    26
  type one_line_params =
blanchet@43050
    27
    play * string * (string * locality) list * minimize_command * int * int
blanchet@38818
    28
  type isar_params =
blanchet@45552
    29
    bool * int * string Symtab.table * (string * locality) list vector
blanchet@45551
    30
    * int Symtab.table * string proof * thm
blanchet@45519
    31
blanchet@45519
    32
  val metisN : string
blanchet@45520
    33
  val smtN : string
blanchet@45519
    34
  val full_typesN : string
blanchet@45519
    35
  val partial_typesN : string
blanchet@45519
    36
  val no_typesN : string
blanchet@45519
    37
  val really_full_type_enc : string
blanchet@45519
    38
  val full_type_enc : string
blanchet@45519
    39
  val partial_type_enc : string
blanchet@45519
    40
  val no_type_enc : string
blanchet@45519
    41
  val full_type_encs : string list
blanchet@45519
    42
  val partial_type_encs : string list
blanchet@45554
    43
  val metis_default_lam_trans : string
blanchet@45554
    44
  val metis_call : string -> string -> string
blanchet@45554
    45
  val string_for_reconstructor : reconstructor -> string
blanchet@42451
    46
  val used_facts_in_atp_proof :
blanchet@45551
    47
    Proof.context -> (string * locality) list vector -> string proof
blanchet@43304
    48
    -> (string * locality) list
blanchet@45554
    49
  val lam_trans_from_atp_proof : string proof -> string -> string
blanchet@45590
    50
  val is_typed_helper_used_in_atp_proof : string proof -> bool
blanchet@42876
    51
  val used_facts_in_unsound_atp_proof :
blanchet@45551
    52
    Proof.context -> (string * locality) list vector -> 'a proof
blanchet@45551
    53
    -> string list option
blanchet@45519
    54
  val unalias_type_enc : string -> string list
blanchet@43033
    55
  val one_line_proof_text : one_line_params -> string
blanchet@43135
    56
  val make_tvar : string -> typ
blanchet@43135
    57
  val make_tfree : Proof.context -> string -> typ
blanchet@43094
    58
  val term_from_atp :
blanchet@44773
    59
    Proof.context -> bool -> int Symtab.table -> typ option
blanchet@44773
    60
    -> (string, string) ho_term -> term
blanchet@43127
    61
  val prop_from_atp :
blanchet@43135
    62
    Proof.context -> bool -> int Symtab.table
nik@43678
    63
    -> (string, string, (string, string) ho_term) formula -> term
blanchet@42968
    64
  val isar_proof_text :
blanchet@43062
    65
    Proof.context -> bool -> isar_params -> one_line_params -> string
blanchet@42968
    66
  val proof_text :
blanchet@43033
    67
    Proof.context -> bool -> isar_params -> one_line_params -> string
paulson@24425
    68
end;
paulson@21978
    69
blanchet@46320
    70
structure ATP_Proof_Reconstruct : ATP_PROOF_RECONSTRUCT =
paulson@21978
    71
struct
paulson@21978
    72
blanchet@43085
    73
open ATP_Util
blanchet@38028
    74
open ATP_Problem
blanchet@39452
    75
open ATP_Proof
blanchet@46320
    76
open ATP_Problem_Generate
paulson@21978
    77
blanchet@46320
    78
structure String_Redirect = ATP_Proof_Redirect(
blanchet@45887
    79
    type key = step_name
blanchet@45887
    80
    val ord = fn ((s, _ : string list), (s', _)) => fast_string_ord (s, s')
blanchet@45887
    81
    val string_of = fst)
blanchet@45887
    82
blanchet@45882
    83
open String_Redirect
blanchet@45882
    84
blanchet@43033
    85
datatype reconstructor =
blanchet@45519
    86
  Metis of string * string |
blanchet@45379
    87
  SMT
blanchet@43033
    88
blanchet@43050
    89
datatype play =
blanchet@43050
    90
  Played of reconstructor * Time.time |
blanchet@43033
    91
  Trust_Playable of reconstructor * Time.time option |
blanchet@43166
    92
  Failed_to_Play of reconstructor
blanchet@43033
    93
blanchet@36281
    94
type minimize_command = string list -> string
blanchet@43033
    95
type one_line_params =
blanchet@43050
    96
  play * string * (string * locality) list * minimize_command * int * int
blanchet@38818
    97
type isar_params =
blanchet@45552
    98
  bool * int * string Symtab.table * (string * locality) list vector
blanchet@45551
    99
  * int Symtab.table * string proof * thm
blanchet@42881
   100
blanchet@45519
   101
val metisN = "metis"
blanchet@45520
   102
val smtN = "smt"
blanchet@45519
   103
blanchet@45519
   104
val full_typesN = "full_types"
blanchet@45519
   105
val partial_typesN = "partial_types"
blanchet@45519
   106
val no_typesN = "no_types"
blanchet@45519
   107
blanchet@45519
   108
val really_full_type_enc = "mono_tags"
blanchet@45519
   109
val full_type_enc = "poly_guards_query"
blanchet@45519
   110
val partial_type_enc = "poly_args"
blanchet@45519
   111
val no_type_enc = "erased"
blanchet@45519
   112
blanchet@45519
   113
val full_type_encs = [full_type_enc, really_full_type_enc]
blanchet@45519
   114
val partial_type_encs = partial_type_enc :: full_type_encs
blanchet@45519
   115
blanchet@45519
   116
val type_enc_aliases =
blanchet@45519
   117
  [(full_typesN, full_type_encs),
blanchet@45519
   118
   (partial_typesN, partial_type_encs),
blanchet@45519
   119
   (no_typesN, [no_type_enc])]
blanchet@45519
   120
blanchet@45519
   121
fun unalias_type_enc s =
blanchet@45519
   122
  AList.lookup (op =) type_enc_aliases s |> the_default [s]
blanchet@45519
   123
blanchet@45519
   124
val metis_default_lam_trans = combinatorsN
blanchet@45519
   125
blanchet@45519
   126
fun metis_call type_enc lam_trans =
blanchet@45519
   127
  let
blanchet@45519
   128
    val type_enc =
blanchet@45519
   129
      case AList.find (fn (enc, encs) => enc = hd encs) type_enc_aliases
blanchet@45519
   130
                      type_enc of
blanchet@45519
   131
        [alias] => alias
blanchet@45519
   132
      | _ => type_enc
blanchet@45522
   133
    val opts = [] |> type_enc <> partial_typesN ? cons type_enc
blanchet@45519
   134
                  |> lam_trans <> metis_default_lam_trans ? cons lam_trans
blanchet@45520
   135
  in metisN ^ (if null opts then "" else " (" ^ commas opts ^ ")") end
blanchet@45519
   136
blanchet@45554
   137
fun string_for_reconstructor (Metis (type_enc, lam_trans)) =
blanchet@45519
   138
    metis_call type_enc lam_trans
blanchet@45554
   139
  | string_for_reconstructor SMT = smtN
blanchet@45554
   140
blanchet@45554
   141
fun find_first_in_list_vector vec key =
blanchet@45554
   142
  Vector.foldl (fn (ps, NONE) => AList.lookup (op =) ps key
blanchet@45554
   143
                 | (_, value) => value) NONE vec
blanchet@45554
   144
blanchet@45554
   145
val unprefix_fact_number = space_implode "_" o tl o space_explode "_"
blanchet@45554
   146
blanchet@45554
   147
fun resolve_one_named_fact fact_names s =
blanchet@45554
   148
  case try (unprefix fact_prefix) s of
blanchet@45554
   149
    SOME s' =>
blanchet@45554
   150
    let val s' = s' |> unprefix_fact_number |> unascii_of in
blanchet@45554
   151
      s' |> find_first_in_list_vector fact_names |> Option.map (pair s')
blanchet@45554
   152
    end
blanchet@45554
   153
  | NONE => NONE
blanchet@45554
   154
fun resolve_fact fact_names = map_filter (resolve_one_named_fact fact_names)
blanchet@45579
   155
fun is_fact fact_names = not o null o resolve_fact fact_names
blanchet@45554
   156
blanchet@45554
   157
fun resolve_one_named_conjecture s =
blanchet@45554
   158
  case try (unprefix conjecture_prefix) s of
blanchet@45554
   159
    SOME s' => Int.fromString s'
blanchet@45554
   160
  | NONE => NONE
blanchet@45554
   161
blanchet@45554
   162
val resolve_conjecture = map_filter resolve_one_named_conjecture
blanchet@45554
   163
val is_conjecture = not o null o resolve_conjecture
blanchet@45554
   164
blanchet@45554
   165
fun is_axiom_used_in_proof pred =
blanchet@45554
   166
  exists (fn Inference ((_, ss), _, _, []) => exists pred ss | _ => false)
blanchet@45554
   167
blanchet@45554
   168
val is_combinator_def = String.isPrefix (helper_prefix ^ combinator_prefix)
blanchet@45554
   169
blanchet@45554
   170
val ascii_of_lam_fact_prefix = ascii_of lam_fact_prefix
blanchet@45554
   171
blanchet@45554
   172
(* overapproximation (good enough) *)
blanchet@45554
   173
fun is_lam_lifted s =
blanchet@45554
   174
  String.isPrefix fact_prefix s andalso
blanchet@45554
   175
  String.isSubstring ascii_of_lam_fact_prefix s
blanchet@45554
   176
blanchet@45554
   177
fun lam_trans_from_atp_proof atp_proof default =
blanchet@45554
   178
  if is_axiom_used_in_proof is_combinator_def atp_proof then combinatorsN
blanchet@45554
   179
  else if is_axiom_used_in_proof is_lam_lifted atp_proof then lam_liftingN
blanchet@45554
   180
  else default
blanchet@45554
   181
blanchet@45554
   182
val is_typed_helper_name =
blanchet@45554
   183
  String.isPrefix helper_prefix andf String.isSuffix typed_helper_suffix
blanchet@45590
   184
fun is_typed_helper_used_in_atp_proof atp_proof =
blanchet@45590
   185
  is_axiom_used_in_proof is_typed_helper_name atp_proof
blanchet@45554
   186
blanchet@45554
   187
val leo2_ext = "extcnf_equal_neg"
blanchet@45554
   188
val isa_ext = Thm.get_name_hint @{thm ext}
blanchet@45554
   189
val isa_short_ext = Long_Name.base_name isa_ext
blanchet@45554
   190
blanchet@45554
   191
fun ext_name ctxt =
blanchet@45554
   192
  if Thm.eq_thm_prop (@{thm ext},
blanchet@45554
   193
         singleton (Attrib.eval_thms ctxt) (Facts.named isa_short_ext, [])) then
blanchet@45554
   194
    isa_short_ext
blanchet@45554
   195
  else
blanchet@45554
   196
    isa_ext
blanchet@45554
   197
blanchet@45554
   198
fun add_fact _ fact_names (Inference ((_, ss), _, _, [])) =
blanchet@45554
   199
    union (op =) (resolve_fact fact_names ss)
blanchet@45554
   200
  | add_fact ctxt _ (Inference (_, _, rule, _)) =
blanchet@45554
   201
    if rule = leo2_ext then insert (op =) (ext_name ctxt, General) else I
blanchet@45554
   202
  | add_fact _ _ _ = I
blanchet@45554
   203
blanchet@45554
   204
fun used_facts_in_atp_proof ctxt fact_names atp_proof =
blanchet@45554
   205
  if null atp_proof then Vector.foldl (uncurry (union (op =))) [] fact_names
blanchet@45554
   206
  else fold (add_fact ctxt fact_names) atp_proof []
blanchet@45554
   207
blanchet@45554
   208
(* (quasi-)underapproximation of the truth *)
blanchet@45554
   209
fun is_locality_global Local = false
blanchet@45554
   210
  | is_locality_global Assum = false
blanchet@45554
   211
  | is_locality_global Chained = false
blanchet@45554
   212
  | is_locality_global _ = true
blanchet@45554
   213
blanchet@45554
   214
fun used_facts_in_unsound_atp_proof _ _ [] = NONE
blanchet@45554
   215
  | used_facts_in_unsound_atp_proof ctxt fact_names atp_proof =
blanchet@45554
   216
    let
blanchet@45554
   217
      val used_facts = used_facts_in_atp_proof ctxt fact_names atp_proof
blanchet@45554
   218
    in
blanchet@45554
   219
      if forall (is_locality_global o snd) used_facts andalso
blanchet@45554
   220
         not (is_axiom_used_in_proof (is_conjecture o single) atp_proof) then
blanchet@45554
   221
        SOME (map fst used_facts)
blanchet@45554
   222
      else
blanchet@45554
   223
        NONE
blanchet@45554
   224
    end
blanchet@45554
   225
blanchet@45554
   226
blanchet@45554
   227
(** Soft-core proof reconstruction: one-liners **)
blanchet@43033
   228
blanchet@42449
   229
fun string_for_label (s, num) = s ^ string_of_int num
blanchet@42449
   230
blanchet@43033
   231
fun show_time NONE = ""
blanchet@43034
   232
  | show_time (SOME ext_time) = " (" ^ string_from_ext_time ext_time ^ ")"
blanchet@43033
   233
blanchet@45379
   234
fun apply_on_subgoal _ 1 = "by "
blanchet@45379
   235
  | apply_on_subgoal 1 _ = "apply "
blanchet@45379
   236
  | apply_on_subgoal i n =
blanchet@45379
   237
    "prefer " ^ string_of_int i ^ " " ^ apply_on_subgoal 1 n
blanchet@44002
   238
fun command_call name [] =
blanchet@44002
   239
    name |> not (Lexicon.is_identifier name) ? enclose "(" ")"
blanchet@42449
   240
  | command_call name args = "(" ^ name ^ " " ^ space_implode " " args ^ ")"
blanchet@43033
   241
fun try_command_line banner time command =
wenzelm@45666
   242
  banner ^ ": " ^ Markup.markup Isabelle_Markup.sendback command ^ show_time time ^ "."
blanchet@42449
   243
fun using_labels [] = ""
blanchet@42449
   244
  | using_labels ls =
blanchet@42449
   245
    "using " ^ space_implode " " (map string_for_label ls) ^ " "
blanchet@45520
   246
fun reconstructor_command reconstr i n (ls, ss) =
blanchet@45379
   247
  using_labels ls ^ apply_on_subgoal i n ^
blanchet@45554
   248
  command_call (string_for_reconstructor reconstr) ss
blanchet@42449
   249
fun minimize_line _ [] = ""
blanchet@42449
   250
  | minimize_line minimize_command ss =
blanchet@42449
   251
    case minimize_command ss of
blanchet@42449
   252
      "" => ""
wenzelm@45666
   253
    | command => "\nTo minimize: " ^ Markup.markup Isabelle_Markup.sendback command ^ "."
blanchet@39453
   254
blanchet@40723
   255
val split_used_facts =
blanchet@40723
   256
  List.partition (curry (op =) Chained o snd)
blanchet@39453
   257
  #> pairself (sort_distinct (string_ord o pairself fst))
blanchet@39453
   258
blanchet@43033
   259
fun one_line_proof_text (preplay, banner, used_facts, minimize_command,
blanchet@43037
   260
                         subgoal, subgoal_count) =
blanchet@39453
   261
  let
blanchet@43033
   262
    val (chained, extra) = split_used_facts used_facts
blanchet@45520
   263
    val (failed, reconstr, ext_time) =
blanchet@43033
   264
      case preplay of
blanchet@45520
   265
        Played (reconstr, time) => (false, reconstr, (SOME (false, time)))
blanchet@45520
   266
      | Trust_Playable (reconstr, time) =>
blanchet@45520
   267
        (false, reconstr,
blanchet@43033
   268
         case time of
blanchet@43033
   269
           NONE => NONE
blanchet@43033
   270
         | SOME time =>
blanchet@43033
   271
           if time = Time.zeroTime then NONE else SOME (true, time))
blanchet@45520
   272
      | Failed_to_Play reconstr => (true, reconstr, NONE)
blanchet@43033
   273
    val try_line =
blanchet@43166
   274
      ([], map fst extra)
blanchet@45520
   275
      |> reconstructor_command reconstr subgoal subgoal_count
blanchet@43166
   276
      |> (if failed then enclose "One-line proof reconstruction failed: " "."
blanchet@43166
   277
          else try_command_line banner ext_time)
blanchet@43033
   278
  in try_line ^ minimize_line minimize_command (map fst (extra @ chained)) end
blanchet@39453
   279
blanchet@39453
   280
(** Hard-core proof reconstruction: structured Isar proofs **)
blanchet@39453
   281
blanchet@39425
   282
fun forall_of v t = HOLogic.all_const (fastype_of v) $ lambda v t
blanchet@39425
   283
fun exists_of v t = HOLogic.exists_const (fastype_of v) $ lambda v t
blanchet@39425
   284
blanchet@43135
   285
fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS)
blanchet@43135
   286
fun make_tfree ctxt w =
blanchet@43135
   287
  let val ww = "'" ^ w in
blanchet@43135
   288
    TFree (ww, the_default HOLogic.typeS (Variable.def_sort ctxt (ww, ~1)))
blanchet@43135
   289
  end
blanchet@43135
   290
blanchet@39453
   291
val indent_size = 2
blanchet@39453
   292
val no_label = ("", ~1)
blanchet@39453
   293
blanchet@45882
   294
val raw_prefix = "x"
blanchet@45882
   295
val assum_prefix = "a"
blanchet@45882
   296
val have_prefix = "f"
blanchet@39370
   297
blanchet@45552
   298
fun raw_label_for_name (num, ss) =
blanchet@45552
   299
  case resolve_conjecture ss of
blanchet@39453
   300
    [j] => (conjecture_prefix, j)
blanchet@45552
   301
  | _ => case Int.fromString num of
blanchet@39453
   302
           SOME j => (raw_prefix, j)
blanchet@45552
   303
         | NONE => (raw_prefix ^ num, 0)
blanchet@39453
   304
paulson@21978
   305
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   306
nik@43678
   307
exception HO_TERM of (string, string) ho_term list
nik@43678
   308
exception FORMULA of (string, string, (string, string) ho_term) formula list
blanchet@37991
   309
exception SAME of unit
paulson@21978
   310
blanchet@36909
   311
(* Type variables are given the basic sort "HOL.type". Some will later be
blanchet@37991
   312
   constrained by information from type literals, or by type inference. *)
blanchet@43135
   313
fun typ_from_atp ctxt (u as ATerm (a, us)) =
blanchet@43135
   314
  let val Ts = map (typ_from_atp ctxt) us in
blanchet@45511
   315
    case unprefix_and_unascii type_const_prefix a of
blanchet@37991
   316
      SOME b => Type (invert_const b, Ts)
blanchet@37991
   317
    | NONE =>
blanchet@37991
   318
      if not (null us) then
nik@43678
   319
        raise HO_TERM [u]  (* only "tconst"s have type arguments *)
blanchet@45511
   320
      else case unprefix_and_unascii tfree_prefix a of
blanchet@43135
   321
        SOME b => make_tfree ctxt b
blanchet@36486
   322
      | NONE =>
blanchet@43302
   323
        (* Could be an Isabelle variable or a variable from the ATP, say "X1"
blanchet@43302
   324
           or "_5018". Sometimes variables from the ATP are indistinguishable
blanchet@43302
   325
           from Isabelle variables, which forces us to use a type parameter in
blanchet@43302
   326
           all cases. *)
blanchet@45511
   327
        (a |> perhaps (unprefix_and_unascii tvar_prefix), HOLogic.typeS)
blanchet@43302
   328
        |> Type_Infer.param 0
blanchet@37991
   329
  end
paulson@21978
   330
blanchet@38014
   331
(* Type class literal applied to a type. Returns triple of polarity, class,
blanchet@38014
   332
   type. *)
blanchet@43135
   333
fun type_constraint_from_term ctxt (u as ATerm (a, us)) =
blanchet@45511
   334
  case (unprefix_and_unascii class_prefix a, map (typ_from_atp ctxt) us) of
blanchet@42606
   335
    (SOME b, [T]) => (b, T)
nik@43678
   336
  | _ => raise HO_TERM [u]
blanchet@38014
   337
blanchet@43907
   338
(* Accumulate type constraints in a formula: negative type literals. *)
blanchet@38014
   339
fun add_var (key, z)  = Vartab.map_default (key, []) (cons z)
blanchet@42606
   340
fun add_type_constraint false (cl, TFree (a ,_)) = add_var ((a, ~1), cl)
blanchet@42606
   341
  | add_type_constraint false (cl, TVar (ix, _)) = add_var (ix, cl)
blanchet@42606
   342
  | add_type_constraint _ _ = I
blanchet@38014
   343
blanchet@43094
   344
fun repair_variable_name f s =
blanchet@36486
   345
  let
blanchet@36486
   346
    fun subscript_name s n = s ^ nat_subscript n
blanchet@38488
   347
    val s = String.map f s
blanchet@36486
   348
  in
blanchet@36486
   349
    case space_explode "_" s of
blanchet@36486
   350
      [_] => (case take_suffix Char.isDigit (String.explode s) of
blanchet@36486
   351
                (cs1 as _ :: _, cs2 as _ :: _) =>
blanchet@36486
   352
                subscript_name (String.implode cs1)
blanchet@36486
   353
                               (the (Int.fromString (String.implode cs2)))
blanchet@36486
   354
              | (_, _) => s)
blanchet@36486
   355
    | [s1, s2] => (case Int.fromString s2 of
blanchet@36486
   356
                     SOME n => subscript_name s1 n
blanchet@36486
   357
                   | NONE => s)
blanchet@36486
   358
    | _ => s
blanchet@36486
   359
  end
blanchet@43182
   360
blanchet@43907
   361
(* The number of type arguments of a constant, zero if it's monomorphic. For
blanchet@43907
   362
   (instances of) Skolem pseudoconstants, this information is encoded in the
blanchet@43907
   363
   constant name. *)
blanchet@43907
   364
fun num_type_args thy s =
blanchet@43907
   365
  if String.isPrefix skolem_const_prefix s then
blanchet@43907
   366
    s |> space_explode Long_Name.separator |> List.last |> Int.fromString |> the
blanchet@45554
   367
  else if String.isPrefix lam_lifted_prefix s then
blanchet@45554
   368
    if String.isPrefix lam_lifted_poly_prefix s then 2 else 0
blanchet@43907
   369
  else
blanchet@43907
   370
    (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
blanchet@43907
   371
blanchet@43182
   372
fun slack_fastype_of t = fastype_of t handle TERM _ => HOLogic.typeT
blanchet@43182
   373
blanchet@36909
   374
(* First-order translation. No types are known for variables. "HOLogic.typeT"
blanchet@38014
   375
   should allow them to be inferred. *)
blanchet@43135
   376
fun term_from_atp ctxt textual sym_tab =
blanchet@36909
   377
  let
blanchet@43135
   378
    val thy = Proof_Context.theory_of ctxt
blanchet@43212
   379
    (* For Metis, we use 1 rather than 0 because variable references in clauses
blanchet@43212
   380
       may otherwise conflict with variable constraints in the goal. At least,
blanchet@43212
   381
       type inference often fails otherwise. See also "axiom_inference" in
blanchet@43212
   382
       "Metis_Reconstruct". *)
blanchet@43094
   383
    val var_index = if textual then 0 else 1
blanchet@43131
   384
    fun do_term extra_ts opt_T u =
blanchet@36909
   385
      case u of
blanchet@44773
   386
        ATerm (s, us) =>
blanchet@44773
   387
        if String.isPrefix simple_type_prefix s then
blanchet@42962
   388
          @{const True} (* ignore TPTP type information *)
blanchet@44773
   389
        else if s = tptp_equal then
blanchet@43093
   390
          let val ts = map (do_term [] NONE) us in
blanchet@43094
   391
            if textual andalso length ts = 2 andalso
blanchet@43094
   392
              hd ts aconv List.last ts then
blanchet@39106
   393
              (* Vampire is keen on producing these. *)
blanchet@39106
   394
              @{const True}
blanchet@39106
   395
            else
blanchet@39106
   396
              list_comb (Const (@{const_name HOL.eq}, HOLogic.typeT), ts)
blanchet@39106
   397
          end
blanchet@45511
   398
        else case unprefix_and_unascii const_prefix s of
blanchet@44773
   399
          SOME s' =>
blanchet@42761
   400
          let
blanchet@44773
   401
            val ((s', s''), mangled_us) =
blanchet@44773
   402
              s' |> unmangled_const |>> `invert_const
blanchet@42761
   403
          in
blanchet@42755
   404
            if s' = type_tag_name then
blanchet@42589
   405
              case mangled_us @ us of
blanchet@42589
   406
                [typ_u, term_u] =>
blanchet@43135
   407
                do_term extra_ts (SOME (typ_from_atp ctxt typ_u)) term_u
nik@43678
   408
              | _ => raise HO_TERM us
blanchet@42966
   409
            else if s' = predicator_name then
blanchet@43093
   410
              do_term [] (SOME @{typ bool}) (hd us)
blanchet@42966
   411
            else if s' = app_op_name then
blanchet@43131
   412
              let val extra_t = do_term [] NONE (List.last us) in
blanchet@43131
   413
                do_term (extra_t :: extra_ts)
blanchet@43131
   414
                        (case opt_T of
blanchet@43182
   415
                           SOME T => SOME (slack_fastype_of extra_t --> T)
blanchet@43131
   416
                         | NONE => NONE)
blanchet@43131
   417
                        (nth us (length us - 2))
blanchet@43131
   418
              end
blanchet@44396
   419
            else if s' = type_guard_name then
blanchet@42551
   420
              @{const True} (* ignore type predicates *)
blanchet@42549
   421
            else
blanchet@42549
   422
              let
blanchet@44773
   423
                val new_skolem = String.isPrefix new_skolem_const_prefix s''
blanchet@42755
   424
                val num_ty_args =
blanchet@42755
   425
                  length us - the_default 0 (Symtab.lookup sym_tab s)
blanchet@42549
   426
                val (type_us, term_us) =
blanchet@42549
   427
                  chop num_ty_args us |>> append mangled_us
blanchet@43093
   428
                val term_ts = map (do_term [] NONE) term_us
blanchet@42549
   429
                val T =
blanchet@43183
   430
                  (if not (null type_us) andalso
blanchet@43183
   431
                      num_type_args thy s' = length type_us then
blanchet@43191
   432
                     let val Ts = type_us |> map (typ_from_atp ctxt) in
blanchet@43191
   433
                       if new_skolem then
blanchet@43191
   434
                         SOME (Type_Infer.paramify_vars (tl Ts ---> hd Ts))
blanchet@43200
   435
                       else if textual then
blanchet@43200
   436
                         try (Sign.const_instance thy) (s', Ts)
blanchet@43191
   437
                       else
blanchet@43200
   438
                         NONE
blanchet@43191
   439
                     end
blanchet@43183
   440
                   else
blanchet@43183
   441
                     NONE)
blanchet@43183
   442
                  |> (fn SOME T => T
blanchet@43183
   443
                       | NONE => map slack_fastype_of term_ts --->
blanchet@43183
   444
                                 (case opt_T of
blanchet@43183
   445
                                    SOME T => T
blanchet@43183
   446
                                  | NONE => HOLogic.typeT))
blanchet@43191
   447
                val t =
blanchet@43191
   448
                  if new_skolem then
blanchet@44773
   449
                    Var ((new_skolem_var_name_from_const s'', var_index), T)
blanchet@43191
   450
                  else
blanchet@43191
   451
                    Const (unproxify_const s', T)
blanchet@43191
   452
              in list_comb (t, term_ts @ extra_ts) end
blanchet@42549
   453
          end
blanchet@36909
   454
        | NONE => (* a free or schematic variable *)
blanchet@36909
   455
          let
blanchet@45042
   456
            val term_ts = map (do_term [] NONE) us
blanchet@45042
   457
            val ts = term_ts @ extra_ts
blanchet@45042
   458
            val T =
blanchet@45042
   459
              case opt_T of
blanchet@45042
   460
                SOME T => map slack_fastype_of term_ts ---> T
blanchet@45042
   461
              | NONE => map slack_fastype_of ts ---> HOLogic.typeT
blanchet@36909
   462
            val t =
blanchet@45511
   463
              case unprefix_and_unascii fixed_var_prefix s of
blanchet@45511
   464
                SOME s => Free (s, T)
blanchet@36909
   465
              | NONE =>
blanchet@45511
   466
                case unprefix_and_unascii schematic_var_prefix s of
blanchet@44773
   467
                  SOME s => Var ((s, var_index), T)
blanchet@36909
   468
                | NONE =>
blanchet@44773
   469
                  Var ((s |> textual ? repair_variable_name Char.toLower,
blanchet@43095
   470
                        var_index), T)
blanchet@36909
   471
          in list_comb (t, ts) end
blanchet@43093
   472
  in do_term [] end
paulson@21978
   473
blanchet@43135
   474
fun term_from_atom ctxt textual sym_tab pos (u as ATerm (s, _)) =
blanchet@38014
   475
  if String.isPrefix class_prefix s then
blanchet@43135
   476
    add_type_constraint pos (type_constraint_from_term ctxt u)
blanchet@38014
   477
    #> pair @{const True}
blanchet@38014
   478
  else
blanchet@43135
   479
    pair (term_from_atp ctxt textual sym_tab (SOME @{typ bool}) u)
blanchet@36402
   480
blanchet@36555
   481
val combinator_table =
blanchet@39953
   482
  [(@{const_name Meson.COMBI}, @{thm Meson.COMBI_def_raw}),
blanchet@39953
   483
   (@{const_name Meson.COMBK}, @{thm Meson.COMBK_def_raw}),
blanchet@39953
   484
   (@{const_name Meson.COMBB}, @{thm Meson.COMBB_def_raw}),
blanchet@39953
   485
   (@{const_name Meson.COMBC}, @{thm Meson.COMBC_def_raw}),
blanchet@39953
   486
   (@{const_name Meson.COMBS}, @{thm Meson.COMBS_def_raw})]
blanchet@36555
   487
blanchet@42761
   488
fun uncombine_term thy =
blanchet@42761
   489
  let
blanchet@42761
   490
    fun aux (t1 $ t2) = betapply (pairself aux (t1, t2))
blanchet@42761
   491
      | aux (Abs (s, T, t')) = Abs (s, T, aux t')
blanchet@42761
   492
      | aux (t as Const (x as (s, _))) =
blanchet@42761
   493
        (case AList.lookup (op =) combinator_table s of
blanchet@42761
   494
           SOME thm => thm |> prop_of |> specialize_type thy x
blanchet@42761
   495
                           |> Logic.dest_equals |> snd
blanchet@42761
   496
         | NONE => t)
blanchet@42761
   497
      | aux t = t
blanchet@42761
   498
  in aux end
blanchet@36555
   499
blanchet@37991
   500
(* Update schematic type variables with detected sort constraints. It's not
blanchet@42563
   501
   totally clear whether this code is necessary. *)
blanchet@38014
   502
fun repair_tvar_sorts (t, tvar_tab) =
blanchet@36909
   503
  let
blanchet@37991
   504
    fun do_type (Type (a, Ts)) = Type (a, map do_type Ts)
blanchet@37991
   505
      | do_type (TVar (xi, s)) =
blanchet@37991
   506
        TVar (xi, the_default s (Vartab.lookup tvar_tab xi))
blanchet@37991
   507
      | do_type (TFree z) = TFree z
blanchet@37991
   508
    fun do_term (Const (a, T)) = Const (a, do_type T)
blanchet@37991
   509
      | do_term (Free (a, T)) = Free (a, do_type T)
blanchet@37991
   510
      | do_term (Var (xi, T)) = Var (xi, do_type T)
blanchet@37991
   511
      | do_term (t as Bound _) = t
blanchet@37991
   512
      | do_term (Abs (a, T, t)) = Abs (a, do_type T, do_term t)
blanchet@37991
   513
      | do_term (t1 $ t2) = do_term t1 $ do_term t2
blanchet@37991
   514
  in t |> not (Vartab.is_empty tvar_tab) ? do_term end
blanchet@37991
   515
blanchet@39425
   516
fun quantify_over_var quant_of var_s t =
blanchet@39425
   517
  let
blanchet@39425
   518
    val vars = [] |> Term.add_vars t |> filter (fn ((s, _), _) => s = var_s)
blanchet@39425
   519
                  |> map Var
blanchet@39425
   520
  in fold_rev quant_of vars t end
blanchet@37991
   521
blanchet@38085
   522
(* Interpret an ATP formula as a HOL term, extracting sort constraints as they
blanchet@38085
   523
   appear in the formula. *)
blanchet@43184
   524
fun prop_from_atp ctxt textual sym_tab phi =
blanchet@38014
   525
  let
blanchet@38014
   526
    fun do_formula pos phi =
blanchet@37991
   527
      case phi of
blanchet@38014
   528
        AQuant (_, [], phi) => do_formula pos phi
blanchet@42526
   529
      | AQuant (q, (s, _) :: xs, phi') =>
blanchet@38014
   530
        do_formula pos (AQuant (q, xs, phi'))
blanchet@42526
   531
        (* FIXME: TFF *)
blanchet@39425
   532
        #>> quantify_over_var (case q of
blanchet@39425
   533
                                 AForall => forall_of
blanchet@39425
   534
                               | AExists => exists_of)
blanchet@43095
   535
                              (s |> textual ? repair_variable_name Char.toLower)
blanchet@38014
   536
      | AConn (ANot, [phi']) => do_formula (not pos) phi' #>> s_not
blanchet@37991
   537
      | AConn (c, [phi1, phi2]) =>
blanchet@38014
   538
        do_formula (pos |> c = AImplies ? not) phi1
blanchet@38014
   539
        ##>> do_formula pos phi2
blanchet@38014
   540
        #>> (case c of
blanchet@38014
   541
               AAnd => s_conj
blanchet@38014
   542
             | AOr => s_disj
blanchet@38014
   543
             | AImplies => s_imp
blanchet@38038
   544
             | AIff => s_iff
blanchet@43163
   545
             | ANot => raise Fail "impossible connective")
blanchet@43135
   546
      | AAtom tm => term_from_atom ctxt textual sym_tab pos tm
blanchet@37991
   547
      | _ => raise FORMULA [phi]
blanchet@38014
   548
  in repair_tvar_sorts (do_formula true phi Vartab.empty) end
blanchet@37991
   549
blanchet@43131
   550
fun infer_formula_types ctxt =
wenzelm@39288
   551
  Type.constraint HOLogic.boolT
blanchet@42761
   552
  #> Syntax.check_term
blanchet@42761
   553
         (Proof_Context.set_mode Proof_Context.mode_schematic ctxt)
paulson@21978
   554
blanchet@43184
   555
fun uncombined_etc_prop_from_atp ctxt textual sym_tab =
blanchet@43136
   556
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43184
   557
    prop_from_atp ctxt textual sym_tab
blanchet@43176
   558
    #> textual ? uncombine_term thy #> infer_formula_types ctxt
blanchet@43136
   559
  end
blanchet@43136
   560
blanchet@43093
   561
(**** Translation of TSTP files to Isar proofs ****)
paulson@21978
   562
blanchet@36486
   563
fun unvarify_term (Var ((s, 0), T)) = Free (s, T)
blanchet@36486
   564
  | unvarify_term t = raise TERM ("unvarify_term: non-Var", [t])
paulson@21978
   565
blanchet@43135
   566
fun decode_line sym_tab (Definition (name, phi1, phi2)) ctxt =
blanchet@36486
   567
    let
wenzelm@42361
   568
      val thy = Proof_Context.theory_of ctxt
blanchet@43184
   569
      val t1 = prop_from_atp ctxt true sym_tab phi1
blanchet@36551
   570
      val vars = snd (strip_comb t1)
blanchet@36486
   571
      val frees = map unvarify_term vars
blanchet@36486
   572
      val unvarify_args = subst_atomic (vars ~~ frees)
blanchet@43184
   573
      val t2 = prop_from_atp ctxt true sym_tab phi2
blanchet@36551
   574
      val (t1, t2) =
blanchet@36551
   575
        HOLogic.eq_const HOLogic.typeT $ t1 $ t2
blanchet@43131
   576
        |> unvarify_args |> uncombine_term thy |> infer_formula_types ctxt
blanchet@36555
   577
        |> HOLogic.dest_eq
blanchet@36486
   578
    in
blanchet@39368
   579
      (Definition (name, t1, t2),
wenzelm@44121
   580
       fold Variable.declare_term (maps Misc_Legacy.term_frees [t1, t2]) ctxt)
blanchet@36486
   581
    end
blanchet@45209
   582
  | decode_line sym_tab (Inference (name, u, rule, deps)) ctxt =
blanchet@43184
   583
    let val t = u |> uncombined_etc_prop_from_atp ctxt true sym_tab in
blanchet@45209
   584
      (Inference (name, t, rule, deps),
wenzelm@44121
   585
       fold Variable.declare_term (Misc_Legacy.term_frees t) ctxt)
blanchet@36486
   586
    end
blanchet@43135
   587
fun decode_lines ctxt sym_tab lines =
blanchet@43135
   588
  fst (fold_map (decode_line sym_tab) lines ctxt)
paulson@21978
   589
blanchet@38035
   590
fun is_same_inference _ (Definition _) = false
blanchet@45209
   591
  | is_same_inference t (Inference (_, t', _, _)) = t aconv t'
blanchet@36486
   592
blanchet@36486
   593
(* No "real" literals means only type information (tfree_tcs, clsrel, or
blanchet@36486
   594
   clsarity). *)
wenzelm@45740
   595
val is_only_type_information = curry (op aconv) @{term True}
blanchet@36486
   596
blanchet@39373
   597
fun replace_one_dependency (old, new) dep =
blanchet@42968
   598
  if is_same_atp_step dep old then new else [dep]
blanchet@39373
   599
fun replace_dependencies_in_line _ (line as Definition _) = line
blanchet@45209
   600
  | replace_dependencies_in_line p (Inference (name, t, rule, deps)) =
blanchet@45209
   601
    Inference (name, t, rule,
blanchet@45209
   602
               fold (union (op =) o replace_one_dependency p) deps [])
paulson@21978
   603
blanchet@40204
   604
(* Discard facts; consolidate adjacent lines that prove the same formula, since
blanchet@38085
   605
   they differ only in type information.*)
blanchet@45551
   606
fun add_line _ (line as Definition _) lines = line :: lines
blanchet@45552
   607
  | add_line fact_names (Inference (name as (_, ss), t, rule, [])) lines =
blanchet@40204
   608
    (* No dependencies: fact, conjecture, or (for Vampire) internal facts or
blanchet@38085
   609
       definitions. *)
blanchet@45552
   610
    if is_fact fact_names ss then
blanchet@40204
   611
      (* Facts are not proof lines. *)
blanchet@36486
   612
      if is_only_type_information t then
blanchet@39373
   613
        map (replace_dependencies_in_line (name, [])) lines
blanchet@36486
   614
      (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   615
      else case take_prefix (not o is_same_inference t) lines of
blanchet@39373
   616
        (_, []) => lines (* no repetition of proof line *)
blanchet@45209
   617
      | (pre, Inference (name', _, _, _) :: post) =>
blanchet@39373
   618
        pre @ map (replace_dependencies_in_line (name', [name])) post
blanchet@40069
   619
      | _ => raise Fail "unexpected inference"
blanchet@45552
   620
    else if is_conjecture ss then
blanchet@45209
   621
      Inference (name, s_not t, rule, []) :: lines
blanchet@36551
   622
    else
blanchet@39373
   623
      map (replace_dependencies_in_line (name, [])) lines
blanchet@45551
   624
  | add_line _ (Inference (name, t, rule, deps)) lines =
blanchet@36486
   625
    (* Type information will be deleted later; skip repetition test. *)
blanchet@36486
   626
    if is_only_type_information t then
blanchet@45209
   627
      Inference (name, t, rule, deps) :: lines
blanchet@36486
   628
    (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@38035
   629
    else case take_prefix (not o is_same_inference t) lines of
blanchet@36486
   630
      (* FIXME: Doesn't this code risk conflating proofs involving different
blanchet@38035
   631
         types? *)
blanchet@45209
   632
       (_, []) => Inference (name, t, rule, deps) :: lines
blanchet@45209
   633
     | (pre, Inference (name', t', rule, _) :: post) =>
blanchet@45209
   634
       Inference (name, t', rule, deps) ::
blanchet@39373
   635
       pre @ map (replace_dependencies_in_line (name', [name])) post
blanchet@40069
   636
     | _ => raise Fail "unexpected inference"
paulson@22044
   637
blanchet@36486
   638
(* Recursively delete empty lines (type information) from the proof. *)
blanchet@45209
   639
fun add_nontrivial_line (line as Inference (name, t, _, [])) lines =
blanchet@39373
   640
    if is_only_type_information t then delete_dependency name lines
blanchet@45209
   641
    else line :: lines
blanchet@36486
   642
  | add_nontrivial_line line lines = line :: lines
blanchet@39373
   643
and delete_dependency name lines =
blanchet@39373
   644
  fold_rev add_nontrivial_line
blanchet@39373
   645
           (map (replace_dependencies_in_line (name, [])) lines) []
blanchet@36486
   646
blanchet@37323
   647
(* ATPs sometimes reuse free variable names in the strangest ways. Removing
blanchet@37323
   648
   offending lines often does the trick. *)
blanchet@36560
   649
fun is_bad_free frees (Free x) = not (member (op =) frees x)
blanchet@36560
   650
  | is_bad_free _ _ = false
paulson@22470
   651
blanchet@45551
   652
fun add_desired_line _ _ _ (line as Definition (name, _, _)) (j, lines) =
blanchet@39373
   653
    (j, line :: map (replace_dependencies_in_line (name, [])) lines)
blanchet@45551
   654
  | add_desired_line isar_shrink_factor fact_names frees
blanchet@45552
   655
                     (Inference (name as (_, ss), t, rule, deps)) (j, lines) =
blanchet@36402
   656
    (j + 1,
blanchet@45552
   657
     if is_fact fact_names ss orelse
blanchet@45552
   658
        is_conjecture ss orelse
blanchet@39373
   659
        (* the last line must be kept *)
blanchet@39373
   660
        j = 0 orelse
blanchet@36570
   661
        (not (is_only_type_information t) andalso
blanchet@36570
   662
         null (Term.add_tvars t []) andalso
blanchet@36570
   663
         not (exists_subterm (is_bad_free frees) t) andalso
blanchet@39373
   664
         length deps >= 2 andalso j mod isar_shrink_factor = 0 andalso
blanchet@39373
   665
         (* kill next to last line, which usually results in a trivial step *)
blanchet@39373
   666
         j <> 1) then
blanchet@45209
   667
       Inference (name, t, rule, deps) :: lines  (* keep line *)
blanchet@36402
   668
     else
blanchet@39373
   669
       map (replace_dependencies_in_line (name, deps)) lines)  (* drop line *)
paulson@21978
   670
blanchet@36486
   671
(** Isar proof construction and manipulation **)
blanchet@36486
   672
blanchet@36402
   673
type label = string * int
blanchet@36402
   674
type facts = label list * string list
blanchet@36402
   675
blanchet@39452
   676
datatype isar_qualifier = Show | Then | Moreover | Ultimately
blanchet@36291
   677
blanchet@39452
   678
datatype isar_step =
blanchet@36478
   679
  Fix of (string * typ) list |
blanchet@36486
   680
  Let of term * term |
blanchet@36402
   681
  Assume of label * term |
blanchet@45882
   682
  Prove of isar_qualifier list * label * term * byline
blanchet@36402
   683
and byline =
blanchet@45882
   684
  By_Metis of facts |
blanchet@45882
   685
  Case_Split of isar_step list list * facts
blanchet@36402
   686
blanchet@45552
   687
fun add_fact_from_dependency fact_names (name as (_, ss)) =
blanchet@45552
   688
  if is_fact fact_names ss then
blanchet@45552
   689
    apsnd (union (op =) (map fst (resolve_fact fact_names ss)))
blanchet@36475
   690
  else
blanchet@45551
   691
    apfst (insert (op =) (raw_label_for_name name))
blanchet@36402
   692
blanchet@39454
   693
fun repair_name "$true" = "c_True"
blanchet@39454
   694
  | repair_name "$false" = "c_False"
blanchet@43000
   695
  | repair_name "$$e" = tptp_equal (* seen in Vampire proofs *)
blanchet@39454
   696
  | repair_name s =
blanchet@43000
   697
    if is_tptp_equal s orelse
blanchet@43000
   698
       (* seen in Vampire proofs *)
blanchet@43000
   699
       (String.isPrefix "sQ" s andalso String.isSuffix "_eqProxy" s) then
blanchet@43000
   700
      tptp_equal
blanchet@39454
   701
    else
blanchet@39454
   702
      s
blanchet@39454
   703
blanchet@45883
   704
(* FIXME: Still needed? Try with SPASS proofs perhaps. *)
blanchet@36402
   705
val kill_duplicate_assumptions_in_proof =
blanchet@36402
   706
  let
blanchet@36402
   707
    fun relabel_facts subst =
blanchet@36402
   708
      apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
blanchet@36491
   709
    fun do_step (step as Assume (l, t)) (proof, subst, assums) =
blanchet@36402
   710
        (case AList.lookup (op aconv) assums t of
blanchet@36967
   711
           SOME l' => (proof, (l, l') :: subst, assums)
blanchet@36491
   712
         | NONE => (step :: proof, subst, (t, l) :: assums))
blanchet@45882
   713
      | do_step (Prove (qs, l, t, by)) (proof, subst, assums) =
blanchet@45882
   714
        (Prove (qs, l, t,
blanchet@45882
   715
                case by of
blanchet@45882
   716
                  By_Metis facts => By_Metis (relabel_facts subst facts)
blanchet@45882
   717
                | Case_Split (proofs, facts) =>
blanchet@45882
   718
                  Case_Split (map do_proof proofs,
blanchet@45882
   719
                              relabel_facts subst facts)) ::
blanchet@36402
   720
         proof, subst, assums)
blanchet@36491
   721
      | do_step step (proof, subst, assums) = (step :: proof, subst, assums)
blanchet@36402
   722
    and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
blanchet@36402
   723
  in do_proof end
blanchet@36402
   724
blanchet@45883
   725
fun used_labels_of_step (Prove (_, _, _, by)) =
blanchet@45883
   726
    (case by of
blanchet@45883
   727
       By_Metis (ls, _) => ls
blanchet@45883
   728
     | Case_Split (proofs, (ls, _)) =>
blanchet@45883
   729
       fold (union (op =) o used_labels_of) proofs ls)
blanchet@45883
   730
  | used_labels_of_step _ = []
blanchet@45883
   731
and used_labels_of proof = fold (union (op =) o used_labels_of_step) proof []
blanchet@36402
   732
blanchet@36402
   733
fun kill_useless_labels_in_proof proof =
blanchet@36402
   734
  let
blanchet@36556
   735
    val used_ls = used_labels_of proof
blanchet@36402
   736
    fun do_label l = if member (op =) used_ls l then l else no_label
blanchet@36556
   737
    fun do_step (Assume (l, t)) = Assume (do_label l, t)
blanchet@45882
   738
      | do_step (Prove (qs, l, t, by)) =
blanchet@45882
   739
        Prove (qs, do_label l, t,
blanchet@45882
   740
               case by of
blanchet@45882
   741
                 Case_Split (proofs, facts) =>
blanchet@45882
   742
                 Case_Split (map (map do_step) proofs, facts)
blanchet@45882
   743
               | _ => by)
blanchet@36556
   744
      | do_step step = step
blanchet@36556
   745
  in map do_step proof end
blanchet@36402
   746
blanchet@36402
   747
fun prefix_for_depth n = replicate_string (n + 1)
blanchet@36402
   748
blanchet@36402
   749
val relabel_proof =
blanchet@36402
   750
  let
blanchet@36402
   751
    fun aux _ _ _ [] = []
blanchet@36402
   752
      | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
blanchet@36402
   753
        if l = no_label then
blanchet@36402
   754
          Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   755
        else
blanchet@36402
   756
          let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
blanchet@36402
   757
            Assume (l', t) ::
blanchet@36402
   758
            aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
blanchet@36402
   759
          end
blanchet@45882
   760
      | aux subst depth (next_assum, next_fact)
blanchet@45882
   761
            (Prove (qs, l, t, by) :: proof) =
blanchet@36402
   762
        let
blanchet@36402
   763
          val (l', subst, next_fact) =
blanchet@36402
   764
            if l = no_label then
blanchet@36402
   765
              (l, subst, next_fact)
blanchet@36402
   766
            else
blanchet@36402
   767
              let
blanchet@42180
   768
                val l' = (prefix_for_depth depth have_prefix, next_fact)
blanchet@36402
   769
              in (l', (l, l') :: subst, next_fact + 1) end
blanchet@36570
   770
          val relabel_facts =
blanchet@39370
   771
            apfst (maps (the_list o AList.lookup (op =) subst))
blanchet@36402
   772
          val by =
blanchet@36402
   773
            case by of
blanchet@45882
   774
              By_Metis facts => By_Metis (relabel_facts facts)
blanchet@45882
   775
            | Case_Split (proofs, facts) =>
blanchet@45882
   776
              Case_Split (map (aux subst (depth + 1) (1, 1)) proofs,
blanchet@45882
   777
                          relabel_facts facts)
blanchet@36402
   778
        in
blanchet@45882
   779
          Prove (qs, l', t, by) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   780
        end
blanchet@36491
   781
      | aux subst depth nextp (step :: proof) =
blanchet@36491
   782
        step :: aux subst depth nextp proof
blanchet@36402
   783
  in aux [] 0 (1, 1) end
blanchet@36402
   784
blanchet@45554
   785
fun string_for_proof ctxt0 type_enc lam_trans i n =
blanchet@36402
   786
  let
blanchet@42761
   787
    val ctxt =
blanchet@42761
   788
      ctxt0 |> Config.put show_free_types false
blanchet@42761
   789
            |> Config.put show_types true
blanchet@42761
   790
            |> Config.put show_sorts true
blanchet@37319
   791
    fun fix_print_mode f x =
wenzelm@39134
   792
      Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
wenzelm@39134
   793
                               (print_mode_value ())) f x
blanchet@36402
   794
    fun do_indent ind = replicate_string (ind * indent_size) " "
blanchet@36478
   795
    fun do_free (s, T) =
blanchet@36478
   796
      maybe_quote s ^ " :: " ^
blanchet@36478
   797
      maybe_quote (fix_print_mode (Syntax.string_of_typ ctxt) T)
blanchet@36570
   798
    fun do_label l = if l = no_label then "" else string_for_label l ^ ": "
blanchet@36402
   799
    fun do_have qs =
blanchet@36402
   800
      (if member (op =) qs Moreover then "moreover " else "") ^
blanchet@36402
   801
      (if member (op =) qs Ultimately then "ultimately " else "") ^
blanchet@36402
   802
      (if member (op =) qs Then then
blanchet@36402
   803
         if member (op =) qs Show then "thus" else "hence"
blanchet@36402
   804
       else
blanchet@36402
   805
         if member (op =) qs Show then "show" else "have")
blanchet@36478
   806
    val do_term = maybe_quote o fix_print_mode (Syntax.string_of_term ctxt)
blanchet@45554
   807
    val reconstr = Metis (type_enc, lam_trans)
blanchet@36570
   808
    fun do_facts (ls, ss) =
blanchet@45520
   809
      reconstructor_command reconstr 1 1
blanchet@43033
   810
          (ls |> sort_distinct (prod_ord string_ord int_ord),
blanchet@43033
   811
           ss |> sort_distinct string_ord)
blanchet@36478
   812
    and do_step ind (Fix xs) =
blanchet@36478
   813
        do_indent ind ^ "fix " ^ space_implode " and " (map do_free xs) ^ "\n"
blanchet@36486
   814
      | do_step ind (Let (t1, t2)) =
blanchet@36486
   815
        do_indent ind ^ "let " ^ do_term t1 ^ " = " ^ do_term t2 ^ "\n"
blanchet@36402
   816
      | do_step ind (Assume (l, t)) =
blanchet@36402
   817
        do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
blanchet@45882
   818
      | do_step ind (Prove (qs, l, t, By_Metis facts)) =
blanchet@36402
   819
        do_indent ind ^ do_have qs ^ " " ^
blanchet@36479
   820
        do_label l ^ do_term t ^ " " ^ do_facts facts ^ "\n"
blanchet@45882
   821
      | do_step ind (Prove (qs, l, t, Case_Split (proofs, facts))) =
blanchet@45882
   822
        implode (map (prefix (do_indent ind ^ "moreover\n") o do_block ind)
blanchet@45882
   823
                     proofs) ^
blanchet@36479
   824
        do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ " " ^
blanchet@36478
   825
        do_facts facts ^ "\n"
blanchet@36402
   826
    and do_steps prefix suffix ind steps =
blanchet@36402
   827
      let val s = implode (map (do_step ind) steps) in
blanchet@36402
   828
        replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
blanchet@36402
   829
        String.extract (s, ind * indent_size,
blanchet@36402
   830
                        SOME (size s - ind * indent_size - 1)) ^
blanchet@36402
   831
        suffix ^ "\n"
blanchet@36402
   832
      end
blanchet@36402
   833
    and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
blanchet@36564
   834
    (* One-step proofs are pointless; better use the Metis one-liner
blanchet@36564
   835
       directly. *)
blanchet@45882
   836
    and do_proof [Prove (_, _, _, By_Metis _)] = ""
blanchet@36564
   837
      | do_proof proof =
blanchet@36480
   838
        (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
blanchet@39452
   839
        do_indent 0 ^ "proof -\n" ^ do_steps "" "" 1 proof ^ do_indent 0 ^
blanchet@39452
   840
        (if n <> 1 then "next" else "qed")
blanchet@36488
   841
  in do_proof end
blanchet@36402
   842
blanchet@43062
   843
fun isar_proof_text ctxt isar_proof_requested
blanchet@45552
   844
        (debug, isar_shrink_factor, pool, fact_names, sym_tab, atp_proof, goal)
blanchet@43037
   845
        (one_line_params as (_, _, _, _, subgoal, subgoal_count)) =
blanchet@36402
   846
  let
blanchet@43062
   847
    val isar_shrink_factor =
blanchet@43062
   848
      (if isar_proof_requested then 1 else 2) * isar_shrink_factor
blanchet@43037
   849
    val (params, hyp_ts, concl_t) = strip_subgoal ctxt goal subgoal
blanchet@36909
   850
    val frees = fold Term.add_frees (concl_t :: hyp_ts) []
blanchet@43033
   851
    val one_line_proof = one_line_proof_text one_line_params
blanchet@45554
   852
    val type_enc =
blanchet@45590
   853
      if is_typed_helper_used_in_atp_proof atp_proof then full_typesN
blanchet@45554
   854
      else partial_typesN
blanchet@45554
   855
    val lam_trans = lam_trans_from_atp_proof atp_proof metis_default_lam_trans
blanchet@45882
   856
blanchet@45883
   857
    fun isar_proof_of () =
blanchet@45883
   858
      let
blanchet@45883
   859
        val atp_proof =
blanchet@45883
   860
          atp_proof
blanchet@45883
   861
          |> clean_up_atp_proof_dependencies
blanchet@45883
   862
          |> nasty_atp_proof pool
blanchet@45883
   863
          |> map_term_names_in_atp_proof repair_name
blanchet@45883
   864
          |> decode_lines ctxt sym_tab
blanchet@45883
   865
          |> rpair [] |-> fold_rev (add_line fact_names)
blanchet@45883
   866
          |> rpair [] |-> fold_rev add_nontrivial_line
blanchet@45883
   867
          |> rpair (0, [])
blanchet@45883
   868
          |-> fold_rev (add_desired_line isar_shrink_factor fact_names frees)
blanchet@45883
   869
          |> snd
blanchet@45883
   870
        val conj_name = conjecture_prefix ^ string_of_int (length hyp_ts)
blanchet@45883
   871
        val conjs =
blanchet@45883
   872
          atp_proof
blanchet@45883
   873
          |> map_filter (fn Inference (name as (_, ss), _, _, []) =>
blanchet@45883
   874
                            if member (op =) ss conj_name then SOME name else NONE
blanchet@45883
   875
                          | _ => NONE)
blanchet@45883
   876
        fun dep_of_step (Definition _) = NONE
blanchet@45883
   877
          | dep_of_step (Inference (name, _, _, from)) = SOME (from, name)
blanchet@45883
   878
        val ref_graph = atp_proof |> map_filter dep_of_step |> make_ref_graph
blanchet@45883
   879
        val axioms = axioms_of_ref_graph ref_graph conjs
blanchet@45883
   880
        val tainted = tainted_atoms_of_ref_graph ref_graph conjs
blanchet@45883
   881
        val props =
blanchet@45883
   882
          Symtab.empty
blanchet@45883
   883
          |> fold (fn Definition _ => I (* FIXME *)
blanchet@45883
   884
                    | Inference ((s, _), t, _, _) =>
blanchet@45883
   885
                      Symtab.update_new (s,
blanchet@45883
   886
                          t |> member (op = o apsnd fst) tainted s ? s_not))
blanchet@45883
   887
                  atp_proof
blanchet@45883
   888
        (* FIXME: add "fold_rev forall_of (map Var (Term.add_vars t []))"? *)
blanchet@45883
   889
        fun prop_of_clause c =
blanchet@45883
   890
          fold (curry s_disj) (map_filter (Symtab.lookup props o fst) c)
blanchet@45883
   891
               @{term False}
blanchet@45883
   892
        fun label_of_clause c = (space_implode "___" (map fst c), 0)
blanchet@45883
   893
        fun maybe_show outer c =
blanchet@45883
   894
          (outer andalso length c = 1 andalso subset (op =) (c, conjs))
blanchet@45883
   895
          ? cons Show
blanchet@45883
   896
        fun do_have outer qs (gamma, c) =
blanchet@45883
   897
          Prove (maybe_show outer c qs, label_of_clause c, prop_of_clause c,
blanchet@45883
   898
                 By_Metis (fold (add_fact_from_dependency fact_names
blanchet@45883
   899
                                 o the_single) gamma ([], [])))
blanchet@45883
   900
        fun do_inf outer (Have z) = do_have outer [] z
blanchet@45883
   901
          | do_inf outer (Hence z) = do_have outer [Then] z
blanchet@45883
   902
          | do_inf outer (Cases cases) =
blanchet@45883
   903
            let val c = succedent_of_cases cases in
blanchet@45883
   904
              Prove (maybe_show outer c [Ultimately], label_of_clause c,
blanchet@45883
   905
                     prop_of_clause c,
blanchet@45883
   906
                     Case_Split (map (do_case false) cases, ([], [])))
blanchet@45883
   907
            end
blanchet@45883
   908
        and do_case outer (c, infs) =
blanchet@45883
   909
          Assume (label_of_clause c, prop_of_clause c) ::
blanchet@45883
   910
          map (do_inf outer) infs
blanchet@45883
   911
        val isar_proof =
blanchet@45883
   912
          (if null params then [] else [Fix params]) @
blanchet@45883
   913
          (ref_graph
blanchet@45883
   914
           |> redirect_graph axioms tainted
blanchet@45883
   915
           |> chain_direct_proof
blanchet@45883
   916
           |> map (do_inf true)
blanchet@36402
   917
           |> kill_duplicate_assumptions_in_proof
blanchet@36402
   918
           |> kill_useless_labels_in_proof
blanchet@45883
   919
           |> relabel_proof)
blanchet@45883
   920
          |> string_for_proof ctxt type_enc lam_trans subgoal subgoal_count
blanchet@45883
   921
      in
blanchet@45883
   922
        case isar_proof of
blanchet@45883
   923
          "" =>
blanchet@45883
   924
          if isar_proof_requested then
blanchet@45883
   925
            "\nNo structured proof available (proof too short)."
blanchet@45883
   926
          else
blanchet@45883
   927
            ""
blanchet@45883
   928
        | _ =>
blanchet@45883
   929
          "\n\n" ^ (if isar_proof_requested then "Structured proof"
blanchet@45883
   930
                    else "Perhaps this will work") ^
blanchet@45883
   931
          ":\n" ^ Markup.markup Isabelle_Markup.sendback isar_proof
blanchet@45883
   932
      end
blanchet@35868
   933
    val isar_proof =
blanchet@36402
   934
      if debug then
blanchet@45883
   935
        isar_proof_of ()
blanchet@45883
   936
      else case try isar_proof_of () of
blanchet@45882
   937
        SOME s => s
blanchet@45882
   938
      | NONE => if isar_proof_requested then
blanchet@45882
   939
                  "\nWarning: The Isar proof construction failed."
blanchet@45882
   940
                else
blanchet@45882
   941
                  ""
blanchet@43033
   942
  in one_line_proof ^ isar_proof end
paulson@21978
   943
blanchet@43033
   944
fun proof_text ctxt isar_proof isar_params
blanchet@43033
   945
               (one_line_params as (preplay, _, _, _, _, _)) =
blanchet@43166
   946
  (if case preplay of Failed_to_Play _ => true | _ => isar_proof then
blanchet@43062
   947
     isar_proof_text ctxt isar_proof isar_params
blanchet@43033
   948
   else
blanchet@43033
   949
     one_line_proof_text) one_line_params
blanchet@36223
   950
immler@31038
   951
end;