src/HOL/Tools/res_reconstruct.ML
author paulson
Wed Jan 03 18:29:46 2007 +0100 (2007-01-03)
changeset 21979 80e10f181c46
parent 21978 72c21698a055
child 21999 0cf192e489e2
permissions -rwxr-xr-x
Improvements to proof reconstruction. Now "fixes" is inserted
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@21979
     6
(*FIXME: can we delete the "thm * int" and "th sgno" below?*)
paulson@21979
     7
paulson@21978
     8
(***************************************************************************)
paulson@21979
     9
(*  Code to deal with the transfer of proofs from a prover process         *)
paulson@21978
    10
(***************************************************************************)
paulson@21978
    11
signature RES_RECONSTRUCT =
paulson@21978
    12
  sig
paulson@21978
    13
    val checkEProofFound: 
paulson@21978
    14
          TextIO.instream * TextIO.outstream * Posix.Process.pid * 
paulson@21978
    15
          string * thm * int * string Vector.vector -> bool
paulson@21978
    16
    val checkVampProofFound: 
paulson@21978
    17
          TextIO.instream * TextIO.outstream * Posix.Process.pid * 
paulson@21978
    18
          string * thm * int * string Vector.vector -> bool
paulson@21978
    19
    val checkSpassProofFound:  
paulson@21978
    20
          TextIO.instream * TextIO.outstream * Posix.Process.pid * 
paulson@21978
    21
          string * thm * int * string Vector.vector -> bool
paulson@21978
    22
    val signal_parent:  
paulson@21978
    23
          TextIO.outstream * Posix.Process.pid * string * string -> unit
paulson@21978
    24
    val nospaces: string -> string
paulson@21978
    25
paulson@21978
    26
  end;
paulson@21978
    27
paulson@21978
    28
structure ResReconstruct =
paulson@21978
    29
struct
paulson@21978
    30
paulson@21978
    31
val trace_path = Path.basic "atp_trace";
paulson@21978
    32
paulson@21978
    33
fun trace s = if !Output.show_debug_msgs then File.append (File.tmp_path trace_path) s 
paulson@21978
    34
              else ();
paulson@21978
    35
paulson@21978
    36
(*Full proof reconstruction wanted*)
paulson@21978
    37
val full = ref true;
paulson@21978
    38
paulson@21978
    39
(**** PARSING OF TSTP FORMAT ****)
paulson@21978
    40
paulson@21978
    41
(*Syntax trees, either termlist or formulae*)
paulson@21978
    42
datatype stree = Int of int | Br of string * stree list;
paulson@21978
    43
paulson@21978
    44
fun atom x = Br(x,[]);
paulson@21978
    45
paulson@21978
    46
fun scons (x,y) = Br("cons", [x,y]);
paulson@21978
    47
val listof = foldl scons (atom "nil");
paulson@21978
    48
paulson@21978
    49
(*Strings enclosed in single quotes, e.g. filenames*)
paulson@21978
    50
val quoted = $$"'" |-- Scan.repeat (~$$"'") --| $$"'" >> implode;
paulson@21978
    51
paulson@21978
    52
(*Intended for $true and $false*)
paulson@21978
    53
fun tf s = "c_" ^ str (Char.toUpper (String.sub(s,0))) ^ String.extract(s,1,NONE);
paulson@21978
    54
val truefalse = $$"$" |-- Symbol.scan_id >> (atom o tf);
paulson@21978
    55
paulson@21978
    56
(*Integer constants, typically proof line numbers*)
paulson@21978
    57
fun is_digit s = Char.isDigit (String.sub(s,0));
paulson@21978
    58
val integer = Scan.many1 is_digit >> (valOf o Int.fromString o implode);
paulson@21978
    59
paulson@21978
    60
(*Generalized FO terms, which include filenames, numbers, etc.*)
paulson@21978
    61
fun termlist x = (term -- Scan.repeat ($$"," |-- term) >> op::) x
paulson@21978
    62
and term x = (quoted >> atom || integer>>Int || truefalse ||
paulson@21978
    63
              Symbol.scan_id -- Scan.optional ($$"(" |-- termlist --| $$")") [] >> Br ||
paulson@21978
    64
              $$"(" |-- term --| $$")" ||
paulson@21978
    65
              $$"[" |-- termlist --| $$"]" >> listof) x;
paulson@21978
    66
paulson@21978
    67
fun negate t = Br("c_Not", [t]);
paulson@21978
    68
fun equate (t1,t2) = Br("c_equal", [t1,t2]);
paulson@21978
    69
paulson@21978
    70
(*Apply equal or not-equal to a term*)
paulson@21978
    71
fun syn_equal (t, NONE) = t
paulson@21978
    72
  | syn_equal (t1, SOME (NONE, t2)) = equate (t1,t2)
paulson@21978
    73
  | syn_equal (t1, SOME (SOME _, t2)) = negate (equate (t1,t2));
paulson@21978
    74
paulson@21978
    75
(*Literals can involve negation, = and !=.*)
paulson@21978
    76
val literal = $$"~" |-- term >> negate || 
paulson@21978
    77
              (term -- Scan.option (Scan.option ($$"!") --| $$"=" -- term) >> syn_equal) ;
paulson@21978
    78
paulson@21978
    79
val literals = literal -- Scan.repeat ($$"|" |-- literal) >> op:: ;
paulson@21978
    80
paulson@21978
    81
(*Clause: a list of literals separated by the disjunction sign*)
paulson@21978
    82
val clause = $$"(" |-- literals --| $$")";
paulson@21978
    83
paulson@21978
    84
val annotations = $$"," |-- term -- Scan.option ($$"," |-- termlist);
paulson@21978
    85
paulson@21978
    86
(*<cnf_annotated> ::=Ęcnf(<name>,<formula_role>,<cnf_formula><annotations>).
paulson@21978
    87
  The <name> could be an identifier, but we assume integers.*)
paulson@21978
    88
val tstp_line = (Scan.this_string "cnf" -- $$"(") |-- 
paulson@21978
    89
                integer --| $$"," -- Symbol.scan_id --| $$"," -- 
paulson@21978
    90
                clause -- Scan.option annotations --| $$ ")";
paulson@21978
    91
paulson@21978
    92
paulson@21978
    93
(**** DUPLICATE of Susanto's code to remove ASCII armouring from names in proof files ****)
paulson@21978
    94
paulson@21978
    95
(*original file: Isabelle_ext.sml*)
paulson@21978
    96
paulson@21978
    97
val A_min_spc = Char.ord #"A" - Char.ord #" ";
paulson@21978
    98
paulson@21978
    99
fun cList2int chs = getOpt (Int.fromString (String.implode (rev chs)), 0);
paulson@21978
   100
paulson@21978
   101
(*why such a tiny range?*)
paulson@21978
   102
fun check_valid_int x =
paulson@21978
   103
  let val val_x = cList2int x
paulson@21978
   104
  in (length x = 3) andalso (val_x >= 123) andalso (val_x <= 126)
paulson@21978
   105
  end;
paulson@21978
   106
paulson@21978
   107
fun normalise_s s [] st_ sti =
paulson@21978
   108
      String.implode(rev(
paulson@21978
   109
        if st_
paulson@21978
   110
        then if null sti
paulson@21978
   111
             then (#"_" :: s)
paulson@21978
   112
             else if check_valid_int sti
paulson@21978
   113
                  then (Char.chr (cList2int sti) :: s)
paulson@21978
   114
                  else (sti @ (#"_" :: s))
paulson@21978
   115
        else s))
paulson@21978
   116
  | normalise_s s (#"_"::cs) st_ sti =
paulson@21978
   117
      if st_
paulson@21978
   118
      then let val s' = if null sti
paulson@21978
   119
                        then (#"_"::s)
paulson@21978
   120
                        else if check_valid_int sti
paulson@21978
   121
                             then (Char.chr (cList2int sti) :: s)
paulson@21978
   122
                             else (sti @ (#"_" :: s))
paulson@21978
   123
           in normalise_s s' cs false [] 
paulson@21978
   124
           end
paulson@21978
   125
      else normalise_s s cs true []
paulson@21978
   126
  | normalise_s s (c::cs) true sti =
paulson@21978
   127
      if (Char.isDigit c)
paulson@21978
   128
      then normalise_s s cs true (c::sti)
paulson@21978
   129
      else let val s' = if null sti
paulson@21978
   130
                        then if ((c >= #"A") andalso (c<= #"P"))
paulson@21978
   131
                             then ((Char.chr(Char.ord c - A_min_spc))::s)
paulson@21978
   132
                             else (c :: (#"_" :: s))
paulson@21978
   133
                        else if check_valid_int sti
paulson@21978
   134
                             then (Char.chr (cList2int sti) :: s)
paulson@21978
   135
                             else (sti @ (#"_" :: s))
paulson@21978
   136
           in normalise_s s' cs false []
paulson@21978
   137
           end
paulson@21978
   138
  | normalise_s s (c::cs) _ _ = normalise_s (c::s) cs false [];
paulson@21978
   139
paulson@21978
   140
(*This version does not look for standard prefixes first.*)
paulson@21978
   141
fun normalise_string s = normalise_s [] (String.explode s) false [];
paulson@21978
   142
paulson@21978
   143
paulson@21978
   144
(**** INTERPRETATION OF TSTP SYNTAX TREES ****)
paulson@21978
   145
paulson@21978
   146
exception STREE of stree;
paulson@21978
   147
paulson@21978
   148
(*If string s has the prefix s1, return the result of deleting it.*)
paulson@21978
   149
fun strip_prefix s1 s = 
paulson@21978
   150
  if String.isPrefix s1 s then SOME (normalise_string (String.extract (s, size s1, NONE)))
paulson@21978
   151
  else NONE;
paulson@21978
   152
paulson@21978
   153
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   154
val type_const_trans_table_inv =
paulson@21978
   155
      Symtab.make (map swap (Symtab.dest ResClause.type_const_trans_table));
paulson@21978
   156
paulson@21978
   157
fun invert_type_const c =
paulson@21978
   158
    case Symtab.lookup type_const_trans_table_inv c of
paulson@21978
   159
        SOME c' => c'
paulson@21978
   160
      | NONE => c;
paulson@21978
   161
paulson@21978
   162
fun make_tvar b = TVar(("'" ^ b, 0), HOLogic.typeS);
paulson@21978
   163
fun make_var (b,T) = Var((b,0),T);
paulson@21978
   164
paulson@21978
   165
(*Type variables are given the basic sort, HOL.type. Some will later be constrained
paulson@21978
   166
  by information from type literals, or by type inference.*)
paulson@21978
   167
fun type_of_stree t =
paulson@21978
   168
  case t of
paulson@21978
   169
      Int _ => raise STREE t
paulson@21978
   170
    | Br (a,ts) => 
paulson@21978
   171
        let val Ts = map type_of_stree ts
paulson@21978
   172
        in 
paulson@21978
   173
          case strip_prefix ResClause.tconst_prefix a of
paulson@21978
   174
              SOME b => Type(invert_type_const b, Ts)
paulson@21978
   175
            | NONE => 
paulson@21978
   176
                if not (null ts) then raise STREE t  (*only tconsts have type arguments*)
paulson@21978
   177
                else 
paulson@21978
   178
                case strip_prefix ResClause.tfree_prefix a of
paulson@21978
   179
                    SOME b => TFree("'" ^ b, HOLogic.typeS)
paulson@21978
   180
                  | NONE => 
paulson@21978
   181
                case strip_prefix ResClause.tvar_prefix a of
paulson@21978
   182
                    SOME b => make_tvar b
paulson@21978
   183
                  | NONE => make_tvar a   (*Variable from the ATP, say X1*)
paulson@21978
   184
        end;
paulson@21978
   185
paulson@21978
   186
(*Invert the table of translations between Isabelle and ATPs*)
paulson@21978
   187
val const_trans_table_inv =
paulson@21978
   188
      Symtab.make (map swap (Symtab.dest ResClause.const_trans_table));
paulson@21978
   189
paulson@21978
   190
fun invert_const c =
paulson@21978
   191
    case Symtab.lookup const_trans_table_inv c of
paulson@21978
   192
        SOME c' => c'
paulson@21978
   193
      | NONE => c;
paulson@21978
   194
paulson@21978
   195
(*The number of type arguments of a constant, zero if it's monomorphic*)
paulson@21978
   196
fun num_typargs thy s = length (Sign.const_typargs thy (s, Sign.the_const_type thy s));
paulson@21978
   197
paulson@21978
   198
(*Generates a constant, given its type arguments*)
paulson@21978
   199
fun const_of thy (a,Ts) = Const(a, Sign.const_instance thy (a,Ts));
paulson@21978
   200
paulson@21978
   201
(*First-order translation. No types are known for variables. HOLogic.typeT should allow
paulson@21978
   202
  them to be inferred.*)
paulson@21978
   203
fun term_of_stree thy t =
paulson@21978
   204
  case t of
paulson@21978
   205
      Int _ => raise STREE t
paulson@21978
   206
    | Br (a,ts) => 
paulson@21978
   207
        case strip_prefix ResClause.const_prefix a of
paulson@21978
   208
            SOME "equal" => 
paulson@21978
   209
              if length ts = 2 then
paulson@21978
   210
                list_comb(Const ("op =", HOLogic.typeT), List.map (term_of_stree thy) ts)
paulson@21978
   211
              else raise STREE t  (*equality needs two arguments*)
paulson@21978
   212
          | SOME b => 
paulson@21978
   213
              let val c = invert_const b
paulson@21978
   214
                  val nterms = length ts - num_typargs thy c
paulson@21978
   215
                  val us = List.map (term_of_stree thy) (List.take(ts,nterms))
paulson@21978
   216
                  val Ts = List.map type_of_stree (List.drop(ts,nterms))
paulson@21978
   217
              in  list_comb(const_of thy (c, Ts), us)  end
paulson@21978
   218
          | NONE => (*a variable, not a constant*)
paulson@21978
   219
              let val T = HOLogic.typeT
paulson@21978
   220
                  val opr = (*a Free variable is typically a Skolem function*)
paulson@21978
   221
                    case strip_prefix ResClause.fixed_var_prefix a of
paulson@21978
   222
                        SOME b => Free(b,T)
paulson@21978
   223
                      | NONE => 
paulson@21978
   224
                    case strip_prefix ResClause.schematic_var_prefix a of
paulson@21978
   225
                        SOME b => make_var (b,T)
paulson@21978
   226
                      | NONE => make_var (a,T)    (*Variable from the ATP, say X1*)
paulson@21978
   227
              in  list_comb (opr, List.map (term_of_stree thy) ts)  end;
paulson@21978
   228
paulson@21978
   229
(*Type class literal applied to a type. Returns triple of polarity, class, type.*)                  
paulson@21978
   230
fun constraint_of_stree pol (Br("c_Not",[t])) = constraint_of_stree (not pol) t
paulson@21978
   231
  | constraint_of_stree pol t = case t of
paulson@21978
   232
        Int _ => raise STREE t
paulson@21978
   233
      | Br (a,ts) => 
paulson@21978
   234
            (case (strip_prefix ResClause.class_prefix a, map type_of_stree ts) of
paulson@21978
   235
                 (SOME b, [T]) => (pol, b, T)
paulson@21978
   236
               | _ => raise STREE t);
paulson@21978
   237
paulson@21978
   238
(** Accumulate type constraints in a clause: negative type literals **)
paulson@21978
   239
paulson@21978
   240
fun addix (key,z)  = Vartab.map_default (key,[]) (cons z);
paulson@21978
   241
paulson@21978
   242
fun add_constraint ((false, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   243
  | add_constraint ((false, cl, TVar(ix,_)), vt) = addix (ix,cl) vt
paulson@21978
   244
  | add_constraint (_, vt) = vt;
paulson@21978
   245
paulson@21978
   246
(*False literals (which E includes in its proofs) are deleted*)
paulson@21978
   247
val nofalses = filter (not o equal HOLogic.false_const);
paulson@21978
   248
paulson@21978
   249
(*Accumulate sort constraints in vt, with "real" literals in lits.*)
paulson@21978
   250
fun lits_of_strees thy (vt, lits) [] = (vt, rev (nofalses lits))
paulson@21978
   251
  | lits_of_strees thy (vt, lits) (t::ts) = 
paulson@21978
   252
      lits_of_strees thy (add_constraint (constraint_of_stree true t, vt), lits) ts
paulson@21978
   253
      handle STREE _ => 
paulson@21978
   254
      lits_of_strees thy (vt, term_of_stree thy t :: lits) ts;
paulson@21978
   255
paulson@21978
   256
(*Update TVars/TFrees with detected sort constraints.*)
paulson@21978
   257
fun fix_sorts vt =
paulson@21978
   258
  let fun tysubst (Type (a, Ts)) = Type (a, map tysubst Ts)
paulson@21978
   259
        | tysubst (TVar (xi, s)) = TVar (xi, getOpt (Vartab.lookup vt xi, s))
paulson@21978
   260
        | tysubst (TFree (x, s)) = TFree (x, getOpt (Vartab.lookup vt (x,~1), s))
paulson@21978
   261
      fun tmsubst (Const (a, T)) = Const (a, tysubst T)
paulson@21978
   262
        | tmsubst (Free (a, T)) = Free (a, tysubst T)
paulson@21978
   263
        | tmsubst (Var (xi, T)) = Var (xi, tysubst T)
paulson@21978
   264
        | tmsubst (t as Bound _) = t
paulson@21978
   265
        | tmsubst (Abs (a, T, t)) = Abs (a, tysubst T, tmsubst t)
paulson@21978
   266
        | tmsubst (t $ u) = tmsubst t $ tmsubst u;
paulson@21978
   267
  in fn t => if Vartab.is_empty vt then t else tmsubst t end;
paulson@21978
   268
paulson@21978
   269
(*Interpret a list of syntax trees as a clause, given by "real" literals and sort constraints.
paulson@21978
   270
  vt0 holds the initial sort constraints, from the conjecture clauses.*)
paulson@21978
   271
fun clause_of_strees_aux thy vt0 ts = 
paulson@21978
   272
  case lits_of_strees thy (vt0,[]) ts of
paulson@21978
   273
      (_, []) => HOLogic.false_const
paulson@21978
   274
    | (vt, lits) => 
paulson@21978
   275
        let val dt = fix_sorts vt (foldr1 HOLogic.mk_disj lits)
paulson@21978
   276
            val infer = Sign.infer_types (Sign.pp thy) thy (Sign.consts_of thy)
paulson@21978
   277
        in 
paulson@21978
   278
           #1(infer (K NONE) (K NONE) (Name.make_context []) true ([dt], HOLogic.boolT))
paulson@21978
   279
        end; 
paulson@21978
   280
paulson@21978
   281
(*Quantification over a list of Vars. FUXNE: for term.ML??*)
paulson@21978
   282
fun list_all_var ([], t: term) = t
paulson@21978
   283
  | list_all_var ((v as Var(ix,T)) :: vars, t) =
paulson@21979
   284
      (all T) $ Abs(string_of_indexname ix, T, abstract_over (v, list_all_var (vars,t)));
paulson@21978
   285
paulson@21978
   286
fun gen_all_vars t = list_all_var (term_vars t, t);
paulson@21978
   287
paulson@21978
   288
fun clause_of_strees thy vt0 ts =
paulson@21978
   289
  gen_all_vars (HOLogic.mk_Trueprop (clause_of_strees_aux thy vt0 ts));
paulson@21978
   290
paulson@21978
   291
fun ints_of_stree_aux (Int n, ns) = n::ns
paulson@21978
   292
  | ints_of_stree_aux (Br(_,ts), ns) = foldl ints_of_stree_aux ns ts;
paulson@21978
   293
paulson@21978
   294
fun ints_of_stree t = ints_of_stree_aux (t, []);
paulson@21978
   295
paulson@21978
   296
fun decode_tstp thy vt0 (name, role, ts, annots) =
paulson@21978
   297
  let val deps = case annots of NONE => [] | SOME (source,_) => ints_of_stree source
paulson@21978
   298
  in  (name, role, clause_of_strees thy vt0 ts, deps)  end;
paulson@21978
   299
paulson@21978
   300
fun dest_tstp ((((name, role), ts), annots), chs) =
paulson@21978
   301
  case chs of
paulson@21978
   302
          "."::_ => (name, role, ts, annots)
paulson@21978
   303
        | _ => error ("TSTP line not terminated by \".\": " ^ implode chs);
paulson@21978
   304
paulson@21978
   305
paulson@21978
   306
(** Global sort constraints on TFrees (from tfree_tcs) are positive unit clauses. **)
paulson@21978
   307
paulson@21978
   308
fun add_tfree_constraint ((true, cl, TFree(a,_)), vt) = addix ((a,~1),cl) vt
paulson@21978
   309
  | add_tfree_constraint (_, vt) = vt;
paulson@21978
   310
paulson@21978
   311
fun tfree_constraints_of_clauses vt [] = vt
paulson@21978
   312
  | tfree_constraints_of_clauses vt ([lit]::tss) = 
paulson@21978
   313
      (tfree_constraints_of_clauses (add_tfree_constraint (constraint_of_stree true lit, vt)) tss
paulson@21978
   314
       handle STREE _ => (*not a positive type constraint: ignore*)
paulson@21978
   315
       tfree_constraints_of_clauses vt tss)
paulson@21978
   316
  | tfree_constraints_of_clauses vt (_::tss) = tfree_constraints_of_clauses vt tss;
paulson@21978
   317
paulson@21978
   318
paulson@21978
   319
(**** Translation of TSTP files to Isar Proofs ****)
paulson@21978
   320
paulson@21978
   321
fun decode_tstp_list thy tuples =
paulson@21978
   322
  let val vt0 = tfree_constraints_of_clauses Vartab.empty (map #3 tuples)
paulson@21978
   323
  in  map (decode_tstp thy vt0) tuples  end;
paulson@21978
   324
paulson@21978
   325
fun isar_lines ctxt =
paulson@21978
   326
  let val string_of = ProofContext.string_of_term ctxt
paulson@21978
   327
      fun doline hs (lname, t, []) =  (*No deps: it's a conjecture clause, with no proof.*)
paulson@21978
   328
            "assume " ^ lname ^ ": \"" ^ string_of t ^ "\"\n"
paulson@21978
   329
        | doline hs (lname, t, deps) =
paulson@21978
   330
            hs ^ lname ^ ": \"" ^ string_of t ^ 
paulson@21978
   331
            "\"\n  by (meson " ^ space_implode " " deps ^ ")\n"
paulson@21978
   332
      fun dolines [(lname, t, deps)] = [doline "show " (lname, t, deps)]
paulson@21978
   333
        | dolines ((lname, t, deps)::lines) = doline "have " (lname, t, deps) :: dolines lines
paulson@21978
   334
  in setmp show_sorts true dolines end;
paulson@21978
   335
paulson@21978
   336
fun notequal t (_,t',_) = not (t aconv t');
paulson@21978
   337
paulson@21978
   338
fun eq_false t = t aconv (HOLogic.mk_Trueprop HOLogic.false_const);
paulson@21978
   339
paulson@21978
   340
fun replace_dep (old, new) dep = if dep=old then new else [dep];
paulson@21978
   341
paulson@21978
   342
fun replace_deps (old, new) (lno, t, deps) = 
paulson@21978
   343
      (lno, t, List.concat (map (replace_dep (old, new)) deps));
paulson@21978
   344
paulson@21978
   345
(*Discard axioms and also False conjecture clauses (which can only contain type information).
paulson@21978
   346
  Consolidate adjacent lines that prove the same clause, since they differ only in type
paulson@21978
   347
  information.*)
paulson@21978
   348
fun add_prfline ((lno, "axiom", t, []), lines) =  (*axioms are not proof lines*)
paulson@21978
   349
      if eq_false t then lines   (*must be clsrel/clsarity: type information*)
paulson@21978
   350
      else (case take_prefix (notequal t) lines of
paulson@21978
   351
               (_,[]) => lines   (*no repetition of proof line*)
paulson@21978
   352
             | (pre, (lno',t',deps')::post) => 
paulson@21978
   353
                 pre @ map (replace_deps (lno', [lno])) post)
paulson@21978
   354
  | add_prfline ((lno, role, t, []), lines) =  (*no deps: conjecture clause*)
paulson@21978
   355
      if eq_false t then lines   (*must be tfree_tcs: type information*)
paulson@21978
   356
      else (lno, t, []) :: lines
paulson@21978
   357
  | add_prfline ((lno, role, t, deps), lines) =
paulson@21978
   358
      (case term_tvars t of (*Delete line if it has TVars: they are forbidden in goals*)
paulson@21978
   359
          _::_ => map (replace_deps (lno, deps)) lines
paulson@21978
   360
        | [] => 
paulson@21978
   361
            case take_prefix (notequal t) lines of
paulson@21978
   362
               (_,[]) => (lno, t, deps) :: lines   (*no repetition of proof line*)
paulson@21978
   363
             | (pre, (lno',t',deps')::post) => 
paulson@21978
   364
                 (lno, t', deps) ::  (*replace later line by earlier one*)
paulson@21978
   365
                 (pre @ map (replace_deps (lno', [lno])) post));
paulson@21978
   366
paulson@21978
   367
(*Replace numeric proof lines by strings.*)
paulson@21978
   368
fun stringify_deps thm_names deps_map [] = []
paulson@21978
   369
  | stringify_deps thm_names deps_map ((lno, t, deps) :: lines) =
paulson@21978
   370
      if lno <= Vector.length thm_names  (*axiom*)
paulson@21978
   371
      then (Vector.sub(thm_names,lno-1), t, []) :: stringify_deps thm_names deps_map lines 
paulson@21979
   372
      else let val lname = Int.toString (length deps_map)
paulson@21978
   373
               fun fix lno = if lno <= Vector.length thm_names  
paulson@21978
   374
                             then SOME(Vector.sub(thm_names,lno-1))
paulson@21978
   375
                             else AList.lookup op= deps_map lno;
paulson@21978
   376
           in  (lname, t, List.mapPartial fix deps) ::
paulson@21978
   377
               stringify_deps thm_names ((lno,lname)::deps_map) lines
paulson@21978
   378
           end;
paulson@21978
   379
paulson@21979
   380
val proofstart = "\nproof (rule ccontr, skolemize, make_clauses)\n";
paulson@21979
   381
paulson@21979
   382
fun string_of_Free (Free (x,_)) = x
paulson@21979
   383
  | string_of_Free _ = "??string_of_Free??";
paulson@21979
   384
paulson@21979
   385
fun isar_header [] = proofstart
paulson@21979
   386
  | isar_header ts = proofstart ^ "fix " ^ space_implode " " (map string_of_Free ts) ^ "\n";
paulson@21979
   387
paulson@21978
   388
fun decode_tstp_file ctxt (cnfs,thm_names) =
paulson@21978
   389
  let val tuples = map (dest_tstp o tstp_line o explode) cnfs
paulson@21979
   390
      val decoded_tuples = decode_tstp_list (ProofContext.theory_of ctxt) tuples
paulson@21979
   391
      val lines = foldr add_prfline [] decoded_tuples
paulson@21979
   392
      and fixes = foldr add_term_frees [] (map #3 decoded_tuples)
paulson@21979
   393
  in  
paulson@21979
   394
      isar_header fixes ^ 
paulson@21979
   395
      String.concat (isar_lines ctxt (stringify_deps thm_names [] lines))
paulson@21979
   396
  end;
paulson@21978
   397
paulson@21978
   398
(*Could use split_lines, but it can return blank lines...*)
paulson@21978
   399
val lines = String.tokens (equal #"\n");
paulson@21978
   400
paulson@21978
   401
val nospaces = String.translate (fn c => if Char.isSpace c then "" else str c);
paulson@21978
   402
paulson@21978
   403
(*The output to the watcher must be a SINGLE line...clearly \t must not be used.*)
paulson@21978
   404
val encode_newlines = String.translate (fn c => if c = #"\n" then "\t" else str c);
paulson@21978
   405
val restore_newlines = String.translate (fn c => if c = #"\t" then "\n" else str c);
paulson@21978
   406
paulson@21978
   407
fun signal_success probfile toParent ppid msg = 
paulson@21978
   408
  (trace ("\nReporting Success for" ^ probfile ^ "\n" ^ msg);
paulson@21978
   409
   TextIO.output (toParent, "Success. " ^ encode_newlines msg ^ "\n");
paulson@21978
   410
   TextIO.output (toParent, probfile ^ "\n");
paulson@21978
   411
   TextIO.flushOut toParent;
paulson@21978
   412
   Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2));
paulson@21978
   413
paulson@21978
   414
fun tstp_extract proofextract probfile toParent ppid th sgno thm_names = 
paulson@21978
   415
  let val cnfs = filter (String.isPrefix "cnf(") (map nospaces (lines proofextract))
paulson@21978
   416
      and ctxt = ProofContext.init (Thm.theory_of_thm th)
paulson@21978
   417
       (*The full context could be sent from ResAtp.isar_atp_body to Watcher.createWatcher,
paulson@21978
   418
         then to setupWatcher and checkChildren...but is it needed?*)
paulson@21978
   419
  in  
paulson@21978
   420
    signal_success probfile toParent ppid 
paulson@21978
   421
      (decode_tstp_file ctxt (cnfs,thm_names))
paulson@21978
   422
  end;
paulson@21978
   423
paulson@21978
   424
paulson@21978
   425
(**** retrieve the axioms that were used in the proof ****)
paulson@21978
   426
paulson@21978
   427
(*Get names of axioms used. Axioms are indexed from 1, while the vector is indexed from 0*)
paulson@21978
   428
fun get_axiom_names (thm_names: string vector) step_nums = 
paulson@21978
   429
    let fun is_axiom n = n <= Vector.length thm_names 
paulson@21978
   430
        fun index i = Vector.sub(thm_names, i-1)
paulson@21978
   431
        val axnums = List.filter is_axiom step_nums
paulson@21978
   432
        val axnames = sort_distinct string_ord (map index axnums)
paulson@21978
   433
    in
paulson@21978
   434
	if length axnums = length step_nums then "UNSOUND!!" :: axnames
paulson@21978
   435
	else axnames
paulson@21978
   436
    end
paulson@21978
   437
paulson@21978
   438
 (*String contains multiple lines. We want those of the form 
paulson@21978
   439
     "253[0:Inp] et cetera..."
paulson@21978
   440
  A list consisting of the first number in each line is returned. *)
paulson@21978
   441
fun get_spass_linenums proofstr = 
paulson@21978
   442
  let val toks = String.tokens (not o Char.isAlphaNum)
paulson@21978
   443
      fun inputno (ntok::"0"::"Inp"::_) = Int.fromString ntok
paulson@21978
   444
        | inputno _ = NONE
paulson@21978
   445
      val lines = String.tokens (fn c => c = #"\n") proofstr
paulson@21978
   446
  in  List.mapPartial (inputno o toks) lines  end
paulson@21978
   447
paulson@21978
   448
fun get_axiom_names_spass proofstr thm_names =
paulson@21978
   449
   get_axiom_names thm_names (get_spass_linenums proofstr);
paulson@21978
   450
    
paulson@21978
   451
fun not_comma c = c <>  #",";
paulson@21978
   452
paulson@21978
   453
(*A valid TSTP axiom line has the form  cnf(NNN,axiom,...) where NNN is a positive integer.*)
paulson@21978
   454
fun parse_tstp_line s =
paulson@21978
   455
  let val ss = Substring.full (unprefix "cnf(" (nospaces s))
paulson@21978
   456
      val (intf,rest) = Substring.splitl not_comma ss
paulson@21978
   457
      val (rolef,rest) = Substring.splitl not_comma (Substring.triml 1 rest)
paulson@21978
   458
      (*We only allow negated_conjecture because the line number will be removed in
paulson@21978
   459
        get_axiom_names above, while suppressing the UNSOUND warning*)
paulson@21978
   460
      val ints = if Substring.string rolef mem_string ["axiom","negated_conjecture"]
paulson@21978
   461
                 then Substring.string intf 
paulson@21978
   462
                 else "error" 
paulson@21978
   463
  in  Int.fromString ints  end
paulson@21978
   464
  handle Fail _ => NONE; 
paulson@21978
   465
paulson@21978
   466
fun get_axiom_names_tstp proofstr thm_names =
paulson@21978
   467
   get_axiom_names thm_names (List.mapPartial parse_tstp_line (split_lines proofstr));
paulson@21978
   468
    
paulson@21978
   469
 (*String contains multiple lines. We want those of the form 
paulson@21978
   470
     "*********** [448, input] ***********".
paulson@21978
   471
  A list consisting of the first number in each line is returned. *)
paulson@21978
   472
fun get_vamp_linenums proofstr = 
paulson@21978
   473
  let val toks = String.tokens (not o Char.isAlphaNum)
paulson@21978
   474
      fun inputno [ntok,"input"] = Int.fromString ntok
paulson@21978
   475
        | inputno _ = NONE
paulson@21978
   476
      val lines = String.tokens (fn c => c = #"\n") proofstr
paulson@21978
   477
  in  List.mapPartial (inputno o toks) lines  end
paulson@21978
   478
paulson@21978
   479
fun get_axiom_names_vamp proofstr thm_names =
paulson@21978
   480
   get_axiom_names thm_names (get_vamp_linenums proofstr);
paulson@21978
   481
    
paulson@21978
   482
fun rules_to_string [] = "NONE"
paulson@21978
   483
  | rules_to_string xs = space_implode "  " xs
paulson@21978
   484
paulson@21978
   485
paulson@21978
   486
(*The signal handler in watcher.ML must be able to read the output of this.*)
paulson@21978
   487
fun prover_lemma_list_aux getax proofstr probfile toParent ppid thm_names = 
paulson@21978
   488
 (trace ("\n\nGetting lemma names. proofstr is " ^ proofstr ^
paulson@21978
   489
         " num of clauses is " ^ string_of_int (Vector.length thm_names));
paulson@21978
   490
  signal_success probfile toParent ppid 
paulson@21978
   491
    ("Lemmas used in automatic proof: " ^ rules_to_string (getax proofstr thm_names)))
paulson@21978
   492
 handle e => (*FIXME: exn handler is too general!*)
paulson@21978
   493
  (trace ("\nprover_lemma_list_aux: In exception handler: " ^ Toplevel.exn_message e);
paulson@21978
   494
   TextIO.output (toParent, "Translation failed for the proof: " ^ 
paulson@21978
   495
                  String.toString proofstr ^ "\n");
paulson@21978
   496
   TextIO.output (toParent, probfile);
paulson@21978
   497
   TextIO.flushOut toParent;
paulson@21978
   498
   Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2));
paulson@21978
   499
paulson@21978
   500
val e_lemma_list = prover_lemma_list_aux get_axiom_names_tstp;
paulson@21978
   501
paulson@21978
   502
val vamp_lemma_list = prover_lemma_list_aux get_axiom_names_vamp;
paulson@21978
   503
paulson@21978
   504
val spass_lemma_list = prover_lemma_list_aux get_axiom_names_spass;
paulson@21978
   505
paulson@21978
   506
paulson@21978
   507
(**** Extracting proofs from an ATP's output ****)
paulson@21978
   508
paulson@21978
   509
(*Return everything in s that comes before the string t*)
paulson@21978
   510
fun cut_before t s = 
paulson@21978
   511
  let val (s1,s2) = Substring.position t (Substring.full s)
paulson@21978
   512
  in  if Substring.size s2 = 0 then error "cut_before: string not found" 
paulson@21978
   513
      else Substring.string s2
paulson@21978
   514
  end;
paulson@21978
   515
paulson@21978
   516
val start_E = "# Proof object starts here."
paulson@21978
   517
val end_E   = "# Proof object ends here."
paulson@21978
   518
val start_V6 = "%================== Proof: ======================"
paulson@21978
   519
val end_V6   = "%==============  End of proof. =================="
paulson@21978
   520
val start_V8 = "=========== Refutation =========="
paulson@21978
   521
val end_V8 = "======= End of refutation ======="
paulson@21978
   522
val end_SPASS = "Formulae used in the proof"
paulson@21978
   523
paulson@21978
   524
(*********************************************************************************)
paulson@21978
   525
(*  Inspect the output of an ATP process to see if it has found a proof,     *)
paulson@21978
   526
(*  and if so, transfer output to the input pipe of the main Isabelle process    *)
paulson@21978
   527
(*********************************************************************************)
paulson@21978
   528
paulson@21978
   529
(*Returns "true" if it successfully returns a lemma list, otherwise "false", but this
paulson@21978
   530
  return value is currently never used!*)
paulson@21978
   531
fun startTransfer (endS, fromChild, toParent, ppid, probfile, th, sgno, thm_names) =
paulson@21978
   532
 let fun transferInput currentString =
paulson@21978
   533
      let val thisLine = TextIO.inputLine fromChild
paulson@21978
   534
      in
paulson@21978
   535
	if thisLine = "" (*end of file?*)
paulson@21978
   536
	then (trace ("\n extraction_failed.  End bracket: " ^ endS ^
paulson@21978
   537
	             "\naccumulated text: " ^ currentString);
paulson@21978
   538
	      false)                    
paulson@21978
   539
	else if String.isPrefix endS thisLine
paulson@21978
   540
	then let val proofextract = currentString ^ cut_before endS thisLine
paulson@21978
   541
	         val lemma_list = if endS = end_V8 then vamp_lemma_list
paulson@21978
   542
			  	  else if endS = end_SPASS then spass_lemma_list
paulson@21978
   543
			  	  else e_lemma_list
paulson@21978
   544
	     in
paulson@21978
   545
	       trace ("\nExtracted proof:\n" ^ proofextract); 
paulson@21978
   546
	       if !full andalso String.isPrefix "cnf(" proofextract
paulson@21978
   547
	       then tstp_extract proofextract probfile toParent ppid th sgno thm_names
paulson@21978
   548
	       else lemma_list proofextract probfile toParent ppid thm_names;
paulson@21978
   549
	       true
paulson@21978
   550
	     end
paulson@21978
   551
	else transferInput (currentString^thisLine)
paulson@21978
   552
      end
paulson@21978
   553
 in
paulson@21978
   554
     transferInput ""
paulson@21978
   555
 end 
paulson@21978
   556
paulson@21978
   557
paulson@21978
   558
(*The signal handler in watcher.ML must be able to read the output of this.*)
paulson@21978
   559
fun signal_parent (toParent, ppid, msg, probfile) =
paulson@21978
   560
 (TextIO.output (toParent, msg);
paulson@21978
   561
  TextIO.output (toParent, probfile ^ "\n");
paulson@21978
   562
  TextIO.flushOut toParent;
paulson@21978
   563
  trace ("\nSignalled parent: " ^ msg ^ probfile);
paulson@21978
   564
  Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
paulson@21978
   565
  (*Give the parent time to respond before possibly sending another signal*)
paulson@21978
   566
  OS.Process.sleep (Time.fromMilliseconds 600));
paulson@21978
   567
paulson@21978
   568
(*Called from watcher. Returns true if the Vampire process has returned a verdict.*)
paulson@21978
   569
fun checkVampProofFound (fromChild, toParent, ppid, probfile, th, sgno, thm_names) =
paulson@21978
   570
 let val thisLine = TextIO.inputLine fromChild
paulson@21978
   571
 in   
paulson@21978
   572
     trace thisLine;
paulson@21978
   573
     if thisLine = "" 
paulson@21978
   574
     then (trace "\nNo proof output seen"; false)
paulson@21978
   575
     else if String.isPrefix start_V8 thisLine
paulson@21978
   576
     then startTransfer (end_V8, fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   577
     else if (String.isPrefix "Satisfiability detected" thisLine) orelse
paulson@21978
   578
             (String.isPrefix "Refutation not found" thisLine)
paulson@21978
   579
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   580
	   true)
paulson@21978
   581
     else checkVampProofFound  (fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   582
  end
paulson@21978
   583
paulson@21978
   584
(*Called from watcher. Returns true if the E process has returned a verdict.*)
paulson@21978
   585
fun checkEProofFound (fromChild, toParent, ppid, probfile, th, sgno, thm_names) = 
paulson@21978
   586
 let val thisLine = TextIO.inputLine fromChild  
paulson@21978
   587
 in   
paulson@21978
   588
     trace thisLine;
paulson@21978
   589
     if thisLine = "" then (trace "\nNo proof output seen"; false)
paulson@21978
   590
     else if String.isPrefix start_E thisLine
paulson@21978
   591
     then startTransfer (end_E, fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   592
     else if String.isPrefix "# Problem is satisfiable" thisLine
paulson@21978
   593
     then (signal_parent (toParent, ppid, "Invalid\n", probfile);
paulson@21978
   594
	   true)
paulson@21978
   595
     else if String.isPrefix "# Cannot determine problem status within resource limit" thisLine
paulson@21978
   596
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   597
	   true)
paulson@21978
   598
     else checkEProofFound (fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   599
 end;
paulson@21978
   600
paulson@21978
   601
(*Called from watcher. Returns true if the SPASS process has returned a verdict.*)
paulson@21978
   602
fun checkSpassProofFound (fromChild, toParent, ppid, probfile, th, sgno, thm_names) = 
paulson@21978
   603
 let val thisLine = TextIO.inputLine fromChild  
paulson@21978
   604
 in    
paulson@21978
   605
     trace thisLine;
paulson@21978
   606
     if thisLine = "" then (trace "\nNo proof output seen"; false)
paulson@21978
   607
     else if String.isPrefix "Here is a proof" thisLine
paulson@21978
   608
     then      
paulson@21978
   609
        startTransfer (end_SPASS, fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   610
     else if thisLine = "SPASS beiseite: Completion found.\n"
paulson@21978
   611
     then (signal_parent (toParent, ppid, "Invalid\n", probfile);
paulson@21978
   612
	   true)
paulson@21978
   613
     else if thisLine = "SPASS beiseite: Ran out of time.\n" orelse
paulson@21978
   614
             thisLine = "SPASS beiseite: Maximal number of loops exceeded.\n"
paulson@21978
   615
     then (signal_parent (toParent, ppid, "Failure\n", probfile);
paulson@21978
   616
	   true)
paulson@21978
   617
    else checkSpassProofFound (fromChild, toParent, ppid, probfile, th, sgno, thm_names)
paulson@21978
   618
 end
paulson@21978
   619
paulson@21978
   620
end;