src/HOL/Tools/res_clause.ML
author paulson
Wed Dec 13 12:42:26 2006 +0100 (2006-12-13)
changeset 21813 06a06f6d3166
parent 21790 9d2761d09d91
child 21858 05f57309170c
permissions -rw-r--r--
Deleted the unused type argument of UVar
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory
     2     ID: $Id$
     3     Copyright 2004 University of Cambridge
     4 
     5 ML data structure for storing/printing FOL clauses and arity clauses.
     6 Typed equality is treated differently.
     7 *)
     8 
     9 (*FIXME: is this signature necessary? Or maybe define and open a Basic_ResClause?*)
    10 signature RES_CLAUSE =
    11   sig
    12   exception CLAUSE of string * term
    13   type clause and arityClause and classrelClause
    14   datatype fol_type = AtomV of string
    15                     | AtomF of string
    16                     | Comp of string * fol_type list;
    17   datatype fol_term = UVar of string
    18                     | Fun of string * fol_type list * fol_term list;
    19   datatype predicate = Predicate of string * fol_type list * fol_term list;
    20   datatype kind = Axiom | Conjecture;
    21   val name_of_kind : kind -> string
    22   type typ_var and type_literal and literal
    23   val literals_of_term: Term.term -> literal list * (typ_var * Term.sort) list
    24   val add_typs_aux : (typ_var * string list) list -> type_literal list * type_literal list
    25   val arity_clause_thy: theory -> arityClause list 
    26   val ascii_of : string -> string
    27   val tptp_pack : string list -> string
    28   val make_classrel_clauses: theory -> class list -> class list -> classrelClause list 
    29   val clause_prefix : string 
    30   val clause2tptp : clause -> string * string list
    31   val const_prefix : string
    32   val dfg_write_file:  thm list -> string -> 
    33        ((thm * (string * int)) list * classrelClause list * arityClause list) -> string list
    34   val fixed_var_prefix : string
    35   val gen_tptp_cls : int * string * string * string list -> string
    36   val get_axiomName : clause ->  string
    37   val get_literals : clause -> literal list
    38   val init : theory -> unit
    39   val isMeta : string -> bool
    40   val isTaut : clause -> bool
    41   val list_ord : ('a * 'b -> order) -> 'a list * 'b list -> order
    42   val make_axiom_clause : thm -> string * int -> clause option
    43   val make_conjecture_clauses : thm list -> clause list
    44   val make_fixed_const : string -> string		
    45   val make_fixed_type_const : string -> string   
    46   val make_fixed_type_var : string -> string
    47   val make_fixed_var : string -> string
    48   val make_schematic_type_var : string * int -> string
    49   val make_schematic_var : string * int -> string
    50   val make_type_class : string -> string
    51   val mk_fol_type: string * string * fol_type list -> fol_type
    52   val mk_typ_var_sort : Term.typ -> typ_var * sort
    53   val paren_pack : string list -> string
    54   val schematic_var_prefix : string
    55   val string_of_fol_type : fol_type -> string
    56   val tconst_prefix : string 
    57   val tfree_prefix : string
    58   val tvar_prefix : string
    59   val tptp_arity_clause : arityClause -> string
    60   val tptp_classrelClause : classrelClause -> string
    61   val tptp_of_typeLit : type_literal -> string
    62   val tptp_tfree_clause : string -> string
    63   val tptp_write_file: thm list -> string -> 
    64        ((thm * (string * int)) list * classrelClause list * arityClause list) -> string list
    65   val union_all : ''a list list -> ''a list
    66   val writeln_strs: TextIO.outstream -> TextIO.vector list -> unit
    67   val dfg_sign: bool -> string -> string
    68   val dfg_of_typeLit: type_literal -> string
    69   val get_tvar_strs: (typ_var * sort) list -> string list
    70   val gen_dfg_cls: int * string * string * string * string list -> string
    71   val add_foltype_funcs: fol_type * int Symtab.table -> int Symtab.table
    72   val add_arityClause_funcs: arityClause * int Symtab.table -> int Symtab.table
    73   val add_arityClause_preds: arityClause * int Symtab.table -> int Symtab.table
    74   val add_classrelClause_preds : classrelClause * int Symtab.table -> int Symtab.table
    75   val dfg_tfree_clause : string -> string
    76   val string_of_start: string -> string
    77   val string_of_descrip : string -> string
    78   val string_of_symbols: string -> string -> string
    79   val string_of_funcs: (string * int) list -> string
    80   val string_of_preds: (string * Int.int) list -> string
    81   val dfg_classrelClause: classrelClause -> string
    82   val dfg_arity_clause: arityClause -> string
    83 end;
    84 
    85 structure ResClause =
    86 struct
    87 
    88 val schematic_var_prefix = "V_";
    89 val fixed_var_prefix = "v_";
    90 
    91 val tvar_prefix = "T_";
    92 val tfree_prefix = "t_";
    93 
    94 val clause_prefix = "cls_"; 
    95 val arclause_prefix = "clsarity_" 
    96 val clrelclause_prefix = "clsrel_";
    97 
    98 val const_prefix = "c_";
    99 val tconst_prefix = "tc_"; 
   100 val class_prefix = "class_"; 
   101 
   102 fun union_all xss = foldl (op union) [] xss;
   103 
   104 (*Provide readable names for the more common symbolic functions*)
   105 val const_trans_table =
   106       Symtab.make [("op =", "equal"),
   107 	  	   ("Orderings.less_eq", "lessequals"),
   108 		   ("Orderings.less", "less"),
   109 		   ("op &", "and"),
   110 		   ("op |", "or"),
   111 		   ("HOL.plus", "plus"),
   112 		   ("HOL.minus", "minus"),
   113 		   ("HOL.times", "times"),
   114 		   ("Divides.div", "div"),
   115 		   ("HOL.divide", "divide"),
   116 		   ("op -->", "implies"),
   117 		   ("{}", "emptyset"),
   118 		   ("op :", "in"),
   119 		   ("op Un", "union"),
   120 		   ("op Int", "inter"),
   121 		   ("List.op @", "append"),
   122 		   ("ATP_Linkup.fequal", "fequal"),
   123 		   ("ATP_Linkup.COMBI", "COMBI"),
   124 		   ("ATP_Linkup.COMBK", "COMBK"),
   125 		   ("ATP_Linkup.COMBB", "COMBB"),
   126 		   ("ATP_Linkup.COMBC", "COMBC"),
   127 		   ("ATP_Linkup.COMBS", "COMBS"),
   128 		   ("ATP_Linkup.COMBB'", "COMBB_e"),
   129 		   ("ATP_Linkup.COMBC'", "COMBC_e"),
   130 		   ("ATP_Linkup.COMBS'", "COMBS_e")];
   131 
   132 val type_const_trans_table =
   133       Symtab.make [("*", "prod"),
   134 	  	   ("+", "sum"),
   135 		   ("~=>", "map")];
   136 
   137 (*Escaping of special characters.
   138   Alphanumeric characters are left unchanged.
   139   The character _ goes to __
   140   Characters in the range ASCII space to / go to _A to _P, respectively.
   141   Other printing characters go to _NNN where NNN is the decimal ASCII code.*)
   142 local
   143 
   144 val A_minus_space = Char.ord #"A" - Char.ord #" ";
   145 
   146 fun ascii_of_c c =
   147   if Char.isAlphaNum c then String.str c
   148   else if c = #"_" then "__"
   149   else if #" " <= c andalso c <= #"/" 
   150        then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
   151   else if Char.isPrint c then ("_" ^ Int.toString (Char.ord c))
   152   else ""
   153 
   154 in
   155 
   156 val ascii_of = String.translate ascii_of_c;
   157 
   158 end;
   159 
   160 (* convert a list of strings into one single string; surrounded by brackets *)
   161 fun paren_pack [] = ""   (*empty argument list*)
   162   | paren_pack strings = "(" ^ commas strings ^ ")";
   163 
   164 (*TSTP format uses (...) rather than the old [...]*)
   165 fun tptp_pack strings = "(" ^ space_implode " | " strings ^ ")";
   166 
   167 
   168 (*Remove the initial ' character from a type variable, if it is present*)
   169 fun trim_type_var s =
   170   if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
   171   else error ("trim_type: Malformed type variable encountered: " ^ s);
   172 
   173 fun ascii_of_indexname (v,0) = ascii_of v
   174   | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ Int.toString i;
   175 
   176 fun make_schematic_var v = schematic_var_prefix ^ (ascii_of_indexname v);
   177 fun make_fixed_var x = fixed_var_prefix ^ (ascii_of x);
   178 
   179 fun make_schematic_type_var (x,i) = 
   180       tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
   181 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
   182 
   183 fun lookup_const c =
   184     case Symtab.lookup const_trans_table c of
   185         SOME c' => c'
   186       | NONE => ascii_of c;
   187 
   188 fun lookup_type_const c = 
   189     case Symtab.lookup type_const_trans_table c of
   190         SOME c' => c'
   191       | NONE => ascii_of c;
   192 
   193 fun make_fixed_const "op =" = "equal"   (*MUST BE "equal" because it's built-in to ATPs*)
   194   | make_fixed_const c      = const_prefix ^ lookup_const c;
   195 
   196 fun make_fixed_type_const c = tconst_prefix ^ lookup_type_const c;
   197 
   198 fun make_type_class clas = class_prefix ^ ascii_of clas;
   199 
   200 
   201 (***** definitions and functions for FOL clauses, for conversion to TPTP or DFG format. *****)
   202 
   203 datatype kind = Axiom | Conjecture;
   204 fun name_of_kind Axiom = "axiom"
   205   | name_of_kind Conjecture = "negated_conjecture";
   206 
   207 type clause_id = int;
   208 type axiom_name = string;
   209 type polarity = bool;
   210 
   211 (**** Isabelle FOL clauses ****)
   212 
   213 datatype typ_var = FOLTVar of indexname | FOLTFree of string;
   214 
   215 (*FIXME: give the constructors more sensible names*)
   216 datatype fol_type = AtomV of string
   217 		  | AtomF of string
   218 		  | Comp of string * fol_type list;
   219 
   220 fun string_of_fol_type (AtomV x) = x
   221   | string_of_fol_type (AtomF x) = x
   222   | string_of_fol_type (Comp(tcon,tps)) = 
   223       tcon ^ (paren_pack (map string_of_fol_type tps));
   224       
   225 fun mk_fol_type ("Var",x,_) = AtomV(x)
   226   | mk_fol_type ("Fixed",x,_) = AtomF(x)
   227   | mk_fol_type ("Comp",con,args) = Comp(con,args)
   228 
   229 
   230 (*First string is the type class; the second is a TVar or TFfree*)
   231 datatype type_literal = LTVar of string * string | LTFree of string * string;
   232 
   233 datatype fol_term = UVar of string
   234                   | Fun of string * fol_type list * fol_term list;
   235 datatype predicate = Predicate of string * fol_type list * fol_term list;
   236 
   237 datatype literal = Literal of polarity * predicate;
   238 
   239 fun mk_typ_var_sort (TFree(a,s)) = (FOLTFree a,s)
   240   | mk_typ_var_sort (TVar(v,s)) = (FOLTVar v,s);
   241 
   242 
   243 (*A clause has first-order literals and other, type-related literals*)
   244 datatype clause = 
   245 	 Clause of {clause_id: clause_id,
   246 		    axiom_name: axiom_name,
   247 		    th: thm,
   248 		    kind: kind,
   249 		    literals: literal list,
   250 		    types_sorts: (typ_var * sort) list};
   251 
   252 fun get_axiomName (Clause cls) = #axiom_name cls;
   253 
   254 fun get_literals (Clause cls) = #literals cls;
   255 
   256 exception CLAUSE of string * term;
   257 
   258 fun isFalse (Literal (pol, Predicate(pname,_,[]))) =
   259       (pol andalso pname = "c_False") orelse
   260       (not pol andalso pname = "c_True")
   261   | isFalse _ = false;
   262 
   263 fun isTrue (Literal (pol, Predicate(pname,_,[]))) =
   264       (pol andalso pname = "c_True") orelse
   265       (not pol andalso pname = "c_False")
   266   | isTrue _ = false;
   267   
   268 fun isTaut (Clause {literals,...}) = exists isTrue literals;  
   269 
   270 
   271 (*Declarations of the current theory--to allow suppressing types.*)
   272 val const_typargs = ref (Library.K [] : (string*typ -> typ list));
   273 
   274 fun num_typargs(s,T) = length (!const_typargs (s,T));
   275 
   276 (*Initialize the type suppression mechanism with the current theory before
   277     producing any clauses!*)
   278 fun init thy = (const_typargs := Sign.const_typargs thy);
   279     
   280 
   281 (*Flatten a type to a fol_type while accumulating sort constraints on the TFrees and
   282   TVars it contains.*)    
   283 fun type_of (Type (a, Ts)) = 
   284       let val (folTyps, ts) = types_of Ts 
   285 	  val t = make_fixed_type_const a
   286       in (Comp(t,folTyps), ts) end
   287   | type_of (TFree (a,s)) = (AtomF(make_fixed_type_var a), [(FOLTFree a, s)]) 
   288   | type_of (TVar (v, s)) = (AtomV(make_schematic_type_var v), [(FOLTVar v, s)])
   289 and types_of Ts =
   290       let val (folTyps,ts) = ListPair.unzip (map type_of Ts)
   291       in (folTyps, union_all ts) end;
   292 
   293 
   294 fun const_types_of (c,T) = types_of (!const_typargs (c,T));
   295 
   296 (* Any variables created via the METAHYPS tactical should be treated as
   297    universal vars, although it is represented as "Free(...)" by Isabelle *)
   298 val isMeta = String.isPrefix "METAHYP1_"
   299 
   300 fun pred_name_type (Const(c,T)) = (make_fixed_const c, const_types_of (c,T))
   301   | pred_name_type (Free(x,T))  = 
   302       if isMeta x then raise CLAUSE("Predicate Not First Order 1", Free(x,T)) 
   303       else (make_fixed_var x, ([],[]))
   304   | pred_name_type (v as Var _) = raise CLAUSE("Predicate Not First Order 2", v)
   305   | pred_name_type t        = raise CLAUSE("Predicate input unexpected", t);
   306 
   307 fun fun_name_type (Const(c,T)) args = (make_fixed_const c, const_types_of (c,T))
   308   | fun_name_type (Free(x,T)) args  = 
   309        if isMeta x then raise CLAUSE("Function Not First Order", Free(x,T))
   310        else (make_fixed_var x, ([],[]))
   311   | fun_name_type f args = raise CLAUSE("Function Not First Order 1", f);
   312 
   313 (*Convert a term to a fol_term while accumulating sort constraints on the TFrees and
   314   TVars it contains.*)    
   315 fun term_of (Var(ind_nm,T)) = 
   316       let val (_,ts) = type_of T
   317       in (UVar(make_schematic_var ind_nm), ts) end
   318   | term_of (Free(x,T)) = 
   319       let val (_,ts) = type_of T
   320       in
   321 	  if isMeta x then (UVar(make_schematic_var(x,0)), ts)
   322 	  else (Fun(make_fixed_var x, [], []), ts)
   323       end
   324   | term_of app = 
   325       let val (f,args) = strip_comb app
   326 	  val (funName,(contys,ts1)) = fun_name_type f args
   327 	  val (args',ts2) = terms_of args
   328       in
   329 	  (Fun(funName,contys,args'), union_all (ts1::ts2))
   330       end
   331 and terms_of ts = ListPair.unzip (map term_of ts)
   332 
   333 (*Create a predicate value, again accumulating sort constraints.*)    
   334 fun pred_of (Const("op =", typ), args) =
   335       let val (args',ts) = terms_of args
   336       in
   337 	  (Predicate(make_fixed_const "op =", [], args'),
   338 	   union_all ts)
   339       end
   340   | pred_of (pred,args) = 
   341       let val (pname, (predType,ts1)) = pred_name_type pred
   342 	  val (args',ts2) = terms_of args
   343       in
   344 	  (Predicate(pname,predType,args'), union_all (ts1::ts2))
   345       end;
   346 
   347 (*Treatment of literals, possibly negated*)
   348 fun predicate_of ((Const("Not",_) $ P), polarity) = predicate_of (P, not polarity)
   349   | predicate_of (term,polarity) = (pred_of (strip_comb term), polarity);
   350 
   351 fun literals_of_term1 args (Const("Trueprop",_) $ P) = literals_of_term1 args P
   352   | literals_of_term1 args (Const("op |",_) $ P $ Q) = 
   353       literals_of_term1 (literals_of_term1 args P) Q
   354   | literals_of_term1 (lits, ts) P =
   355       let val ((pred, ts'), polarity) = predicate_of (P,true)
   356 	  val lits' = Literal(polarity,pred) :: lits
   357       in
   358 	  (lits', ts union ts')
   359       end;
   360 
   361 val literals_of_term = literals_of_term1 ([],[]);
   362 
   363 
   364 fun list_ord _ ([],[]) = EQUAL
   365   | list_ord _ ([],_) = LESS
   366   | list_ord _ (_,[]) = GREATER
   367   | list_ord ord (x::xs, y::ys) = 
   368       (case ord(x,y) of EQUAL => list_ord ord (xs,ys)
   369 	 	      | xy_ord => xy_ord);
   370 		     
   371 (*Make literals for sorted type variables.  FIXME: can it use map?*) 
   372 fun sorts_on_typs (_, [])   = ([]) 
   373   | sorts_on_typs (v, "HOL.type" :: s) =
   374       sorts_on_typs (v,s)                (*IGNORE sort "type"*)
   375   | sorts_on_typs ((FOLTVar indx), s::ss) =
   376       LTVar(make_type_class s, make_schematic_type_var indx) :: 
   377       sorts_on_typs ((FOLTVar indx), ss)
   378   | sorts_on_typs ((FOLTFree x), s::ss) =
   379       LTFree(make_type_class s, make_fixed_type_var x) :: 
   380       sorts_on_typs ((FOLTFree x), ss);
   381 
   382 
   383 fun pred_of_sort (LTVar (s,ty)) = (s,1)
   384 |   pred_of_sort (LTFree (s,ty)) = (s,1)
   385 
   386 (*Given a list of sorted type variables, return two separate lists.
   387   The first is for TVars, the second for TFrees.*)
   388 fun add_typs_aux [] = ([],[])
   389   | add_typs_aux ((FOLTVar indx,s)::tss) = 
   390       let val vs = sorts_on_typs (FOLTVar indx, s)
   391 	  val (vss,fss) = add_typs_aux tss
   392       in
   393 	  (vs union vss, fss)
   394       end
   395   | add_typs_aux ((FOLTFree x,s)::tss) =
   396       let val fs = sorts_on_typs (FOLTFree x, s)
   397 	  val (vss,fss) = add_typs_aux tss
   398       in
   399 	  (vss, fs union fss)
   400       end;
   401 
   402 
   403 (** make axiom and conjecture clauses. **)
   404 
   405 exception MAKE_CLAUSE;
   406 fun make_clause (clause_id, axiom_name, th, kind) =
   407   let val (lits,types_sorts) = literals_of_term (prop_of th)
   408   in if forall isFalse lits 
   409      then error "Problem too trivial for resolution (empty clause)"
   410      else Clause {clause_id = clause_id, axiom_name = axiom_name, th = th, 
   411                   kind = kind, literals = lits, types_sorts = types_sorts}
   412   end;		     
   413 
   414 fun get_tvar_strs [] = []
   415   | get_tvar_strs ((FOLTVar indx,s)::tss) = 
   416       insert (op =) (make_schematic_type_var indx) (get_tvar_strs tss)
   417   | get_tvar_strs((FOLTFree x,s)::tss) = get_tvar_strs tss
   418 
   419 (* check if a clause is first-order before making a conjecture clause*)
   420 fun make_conjecture_clause n th =
   421   if Meson.is_fol_term (prop_of th) then make_clause(n, "conjecture", th, Conjecture)
   422   else raise CLAUSE("Goal is not FOL", prop_of th);
   423   
   424 fun make_conjecture_clauses_aux _ [] = []
   425   | make_conjecture_clauses_aux n (t::ts) =
   426       make_conjecture_clause n t :: make_conjecture_clauses_aux (n+1) ts
   427 
   428 val make_conjecture_clauses = make_conjecture_clauses_aux 0
   429 
   430 (*before converting an axiom clause to "clause" format, check if it is FOL*)
   431 fun make_axiom_clause thm (ax_name,cls_id) =
   432   if Meson.is_fol_term (prop_of thm) 
   433   then (SOME (make_clause(cls_id, ax_name, thm, Axiom)) handle MAKE_CLAUSE => NONE)
   434   else (Output.debug ("Omitting " ^ ax_name ^ ": Axiom is not FOL"); NONE)
   435     
   436 fun make_axiom_clauses [] = []
   437   | make_axiom_clauses ((thm,(name,id))::thms) =
   438       case make_axiom_clause thm (name,id) of 
   439           SOME cls => if isTaut cls then make_axiom_clauses thms 
   440                       else (name,cls) :: make_axiom_clauses thms
   441         | NONE => make_axiom_clauses thms;
   442 
   443 (**** Isabelle arities ****)
   444 
   445 exception ARCLAUSE of string;
   446  
   447 type class = string; 
   448 type tcons = string; 
   449 
   450 datatype arLit = TConsLit of bool * (class * tcons * string list)
   451                | TVarLit of bool * (class * string);
   452  
   453 datatype arityClause =  
   454 	 ArityClause of {axiom_name: axiom_name,
   455 			 kind: kind,
   456 			 conclLit: arLit,
   457 			 premLits: arLit list};
   458 
   459 
   460 fun gen_TVars 0 = []
   461   | gen_TVars n = ("T_" ^ Int.toString n) :: gen_TVars (n-1);
   462 
   463 fun pack_sort(_,[])  = []
   464   | pack_sort(tvar, "HOL.type"::srt) = pack_sort(tvar, srt)   (*IGNORE sort "type"*)
   465   | pack_sort(tvar, cls::srt) =  (make_type_class cls, tvar) :: pack_sort(tvar, srt);
   466     
   467 fun make_TVarLit b (cls,str) = TVarLit(b, (cls,str));
   468 
   469 fun make_TConsLit b (cls,tcons,tvars) = 
   470       TConsLit(b, (make_type_class cls, make_fixed_type_const tcons, tvars));
   471 
   472 (*Arity of type constructor tcon :: (arg1,...,argN)res*)
   473 fun make_axiom_arity_clause (tcons, axiom_name, (res,args)) =
   474    let val tvars = gen_TVars (length args)
   475        val tvars_srts = ListPair.zip (tvars,args)
   476    in
   477       ArityClause {axiom_name = axiom_name, kind = Axiom, 
   478                    conclLit = make_TConsLit true (res,tcons,tvars), 
   479                    premLits = map (make_TVarLit false) (union_all(map pack_sort tvars_srts))}
   480    end;
   481 
   482 
   483 (**** Isabelle class relations ****)
   484 
   485 datatype classrelClause = 
   486 	 ClassrelClause of {axiom_name: axiom_name,
   487 			    subclass: class,
   488 			    superclass: class};
   489  
   490 (*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
   491 fun class_pairs thy [] supers = []
   492   | class_pairs thy subs supers =
   493       let val class_less = Sorts.class_less(Sign.classes_of thy)
   494 	  fun add_super sub (super,pairs) = 
   495 		if class_less (sub,super) then (sub,super)::pairs else pairs
   496 	  fun add_supers (sub,pairs) = foldl (add_super sub) pairs supers
   497       in  foldl add_supers [] subs  end;
   498 
   499 fun make_classrelClause (sub,super) =
   500   ClassrelClause {axiom_name = clrelclause_prefix ^ ascii_of sub ^ "_" ^ ascii_of super,
   501                   subclass = make_type_class sub, 
   502                   superclass = make_type_class super};
   503 
   504 fun make_classrel_clauses thy subs supers =
   505   map make_classrelClause (class_pairs thy subs supers);
   506 
   507 
   508 (** Isabelle arities **)
   509 
   510 fun arity_clause _ _ (tcons, []) = []
   511   | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
   512       arity_clause seen n (tcons,ars)
   513   | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
   514       if class mem_string seen then (*multiple arities for the same tycon, class pair*)
   515 	  make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class ^ "_" ^ Int.toString n, ar) :: 
   516 	  arity_clause seen (n+1) (tcons,ars)
   517       else
   518 	  make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class, ar) :: 
   519 	  arity_clause (class::seen) n (tcons,ars)
   520 
   521 fun multi_arity_clause [] = []
   522   | multi_arity_clause ((tcons,ars) :: tc_arlists) =
   523       arity_clause [] 1 (tcons, ars)  @  
   524       multi_arity_clause tc_arlists 
   525 
   526 (*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy.*)
   527 fun type_class_pairs thy tycons classes =
   528   let val alg = Sign.classes_of thy
   529       fun domain_sorts (tycon,class) = Sorts.mg_domain alg tycon [class]
   530       fun add_class tycon (class,pairs) = 
   531             (class, domain_sorts(tycon,class))::pairs 
   532             handle Sorts.CLASS_ERROR _ => pairs
   533       fun try_classes tycon = (tycon, foldl (add_class tycon) [] classes)
   534   in  map try_classes tycons  end;
   535 
   536 fun arity_clause_thy thy tycons classes =
   537   multi_arity_clause (type_class_pairs thy tycons classes);
   538 
   539 
   540 (**** Find occurrences of predicates in clauses ****)
   541 
   542 (*FIXME: multiple-arity checking doesn't work, as update_new is the wrong 
   543   function (it flags repeated declarations of a function, even with the same arity)*)
   544 
   545 fun update_many (tab, keypairs) = foldl (uncurry Symtab.update) tab keypairs;
   546 
   547 fun add_predicate_preds (Predicate(pname,tys,tms), preds) = 
   548   if pname = "equal" then preds (*equality is built-in and requires no declaration*)
   549   else Symtab.update (pname, length tys + length tms) preds
   550 
   551 fun add_literal_preds (Literal(_,pred), preds) = add_predicate_preds (pred,preds)
   552 
   553 fun add_type_sort_preds ((FOLTVar indx,s), preds) = 
   554       update_many (preds, map pred_of_sort (sorts_on_typs (FOLTVar indx, s)))
   555   | add_type_sort_preds ((FOLTFree x,s), preds) =
   556       update_many (preds, map pred_of_sort (sorts_on_typs (FOLTFree x, s)));
   557 
   558 fun add_clause_preds (Clause {literals, types_sorts, ...}, preds) =
   559   foldl add_literal_preds (foldl add_type_sort_preds preds types_sorts) literals
   560   handle Symtab.DUP a => raise ERROR ("predicate " ^ a ^ " has multiple arities")
   561 
   562 fun add_classrelClause_preds (ClassrelClause {subclass,superclass,...}, preds) =
   563   Symtab.update (subclass,1) (Symtab.update (superclass,1) preds);
   564 
   565 fun class_of_arityLit (TConsLit(_, (tclass, _, _))) = tclass
   566   | class_of_arityLit (TVarLit(_, (tclass, _))) = tclass;
   567 
   568 fun add_arityClause_preds (ArityClause {conclLit,premLits,...}, preds) =
   569   let val classes = map class_of_arityLit (conclLit::premLits)
   570       fun upd (class,preds) = Symtab.update (class,1) preds
   571   in  foldl upd preds classes  end;
   572 
   573 fun preds_of_clauses clauses clsrel_clauses arity_clauses = 
   574   Symtab.dest
   575     (foldl add_classrelClause_preds 
   576       (foldl add_arityClause_preds
   577         (foldl add_clause_preds Symtab.empty clauses)
   578         arity_clauses)
   579       clsrel_clauses)
   580 
   581 (*** Find occurrences of functions in clauses ***)
   582 
   583 fun add_foltype_funcs (AtomV _, funcs) = funcs
   584   | add_foltype_funcs (AtomF a, funcs) = Symtab.update (a,0) funcs
   585   | add_foltype_funcs (Comp(a,tys), funcs) = 
   586       foldl add_foltype_funcs (Symtab.update (a, length tys) funcs) tys;
   587 
   588 fun add_folterm_funcs (UVar _, funcs) = funcs
   589   | add_folterm_funcs (Fun(a,tys,tms), funcs) = 
   590       foldl add_foltype_funcs 
   591 	    (foldl add_folterm_funcs (Symtab.update (a, length tys + length tms) funcs) 
   592 	           tms) 
   593 	    tys
   594 
   595 fun add_predicate_funcs (Predicate(_,tys,tms), funcs) = 
   596     foldl add_foltype_funcs (foldl add_folterm_funcs funcs tms) tys;
   597 
   598 fun add_literal_funcs (Literal(_,pred), funcs) = add_predicate_funcs (pred,funcs)
   599 
   600 (*TFrees are recorded as constants*)
   601 fun add_type_sort_funcs ((FOLTVar _, _), funcs) = funcs
   602   | add_type_sort_funcs ((FOLTFree a, _), funcs) = 
   603       Symtab.update (make_fixed_type_var a, 0) funcs
   604 
   605 fun add_arityClause_funcs (ArityClause {conclLit,...}, funcs) =
   606   let val TConsLit(_, (_, tcons, tvars)) = conclLit
   607   in  Symtab.update (tcons, length tvars) funcs  end;
   608 
   609 fun add_clause_funcs (Clause {literals, types_sorts, ...}, funcs) =
   610   foldl add_literal_funcs (foldl add_type_sort_funcs funcs types_sorts)
   611        literals
   612   handle Symtab.DUP a => raise ERROR ("function " ^ a ^ " has multiple arities")
   613 
   614 fun funcs_of_clauses clauses arity_clauses = 
   615   Symtab.dest (foldl add_arityClause_funcs 
   616                      (foldl add_clause_funcs Symtab.empty clauses)
   617                      arity_clauses)
   618 
   619 
   620 (**** String-oriented operations ****)
   621 
   622 fun string_of_term (UVar x) = x
   623   | string_of_term (Fun (name,typs,terms)) = 
   624       name ^ (paren_pack (map string_of_term terms @ map string_of_fol_type typs));
   625 
   626 fun string_of_pair [t1,t2] = (string_of_term t1, string_of_term t2)
   627   | string_of_pair _ = raise ERROR ("equality predicate requires two arguments");
   628 
   629 fun string_of_equality ts =
   630   let val (s1,s2) = string_of_pair ts
   631   in "equal(" ^ s1 ^ "," ^ s2 ^ ")" end;
   632 
   633 (* before output the string of the predicate, check if the predicate corresponds to an equality or not. *)
   634 fun string_of_predicate (Predicate("equal",_,ts)) = string_of_equality ts
   635   | string_of_predicate (Predicate(name,typs,ts)) = 
   636       name ^ (paren_pack (map string_of_term ts @ map string_of_fol_type typs));
   637 
   638 fun string_of_clausename (cls_id,ax_name) = 
   639     clause_prefix ^ ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   640 
   641 fun clause_name_of (cls_id,ax_name) = 
   642     ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   643 
   644 fun string_of_type_clsname (cls_id,ax_name,idx) = 
   645     string_of_clausename (cls_id,ax_name) ^ "_tcs" ^ (Int.toString idx);
   646 
   647 (*Write a list of strings to a file*)
   648 fun writeln_strs os = List.app (fn s => TextIO.output (os,s));
   649 
   650     
   651 (**** Producing DFG files ****)
   652 
   653 (*Attach sign in DFG syntax: false means negate.*)
   654 fun dfg_sign true s = s
   655   | dfg_sign false s = "not(" ^ s ^ ")"  
   656 
   657 fun dfg_literal (Literal(pol,pred)) = dfg_sign pol (string_of_predicate pred)
   658 
   659 fun dfg_of_typeLit (LTVar (s,ty)) = "not(" ^ s ^ "(" ^ ty ^ "))"
   660   | dfg_of_typeLit (LTFree (s,ty)) = s ^ "(" ^ ty ^ ")";
   661  
   662 (*Enclose the clause body by quantifiers, if necessary*)
   663 fun dfg_forall [] body = body  
   664   | dfg_forall vars body = "forall([" ^ commas vars ^ "],\n" ^ body ^ ")"
   665 
   666 fun gen_dfg_cls (cls_id, ax_name, knd, lits, vars) = 
   667     "clause( %(" ^ knd ^ ")\n" ^ 
   668     dfg_forall vars ("or(" ^ lits ^ ")") ^ ",\n" ^ 
   669     string_of_clausename (cls_id,ax_name) ^  ").\n\n";
   670 
   671 fun dfg_clause_aux (Clause{literals, types_sorts, ...}) = 
   672   let val (tvar_lits,tfree_lits) = add_typs_aux types_sorts
   673   in  (map dfg_of_typeLit tvar_lits @ map dfg_literal literals, 
   674        map dfg_of_typeLit tfree_lits)
   675   end; 
   676 
   677 fun dfg_folterms (Literal(pol,pred)) = 
   678   let val Predicate (_, _, folterms) = pred
   679   in  folterms  end
   680 
   681 fun get_uvars (UVar a) = [a] 
   682   | get_uvars (Fun (_,typ,tlist)) = union_all(map get_uvars tlist)
   683 
   684 fun dfg_vars (Clause {literals,...}) =
   685   union_all (map get_uvars (List.concat (map dfg_folterms literals)))
   686 
   687 fun clause2dfg (cls as Clause{axiom_name,clause_id,kind,types_sorts,...}) =
   688     let val (lits,tfree_lits) = dfg_clause_aux cls 
   689             (*"lits" includes the typing assumptions (TVars)*)
   690         val vars = dfg_vars cls
   691         val tvars = get_tvar_strs types_sorts
   692 	val cls_str = gen_dfg_cls(clause_id, axiom_name, name_of_kind kind, 
   693 	                           commas lits, tvars@vars) 
   694     in (cls_str, tfree_lits) end;
   695 
   696 fun string_of_arity (name, num) =  "(" ^ name ^ "," ^ Int.toString num ^ ")"
   697 
   698 fun string_of_preds [] = ""
   699   | string_of_preds preds = "predicates[" ^ commas(map string_of_arity preds) ^ "].\n";
   700 
   701 fun string_of_funcs [] = ""
   702   | string_of_funcs funcs = "functions[" ^ commas(map string_of_arity funcs) ^ "].\n" ;
   703 
   704 fun string_of_symbols predstr funcstr = 
   705   "list_of_symbols.\n" ^ predstr  ^ funcstr  ^ "end_of_list.\n\n";
   706 
   707 fun string_of_start name = "begin_problem(" ^ name ^ ").\n\n";
   708 
   709 fun string_of_descrip name = 
   710   "list_of_descriptions.\nname({*" ^ name ^ 
   711   "*}).\nauthor({*Isabelle*}).\nstatus(unknown).\ndescription({*auto-generated*}).\nend_of_list.\n\n"
   712 
   713 fun dfg_tfree_clause tfree_lit =
   714   "clause( %(negated_conjecture)\n" ^ "or( " ^ tfree_lit ^ "),\n" ^ "tfree_tcs" ^ ").\n\n"
   715 
   716 fun dfg_of_arLit (TConsLit(pol,(c,t,args))) =
   717       dfg_sign pol (c ^ "(" ^ t ^ paren_pack args ^ ")")
   718   | dfg_of_arLit (TVarLit(pol,(c,str))) =
   719       dfg_sign pol (c ^ "(" ^ str ^ ")")
   720     
   721 fun dfg_classrelLits sub sup =  "not(" ^ sub ^ "(T)), " ^ sup ^ "(T)";
   722 
   723 fun dfg_classrelClause (ClassrelClause {axiom_name,subclass,superclass,...}) =
   724   "clause(forall([T],\nor( " ^ dfg_classrelLits subclass superclass ^ ")),\n" ^
   725   axiom_name ^ ").\n\n";
   726       
   727 fun string_of_ar axiom_name = arclause_prefix ^ ascii_of axiom_name;
   728 
   729 fun dfg_arity_clause (ArityClause{axiom_name,kind,conclLit,premLits,...}) = 
   730   let val TConsLit(_, (_,_,tvars)) = conclLit
   731       val lits = map dfg_of_arLit (conclLit :: premLits)
   732   in
   733       "clause( %(" ^ name_of_kind kind ^ ")\n" ^ 
   734       dfg_forall tvars ("or( " ^ commas lits ^ ")") ^ ",\n" ^
   735       string_of_ar axiom_name ^ ").\n\n"
   736   end;
   737 
   738 (* write out a subgoal in DFG format to the file "xxxx_N"*)
   739 fun dfg_write_file thms filename (ax_tuples,classrel_clauses,arity_clauses) = 
   740   let 
   741     val _ = Output.debug ("Preparing to write the DFG file " ^ filename)
   742     val conjectures = make_conjecture_clauses thms
   743     val (clnames,axclauses) = ListPair.unzip (make_axiom_clauses ax_tuples)
   744     val (dfg_clss, tfree_litss) = ListPair.unzip (map clause2dfg conjectures)
   745     val clss = conjectures @ axclauses
   746     val funcs = funcs_of_clauses clss arity_clauses
   747     and preds = preds_of_clauses clss classrel_clauses arity_clauses
   748     and probname = Path.pack (Path.base (Path.unpack filename))
   749     val (axstrs, _) = ListPair.unzip (map clause2dfg axclauses)
   750     val tfree_clss = map dfg_tfree_clause (union_all tfree_litss) 
   751     val out = TextIO.openOut filename
   752   in
   753     TextIO.output (out, string_of_start probname); 
   754     TextIO.output (out, string_of_descrip probname); 
   755     TextIO.output (out, string_of_symbols (string_of_funcs funcs) (string_of_preds preds)); 
   756     TextIO.output (out, "list_of_clauses(axioms,cnf).\n");
   757     writeln_strs out axstrs;
   758     List.app (curry TextIO.output out o dfg_classrelClause) classrel_clauses;
   759     List.app (curry TextIO.output out o dfg_arity_clause) arity_clauses;
   760     TextIO.output (out, "end_of_list.\n\nlist_of_clauses(conjectures,cnf).\n");
   761     writeln_strs out tfree_clss;
   762     writeln_strs out dfg_clss;
   763     TextIO.output (out, "end_of_list.\n\nend_problem.\n");
   764     TextIO.closeOut out;
   765     clnames
   766   end;
   767 
   768 
   769 (**** Produce TPTP files ****)
   770 
   771 (*Attach sign in TPTP syntax: false means negate.*)
   772 fun tptp_sign true s = s
   773   | tptp_sign false s = "~ " ^ s
   774 
   775 fun tptp_of_equality pol ts =
   776   let val (s1,s2) = string_of_pair ts
   777       val eqop = if pol then " = " else " != "
   778   in  s1 ^ eqop ^ s2  end;
   779 
   780 fun tptp_literal (Literal(pol,Predicate("equal",_,ts))) = tptp_of_equality pol ts
   781   | tptp_literal (Literal(pol,pred)) = tptp_sign pol (string_of_predicate pred);
   782 
   783 fun tptp_of_typeLit (LTVar (s,ty))  = tptp_sign false (s ^ "(" ^ ty ^ ")")
   784   | tptp_of_typeLit (LTFree (s,ty)) = tptp_sign true  (s ^ "(" ^ ty ^ ")");
   785  
   786 fun gen_tptp_cls (cls_id,ax_name,knd,lits) = 
   787     "cnf(" ^ string_of_clausename (cls_id,ax_name) ^ "," ^ 
   788     name_of_kind knd ^ "," ^ tptp_pack lits ^ ").\n";
   789 
   790 fun tptp_type_lits (Clause {literals, types_sorts, ...}) = 
   791   let val (tvar_lits,tfree_lits) = add_typs_aux types_sorts
   792   in
   793       (map tptp_of_typeLit tvar_lits @ map tptp_literal literals,
   794        map tptp_of_typeLit tfree_lits)
   795   end; 
   796 
   797 fun clause2tptp (cls as Clause {clause_id, axiom_name, kind, ...}) =
   798     let val (lits,tfree_lits) = tptp_type_lits cls 
   799             (*"lits" includes the typing assumptions (TVars)*)
   800 	val cls_str = gen_tptp_cls(clause_id, axiom_name, kind, lits) 
   801     in
   802 	(cls_str,tfree_lits) 
   803     end;
   804 
   805 fun tptp_tfree_clause tfree_lit =
   806     "cnf(" ^ "tfree_tcs," ^ "negated_conjecture" ^ "," ^ tptp_pack[tfree_lit] ^ ").\n";
   807     
   808 fun tptp_of_arLit (TConsLit(b,(c,t,args))) =
   809       tptp_sign b (c ^ "(" ^ t ^ paren_pack args ^ ")")
   810   | tptp_of_arLit (TVarLit(b,(c,str))) =
   811       tptp_sign b (c ^ "(" ^ str ^ ")")
   812     
   813 fun tptp_arity_clause (ArityClause{axiom_name,kind,conclLit,premLits,...}) = 
   814   "cnf(" ^ string_of_ar axiom_name ^ "," ^ name_of_kind kind ^ "," ^ 
   815   tptp_pack (map tptp_of_arLit (conclLit :: premLits)) ^ ").\n";
   816 
   817 fun tptp_classrelLits sub sup = 
   818   let val tvar = "(T)"
   819   in  tptp_pack [tptp_sign false (sub^tvar), tptp_sign true (sup^tvar)]  end;
   820 
   821 fun tptp_classrelClause (ClassrelClause {axiom_name,subclass,superclass,...}) =
   822   "cnf(" ^ axiom_name ^ ",axiom," ^ tptp_classrelLits subclass superclass ^ ").\n" 
   823 
   824 (* write out a subgoal as tptp clauses to the file "xxxx_N"*)
   825 fun tptp_write_file thms filename (ax_tuples,classrel_clauses,arity_clauses) =
   826   let
   827     val _ = Output.debug ("Preparing to write the TPTP file " ^ filename)
   828     val clss = make_conjecture_clauses thms
   829     val (clnames,axclauses) = ListPair.unzip (make_axiom_clauses ax_tuples)
   830     val (tptp_clss,tfree_litss) = ListPair.unzip (map clause2tptp clss)
   831     val tfree_clss = map tptp_tfree_clause (foldl (op union_string) [] tfree_litss)
   832     val out = TextIO.openOut filename
   833   in
   834     List.app (curry TextIO.output out o #1 o clause2tptp) axclauses;
   835     writeln_strs out tfree_clss;
   836     writeln_strs out tptp_clss;
   837     List.app (curry TextIO.output out o tptp_classrelClause) classrel_clauses;
   838     List.app (curry TextIO.output out o tptp_arity_clause) arity_clauses;
   839     TextIO.closeOut out;
   840     clnames
   841   end;
   842 
   843 end;