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