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