src/HOL/Tools/Sledgehammer/sledgehammer_proof_reconstruct.ML
author blanchet
Fri Apr 23 13:16:50 2010 +0200 (2010-04-23)
changeset 36369 d2cd0d04b8e6
parent 36293 e6db3ba0b61d
child 36392 c00c57850eb7
permissions -rw-r--r--
handle ATP proof delimiters in a cleaner, more extensible fashion
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
paulson@21978
     3
wenzelm@33310
     4
Transfer of proofs from external provers.
wenzelm@33310
     5
*)
wenzelm@33310
     6
blanchet@35826
     7
signature SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@24425
     8
sig
blanchet@36281
     9
  type minimize_command = string list -> string
blanchet@36281
    10
paulson@25492
    11
  val chained_hint: string
paulson@24425
    12
  val invert_const: string -> string
paulson@24425
    13
  val invert_type_const: string -> string
wenzelm@33243
    14
  val num_typargs: theory -> string -> int
paulson@24425
    15
  val make_tvar: string -> typ
paulson@24425
    16
  val strip_prefix: string -> string -> string option
blanchet@36063
    17
  val metis_line: int -> int -> string list -> string
blanchet@36223
    18
  val metis_proof_text:
blanchet@36287
    19
    minimize_command * string * string vector * thm * int
blanchet@36281
    20
    -> string * string list
blanchet@36223
    21
  val isar_proof_text:
blanchet@36287
    22
    bool -> int -> bool -> Proof.context
blanchet@36287
    23
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    24
    -> string * string list
blanchet@36223
    25
  val proof_text:
blanchet@36288
    26
    bool -> bool -> int -> bool -> Proof.context
blanchet@36287
    27
    -> minimize_command * string * string vector * thm * int
blanchet@36287
    28
    -> string * string list
paulson@24425
    29
end;
paulson@21978
    30
blanchet@35826
    31
structure Sledgehammer_Proof_Reconstruct : SLEDGEHAMMER_PROOF_RECONSTRUCT =
paulson@21978
    32
struct
paulson@21978
    33
blanchet@35865
    34
open Sledgehammer_FOL_Clause
blanchet@35865
    35
open Sledgehammer_Fact_Preprocessor
paulson@21978
    36
blanchet@36281
    37
type minimize_command = string list -> string
blanchet@36281
    38
blanchet@35865
    39
val trace_proof_path = Path.basic "atp_trace";
blanchet@35865
    40
blanchet@35865
    41
fun trace_proof_msg f =
blanchet@35865
    42
  if !trace then File.append (File.tmp_path trace_proof_path) (f ()) else ();
paulson@21978
    43
wenzelm@32091
    44
fun string_of_thm ctxt = PrintMode.setmp [] (Display.string_of_thm ctxt);
paulson@26333
    45
blanchet@36291
    46
fun is_ident_char c = Char.isAlphaNum c orelse c = #"_"
blanchet@36291
    47
blanchet@36291
    48
fun is_axiom thm_names line_no = line_no <= Vector.length thm_names
blanchet@36291
    49
paulson@21978
    50
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    51
blanchet@36291
    52
(* Syntax trees, either term list or formulae *)
paulson@21978
    53
datatype stree = Int of int | Br of string * stree list;
paulson@21978
    54
paulson@21978
    55
fun atom x = Br(x,[]);
paulson@21978
    56
paulson@21978
    57
fun scons (x,y) = Br("cons", [x,y]);
wenzelm@30190
    58
val listof = List.foldl scons (atom "nil");
paulson@21978
    59
paulson@21978
    60
(*Strings enclosed in single quotes, e.g. filenames*)
blanchet@36291
    61
val quoted = $$ "'" |-- Scan.repeat (~$$ "'") --| $$ "'" >> implode;
paulson@21978
    62
paulson@21978
    63
(*Intended for $true and $false*)
paulson@21978
    64
fun tf s = "c_" ^ str (Char.toUpper (String.sub(s,0))) ^ String.extract(s,1,NONE);
blanchet@36291
    65
val truefalse = $$ "$" |-- Symbol.scan_id >> (atom o tf);
paulson@21978
    66
paulson@21978
    67
(*Integer constants, typically proof line numbers*)
paulson@21978
    68
fun is_digit s = Char.isDigit (String.sub(s,0));
wenzelm@33035
    69
val integer = Scan.many1 is_digit >> (the o Int.fromString o implode);
paulson@21978
    70
blanchet@36369
    71
(* needed for SPASS's output format *)
blanchet@36293
    72
fun fix_symbol "equal" = "c_equal"
blanchet@36293
    73
  | fix_symbol s = s
blanchet@36291
    74
paulson@21978
    75
(*Generalized FO terms, which include filenames, numbers, etc.*)
blanchet@36291
    76
fun term x = (quoted >> atom || integer >> Int || truefalse
blanchet@36293
    77
              || (Symbol.scan_id >> fix_symbol)
blanchet@36293
    78
                 -- Scan.optional ($$ "(" |-- terms --| $$ ")") [] >> Br
blanchet@36291
    79
              || $$ "(" |-- term --| $$ ")"
blanchet@36291
    80
              || $$ "[" |-- Scan.optional terms [] --| $$ "]" >> listof) x
blanchet@36291
    81
and terms x = (term ::: Scan.repeat ($$ "," |-- term)) x
paulson@21978
    82
blanchet@36291
    83
fun negate t = Br ("c_Not", [t])
blanchet@36291
    84
fun equate t1 t2 = Br ("c_equal", [t1, t2]);
paulson@21978
    85
paulson@21978
    86
(*Apply equal or not-equal to a term*)
paulson@21978
    87
fun syn_equal (t, NONE) = t
blanchet@36291
    88
  | syn_equal (t1, SOME (NONE, t2)) = equate t1 t2
blanchet@36291
    89
  | syn_equal (t1, SOME (SOME _, t2)) = negate (equate t1 t2)
paulson@21978
    90
paulson@21978
    91
(*Literals can involve negation, = and !=.*)
blanchet@36291
    92
fun literal x =
blanchet@36291
    93
  ($$ "~" |-- literal >> negate
blanchet@36291
    94
   || (term -- Scan.option (Scan.option ($$ "!") --| $$ "=" -- term)
blanchet@36291
    95
       >> syn_equal)) x
paulson@21978
    96
blanchet@36291
    97
val literals = literal ::: Scan.repeat ($$ "|" |-- literal);
paulson@21978
    98
paulson@21978
    99
(*Clause: a list of literals separated by the disjunction sign*)
blanchet@36291
   100
val clause = $$ "(" |-- literals --| $$ ")" || Scan.single literal;
blanchet@36291
   101
blanchet@36291
   102
fun ints_of_stree (Int n) = cons n
blanchet@36291
   103
  | ints_of_stree (Br (_, ts)) = fold ints_of_stree ts
blanchet@36291
   104
blanchet@36291
   105
val tstp_annotations =
blanchet@36291
   106
  Scan.optional ($$ "," |-- term --| Scan.option ($$ "," |-- terms)
blanchet@36291
   107
                 >> (fn source => ints_of_stree source [])) []
blanchet@36291
   108
blanchet@36291
   109
fun retuple_tstp_line ((name, ts), deps) = (name, ts, deps)
paulson@21978
   110
blanchet@36291
   111
(* <cnf_annotated> ::= cnf(<name>, <formula_role>, <cnf_formula> <annotations>).
blanchet@36291
   112
   The <name> could be an identifier, but we assume integers. *)
blanchet@36291
   113
val parse_tstp_line =
blanchet@36291
   114
  (Scan.this_string "cnf" -- $$ "(") |-- integer --| $$ "," --| Symbol.scan_id
blanchet@36291
   115
   --| $$ "," -- clause -- tstp_annotations --| $$ ")" --| $$ "."
blanchet@36291
   116
  >> retuple_tstp_line
blanchet@36291
   117
blanchet@36291
   118
(**** PARSING OF SPASS OUTPUT ****)
blanchet@36291
   119
blanchet@36291
   120
val dot_name = integer --| $$ "." --| integer
paulson@21978
   121
blanchet@36291
   122
val spass_annotations =
blanchet@36291
   123
  Scan.optional ($$ ":" |-- Scan.repeat (dot_name --| Scan.option ($$ ","))) []
blanchet@36291
   124
blanchet@36291
   125
val starred_literal = literal --| Scan.repeat ($$ "*" || $$ " ")
blanchet@36291
   126
blanchet@36291
   127
val horn_clause =
blanchet@36291
   128
  Scan.repeat starred_literal --| $$ "-" --| $$ ">"
blanchet@36291
   129
  -- Scan.repeat starred_literal
blanchet@36291
   130
  >> (fn ([], []) => [atom (tf "false")]
blanchet@36291
   131
       | (clauses1, clauses2) => map negate clauses1 @ clauses2)
paulson@21978
   132
blanchet@36291
   133
fun retuple_spass_proof_line ((name, deps), ts) = (name, ts, deps)
blanchet@36291
   134
blanchet@36291
   135
(* Syntax: <name>[0:<inference><annotations>] || -> <cnf_formula> **. *)
blanchet@36291
   136
val parse_spass_proof_line =
blanchet@36291
   137
  integer --| $$ "[" --| $$ "0" --| $$ ":" --| Symbol.scan_id
blanchet@36291
   138
  -- spass_annotations --| $$ "]" --| $$ "|" --| $$ "|" -- horn_clause
blanchet@36291
   139
  --| $$ "."
blanchet@36291
   140
  >> retuple_spass_proof_line
blanchet@36291
   141
blanchet@36291
   142
val parse_proof_line = fst o (parse_tstp_line || parse_spass_proof_line)
paulson@21978
   143
paulson@21978
   144
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   145
paulson@21978
   146
exception STREE of stree;
paulson@21978
   147
paulson@21978
   148
(*If string s has the prefix s1, return the result of deleting it.*)
wenzelm@23139
   149
fun strip_prefix s1 s =
immler@31038
   150
  if String.isPrefix s1 s
blanchet@35865
   151
  then SOME (undo_ascii_of (String.extract (s, size s1, NONE)))
paulson@21978
   152
  else NONE;
paulson@21978
   153
paulson@21978
   154
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   155
val type_const_trans_table_inv =
blanchet@35865
   156
      Symtab.make (map swap (Symtab.dest type_const_trans_table));
paulson@21978
   157
paulson@21978
   158
fun invert_type_const c =
paulson@21978
   159
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   160
        SOME c' => c'
paulson@21978
   161
      | NONE => c;
paulson@21978
   162
blanchet@36285
   163
fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS);
blanchet@36285
   164
fun make_tparam s = TypeInfer.param 0 (s, HOLogic.typeS)
paulson@21978
   165
fun make_var (b,T) = Var((b,0),T);
paulson@21978
   166
paulson@21978
   167
(*Type variables are given the basic sort, HOL.type. Some will later be constrained
paulson@21978
   168
  by information from type literals, or by type inference.*)
paulson@21978
   169
fun type_of_stree t =
paulson@21978
   170
  case t of
paulson@21978
   171
      Int _ => raise STREE t
wenzelm@23139
   172
    | Br (a,ts) =>
paulson@21978
   173
        let val Ts = map type_of_stree ts
wenzelm@23139
   174
        in
blanchet@35865
   175
          case strip_prefix tconst_prefix a of
paulson@21978
   176
              SOME b => Type(invert_type_const b, Ts)
wenzelm@23139
   177
            | NONE =>
paulson@21978
   178
                if not (null ts) then raise STREE t  (*only tconsts have type arguments*)
wenzelm@23139
   179
                else
blanchet@35865
   180
                case strip_prefix tfree_prefix a of
paulson@21978
   181
                    SOME b => TFree("'" ^ b, HOLogic.typeS)
wenzelm@23139
   182
                  | NONE =>
blanchet@35865
   183
                case strip_prefix tvar_prefix a of
paulson@21978
   184
                    SOME b => make_tvar b
blanchet@36285
   185
                  | NONE => make_tparam a  (* Variable from the ATP, say "X1" *)
paulson@21978
   186
        end;
paulson@21978
   187
paulson@21978
   188
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   189
val const_trans_table_inv =
wenzelm@23139
   190
      Symtab.update ("fequal", "op =")
blanchet@35865
   191
        (Symtab.make (map swap (Symtab.dest const_trans_table)));
paulson@21978
   192
paulson@21978
   193
fun invert_const c =
paulson@21978
   194
    case Symtab.lookup const_trans_table_inv c of
paulson@21978
   195
        SOME c' => c'
paulson@21978
   196
      | NONE => c;
paulson@21978
   197
paulson@21978
   198
(*The number of type arguments of a constant, zero if it's monomorphic*)
paulson@21978
   199
fun num_typargs thy s = length (Sign.const_typargs thy (s, Sign.the_const_type thy s));
paulson@21978
   200
paulson@21978
   201
(*Generates a constant, given its type arguments*)
paulson@21978
   202
fun const_of thy (a,Ts) = Const(a, Sign.const_instance thy (a,Ts));
paulson@21978
   203
paulson@21978
   204
(*First-order translation. No types are known for variables. HOLogic.typeT should allow
paulson@21978
   205
  them to be inferred.*)
paulson@22428
   206
fun term_of_stree args thy t =
paulson@21978
   207
  case t of
paulson@21978
   208
      Int _ => raise STREE t
paulson@22428
   209
    | Br ("hBOOL",[t]) => term_of_stree [] thy t  (*ignore hBOOL*)
paulson@22428
   210
    | Br ("hAPP",[t,u]) => term_of_stree (u::args) thy t
wenzelm@23139
   211
    | Br (a,ts) =>
blanchet@35865
   212
        case strip_prefix const_prefix a of
wenzelm@23139
   213
            SOME "equal" =>
blanchet@35865
   214
              list_comb(Const (@{const_name "op ="}, HOLogic.typeT), List.map (term_of_stree [] thy) ts)
wenzelm@23139
   215
          | SOME b =>
paulson@21978
   216
              let val c = invert_const b
paulson@21978
   217
                  val nterms = length ts - num_typargs thy c
paulson@22428
   218
                  val us = List.map (term_of_stree [] thy) (List.take(ts,nterms) @ args)
paulson@22428
   219
                  (*Extra args from hAPP come AFTER any arguments given directly to the
paulson@22428
   220
                    constant.*)
paulson@21978
   221
                  val Ts = List.map type_of_stree (List.drop(ts,nterms))
paulson@21978
   222
              in  list_comb(const_of thy (c, Ts), us)  end
paulson@21978
   223
          | NONE => (*a variable, not a constant*)
paulson@21978
   224
              let val T = HOLogic.typeT
paulson@21978
   225
                  val opr = (*a Free variable is typically a Skolem function*)
blanchet@35865
   226
                    case strip_prefix fixed_var_prefix a of
paulson@21978
   227
                        SOME b => Free(b,T)
wenzelm@23139
   228
                      | NONE =>
blanchet@35865
   229
                    case strip_prefix schematic_var_prefix a of
paulson@21978
   230
                        SOME b => make_var (b,T)
blanchet@36291
   231
                      | NONE => make_var (a,T)  (* Variable from the ATP, say "X1" *)
paulson@23519
   232
              in  list_comb (opr, List.map (term_of_stree [] thy) (ts@args))  end;
paulson@21978
   233
wenzelm@23139
   234
(*Type class literal applied to a type. Returns triple of polarity, class, type.*)
paulson@21978
   235
fun constraint_of_stree pol (Br("c_Not",[t])) = constraint_of_stree (not pol) t
paulson@21978
   236
  | constraint_of_stree pol t = case t of
paulson@21978
   237
        Int _ => raise STREE t
wenzelm@23139
   238
      | Br (a,ts) =>
blanchet@35865
   239
            (case (strip_prefix class_prefix a, map type_of_stree ts) of
paulson@21978
   240
                 (SOME b, [T]) => (pol, b, T)
paulson@21978
   241
               | _ => raise STREE t);
paulson@21978
   242
paulson@21978
   243
(** Accumulate type constraints in a clause: negative type literals **)
paulson@21978
   244
paulson@21978
   245
fun addix (key,z)  = Vartab.map_default (key,[]) (cons z);
paulson@21978
   246
paulson@21978
   247
fun add_constraint ((false, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   248
  | add_constraint ((false, cl, TVar(ix,_)), vt) = addix (ix,cl) vt
paulson@21978
   249
  | add_constraint (_, vt) = vt;
paulson@21978
   250
paulson@21978
   251
(*False literals (which E includes in its proofs) are deleted*)
paulson@21978
   252
val nofalses = filter (not o equal HOLogic.false_const);
paulson@21978
   253
paulson@22491
   254
(*Final treatment of the list of "real" literals from a clause.*)
paulson@22491
   255
fun finish [] = HOLogic.true_const  (*No "real" literals means only type information*)
wenzelm@23139
   256
  | finish lits =
paulson@22491
   257
      case nofalses lits of
paulson@22491
   258
          [] => HOLogic.false_const  (*The empty clause, since we started with real literals*)
paulson@22491
   259
        | xs => foldr1 HOLogic.mk_disj (rev xs);
paulson@22491
   260
paulson@21978
   261
(*Accumulate sort constraints in vt, with "real" literals in lits.*)
wenzelm@32994
   262
fun lits_of_strees _ (vt, lits) [] = (vt, finish lits)
wenzelm@23139
   263
  | lits_of_strees ctxt (vt, lits) (t::ts) =
paulson@22012
   264
      lits_of_strees ctxt (add_constraint (constraint_of_stree true t, vt), lits) ts
wenzelm@23139
   265
      handle STREE _ =>
paulson@22428
   266
      lits_of_strees ctxt (vt, term_of_stree [] (ProofContext.theory_of ctxt) t :: lits) ts;
paulson@21978
   267
paulson@21978
   268
(*Update TVars/TFrees with detected sort constraints.*)
paulson@21978
   269
fun fix_sorts vt =
paulson@21978
   270
  let fun tysubst (Type (a, Ts)) = Type (a, map tysubst Ts)
wenzelm@33035
   271
        | tysubst (TVar (xi, s)) = TVar (xi, the_default s (Vartab.lookup vt xi))
wenzelm@33035
   272
        | tysubst (TFree (x, s)) = TFree (x, the_default s (Vartab.lookup vt (x, ~1)))
paulson@21978
   273
      fun tmsubst (Const (a, T)) = Const (a, tysubst T)
paulson@21978
   274
        | tmsubst (Free (a, T)) = Free (a, tysubst T)
paulson@21978
   275
        | tmsubst (Var (xi, T)) = Var (xi, tysubst T)
paulson@21978
   276
        | tmsubst (t as Bound _) = t
paulson@21978
   277
        | tmsubst (Abs (a, T, t)) = Abs (a, tysubst T, tmsubst t)
paulson@21978
   278
        | tmsubst (t $ u) = tmsubst t $ tmsubst u;
blanchet@36285
   279
  in not (Vartab.is_empty vt) ? tmsubst end;
paulson@21978
   280
paulson@21978
   281
(*Interpret a list of syntax trees as a clause, given by "real" literals and sort constraints.
paulson@21978
   282
  vt0 holds the initial sort constraints, from the conjecture clauses.*)
paulson@23519
   283
fun clause_of_strees ctxt vt0 ts =
wenzelm@22728
   284
  let val (vt, dt) = lits_of_strees ctxt (vt0,[]) ts in
wenzelm@24680
   285
    singleton (Syntax.check_terms ctxt) (TypeInfer.constrain HOLogic.boolT (fix_sorts vt dt))
blanchet@36285
   286
  end
paulson@21978
   287
wenzelm@29268
   288
fun gen_all_vars t = fold_rev Logic.all (OldTerm.term_vars t) t;
paulson@21978
   289
blanchet@36291
   290
fun decode_proof_step vt0 (name, ts, deps) ctxt =
blanchet@36291
   291
  let val cl = clause_of_strees ctxt vt0 ts in
blanchet@36291
   292
    ((name, cl, deps), fold Variable.declare_term (OldTerm.term_frees cl) ctxt)
blanchet@36291
   293
  end
paulson@21978
   294
paulson@21978
   295
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit clauses. **)
paulson@21978
   296
paulson@21978
   297
fun add_tfree_constraint ((true, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   298
  | add_tfree_constraint (_, vt) = vt;
paulson@21978
   299
paulson@21978
   300
fun tfree_constraints_of_clauses vt [] = vt
wenzelm@23139
   301
  | tfree_constraints_of_clauses vt ([lit]::tss) =
paulson@21978
   302
      (tfree_constraints_of_clauses (add_tfree_constraint (constraint_of_stree true lit, vt)) tss
paulson@21978
   303
       handle STREE _ => (*not a positive type constraint: ignore*)
paulson@21978
   304
       tfree_constraints_of_clauses vt tss)
paulson@21978
   305
  | tfree_constraints_of_clauses vt (_::tss) = tfree_constraints_of_clauses vt tss;
paulson@21978
   306
paulson@21978
   307
paulson@21978
   308
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   309
blanchet@36291
   310
fun decode_proof_steps ctxt tuples =
blanchet@36291
   311
  let val vt0 = tfree_constraints_of_clauses Vartab.empty (map #2 tuples) in
blanchet@36291
   312
    #1 (fold_map (decode_proof_step vt0) tuples ctxt)
blanchet@36291
   313
  end
paulson@21978
   314
paulson@23519
   315
(** Finding a matching assumption. The literals may be permuted, and variable names
blanchet@36293
   316
    may disagree. We must try all combinations of literals (quadratic!) and
blanchet@36293
   317
    match the variable names consistently. **)
paulson@23519
   318
blanchet@35865
   319
fun strip_alls_aux n (Const(@{const_name all}, _)$Abs(a,T,t))  =
paulson@23519
   320
      strip_alls_aux (n+1) (subst_bound (Var ((a,n), T), t))
paulson@23519
   321
  | strip_alls_aux _ t  =  t;
paulson@23519
   322
paulson@23519
   323
val strip_alls = strip_alls_aux 0;
paulson@23519
   324
blanchet@36293
   325
exception MATCH_LITERAL of unit
paulson@22012
   326
blanchet@36293
   327
(* Remark 1: Ignore types. They are not to be trusted.
blanchet@36293
   328
   Remark 2: Ignore order of arguments for equality. SPASS sometimes swaps
blanchet@36293
   329
   them for no apparent reason. *)
blanchet@36293
   330
fun match_literal (Const (@{const_name "op ="}, _) $ t1 $ u1)
blanchet@36293
   331
                  (Const (@{const_name "op ="}, _) $ t2 $ u2) env =
blanchet@36293
   332
    (env |> match_literal t1 t2 |> match_literal u1 u2
blanchet@36293
   333
     handle MATCH_LITERAL () =>
blanchet@36293
   334
            env |> match_literal t1 u2 |> match_literal u1 t2)
blanchet@36293
   335
  | match_literal (t1 $ u1) (t2 $ u2) env =
blanchet@36293
   336
    env |> match_literal t1 t2 |> match_literal u1 u2
immler@31038
   337
  | match_literal (Abs (_,_,t1)) (Abs (_,_,t2)) env =
blanchet@36293
   338
    match_literal t1 t2 env
immler@31038
   339
  | match_literal (Bound i1) (Bound i2) env =
blanchet@36293
   340
    if i1=i2 then env else raise MATCH_LITERAL ()
immler@31038
   341
  | match_literal (Const(a1,_)) (Const(a2,_)) env =
blanchet@36293
   342
    if a1=a2 then env else raise MATCH_LITERAL ()
immler@31038
   343
  | match_literal (Free(a1,_)) (Free(a2,_)) env =
blanchet@36293
   344
    if a1=a2 then env else raise MATCH_LITERAL ()
paulson@23519
   345
  | match_literal (Var(ix1,_)) (Var(ix2,_)) env = insert (op =) (ix1,ix2) env
blanchet@36293
   346
  | match_literal _ _ _ = raise MATCH_LITERAL ()
paulson@23519
   347
blanchet@36293
   348
(* Checking that all variable associations are unique. The list "env" contains
blanchet@36293
   349
   no repetitions, but does it contain say (x, y) and (y, y)? *)
immler@31038
   350
fun good env =
paulson@23519
   351
  let val (xs,ys) = ListPair.unzip env
paulson@23519
   352
  in  not (has_duplicates (op=) xs orelse has_duplicates (op=) ys)  end;
paulson@23519
   353
paulson@23519
   354
(*Match one list of literals against another, ignoring types and the order of
paulson@23519
   355
  literals. Sorting is unreliable because we don't have types or variable names.*)
paulson@23519
   356
fun matches_aux _ [] [] = true
paulson@23519
   357
  | matches_aux env (lit::lits) ts =
paulson@23519
   358
      let fun match1 us [] = false
paulson@23519
   359
            | match1 us (t::ts) =
paulson@23519
   360
                let val env' = match_literal lit t env
immler@31038
   361
                in  (good env' andalso matches_aux env' lits (us@ts)) orelse
immler@31038
   362
                    match1 (t::us) ts
paulson@23519
   363
                end
blanchet@36293
   364
                handle MATCH_LITERAL () => match1 (t::us) ts
immler@31038
   365
      in  match1 [] ts  end;
paulson@23519
   366
paulson@23519
   367
(*Is this length test useful?*)
immler@31038
   368
fun matches (lits1,lits2) =
immler@31038
   369
  length lits1 = length lits2  andalso
paulson@23519
   370
  matches_aux [] (map Envir.eta_contract lits1) (map Envir.eta_contract lits2);
paulson@21999
   371
paulson@21999
   372
fun permuted_clause t =
paulson@24958
   373
  let val lits = HOLogic.disjuncts t
paulson@21999
   374
      fun perm [] = NONE
wenzelm@23139
   375
        | perm (ctm::ctms) =
paulson@24958
   376
            if matches (lits, HOLogic.disjuncts (HOLogic.dest_Trueprop (strip_alls ctm)))
paulson@23519
   377
            then SOME ctm else perm ctms
paulson@21999
   378
  in perm end;
paulson@21999
   379
paulson@21999
   380
(*ctms is a list of conjecture clauses as yielded by Isabelle. Those returned by the
paulson@21999
   381
  ATP may have their literals reordered.*)
blanchet@36064
   382
fun isar_proof_body ctxt sorts ctms =
blanchet@35869
   383
  let
blanchet@35869
   384
    val _ = trace_proof_msg (K "\n\nisar_proof_body: start\n")
blanchet@36064
   385
    val string_of_term = 
blanchet@36064
   386
      PrintMode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@36064
   387
                              (print_mode_value ()))
blanchet@36064
   388
                      (Syntax.string_of_term ctxt)
blanchet@35966
   389
    fun have_or_show "show" _ = "  show \""
blanchet@35966
   390
      | have_or_show have lname = "  " ^ have ^ " " ^ lname ^ ": \""
blanchet@35869
   391
    fun do_line _ (lname, t, []) =
blanchet@36285
   392
       (* No depedencies: it's a conjecture clause, with no proof. *)
blanchet@35869
   393
       (case permuted_clause t ctms of
blanchet@35966
   394
          SOME u => "  assume " ^ lname ^ ": \"" ^ string_of_term u ^ "\"\n"
blanchet@35869
   395
        | NONE => raise TERM ("Sledgehammer_Proof_Reconstruct.isar_proof_body",
blanchet@35869
   396
                              [t]))
blanchet@35869
   397
      | do_line have (lname, t, deps) =
blanchet@35869
   398
        have_or_show have lname ^
blanchet@35869
   399
        string_of_term (gen_all_vars (HOLogic.mk_Trueprop t)) ^
blanchet@35966
   400
        "\"\n    by (metis " ^ space_implode " " deps ^ ")\n"
blanchet@35869
   401
    fun do_lines [(lname, t, deps)] = [do_line "show" (lname, t, deps)]
blanchet@35869
   402
      | do_lines ((lname, t, deps) :: lines) =
blanchet@35869
   403
        do_line "have" (lname, t, deps) :: do_lines lines
blanchet@36064
   404
  in setmp_CRITICAL show_sorts sorts do_lines end;
paulson@21978
   405
blanchet@35869
   406
fun unequal t (_, t', _) = not (t aconv t');
paulson@21978
   407
paulson@22491
   408
(*No "real" literals means only type information*)
paulson@23519
   409
fun eq_types t = t aconv HOLogic.true_const;
paulson@21978
   410
paulson@22731
   411
fun replace_dep (old:int, new) dep = if dep=old then new else [dep];
paulson@21978
   412
wenzelm@23139
   413
fun replace_deps (old:int, new) (lno, t, deps) =
haftmann@33042
   414
      (lno, t, List.foldl (uncurry (union (op =))) [] (map (replace_dep (old, new)) deps));
paulson@21978
   415
paulson@22491
   416
(*Discard axioms; consolidate adjacent lines that prove the same clause, since they differ
paulson@22491
   417
  only in type information.*)
blanchet@36291
   418
fun add_proof_line thm_names (lno, t, []) lines =
blanchet@36291
   419
      (* No dependencies: axiom or conjecture clause *)
blanchet@36291
   420
      if is_axiom thm_names lno then
blanchet@36291
   421
        (* Axioms are not proof lines *)
blanchet@36291
   422
        if eq_types t then
blanchet@36291
   423
          (* Must be clsrel/clsarity: type information, so delete refs to it *)
blanchet@36291
   424
          map (replace_deps (lno, [])) lines
blanchet@36291
   425
        else
blanchet@36291
   426
          (case take_prefix (unequal t) lines of
blanchet@36291
   427
             (_,[]) => lines                  (*no repetition of proof line*)
blanchet@36291
   428
           | (pre, (lno', _, _) :: post) =>   (*repetition: replace later line by earlier one*)
blanchet@36291
   429
               pre @ map (replace_deps (lno', [lno])) post)
paulson@22470
   430
      else
blanchet@36291
   431
        (lno, t, []) :: lines
blanchet@36291
   432
  | add_proof_line _ (lno, t, deps) lines =
paulson@22491
   433
      if eq_types t then (lno, t, deps) :: lines
paulson@22491
   434
      (*Type information will be deleted later; skip repetition test.*)
paulson@22491
   435
      else (*FIXME: Doesn't this code risk conflating proofs involving different types??*)
blanchet@35869
   436
      case take_prefix (unequal t) lines of
paulson@22044
   437
         (_,[]) => (lno, t, deps) :: lines  (*no repetition of proof line*)
wenzelm@32994
   438
       | (pre, (lno', t', _) :: post) =>
paulson@22044
   439
           (lno, t', deps) ::               (*repetition: replace later line by earlier one*)
paulson@22044
   440
           (pre @ map (replace_deps (lno', [lno])) post);
paulson@22044
   441
paulson@22470
   442
(*Recursively delete empty lines (type information) from the proof.*)
paulson@22470
   443
fun add_nonnull_prfline ((lno, t, []), lines) = (*no dependencies, so a conjecture clause*)
paulson@22491
   444
     if eq_types t (*must be type information, tfree_tcs, clsrel, clsarity: delete refs to it*)
wenzelm@23139
   445
     then delete_dep lno lines
wenzelm@23139
   446
     else (lno, t, []) :: lines
paulson@22470
   447
  | add_nonnull_prfline ((lno, t, deps), lines) = (lno, t, deps) :: lines
wenzelm@30190
   448
and delete_dep lno lines = List.foldr add_nonnull_prfline [] (map (replace_deps (lno, [])) lines);
paulson@22470
   449
blanchet@35865
   450
fun bad_free (Free (a,_)) = String.isPrefix skolem_prefix a
paulson@22731
   451
  | bad_free _ = false;
paulson@22731
   452
wenzelm@23139
   453
(*TVars are forbidden in goals. Also, we don't want lines with <2 dependencies.
paulson@22491
   454
  To further compress proofs, setting modulus:=n deletes every nth line, and nlines
paulson@22491
   455
  counts the number of proof lines processed so far.
paulson@22491
   456
  Deleted lines are replaced by their own dependencies. Note that the "add_nonnull_prfline"
paulson@22044
   457
  phase may delete some dependencies, hence this phase comes later.*)
blanchet@36064
   458
fun add_wanted_prfline ctxt _ ((lno, t, []), (nlines, lines)) =
paulson@22491
   459
      (nlines, (lno, t, []) :: lines)   (*conjecture clauses must be kept*)
blanchet@36064
   460
  | add_wanted_prfline ctxt modulus ((lno, t, deps), (nlines, lines)) =
wenzelm@29272
   461
      if eq_types t orelse not (null (Term.add_tvars t [])) orelse
wenzelm@29268
   462
         exists_subterm bad_free t orelse
paulson@24937
   463
         (not (null lines) andalso   (*final line can't be deleted for these reasons*)
blanchet@36064
   464
          (length deps < 2 orelse nlines mod modulus <> 0))
paulson@22491
   465
      then (nlines+1, map (replace_deps (lno, deps)) lines) (*Delete line*)
paulson@22491
   466
      else (nlines+1, (lno, t, deps) :: lines);
paulson@21978
   467
paulson@21999
   468
(*Replace numeric proof lines by strings, either from thm_names or sequential line numbers*)
paulson@21978
   469
fun stringify_deps thm_names deps_map [] = []
paulson@21978
   470
  | stringify_deps thm_names deps_map ((lno, t, deps) :: lines) =
blanchet@36291
   471
      if is_axiom thm_names lno then
blanchet@36291
   472
        (Vector.sub(thm_names,lno-1), t, []) :: stringify_deps thm_names deps_map lines
paulson@21979
   473
      else let val lname = Int.toString (length deps_map)
blanchet@36291
   474
               fun fix lno = if is_axiom thm_names lno
paulson@21978
   475
                             then SOME(Vector.sub(thm_names,lno-1))
blanchet@36291
   476
                             else AList.lookup (op =) deps_map lno;
wenzelm@32952
   477
           in  (lname, t, map_filter fix (distinct (op=) deps)) ::
paulson@21978
   478
               stringify_deps thm_names ((lno,lname)::deps_map) lines
paulson@21978
   479
           end;
paulson@21978
   480
blanchet@36063
   481
fun isar_proof_start i =
blanchet@36063
   482
  (if i = 1 then "" else "prefer " ^ string_of_int i ^ "\n") ^
blanchet@36063
   483
  "proof (neg_clausify)\n";
blanchet@36063
   484
fun isar_fixes [] = ""
blanchet@36063
   485
  | isar_fixes ts = "  fix " ^ space_implode " " ts ^ "\n";
blanchet@36063
   486
fun isar_proof_end 1 = "qed"
blanchet@36063
   487
  | isar_proof_end _ = "next"
paulson@21979
   488
blanchet@36291
   489
fun isar_proof_from_atp_proof cnfs modulus sorts ctxt goal i thm_names =
blanchet@35868
   490
  let
blanchet@36291
   491
    val _ = trace_proof_msg (K "\nisar_proof_from_atp_proof: start\n")
blanchet@36291
   492
    val tuples = map (parse_proof_line o explode) cnfs
blanchet@35868
   493
    val _ = trace_proof_msg (fn () =>
blanchet@35868
   494
      Int.toString (length tuples) ^ " tuples extracted\n")
blanchet@35868
   495
    val ctxt = ProofContext.set_mode ProofContext.mode_schematic ctxt
blanchet@36291
   496
    val raw_lines =
blanchet@36291
   497
      fold_rev (add_proof_line thm_names) (decode_proof_steps ctxt tuples) []
blanchet@35868
   498
    val _ = trace_proof_msg (fn () =>
blanchet@35868
   499
      Int.toString (length raw_lines) ^ " raw_lines extracted\n")
blanchet@35868
   500
    val nonnull_lines = List.foldr add_nonnull_prfline [] raw_lines
blanchet@35868
   501
    val _ = trace_proof_msg (fn () =>
blanchet@35868
   502
      Int.toString (length nonnull_lines) ^ " nonnull_lines extracted\n")
blanchet@36064
   503
    val (_, lines) = List.foldr (add_wanted_prfline ctxt modulus) (0,[]) nonnull_lines
blanchet@35868
   504
    val _ = trace_proof_msg (fn () =>
blanchet@35868
   505
      Int.toString (length lines) ^ " lines extracted\n")
blanchet@36063
   506
    val (ccls, fixes) = neg_conjecture_clauses ctxt goal i
blanchet@35868
   507
    val _ = trace_proof_msg (fn () =>
blanchet@35868
   508
      Int.toString (length ccls) ^ " conjecture clauses\n")
blanchet@35868
   509
    val ccls = map forall_intr_vars ccls
blanchet@35868
   510
    val _ = app (fn th => trace_proof_msg
blanchet@35868
   511
                              (fn () => "\nccl: " ^ string_of_thm ctxt th)) ccls
blanchet@36064
   512
    val body = isar_proof_body ctxt sorts (map prop_of ccls)
blanchet@35869
   513
                               (stringify_deps thm_names [] lines)
blanchet@36063
   514
    val n = Logic.count_prems (prop_of goal)
blanchet@36291
   515
    val _ = trace_proof_msg (K "\nisar_proof_from_atp_proof: finishing\n")
blanchet@36063
   516
  in
blanchet@36063
   517
    isar_proof_start i ^ isar_fixes (map #1 fixes) ^ implode body ^
blanchet@36063
   518
    isar_proof_end n ^ "\n"
blanchet@36063
   519
  end
blanchet@36288
   520
  handle STREE _ => raise Fail "Cannot parse ATP output";
paulson@21978
   521
paulson@21978
   522
wenzelm@33310
   523
(* === EXTRACTING LEMMAS === *)
blanchet@36223
   524
(* A list consisting of the first number in each line is returned.
blanchet@36223
   525
   TPTP: Interesting lines have the form "cnf(108, axiom, ...)", where the
blanchet@36223
   526
   number (108) is extracted.
blanchet@36223
   527
   DFG: Lines have the form "108[0:Inp] ...", where the first number (108) is
blanchet@36223
   528
   extracted. *)
blanchet@36369
   529
fun get_step_nums proof =
blanchet@35865
   530
  let
blanchet@36291
   531
    val toks = String.tokens (not o is_ident_char)
blanchet@35865
   532
    fun inputno ("cnf" :: ntok :: "axiom" :: _) = Int.fromString ntok
blanchet@36291
   533
      | inputno ("cnf" :: ntok :: "negated_conjecture" :: _) =
blanchet@35865
   534
        Int.fromString ntok
blanchet@36369
   535
      | inputno (ntok :: "0" :: "Inp" :: _) =
blanchet@36369
   536
        Int.fromString ntok  (* SPASS's output format *)
blanchet@35865
   537
      | inputno _ = NONE
blanchet@36369
   538
  in map_filter (inputno o toks) (split_lines proof) end
wenzelm@33310
   539
  
wenzelm@33310
   540
(*Used to label theorems chained into the sledgehammer call*)
wenzelm@33310
   541
val chained_hint = "CHAINED";
blanchet@35865
   542
val kill_chained = filter_out (curry (op =) chained_hint)
blanchet@35865
   543
blanchet@36063
   544
fun apply_command _ 1 = "by "
blanchet@36063
   545
  | apply_command 1 _ = "apply "
blanchet@36063
   546
  | apply_command i _ = "prefer " ^ string_of_int i ^ " apply "
blanchet@36063
   547
fun metis_command i n [] =
blanchet@36063
   548
    apply_command i n ^ "metis"
blanchet@36063
   549
  | metis_command i n xs =
blanchet@36063
   550
    apply_command i n ^ "(metis " ^ space_implode " " xs ^ ")"
blanchet@36063
   551
fun metis_line i n xs =
blanchet@36063
   552
  "Try this command: " ^
blanchet@36063
   553
  Markup.markup Markup.sendback (metis_command i n xs) ^ ".\n" 
blanchet@36281
   554
fun minimize_line _ [] = ""
blanchet@36281
   555
  | minimize_line minimize_command facts =
blanchet@36281
   556
    case minimize_command facts of
blanchet@36281
   557
      "" => ""
blanchet@36281
   558
    | command =>
blanchet@36065
   559
      "To minimize the number of lemmas, try this command: " ^
blanchet@36281
   560
      Markup.markup Markup.sendback command ^ ".\n"
immler@31840
   561
blanchet@36287
   562
fun metis_proof_text (minimize_command, proof, thm_names, goal, i) =
blanchet@36063
   563
  let
blanchet@36231
   564
    val lemmas =
blanchet@36369
   565
      proof |> get_step_nums
blanchet@36291
   566
            |> filter (is_axiom thm_names)
blanchet@36231
   567
            |> map (fn i => Vector.sub (thm_names, i - 1))
blanchet@36231
   568
            |> filter (fn x => x <> "??.unknown")
blanchet@36231
   569
            |> sort_distinct string_ord
blanchet@36063
   570
    val n = Logic.count_prems (prop_of goal)
blanchet@36063
   571
    val xs = kill_chained lemmas
blanchet@36063
   572
  in
blanchet@36281
   573
    (metis_line i n xs ^ minimize_line minimize_command xs, kill_chained lemmas)
blanchet@36223
   574
  end
immler@31037
   575
blanchet@36291
   576
val is_proof_line = String.isPrefix "cnf(" orf String.isSubstring "||"
blanchet@36291
   577
blanchet@36291
   578
fun do_space c = if Char.isSpace c then "" else str c
blanchet@36291
   579
blanchet@36291
   580
fun strip_spaces_in_list [] = ""
blanchet@36291
   581
  | strip_spaces_in_list [c1] = do_space c1
blanchet@36291
   582
  | strip_spaces_in_list [c1, c2] = do_space c1 ^ do_space c2
blanchet@36291
   583
  | strip_spaces_in_list (c1 :: c2 :: c3 :: cs) =
blanchet@36291
   584
    if Char.isSpace c1 then
blanchet@36291
   585
      strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36291
   586
    else if Char.isSpace c2 then
blanchet@36291
   587
      if Char.isSpace c3 then
blanchet@36291
   588
        strip_spaces_in_list (c1 :: c3 :: cs)
blanchet@36291
   589
      else
blanchet@36291
   590
        str c1 ^
blanchet@36291
   591
        (if is_ident_char c1 andalso is_ident_char c3 then " " else "") ^
blanchet@36291
   592
        strip_spaces_in_list (c3 :: cs)
blanchet@36291
   593
    else
blanchet@36291
   594
      str c1 ^ strip_spaces_in_list (c2 :: c3 :: cs)
blanchet@36291
   595
blanchet@36291
   596
val strip_spaces = strip_spaces_in_list o String.explode
blanchet@36291
   597
blanchet@36287
   598
fun isar_proof_text debug modulus sorts ctxt
blanchet@36287
   599
                    (minimize_command, proof, thm_names, goal, i) =
wenzelm@33310
   600
  let
blanchet@36369
   601
    val cnfs = proof |> split_lines |> map strip_spaces |> filter is_proof_line
blanchet@36223
   602
    val (one_line_proof, lemma_names) =
blanchet@36287
   603
      metis_proof_text (minimize_command, proof, thm_names, goal, i)
blanchet@35868
   604
    val tokens = String.tokens (fn c => c = #" ") one_line_proof
blanchet@36283
   605
    fun isar_proof_for () =
blanchet@36291
   606
      case isar_proof_from_atp_proof cnfs modulus sorts ctxt goal i thm_names of
blanchet@36283
   607
        "" => ""
blanchet@36285
   608
      | isar_proof =>
blanchet@36285
   609
        "\nStructured proof:\n" ^ Markup.markup Markup.sendback isar_proof
blanchet@35868
   610
    val isar_proof =
blanchet@36283
   611
      if member (op =) tokens chained_hint then
blanchet@36283
   612
        ""
blanchet@36283
   613
      else if debug then
blanchet@36283
   614
        isar_proof_for ()
blanchet@36283
   615
      else
blanchet@36283
   616
        try isar_proof_for ()
blanchet@36287
   617
        |> the_default "Warning: The Isar proof construction failed.\n"
blanchet@36283
   618
  in (one_line_proof ^ isar_proof, lemma_names) end
paulson@21978
   619
blanchet@36288
   620
fun proof_text isar_proof debug modulus sorts ctxt =
blanchet@36288
   621
  if isar_proof then isar_proof_text debug modulus sorts ctxt
blanchet@36288
   622
  else metis_proof_text
blanchet@36223
   623
immler@31038
   624
end;