src/HOL/Tools/res_clause.ML
author paulson
Wed Oct 05 11:18:06 2005 +0200 (2005-10-05 ago)
changeset 17764 fde495b9e24b
parent 17745 38b4d8bf2627
child 17775 2679ba74411f
permissions -rw-r--r--
improved process handling. tidied
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory
     2 
     3     ID: $Id$
     4     Copyright 2004 University of Cambridge
     5 
     6 ML data structure for storing/printing FOL clauses and arity clauses.
     7 Typed equality is treated differently.
     8 *)
     9 
    10 (* works for writeoutclasimp on typed *)
    11 signature RES_CLAUSE =
    12   sig
    13   val keep_types : bool ref
    14   val special_equal : bool ref
    15   val tagged : bool ref
    16 
    17   exception ARCLAUSE of string
    18   exception CLAUSE of string * term
    19   type arityClause 
    20   type classrelClause
    21   val classrelClauses_of : string * string list -> classrelClause list
    22   type clause
    23   val init : theory -> unit
    24   val make_axiom_arity_clause :
    25      string * (string * string list list) -> arityClause
    26   val make_axiom_classrelClause :  string * string option -> classrelClause
    27   val make_axiom_clause : Term.term -> string * int -> clause
    28   val make_conjecture_clause : Term.term -> clause
    29   val make_conjecture_clause_thm : Thm.thm -> clause
    30   val make_hypothesis_clause : Term.term -> clause
    31   val get_axiomName : clause ->  string
    32   val isTaut : clause -> bool
    33   val num_of_clauses : clause -> int
    34 
    35   val clause2dfg : clause -> string * string list
    36   val clauses2dfg : clause list -> string -> clause list -> clause list ->
    37 	   (string * int) list -> (string * int) list -> string
    38   val tfree_dfg_clause : string -> string
    39 
    40   val tptp_arity_clause : arityClause -> string
    41   val tptp_classrelClause : classrelClause -> string
    42   val tptp_clause : clause -> string list
    43   val clause2tptp : clause -> string * string list
    44   val tfree_clause : string -> string
    45   val schematic_var_prefix : string
    46   val fixed_var_prefix : string
    47   val tvar_prefix : string
    48   val tfree_prefix : string
    49   val clause_prefix : string 
    50   val arclause_prefix : string
    51   val const_prefix : string
    52   val tconst_prefix : string 
    53   val class_prefix : string 
    54   end;
    55 
    56 structure ResClause: RES_CLAUSE =
    57 struct
    58 
    59 (* Added for typed equality *)
    60 val special_equal = ref false; (* by default,equality does not carry type information *)
    61 val eq_typ_wrapper = "typeinfo"; (* default string *)
    62 
    63 
    64 val schematic_var_prefix = "V_";
    65 val fixed_var_prefix = "v_";
    66 
    67 val tvar_prefix = "T_";
    68 val tfree_prefix = "t_";
    69 
    70 val clause_prefix = "cls_"; 
    71 val arclause_prefix = "clsarity_" 
    72 val clrelclause_prefix = "clsrel_";
    73 
    74 val const_prefix = "c_";
    75 val tconst_prefix = "tc_"; 
    76 
    77 val class_prefix = "class_"; 
    78 
    79 
    80 (**** some useful functions ****)
    81  
    82 val const_trans_table =
    83       Symtab.make [("op =", "equal"),
    84 	  	   ("op <=", "lessequals"),
    85 		   ("op <", "less"),
    86 		   ("op &", "and"),
    87 		   ("op |", "or"),
    88 		   ("op +", "plus"),
    89 		   ("op -", "minus"),
    90 		   ("op *", "times"),
    91 		   ("op -->", "implies"),
    92 		   ("{}", "emptyset"),
    93 		   ("op :", "in"),
    94 		   ("op Un", "union"),
    95 		   ("op Int", "inter")];
    96 
    97 val type_const_trans_table =
    98       Symtab.make [("*", "t_prod"),
    99 	  	   ("+", "t_sum"),
   100 		   ("~=>", "t_map")];
   101 
   102 (*Escaping of special characters.
   103   Alphanumeric characters are left unchanged.
   104   The character _ goes to __
   105   Characters in the range ASCII space to / go to _A to _P, respectively.
   106   Other printing characters go to _NNN where NNN is the decimal ASCII code.*)
   107 local
   108 
   109 val A_minus_space = Char.ord #"A" - Char.ord #" ";
   110 
   111 fun ascii_of_c c =
   112   if Char.isAlphaNum c then String.str c
   113   else if c = #"_" then "__"
   114   else if #" " <= c andalso c <= #"/" 
   115        then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
   116   else if Char.isPrint c then ("_" ^ Int.toString (Char.ord c))
   117   else ""
   118 
   119 in
   120 
   121 val ascii_of = String.translate ascii_of_c;
   122 
   123 end;
   124 
   125 (* convert a list of strings into one single string; surrounded by brackets *)
   126 fun paren_pack strings = "(" ^ commas strings ^ ")";
   127 
   128 fun bracket_pack strings = "[" ^ commas strings ^ "]";
   129 
   130 
   131 (*Remove the initial ' character from a type variable, if it is present*)
   132 fun trim_type_var s =
   133   if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
   134   else error ("trim_type: Malformed type variable encountered: " ^ s);
   135 
   136 fun ascii_of_indexname (v,0) = ascii_of v
   137   | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ Int.toString i;
   138 
   139 fun make_schematic_var v = schematic_var_prefix ^ (ascii_of_indexname v);
   140 fun make_fixed_var x = fixed_var_prefix ^ (ascii_of x);
   141 
   142 (*Type variables contain _H because the character ' translates to that.*)
   143 fun make_schematic_type_var (x,i) = 
   144       tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
   145 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
   146 
   147 fun make_fixed_const c =
   148     case Symtab.lookup const_trans_table c of
   149         SOME c' => c'
   150       | NONE =>  const_prefix ^ ascii_of c;
   151 
   152 fun make_fixed_type_const c = 
   153     case Symtab.lookup type_const_trans_table c of
   154         SOME c' => c'
   155       | NONE =>  tconst_prefix ^ ascii_of c;
   156 
   157 fun make_type_class clas = class_prefix ^ ascii_of clas;
   158 
   159 
   160 
   161 (***** definitions and functions for FOL clauses, prepared for conversion into TPTP format or SPASS format. *****)
   162 
   163 val keep_types = ref true;
   164 
   165 datatype kind = Axiom | Hypothesis | Conjecture;
   166 fun name_of_kind Axiom = "axiom"
   167   | name_of_kind Hypothesis = "hypothesis"
   168   | name_of_kind Conjecture = "conjecture";
   169 
   170 type clause_id = int;
   171 type axiom_name = string;
   172 
   173 
   174 type polarity = bool;
   175 
   176 type indexname = Term.indexname;
   177 
   178 
   179 (* "tag" is used for vampire specific syntax  *)
   180 type tag = bool; 
   181 
   182 
   183 val id_ref = ref 0;
   184 
   185 fun generate_id () = 
   186   let val id = !id_ref
   187   in id_ref := id + 1; id end;
   188 
   189 
   190 
   191 (**** Isabelle FOL clauses ****)
   192 
   193 val tagged = ref false;
   194 
   195 type pred_name = string;
   196 type sort = Term.sort;
   197 type fol_type = string;
   198 
   199 
   200 datatype type_literal = LTVar of string | LTFree of string;
   201 
   202 
   203 datatype folTerm = UVar of string * fol_type
   204                  | Fun of string * fol_type * folTerm list;
   205 datatype predicate = Predicate of pred_name * fol_type * folTerm list;
   206 
   207 datatype literal = Literal of polarity * predicate * tag;
   208 
   209 datatype typ_var = FOLTVar of indexname | FOLTFree of string;
   210 
   211 
   212 (* ML datatype used to repsent one single clause: disjunction of literals. *)
   213 datatype clause = 
   214 	 Clause of {clause_id: clause_id,
   215 		    axiom_name: axiom_name,
   216 		    kind: kind,
   217 		    literals: literal list,
   218 		    types_sorts: (typ_var * sort) list, 
   219                     tvar_type_literals: type_literal list, 
   220                     tfree_type_literals: type_literal list ,
   221                     tvars: string list,
   222                     predicates: (string*int) list,
   223                     functions: (string*int) list};
   224 
   225 
   226 exception CLAUSE of string * term;
   227 
   228 
   229 (*** make clauses ***)
   230 
   231 fun isFalse (Literal (pol,Predicate(a,_,[]),_)) =
   232       (pol andalso a = "c_False") orelse
   233       (not pol andalso a = "c_True")
   234   | isFalse _ = false;
   235 
   236 fun isTrue (Literal (pol,Predicate(a,_,[]),_)) =
   237       (pol andalso a = "c_True") orelse
   238       (not pol andalso a = "c_False")
   239   | isTrue _ = false;
   240   
   241 fun isTaut (Clause {literals,...}) = exists isTrue literals;  
   242 
   243 fun make_clause (clause_id,axiom_name,kind,literals,
   244                  types_sorts,tvar_type_literals,
   245                  tfree_type_literals,tvars, predicates, functions) =
   246   if forall isFalse literals 
   247   then error "Problem too trivial for resolution (empty clause)"
   248   else
   249      Clause {clause_id = clause_id, axiom_name = axiom_name, kind = kind, 
   250              literals = literals, types_sorts = types_sorts,
   251              tvar_type_literals = tvar_type_literals,
   252              tfree_type_literals = tfree_type_literals,
   253              tvars = tvars, predicates = predicates, 
   254              functions = functions};
   255 
   256 
   257 (** Some Clause destructor functions **)
   258 
   259 fun string_of_kind (Clause cls) = name_of_kind (#kind cls);
   260 
   261 fun get_axiomName (Clause cls) = #axiom_name cls;
   262 
   263 fun get_clause_id (Clause cls) = #clause_id cls;
   264 
   265 fun funcs_of_cls (Clause cls) = #functions cls;
   266 
   267 fun preds_of_cls (Clause cls) = #predicates cls;
   268 
   269 
   270 
   271 (*Definitions of the current theory--to allow suppressing types.*)
   272 val curr_defs = ref Defs.empty;
   273 
   274 (*Initialize the type suppression mechanism with the current theory before
   275     producing any clauses!*)
   276 fun init thy = (id_ref := 0; curr_defs := Theory.defs_of thy);
   277 
   278 fun no_types_needed s = Defs.monomorphic (!curr_defs) s;
   279     
   280 
   281 (*Flatten a type to a string while accumulating sort constraints on the TFress and
   282   TVars it contains.*)    
   283 fun type_of (Type (a, [])) = 
   284       let val t = make_fixed_type_const a
   285       in (t,([],[(t,0)]))  end
   286   | type_of (Type (a, Ts)) = 
   287       let val foltyps_ts = map type_of Ts 
   288 	  val (folTyps,ts_funcs) = ListPair.unzip foltyps_ts
   289 	  val (ts, funcslist) = ListPair.unzip ts_funcs
   290 	  val ts' = ResLib.flat_noDup ts
   291 	  val funcs' = ResLib.flat_noDup funcslist
   292 	  val t = make_fixed_type_const a
   293       in    
   294 	  ((t ^ paren_pack folTyps), (ts', (t, length Ts)::funcs'))
   295       end
   296   | type_of (TFree (a, s)) = 
   297       let val t = make_fixed_type_var a
   298       in (t, ([((FOLTFree a),s)],[(t,0)])) end
   299   | type_of (TVar (v, s)) = (make_schematic_type_var v, ([((FOLTVar v),s)], []))
   300 
   301 
   302 fun maybe_type_of c T =
   303  if no_types_needed c then ("",([],[])) else type_of T;
   304 
   305 (* Any variables created via the METAHYPS tactical should be treated as
   306    universal vars, although it is represented as "Free(...)" by Isabelle *)
   307 val isMeta = String.isPrefix "METAHYP1_"
   308 
   309 fun pred_name_type (Const(c,T)) = 
   310       let val (typof,(folTyps,funcs)) = maybe_type_of c T
   311       in (make_fixed_const c, (typof,folTyps), funcs) end
   312   | pred_name_type (Free(x,T))  = 
   313       if isMeta x then raise CLAUSE("Predicate Not First Order 1", Free(x,T)) 
   314       else (make_fixed_var x, ("",[]), [])
   315   | pred_name_type (v as Var _) = raise CLAUSE("Predicate Not First Order 2", v)
   316   | pred_name_type t        = raise CLAUSE("Predicate input unexpected", t);
   317 
   318 
   319 (* For type equality *)
   320 (* here "arg_typ" is the type of "="'s argument's type, not the type of the equality *)
   321 (* Find type of equality arg *)
   322 fun eq_arg_type (Type("fun",[T,_])) = 
   323     let val (folT,_) = type_of T;
   324     in  folT  end;
   325 
   326 fun fun_name_type (Const(c,T)) args = 
   327       let val t = make_fixed_const c
   328 	val (typof, (folTyps,funcs)) = maybe_type_of c T
   329 	val arity = if !keep_types andalso not (no_types_needed c)
   330 	            then 1 + length args
   331 	            else length args
   332       in
   333 	  (t, (typof,folTyps), ((t,arity)::funcs))
   334       end
   335  | fun_name_type (Free(x,T)) args  = 
   336       let val t = make_fixed_var x
   337       in
   338 	    (t, ("",[]), [(t, length args)])
   339       end
   340   | fun_name_type f args = raise CLAUSE("Function Not First Order 1", f);
   341 
   342 
   343 fun term_of (Var(ind_nm,T)) = 
   344       let val (folType,(ts,funcs)) = type_of T
   345       in
   346 	  (UVar(make_schematic_var ind_nm, folType), (ts, funcs))
   347       end
   348   | term_of (Free(x,T)) = 
   349       let val (folType, (ts,funcs)) = type_of T
   350       in
   351 	  if isMeta x then (UVar(make_schematic_var(x,0),folType),
   352 			    (ts, ((make_schematic_var(x,0)),0)::funcs))
   353 	  else
   354 	      (Fun(make_fixed_var x, folType, []), 
   355 	       (ts, ((make_fixed_var x),0)::funcs))
   356       end
   357   | term_of (Const(c,T)) =  (* impossible to be equality *)
   358       let val (folType,(ts,funcs)) = type_of T
   359       in
   360 	  (Fun(make_fixed_const c, folType, []),
   361 	   (ts, ((make_fixed_const c),0)::funcs))
   362       end    
   363   | term_of (app as (t $ a)) = 
   364       let val (f,args) = strip_comb app
   365 	  fun term_of_aux () = 
   366 	      let val (funName,(funType,ts1),funcs) = fun_name_type f args
   367 		  val (args',ts_funcs) = ListPair.unzip (map term_of args)
   368 		  val (ts2,funcs') = ListPair.unzip ts_funcs
   369 		  val ts3 = ResLib.flat_noDup (ts1::ts2)
   370 		  val funcs'' = ResLib.flat_noDup((funcs::funcs'))
   371 	      in
   372 		  (Fun(funName,funType,args'), (ts3,funcs''))
   373 	      end
   374 	  fun term_of_eq ((Const ("op =", typ)),args) =
   375 	      let val arg_typ = eq_arg_type typ
   376 		  val (args',ts_funcs) = ListPair.unzip (map term_of args)
   377 		  val (ts,funcs) = ListPair.unzip ts_funcs
   378 		  val equal_name = make_fixed_const ("op =")
   379 	      in
   380 		  (Fun(equal_name,arg_typ,args'),
   381 		   (ResLib.flat_noDup ts, 
   382 		    (make_fixed_var equal_name, 2):: ResLib.flat_noDup funcs))
   383 	      end
   384       in
   385 	 case f of Const ("op =", typ) => term_of_eq (f,args)
   386 		 | Const(_,_) => term_of_aux ()
   387 		 | Free(s,_)  => 
   388 		     if isMeta s 
   389 		     then raise CLAUSE("Function Not First Order 2", f)
   390 		     else term_of_aux()
   391 		 | _ => raise CLAUSE("Function Not First Order 3", f)
   392       end
   393   | term_of t = raise CLAUSE("Function Not First Order 4", t); 
   394 
   395 
   396 fun pred_of (Const("op =", typ), args) =
   397       let val arg_typ = eq_arg_type typ 
   398 	  val (args',ts_funcs) = ListPair.unzip (map term_of args)
   399 	  val (ts,funcs) = ListPair.unzip ts_funcs
   400 	  val equal_name = make_fixed_const "op ="
   401       in
   402 	  (Predicate(equal_name,arg_typ,args'),
   403 	   ResLib.flat_noDup ts, 
   404 	   [((make_fixed_var equal_name), 2)], 
   405 	   (ResLib.flat_noDup funcs))
   406       end
   407   | pred_of (pred,args) = 
   408       let val (predName,(predType,ts1), pfuncs) = pred_name_type pred
   409 	  val (args',ts_funcs) = ListPair.unzip (map term_of args)
   410 	  val (ts2,ffuncs) = ListPair.unzip ts_funcs
   411 	  val ts3 = ResLib.flat_noDup (ts1::ts2)
   412 	  val ffuncs' = (ResLib.flat_noDup ffuncs)
   413 	  val newfuncs = distinct (pfuncs@ffuncs')
   414 	  val arity = 
   415 	    case pred of
   416 		Const (c,_) => 
   417 		      if !keep_types andalso not (no_types_needed c)
   418 		      then 1 + length args
   419 		      else length args
   420 	      | _ => length args
   421       in
   422 	  (Predicate(predName,predType,args'), ts3, 
   423 	   [(predName, arity)], newfuncs)
   424       end;
   425 
   426 
   427 (*Treatment of literals, possibly negated or tagged*)
   428 fun predicate_of ((Const("Not",_) $ P), polarity, tag) =
   429       predicate_of (P, not polarity, tag)
   430   | predicate_of ((Const("HOL.tag",_) $ P), polarity, tag) =
   431       predicate_of (P, polarity, true)
   432   | predicate_of (term,polarity,tag) =
   433         (pred_of (strip_comb term), polarity, tag);
   434 
   435 fun literals_of_term ((Const("Trueprop",_) $ P),lits_ts, preds, funcs) =    
   436       literals_of_term(P,lits_ts, preds, funcs)
   437   | literals_of_term ((Const("op |",_) $ P $ Q),(lits,ts), preds,funcs) = 
   438       let val (lits',ts', preds', funcs') = 
   439             literals_of_term(P,(lits,ts), preds,funcs)
   440       in
   441 	  literals_of_term(Q, (lits',ts'), distinct(preds'@preds), 
   442 	                   distinct(funcs'@funcs))
   443       end
   444   | literals_of_term (P,(lits,ts), preds, funcs) = 
   445       let val ((pred,ts', preds', funcs'), pol, tag) = 
   446               predicate_of (P,true,false)
   447 	  val lits' = Literal(pol,pred,tag) :: lits
   448 	  val ts'' = ResLib.no_rep_app ts ts' 
   449       in
   450 	  (lits',ts'', distinct(preds'@preds), distinct(funcs'@funcs))
   451       end;
   452 
   453 
   454 fun literals_of_thm thm = literals_of_term (prop_of thm, ([],[]), [], []);
   455 
   456 
   457 (* FIX: not sure what to do with these funcs *)
   458 
   459 (*Make literals for sorted type variables*) 
   460 fun sorts_on_typs (_, [])   = ([]) 
   461   | sorts_on_typs (v, "HOL.type" :: s) =
   462       sorts_on_typs (v,s)   (*Ignore sort "type"*)
   463   | sorts_on_typs ((FOLTVar indx), (s::ss)) =
   464       LTVar((make_type_class s) ^ 
   465         "(" ^ (make_schematic_type_var indx) ^ ")") :: 
   466       (sorts_on_typs ((FOLTVar indx), ss))
   467   | sorts_on_typs ((FOLTFree x), (s::ss)) =
   468       LTFree((make_type_class s) ^ "(" ^ (make_fixed_type_var x) ^ ")") :: 
   469       (sorts_on_typs ((FOLTFree x), ss));
   470 
   471 
   472 (*UGLY: seems to be parsing the "show sorts" output, removing anything that
   473   starts with a left parenthesis.*)
   474 fun remove_type str = hd (String.fields (fn c => c = #"(") str);
   475 
   476 fun pred_of_sort (LTVar x) = ((remove_type x),1)
   477 |   pred_of_sort (LTFree x) = ((remove_type x),1)
   478 
   479 
   480 
   481 
   482 (*Given a list of sorted type variables, return two separate lists.
   483   The first is for TVars, the second for TFrees.*)
   484 fun add_typs_aux [] preds  = ([],[], preds)
   485   | add_typs_aux ((FOLTVar indx,s)::tss) preds = 
   486       let val vs = sorts_on_typs (FOLTVar indx, s)
   487           val preds' = (map pred_of_sort vs)@preds
   488 	  val (vss,fss, preds'') = add_typs_aux tss preds'
   489       in
   490 	  (ResLib.no_rep_app vs vss, fss, preds'')
   491       end
   492   | add_typs_aux ((FOLTFree x,s)::tss) preds  =
   493       let val fs = sorts_on_typs (FOLTFree x, s)
   494           val preds' = (map pred_of_sort fs)@preds
   495 	  val (vss,fss, preds'') = add_typs_aux tss preds'
   496       in
   497 	  (vss, ResLib.no_rep_app fs fss,preds'')
   498       end;
   499 
   500 fun add_typs (Clause cls) preds  = add_typs_aux (#types_sorts cls) preds 
   501 
   502 
   503 (** make axiom clauses, hypothesis clauses and conjecture clauses. **)
   504 
   505 fun get_tvar_strs [] = []
   506   | get_tvar_strs ((FOLTVar indx,s)::tss) = 
   507       let val vstr = make_schematic_type_var indx
   508           val vstrs = get_tvar_strs tss
   509       in
   510 	  (distinct( vstr:: vstrs))
   511       end
   512   | get_tvar_strs((FOLTFree x,s)::tss) = distinct (get_tvar_strs tss)
   513 
   514 (* FIX add preds and funcs to add typs aux here *)
   515 
   516 fun make_axiom_clause_thm thm (ax_name,cls_id) =
   517     let val (lits,types_sorts, preds, funcs) = literals_of_thm thm
   518 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds 
   519         val tvars = get_tvar_strs types_sorts
   520     in 
   521 	make_clause(cls_id,ax_name,Axiom,
   522 	            lits,types_sorts,tvar_lits,tfree_lits,
   523 	            tvars, preds, funcs)
   524     end;
   525 
   526 
   527 
   528 fun make_conjecture_clause_thm thm =
   529     let val (lits,types_sorts, preds, funcs) = literals_of_thm thm
   530 	val cls_id = generate_id()
   531 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds 
   532         val tvars = get_tvar_strs types_sorts
   533     in
   534 	make_clause(cls_id,"",Conjecture,
   535 	            lits,types_sorts,tvar_lits,tfree_lits,
   536 	            tvars, preds, funcs)
   537     end;
   538 
   539 
   540 fun make_axiom_clause term (ax_name,cls_id) =
   541     let val (lits,types_sorts, preds,funcs) = literals_of_term (term,([],[]), [],[])
   542 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds
   543         val tvars = get_tvar_strs types_sorts	
   544     in 
   545 	make_clause(cls_id,ax_name,Axiom,
   546 	            lits,types_sorts,tvar_lits,tfree_lits,
   547 	            tvars, preds,funcs)
   548     end;
   549 
   550 
   551 fun make_hypothesis_clause term =
   552     let val (lits,types_sorts, preds, funcs) = literals_of_term (term,([],[]),[],[])
   553 	val cls_id = generate_id()
   554 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts  preds 
   555         val tvars = get_tvar_strs types_sorts
   556     in
   557 	make_clause(cls_id,"",Hypothesis,
   558 	            lits,types_sorts,tvar_lits,tfree_lits,
   559 	            tvars, preds, funcs)
   560     end;
   561  
   562 fun make_conjecture_clause term =
   563     let val (lits,types_sorts, preds, funcs) = literals_of_term (term,([],[]),[],[])
   564 	val cls_id = generate_id()
   565 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds 
   566         val tvars = get_tvar_strs types_sorts	
   567     in
   568 	make_clause(cls_id,"",Conjecture,
   569 	            lits,types_sorts,tvar_lits,tfree_lits,
   570 	            tvars, preds, funcs)
   571     end;
   572  
   573 
   574  
   575 (**** Isabelle arities ****)
   576 
   577 exception ARCLAUSE of string;
   578  
   579 
   580 type class = string; 
   581 type tcons = string; 
   582 
   583 
   584 datatype arLit = TConsLit of bool * (class * tcons * string list) | TVarLit of bool * (class * string);
   585  
   586 datatype arityClause =  
   587 	 ArityClause of {clause_id: clause_id,
   588 			 kind: kind,
   589 			 conclLit: arLit,
   590 			 premLits: arLit list};
   591 
   592 
   593 fun get_TVars 0 = []
   594   | get_TVars n = ("T_" ^ (Int.toString n)) :: get_TVars (n-1);
   595 
   596 
   597 
   598 fun pack_sort(_,[])  = raise ARCLAUSE("Empty Sort Found") 
   599   | pack_sort(tvar, [cls]) = [(make_type_class cls, tvar)] 
   600   | pack_sort(tvar, cls::srt) =  (make_type_class cls,tvar) :: (pack_sort(tvar, srt));
   601     
   602     
   603 fun make_TVarLit (b,(cls,str)) = TVarLit(b,(cls,str));
   604 fun make_TConsLit (b,(cls,tcons,tvars)) = TConsLit(b,(make_type_class cls,make_fixed_type_const tcons,tvars));
   605 
   606 
   607 fun make_arity_clause (clause_id,kind,conclLit,premLits) =
   608     ArityClause {clause_id = clause_id, kind = kind, conclLit = conclLit, premLits = premLits};
   609 
   610 
   611 fun make_axiom_arity_clause (tcons,(res,args)) =
   612      let val cls_id = generate_id()
   613 	 val nargs = length args
   614 	 val tvars = get_TVars nargs
   615 	 val conclLit = make_TConsLit(true,(res,tcons,tvars))
   616          val tvars_srts = ListPair.zip (tvars,args)
   617 	 val tvars_srts' = ResLib.flat_noDup(map pack_sort tvars_srts)
   618          val false_tvars_srts' = map (pair false) tvars_srts'
   619 	 val premLits = map make_TVarLit false_tvars_srts'
   620      in
   621 	 make_arity_clause (cls_id,Axiom,conclLit,premLits)
   622      end;
   623     
   624 (*The number of clauses generated from cls, including type clauses*)
   625 fun num_of_clauses (Clause cls) =
   626     let val num_tfree_lits = 
   627 	      if !keep_types then length (#tfree_type_literals cls)
   628 	      else 0
   629     in 	1 + num_tfree_lits  end;
   630 
   631 
   632 (**** Isabelle class relations ****)
   633 
   634 
   635 datatype classrelClause = 
   636 	 ClassrelClause of {clause_id: clause_id,
   637 			    subclass: class,
   638 			    superclass: class option};
   639 
   640 fun make_classrelClause (clause_id,subclass,superclass) =
   641     ClassrelClause {clause_id = clause_id,subclass = subclass, superclass = superclass};
   642 
   643 
   644 fun make_axiom_classrelClause (subclass,superclass) =
   645     let val cls_id = generate_id()
   646 	val sub = make_type_class subclass
   647 	val sup = case superclass of NONE => NONE 
   648 				   | SOME s => SOME (make_type_class s)
   649     in
   650 	make_classrelClause(cls_id,sub,sup)
   651     end;
   652 
   653 
   654 
   655 fun classrelClauses_of_aux (sub,[]) = []
   656   | classrelClauses_of_aux (sub,(sup::sups)) = make_axiom_classrelClause(sub,SOME sup) :: (classrelClauses_of_aux (sub,sups));
   657 
   658 
   659 fun classrelClauses_of (sub,sups) = 
   660     case sups of [] => [make_axiom_classrelClause (sub,NONE)]
   661 	       | _ => classrelClauses_of_aux (sub, sups);
   662 
   663 
   664 (****!!!! Changed for typed equality !!!!****)
   665 
   666 fun wrap_eq_type typ t = eq_typ_wrapper ^"(" ^ t ^ "," ^ typ ^ ")";
   667 
   668 (* Only need to wrap equality's arguments with "typeinfo" if the output clauses are typed && if we specifically ask for types to be included.   *)
   669 fun string_of_equality (typ,terms) =
   670       let val [tstr1,tstr2] = map string_of_term terms
   671       in
   672 	  if !keep_types andalso !special_equal 
   673 	  then "equal(" ^ (wrap_eq_type typ tstr1) ^ "," ^ 
   674 		 	  (wrap_eq_type typ tstr2) ^ ")"
   675 	  else "equal(" ^ tstr1 ^ "," ^ tstr2 ^ ")"
   676       end
   677 and string_of_term (UVar(x,_)) = x
   678   | string_of_term (Fun("equal",typ,terms)) = string_of_equality(typ,terms)
   679   | string_of_term (Fun (name,typ,[])) = name
   680   | string_of_term (Fun (name,typ,terms)) = 
   681       let val terms' = map string_of_term terms
   682       in
   683 	  if !keep_types andalso typ<>"" 
   684 	  then name ^ (paren_pack (terms' @ [typ]))
   685 	  else name ^ (paren_pack terms')
   686       end;
   687 
   688 (* before output the string of the predicate, check if the predicate corresponds to an equality or not. *)
   689 fun string_of_predicate (Predicate("equal",typ,terms)) = 
   690       string_of_equality(typ,terms)
   691   | string_of_predicate (Predicate(name,_,[])) = name 
   692   | string_of_predicate (Predicate(name,typ,terms)) = 
   693       let val terms_as_strings = map string_of_term terms
   694       in
   695 	  if !keep_types andalso typ<>""
   696 	  then name ^ (paren_pack (terms_as_strings @ [typ]))
   697 	  else name ^ (paren_pack terms_as_strings) 
   698       end;
   699 
   700 
   701 fun string_of_clausename (cls_id,ax_name) = 
   702     clause_prefix ^ ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   703 
   704 fun string_of_type_clsname (cls_id,ax_name,idx) = 
   705     string_of_clausename (cls_id,ax_name) ^ "_tcs" ^ (Int.toString idx);
   706     
   707 
   708 (********************************)
   709 (* Code for producing DFG files *)
   710 (********************************)
   711 
   712 fun dfg_literal (Literal(pol,pred,tag)) =
   713     let val pred_string = string_of_predicate pred
   714     in
   715 	if pol then pred_string else "not(" ^pred_string ^ ")"  
   716     end;
   717 
   718 
   719 (* FIX: what does this mean? *)
   720 (*fun dfg_of_typeLit (LTVar x) = "not(" ^ x ^ ")"
   721   | dfg_of_typeLit (LTFree x) = "(" ^ x ^ ")";*)
   722 
   723 fun dfg_of_typeLit (LTVar x) =  x 
   724   | dfg_of_typeLit (LTFree x) = x ;
   725  
   726 (*Make the string of universal quantifiers for a clause*)
   727 fun forall_open ([],[]) = ""
   728   | forall_open (vars,tvars) = "forall([" ^ (commas (tvars@vars))^ "],\n"
   729 
   730 fun forall_close ([],[]) = ""
   731   | forall_close (vars,tvars) = ")"
   732 
   733 fun gen_dfg_cls (cls_id,ax_name,knd,lits,tvars,vars) = 
   734     "clause( %(" ^ knd ^ ")\n" ^ forall_open(vars,tvars) ^ 
   735     "or(" ^ lits ^ ")" ^ forall_close(vars,tvars) ^ ",\n" ^ 
   736     string_of_clausename (cls_id,ax_name) ^  ").";
   737 
   738 fun gen_dfg_type_cls (cls_id,ax_name,knd,tfree_lit,idx,tvars,vars) = 
   739     "clause( %(" ^ knd ^ ")\n" ^ forall_open(vars,tvars) ^ 
   740     "or( " ^ tfree_lit ^ ")" ^ forall_close(vars,tvars) ^ ",\n" ^ 
   741     string_of_type_clsname (cls_id,ax_name,idx) ^  ").";
   742 
   743 fun dfg_clause_aux (Clause cls) = 
   744   let val lits = map dfg_literal (#literals cls)
   745       val tvar_lits_strs = 
   746 	  if !keep_types then map dfg_of_typeLit (#tvar_type_literals cls) 
   747 	  else []
   748       val tfree_lits =
   749           if !keep_types then map dfg_of_typeLit (#tfree_type_literals cls)
   750           else []
   751   in
   752       (tvar_lits_strs @ lits, tfree_lits)
   753   end; 
   754 
   755 
   756 fun dfg_folterms (Literal(pol,pred,tag)) = 
   757   let val Predicate (predname, foltype, folterms) = pred
   758   in
   759       folterms
   760   end
   761 
   762  
   763 fun get_uvars (UVar(a,typ)) = [a] 
   764 |   get_uvars (Fun (_,typ,tlist)) = ResLib.flat_noDup(map get_uvars tlist)
   765 
   766 
   767 fun is_uvar (UVar _) = true
   768 |   is_uvar (Fun _) = false;
   769 
   770 fun uvar_name (UVar(a,_)) = a
   771 |   uvar_name (Fun (a,_,_)) = raise CLAUSE("Not a variable", Const(a,dummyT));
   772 
   773 fun mergelist [] = []
   774 |   mergelist (x::xs) = x @ mergelist xs
   775 
   776 fun dfg_vars (Clause cls) =
   777     let val lits = #literals cls
   778         val folterms = mergelist(map dfg_folterms lits)
   779     in 
   780         ResLib.flat_noDup(map get_uvars folterms)
   781     end
   782 
   783 
   784 fun dfg_tvars (Clause cls) =(#tvars cls)
   785 
   786 
   787 	
   788 (* make this return funcs and preds too? *)
   789 fun string_of_predname (Predicate("equal",typ,terms)) = "EQUALITY"
   790   | string_of_predname (Predicate(name,_,[])) = name 
   791   | string_of_predname (Predicate(name,typ,terms)) = name
   792     
   793 	
   794 (* make this return funcs and preds too? *)
   795 
   796 fun string_of_predicate (Predicate("equal",typ,terms)) =  
   797       string_of_equality(typ,terms)
   798   | string_of_predicate (Predicate(name,_,[])) = name 
   799   | string_of_predicate (Predicate(name,typ,terms)) = 
   800       let val terms_as_strings = map string_of_term terms
   801       in
   802 	  if !keep_types andalso typ<>""
   803 	  then name ^ (paren_pack  (terms_as_strings @ [typ]))
   804 	  else name ^ (paren_pack terms_as_strings) 
   805       end;
   806 
   807 
   808 fun concat_with sep []  = ""
   809   | concat_with sep [x] = "(" ^ x ^ ")"
   810   | concat_with sep (x::xs) = "(" ^ x ^ ")" ^  sep ^ (concat_with sep xs);
   811 
   812 fun dfg_pred (Literal(pol,pred,tag)) ax_name = 
   813     (string_of_predname pred) ^ " " ^ ax_name
   814 
   815 fun dfg_clause cls =
   816     let val (lits,tfree_lits) = dfg_clause_aux cls 
   817              (*"lits" includes the typing assumptions (TVars)*)
   818         val vars = dfg_vars cls
   819         val tvars = dfg_tvars cls
   820 	val knd = string_of_kind cls
   821 	val lits_str = commas lits
   822 	val cls_id = get_clause_id cls
   823 	val axname = get_axiomName cls
   824 	val cls_str = gen_dfg_cls(cls_id,axname,knd,lits_str,tvars, vars) 			
   825         fun typ_clss k [] = []
   826           | typ_clss k (tfree :: tfrees) = 
   827               (gen_dfg_type_cls(cls_id,axname,knd,tfree,k, tvars,vars)) :: 
   828               (typ_clss (k+1) tfrees)
   829     in 
   830 	cls_str :: (typ_clss 0 tfree_lits)
   831     end;
   832 
   833 fun string_of_arity (name, num) =  name ^ "," ^ (Int.toString num) 
   834 
   835 fun string_of_preds preds = 
   836   "predicates[" ^ (concat_with ", " (map string_of_arity preds)) ^ "].\n";
   837 
   838 fun string_of_funcs funcs =
   839   "functions[" ^ (concat_with ", " (map string_of_arity funcs)) ^ "].\n" ;
   840 
   841 
   842 fun string_of_symbols predstr funcstr = 
   843   "list_of_symbols.\n" ^ predstr  ^ funcstr  ^ "end_of_list.\n\n";
   844 
   845 
   846 fun string_of_axioms axstr = 
   847   "list_of_clauses(axioms,cnf).\n" ^ axstr ^ "end_of_list.\n\n";
   848 
   849 
   850 fun string_of_conjectures conjstr = 
   851   "list_of_clauses(conjectures,cnf).\n" ^ conjstr ^ "end_of_list.\n\n";
   852 
   853 fun string_of_descrip () = 
   854   "list_of_descriptions.\nname({*[ File     : ],[ Names    :]*}).\nauthor({*[ Source   :]*}).\nstatus(unknown).\ndescription({*[ Refs     :]*}).\nend_of_list.\n\n"
   855 
   856 
   857 fun string_of_start name = "%------------------------------------------------------------------------------\nbegin_problem(" ^ name ^ ").\n\n";
   858 
   859 
   860 fun string_of_end () = "end_problem.\n%------------------------------------------------------------------------------";
   861 
   862 
   863 fun clause2dfg cls =
   864     let val (lits,tfree_lits) = dfg_clause_aux cls 
   865             (*"lits" includes the typing assumptions (TVars)*)
   866 	val cls_id = get_clause_id cls
   867 	val ax_name = get_axiomName cls
   868         val vars = dfg_vars cls
   869         val tvars = dfg_tvars cls
   870         val funcs = funcs_of_cls cls
   871         val preds = preds_of_cls cls
   872 	val knd = string_of_kind cls
   873 	val lits_str = commas lits
   874 	val cls_str = gen_dfg_cls(cls_id,ax_name,knd,lits_str,tvars,vars) 
   875     in
   876 	(cls_str,tfree_lits) 
   877     end;
   878 
   879 
   880 
   881 fun tfree_dfg_clause tfree_lit =
   882   "clause( %(conjecture)\n" ^ "or( " ^ tfree_lit ^ "),\n" ^ "tfree_tcs" ^ ")."
   883 
   884 
   885 fun gen_dfg_file probname axioms conjectures funcs preds = 
   886     let val axstrs_tfrees = (map clause2dfg axioms)
   887 	val (axstrs, atfrees) = ListPair.unzip axstrs_tfrees
   888         val axstr = (space_implode "\n" axstrs) ^ "\n\n"
   889         val conjstrs_tfrees = (map clause2dfg conjectures)
   890 	val (conjstrs, atfrees) = ListPair.unzip conjstrs_tfrees
   891         val tfree_clss = map tfree_dfg_clause (ResLib.flat_noDup atfrees) 
   892         val conjstr = (space_implode "\n" (tfree_clss@conjstrs)) ^ "\n\n"
   893         val funcstr = string_of_funcs funcs
   894         val predstr = string_of_preds preds
   895     in
   896        (string_of_start probname) ^ (string_of_descrip ()) ^ 
   897        (string_of_symbols funcstr predstr) ^  
   898        (string_of_axioms axstr) ^
   899        (string_of_conjectures conjstr) ^ (string_of_end ())
   900     end;
   901    
   902 fun clauses2dfg [] probname axioms conjectures funcs preds = 
   903       let val funcs' = (ResLib.flat_noDup(map funcs_of_cls axioms)) @ funcs
   904 	  val preds' = (ResLib.flat_noDup(map preds_of_cls axioms)) @ preds
   905       in
   906 	 gen_dfg_file probname axioms conjectures funcs' preds' 
   907       end
   908  | clauses2dfg (cls::clss) probname axioms conjectures funcs preds = 
   909      let val (lits,tfree_lits) = dfg_clause_aux cls
   910 	       (*"lits" includes the typing assumptions (TVars)*)
   911 	 val cls_id = get_clause_id cls
   912 	 val ax_name = get_axiomName cls
   913 	 val vars = dfg_vars cls
   914 	 val tvars = dfg_tvars cls
   915 	 val funcs' = distinct((funcs_of_cls cls)@funcs)
   916 	 val preds' = distinct((preds_of_cls cls)@preds)
   917 	 val knd = string_of_kind cls
   918 	 val lits_str = concat_with ", " lits
   919 	 val axioms' = if knd = "axiom" then (cls::axioms) else axioms
   920 	 val conjectures' = 
   921 	     if knd = "conjecture" then (cls::conjectures) else conjectures
   922      in
   923 	 clauses2dfg clss probname axioms' conjectures' funcs' preds' 
   924      end;
   925 
   926 
   927 fun string_of_arClauseID (ArityClause arcls) =
   928     arclause_prefix ^ Int.toString(#clause_id arcls);
   929 
   930 fun string_of_arKind (ArityClause arcls) = name_of_kind(#kind arcls);
   931 
   932 (*FIXME!!! currently is TPTP format!*)
   933 fun dfg_of_arLit (TConsLit(b,(c,t,args))) =
   934       let val pol = if b then "++" else "--"
   935 	  val arg_strs = (case args of [] => "" | _ => paren_pack args)
   936       in 
   937 	  pol ^ c ^ "(" ^ t ^ arg_strs ^ ")"
   938       end
   939   | dfg_of_arLit (TVarLit(b,(c,str))) =
   940       let val pol = if b then "++" else "--"
   941       in
   942 	  pol ^ c ^ "(" ^ str ^ ")"
   943       end;
   944     
   945 
   946 fun dfg_of_conclLit (ArityClause arcls) = dfg_of_arLit (#conclLit arcls);
   947      
   948 
   949 fun dfg_of_premLits (ArityClause arcls) = map dfg_of_arLit (#premLits arcls);
   950 		
   951 
   952 
   953 (*FIXME: would this have variables in a forall? *)
   954 
   955 fun dfg_arity_clause arcls = 
   956   let val arcls_id = string_of_arClauseID arcls
   957       val concl_lit = dfg_of_conclLit arcls
   958       val prems_lits = dfg_of_premLits arcls
   959       val knd = string_of_arKind arcls
   960       val all_lits = concl_lit :: prems_lits
   961   in
   962       "clause( %(" ^ knd ^ ")\n" ^  "or( " ^ (bracket_pack all_lits) ^ ")),\n" ^
   963        arcls_id ^  ")."
   964   end;
   965 
   966 
   967 (********************************)
   968 (* code to produce TPTP files   *)
   969 (********************************)
   970 
   971 fun tptp_literal (Literal(pol,pred,tag)) =
   972     let val pred_string = string_of_predicate pred
   973 	val tagged_pol = 
   974 	      if (tag andalso !tagged) then (if pol then "+++" else "---")
   975 	      else (if pol then "++" else "--")
   976      in
   977 	tagged_pol ^ pred_string
   978     end;
   979 
   980 
   981 
   982 fun tptp_of_typeLit (LTVar x) = "--" ^ x
   983   | tptp_of_typeLit (LTFree x) = "++" ^ x;
   984  
   985 
   986 fun gen_tptp_cls (cls_id,ax_name,knd,lits) = 
   987     "input_clause(" ^ string_of_clausename (cls_id,ax_name) ^ "," ^ 
   988     knd ^ "," ^ lits ^ ").";
   989 
   990 fun gen_tptp_type_cls (cls_id,ax_name,knd,tfree_lit,idx) = 
   991     "input_clause(" ^ string_of_type_clsname (cls_id,ax_name,idx) ^ "," ^ 
   992     knd ^ ",[" ^ tfree_lit ^ "]).";
   993 
   994 fun tptp_type_lits (Clause cls) = 
   995     let val lits = map tptp_literal (#literals cls)
   996 	val tvar_lits_strs =
   997 	      if !keep_types 
   998 	      then (map tptp_of_typeLit (#tvar_type_literals cls)) 
   999 	      else []
  1000 	val tfree_lits = 
  1001 	      if !keep_types
  1002 	      then (map tptp_of_typeLit (#tfree_type_literals cls)) 
  1003 	      else []
  1004     in
  1005 	(tvar_lits_strs @ lits, tfree_lits)
  1006     end; 
  1007 
  1008 fun tptp_clause cls =
  1009     let val (lits,tfree_lits) = tptp_type_lits cls 
  1010             (*"lits" includes the typing assumptions (TVars)*)
  1011 	val cls_id = get_clause_id cls
  1012 	val ax_name = get_axiomName cls
  1013 	val knd = string_of_kind cls
  1014 	val lits_str = bracket_pack lits
  1015 	val cls_str = gen_tptp_cls(cls_id,ax_name,knd,lits_str) 			 
  1016 	fun typ_clss k [] = []
  1017           | typ_clss k (tfree :: tfrees) = 
  1018               gen_tptp_type_cls(cls_id,ax_name,knd,tfree,k) :: 
  1019               typ_clss (k+1) tfrees
  1020     in 
  1021 	cls_str :: (typ_clss 0 tfree_lits)
  1022     end;
  1023 
  1024 fun clause2tptp cls =
  1025     let val (lits,tfree_lits) = tptp_type_lits cls 
  1026             (*"lits" includes the typing assumptions (TVars)*)
  1027 	val cls_id = get_clause_id cls
  1028 	val ax_name = get_axiomName cls
  1029 	val knd = string_of_kind cls
  1030 	val lits_str = bracket_pack lits
  1031 	val cls_str = gen_tptp_cls(cls_id,ax_name,knd,lits_str) 
  1032     in
  1033 	(cls_str,tfree_lits) 
  1034     end;
  1035 
  1036 
  1037 fun tfree_clause tfree_lit =
  1038     "input_clause(" ^ "tfree_tcs," ^ "conjecture" ^ ",[" ^ tfree_lit ^ "]).";
  1039 
  1040 
  1041 fun tptp_of_arLit (TConsLit(b,(c,t,args))) =
  1042       let val pol = if b then "++" else "--"
  1043 	  val  arg_strs = (case args of [] => "" | _ => paren_pack args)
  1044       in 
  1045 	  pol ^ c ^ "(" ^ t ^ arg_strs ^ ")"
  1046       end
  1047   | tptp_of_arLit (TVarLit(b,(c,str))) =
  1048       let val pol = if b then "++" else "--"
  1049       in
  1050 	  pol ^ c ^ "(" ^ str ^ ")"
  1051       end;
  1052     
  1053 
  1054 fun tptp_of_conclLit (ArityClause arcls) = tptp_of_arLit (#conclLit arcls);
  1055      
  1056 fun tptp_of_premLits (ArityClause arcls) = map tptp_of_arLit (#premLits arcls);
  1057 		
  1058 fun tptp_arity_clause arcls = 
  1059     let val arcls_id = string_of_arClauseID arcls
  1060 	val concl_lit = tptp_of_conclLit arcls
  1061 	val prems_lits = tptp_of_premLits arcls
  1062 	val knd = string_of_arKind arcls
  1063 	val all_lits = concl_lit :: prems_lits
  1064     in
  1065 	"input_clause(" ^ arcls_id ^ "," ^ knd ^ "," ^ 
  1066 	(bracket_pack all_lits) ^ ")."
  1067     end;
  1068 
  1069 fun tptp_classrelLits sub sup = 
  1070     let val tvar = "(T)"
  1071     in 
  1072 	case sup of NONE => "[++" ^ sub ^ tvar ^ "]"
  1073 		  | (SOME supcls) =>  "[--" ^ sub ^ tvar ^ ",++" ^ supcls ^ tvar ^ "]"
  1074     end;
  1075 
  1076 
  1077 fun tptp_classrelClause (ClassrelClause cls) =
  1078     let val relcls_id = clrelclause_prefix ^ Int.toString(#clause_id cls)
  1079 	val sub = #subclass cls
  1080 	val sup = #superclass cls
  1081 	val lits = tptp_classrelLits sub sup
  1082     in
  1083 	"input_clause(" ^ relcls_id ^ ",axiom," ^ lits ^ ")."
  1084     end; 
  1085 
  1086 end;