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