src/HOL/Tools/res_reconstruct.ML
author paulson
Wed Nov 28 16:26:03 2007 +0100 (2007-11-28)
changeset 25492 4cc7976948ac
parent 25414 3326bd7ecd48
child 25710 4cdf7de81e1b
permissions -rwxr-xr-x
Chained theorems are no longer mentioned in metis calls and (if used) they prevent the
output of a structured proof.
paulson@21978
     1
(*  ID:         $Id$
paulson@21979
     2
    Author:     L C Paulson and Claire Quigley
paulson@21978
     3
    Copyright   2004  University of Cambridge
paulson@21978
     4
*)
paulson@21978
     5
paulson@21978
     6
(***************************************************************************)
paulson@21979
     7
(*  Code to deal with the transfer of proofs from a prover process         *)
paulson@21978
     8
(***************************************************************************)
paulson@21978
     9
signature RES_RECONSTRUCT =
paulson@24425
    10
sig
paulson@24425
    11
  datatype atp = E | SPASS | Vampire
paulson@24425
    12
  val modulus:     int ref
paulson@24425
    13
  val recon_sorts: bool ref
paulson@25492
    14
  val chained_hint: string
paulson@24425
    15
  val checkEProofFound:
paulson@24425
    16
	TextIO.instream * TextIO.outstream * Posix.Process.pid *
paulson@24425
    17
	string * Proof.context * thm * int * string Vector.vector -> bool
paulson@24425
    18
  val checkVampProofFound:
paulson@24425
    19
	TextIO.instream * TextIO.outstream * Posix.Process.pid *
paulson@24425
    20
	string * Proof.context * thm * int * string Vector.vector -> bool
paulson@24425
    21
  val checkSpassProofFound:
paulson@24425
    22
	TextIO.instream * TextIO.outstream * Posix.Process.pid *
paulson@24425
    23
	string * Proof.context * thm * int * string Vector.vector -> bool
paulson@24425
    24
  val signal_parent: TextIO.outstream * Posix.Process.pid * string * string -> unit
paulson@24425
    25
  val txt_path: string -> Path.T
paulson@24425
    26
  val fix_sorts: sort Vartab.table -> term -> term
paulson@24425
    27
  val invert_const: string -> string
paulson@24425
    28
  val invert_type_const: string -> string
paulson@24425
    29
  val num_typargs: Context.theory -> string -> int
paulson@24425
    30
  val make_tvar: string -> typ
paulson@24425
    31
  val strip_prefix: string -> string -> string option
paulson@24425
    32
end;
paulson@21978
    33
paulson@24425
    34
structure ResReconstruct : RES_RECONSTRUCT =
paulson@21978
    35
struct
paulson@21978
    36
paulson@21978
    37
val trace_path = Path.basic "atp_trace";
paulson@21978
    38
wenzelm@23139
    39
fun trace s = if !Output.debugging then File.append (File.tmp_path trace_path) s
paulson@21978
    40
              else ();
paulson@21978
    41
paulson@24425
    42
datatype atp = E | SPASS | Vampire;
paulson@21978
    43
paulson@23833
    44
val recon_sorts = ref true;
paulson@22491
    45
paulson@22491
    46
val modulus = ref 1;    (*keep every nth proof line*)
paulson@22044
    47
paulson@21978
    48
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    49
paulson@21978
    50
(*Syntax trees, either termlist or formulae*)
paulson@21978
    51
datatype stree = Int of int | Br of string * stree list;
paulson@21978
    52
paulson@21978
    53
fun atom x = Br(x,[]);
paulson@21978
    54
paulson@21978
    55
fun scons (x,y) = Br("cons", [x,y]);
paulson@21978
    56
val listof = foldl scons (atom "nil");
paulson@21978
    57
paulson@21978
    58
(*Strings enclosed in single quotes, e.g. filenames*)
paulson@21978
    59
val quoted = $$"'" |-- Scan.repeat (~$$"'") --| $$"'" >> implode;
paulson@21978
    60
paulson@21978
    61
(*Intended for $true and $false*)
paulson@21978
    62
fun tf s = "c_" ^ str (Char.toUpper (String.sub(s,0))) ^ String.extract(s,1,NONE);
paulson@21978
    63
val truefalse = $$"$" |-- Symbol.scan_id >> (atom o tf);
paulson@21978
    64
paulson@21978
    65
(*Integer constants, typically proof line numbers*)
paulson@21978
    66
fun is_digit s = Char.isDigit (String.sub(s,0));
paulson@21978
    67
val integer = Scan.many1 is_digit >> (valOf o Int.fromString o implode);
paulson@21978
    68
paulson@21978
    69
(*Generalized FO terms, which include filenames, numbers, etc.*)
paulson@21978
    70
fun termlist x = (term -- Scan.repeat ($$"," |-- term) >> op::) x
paulson@21978
    71
and term x = (quoted >> atom || integer>>Int || truefalse ||
paulson@21978
    72
              Symbol.scan_id -- Scan.optional ($$"(" |-- termlist --| $$")") [] >> Br ||
paulson@21978
    73
              $$"(" |-- term --| $$")" ||
paulson@24547
    74
              $$"[" |-- Scan.optional termlist [] --| $$"]" >> listof) x;
paulson@21978
    75
paulson@21978
    76
fun negate t = Br("c_Not", [t]);
paulson@21978
    77
fun equate (t1,t2) = Br("c_equal", [t1,t2]);
paulson@21978
    78
paulson@21978
    79
(*Apply equal or not-equal to a term*)
paulson@21978
    80
fun syn_equal (t, NONE) = t
paulson@21978
    81
  | syn_equal (t1, SOME (NONE, t2)) = equate (t1,t2)
paulson@21978
    82
  | syn_equal (t1, SOME (SOME _, t2)) = negate (equate (t1,t2));
paulson@21978
    83
paulson@21978
    84
(*Literals can involve negation, = and !=.*)
paulson@24547
    85
fun literal x = ($$"~" |-- literal >> negate ||
paulson@24547
    86
                 (term -- Scan.option (Scan.option ($$"!") --| $$"=" -- term) >> syn_equal)) x;
paulson@21978
    87
paulson@21978
    88
val literals = literal -- Scan.repeat ($$"|" |-- literal) >> op:: ;
paulson@21978
    89
paulson@21978
    90
(*Clause: a list of literals separated by the disjunction sign*)
paulson@24547
    91
val clause = $$"(" |-- literals --| $$")" || Scan.single literal;
paulson@21978
    92
paulson@21978
    93
val annotations = $$"," |-- term -- Scan.option ($$"," |-- termlist);
paulson@21978
    94
paulson@21978
    95
(*<cnf_annotated> ::=Ęcnf(<name>,<formula_role>,<cnf_formula><annotations>).
paulson@21978
    96
  The <name> could be an identifier, but we assume integers.*)
wenzelm@23139
    97
val tstp_line = (Scan.this_string "cnf" -- $$"(") |--
wenzelm@23139
    98
                integer --| $$"," -- Symbol.scan_id --| $$"," --
paulson@21978
    99
                clause -- Scan.option annotations --| $$ ")";
paulson@21978
   100
paulson@21978
   101
paulson@21978
   102
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   103
paulson@21978
   104
exception STREE of stree;
paulson@21978
   105
paulson@21978
   106
(*If string s has the prefix s1, return the result of deleting it.*)
wenzelm@23139
   107
fun strip_prefix s1 s =
paulson@24182
   108
  if String.isPrefix s1 s 
paulson@24182
   109
  then SOME (ResClause.undo_ascii_of (String.extract (s, size s1, NONE)))
paulson@21978
   110
  else NONE;
paulson@21978
   111
paulson@21978
   112
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   113
val type_const_trans_table_inv =
paulson@21978
   114
      Symtab.make (map swap (Symtab.dest ResClause.type_const_trans_table));
paulson@21978
   115
paulson@21978
   116
fun invert_type_const c =
paulson@21978
   117
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   118
        SOME c' => c'
paulson@21978
   119
      | NONE => c;
paulson@21978
   120
paulson@21978
   121
fun make_tvar b = TVar(("'" ^ b, 0), 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
paulson@21978
   132
          case strip_prefix ResClause.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
paulson@21978
   137
                case strip_prefix ResClause.tfree_prefix a of
paulson@21978
   138
                    SOME b => TFree("'" ^ b, HOLogic.typeS)
wenzelm@23139
   139
                  | NONE =>
paulson@21978
   140
                case strip_prefix ResClause.tvar_prefix a of
paulson@21978
   141
                    SOME b => make_tvar b
paulson@21978
   142
                  | NONE => make_tvar 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 =")
paulson@22731
   148
        (Symtab.make (map swap (Symtab.dest ResClause.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) =>
paulson@21978
   169
        case strip_prefix ResClause.const_prefix a of
wenzelm@23139
   170
            SOME "equal" =>
paulson@22731
   171
              list_comb(Const ("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*)
paulson@21978
   183
                    case strip_prefix ResClause.fixed_var_prefix a of
paulson@21978
   184
                        SOME b => Free(b,T)
wenzelm@23139
   185
                      | NONE =>
paulson@21978
   186
                    case strip_prefix ResClause.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) =>
paulson@21978
   196
            (case (strip_prefix ResClause.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.*)
paulson@22491
   219
fun lits_of_strees ctxt (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)
paulson@21978
   228
        | tysubst (TVar (xi, s)) = TVar (xi, getOpt (Vartab.lookup vt xi, s))
paulson@21978
   229
        | tysubst (TFree (x, s)) = TFree (x, getOpt (Vartab.lookup vt (x,~1), s))
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;
paulson@21978
   236
  in fn t => if Vartab.is_empty vt then t else tmsubst t 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))
wenzelm@22728
   243
  end;
paulson@21978
   244
paulson@23519
   245
(*Quantification over a list of Vars. FIXME: for term.ML??*)
paulson@21978
   246
fun list_all_var ([], t: term) = t
paulson@21978
   247
  | list_all_var ((v as Var(ix,T)) :: vars, t) =
paulson@21979
   248
      (all T) $ Abs(string_of_indexname ix, T, abstract_over (v, list_all_var (vars,t)));
paulson@21978
   249
paulson@21978
   250
fun gen_all_vars t = list_all_var (term_vars t, t);
paulson@21978
   251
paulson@21978
   252
fun ints_of_stree_aux (Int n, ns) = n::ns
paulson@21978
   253
  | ints_of_stree_aux (Br(_,ts), ns) = foldl ints_of_stree_aux ns ts;
paulson@21978
   254
paulson@21978
   255
fun ints_of_stree t = ints_of_stree_aux (t, []);
paulson@21978
   256
paulson@25086
   257
fun decode_tstp vt0 (name, role, ts, annots) ctxt =
paulson@21978
   258
  let val deps = case annots of NONE => [] | SOME (source,_) => ints_of_stree source
paulson@25086
   259
      val cl = clause_of_strees ctxt vt0 ts
paulson@25086
   260
  in  ((name, role, cl, deps), fold Variable.declare_term (term_frees cl) ctxt)  end;
paulson@21978
   261
paulson@21978
   262
fun dest_tstp ((((name, role), ts), annots), chs) =
paulson@21978
   263
  case chs of
paulson@21978
   264
          "."::_ => (name, role, ts, annots)
paulson@21978
   265
        | _ => error ("TSTP line not terminated by \".\": " ^ implode chs);
paulson@21978
   266
paulson@21978
   267
paulson@21978
   268
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit clauses. **)
paulson@21978
   269
paulson@21978
   270
fun add_tfree_constraint ((true, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   271
  | add_tfree_constraint (_, vt) = vt;
paulson@21978
   272
paulson@21978
   273
fun tfree_constraints_of_clauses vt [] = vt
wenzelm@23139
   274
  | tfree_constraints_of_clauses vt ([lit]::tss) =
paulson@21978
   275
      (tfree_constraints_of_clauses (add_tfree_constraint (constraint_of_stree true lit, vt)) tss
paulson@21978
   276
       handle STREE _ => (*not a positive type constraint: ignore*)
paulson@21978
   277
       tfree_constraints_of_clauses vt tss)
paulson@21978
   278
  | tfree_constraints_of_clauses vt (_::tss) = tfree_constraints_of_clauses vt tss;
paulson@21978
   279
paulson@21978
   280
paulson@21978
   281
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   282
paulson@22012
   283
fun decode_tstp_list ctxt tuples =
paulson@21978
   284
  let val vt0 = tfree_constraints_of_clauses Vartab.empty (map #3 tuples)
paulson@25086
   285
  in  #1 (fold_map (decode_tstp vt0) tuples ctxt) end;
paulson@21978
   286
paulson@23519
   287
(** Finding a matching assumption. The literals may be permuted, and variable names
paulson@23519
   288
    may disagree. We have to try all combinations of literals (quadratic!) and 
paulson@23519
   289
    match up the variable names consistently. **)
paulson@23519
   290
paulson@23519
   291
fun strip_alls_aux n (Const("all",_)$Abs(a,T,t))  =  
paulson@23519
   292
      strip_alls_aux (n+1) (subst_bound (Var ((a,n), T), t))
paulson@23519
   293
  | strip_alls_aux _ t  =  t;
paulson@23519
   294
paulson@23519
   295
val strip_alls = strip_alls_aux 0;
paulson@23519
   296
paulson@23519
   297
exception MATCH_LITERAL;
paulson@22012
   298
paulson@23519
   299
(*Ignore types: they are not to be trusted...*)
paulson@23519
   300
fun match_literal (t1$u1) (t2$u2) env =
paulson@23519
   301
      match_literal t1 t2 (match_literal u1 u2 env)
paulson@23519
   302
  | match_literal (Abs (_,_,t1)) (Abs (_,_,t2)) env = 
paulson@23519
   303
      match_literal t1 t2 env
paulson@23519
   304
  | match_literal (Bound i1) (Bound i2) env = 
paulson@23519
   305
      if i1=i2 then env else raise MATCH_LITERAL
paulson@23519
   306
  | match_literal (Const(a1,_)) (Const(a2,_)) env = 
paulson@23519
   307
      if a1=a2 then env else raise MATCH_LITERAL
paulson@23519
   308
  | match_literal (Free(a1,_)) (Free(a2,_)) env = 
paulson@23519
   309
      if a1=a2 then env else raise MATCH_LITERAL
paulson@23519
   310
  | match_literal (Var(ix1,_)) (Var(ix2,_)) env = insert (op =) (ix1,ix2) env
paulson@23519
   311
  | match_literal _ _ env = raise MATCH_LITERAL;
paulson@23519
   312
paulson@23519
   313
(*Checking that all variable associations are unique. The list env contains no
paulson@23519
   314
  repetitions, but does it contain say (x,y) and (y,y)? *)
paulson@23519
   315
fun good env = 
paulson@23519
   316
  let val (xs,ys) = ListPair.unzip env
paulson@23519
   317
  in  not (has_duplicates (op=) xs orelse has_duplicates (op=) ys)  end;
paulson@23519
   318
paulson@23519
   319
(*Match one list of literals against another, ignoring types and the order of
paulson@23519
   320
  literals. Sorting is unreliable because we don't have types or variable names.*)
paulson@23519
   321
fun matches_aux _ [] [] = true
paulson@23519
   322
  | matches_aux env (lit::lits) ts =
paulson@23519
   323
      let fun match1 us [] = false
paulson@23519
   324
            | match1 us (t::ts) =
paulson@23519
   325
                let val env' = match_literal lit t env
paulson@23519
   326
                in  (good env' andalso matches_aux env' lits (us@ts)) orelse 
paulson@23519
   327
                    match1 (t::us) ts  
paulson@23519
   328
                end
paulson@23519
   329
                handle MATCH_LITERAL => match1 (t::us) ts
paulson@23519
   330
      in  match1 [] ts  end; 
paulson@23519
   331
paulson@23519
   332
(*Is this length test useful?*)
paulson@23519
   333
fun matches (lits1,lits2) = 
paulson@23519
   334
  length lits1 = length lits2  andalso  
paulson@23519
   335
  matches_aux [] (map Envir.eta_contract lits1) (map Envir.eta_contract lits2);
paulson@21999
   336
paulson@21999
   337
fun permuted_clause t =
paulson@24958
   338
  let val lits = HOLogic.disjuncts t
paulson@21999
   339
      fun perm [] = NONE
wenzelm@23139
   340
        | perm (ctm::ctms) =
paulson@24958
   341
            if matches (lits, HOLogic.disjuncts (HOLogic.dest_Trueprop (strip_alls ctm)))
paulson@23519
   342
            then SOME ctm else perm ctms
paulson@21999
   343
  in perm end;
paulson@21999
   344
paulson@22470
   345
fun have_or_show "show " lname = "show \""
paulson@22470
   346
  | have_or_show have lname = have ^ lname ^ ": \""
paulson@22470
   347
paulson@21999
   348
(*ctms is a list of conjecture clauses as yielded by Isabelle. Those returned by the
paulson@21999
   349
  ATP may have their literals reordered.*)
paulson@21999
   350
fun isar_lines ctxt ctms =
wenzelm@24920
   351
  let val string_of = Syntax.string_of_term ctxt
paulson@22470
   352
      fun doline have (lname, t, []) =  (*No deps: it's a conjecture clause, with no proof.*)
paulson@21999
   353
           (case permuted_clause t ctms of
paulson@21999
   354
                SOME u => "assume " ^ lname ^ ": \"" ^ string_of u ^ "\"\n"
paulson@21999
   355
              | NONE => "assume? " ^ lname ^ ": \"" ^ string_of t ^ "\"\n")  (*no match!!*)
paulson@22470
   356
        | doline have (lname, t, deps) =
paulson@23519
   357
            have_or_show have lname ^ string_of (gen_all_vars (HOLogic.mk_Trueprop t)) ^
paulson@22372
   358
            "\"\n  by (metis " ^ space_implode " " deps ^ ")\n"
paulson@21978
   359
      fun dolines [(lname, t, deps)] = [doline "show " (lname, t, deps)]
paulson@21978
   360
        | dolines ((lname, t, deps)::lines) = doline "have " (lname, t, deps) :: dolines lines
paulson@22491
   361
  in setmp show_sorts (!recon_sorts) dolines end;
paulson@21978
   362
paulson@21978
   363
fun notequal t (_,t',_) = not (t aconv t');
paulson@21978
   364
paulson@22491
   365
(*No "real" literals means only type information*)
paulson@23519
   366
fun eq_types t = t aconv HOLogic.true_const;
paulson@21978
   367
paulson@22731
   368
fun replace_dep (old:int, new) dep = if dep=old then new else [dep];
paulson@21978
   369
wenzelm@23139
   370
fun replace_deps (old:int, new) (lno, t, deps) =
paulson@22731
   371
      (lno, t, foldl (op union_int) [] (map (replace_dep (old, new)) deps));
paulson@21978
   372
paulson@22491
   373
(*Discard axioms; consolidate adjacent lines that prove the same clause, since they differ
paulson@22491
   374
  only in type information.*)
paulson@21978
   375
fun add_prfline ((lno, "axiom", t, []), lines) =  (*axioms are not proof lines*)
paulson@22491
   376
      if eq_types t (*must be clsrel/clsarity: type information, so delete refs to it*)
wenzelm@23139
   377
      then map (replace_deps (lno, [])) lines
paulson@22470
   378
      else
paulson@22470
   379
       (case take_prefix (notequal t) lines of
paulson@22470
   380
           (_,[]) => lines                  (*no repetition of proof line*)
paulson@22470
   381
         | (pre, (lno',t',deps')::post) =>  (*repetition: replace later line by earlier one*)
paulson@22470
   382
             pre @ map (replace_deps (lno', [lno])) post)
paulson@21978
   383
  | add_prfline ((lno, role, t, []), lines) =  (*no deps: conjecture clause*)
paulson@22470
   384
      (lno, t, []) :: lines
paulson@21978
   385
  | add_prfline ((lno, role, t, deps), lines) =
paulson@22491
   386
      if eq_types t then (lno, t, deps) :: lines
paulson@22491
   387
      (*Type information will be deleted later; skip repetition test.*)
paulson@22491
   388
      else (*FIXME: Doesn't this code risk conflating proofs involving different types??*)
paulson@22044
   389
      case take_prefix (notequal t) lines of
paulson@22044
   390
         (_,[]) => (lno, t, deps) :: lines  (*no repetition of proof line*)
wenzelm@23139
   391
       | (pre, (lno',t',deps')::post) =>
paulson@22044
   392
           (lno, t', deps) ::               (*repetition: replace later line by earlier one*)
paulson@22044
   393
           (pre @ map (replace_deps (lno', [lno])) post);
paulson@22044
   394
paulson@22470
   395
(*Recursively delete empty lines (type information) from the proof.*)
paulson@22470
   396
fun add_nonnull_prfline ((lno, t, []), lines) = (*no dependencies, so a conjecture clause*)
paulson@22491
   397
     if eq_types t (*must be type information, tfree_tcs, clsrel, clsarity: delete refs to it*)
wenzelm@23139
   398
     then delete_dep lno lines
wenzelm@23139
   399
     else (lno, t, []) :: lines
paulson@22470
   400
  | add_nonnull_prfline ((lno, t, deps), lines) = (lno, t, deps) :: lines
paulson@22470
   401
and delete_dep lno lines = foldr add_nonnull_prfline [] (map (replace_deps (lno, [])) lines);
paulson@22470
   402
paulson@24937
   403
fun bad_free (Free (a,_)) = String.isPrefix "sko_" a
paulson@22731
   404
  | bad_free _ = false;
paulson@22731
   405
wenzelm@23139
   406
(*TVars are forbidden in goals. Also, we don't want lines with <2 dependencies.
paulson@22491
   407
  To further compress proofs, setting modulus:=n deletes every nth line, and nlines
paulson@22491
   408
  counts the number of proof lines processed so far.
paulson@22491
   409
  Deleted lines are replaced by their own dependencies. Note that the "add_nonnull_prfline"
paulson@22044
   410
  phase may delete some dependencies, hence this phase comes later.*)
paulson@22491
   411
fun add_wanted_prfline ((lno, t, []), (nlines, lines)) =
paulson@22491
   412
      (nlines, (lno, t, []) :: lines)   (*conjecture clauses must be kept*)
paulson@22491
   413
  | add_wanted_prfline ((lno, t, deps), (nlines, lines)) =
paulson@22545
   414
      if eq_types t orelse not (null (term_tvars t)) orelse
paulson@24937
   415
         exists bad_free (term_frees t) orelse
paulson@24937
   416
         (not (null lines) andalso   (*final line can't be deleted for these reasons*)
paulson@24937
   417
          (length deps < 2 orelse nlines mod !modulus <> 0))   
paulson@22491
   418
      then (nlines+1, map (replace_deps (lno, deps)) lines) (*Delete line*)
paulson@22491
   419
      else (nlines+1, (lno, t, deps) :: lines);
paulson@21978
   420
paulson@21999
   421
(*Replace numeric proof lines by strings, either from thm_names or sequential line numbers*)
paulson@21978
   422
fun stringify_deps thm_names deps_map [] = []
paulson@21978
   423
  | stringify_deps thm_names deps_map ((lno, t, deps) :: lines) =
paulson@21978
   424
      if lno <= Vector.length thm_names  (*axiom*)
wenzelm@23139
   425
      then (Vector.sub(thm_names,lno-1), t, []) :: stringify_deps thm_names deps_map lines
paulson@21979
   426
      else let val lname = Int.toString (length deps_map)
wenzelm@23139
   427
               fun fix lno = if lno <= Vector.length thm_names
paulson@21978
   428
                             then SOME(Vector.sub(thm_names,lno-1))
paulson@21978
   429
                             else AList.lookup op= deps_map lno;
paulson@22731
   430
           in  (lname, t, List.mapPartial fix (distinct (op=) deps)) ::
paulson@21978
   431
               stringify_deps thm_names ((lno,lname)::deps_map) lines
paulson@21978
   432
           end;
paulson@21978
   433
paulson@24547
   434
val proofstart = "proof (neg_clausify)\n";
paulson@21979
   435
paulson@21979
   436
fun isar_header [] = proofstart
paulson@21999
   437
  | isar_header ts = proofstart ^ "fix " ^ space_implode " " ts ^ "\n";
paulson@21979
   438
paulson@22012
   439
fun decode_tstp_file cnfs ctxt th sgno thm_names =
paulson@21978
   440
  let val tuples = map (dest_tstp o tstp_line o explode) cnfs
paulson@24552
   441
      val ctxt = ProofContext.set_mode ProofContext.mode_schematic ctxt
wenzelm@23139
   442
      val nonnull_lines =
wenzelm@23139
   443
              foldr add_nonnull_prfline []
paulson@22491
   444
                    (foldr add_prfline [] (decode_tstp_list ctxt tuples))
paulson@22491
   445
      val (_,lines) = foldr add_wanted_prfline (0,[]) nonnull_lines
paulson@21999
   446
      val (ccls,fixes) = ResAxioms.neg_conjecture_clauses th sgno
paulson@21999
   447
      val ccls = map forall_intr_vars ccls
wenzelm@23139
   448
  in
wenzelm@22130
   449
    app (fn th => Output.debug (fn () => string_of_thm th)) ccls;
wenzelm@23139
   450
    isar_header (map #1 fixes) ^
paulson@25492
   451
    String.concat (isar_lines ctxt (map prop_of ccls) (stringify_deps thm_names [] lines)) ^
paulson@25492
   452
    "qed\n"
paulson@24547
   453
  end
paulson@24547
   454
  handle e => (*FIXME: exn handler is too general!*)
paulson@24547
   455
    "Translation of TSTP raised an exception: " ^ Toplevel.exn_message e;
paulson@21978
   456
paulson@21978
   457
(*Could use split_lines, but it can return blank lines...*)
paulson@21978
   458
val lines = String.tokens (equal #"\n");
paulson@21978
   459
paulson@21978
   460
val nospaces = String.translate (fn c => if Char.isSpace c then "" else str c);
paulson@21978
   461
paulson@23519
   462
val txt_path = Path.ext "txt" o Path.explode o nospaces;
paulson@21978
   463
wenzelm@23139
   464
fun signal_success probfile toParent ppid msg =
paulson@23519
   465
  let val _ = trace ("\nReporting Success for " ^ probfile ^ "\n" ^ msg)
paulson@23519
   466
  in
paulson@23519
   467
    (*We write the proof to a file because sending very long lines may fail...*)
paulson@23519
   468
    File.write (txt_path probfile) msg;
paulson@23519
   469
    TextIO.output (toParent, "Success.\n");
paulson@23519
   470
    TextIO.output (toParent, probfile ^ "\n");
paulson@23519
   471
    TextIO.flushOut toParent;
wenzelm@25414
   472
    Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
paulson@23833
   473
    (*Give the parent time to respond before possibly sending another signal*)
paulson@23833
   474
    OS.Process.sleep (Time.fromMilliseconds 600)
paulson@23519
   475
  end;
paulson@21978
   476
paulson@21978
   477
paulson@21978
   478
(**** retrieve the axioms that were used in the proof ****)
paulson@21978
   479
paulson@24547
   480
(*PureThy.get_name_hint returns "??.unknown" if no name is available.*)
paulson@24547
   481
fun goodhint x = (x <> "??.unknown");  
paulson@24547
   482
paulson@21978
   483
(*Get names of axioms used. Axioms are indexed from 1, while the vector is indexed from 0*)
wenzelm@23139
   484
fun get_axiom_names (thm_names: string vector) step_nums =
wenzelm@23139
   485
    let fun is_axiom n = n <= Vector.length thm_names
paulson@24547
   486
        fun getname i = Vector.sub(thm_names, i-1)
paulson@21978
   487
    in
paulson@24547
   488
	sort_distinct string_ord (filter goodhint (map getname (filter is_axiom step_nums)))
paulson@24547
   489
    end;
paulson@21978
   490
wenzelm@23139
   491
 (*String contains multiple lines. We want those of the form
paulson@21978
   492
     "253[0:Inp] et cetera..."
paulson@21978
   493
  A list consisting of the first number in each line is returned. *)
paulson@24425
   494
fun get_spass_linenums proofextract =
paulson@21978
   495
  let val toks = String.tokens (not o Char.isAlphaNum)
paulson@21978
   496
      fun inputno (ntok::"0"::"Inp"::_) = Int.fromString ntok
paulson@21978
   497
        | inputno _ = NONE
paulson@24425
   498
      val lines = String.tokens (fn c => c = #"\n") proofextract
paulson@21978
   499
  in  List.mapPartial (inputno o toks) lines  end
paulson@21978
   500
paulson@24425
   501
fun get_axiom_names_spass proofextract thm_names =
paulson@24425
   502
   get_axiom_names thm_names (get_spass_linenums proofextract);
wenzelm@23139
   503
paulson@21978
   504
fun not_comma c = c <>  #",";
paulson@21978
   505
paulson@21978
   506
(*A valid TSTP axiom line has the form  cnf(NNN,axiom,...) where NNN is a positive integer.*)
paulson@21978
   507
fun parse_tstp_line s =
paulson@21978
   508
  let val ss = Substring.full (unprefix "cnf(" (nospaces s))
paulson@21978
   509
      val (intf,rest) = Substring.splitl not_comma ss
paulson@21978
   510
      val (rolef,rest) = Substring.splitl not_comma (Substring.triml 1 rest)
paulson@21978
   511
      (*We only allow negated_conjecture because the line number will be removed in
paulson@21978
   512
        get_axiom_names above, while suppressing the UNSOUND warning*)
paulson@21978
   513
      val ints = if Substring.string rolef mem_string ["axiom","negated_conjecture"]
wenzelm@23139
   514
                 then Substring.string intf
wenzelm@23139
   515
                 else "error"
paulson@21978
   516
  in  Int.fromString ints  end
wenzelm@23139
   517
  handle Fail _ => NONE;
paulson@21978
   518
paulson@24425
   519
fun get_axiom_names_tstp proofextract thm_names =
paulson@24425
   520
   get_axiom_names thm_names (List.mapPartial parse_tstp_line (split_lines proofextract));
wenzelm@23139
   521
wenzelm@23139
   522
 (*String contains multiple lines. We want those of the form
paulson@24632
   523
     "*********** [448, input] ***********"
paulson@24632
   524
   or possibly those of the form
paulson@24632
   525
     "cnf(108, axiom, ..."
paulson@21978
   526
  A list consisting of the first number in each line is returned. *)
paulson@24425
   527
fun get_vamp_linenums proofextract =
paulson@21978
   528
  let val toks = String.tokens (not o Char.isAlphaNum)
paulson@21978
   529
      fun inputno [ntok,"input"] = Int.fromString ntok
paulson@24632
   530
        | inputno ("cnf"::ntok::"axiom"::_) = Int.fromString ntok
paulson@21978
   531
        | inputno _ = NONE
paulson@24425
   532
      val lines = String.tokens (fn c => c = #"\n") proofextract
paulson@21978
   533
  in  List.mapPartial (inputno o toks) lines  end
paulson@21978
   534
paulson@24425
   535
fun get_axiom_names_vamp proofextract thm_names =
paulson@24425
   536
   get_axiom_names thm_names (get_vamp_linenums proofextract);
paulson@24425
   537
paulson@24547
   538
fun get_axiom_names_for E       = get_axiom_names_tstp
paulson@24547
   539
  | get_axiom_names_for SPASS   = get_axiom_names_spass
paulson@24547
   540
  | get_axiom_names_for Vampire = get_axiom_names_vamp;
wenzelm@23139
   541
paulson@24547
   542
fun metis_line [] = "apply metis"
paulson@24547
   543
  | metis_line xs = "apply (metis " ^ space_implode " " xs ^ ")"
paulson@21978
   544
paulson@25492
   545
(*Used to label theorems chained into the sledgehammer call*)
paulson@25492
   546
val chained_hint = "CHAINED";
paulson@25492
   547
paulson@25492
   548
val nochained = filter_out (fn y => y = chained_hint);
paulson@25492
   549
paulson@21978
   550
(*The signal handler in watcher.ML must be able to read the output of this.*)
paulson@24425
   551
fun lemma_list atp proofextract thm_names probfile toParent ppid =
paulson@24547
   552
  signal_success probfile toParent ppid 
paulson@25492
   553
                 (metis_line (nochained (get_axiom_names_for atp proofextract thm_names)));
paulson@21978
   554
paulson@24547
   555
fun tstp_extract proofextract thm_names probfile toParent ppid ctxt th sgno =
paulson@24425
   556
  let val cnfs = filter (String.isPrefix "cnf(") (map nospaces (lines proofextract))
paulson@25492
   557
      val names = get_axiom_names_tstp proofextract thm_names
paulson@25492
   558
      val line1 = metis_line (nochained names)
paulson@25492
   559
      val line2 = if chained_hint mem_string names then ""
paulson@25492
   560
                  else decode_tstp_file cnfs ctxt th sgno thm_names
paulson@24425
   561
  in
paulson@25492
   562
    signal_success probfile toParent ppid (line1 ^ "\n" ^ line2)
paulson@24425
   563
  end;
paulson@21978
   564
paulson@21978
   565
(**** Extracting proofs from an ATP's output ****)
paulson@21978
   566
paulson@24547
   567
val start_TSTP = "SZS output start CNFRefutation"
paulson@24547
   568
val end_TSTP   = "SZS output end CNFRefutation"
paulson@21978
   569
val start_E = "# Proof object starts here."
paulson@21978
   570
val end_E   = "# Proof object ends here."
paulson@21978
   571
val start_V8 = "=========== Refutation =========="
paulson@21978
   572
val end_V8 = "======= End of refutation ======="
paulson@24547
   573
val start_SPASS = "Here is a proof"
paulson@21978
   574
val end_SPASS = "Formulae used in the proof"
paulson@21978
   575
paulson@24547
   576
fun any_substring ss ln = exists (fn s => String.isSubstring s ln) ss;
paulson@24547
   577
paulson@21978
   578
(*********************************************************************************)
paulson@21978
   579
(*  Inspect the output of an ATP process to see if it has found a proof,     *)
paulson@21978
   580
(*  and if so, transfer output to the input pipe of the main Isabelle process    *)
paulson@21978
   581
(*********************************************************************************)
paulson@21978
   582
paulson@21978
   583
(*Returns "true" if it successfully returns a lemma list, otherwise "false", but this
paulson@21978
   584
  return value is currently never used!*)
paulson@22012
   585
fun startTransfer endS (fromChild, toParent, ppid, probfile, ctxt, th, sgno, thm_names) =
paulson@24547
   586
 let val atp = if endS = end_V8 then Vampire
paulson@24547
   587
	       else if endS = end_SPASS then SPASS
paulson@24547
   588
	       else E
paulson@24547
   589
     fun transferInput proofextract =
paulson@24547
   590
       case TextIO.inputLine fromChild of
paulson@24547
   591
	   NONE =>  (*end of file?*)
paulson@24547
   592
	     (trace ("\n extraction_failed.  End bracket: " ^ endS ^
paulson@24547
   593
		     "\naccumulated text: " ^ proofextract);
paulson@24547
   594
	      false)
paulson@24547
   595
	 | SOME thisLine =>
paulson@24547
   596
	     if any_substring [endS,end_TSTP] thisLine
paulson@24547
   597
	     then
paulson@24547
   598
	      (trace ("\nExtracted proof:\n" ^ proofextract);
paulson@24425
   599
	       if String.isPrefix "cnf(" proofextract
paulson@24547
   600
	       then tstp_extract proofextract thm_names probfile toParent ppid ctxt th sgno
paulson@24425
   601
	       else lemma_list atp proofextract thm_names probfile toParent ppid;
paulson@24425
   602
	       true)
paulson@24547
   603
	     else transferInput (proofextract ^ thisLine)
paulson@21978
   604
 in
paulson@21978
   605
     transferInput ""
wenzelm@23139
   606
 end
paulson@21978
   607
paulson@21978
   608
paulson@21978
   609
(*The signal handler in watcher.ML must be able to read the output of this.*)
paulson@21978
   610
fun signal_parent (toParent, ppid, msg, probfile) =
paulson@21978
   611
 (TextIO.output (toParent, msg);
paulson@21978
   612
  TextIO.output (toParent, probfile ^ "\n");
paulson@21978
   613
  TextIO.flushOut toParent;
paulson@21978
   614
  trace ("\nSignalled parent: " ^ msg ^ probfile);
wenzelm@25414
   615
  Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
paulson@21978
   616
  (*Give the parent time to respond before possibly sending another signal*)
paulson@21978
   617
  OS.Process.sleep (Time.fromMilliseconds 600));
paulson@21978
   618
paulson@22012
   619
(*FIXME: once TSTP output is produced by all ATPs, these three functions can be combined.*)
paulson@22012
   620
paulson@21978
   621
(*Called from watcher. Returns true if the Vampire process has returned a verdict.*)
paulson@22012
   622
fun checkVampProofFound (arg as (fromChild, toParent, ppid, probfile, ctxt, th, sgno, thm_names)) =
wenzelm@23139
   623
  (case TextIO.inputLine fromChild of
wenzelm@23139
   624
    NONE => (trace "\nNo proof output seen"; false)
wenzelm@23139
   625
  | SOME thisLine =>
paulson@24547
   626
     if any_substring [start_V8,start_TSTP] thisLine
paulson@22012
   627
     then startTransfer end_V8 arg
paulson@24547
   628
     else if (String.isSubstring "Satisfiability detected" thisLine) orelse
paulson@24956
   629
             (String.isSubstring "Refutation not found" thisLine) orelse
paulson@24956
   630
             (String.isSubstring "CANNOT PROVE" thisLine)
paulson@21978
   631
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   632
	   true)
wenzelm@23139
   633
     else checkVampProofFound arg);
paulson@21978
   634
paulson@21978
   635
(*Called from watcher. Returns true if the E process has returned a verdict.*)
wenzelm@23139
   636
fun checkEProofFound (arg as (fromChild, toParent, ppid, probfile, ctxt, th, sgno, thm_names)) =
wenzelm@23139
   637
  (case TextIO.inputLine fromChild of
wenzelm@23139
   638
    NONE => (trace "\nNo proof output seen"; false)
wenzelm@23139
   639
  | SOME thisLine =>
paulson@24547
   640
     if any_substring [start_E,start_TSTP] thisLine 
paulson@22012
   641
     then startTransfer end_E arg
paulson@24547
   642
     else if String.isSubstring "SZS status: Satisfiable" thisLine
paulson@21978
   643
     then (signal_parent (toParent, ppid, "Invalid\n", probfile);
paulson@21978
   644
	   true)
paulson@24956
   645
     else if String.isSubstring "SZS status: ResourceOut" thisLine orelse
paulson@24956
   646
             String.isSubstring "# Cannot determine problem status" thisLine
paulson@21978
   647
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   648
	   true)
wenzelm@23139
   649
     else checkEProofFound arg);
paulson@21978
   650
paulson@21978
   651
(*Called from watcher. Returns true if the SPASS process has returned a verdict.*)
wenzelm@23139
   652
fun checkSpassProofFound (arg as (fromChild, toParent, ppid, probfile, ctxt, th, sgno, thm_names)) =
wenzelm@23139
   653
  (case TextIO.inputLine fromChild of
wenzelm@23139
   654
    NONE => (trace "\nNo proof output seen"; false)
wenzelm@23139
   655
  | SOME thisLine =>
paulson@24547
   656
     if any_substring [start_SPASS,start_TSTP] thisLine
paulson@22012
   657
     then startTransfer end_SPASS arg
paulson@21978
   658
     else if thisLine = "SPASS beiseite: Completion found.\n"
paulson@21978
   659
     then (signal_parent (toParent, ppid, "Invalid\n", probfile);
paulson@21978
   660
	   true)
paulson@21978
   661
     else if thisLine = "SPASS beiseite: Ran out of time.\n" orelse
paulson@21978
   662
             thisLine = "SPASS beiseite: Maximal number of loops exceeded.\n"
paulson@21978
   663
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   664
	   true)
wenzelm@23139
   665
    else checkSpassProofFound arg);
paulson@21978
   666
paulson@21978
   667
end;