src/HOL/Tools/ATP/recon_transfer_proof.ML
author paulson
Thu Aug 18 13:09:40 2005 +0200 (2005-08-18)
changeset 17122 278eb6251dc0
parent 16905 fa26952fa7b6
child 17235 8e55ad29b690
permissions -rw-r--r--
nicer list of axioms used
     1 (*  ID:         $Id$
     2     Author:     Claire Quigley
     3     Copyright   2004  University of Cambridge
     4 *)
     5 
     6 (******************)
     7 (* complete later *)
     8 (******************)
     9 
    10 structure Recon_Transfer =
    11 struct
    12 
    13 open Recon_Parse
    14 
    15 infixr 8 ++; infixr 7 >>; infixr 6 ||;
    16 
    17 
    18 (* Versions that include type information *)
    19  
    20 (* FIXME rename to str_of_thm *)
    21 fun string_of_thm thm =
    22   setmp show_sorts true (Pretty.str_of o Display.pretty_thm) thm;
    23 
    24 
    25 (* check separate args in the watcher program for separating strings with a * or ; or something *)
    26 
    27 fun clause_strs_to_string [] str = str
    28 |   clause_strs_to_string (x::xs) str = clause_strs_to_string xs (str^x^"%")
    29 
    30 fun thmvars_to_string [] str = str
    31 |   thmvars_to_string (x::xs) str = thmvars_to_string xs (str^x^"%")
    32 
    33 
    34 fun proofstep_to_string Axiom = "Axiom()"
    35 |   proofstep_to_string  (Binary ((a,b), (c,d)))=
    36       "Binary(("^(string_of_int a)^","^(string_of_int b)^"),("^(string_of_int c)^","^(string_of_int d)^"))"
    37 |   proofstep_to_string (Factor (a,b,c)) =
    38       "Factor("^(string_of_int a)^","^(string_of_int b)^","^(string_of_int c)^")"
    39 |   proofstep_to_string  (Para ((a,b), (c,d)))= 
    40       "Para(("^(string_of_int a)^","^(string_of_int b)^"),("^(string_of_int c)^","^(string_of_int d)^"))"
    41 |   proofstep_to_string  (MRR ((a,b), (c,d))) =
    42       "MRR(("^(string_of_int a)^","^(string_of_int b)^"),("^(string_of_int c)^","^(string_of_int d)^"))"
    43 (*|   proofstep_to_string (Rewrite((a,b),(c,d))) =
    44       "Rewrite(("^(string_of_int a)^","^(string_of_int b)^"),("^(string_of_int c)^","^(string_of_int d)^"))"*)
    45 
    46 fun list_to_string [] liststr = liststr
    47 |   list_to_string (x::[]) liststr = liststr^(string_of_int x)
    48 |   list_to_string (x::xs) liststr = list_to_string xs (liststr^(string_of_int x)^",")
    49 
    50 
    51 fun proof_to_string (num,(step,clause_strs, thmvars)) = (string_of_int num)^(proofstep_to_string step)^"["^(clause_strs_to_string clause_strs "")^"]["^(thmvars_to_string thmvars "")^"]"
    52  
    53 
    54 fun proofs_to_string [] str = str
    55 |   proofs_to_string (x::xs) str = let val newstr = proof_to_string x 
    56                                    in
    57                                        proofs_to_string xs (str^newstr)
    58                                    end
    59 
    60 
    61 
    62 fun init_proofstep_to_string (num, step, clause_strs) = (string_of_int num)^" "^(proofstep_to_string step)^" "^(clause_strs_to_string clause_strs "")^" "
    63 
    64 fun init_proofsteps_to_string [] str = str
    65 |   init_proofsteps_to_string (x::xs) str = let val newstr = init_proofstep_to_string x 
    66                                    in
    67                                        init_proofsteps_to_string xs (str^newstr)
    68                                    end
    69   
    70 
    71 
    72 (*** get a string representing the Isabelle ordered axioms ***)
    73 
    74 fun origAx_to_string (num,(meta,thmvars)) =
    75     let val clause_strs = ReconOrderClauses.get_meta_lits_bracket meta
    76     in
    77        (string_of_int num)^"OrigAxiom()["^
    78        (clause_strs_to_string clause_strs "")^"]["^
    79        (thmvars_to_string thmvars "")^"]"
    80     end
    81 
    82 
    83 fun  origAxs_to_string [] str = str
    84 |   origAxs_to_string (x::xs) str = let val newstr = origAx_to_string x 
    85                                    in
    86                                        origAxs_to_string xs (str^newstr)
    87                                    end
    88 
    89 
    90 (*** get a string representing the Isabelle ordered axioms not used in the spass proof***)
    91 
    92 fun extraAx_to_string (num, (meta,thmvars)) =
    93    let val clause_strs = ReconOrderClauses.get_meta_lits_bracket meta
    94    in
    95       (string_of_int num)^"ExtraAxiom()["^
    96       (clause_strs_to_string clause_strs "")^"]"^
    97       "["^(thmvars_to_string thmvars "")^"]"
    98    end;
    99 
   100 fun extraAxs_to_string [] str = str
   101 |   extraAxs_to_string (x::xs) str =
   102       let val newstr = extraAx_to_string x 
   103       in
   104 	  extraAxs_to_string xs (str^newstr)
   105       end;
   106 
   107 fun is_axiom ( num:int,Axiom, str) = true
   108 |   is_axiom (num, _,_) = false
   109 
   110 fun get_init_axioms xs = List.filter (is_axiom) ( xs)
   111 
   112 fun get_step_nums [] nums = nums
   113 |   get_step_nums (( num:int,Axiom, str)::xs) nums = get_step_nums xs (nums@[num])
   114 
   115 exception Noassoc;
   116 
   117 fun assoc_snd a [] = raise Noassoc
   118   | assoc_snd a ((x, y)::t) = if a = y then x else assoc_snd a t;
   119 
   120 (* change to be something using check_order  instead of a = y --> returns true if ASSERTION not raised in checkorder, false otherwise *)
   121 
   122 (*fun get_assoc_snds [] xs assocs= assocs
   123 |   get_assoc_snds (x::xs) ys assocs = get_assoc_snds xs ys (assocs@[((assoc_snd x ys))])
   124 *)
   125 (*FIX - should this have vars in it? *)
   126 fun there_out_of_order xs ys = (ReconOrderClauses.checkorder xs ys [] ([],[],[]); true) 
   127                                handle _ => false
   128 
   129 fun assoc_out_of_order a [] = raise Noassoc
   130 |   assoc_out_of_order a ((b,c)::t) = if there_out_of_order a c then b else assoc_out_of_order a t;
   131 
   132 fun get_assoc_snds [] xs assocs= assocs
   133 |   get_assoc_snds (x::xs) ys assocs = get_assoc_snds xs ys (assocs@[((assoc_out_of_order x ys))])
   134 
   135 fun add_if_not_inlist [] xs newlist = newlist
   136 |   add_if_not_inlist (y::ys) xs newlist = if (not (y mem xs)) then 
   137                                       add_if_not_inlist ys xs (y::newlist)
   138                                         else add_if_not_inlist ys xs (newlist)
   139 
   140 (*Flattens a list of list of strings to one string*)
   141 fun onestr ls = String.concat (map String.concat ls);
   142 
   143 fun thmstrings [] str = str
   144 |   thmstrings (x::xs) str = thmstrings xs (str^(string_of_thm x))
   145 
   146 fun is_clasimp_ax clasimp_num n = n <=clasimp_num 
   147 
   148 
   149 
   150 fun retrieve_axioms clause_arr  [] = []
   151 |   retrieve_axioms clause_arr  (x::xs) =  [Array.sub(clause_arr, x)]@
   152  						     (retrieve_axioms clause_arr  xs)
   153 
   154 fun subone x = x - 1
   155 
   156 fun numstr [] = ""
   157 |   numstr (x::xs) = (string_of_int x)^"%"^(numstr xs)
   158 
   159 
   160 (* retrieve the axioms that were obtained from the clasimpset *)
   161 
   162 fun get_clasimp_cls clause_arr clasimp_num step_nums = 
   163     let val realnums = map subone step_nums	
   164 	val clasimp_nums = List.filter (is_clasimp_ax (clasimp_num - 1)) realnums
   165 (*	val axnums = TextIO.openOut(File.platform_path(File.tmp_path (Path.basic "axnums")))     
   166 	val _ = TextIO.output(axnums,(numstr clasimp_nums))
   167 	val _ = TextIO.closeOut(axnums)*)
   168     in
   169 	retrieve_axioms clause_arr  clasimp_nums
   170     end
   171 
   172 
   173 
   174 (*****************************************************)
   175 (* get names of clasimp axioms used                  *)
   176 (*****************************************************)
   177 
   178  fun get_axiom_names proof_steps thms (clause_arr:(ResClause.clause * thm) Array.array) num_of_clauses  =
   179    let 
   180      (* not sure why this is necessary again, but seems to be *)
   181       val _ = (print_mode := (Library.gen_rems (op =) (! print_mode, ["xsymbols", "symbols"])))
   182       val axioms = get_init_axioms proof_steps
   183       val step_nums = get_step_nums axioms []
   184   
   185      (***********************************************)
   186      (* here need to add the clauses from clause_arr*)
   187      (***********************************************)
   188   
   189       val (clasimp_names_cls) = get_clasimp_cls clause_arr num_of_clauses step_nums 
   190       val clasimp_names = map (#1 o ResClause.clause_info o #1) clasimp_names_cls
   191   
   192       val _ = File.write (File.tmp_path (Path.basic "clasimp_names"))                                                               
   193                          (concat clasimp_names)
   194       val _ = (print_mode := (["xsymbols", "symbols"] @ ! print_mode))
   195    in
   196       clasimp_names
   197    end
   198     
   199  fun get_axiom_names_vamp proofstr thms (clause_arr:(ResClause.clause * thm) Array.array) num_of_clauses  =
   200    let 
   201      (* not sure why this is necessary again, but seems to be *)
   202       val _ = (print_mode := (Library.gen_rems (op =) (! print_mode, ["xsymbols", "symbols"])))
   203       val step_nums =get_linenums proofstr
   204   
   205      (***********************************************)
   206      (* here need to add the clauses from clause_arr*)
   207      (***********************************************)
   208   
   209       val (clasimp_names_cls) = get_clasimp_cls clause_arr num_of_clauses step_nums 
   210       val clasimp_names = map (#1 o ResClause.clause_info o #1) clasimp_names_cls
   211   
   212       val _ = File.write (File.tmp_path (Path.basic "clasimp_names"))                                                               
   213                          (concat clasimp_names)
   214       val _ = (print_mode := (["xsymbols", "symbols"] @ ! print_mode))
   215    in
   216       clasimp_names
   217    end
   218     
   219 
   220 (***********************************************)
   221 (* get axioms for reconstruction               *)
   222 (***********************************************)
   223 fun numclstr (vars, []) str = str
   224 |   numclstr ( vars, ((num, thm)::rest)) str =
   225       let val newstr = str^(string_of_int num)^" "^(string_of_thm thm)^" "
   226       in
   227         numclstr  (vars,rest) newstr
   228       end
   229 
   230 fun addvars c (a,b)  = (a,b,c)
   231 
   232  fun get_axioms_used proof_steps thms clause_arr num_of_clauses  =
   233      let 
   234 	val _=  (print_mode := (Library.gen_rems (op =) (! print_mode, ["xsymbols", "symbols"])))
   235 	val axioms = get_init_axioms proof_steps
   236 	val step_nums = get_step_nums axioms []
   237 
   238        (***********************************************)
   239        (* here need to add the clauses from clause_arr*)
   240        (***********************************************)
   241 
   242        (* val clasimp_names_cls = get_clasimp_cls clause_arr   num_of_clauses step_nums   
   243 	val clasimp_names = map #1 clasimp_names_cls
   244 	val clasimp_cls = map #2 clasimp_names_cls
   245 	val _ = TextIO.openAppend(File.platform_path(File.tmp_path (Path.basic "clasimp_names")))                                                            val clasimp_namestr = concat clasimp_names                            
   246 	 val _ = TextIO.output (outfile,clasimp_namestr)
   247 	 
   248 	 val _ =  TextIO.closeOut outfile
   249 *)
   250 
   251 	val clauses =(*(clasimp_cls)@*)( make_clauses thms)
   252 	
   253 	val vars = map thm_vars clauses
   254        
   255 	val distvars = distinct (fold append vars [])
   256 	val clause_terms = map prop_of clauses  
   257 	val clause_frees = List.concat (map term_frees clause_terms)
   258 
   259 	val frees = map lit_string_with_nums clause_frees;
   260 
   261 	val distfrees = distinct frees
   262 
   263 	val metas = map Meson.make_meta_clause clauses
   264 	val ax_strs = map #3 axioms
   265 
   266 	(* literals of -all- axioms, not just those used by spass *)
   267 	val meta_strs = map ReconOrderClauses.get_meta_lits metas
   268        
   269 	val metas_and_strs = ListPair.zip (metas,meta_strs)
   270 	val _ = File.write(File.tmp_path (Path.basic "foo_clauses")) (onestr ax_strs)
   271 	val _ = File.write(File.tmp_path (Path.basic "foo_metastrs")) (onestr meta_strs)
   272 
   273 	(* get list of axioms as thms with their variables *)
   274 
   275 	val ax_metas = get_assoc_snds ax_strs metas_and_strs []
   276 	val ax_vars = map thm_vars ax_metas
   277 	val ax_with_vars = ListPair.zip (ax_metas,ax_vars)
   278 
   279 	(* get list of extra axioms as thms with their variables *)
   280 	val extra_metas = add_if_not_inlist metas ax_metas []
   281 	val extra_vars = map thm_vars extra_metas
   282 	val extra_with_vars = if (not (extra_metas = []) ) 
   283 			      then ListPair.zip (extra_metas,extra_vars)
   284 			      else []
   285        (* val _=  (print_mode := (Library.gen_rems (op =) (! print_mode, ["xsymbols", "symbols"])))
   286        val _ = TextIO.openOut(File.platform_path(File.tmp_path (Path.basic "foo_metas")))
   287 
   288        val _ = TextIO.output (outfile, ((thmstrings ax_metas "")))
   289        val _ =  TextIO.closeOut outfile
   290       val foo_metas =  File.platform_path(File.tmp_path (Path.basic "foo_metas"))
   291       val foo_metas2 =   File.platform_path(File.tmp_path (Path.basic "foo_metas2"))
   292 	val execperl = Unix.execute("/usr/bin/perl", ["remchars.pl", "  <", foo_metas, "  >", foo_metas2])
   293      val infile = TextIO.openIn(File.platform_path(File.tmp_path (Path.basic "foo_metas2")))
   294     val ax_metas_str = TextIO.inputLine (infile)
   295     val _ = TextIO.closeIn infile
   296        val _= (print_mode := (["xsymbols", "symbols"] @ ! print_mode))*)
   297      in
   298 	(distfrees,distvars, extra_with_vars,ax_with_vars, (*clasimp_names*)(ListPair.zip (step_nums,ax_metas)))
   299      end;
   300                                             
   301 
   302 (*********************************************************************)
   303 (* Pass in spass string of proof and string version of isabelle goal *)
   304 (* Get out reconstruction steps as a string to be sent to Isabelle   *)
   305 (*********************************************************************)
   306 
   307 
   308 fun rules_to_string [] = "NONE"
   309   | rules_to_string xs = "[" ^ space_implode ", " xs ^ "]"
   310                                   
   311 
   312 val dummy_tac = PRIMITIVE(fn thm => thm );
   313 
   314 
   315 (*val  proofstr = "1242[0:Inp] ||  -> equal(const_List_Orev(tconst_fun(tconst_List_Olist(U),tconst_List_Olist(U)),const_List_Olist_ONil),const_List_Olist_ONil)**.\
   316 \1279[0:Inp] ||  -> equal(const_Nat_Osize(tconst_fun(tconst_List_Olist(U),tconst_nat),const_List_Olist_ONil),const_0)**.\
   317 \1430[0:Inp] || equal(const_Nat_Osize(tconst_fun(tconst_List_Olist(typ__Ha),tconst_nat),const_List_Orev(tconst_fun(tconst_List_Olist(typ__Ha),tconst_List_Olist(typ__Ha)),const_List_Olist_ONil)),const_Nat_Osize(tconst_fun(tconst_List_Olist(typ__Ha),tconst_nat),const_List_Olist_ONil))** -> .\
   318 \1453[0:Rew:1279.0,1430.0,1242.0,1430.0,1279.0,1430.0] || equal(const_0,const_0)* -> .\
   319 \1454[0:Obv:1453.0] ||  -> .";*)
   320 
   321 fun subst_for a b = String.translate (fn c => str (if c=a then b else c));
   322 
   323 val remove_linebreaks = subst_for #"\n" #"\t";
   324 val restore_linebreaks = subst_for #"\t" #"\n";
   325 
   326 fun spassString_to_lemmaString proofstr thmstring goalstring toParent ppid thms clause_arr  num_of_clauses  = 
   327   let val _ = File.append(File.tmp_path (Path.basic"thmstringfile"))
   328                   ("thmstring is: "^thmstring^"\n proofstr is: "^proofstr^"\n goalstr is: "^goalstring^" \n  num of clauses is: "^(string_of_int num_of_clauses))
   329 
   330      (***********************************)
   331      (* parse spass proof into datatype *)
   332      (***********************************)
   333       val tokens = #1(lex proofstr)
   334       val proof_steps1 = parse tokens
   335       val proof_steps = just_change_space proof_steps1
   336       val _ = File.write (File.tmp_path (Path.basic "foo_parse")) ("Did parsing on "^proofstr)
   337       val _ = File.write(File.tmp_path (Path.basic "foo_thmstring_at_parse"))
   338                         ("Parsing for thmstring: "^thmstring)
   339       (************************************)
   340       (* recreate original subgoal as thm *)
   341       (************************************)
   342     
   343       (* get axioms as correctly numbered clauses w.r.t. the Spass proof *)
   344       (* need to get prems_of thm, then get right one of the prems, relating to whichever*)
   345       (* subgoal this is, and turn it into meta_clauses *)
   346       (* should prob add array and table here, so that we can get axioms*)
   347       (* produced from the clasimpset rather than the problem *)
   348 
   349       val (axiom_names) = get_axiom_names proof_steps  thms clause_arr  num_of_clauses
   350       val ax_str = "Rules from clasimpset used in proof found by SPASS: " ^ 
   351                    rules_to_string axiom_names 
   352       val _ = File.append(File.tmp_path (Path.basic "reconstrfile"))
   353                          ("reconstring is: "^ax_str^"  "^goalstring)       
   354   in 
   355        TextIO.output (toParent, ax_str^"\n");
   356        TextIO.flushOut toParent;
   357        TextIO.output (toParent, "goalstring: "^goalstring^"\n");
   358        TextIO.flushOut toParent;
   359        TextIO.output (toParent, "thmstring: "^thmstring^"\n");
   360        TextIO.flushOut toParent;
   361 
   362        Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   363       (* Attempt to prevent several signals from turning up simultaneously *)
   364        Posix.Process.sleep(Time.fromSeconds 1) ; dummy_tac
   365   end
   366   handle _ => 
   367   let val _ = File.write(File.tmp_path (Path.basic "foo_handler")) "In exception handler"
   368   in 
   369      TextIO.output (toParent,"Proof found but parsing failed for resolution proof: "^(remove_linebreaks proofstr)^"\n" );
   370       TextIO.flushOut toParent;
   371        TextIO.output (toParent, (remove_linebreaks thmstring)^"\n");
   372        TextIO.flushOut toParent;
   373        TextIO.output (toParent, ( (remove_linebreaks goalstring)^"\n"));
   374        TextIO.flushOut toParent;
   375       Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   376       (* Attempt to prevent several signals from turning up simultaneously *)
   377       Posix.Process.sleep(Time.fromSeconds 1) ;dummy_tac
   378   end
   379 
   380 
   381 fun vampString_to_lemmaString proofstr thmstring goalstring toParent ppid thms clause_arr  num_of_clauses  = 
   382  let val _ = File.append(File.tmp_path (Path.basic "thmstringfile"))
   383                (" thmstring is: "^thmstring^"proofstr is: "^proofstr^
   384                 "goalstr is: "^goalstring^" num of clauses is: "^
   385                 (string_of_int num_of_clauses))
   386 
   387     (***********************************)
   388     (* get vampire axiom names         *)
   389     (***********************************)
   390 
   391      val (axiom_names) = get_axiom_names_vamp proofstr  thms clause_arr  num_of_clauses
   392      val ax_str = "Rules from clasimpset used in proof found by Vampire: " ^
   393                   rules_to_string axiom_names
   394     in 
   395 	 File.append(File.tmp_path (Path.basic "reconstrfile")) ("reconstring is: "^ax_str^"  "^goalstring);
   396          TextIO.output (toParent, ax_str^"\n");
   397 	 TextIO.flushOut toParent;
   398 	 TextIO.output (toParent, "goalstring: "^goalstring^"\n");
   399 	 TextIO.flushOut toParent;
   400 	 TextIO.output (toParent, "thmstring: "^thmstring^"\n");
   401 	 TextIO.flushOut toParent;
   402 
   403 	 Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   404 	(* Attempt to prevent several signals from turning up simultaneously *)
   405 	 Posix.Process.sleep(Time.fromSeconds 1) ; dummy_tac
   406     end
   407     handle _ => 
   408     let val _ = File.write(File.tmp_path (Path.basic "foo_handler")) "In exception handler"
   409     in 
   410 	TextIO.output (toParent,"Proof found by Vampire but translation failed for resolution proof: "^(remove_linebreaks proofstr) );
   411 	TextIO.flushOut toParent;
   412 	 TextIO.output (toParent, thmstring^"\n");
   413 	 TextIO.flushOut toParent;
   414 	 TextIO.output (toParent, goalstring^"\n");
   415 	 TextIO.flushOut toParent;
   416 	Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   417 	(* Attempt to prevent several signals from turning up simultaneously *)
   418 	Posix.Process.sleep(Time.fromSeconds 1) ;dummy_tac
   419     end;
   420 
   421 
   422 (* val proofstr = "1582[0:Inp] || -> v_P*.\
   423                  \1583[0:Inp] || v_P* -> .\
   424 		 \1584[0:MRR:1583.0,1582.0] || -> ."; *)
   425 
   426 fun spassString_to_reconString proofstr thmstring goalstring toParent ppid thms clause_arr  num_of_clauses  = 
   427   let val _ = File.write(File.tmp_path (Path.basic "thmstringfile")) 
   428                  (" thmstring is: "^thmstring^"proofstr is: "^proofstr)
   429       val tokens = #1(lex proofstr)
   430 
   431   (***********************************)
   432   (* parse spass proof into datatype *)
   433   (***********************************)
   434       val proof_steps1 = parse tokens
   435       val proof_steps = just_change_space proof_steps1
   436 
   437       val _ = File.write (File.tmp_path (Path.basic "foo_parse"))
   438                       ("Did parsing on "^proofstr)
   439     
   440       val _ = File.write (File.tmp_path (Path.basic "foo_thmstring_at_parse"))
   441                                 ("Parsing for thmstring: "^thmstring)
   442   (************************************)
   443   (* recreate original subgoal as thm *)
   444   (************************************)
   445       (* get axioms as correctly numbered clauses w.r.t. the Spass proof *)
   446       (* need to get prems_of thm, then get right one of the prems, relating to whichever*)
   447       (* subgoal this is, and turn it into meta_clauses *)
   448       (* should prob add array and table here, so that we can get axioms*)
   449       (* produced from the clasimpset rather than the problem *)
   450       val (frees,vars,extra_with_vars ,ax_with_vars,numcls) = get_axioms_used proof_steps  thms clause_arr  num_of_clauses
   451       
   452       (*val numcls_string = numclstr ( vars, numcls) ""*)
   453       val _ = File.write (File.tmp_path (Path.basic "foo_axiom")) "got axioms"
   454 	
   455   (************************************)
   456   (* translate proof                  *)
   457   (************************************)
   458       val _ = File.write (File.tmp_path (Path.basic "foo_steps"))                                                                           
   459                        ("about to translate proof, steps: "
   460                        ^(init_proofsteps_to_string proof_steps ""))
   461       val (newthm,proof) = translate_proof numcls  proof_steps vars
   462       val _ = File.write (File.tmp_path (Path.basic "foo_steps2"))                                                                       
   463                        ("translated proof, steps: "^(init_proofsteps_to_string proof_steps ""))
   464   (***************************************************)
   465   (* transfer necessary steps as strings to Isabelle *)
   466   (***************************************************)
   467       (* turn the proof into a string *)
   468       val reconProofStr = proofs_to_string proof ""
   469       (* do the bit for the Isabelle ordered axioms at the top *)
   470       val ax_nums = map #1 numcls
   471       val ax_strs = map ReconOrderClauses.get_meta_lits_bracket (map #2 numcls)
   472       val numcls_strs = ListPair.zip (ax_nums,ax_strs)
   473       val num_cls_vars =  map (addvars vars) numcls_strs;
   474       val reconIsaAxStr = origAxs_to_string (ListPair.zip (ax_nums,ax_with_vars)) ""
   475       
   476       val extra_nums = if (not (extra_with_vars = [])) then (1 upto (length extra_with_vars))
   477                        else []
   478       val reconExtraAxStr = extraAxs_to_string ( ListPair.zip (extra_nums,extra_with_vars)) ""
   479       val frees_str = "["^(thmvars_to_string frees "")^"]"
   480       val _ = File.write (File.tmp_path (Path.basic "reconstringfile"))
   481                           (frees_str^reconExtraAxStr^reconIsaAxStr^reconProofStr)
   482       val reconstr = (frees_str^reconExtraAxStr^reconIsaAxStr^reconProofStr)
   483   in 
   484        TextIO.output (toParent, reconstr^"\n");
   485        TextIO.flushOut toParent;
   486        TextIO.output (toParent, thmstring^"\n");
   487        TextIO.flushOut toParent;
   488        TextIO.output (toParent, goalstring^"\n");
   489        TextIO.flushOut toParent;
   490 
   491        Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   492       (* Attempt to prevent several signals from turning up simultaneously *)
   493        Posix.Process.sleep(Time.fromSeconds 1) ; dummy_tac
   494   end
   495   handle _ => 
   496   let val _ = File.write(File.tmp_path (Path.basic "foo_handler")) "In exception handler"
   497   in 
   498        TextIO.output (toParent,"Proof found but translation failed for resolution proof:"^(remove_linebreaks proofstr) ^"\n");
   499       TextIO.flushOut toParent;
   500     TextIO.output (toParent, thmstring^"\n");
   501        TextIO.flushOut toParent;
   502        TextIO.output (toParent, goalstring^"\n");
   503        TextIO.flushOut toParent;
   504       Posix.Process.kill(Posix.Process.K_PROC ppid, Posix.Signal.usr2);
   505       (* Attempt to prevent several signals from turning up simultaneously *)
   506       Posix.Process.sleep(Time.fromSeconds 1) ;dummy_tac
   507   end
   508 
   509 
   510 (**********************************************************************************)
   511 (* At other end, want to turn back into datatype so can apply reconstruct_proof.  *)
   512 (* This will be done by the signal handler                                        *)
   513 (**********************************************************************************)
   514 
   515 (* Parse in the string version of the proof steps for reconstruction *)
   516 (* Isar format: cl1 [BINARY 0 cl2 0];cl1 [PARAMOD 0 cl2 0]; cl1 [DEMOD 0 cl2];cl1 [FACTOR 1 2];*)
   517 
   518 
   519  val term_numstep =
   520         (number ++ (a (Other ",")) ++ number) >> (fn (a, (_, c)) => (a, c))
   521 
   522 val extraaxiomstep = (a (Word "ExtraAxiom"))++ (a (Other "(")) ++(a (Other ")"))
   523             >> (fn (_) => ExtraAxiom)
   524 
   525 
   526 
   527 val origaxiomstep = (a (Word "OrigAxiom"))++ (a (Other "(")) ++(a (Other ")"))
   528             >> (fn (_) => OrigAxiom)
   529 
   530 
   531  val axiomstep = (a (Word "Axiom"))++ (a (Other "(")) ++(a (Other ")"))
   532             >> (fn (_) => Axiom)
   533      
   534 
   535 
   536       
   537  val binarystep = (a (Word "Binary")) ++ (a (Other "(")) ++ (a (Other "(")) 
   538                    ++ term_numstep  ++ (a (Other ")")) ++ (a (Other ","))
   539                    ++ (a (Other "(")) ++ term_numstep ++ (a (Other ")")) ++ (a (Other ")"))
   540             >> (fn (_, (_, (_, (c, (_,(_,(_, (e,(_,_))))))))) => Binary (c,e))
   541       
   542 
   543  val parastep = (a (Word "Para")) ++ (a (Other "(")) ++ (a (Other "(")) 
   544                    ++ term_numstep  ++ (a (Other ")")) ++ (a (Other ","))
   545                    ++ (a (Other "(")) ++ term_numstep ++ (a (Other ")")) ++ (a (Other ")"))
   546             >> (fn (_, (_, (_, (c, (_,(_,(_, (e,(_,_))))))))) => Para(c, e))
   547       
   548  val mrrstep = (a (Word "MRR")) ++ (a (Other "(")) ++ (a (Other "(")) 
   549                    ++ term_numstep  ++ (a (Other ")")) ++ (a (Other ","))
   550                    ++ (a (Other "(")) ++ term_numstep ++ (a (Other ")")) ++ (a (Other ")"))
   551             >> (fn (_, (_, (_, (c, (_,(_,(_, (e,(_,_))))))))) => MRR(c, e))
   552       
   553 
   554  val factorstep = (a (Word "Factor")) ++ (a (Other "("))
   555                     ++ number ++ (a (Other ","))
   556                        ++ number ++ (a (Other ","))
   557                        ++ number ++  (a (Other ")"))
   558                    
   559             >> (fn (_, (_, (c, (_, (e,(_,(f,_))))))) =>  Factor (c,e,f))
   560 
   561 
   562 (*val rewritestep = (a (Word "Rewrite"))  ++ (a (Other "(")) ++ (a (Other "(")) 
   563                    ++ term_numstep  ++ (a (Other ")")) ++ (a (Other ","))
   564                    ++ (a (Other "(")) ++ term_numstep ++ (a (Other ")")) ++ (a (Other ")"))
   565             >> (fn (_, (_, (_, (c, (_,(_,(_, (e,(_,_))))))))) => Rewrite (c,e))*)
   566 
   567 val obviousstep = (a (Word "Obvious")) ++ (a (Other "(")) 
   568                    ++ term_numstep  ++ (a (Other ")")) 
   569             >> (fn (_, (_, (c,_))) => Obvious (c))
   570 
   571  val methodstep = extraaxiomstep || origaxiomstep || axiomstep ||binarystep || factorstep|| parastep || mrrstep || (*rewritestep ||*) obviousstep
   572 
   573 
   574  val number_list_step =
   575         ( number ++ many ((a (Other ",") ++ number)>> #2))
   576         >> (fn (a,b) => (a::b))
   577         
   578  val numberlist_step = a (Other "[")  ++ a (Other "]")
   579                         >>(fn (_,_) => ([]:int list))
   580                        || a (Other "[") ++ number_list_step ++ a (Other "]")
   581                         >>(fn (_,(a,_)) => a)
   582                     
   583 
   584 
   585 (** change this to allow P (x U) *)
   586  fun arglist_step input = ( word ++ many  word >> (fn (a, b) => (a^" "^(implode_with_space b)))
   587                            ||word >> (fn (a) => (a)))input
   588                 
   589 
   590 fun literal_step input = (word ++ a (Other "(") ++ arglist_step ++  a (Other ")")
   591                                           >>(fn (a, (b, (c,d))) => (a^" ("^(c)^")"))
   592                         || arglist_step >> (fn (a) => (a)))input
   593                            
   594 
   595 
   596 (* fun term_step input = (a (Other "~") ++ arglist_step ++ a (Other "%")>> (fn (a,(b,c)) => ("~ "^b))
   597                      ||  arglist_step ++ a (Other "%")>> (fn (a,b) => a ))input
   598 *)
   599 
   600 
   601  fun term_step input = (a (Other "~") ++ literal_step ++ a (Other "%")>> (fn (a,(b,c)) => ("~ "^b))
   602                      ||  literal_step ++ a (Other "%")>> (fn (a,b) => a ))input
   603 
   604 
   605          
   606 
   607  val term_list_step =
   608         (  term_step ++ many ( term_step))
   609         >> (fn (a,b) => (a::b))
   610         
   611  
   612 val term_lists_step = a (Other "[")  ++ a (Other "]")
   613                         >>(fn (_,_) => ([]:string list))
   614                        || a (Other "[") ++ term_list_step ++ a (Other "]")
   615                         >>(fn (_,(a,_)) => a)
   616                      
   617 
   618 
   619 
   620 fun anytoken_step input  = (word>> (fn (a) => a)  ) input
   621                        handle NOPARSE_WORD => (number>> (fn (a) => string_of_int a)  ) input
   622                       handle NOPARSE_NUMBER => (other_char >> (fn(a) => a)) input
   623 
   624 
   625 
   626 fun goalstring_step input= (anytoken_step ++ many (anytoken_step )
   627                   >> (fn (a,b) =>  (a^" "^(implode b)))) input
   628 
   629 
   630 
   631  val linestep = number ++ methodstep ++ term_lists_step ++ term_lists_step
   632                 >> (fn (a, (b, (c,d))) => (a,(b,c,d)))
   633     
   634  val lines_step = many linestep
   635 
   636  val alllines_step = (term_lists_step ++ lines_step ) ++ finished >> #1
   637     
   638  val parse_step = #1 o alllines_step
   639 
   640 
   641  (*
   642 val reconstr ="[P%x%xa%xb%]1OrigAxiom()[P x%~ P U%][U%]3OrigAxiom()[P U%~ P x%][U%]5OrigAxiom()[~ P xa%~ P U%][U%]7OrigAxiom()[P U%P xb%][U%]1Axiom()[P x%~ P U%][U%]3Axiom()[P U%~ P x%][U%]5Axiom()[~ P U%~ P xa%][U%]7Axiom()[P U%P xb%][U%]9Factor(5,0,1)[~ P xa%][]10Binary((9,0),(3,0))[~ P x%][]11Binary((10,0),(1,0))[~ P U%][U%]12Factor(7,0,1)[P xb%][]14Binary((11,0),(12,0))[][]%(EX x::'a::type. ALL y::'a::type. (P::'a::type => bool) x = P y) -->(EX x::'a::type. P x) = (ALL y::'a::type. P y)"
   643 *)
   644 
   645 (************************************************************)
   646 (* Construct an Isar style proof from a list of proof steps *)
   647 (************************************************************)
   648 (* want to assume all axioms, then do haves for the other clauses*)
   649 (* then show for the last step *)
   650 
   651 (* replace ~ by not here *)
   652 fun change_nots [] = []
   653 |   change_nots (x::xs) = if x = "~" 
   654                           then 
   655                              ["\\", "<", "n", "o", "t", ">"]@(change_nots xs)
   656                           else (x::(change_nots xs))
   657 
   658 (*
   659 fun clstrs_to_string [] str = str
   660 |   clstrs_to_string (x::[]) str = str^x
   661 |   clstrs_to_string (x::xs) str = clstrs_to_string xs (str^(x^"; "))
   662 *)
   663 fun clstrs_to_string [] str = implode (change_nots (explode str))
   664 |   clstrs_to_string (x::[]) str = implode (change_nots (explode (str^x)))
   665 |   clstrs_to_string (x::xs) str = implode (change_nots (explode (clstrs_to_string xs (str^(x^"; ")))))
   666 
   667 
   668 
   669 fun thmvars_to_quantstring [] str = str
   670 |   thmvars_to_quantstring (x::[]) str =str^x^". "
   671 |   thmvars_to_quantstring (x::xs) str = thmvars_to_quantstring xs (str^(x^" "))
   672 
   673 
   674 fun clause_strs_to_isar clstrs [] =  "\"\\<lbrakk>"^(clstrs_to_string clstrs "")^"\\<rbrakk> \\<Longrightarrow> False\""
   675 |   clause_strs_to_isar clstrs thmvars = "\"\\<And>"^(thmvars_to_quantstring thmvars "")^"\\<lbrakk>"^(clstrs_to_string clstrs "")^"\\<rbrakk> \\<Longrightarrow> False\""
   676 
   677 fun frees_to_string [] str = implode (change_nots (explode str))
   678 |   frees_to_string (x::[]) str = implode (change_nots (explode (str^x)))
   679 |   frees_to_string  (x::xs) str = implode (change_nots (explode (frees_to_string xs (str^(x^" ")))))
   680 
   681 fun frees_to_isar_str [] =  ""
   682 |   frees_to_isar_str  clstrs = (frees_to_string clstrs "")
   683 
   684 
   685 (***********************************************************************)
   686 (* functions for producing assumptions for the Isabelle ordered axioms *)
   687 (***********************************************************************)
   688 (*val str = "[P%x%xa%xb%]1OrigAxiom()[P x%~ P U%][U%]3OrigAxiom()[P U%~ P x%][U%]5OrigAxiom()[~ P xa%~ P U%][U%]7OrigAxiom()[P U%P xb%][U%]1Axiom()[P x%~ P U%][U%]3Axiom()[P U%~ P x%][U%]5Axiom()[~ P U%~ P xa%][U%]7Axiom()[P U%P xb%][U%]9Factor(5,0,1)[~ P xa%][]10Binary((9,0),(3,0))[~ P x%][]11Binary((10,0),(1,0))[~ P U%][U%]12Factor(7,0,1)[P xb%][]14Binary((11,0),(12,0))[][]";       
   689 num, rule, clausestrs, vars*)
   690 
   691 
   692 (* assume the extra clauses - not used in Spass proof *)
   693 
   694 fun is_extraaxiom_step ( num:int,(ExtraAxiom, str, tstr)) = true
   695 |   is_extraaxiom_step (num, _) = false
   696 
   697 fun get_extraaxioms xs = List.filter (is_extraaxiom_step) ( xs)
   698 
   699 fun assume_isar_extraaxiom [] str  = str
   700 |   assume_isar_extraaxiom ((numb,(step, clstr, thmvars))::xs) str  = assume_isar_extraaxiom xs (str^"and cl"^(string_of_int numb)^"': "^(clause_strs_to_isar clstr thmvars)^"\n " )
   701 
   702 
   703 
   704 fun assume_isar_extraaxioms  [] = ""
   705 |assume_isar_extraaxioms ((numb,(step, clstrs, thmstrs))::xs) = let val str = "assume cl"^(string_of_int numb)^"': "^(clause_strs_to_isar clstrs thmstrs)^"\n" 
   706                                          in
   707                                              assume_isar_extraaxiom xs str
   708                                          end
   709 
   710 (* assume the Isabelle ordered clauses *)
   711 
   712 fun is_origaxiom_step ( num:int,(OrigAxiom, str, tstr)) = true
   713 |   is_origaxiom_step (num, _) = false
   714 
   715 fun get_origaxioms xs = List.filter (is_origaxiom_step) ( xs)
   716 
   717 fun assume_isar_origaxiom [] str  = str
   718 |   assume_isar_origaxiom ((numb,(step, clstr, thmvars))::xs) str  = assume_isar_origaxiom xs (str^"and cl"^(string_of_int numb)^"': "^(clause_strs_to_isar clstr thmvars)^"\n " )
   719 
   720 
   721 
   722 fun assume_isar_origaxioms ((numb,(step, clstrs, thmstrs))::xs) = let val str = "assume cl"^(string_of_int numb)^"': "^(clause_strs_to_isar clstrs thmstrs)^"\n" 
   723                                          in
   724                                              assume_isar_origaxiom xs str
   725                                          end
   726 
   727 
   728 
   729 fun is_axiom_step ( num:int,(Axiom, str, tstr)) = true
   730 |   is_axiom_step (num, _) = false
   731 
   732 fun get_axioms xs = List.filter  (is_axiom_step) ( xs)
   733 
   734 fun have_isar_axiomline (numb,(step, clstrs, thmstrs))="have cl"^(string_of_int numb)^": "^(clause_strs_to_isar clstrs thmstrs)^"\n"
   735 
   736 fun  by_isar_axiomline (numb,(step, clstrs, thmstrs))="by (rule cl"^ (string_of_int numb)^"') \n"
   737 
   738 
   739 fun isar_axiomline (numb, (step, clstrs, thmstrs))  = (have_isar_axiomline (numb,(step,clstrs, thmstrs )))^( by_isar_axiomline(numb,(step,clstrs, thmstrs )) )
   740 
   741 
   742 fun isar_axiomlines [] str = str
   743 |   isar_axiomlines (x::xs) str = isar_axiomlines xs (str^(isar_axiomline x))
   744 
   745 
   746 fun have_isar_line (numb,(step, clstrs, thmstrs))="have cl"^(string_of_int numb)^": "^(clause_strs_to_isar clstrs thmstrs)^"\n"
   747 (*FIX: ask Larry to add and mrr attribute *)
   748 
   749 fun by_isar_line ((Binary ((a,b), (c,d)))) = 
   750     "by(rule cl"^
   751 		(string_of_int a)^" [binary "^(string_of_int b)^" cl"^
   752 		(string_of_int c)^" "^(string_of_int d)^"])\n"
   753 |by_isar_line ((MRR ((a,b), (c,d)))) = 
   754     "by(rule cl"^
   755 		(string_of_int a)^" [binary "^(string_of_int b)^" cl"^
   756 		(string_of_int c)^" "^(string_of_int d)^"])\n"
   757 |   by_isar_line ( (Para ((a,b), (c,d)))) =
   758     "by (rule cl"^
   759 		(string_of_int a)^" [paramod "^(string_of_int b)^" cl"^
   760 		(string_of_int c)^" "^(string_of_int d)^"])\n"
   761 |   by_isar_line ((Factor ((a,b,c)))) = 
   762     "by (rule cl"^(string_of_int a)^" [factor "^(string_of_int b)^" "^
   763 		(string_of_int c)^" ])\n"
   764 (*|   by_isar_line ( (Rewrite ((a,b),(c,d)))) =
   765     "by (rule cl"^(string_of_int a)^" [demod "^(string_of_int b)^" "^
   766 		(string_of_int c)^" "^(string_of_int d)^" ])\n"*)
   767 |   by_isar_line ( (Obvious ((a,b)))) =
   768     "by (rule cl"^(string_of_int a)^" [obvious "^(string_of_int b)^" ])\n"
   769 
   770 fun isar_line (numb, (step, clstrs, thmstrs))  = (have_isar_line (numb,(step,clstrs, thmstrs )))^( by_isar_line step)
   771 
   772 
   773 fun isar_lines [] str = str
   774 |   isar_lines (x::xs) str = isar_lines xs (str^(isar_line x))
   775 
   776 fun last_isar_line (numb,( step, clstrs,thmstrs)) = "show \"False\"\n"^(by_isar_line step)
   777 
   778 
   779 fun to_isar_proof (frees, xs, goalstring) =
   780     let val extraaxioms = get_extraaxioms xs
   781 	val extraax_num = length extraaxioms
   782 	val origaxioms_and_steps = Library.drop (extraax_num, xs)  
   783 	
   784 	val origaxioms = get_origaxioms origaxioms_and_steps
   785 	val origax_num = length origaxioms
   786 	val axioms_and_steps = Library.drop (origax_num + extraax_num, xs)  
   787 	val axioms = get_axioms axioms_and_steps
   788 	
   789 	val steps = Library.drop (origax_num, axioms_and_steps)
   790 	val firststeps = ReconOrderClauses.butlast steps
   791 	val laststep = ReconOrderClauses.last steps
   792 	val goalstring = implode(ReconOrderClauses.butlast(explode goalstring))
   793 	
   794 	val isar_proof = 
   795 		("show \""^goalstring^"\"\n")^
   796 		("proof (rule ccontr,skolemize, make_clauses) \n")^
   797 		("fix "^(frees_to_isar_str frees)^"\n")^
   798 		(assume_isar_extraaxioms extraaxioms)^
   799 		(assume_isar_origaxioms origaxioms)^
   800 		(isar_axiomlines axioms "")^
   801 		(isar_lines firststeps "")^
   802 		(last_isar_line laststep)^
   803 		("qed")
   804 	val _ = File.write (File.tmp_path (Path.basic "isar_proof_file")) isar_proof
   805     in
   806 	isar_proof
   807     end;
   808 
   809 (* get fix vars from axioms - all Frees *)
   810 (* check each clause for meta-vars and /\ over them at each step*)
   811 
   812 (*******************************************************)
   813 (* This assumes the thm list  "numcls" is still there  *)
   814 (* In reality, should probably label it with an        *)
   815 (* ID number identifying the subgoal.  This could      *)
   816 (* be passed over to the watcher, e.g.  numcls25       *)
   817 (*******************************************************)
   818 
   819 (* val str = "[S%x%P%R%Q%]1ExtraAxiom()[~ Q U%~ R U%][U%]2ExtraAxiom()[~ Q U%~ P U%][U%]3ExtraAxiom()[Q U%R U%][U%]1OrigAxiom()[S x%][]2OrigAxiom()[P U%R U%][U%]6OrigAxiom()[~ S U%~ P U%][U%]7OrigAxiom()[~ S U%~ R U%][U%]1Axiom()[S x%][]2Axiom()[R U%P U%][U%]6Axiom()[~ P U%~ S U%][U%]7Axiom()[~ R U%~ S U%][U%]8Binary((6,1),(1,0))[~ P x%][]9Binary((7,1),(1,0))[~ R x%][]19Binary((9,0),(2,0))[P x%][]25Binary((8,0),(19,0))[][]";
   820 
   821 val str = "[P%x%xa%xb%]1OrigAxiom()[P x%~ P U%][U%]3OrigAxiom()[P U%~ P x%][U%]5OrigAxiom()[~ P xa%~ P U%][U%]7OrigAxiom()[P U%P xb%][U%]1Axiom()[P x%~ P U%][U%]3Axiom()[P U%~ P x%][U%]5Axiom()[~ P U%~ P xa%][U%]7Axiom()[P U%P xb%][U%]9Factor(5,0,1)[~ P xa%][]10Binary((9,0),(3,0))[~ P x%][]11Binary((10,0),(1,0))[~ P U%][U%]12Factor(7,0,1)[P xb%][]14Binary((11,0),(12,0))[][]";
   822 
   823 val reconstr = "[P%Q%x%xa%]1OrigAxiom()[~ P U%][U%]3OrigAxiom()[Q U%][U%]5OrigAxiom()[P (x U)%~ Q (xa U)%][U%]9Binary((7,0),(3,0))[][]7Binary((1,0),(5,0))[~ Q (xa U)%][U%]5Axiom()[P (x U)%~ Q (xa U)%][U%]3Axiom()[Q U%][U%]1Axiom()[~ P U%][U%](ALL xb::'a::type.   (~ (P::'a::type => bool) ((x::'a::type => 'a::type) xb) |    (Q::'a::type => bool) ((xa::'a::type => 'a::type) xb)) &   P xb & ~ Q xb)";
   824 
   825 
   826 val reconstr = "[P%x%xa%xb%]1OrigAxiom()[P x%~ P U%][U%]3OrigAxiom()[P U%~ P x%][U%]5OrigAxiom()[~ P xa%~ P U%][U%]7OrigAxiom()[P U%P xb%][U%]1Axiom()[P x%~ P U%][U%]3Axiom()[P U%~ P x%][U%]5Axiom()[~ P U%~ P xa%][U%]7Axiom()[P U%P xb%][U%]9Factor(5,0,1)[~ P xa%][]10Binary((9,0),(3,0))[~ P x%][]11Binary((10,0),(1,0))[~ P U%][U%]12Factor(7,0,1)[P xb%][]14Binary((11,0),(12,0))[][]";
   827 
   828 val thmstring = " (ALL xa::'a::type.   (~ (P::'a::type => bool) (x::'a::type) | P xa) & (~ P xa | P x)) & (((P::'a::type => bool) (xa::'a::type) | (ALL x::'a::type. P x)) &((ALL x::'a::type. ~ P x) | ~ P (xb::'a::type)))";
   829 *)
   830 
   831 fun apply_res_thm str goalstring  = let val tokens = #1 (lex str);
   832 				val _ = File.append (File.tmp_path (Path.basic "applyres")) 
   833 			           ("str is: "^str^" goalstr is: "^goalstring^"\n")	
   834                                    val (frees,recon_steps) = parse_step tokens 
   835                                    val isar_str = to_isar_proof (frees, recon_steps, goalstring)
   836                                    val foo =   TextIO.openOut (File.platform_path(File.tmp_path (Path.basic "foobar")));
   837                                in 
   838                                   TextIO.output(foo,(isar_str));TextIO.closeOut foo;Pretty.writeln(Pretty.str  isar_str); () 
   839                                end 
   840 
   841 
   842 (* val reconstr = reconstr^"[P%]51Axiom()[~P%]52Axiom[P%][]53MRR((52,0),(51,0))[][]";
   843 *)
   844 end;