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