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