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