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