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