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