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