src/HOL/Tools/Sledgehammer/sledgehammer_proof_reconstruct.ML
author krauss
Sat May 01 20:49:39 2010 +0200 (2010-05-01)
changeset 36606 5479681ab465
parent 36605 6f11c9b1fb3e
child 36607 e5f7235f39c5
permissions -rw-r--r--
Backed out changeset 6f11c9b1fb3e (breaks compilation of HOL image)
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_proof_reconstruct.ML
wenzelm@33310
     2
    Author:     Lawrence C Paulson and Claire Quigley, Cambridge University Computer Laboratory
blanchet@36392
     3
    Author:     Jasmin Blanchette, TU Muenchen
paulson@21978
     4
wenzelm@33310
     5
Transfer of proofs from external provers.
wenzelm@33310
     6
*)
wenzelm@33310
     7
blanchet@35826
     8
signature SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@24425
     9
sig
blanchet@36281
    10
  type minimize_command = string list -> string
blanchet@36393
    11
  type name_pool = Sledgehammer_FOL_Clause.name_pool
blanchet@36281
    12
paulson@25492
    13
  val chained_hint: string
paulson@24425
    14
  val invert_const: string -> string
paulson@24425
    15
  val invert_type_const: string -> string
krauss@36606
    16
  val num_typargs: theory -> string -> int
paulson@24425
    17
  val make_tvar: string -> typ
paulson@24425
    18
  val strip_prefix: string -> string -> string option
blanchet@36063
    19
  val metis_line: int -> int -> string list -> string
blanchet@36223
    20
  val metis_proof_text:
blanchet@36287
    21
    minimize_command * string * string vector * thm * int
blanchet@36281
    22
    -> string * string list
blanchet@36223
    23
  val isar_proof_text:
krauss@36606
    24
    name_pool option * bool * int * Proof.context * int list list
blanchet@36287
    25
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    26
    -> string * string list
blanchet@36223
    27
  val proof_text:
krauss@36606
    28
    bool -> name_pool option * bool * int * Proof.context * int list list
blanchet@36287
    29
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    30
    -> string * string list
paulson@24425
    31
end;
paulson@21978
    32
blanchet@35826
    33
structure Sledgehammer_Proof_Reconstruct : SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@21978
    34
struct
paulson@21978
    35
blanchet@36478
    36
open Sledgehammer_Util
blanchet@35865
    37
open Sledgehammer_FOL_Clause
blanchet@35865
    38
open Sledgehammer_Fact_Preprocessor
paulson@21978
    39
blanchet@36281
    40
type minimize_command = string list -> string
blanchet@36281
    41
blanchet@36291
    42
fun is_ident_char c = Char.isAlphaNum c orelse c = #"_"
blanchet@36392
    43
fun is_head_digit s = Char.isDigit (String.sub (s, 0))
blanchet@36291
    44
blanchet@36551
    45
(* Hack: Could return false positives (e.g., a user happens to declare a
blanchet@36551
    46
   constant called "SomeTheory.sko_means_shoe_in_$wedish". *)
blanchet@36551
    47
val is_skolem_const_name =
blanchet@36551
    48
  Long_Name.base_name
blanchet@36551
    49
  #> String.isPrefix skolem_prefix andf String.isSubstring skolem_infix
blanchet@36551
    50
blanchet@36570
    51
val index_in_shape = find_index o exists o curry (op =)
blanchet@36402
    52
fun is_axiom_clause_number thm_names num = num <= Vector.length thm_names
blanchet@36570
    53
fun is_conjecture_clause_number conjecture_shape num =
blanchet@36570
    54
  index_in_shape num conjecture_shape >= 0
blanchet@36291
    55
blanchet@36393
    56
fun ugly_name NONE s = s
blanchet@36393
    57
  | ugly_name (SOME the_pool) s =
blanchet@36393
    58
    case Symtab.lookup (snd the_pool) s of
blanchet@36393
    59
      SOME s' => s'
blanchet@36393
    60
    | NONE => s
blanchet@36393
    61
blanchet@36491
    62
fun smart_lambda v t =
blanchet@36551
    63
  Abs (case v of
blanchet@36551
    64
         Const (s, _) =>
blanchet@36551
    65
         List.last (space_explode skolem_infix (Long_Name.base_name s))
blanchet@36551
    66
       | Var ((s, _), _) => s
blanchet@36551
    67
       | Free (s, _) => s
blanchet@36551
    68
       | _ => "", fastype_of v, abstract_over (v, t))
blanchet@36491
    69
fun forall_of v t = HOLogic.all_const (fastype_of v) $ smart_lambda v t
blanchet@36491
    70
blanchet@36491
    71
datatype ('a, 'b, 'c, 'd, 'e) raw_step =
blanchet@36491
    72
  Definition of 'a * 'b * 'c |
blanchet@36491
    73
  Inference of 'a * 'd * 'e list
blanchet@36491
    74
paulson@21978
    75
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    76
blanchet@36548
    77
fun strip_spaces_in_list [] = ""
blanchet@36548
    78
  | strip_spaces_in_list [c1] = if Char.isSpace c1 then "" else str c1
blanchet@36548
    79
  | strip_spaces_in_list [c1, c2] =
blanchet@36548
    80
    strip_spaces_in_list [c1] ^ strip_spaces_in_list [c2]
blanchet@36548
    81
  | strip_spaces_in_list (c1 :: c2 :: c3 :: cs) =
blanchet@36548
    82
    if Char.isSpace c1 then
blanchet@36548
    83
      strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36548
    84
    else if Char.isSpace c2 then
blanchet@36548
    85
      if Char.isSpace c3 then
blanchet@36548
    86
        strip_spaces_in_list (c1 :: c3 :: cs)
blanchet@36548
    87
      else
blanchet@36548
    88
        str c1 ^ (if forall is_ident_char [c1, c3] then " " else "") ^
blanchet@36548
    89
        strip_spaces_in_list (c3 :: cs)
blanchet@36548
    90
    else
blanchet@36548
    91
      str c1 ^ strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36548
    92
val strip_spaces = strip_spaces_in_list o String.explode
blanchet@36548
    93
blanchet@36291
    94
(* Syntax trees, either term list or formulae *)
blanchet@36486
    95
datatype node = IntLeaf of int | StrNode of string * node list
paulson@21978
    96
blanchet@36548
    97
fun str_leaf s = StrNode (s, [])
paulson@21978
    98
blanchet@36486
    99
fun scons (x, y) = StrNode ("cons", [x, y])
blanchet@36548
   100
val slist_of = List.foldl scons (str_leaf "nil")
paulson@21978
   101
paulson@21978
   102
(*Strings enclosed in single quotes, e.g. filenames*)
blanchet@36392
   103
val parse_quoted = $$ "'" |-- Scan.repeat (~$$ "'") --| $$ "'" >> implode;
paulson@21978
   104
paulson@21978
   105
(*Integer constants, typically proof line numbers*)
blanchet@36392
   106
val parse_integer = Scan.many1 is_head_digit >> (the o Int.fromString o implode)
paulson@21978
   107
blanchet@36548
   108
val parse_dollar_name =
blanchet@36548
   109
  Scan.repeat ($$ "$") -- Symbol.scan_id >> (fn (ss, s) => implode ss ^ s)
blanchet@36548
   110
blanchet@36369
   111
(* needed for SPASS's output format *)
blanchet@36548
   112
fun repair_name _ "$true" = "c_True"
blanchet@36548
   113
  | repair_name _ "$false" = "c_False"
blanchet@36559
   114
  | repair_name _ "$$e" = "c_equal" (* seen in Vampire 11 proofs *)
blanchet@36548
   115
  | repair_name _ "equal" = "c_equal" (* probably not needed *)
blanchet@36393
   116
  | repair_name pool s = ugly_name pool s
blanchet@36392
   117
(* Generalized first-order terms, which include file names, numbers, etc. *)
blanchet@36393
   118
(* The "x" argument is not strictly necessary, but without it Poly/ML loops
blanchet@36393
   119
   forever at compile time. *)
blanchet@36393
   120
fun parse_term pool x =
blanchet@36548
   121
     (parse_quoted >> str_leaf
blanchet@36486
   122
   || parse_integer >> IntLeaf
blanchet@36548
   123
   || (parse_dollar_name >> repair_name pool)
blanchet@36486
   124
      -- Scan.optional ($$ "(" |-- parse_terms pool --| $$ ")") [] >> StrNode
blanchet@36393
   125
   || $$ "(" |-- parse_term pool --| $$ ")"
blanchet@36393
   126
   || $$ "[" |-- Scan.optional (parse_terms pool) [] --| $$ "]" >> slist_of) x
blanchet@36393
   127
and parse_terms pool x =
blanchet@36393
   128
  (parse_term pool ::: Scan.repeat ($$ "," |-- parse_term pool)) x
paulson@21978
   129
blanchet@36486
   130
fun negate_node u = StrNode ("c_Not", [u])
blanchet@36486
   131
fun equate_nodes u1 u2 = StrNode ("c_equal", [u1, u2])
paulson@21978
   132
blanchet@36392
   133
(* Apply equal or not-equal to a term. *)
blanchet@36486
   134
fun repair_predicate_term (u, NONE) = u
blanchet@36486
   135
  | repair_predicate_term (u1, SOME (NONE, u2)) = equate_nodes u1 u2
blanchet@36486
   136
  | repair_predicate_term (u1, SOME (SOME _, u2)) =
blanchet@36486
   137
    negate_node (equate_nodes u1 u2)
blanchet@36393
   138
fun parse_predicate_term pool =
blanchet@36393
   139
  parse_term pool -- Scan.option (Scan.option ($$ "!") --| $$ "="
blanchet@36393
   140
                                  -- parse_term pool)
blanchet@36393
   141
  >> repair_predicate_term
blanchet@36393
   142
fun parse_literal pool x =
blanchet@36486
   143
  ($$ "~" |-- parse_literal pool >> negate_node || parse_predicate_term pool) x
blanchet@36393
   144
fun parse_literals pool =
blanchet@36393
   145
  parse_literal pool ::: Scan.repeat ($$ "|" |-- parse_literal pool)
blanchet@36548
   146
fun parse_parenthesized_literals pool =
blanchet@36548
   147
  $$ "(" |-- parse_literals pool --| $$ ")" || parse_literals pool
blanchet@36393
   148
fun parse_clause pool =
blanchet@36548
   149
  parse_parenthesized_literals pool
blanchet@36548
   150
    ::: Scan.repeat ($$ "|" |-- parse_parenthesized_literals pool)
blanchet@36548
   151
  >> List.concat
blanchet@36291
   152
blanchet@36486
   153
fun ints_of_node (IntLeaf n) = cons n
blanchet@36486
   154
  | ints_of_node (StrNode (_, us)) = fold ints_of_node us
blanchet@36392
   155
val parse_tstp_annotations =
blanchet@36393
   156
  Scan.optional ($$ "," |-- parse_term NONE
blanchet@36393
   157
                   --| Scan.option ($$ "," |-- parse_terms NONE)
blanchet@36486
   158
                 >> (fn source => ints_of_node source [])) []
blanchet@36486
   159
blanchet@36486
   160
fun parse_definition pool =
blanchet@36486
   161
  $$ "(" |-- parse_literal NONE --| Scan.this_string "<=>"
blanchet@36486
   162
  -- parse_clause pool --| $$ ")"
blanchet@36291
   163
blanchet@36486
   164
(* Syntax: cnf(<num>, <formula_role>, <cnf_formula> <annotations>).
blanchet@36486
   165
   The <num> could be an identifier, but we assume integers. *)
blanchet@36486
   166
fun finish_tstp_definition_line (num, (u, us)) = Definition (num, u, us)
blanchet@36486
   167
fun finish_tstp_inference_line ((num, us), deps) = Inference (num, us, deps)
blanchet@36393
   168
fun parse_tstp_line pool =
blanchet@36486
   169
     ((Scan.this_string "fof" -- $$ "(") |-- parse_integer --| $$ ","
blanchet@36486
   170
       --| Scan.this_string "definition" --| $$ "," -- parse_definition pool
blanchet@36486
   171
       --| parse_tstp_annotations --| $$ ")" --| $$ "."
blanchet@36486
   172
      >> finish_tstp_definition_line)
blanchet@36486
   173
  || ((Scan.this_string "cnf" -- $$ "(") |-- parse_integer --| $$ ","
blanchet@36486
   174
       --| Symbol.scan_id --| $$ "," -- parse_clause pool
blanchet@36486
   175
       -- parse_tstp_annotations --| $$ ")" --| $$ "."
blanchet@36486
   176
      >> finish_tstp_inference_line)
blanchet@36291
   177
blanchet@36291
   178
(**** PARSING OF SPASS OUTPUT ****)
blanchet@36291
   179
blanchet@36392
   180
(* SPASS returns clause references of the form "x.y". We ignore "y", whose role
blanchet@36392
   181
   is not clear anyway. *)
blanchet@36392
   182
val parse_dot_name = parse_integer --| $$ "." --| parse_integer
paulson@21978
   183
blanchet@36392
   184
val parse_spass_annotations =
blanchet@36392
   185
  Scan.optional ($$ ":" |-- Scan.repeat (parse_dot_name
blanchet@36392
   186
                                         --| Scan.option ($$ ","))) []
blanchet@36291
   187
blanchet@36574
   188
(* It is not clear why some literals are followed by sequences of stars and/or
blanchet@36574
   189
   pluses. We ignore them. *)
blanchet@36574
   190
fun parse_decorated_predicate_term pool =
blanchet@36562
   191
  parse_predicate_term pool --| Scan.repeat ($$ "*" || $$ "+" || $$ " ")
blanchet@36291
   192
blanchet@36393
   193
fun parse_horn_clause pool =
blanchet@36574
   194
  Scan.repeat (parse_decorated_predicate_term pool) --| $$ "|" --| $$ "|"
blanchet@36574
   195
    -- Scan.repeat (parse_decorated_predicate_term pool) --| $$ "-" --| $$ ">"
blanchet@36574
   196
    -- Scan.repeat (parse_decorated_predicate_term pool)
blanchet@36558
   197
  >> (fn (([], []), []) => [str_leaf "c_False"]
blanchet@36558
   198
       | ((clauses1, clauses2), clauses3) =>
blanchet@36558
   199
         map negate_node (clauses1 @ clauses2) @ clauses3)
paulson@21978
   200
blanchet@36558
   201
(* Syntax: <num>[0:<inference><annotations>]
blanchet@36558
   202
   <cnf_formulas> || <cnf_formulas> -> <cnf_formulas>. *)
blanchet@36486
   203
fun finish_spass_line ((num, deps), us) = Inference (num, us, deps)
blanchet@36402
   204
fun parse_spass_line pool =
blanchet@36392
   205
  parse_integer --| $$ "[" --| $$ "0" --| $$ ":" --| Symbol.scan_id
blanchet@36558
   206
  -- parse_spass_annotations --| $$ "]" -- parse_horn_clause pool --| $$ "."
blanchet@36486
   207
  >> finish_spass_line
blanchet@36291
   208
blanchet@36548
   209
fun parse_line pool = parse_tstp_line pool || parse_spass_line pool
blanchet@36548
   210
fun parse_lines pool = Scan.repeat1 (parse_line pool)
blanchet@36548
   211
fun parse_proof pool =
blanchet@36548
   212
  fst o Scan.finite Symbol.stopper
blanchet@36548
   213
            (Scan.error (!! (fn _ => raise Fail "unrecognized ATP output")
blanchet@36548
   214
                            (parse_lines pool)))
blanchet@36548
   215
  o explode o strip_spaces
paulson@21978
   216
paulson@21978
   217
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   218
krauss@36606
   219
exception NODE of node
paulson@21978
   220
paulson@21978
   221
(*If string s has the prefix s1, return the result of deleting it.*)
wenzelm@23139
   222
fun strip_prefix s1 s =
immler@31038
   223
  if String.isPrefix s1 s
blanchet@35865
   224
  then SOME (undo_ascii_of (String.extract (s, size s1, NONE)))
paulson@21978
   225
  else NONE;
paulson@21978
   226
paulson@21978
   227
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   228
val type_const_trans_table_inv =
blanchet@35865
   229
      Symtab.make (map swap (Symtab.dest type_const_trans_table));
paulson@21978
   230
paulson@21978
   231
fun invert_type_const c =
paulson@21978
   232
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   233
        SOME c' => c'
paulson@21978
   234
      | NONE => c;
paulson@21978
   235
blanchet@36285
   236
fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS);
blanchet@36285
   237
fun make_tparam s = TypeInfer.param 0 (s, HOLogic.typeS)
paulson@21978
   238
fun make_var (b,T) = Var((b,0),T);
paulson@21978
   239
krauss@36606
   240
(*Type variables are given the basic sort, HOL.type. Some will later be constrained
krauss@36606
   241
  by information from type literals, or by type inference.*)
krauss@36606
   242
fun type_of_node (u as IntLeaf _) = raise NODE u
krauss@36606
   243
  | type_of_node (u as StrNode (a, us)) =
krauss@36606
   244
    let val Ts = map type_of_node us in
blanchet@36486
   245
      case strip_prefix tconst_prefix a of
blanchet@36486
   246
        SOME b => Type (invert_type_const b, Ts)
blanchet@36486
   247
      | NONE =>
blanchet@36486
   248
        if not (null us) then
krauss@36606
   249
          raise NODE u  (*only tconsts have type arguments*)
blanchet@36486
   250
        else case strip_prefix tfree_prefix a of
blanchet@36486
   251
          SOME b => TFree ("'" ^ b, HOLogic.typeS)
blanchet@36486
   252
        | NONE =>
blanchet@36486
   253
          case strip_prefix tvar_prefix a of
blanchet@36486
   254
            SOME b => make_tvar b
blanchet@36486
   255
          | NONE => make_tparam a  (* Variable from the ATP, say "X1" *)
blanchet@36486
   256
    end
paulson@21978
   257
paulson@21978
   258
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   259
val const_trans_table_inv =
blanchet@36402
   260
  Symtab.update ("fequal", @{const_name "op ="})
blanchet@36402
   261
                (Symtab.make (map swap (Symtab.dest const_trans_table)))
paulson@21978
   262
blanchet@36402
   263
fun invert_const c = c |> Symtab.lookup const_trans_table_inv |> the_default c
paulson@21978
   264
paulson@21978
   265
(*The number of type arguments of a constant, zero if it's monomorphic*)
krauss@36606
   266
fun num_typargs thy s = length (Sign.const_typargs thy (s, Sign.the_const_type thy s));
krauss@36606
   267
krauss@36606
   268
(*Generates a constant, given its type arguments*)
krauss@36606
   269
fun const_of thy (a,Ts) = Const(a, Sign.const_instance thy (a,Ts));
paulson@21978
   270
blanchet@36486
   271
fun fix_atp_variable_name s =
blanchet@36486
   272
  let
blanchet@36486
   273
    fun subscript_name s n = s ^ nat_subscript n
blanchet@36486
   274
    val s = String.map Char.toLower s
blanchet@36486
   275
  in
blanchet@36486
   276
    case space_explode "_" s of
blanchet@36486
   277
      [_] => (case take_suffix Char.isDigit (String.explode s) of
blanchet@36486
   278
                (cs1 as _ :: _, cs2 as _ :: _) =>
blanchet@36486
   279
                subscript_name (String.implode cs1)
blanchet@36486
   280
                               (the (Int.fromString (String.implode cs2)))
blanchet@36486
   281
              | (_, _) => s)
blanchet@36486
   282
    | [s1, s2] => (case Int.fromString s2 of
blanchet@36486
   283
                     SOME n => subscript_name s1 n
blanchet@36486
   284
                   | NONE => s)
blanchet@36486
   285
    | _ => s
blanchet@36486
   286
  end
blanchet@36486
   287
krauss@36606
   288
(*First-order translation. No types are known for variables. HOLogic.typeT should allow
krauss@36606
   289
  them to be inferred.*)
krauss@36606
   290
fun term_of_node args thy u =
krauss@36606
   291
  case u of
krauss@36606
   292
    IntLeaf _ => raise NODE u
krauss@36606
   293
  | StrNode ("hBOOL", [u]) => term_of_node [] thy u  (* ignore hBOOL *)
krauss@36606
   294
  | StrNode ("hAPP", [u1, u2]) => term_of_node (u2 :: args) thy u1
krauss@36606
   295
  | StrNode (a, us) =>
krauss@36606
   296
    case strip_prefix const_prefix a of
krauss@36606
   297
      SOME "equal" =>
krauss@36606
   298
      list_comb (Const (@{const_name "op ="}, HOLogic.typeT),
krauss@36606
   299
                 map (term_of_node [] thy) us)
krauss@36606
   300
    | SOME b =>
krauss@36606
   301
      let
krauss@36606
   302
        val c = invert_const b
krauss@36606
   303
        val nterms = length us - num_typargs thy c
krauss@36606
   304
        val ts = map (term_of_node [] thy) (take nterms us @ args)
krauss@36606
   305
        (*Extra args from hAPP come AFTER any arguments given directly to the
krauss@36606
   306
          constant.*)
krauss@36606
   307
        val Ts = map type_of_node (drop nterms us)
krauss@36606
   308
      in list_comb(const_of thy (c, Ts), ts) end
krauss@36606
   309
    | NONE => (*a variable, not a constant*)
krauss@36606
   310
      let
krauss@36606
   311
        val opr =
krauss@36606
   312
          (* a Free variable is typically a Skolem function *)
krauss@36606
   313
          case strip_prefix fixed_var_prefix a of
krauss@36606
   314
            SOME b => Free (b, HOLogic.typeT)
krauss@36606
   315
          | NONE =>
krauss@36606
   316
            case strip_prefix schematic_var_prefix a of
krauss@36606
   317
              SOME b => make_var (b, HOLogic.typeT)
krauss@36606
   318
            | NONE =>
krauss@36606
   319
              (* Variable from the ATP, say "X1" *)
krauss@36606
   320
              make_var (fix_atp_variable_name a, HOLogic.typeT)
krauss@36606
   321
      in list_comb (opr, map (term_of_node [] thy) (us @ args)) end
paulson@21978
   322
blanchet@36392
   323
(* Type class literal applied to a type. Returns triple of polarity, class,
blanchet@36392
   324
   type. *)
krauss@36606
   325
fun constraint_of_node pos (StrNode ("c_Not", [u])) =
krauss@36606
   326
    constraint_of_node (not pos) u
krauss@36606
   327
  | constraint_of_node pos u = case u of
krauss@36606
   328
        IntLeaf _ => raise NODE u
blanchet@36486
   329
      | StrNode (a, us) =>
krauss@36606
   330
            (case (strip_prefix class_prefix a, map type_of_node us) of
blanchet@36486
   331
                 (SOME b, [T]) => (pos, b, T)
krauss@36606
   332
               | _ => raise NODE u)
paulson@21978
   333
paulson@21978
   334
(** Accumulate type constraints in a clause: negative type literals **)
paulson@21978
   335
blanchet@36485
   336
fun add_var (key, z)  = Vartab.map_default (key, []) (cons z)
paulson@21978
   337
krauss@36606
   338
fun add_constraint ((false, cl, TFree(a,_)), vt) = add_var ((a,~1),cl) vt
krauss@36606
   339
  | add_constraint ((false, cl, TVar(ix,_)), vt) = add_var (ix,cl) vt
krauss@36606
   340
  | add_constraint (_, vt) = vt;
paulson@21978
   341
blanchet@36491
   342
fun is_positive_literal (@{const Not} $ _) = false
blanchet@36402
   343
  | is_positive_literal t = true
blanchet@36402
   344
blanchet@36485
   345
fun negate_term thy (Const (@{const_name All}, T) $ Abs (s, T', t')) =
blanchet@36402
   346
    Const (@{const_name Ex}, T) $ Abs (s, T', negate_term thy t')
blanchet@36402
   347
  | negate_term thy (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
blanchet@36402
   348
    Const (@{const_name All}, T) $ Abs (s, T', negate_term thy t')
blanchet@36402
   349
  | negate_term thy (@{const "op -->"} $ t1 $ t2) =
blanchet@36402
   350
    @{const "op &"} $ t1 $ negate_term thy t2
blanchet@36402
   351
  | negate_term thy (@{const "op &"} $ t1 $ t2) =
blanchet@36402
   352
    @{const "op |"} $ negate_term thy t1 $ negate_term thy t2
blanchet@36402
   353
  | negate_term thy (@{const "op |"} $ t1 $ t2) =
blanchet@36402
   354
    @{const "op &"} $ negate_term thy t1 $ negate_term thy t2
blanchet@36486
   355
  | negate_term _ (@{const Not} $ t) = t
blanchet@36486
   356
  | negate_term _ t = @{const Not} $ t
blanchet@36402
   357
blanchet@36402
   358
fun clause_for_literals _ [] = HOLogic.false_const
blanchet@36402
   359
  | clause_for_literals _ [lit] = lit
blanchet@36402
   360
  | clause_for_literals thy lits =
blanchet@36402
   361
    case List.partition is_positive_literal lits of
blanchet@36402
   362
      (pos_lits as _ :: _, neg_lits as _ :: _) =>
blanchet@36402
   363
      @{const "op -->"}
blanchet@36402
   364
          $ foldr1 HOLogic.mk_conj (map (negate_term thy) neg_lits)
blanchet@36402
   365
          $ foldr1 HOLogic.mk_disj pos_lits
blanchet@36402
   366
    | _ => foldr1 HOLogic.mk_disj lits
blanchet@36402
   367
blanchet@36402
   368
(* Final treatment of the list of "real" literals from a clause.
blanchet@36402
   369
   No "real" literals means only type information. *)
blanchet@36402
   370
fun finish_clause _ [] = HOLogic.true_const
blanchet@36402
   371
  | finish_clause thy lits =
blanchet@36402
   372
    lits |> filter_out (curry (op =) HOLogic.false_const) |> rev
blanchet@36402
   373
         |> clause_for_literals thy
paulson@22491
   374
paulson@21978
   375
(*Accumulate sort constraints in vt, with "real" literals in lits.*)
krauss@36606
   376
fun lits_of_nodes thy (vt, lits) [] = (vt, finish_clause thy lits)
krauss@36606
   377
  | lits_of_nodes thy (vt, lits) (u :: us) =
krauss@36606
   378
    lits_of_nodes thy (add_constraint (constraint_of_node true u, vt), lits) us
krauss@36606
   379
    handle NODE _ => lits_of_nodes thy (vt, term_of_node [] thy u :: lits) us
paulson@21978
   380
paulson@21978
   381
(*Update TVars/TFrees with detected sort constraints.*)
blanchet@36393
   382
fun repair_sorts vt =
blanchet@36556
   383
  let
blanchet@36556
   384
    fun do_type (Type (a, Ts)) = Type (a, map do_type Ts)
blanchet@36556
   385
      | do_type (TVar (xi, s)) = TVar (xi, the_default s (Vartab.lookup vt xi))
blanchet@36556
   386
      | do_type (TFree (x, s)) =
blanchet@36556
   387
        TFree (x, the_default s (Vartab.lookup vt (x, ~1)))
blanchet@36556
   388
    fun do_term (Const (a, T)) = Const (a, do_type T)
blanchet@36556
   389
      | do_term (Free (a, T)) = Free (a, do_type T)
blanchet@36556
   390
      | do_term (Var (xi, T)) = Var (xi, do_type T)
blanchet@36556
   391
      | do_term (t as Bound _) = t
blanchet@36556
   392
      | do_term (Abs (a, T, t)) = Abs (a, do_type T, do_term t)
blanchet@36556
   393
      | do_term (t1 $ t2) = do_term t1 $ do_term t2
blanchet@36556
   394
  in not (Vartab.is_empty vt) ? do_term end
blanchet@36551
   395
blanchet@36551
   396
fun unskolemize_term t =
krauss@36606
   397
  fold forall_of (Term.add_consts t []
krauss@36606
   398
                 |> filter (is_skolem_const_name o fst) |> map Const) t
paulson@21978
   399
blanchet@36555
   400
val combinator_table =
blanchet@36555
   401
  [(@{const_name COMBI}, @{thm COMBI_def_raw}),
blanchet@36555
   402
   (@{const_name COMBK}, @{thm COMBK_def_raw}),
blanchet@36555
   403
   (@{const_name COMBB}, @{thm COMBB_def_raw}),
blanchet@36555
   404
   (@{const_name COMBC}, @{thm COMBC_def_raw}),
blanchet@36555
   405
   (@{const_name COMBS}, @{thm COMBS_def_raw})]
blanchet@36555
   406
blanchet@36555
   407
fun uncombine_term (t1 $ t2) = betapply (pairself uncombine_term (t1, t2))
blanchet@36555
   408
  | uncombine_term (Abs (s, T, t')) = Abs (s, T, uncombine_term t')
blanchet@36555
   409
  | uncombine_term (t as Const (x as (s, _))) =
blanchet@36555
   410
    (case AList.lookup (op =) combinator_table s of
blanchet@36555
   411
       SOME thm => thm |> prop_of |> specialize_type @{theory} x |> Logic.dest_equals |> snd
blanchet@36555
   412
     | NONE => t)
blanchet@36555
   413
  | uncombine_term t = t
blanchet@36555
   414
blanchet@36486
   415
(* Interpret a list of syntax trees as a clause, given by "real" literals and
blanchet@36486
   416
   sort constraints. "vt" holds the initial sort constraints, from the
blanchet@36486
   417
   conjecture clauses. *)
krauss@36606
   418
fun clause_of_nodes ctxt vt us =
krauss@36606
   419
  let val (vt, t) = lits_of_nodes (ProofContext.theory_of ctxt) (vt, []) us in
krauss@36606
   420
    t |> repair_sorts vt
krauss@36606
   421
  end
blanchet@36556
   422
fun check_formula ctxt =
krauss@36606
   423
  TypeInfer.constrain HOLogic.boolT
blanchet@36486
   424
  #> Syntax.check_term (ProofContext.set_mode ProofContext.mode_schematic ctxt)
paulson@21978
   425
blanchet@36486
   426
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit
blanchet@36486
   427
    clauses. **)
paulson@21978
   428
blanchet@36486
   429
fun add_tfree_constraint (true, cl, TFree (a, _)) = add_var ((a, ~1), cl)
blanchet@36486
   430
  | add_tfree_constraint _ = I
paulson@21978
   431
fun tfree_constraints_of_clauses vt [] = vt
blanchet@36486
   432
  | tfree_constraints_of_clauses vt ([lit] :: uss) =
blanchet@36486
   433
    (tfree_constraints_of_clauses (add_tfree_constraint
krauss@36606
   434
                                          (constraint_of_node true lit) vt) uss
blanchet@36486
   435
     handle NODE _ => (* Not a positive type constraint? Ignore the literal. *)
blanchet@36486
   436
     tfree_constraints_of_clauses vt uss)
blanchet@36486
   437
  | tfree_constraints_of_clauses vt (_ :: uss) =
blanchet@36486
   438
    tfree_constraints_of_clauses vt uss
paulson@21978
   439
paulson@21978
   440
paulson@21978
   441
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   442
blanchet@36486
   443
fun unvarify_term (Var ((s, 0), T)) = Free (s, T)
blanchet@36486
   444
  | unvarify_term t = raise TERM ("unvarify_term: non-Var", [t])
paulson@21978
   445
blanchet@36486
   446
fun clauses_in_lines (Definition (_, u, us)) = u :: us
blanchet@36486
   447
  | clauses_in_lines (Inference (_, us, _)) = us
paulson@21978
   448
krauss@36606
   449
fun decode_line vt (Definition (num, u, us)) ctxt =
blanchet@36486
   450
    let
krauss@36606
   451
      val t1 = clause_of_nodes ctxt vt [u]
blanchet@36551
   452
      val vars = snd (strip_comb t1)
blanchet@36486
   453
      val frees = map unvarify_term vars
blanchet@36486
   454
      val unvarify_args = subst_atomic (vars ~~ frees)
krauss@36606
   455
      val t2 = clause_of_nodes ctxt vt us
blanchet@36551
   456
      val (t1, t2) =
blanchet@36551
   457
        HOLogic.eq_const HOLogic.typeT $ t1 $ t2
blanchet@36556
   458
        |> unvarify_args |> uncombine_term |> check_formula ctxt
blanchet@36555
   459
        |> HOLogic.dest_eq
blanchet@36486
   460
    in
blanchet@36551
   461
      (Definition (num, t1, t2),
blanchet@36551
   462
       fold Variable.declare_term (maps OldTerm.term_frees [t1, t2]) ctxt)
blanchet@36486
   463
    end
krauss@36606
   464
  | decode_line vt (Inference (num, us, deps)) ctxt =
blanchet@36551
   465
    let
krauss@36606
   466
      val t = us |> clause_of_nodes ctxt vt
blanchet@36556
   467
                 |> unskolemize_term |> uncombine_term |> check_formula ctxt
blanchet@36551
   468
    in
blanchet@36551
   469
      (Inference (num, t, deps),
blanchet@36551
   470
       fold Variable.declare_term (OldTerm.term_frees t) ctxt)
blanchet@36486
   471
    end
krauss@36606
   472
fun decode_lines ctxt lines =
blanchet@36486
   473
  let
blanchet@36486
   474
    val vt = tfree_constraints_of_clauses Vartab.empty
blanchet@36486
   475
                                          (map clauses_in_lines lines)
krauss@36606
   476
  in #1 (fold_map (decode_line vt) lines ctxt) end
paulson@21978
   477
blanchet@36486
   478
fun aint_inference _ (Definition _) = true
blanchet@36486
   479
  | aint_inference t (Inference (_, t', _)) = not (t aconv t')
blanchet@36486
   480
blanchet@36486
   481
(* No "real" literals means only type information (tfree_tcs, clsrel, or
blanchet@36486
   482
   clsarity). *)
blanchet@36486
   483
val is_only_type_information = curry (op aconv) HOLogic.true_const
blanchet@36486
   484
blanchet@36486
   485
fun replace_one_dep (old, new) dep = if dep = old then new else [dep]
blanchet@36486
   486
fun replace_deps_in_line _ (line as Definition _) = line
blanchet@36486
   487
  | replace_deps_in_line p (Inference (num, t, deps)) =
blanchet@36486
   488
    Inference (num, t, fold (union (op =) o replace_one_dep p) deps [])
paulson@21978
   489
paulson@22491
   490
(*Discard axioms; consolidate adjacent lines that prove the same clause, since they differ
paulson@22491
   491
  only in type information.*)
blanchet@36551
   492
fun add_line _ _ (line as Definition _) lines = line :: lines
blanchet@36551
   493
  | add_line conjecture_shape thm_names (Inference (num, t, [])) lines =
blanchet@36570
   494
    (* No dependencies: axiom, conjecture clause, or internal axioms or
blanchet@36570
   495
       definitions (Vampire). *)
blanchet@36486
   496
    if is_axiom_clause_number thm_names num then
blanchet@36486
   497
      (* Axioms are not proof lines. *)
blanchet@36486
   498
      if is_only_type_information t then
blanchet@36486
   499
        map (replace_deps_in_line (num, [])) lines
blanchet@36486
   500
      (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@36486
   501
      else case take_prefix (aint_inference t) lines of
blanchet@36486
   502
        (_, []) => lines (*no repetition of proof line*)
blanchet@36486
   503
      | (pre, Inference (num', _, _) :: post) =>
blanchet@36486
   504
        pre @ map (replace_deps_in_line (num', [num])) post
blanchet@36570
   505
    else if is_conjecture_clause_number conjecture_shape num then
blanchet@36486
   506
      Inference (num, t, []) :: lines
blanchet@36551
   507
    else
blanchet@36570
   508
      map (replace_deps_in_line (num, [])) lines
blanchet@36551
   509
  | add_line _ _ (Inference (num, t, deps)) lines =
blanchet@36486
   510
    (* Type information will be deleted later; skip repetition test. *)
blanchet@36486
   511
    if is_only_type_information t then
blanchet@36486
   512
      Inference (num, t, deps) :: lines
blanchet@36486
   513
    (* Is there a repetition? If so, replace later line by earlier one. *)
blanchet@36486
   514
    else case take_prefix (aint_inference t) lines of
blanchet@36486
   515
      (* FIXME: Doesn't this code risk conflating proofs involving different
blanchet@36486
   516
         types?? *)
blanchet@36486
   517
       (_, []) => Inference (num, t, deps) :: lines
blanchet@36486
   518
     | (pre, Inference (num', t', _) :: post) =>
blanchet@36486
   519
       Inference (num, t', deps) ::
blanchet@36486
   520
       pre @ map (replace_deps_in_line (num', [num])) post
paulson@22044
   521
blanchet@36486
   522
(* Recursively delete empty lines (type information) from the proof. *)
blanchet@36486
   523
fun add_nontrivial_line (Inference (num, t, [])) lines =
blanchet@36486
   524
    if is_only_type_information t then delete_dep num lines
blanchet@36486
   525
    else Inference (num, t, []) :: lines
blanchet@36486
   526
  | add_nontrivial_line line lines = line :: lines
blanchet@36395
   527
and delete_dep num lines =
blanchet@36486
   528
  fold_rev add_nontrivial_line (map (replace_deps_in_line (num, [])) lines) []
blanchet@36486
   529
blanchet@36560
   530
(* ATPs sometimes reuse free variable names in the strangest ways. Surprisingly,
blanchet@36560
   531
   removing the offending lines often does the trick. *)
blanchet@36560
   532
fun is_bad_free frees (Free x) = not (member (op =) frees x)
blanchet@36560
   533
  | is_bad_free _ _ = false
paulson@22470
   534
blanchet@36570
   535
(* Vampire is keen on producing these. *)
blanchet@36570
   536
fun is_trivial_formula (@{const Not} $ (Const (@{const_name "op ="}, _)
blanchet@36570
   537
                                        $ t1 $ t2)) = (t1 aconv t2)
blanchet@36570
   538
  | is_trivial_formula t = false
blanchet@36570
   539
blanchet@36570
   540
fun add_desired_line _ _ _ _ _ (line as Definition _) (j, lines) =
blanchet@36560
   541
    (j, line :: lines)
blanchet@36570
   542
  | add_desired_line ctxt shrink_factor conjecture_shape thm_names frees
blanchet@36570
   543
                     (Inference (num, t, deps)) (j, lines) =
blanchet@36402
   544
    (j + 1,
blanchet@36570
   545
     if is_axiom_clause_number thm_names num orelse
blanchet@36570
   546
        is_conjecture_clause_number conjecture_shape num orelse
blanchet@36570
   547
        (not (is_only_type_information t) andalso
blanchet@36570
   548
         null (Term.add_tvars t []) andalso
blanchet@36570
   549
         not (exists_subterm (is_bad_free frees) t) andalso
blanchet@36570
   550
         not (is_trivial_formula t) andalso
blanchet@36570
   551
         (null lines orelse (* last line must be kept *)
blanchet@36570
   552
          (length deps >= 2 andalso j mod shrink_factor = 0))) then
blanchet@36570
   553
       Inference (num, t, deps) :: lines  (* keep line *)
blanchet@36402
   554
     else
blanchet@36570
   555
       map (replace_deps_in_line (num, deps)) lines)  (* drop line *)
paulson@21978
   556
blanchet@36402
   557
(** EXTRACTING LEMMAS **)
paulson@21979
   558
blanchet@36223
   559
(* A list consisting of the first number in each line is returned.
blanchet@36395
   560
   TSTP: Interesting lines have the form "cnf(108, axiom, ...)", where the
blanchet@36223
   561
   number (108) is extracted.
blanchet@36395
   562
   SPASS: Lines have the form "108[0:Inp] ...", where the first number (108) is
blanchet@36223
   563
   extracted. *)
blanchet@36402
   564
fun extract_clause_numbers_in_atp_proof atp_proof =
blanchet@35865
   565
  let
blanchet@36395
   566
    val tokens_of = String.tokens (not o is_ident_char)
blanchet@36402
   567
    fun extract_num ("cnf" :: num :: "axiom" :: _) = Int.fromString num
blanchet@36395
   568
      | extract_num (num :: "0" :: "Inp" :: _) = Int.fromString num
blanchet@36395
   569
      | extract_num _ = NONE
blanchet@36402
   570
  in atp_proof |> split_lines |> map_filter (extract_num o tokens_of) end
wenzelm@33310
   571
  
blanchet@36395
   572
(* Used to label theorems chained into the Sledgehammer call (or rather
blanchet@36395
   573
   goal?) *)
blanchet@36395
   574
val chained_hint = "sledgehammer_chained"
blanchet@35865
   575
blanchet@36063
   576
fun apply_command _ 1 = "by "
blanchet@36063
   577
  | apply_command 1 _ = "apply "
blanchet@36063
   578
  | apply_command i _ = "prefer " ^ string_of_int i ^ " apply "
blanchet@36570
   579
fun metis_command i n [] = apply_command i n ^ "metis"
blanchet@36570
   580
  | metis_command i n ss =
blanchet@36570
   581
    apply_command i n ^ "(metis " ^ space_implode " " ss ^ ")"
blanchet@36063
   582
fun metis_line i n xs =
blanchet@36063
   583
  "Try this command: " ^
blanchet@36063
   584
  Markup.markup Markup.sendback (metis_command i n xs) ^ ".\n" 
blanchet@36281
   585
fun minimize_line _ [] = ""
blanchet@36281
   586
  | minimize_line minimize_command facts =
blanchet@36281
   587
    case minimize_command facts of
blanchet@36281
   588
      "" => ""
blanchet@36281
   589
    | command =>
blanchet@36065
   590
      "To minimize the number of lemmas, try this command: " ^
blanchet@36281
   591
      Markup.markup Markup.sendback command ^ ".\n"
immler@31840
   592
krauss@36606
   593
fun metis_proof_text (minimize_command, atp_proof, thm_names, goal, i) =
blanchet@36063
   594
  let
blanchet@36231
   595
    val lemmas =
blanchet@36402
   596
      atp_proof |> extract_clause_numbers_in_atp_proof
blanchet@36402
   597
                |> filter (is_axiom_clause_number thm_names)
blanchet@36402
   598
                |> map (fn i => Vector.sub (thm_names, i - 1))
blanchet@36402
   599
                |> filter_out (fn s => s = "??.unknown" orelse s = chained_hint)
blanchet@36402
   600
                |> sort_distinct string_ord
blanchet@36063
   601
    val n = Logic.count_prems (prop_of goal)
blanchet@36395
   602
  in (metis_line i n lemmas ^ minimize_line minimize_command lemmas, lemmas) end
immler@31037
   603
blanchet@36486
   604
(** Isar proof construction and manipulation **)
blanchet@36486
   605
blanchet@36486
   606
fun merge_fact_sets (ls1, ss1) (ls2, ss2) =
blanchet@36486
   607
  (union (op =) ls1 ls2, union (op =) ss1 ss2)
blanchet@36402
   608
blanchet@36402
   609
type label = string * int
blanchet@36402
   610
type facts = label list * string list
blanchet@36402
   611
blanchet@36402
   612
datatype qualifier = Show | Then | Moreover | Ultimately
blanchet@36291
   613
blanchet@36402
   614
datatype step =
blanchet@36478
   615
  Fix of (string * typ) list |
blanchet@36486
   616
  Let of term * term |
blanchet@36402
   617
  Assume of label * term |
blanchet@36402
   618
  Have of qualifier list * label * term * byline
blanchet@36402
   619
and byline =
blanchet@36564
   620
  ByMetis of facts |
blanchet@36402
   621
  CaseSplit of step list list * facts
blanchet@36402
   622
blanchet@36574
   623
fun smart_case_split [] facts = ByMetis facts
blanchet@36574
   624
  | smart_case_split proofs facts = CaseSplit (proofs, facts)
blanchet@36574
   625
blanchet@36402
   626
val raw_prefix = "X"
blanchet@36402
   627
val assum_prefix = "A"
blanchet@36402
   628
val fact_prefix = "F"
blanchet@36402
   629
blanchet@36570
   630
fun string_for_label (s, num) = s ^ string_of_int num
blanchet@36570
   631
blanchet@36475
   632
fun add_fact_from_dep thm_names num =
blanchet@36475
   633
  if is_axiom_clause_number thm_names num then
blanchet@36480
   634
    apsnd (insert (op =) (Vector.sub (thm_names, num - 1)))
blanchet@36475
   635
  else
blanchet@36480
   636
    apfst (insert (op =) (raw_prefix, num))
blanchet@36402
   637
blanchet@36491
   638
fun forall_vars t = fold_rev forall_of (map Var (Term.add_vars t [])) t
blanchet@36491
   639
blanchet@36486
   640
fun step_for_line _ _ (Definition (num, t1, t2)) = Let (t1, t2)
blanchet@36486
   641
  | step_for_line _ _ (Inference (num, t, [])) = Assume ((raw_prefix, num), t)
blanchet@36486
   642
  | step_for_line thm_names j (Inference (num, t, deps)) =
blanchet@36486
   643
    Have (if j = 1 then [Show] else [], (raw_prefix, num),
blanchet@36491
   644
          forall_vars t,
blanchet@36564
   645
          ByMetis (fold (add_fact_from_dep thm_names) deps ([], [])))
blanchet@36291
   646
krauss@36606
   647
fun proof_from_atp_proof pool ctxt shrink_factor atp_proof conjecture_shape
krauss@36606
   648
                         thm_names frees =
blanchet@36402
   649
  let
blanchet@36486
   650
    val lines =
blanchet@36574
   651
      atp_proof ^ "$" (* the $ sign acts as a sentinel *)
blanchet@36548
   652
      |> parse_proof pool
krauss@36606
   653
      |> decode_lines ctxt
blanchet@36551
   654
      |> rpair [] |-> fold_rev (add_line conjecture_shape thm_names)
blanchet@36486
   655
      |> rpair [] |-> fold_rev add_nontrivial_line
blanchet@36570
   656
      |> rpair (0, []) |-> fold_rev (add_desired_line ctxt shrink_factor
blanchet@36570
   657
                                               conjecture_shape thm_names frees)
blanchet@36486
   658
      |> snd
blanchet@36402
   659
  in
krauss@36606
   660
    (if null frees then [] else [Fix frees]) @
blanchet@36486
   661
    map2 (step_for_line thm_names) (length lines downto 1) lines
blanchet@36402
   662
  end
blanchet@36402
   663
blanchet@36402
   664
val indent_size = 2
blanchet@36402
   665
val no_label = ("", ~1)
blanchet@36402
   666
blanchet@36402
   667
fun no_show qs = not (member (op =) qs Show)
blanchet@36402
   668
blanchet@36402
   669
(* When redirecting proofs, we keep information about the labels seen so far in
blanchet@36402
   670
   the "backpatches" data structure. The first component indicates which facts
blanchet@36402
   671
   should be associated with forthcoming proof steps. The second component is a
blanchet@36402
   672
   pair ("keep_ls", "drop_ls"), where "keep_ls" are the labels to keep and
blanchet@36402
   673
   "drop_ls" are those that should be dropped in a case split. *)
blanchet@36402
   674
type backpatches = (label * facts) list * (label list * label list)
blanchet@36402
   675
blanchet@36556
   676
fun used_labels_of_step (Have (_, _, _, by)) =
blanchet@36402
   677
    (case by of
blanchet@36564
   678
       ByMetis (ls, _) => ls
blanchet@36556
   679
     | CaseSplit (proofs, (ls, _)) =>
blanchet@36556
   680
       fold (union (op =) o used_labels_of) proofs ls)
blanchet@36556
   681
  | used_labels_of_step _ = []
blanchet@36556
   682
and used_labels_of proof = fold (union (op =) o used_labels_of_step) proof []
blanchet@36402
   683
blanchet@36402
   684
fun new_labels_of_step (Fix _) = []
blanchet@36486
   685
  | new_labels_of_step (Let _) = []
blanchet@36402
   686
  | new_labels_of_step (Assume (l, _)) = [l]
blanchet@36402
   687
  | new_labels_of_step (Have (_, l, _, _)) = [l]
blanchet@36402
   688
val new_labels_of = maps new_labels_of_step
blanchet@36402
   689
blanchet@36402
   690
val join_proofs =
blanchet@36402
   691
  let
blanchet@36402
   692
    fun aux _ [] = NONE
blanchet@36402
   693
      | aux proof_tail (proofs as (proof1 :: _)) =
blanchet@36402
   694
        if exists null proofs then
blanchet@36402
   695
          NONE
blanchet@36402
   696
        else if forall (curry (op =) (hd proof1) o hd) (tl proofs) then
blanchet@36402
   697
          aux (hd proof1 :: proof_tail) (map tl proofs)
blanchet@36402
   698
        else case hd proof1 of
blanchet@36402
   699
          Have ([], l, t, by) =>
blanchet@36402
   700
          if forall (fn Have ([], l', t', _) :: _ => (l, t) = (l', t')
blanchet@36402
   701
                      | _ => false) (tl proofs) andalso
blanchet@36402
   702
             not (exists (member (op =) (maps new_labels_of proofs))
blanchet@36556
   703
                         (used_labels_of proof_tail)) then
blanchet@36402
   704
            SOME (l, t, map rev proofs, proof_tail)
blanchet@36402
   705
          else
blanchet@36402
   706
            NONE
blanchet@36402
   707
        | _ => NONE
blanchet@36402
   708
  in aux [] o map rev end
blanchet@36402
   709
blanchet@36402
   710
fun case_split_qualifiers proofs =
blanchet@36402
   711
  case length proofs of
blanchet@36402
   712
    0 => []
blanchet@36402
   713
  | 1 => [Then]
blanchet@36402
   714
  | _ => [Ultimately]
blanchet@36402
   715
blanchet@36491
   716
fun redirect_proof thy conjecture_shape hyp_ts concl_t proof =
wenzelm@33310
   717
  let
blanchet@36402
   718
    val concl_ls = map (pair raw_prefix) (List.last conjecture_shape)
blanchet@36551
   719
    fun find_hyp num = nth hyp_ts (index_in_shape num conjecture_shape)
blanchet@36402
   720
    fun first_pass ([], contra) = ([], contra)
blanchet@36491
   721
      | first_pass ((step as Fix _) :: proof, contra) =
blanchet@36491
   722
        first_pass (proof, contra) |>> cons step
blanchet@36491
   723
      | first_pass ((step as Let _) :: proof, contra) =
blanchet@36491
   724
        first_pass (proof, contra) |>> cons step
blanchet@36551
   725
      | first_pass ((step as Assume (l as (_, num), t)) :: proof, contra) =
blanchet@36402
   726
        if member (op =) concl_ls l then
blanchet@36491
   727
          first_pass (proof, contra ||> cons step)
blanchet@36402
   728
        else
blanchet@36551
   729
          first_pass (proof, contra) |>> cons (Assume (l, find_hyp num))
blanchet@36564
   730
      | first_pass ((step as Have (qs, l, t, ByMetis (ls, ss))) :: proof,
blanchet@36491
   731
                    contra) =
blanchet@36402
   732
        if exists (member (op =) (fst contra)) ls then
blanchet@36491
   733
          first_pass (proof, contra |>> cons l ||> cons step)
blanchet@36402
   734
        else
blanchet@36491
   735
          first_pass (proof, contra) |>> cons step
blanchet@36402
   736
      | first_pass _ = raise Fail "malformed proof"
blanchet@36402
   737
    val (proof_top, (contra_ls, contra_proof)) =
blanchet@36402
   738
      first_pass (proof, (concl_ls, []))
blanchet@36402
   739
    val backpatch_label = the_default ([], []) oo AList.lookup (op =) o fst
blanchet@36402
   740
    fun backpatch_labels patches ls =
blanchet@36402
   741
      fold merge_fact_sets (map (backpatch_label patches) ls) ([], [])
blanchet@36402
   742
    fun second_pass end_qs ([], assums, patches) =
blanchet@36402
   743
        ([Have (end_qs, no_label,
blanchet@36402
   744
                if length assums < length concl_ls then
blanchet@36491
   745
                  clause_for_literals thy (map (negate_term thy o fst) assums)
blanchet@36402
   746
                else
blanchet@36402
   747
                  concl_t,
blanchet@36564
   748
                ByMetis (backpatch_labels patches (map snd assums)))], patches)
blanchet@36402
   749
      | second_pass end_qs (Assume (l, t) :: proof, assums, patches) =
blanchet@36402
   750
        second_pass end_qs (proof, (t, l) :: assums, patches)
blanchet@36564
   751
      | second_pass end_qs (Have (qs, l, t, ByMetis (ls, ss)) :: proof, assums,
blanchet@36402
   752
                            patches) =
blanchet@36402
   753
        if member (op =) (snd (snd patches)) l andalso
blanchet@36402
   754
           not (AList.defined (op =) (fst patches) l) then
blanchet@36402
   755
          second_pass end_qs (proof, assums, patches ||> apsnd (append ls))
blanchet@36402
   756
        else
blanchet@36402
   757
          (case List.partition (member (op =) contra_ls) ls of
blanchet@36402
   758
             ([contra_l], co_ls) =>
blanchet@36402
   759
             if no_show qs then
blanchet@36402
   760
               second_pass end_qs
blanchet@36402
   761
                           (proof, assums,
blanchet@36402
   762
                            patches |>> cons (contra_l, (l :: co_ls, ss)))
blanchet@36402
   763
               |>> cons (if member (op =) (fst (snd patches)) l then
blanchet@36491
   764
                           Assume (l, negate_term thy t)
blanchet@36402
   765
                         else
blanchet@36491
   766
                           Have (qs, l, negate_term thy t,
blanchet@36564
   767
                                 ByMetis (backpatch_label patches l)))
blanchet@36402
   768
             else
blanchet@36402
   769
               second_pass end_qs (proof, assums,
blanchet@36402
   770
                                   patches |>> cons (contra_l, (co_ls, ss)))
blanchet@36402
   771
           | (contra_ls as _ :: _, co_ls) =>
blanchet@36402
   772
             let
blanchet@36402
   773
               val proofs =
blanchet@36402
   774
                 map_filter
blanchet@36402
   775
                     (fn l =>
blanchet@36402
   776
                         if member (op =) concl_ls l then
blanchet@36402
   777
                           NONE
blanchet@36402
   778
                         else
blanchet@36402
   779
                           let
blanchet@36402
   780
                             val drop_ls = filter (curry (op <>) l) contra_ls
blanchet@36402
   781
                           in
blanchet@36402
   782
                             second_pass []
blanchet@36402
   783
                                 (proof, assums,
blanchet@36402
   784
                                  patches ||> apfst (insert (op =) l)
blanchet@36402
   785
                                          ||> apsnd (union (op =) drop_ls))
blanchet@36402
   786
                             |> fst |> SOME
blanchet@36402
   787
                           end) contra_ls
blanchet@36402
   788
               val facts = (co_ls, [])
blanchet@36402
   789
             in
blanchet@36402
   790
               (case join_proofs proofs of
blanchet@36402
   791
                  SOME (l, t, proofs, proof_tail) =>
blanchet@36402
   792
                  Have (case_split_qualifiers proofs @
blanchet@36402
   793
                        (if null proof_tail then end_qs else []), l, t,
blanchet@36574
   794
                        smart_case_split proofs facts) :: proof_tail
blanchet@36402
   795
                | NONE =>
blanchet@36402
   796
                  [Have (case_split_qualifiers proofs @ end_qs, no_label,
blanchet@36574
   797
                         concl_t, smart_case_split proofs facts)],
blanchet@36402
   798
                patches)
blanchet@36402
   799
             end
blanchet@36402
   800
           | _ => raise Fail "malformed proof")
blanchet@36402
   801
       | second_pass _ _ = raise Fail "malformed proof"
blanchet@36486
   802
    val proof_bottom =
blanchet@36486
   803
      second_pass [Show] (contra_proof, [], ([], ([], []))) |> fst
blanchet@36402
   804
  in proof_top @ proof_bottom end
blanchet@36402
   805
blanchet@36402
   806
val kill_duplicate_assumptions_in_proof =
blanchet@36402
   807
  let
blanchet@36402
   808
    fun relabel_facts subst =
blanchet@36402
   809
      apfst (map (fn l => AList.lookup (op =) subst l |> the_default l))
blanchet@36491
   810
    fun do_step (step as Assume (l, t)) (proof, subst, assums) =
blanchet@36402
   811
        (case AList.lookup (op aconv) assums t of
blanchet@36402
   812
           SOME l' => (proof, (l', l) :: subst, assums)
blanchet@36491
   813
         | NONE => (step :: proof, subst, (t, l) :: assums))
blanchet@36402
   814
      | do_step (Have (qs, l, t, by)) (proof, subst, assums) =
blanchet@36402
   815
        (Have (qs, l, t,
blanchet@36402
   816
               case by of
blanchet@36564
   817
                 ByMetis facts => ByMetis (relabel_facts subst facts)
blanchet@36402
   818
               | CaseSplit (proofs, facts) =>
blanchet@36402
   819
                 CaseSplit (map do_proof proofs, relabel_facts subst facts)) ::
blanchet@36402
   820
         proof, subst, assums)
blanchet@36491
   821
      | do_step step (proof, subst, assums) = (step :: proof, subst, assums)
blanchet@36402
   822
    and do_proof proof = fold do_step proof ([], [], []) |> #1 |> rev
blanchet@36402
   823
  in do_proof end
blanchet@36402
   824
blanchet@36402
   825
val then_chain_proof =
blanchet@36402
   826
  let
blanchet@36402
   827
    fun aux _ [] = []
blanchet@36491
   828
      | aux _ ((step as Assume (l, _)) :: proof) = step :: aux l proof
blanchet@36402
   829
      | aux l' (Have (qs, l, t, by) :: proof) =
blanchet@36402
   830
        (case by of
blanchet@36564
   831
           ByMetis (ls, ss) =>
blanchet@36402
   832
           Have (if member (op =) ls l' then
blanchet@36402
   833
                   (Then :: qs, l, t,
blanchet@36564
   834
                    ByMetis (filter_out (curry (op =) l') ls, ss))
blanchet@36402
   835
                 else
blanchet@36564
   836
                   (qs, l, t, ByMetis (ls, ss)))
blanchet@36402
   837
         | CaseSplit (proofs, facts) =>
blanchet@36402
   838
           Have (qs, l, t, CaseSplit (map (aux no_label) proofs, facts))) ::
blanchet@36402
   839
        aux l proof
blanchet@36491
   840
      | aux _ (step :: proof) = step :: aux no_label proof
blanchet@36402
   841
  in aux no_label end
blanchet@36402
   842
blanchet@36402
   843
fun kill_useless_labels_in_proof proof =
blanchet@36402
   844
  let
blanchet@36556
   845
    val used_ls = used_labels_of proof
blanchet@36402
   846
    fun do_label l = if member (op =) used_ls l then l else no_label
blanchet@36556
   847
    fun do_step (Assume (l, t)) = Assume (do_label l, t)
blanchet@36556
   848
      | do_step (Have (qs, l, t, by)) =
blanchet@36402
   849
        Have (qs, do_label l, t,
blanchet@36402
   850
              case by of
blanchet@36402
   851
                CaseSplit (proofs, facts) =>
blanchet@36556
   852
                CaseSplit (map (map do_step) proofs, facts)
blanchet@36402
   853
              | _ => by)
blanchet@36556
   854
      | do_step step = step
blanchet@36556
   855
  in map do_step proof end
blanchet@36402
   856
blanchet@36402
   857
fun prefix_for_depth n = replicate_string (n + 1)
blanchet@36402
   858
blanchet@36402
   859
val relabel_proof =
blanchet@36402
   860
  let
blanchet@36402
   861
    fun aux _ _ _ [] = []
blanchet@36402
   862
      | aux subst depth (next_assum, next_fact) (Assume (l, t) :: proof) =
blanchet@36402
   863
        if l = no_label then
blanchet@36402
   864
          Assume (l, t) :: aux subst depth (next_assum, next_fact) proof
blanchet@36402
   865
        else
blanchet@36402
   866
          let val l' = (prefix_for_depth depth assum_prefix, next_assum) in
blanchet@36402
   867
            Assume (l', t) ::
blanchet@36402
   868
            aux ((l, l') :: subst) depth (next_assum + 1, next_fact) proof
blanchet@36402
   869
          end
blanchet@36402
   870
      | aux subst depth (next_assum, next_fact) (Have (qs, l, t, by) :: proof) =
blanchet@36402
   871
        let
blanchet@36402
   872
          val (l', subst, next_fact) =
blanchet@36402
   873
            if l = no_label then
blanchet@36402
   874
              (l, subst, next_fact)
blanchet@36402
   875
            else
blanchet@36402
   876
              let
blanchet@36402
   877
                val l' = (prefix_for_depth depth fact_prefix, next_fact)
blanchet@36402
   878
              in (l', (l, l') :: subst, next_fact + 1) end
blanchet@36570
   879
          val relabel_facts =
blanchet@36570
   880
            apfst (map (fn l =>
blanchet@36570
   881
                           case AList.lookup (op =) subst l of
blanchet@36570
   882
                             SOME l' => l'
blanchet@36570
   883
                           | NONE => raise Fail ("unknown label " ^
blanchet@36570
   884
                                                 quote (string_for_label l))))
blanchet@36402
   885
          val by =
blanchet@36402
   886
            case by of
blanchet@36564
   887
              ByMetis facts => ByMetis (relabel_facts facts)
blanchet@36402
   888
            | CaseSplit (proofs, facts) =>
blanchet@36402
   889
              CaseSplit (map (aux subst (depth + 1) (1, 1)) proofs,
blanchet@36402
   890
                         relabel_facts facts)
blanchet@36402
   891
        in
blanchet@36402
   892
          Have (qs, l', t, by) ::
blanchet@36402
   893
          aux subst depth (next_assum, next_fact) proof
blanchet@36402
   894
        end
blanchet@36491
   895
      | aux subst depth nextp (step :: proof) =
blanchet@36491
   896
        step :: aux subst depth nextp proof
blanchet@36402
   897
  in aux [] 0 (1, 1) end
blanchet@36402
   898
blanchet@36488
   899
fun string_for_proof ctxt i n =
blanchet@36402
   900
  let
blanchet@36478
   901
    fun fix_print_mode f =
blanchet@36478
   902
      PrintMode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@36478
   903
                      (print_mode_value ())) f
blanchet@36402
   904
    fun do_indent ind = replicate_string (ind * indent_size) " "
blanchet@36478
   905
    fun do_free (s, T) =
blanchet@36478
   906
      maybe_quote s ^ " :: " ^
blanchet@36478
   907
      maybe_quote (fix_print_mode (Syntax.string_of_typ ctxt) T)
blanchet@36570
   908
    fun do_label l = if l = no_label then "" else string_for_label l ^ ": "
blanchet@36402
   909
    fun do_have qs =
blanchet@36402
   910
      (if member (op =) qs Moreover then "moreover " else "") ^
blanchet@36402
   911
      (if member (op =) qs Ultimately then "ultimately " else "") ^
blanchet@36402
   912
      (if member (op =) qs Then then
blanchet@36402
   913
         if member (op =) qs Show then "thus" else "hence"
blanchet@36402
   914
       else
blanchet@36402
   915
         if member (op =) qs Show then "show" else "have")
blanchet@36478
   916
    val do_term = maybe_quote o fix_print_mode (Syntax.string_of_term ctxt)
blanchet@36570
   917
    fun do_facts (ls, ss) =
blanchet@36570
   918
      let
blanchet@36570
   919
        val ls = ls |> sort_distinct (prod_ord string_ord int_ord)
blanchet@36570
   920
        val ss = ss |> sort_distinct string_ord
blanchet@36570
   921
      in metis_command 1 1 (map string_for_label ls @ ss) end
blanchet@36478
   922
    and do_step ind (Fix xs) =
blanchet@36478
   923
        do_indent ind ^ "fix " ^ space_implode " and " (map do_free xs) ^ "\n"
blanchet@36486
   924
      | do_step ind (Let (t1, t2)) =
blanchet@36486
   925
        do_indent ind ^ "let " ^ do_term t1 ^ " = " ^ do_term t2 ^ "\n"
blanchet@36402
   926
      | do_step ind (Assume (l, t)) =
blanchet@36402
   927
        do_indent ind ^ "assume " ^ do_label l ^ do_term t ^ "\n"
blanchet@36564
   928
      | do_step ind (Have (qs, l, t, ByMetis facts)) =
blanchet@36402
   929
        do_indent ind ^ do_have qs ^ " " ^
blanchet@36479
   930
        do_label l ^ do_term t ^ " " ^ do_facts facts ^ "\n"
blanchet@36402
   931
      | do_step ind (Have (qs, l, t, CaseSplit (proofs, facts))) =
blanchet@36402
   932
        space_implode (do_indent ind ^ "moreover\n")
blanchet@36402
   933
                      (map (do_block ind) proofs) ^
blanchet@36479
   934
        do_indent ind ^ do_have qs ^ " " ^ do_label l ^ do_term t ^ " " ^
blanchet@36478
   935
        do_facts facts ^ "\n"
blanchet@36402
   936
    and do_steps prefix suffix ind steps =
blanchet@36402
   937
      let val s = implode (map (do_step ind) steps) in
blanchet@36402
   938
        replicate_string (ind * indent_size - size prefix) " " ^ prefix ^
blanchet@36402
   939
        String.extract (s, ind * indent_size,
blanchet@36402
   940
                        SOME (size s - ind * indent_size - 1)) ^
blanchet@36402
   941
        suffix ^ "\n"
blanchet@36402
   942
      end
blanchet@36402
   943
    and do_block ind proof = do_steps "{ " " }" (ind + 1) proof
blanchet@36564
   944
    (* One-step proofs are pointless; better use the Metis one-liner
blanchet@36564
   945
       directly. *)
blanchet@36564
   946
    and do_proof [Have (_, _, _, ByMetis _)] = ""
blanchet@36564
   947
      | do_proof proof =
blanchet@36480
   948
        (if i <> 1 then "prefer " ^ string_of_int i ^ "\n" else "") ^
blanchet@36480
   949
        do_indent 0 ^ "proof -\n" ^
blanchet@36480
   950
        do_steps "" "" 1 proof ^
blanchet@36480
   951
        do_indent 0 ^ (if n <> 1 then "next" else "qed") ^ "\n"
blanchet@36488
   952
  in do_proof end
blanchet@36402
   953
krauss@36606
   954
fun isar_proof_text (pool, debug, shrink_factor, ctxt, conjecture_shape)
krauss@36606
   955
                    (minimize_command, atp_proof, thm_names, goal, i) =
blanchet@36402
   956
  let
blanchet@36402
   957
    val thy = ProofContext.theory_of ctxt
krauss@36606
   958
    val (frees, hyp_ts, concl_t) = strip_subgoal goal i
blanchet@36402
   959
    val n = Logic.count_prems (prop_of goal)
blanchet@36223
   960
    val (one_line_proof, lemma_names) =
blanchet@36402
   961
      metis_proof_text (minimize_command, atp_proof, thm_names, goal, i)
blanchet@36283
   962
    fun isar_proof_for () =
krauss@36606
   963
      case proof_from_atp_proof pool ctxt shrink_factor atp_proof
krauss@36606
   964
                                conjecture_shape thm_names frees
blanchet@36491
   965
           |> redirect_proof thy conjecture_shape hyp_ts concl_t
blanchet@36402
   966
           |> kill_duplicate_assumptions_in_proof
blanchet@36402
   967
           |> then_chain_proof
blanchet@36402
   968
           |> kill_useless_labels_in_proof
blanchet@36402
   969
           |> relabel_proof
blanchet@36488
   970
           |> string_for_proof ctxt i n of
blanchet@36283
   971
        "" => ""
blanchet@36402
   972
      | proof => "\nStructured proof:\n" ^ Markup.markup Markup.sendback proof
blanchet@35868
   973
    val isar_proof =
blanchet@36402
   974
      if debug then
blanchet@36283
   975
        isar_proof_for ()
blanchet@36283
   976
      else
blanchet@36283
   977
        try isar_proof_for ()
blanchet@36287
   978
        |> the_default "Warning: The Isar proof construction failed.\n"
blanchet@36283
   979
  in (one_line_proof ^ isar_proof, lemma_names) end
paulson@21978
   980
blanchet@36557
   981
fun proof_text isar_proof isar_params other_params =
blanchet@36557
   982
  (if isar_proof then isar_proof_text isar_params else metis_proof_text)
blanchet@36557
   983
      other_params
blanchet@36223
   984
immler@31038
   985
end;