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