src/HOL/Tools/res_clause.ML
author paulson
Tue Dec 12 16:20:57 2006 +0100 (2006-12-12)
changeset 21790 9d2761d09d91
parent 21564 519ee3129ee1
child 21813 06a06f6d3166
permissions -rw-r--r--
Removal of the "keep_types" flag: we always keep types!
     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 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 tptp_arity_clause : arityClause -> string
    59   val tptp_classrelClause : classrelClause -> string
    60   val tptp_of_typeLit : type_literal -> string
    61   val tptp_tfree_clause : string -> string
    62   val tptp_write_file: thm list -> string -> 
    63        ((thm * (string * int)) list * classrelClause list * arityClause list) -> string list
    64   val tvar_prefix : string
    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 * fol_type
   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 
   308 (* For typed equality *)
   309 (* here "arg_typ" is the type of "="'s argument's type, not the type of the equality *)
   310 (* Find type of equality arg *)
   311 fun eq_arg_type (Type("fun",[T,_])) = 
   312     let val (folT,_) = type_of T;
   313     in  folT  end;
   314 
   315 fun fun_name_type (Const(c,T)) args = (make_fixed_const c, const_types_of (c,T))
   316   | fun_name_type (Free(x,T)) args  = 
   317        if isMeta x then raise CLAUSE("Function Not First Order", Free(x,T))
   318        else (make_fixed_var x, ([],[]))
   319   | fun_name_type f args = raise CLAUSE("Function Not First Order 1", f);
   320 
   321 (*Convert a term to a fol_term while accumulating sort constraints on the TFrees and
   322   TVars it contains.*)    
   323 fun term_of (Var(ind_nm,T)) = 
   324       let val (folType,ts) = type_of T
   325       in (UVar(make_schematic_var ind_nm, folType), ts) end
   326   | term_of (Free(x,T)) = 
   327       let val (folType, ts) = type_of T
   328       in
   329 	  if isMeta x then (UVar(make_schematic_var(x,0),folType), ts)
   330 	  else (Fun(make_fixed_var x, [], []), ts)  (*Frees don't need types!*)
   331       end
   332   | term_of app = 
   333       let val (f,args) = strip_comb app
   334 	  val (funName,(contys,ts1)) = fun_name_type f args
   335 	  val (args',ts2) = terms_of args
   336       in
   337 	  (Fun(funName,contys,args'), union_all (ts1::ts2))
   338       end
   339 and terms_of ts = ListPair.unzip (map term_of ts)
   340 
   341 (*Create a predicate value, again accumulating sort constraints.*)    
   342 fun pred_of (Const("op =", typ), args) =
   343       let val arg_typ = eq_arg_type typ 
   344 	  val (args',ts) = terms_of args
   345 	  val equal_name = make_fixed_const "op ="
   346       in
   347 	  (Predicate(equal_name,[arg_typ],args'),
   348 	   union_all ts)
   349       end
   350   | pred_of (pred,args) = 
   351       let val (pname, (predType,ts1)) = pred_name_type pred
   352 	  val (args',ts2) = terms_of args
   353       in
   354 	  (Predicate(pname,predType,args'), union_all (ts1::ts2))
   355       end;
   356 
   357 (*Treatment of literals, possibly negated*)
   358 fun predicate_of ((Const("Not",_) $ P), polarity) = predicate_of (P, not polarity)
   359   | predicate_of (term,polarity) = (pred_of (strip_comb term), polarity);
   360 
   361 fun literals_of_term1 args (Const("Trueprop",_) $ P) = literals_of_term1 args P
   362   | literals_of_term1 args (Const("op |",_) $ P $ Q) = 
   363       literals_of_term1 (literals_of_term1 args P) Q
   364   | literals_of_term1 (lits, ts) P =
   365       let val ((pred, ts'), polarity) = predicate_of (P,true)
   366 	  val lits' = Literal(polarity,pred) :: lits
   367       in
   368 	  (lits', ts union ts')
   369       end;
   370 
   371 val literals_of_term = literals_of_term1 ([],[]);
   372 
   373 
   374 fun list_ord _ ([],[]) = EQUAL
   375   | list_ord _ ([],_) = LESS
   376   | list_ord _ (_,[]) = GREATER
   377   | list_ord ord (x::xs, y::ys) = 
   378       (case ord(x,y) of EQUAL => list_ord ord (xs,ys)
   379 	 	      | xy_ord => xy_ord);
   380 		     
   381 (*Make literals for sorted type variables.  FIXME: can it use map?*) 
   382 fun sorts_on_typs (_, [])   = ([]) 
   383   | sorts_on_typs (v, "HOL.type" :: s) =
   384       sorts_on_typs (v,s)                (*IGNORE sort "type"*)
   385   | sorts_on_typs ((FOLTVar indx), s::ss) =
   386       LTVar(make_type_class s, make_schematic_type_var indx) :: 
   387       sorts_on_typs ((FOLTVar indx), ss)
   388   | sorts_on_typs ((FOLTFree x), s::ss) =
   389       LTFree(make_type_class s, make_fixed_type_var x) :: 
   390       sorts_on_typs ((FOLTFree x), ss);
   391 
   392 
   393 fun pred_of_sort (LTVar (s,ty)) = (s,1)
   394 |   pred_of_sort (LTFree (s,ty)) = (s,1)
   395 
   396 (*Given a list of sorted type variables, return two separate lists.
   397   The first is for TVars, the second for TFrees.*)
   398 fun add_typs_aux [] = ([],[])
   399   | add_typs_aux ((FOLTVar indx,s)::tss) = 
   400       let val vs = sorts_on_typs (FOLTVar indx, s)
   401 	  val (vss,fss) = add_typs_aux tss
   402       in
   403 	  (vs union vss, fss)
   404       end
   405   | add_typs_aux ((FOLTFree x,s)::tss) =
   406       let val fs = sorts_on_typs (FOLTFree x, s)
   407 	  val (vss,fss) = add_typs_aux tss
   408       in
   409 	  (vss, fs union fss)
   410       end;
   411 
   412 
   413 (** make axiom and conjecture clauses. **)
   414 
   415 exception MAKE_CLAUSE;
   416 fun make_clause (clause_id, axiom_name, th, kind) =
   417   let val (lits,types_sorts) = literals_of_term (prop_of th)
   418   in if forall isFalse lits 
   419      then error "Problem too trivial for resolution (empty clause)"
   420      else Clause {clause_id = clause_id, axiom_name = axiom_name, th = th, 
   421                   kind = kind, literals = lits, types_sorts = types_sorts}
   422   end;		     
   423 
   424 fun get_tvar_strs [] = []
   425   | get_tvar_strs ((FOLTVar indx,s)::tss) = 
   426       insert (op =) (make_schematic_type_var indx) (get_tvar_strs tss)
   427   | get_tvar_strs((FOLTFree x,s)::tss) = get_tvar_strs tss
   428 
   429 (* check if a clause is first-order before making a conjecture clause*)
   430 fun make_conjecture_clause n th =
   431   if Meson.is_fol_term (prop_of th) then make_clause(n, "conjecture", th, Conjecture)
   432   else raise CLAUSE("Goal is not FOL", prop_of th);
   433   
   434 fun make_conjecture_clauses_aux _ [] = []
   435   | make_conjecture_clauses_aux n (t::ts) =
   436       make_conjecture_clause n t :: make_conjecture_clauses_aux (n+1) ts
   437 
   438 val make_conjecture_clauses = make_conjecture_clauses_aux 0
   439 
   440 (*before converting an axiom clause to "clause" format, check if it is FOL*)
   441 fun make_axiom_clause thm (ax_name,cls_id) =
   442   if Meson.is_fol_term (prop_of thm) 
   443   then (SOME (make_clause(cls_id, ax_name, thm, Axiom)) handle MAKE_CLAUSE => NONE)
   444   else (Output.debug ("Omitting " ^ ax_name ^ ": Axiom is not FOL"); NONE)
   445     
   446 fun make_axiom_clauses [] = []
   447   | make_axiom_clauses ((thm,(name,id))::thms) =
   448       case make_axiom_clause thm (name,id) of 
   449           SOME cls => if isTaut cls then make_axiom_clauses thms 
   450                       else (name,cls) :: make_axiom_clauses thms
   451         | NONE => make_axiom_clauses thms;
   452 
   453 (**** Isabelle arities ****)
   454 
   455 exception ARCLAUSE of string;
   456  
   457 type class = string; 
   458 type tcons = string; 
   459 
   460 datatype arLit = TConsLit of bool * (class * tcons * string list)
   461                | TVarLit of bool * (class * string);
   462  
   463 datatype arityClause =  
   464 	 ArityClause of {axiom_name: axiom_name,
   465 			 kind: kind,
   466 			 conclLit: arLit,
   467 			 premLits: arLit list};
   468 
   469 
   470 fun gen_TVars 0 = []
   471   | gen_TVars n = ("T_" ^ Int.toString n) :: gen_TVars (n-1);
   472 
   473 fun pack_sort(_,[])  = []
   474   | pack_sort(tvar, "HOL.type"::srt) = pack_sort(tvar, srt)   (*IGNORE sort "type"*)
   475   | pack_sort(tvar, cls::srt) =  (make_type_class cls, tvar) :: pack_sort(tvar, srt);
   476     
   477 fun make_TVarLit b (cls,str) = TVarLit(b, (cls,str));
   478 
   479 fun make_TConsLit b (cls,tcons,tvars) = 
   480       TConsLit(b, (make_type_class cls, make_fixed_type_const tcons, tvars));
   481 
   482 (*Arity of type constructor tcon :: (arg1,...,argN)res*)
   483 fun make_axiom_arity_clause (tcons, axiom_name, (res,args)) =
   484    let val tvars = gen_TVars (length args)
   485        val tvars_srts = ListPair.zip (tvars,args)
   486    in
   487       ArityClause {axiom_name = axiom_name, kind = Axiom, 
   488                    conclLit = make_TConsLit true (res,tcons,tvars), 
   489                    premLits = map (make_TVarLit false) (union_all(map pack_sort tvars_srts))}
   490    end;
   491 
   492 
   493 (**** Isabelle class relations ****)
   494 
   495 datatype classrelClause = 
   496 	 ClassrelClause of {axiom_name: axiom_name,
   497 			    subclass: class,
   498 			    superclass: class};
   499  
   500 (*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
   501 fun class_pairs thy [] supers = []
   502   | class_pairs thy subs supers =
   503       let val class_less = Sorts.class_less(Sign.classes_of thy)
   504 	  fun add_super sub (super,pairs) = 
   505 		if class_less (sub,super) then (sub,super)::pairs else pairs
   506 	  fun add_supers (sub,pairs) = foldl (add_super sub) pairs supers
   507       in  foldl add_supers [] subs  end;
   508 
   509 fun make_classrelClause (sub,super) =
   510   ClassrelClause {axiom_name = clrelclause_prefix ^ ascii_of sub ^ "_" ^ ascii_of super,
   511                   subclass = make_type_class sub, 
   512                   superclass = make_type_class super};
   513 
   514 fun make_classrel_clauses thy subs supers =
   515   map make_classrelClause (class_pairs thy subs supers);
   516 
   517 
   518 (** Isabelle arities **)
   519 
   520 fun arity_clause _ _ (tcons, []) = []
   521   | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
   522       arity_clause seen n (tcons,ars)
   523   | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
   524       if class mem_string seen then (*multiple arities for the same tycon, class pair*)
   525 	  make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class ^ "_" ^ Int.toString n, ar) :: 
   526 	  arity_clause seen (n+1) (tcons,ars)
   527       else
   528 	  make_axiom_arity_clause (tcons, lookup_type_const tcons ^ "_" ^ class, ar) :: 
   529 	  arity_clause (class::seen) n (tcons,ars)
   530 
   531 fun multi_arity_clause [] = []
   532   | multi_arity_clause ((tcons,ars) :: tc_arlists) =
   533       arity_clause [] 1 (tcons, ars)  @  
   534       multi_arity_clause tc_arlists 
   535 
   536 (*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy.*)
   537 fun type_class_pairs thy tycons classes =
   538   let val alg = Sign.classes_of thy
   539       fun domain_sorts (tycon,class) = Sorts.mg_domain alg tycon [class]
   540       fun add_class tycon (class,pairs) = 
   541             (class, domain_sorts(tycon,class))::pairs 
   542             handle Sorts.CLASS_ERROR _ => pairs
   543       fun try_classes tycon = (tycon, foldl (add_class tycon) [] classes)
   544   in  map try_classes tycons  end;
   545 
   546 fun arity_clause_thy thy tycons classes =
   547   multi_arity_clause (type_class_pairs thy tycons classes);
   548 
   549 
   550 (**** Find occurrences of predicates in clauses ****)
   551 
   552 (*FIXME: multiple-arity checking doesn't work, as update_new is the wrong 
   553   function (it flags repeated declarations of a function, even with the same arity)*)
   554 
   555 fun update_many (tab, keypairs) = foldl (uncurry Symtab.update) tab keypairs;
   556 
   557 fun add_predicate_preds (Predicate(pname,tys,tms), preds) = 
   558   if pname = "equal" then preds (*equality is built-in and requires no declaration*)
   559   else Symtab.update (pname, length tys + length tms) preds
   560 
   561 fun add_literal_preds (Literal(_,pred), preds) = add_predicate_preds (pred,preds)
   562 
   563 fun add_type_sort_preds ((FOLTVar indx,s), preds) = 
   564       update_many (preds, map pred_of_sort (sorts_on_typs (FOLTVar indx, s)))
   565   | add_type_sort_preds ((FOLTFree x,s), preds) =
   566       update_many (preds, map pred_of_sort (sorts_on_typs (FOLTFree x, s)));
   567 
   568 fun add_clause_preds (Clause {literals, types_sorts, ...}, preds) =
   569   foldl add_literal_preds (foldl add_type_sort_preds preds types_sorts) literals
   570   handle Symtab.DUP a => raise ERROR ("predicate " ^ a ^ " has multiple arities")
   571 
   572 fun add_classrelClause_preds (ClassrelClause {subclass,superclass,...}, preds) =
   573   Symtab.update (subclass,1) (Symtab.update (superclass,1) preds);
   574 
   575 fun class_of_arityLit (TConsLit(_, (tclass, _, _))) = tclass
   576   | class_of_arityLit (TVarLit(_, (tclass, _))) = tclass;
   577 
   578 fun add_arityClause_preds (ArityClause {conclLit,premLits,...}, preds) =
   579   let val classes = map class_of_arityLit (conclLit::premLits)
   580       fun upd (class,preds) = Symtab.update (class,1) preds
   581   in  foldl upd preds classes  end;
   582 
   583 fun preds_of_clauses clauses clsrel_clauses arity_clauses = 
   584   Symtab.dest
   585     (foldl add_classrelClause_preds 
   586       (foldl add_arityClause_preds
   587         (foldl add_clause_preds Symtab.empty clauses)
   588         arity_clauses)
   589       clsrel_clauses)
   590 
   591 (*** Find occurrences of functions in clauses ***)
   592 
   593 fun add_foltype_funcs (AtomV _, funcs) = funcs
   594   | add_foltype_funcs (AtomF a, funcs) = Symtab.update (a,0) funcs
   595   | add_foltype_funcs (Comp(a,tys), funcs) = 
   596       foldl add_foltype_funcs (Symtab.update (a, length tys) funcs) tys;
   597 
   598 fun add_folterm_funcs (UVar(_,ty), funcs) = add_foltype_funcs (ty, funcs)
   599   | add_folterm_funcs (Fun(a,tys,tms), funcs) = 
   600       foldl add_foltype_funcs 
   601 	    (foldl add_folterm_funcs (Symtab.update (a, length tys + length tms) funcs) 
   602 	           tms) 
   603 	    tys
   604 
   605 fun add_predicate_funcs (Predicate(_,tys,tms), funcs) = 
   606     foldl add_foltype_funcs (foldl add_folterm_funcs funcs tms) tys;
   607 
   608 fun add_literal_funcs (Literal(_,pred), funcs) = add_predicate_funcs (pred,funcs)
   609 
   610 (*TFrees are recorded as constants*)
   611 fun add_type_sort_funcs ((FOLTVar _, _), funcs) = funcs
   612   | add_type_sort_funcs ((FOLTFree a, _), funcs) = 
   613       Symtab.update (make_fixed_type_var a, 0) funcs
   614 
   615 fun add_arityClause_funcs (ArityClause {conclLit,...}, funcs) =
   616   let val TConsLit(_, (_, tcons, tvars)) = conclLit
   617   in  Symtab.update (tcons, length tvars) funcs  end;
   618 
   619 fun add_clause_funcs (Clause {literals, types_sorts, ...}, funcs) =
   620   foldl add_literal_funcs (foldl add_type_sort_funcs funcs types_sorts)
   621        literals
   622   handle Symtab.DUP a => raise ERROR ("function " ^ a ^ " has multiple arities")
   623 
   624 fun funcs_of_clauses clauses arity_clauses = 
   625   Symtab.dest (foldl add_arityClause_funcs 
   626                      (foldl add_clause_funcs Symtab.empty clauses)
   627                      arity_clauses)
   628 
   629 
   630 (**** String-oriented operations ****)
   631 
   632 fun string_of_term (UVar(x,_)) = x
   633   | string_of_term (Fun (name,typs,terms)) = 
   634       name ^ (paren_pack (map string_of_term terms @ map string_of_fol_type typs));
   635 
   636 fun string_of_pair [t1,t2] = (string_of_term t1, string_of_term t2)
   637   | string_of_pair _ = raise ERROR ("equality predicate requires two arguments");
   638 
   639 fun string_of_equality ts =
   640   let val (s1,s2) = string_of_pair ts
   641   in "equal(" ^ s1 ^ "," ^ s2 ^ ")" end;
   642 
   643 (* before output the string of the predicate, check if the predicate corresponds to an equality or not. *)
   644 fun string_of_predicate (Predicate("equal",_,ts)) = string_of_equality ts
   645   | string_of_predicate (Predicate(name,typs,ts)) = 
   646       name ^ (paren_pack (map string_of_term ts @ map string_of_fol_type typs));
   647 
   648 fun string_of_clausename (cls_id,ax_name) = 
   649     clause_prefix ^ ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   650 
   651 fun clause_name_of (cls_id,ax_name) = 
   652     ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   653 
   654 fun string_of_type_clsname (cls_id,ax_name,idx) = 
   655     string_of_clausename (cls_id,ax_name) ^ "_tcs" ^ (Int.toString idx);
   656 
   657 (*Write a list of strings to a file*)
   658 fun writeln_strs os = List.app (fn s => TextIO.output (os,s));
   659 
   660     
   661 (**** Producing DFG files ****)
   662 
   663 (*Attach sign in DFG syntax: false means negate.*)
   664 fun dfg_sign true s = s
   665   | dfg_sign false s = "not(" ^ s ^ ")"  
   666 
   667 fun dfg_literal (Literal(pol,pred)) = dfg_sign pol (string_of_predicate pred)
   668 
   669 fun dfg_of_typeLit (LTVar (s,ty)) = "not(" ^ s ^ "(" ^ ty ^ "))"
   670   | dfg_of_typeLit (LTFree (s,ty)) = s ^ "(" ^ ty ^ ")";
   671  
   672 (*Enclose the clause body by quantifiers, if necessary*)
   673 fun dfg_forall [] body = body  
   674   | dfg_forall vars body = "forall([" ^ commas vars ^ "],\n" ^ body ^ ")"
   675 
   676 fun gen_dfg_cls (cls_id, ax_name, knd, lits, vars) = 
   677     "clause( %(" ^ knd ^ ")\n" ^ 
   678     dfg_forall vars ("or(" ^ lits ^ ")") ^ ",\n" ^ 
   679     string_of_clausename (cls_id,ax_name) ^  ").\n\n";
   680 
   681 fun dfg_clause_aux (Clause{literals, types_sorts, ...}) = 
   682   let val (tvar_lits,tfree_lits) = add_typs_aux types_sorts
   683   in  (map dfg_of_typeLit tvar_lits @ map dfg_literal literals, 
   684        map dfg_of_typeLit tfree_lits)
   685   end; 
   686 
   687 fun dfg_folterms (Literal(pol,pred)) = 
   688   let val Predicate (_, _, folterms) = pred
   689   in  folterms  end
   690 
   691 fun get_uvars (UVar(a,typ)) = [a] 
   692   | get_uvars (Fun (_,typ,tlist)) = union_all(map get_uvars tlist)
   693 
   694 fun dfg_vars (Clause {literals,...}) =
   695   union_all (map get_uvars (List.concat (map dfg_folterms literals)))
   696 
   697 fun clause2dfg (cls as Clause{axiom_name,clause_id,kind,types_sorts,...}) =
   698     let val (lits,tfree_lits) = dfg_clause_aux cls 
   699             (*"lits" includes the typing assumptions (TVars)*)
   700         val vars = dfg_vars cls
   701         val tvars = get_tvar_strs types_sorts
   702 	val cls_str = gen_dfg_cls(clause_id, axiom_name, name_of_kind kind, 
   703 	                           commas lits, tvars@vars) 
   704     in (cls_str, tfree_lits) end;
   705 
   706 fun string_of_arity (name, num) =  "(" ^ name ^ "," ^ Int.toString num ^ ")"
   707 
   708 fun string_of_preds [] = ""
   709   | string_of_preds preds = "predicates[" ^ commas(map string_of_arity preds) ^ "].\n";
   710 
   711 fun string_of_funcs [] = ""
   712   | string_of_funcs funcs = "functions[" ^ commas(map string_of_arity funcs) ^ "].\n" ;
   713 
   714 fun string_of_symbols predstr funcstr = 
   715   "list_of_symbols.\n" ^ predstr  ^ funcstr  ^ "end_of_list.\n\n";
   716 
   717 fun string_of_start name = "begin_problem(" ^ name ^ ").\n\n";
   718 
   719 fun string_of_descrip name = 
   720   "list_of_descriptions.\nname({*" ^ name ^ 
   721   "*}).\nauthor({*Isabelle*}).\nstatus(unknown).\ndescription({*auto-generated*}).\nend_of_list.\n\n"
   722 
   723 fun dfg_tfree_clause tfree_lit =
   724   "clause( %(negated_conjecture)\n" ^ "or( " ^ tfree_lit ^ "),\n" ^ "tfree_tcs" ^ ").\n\n"
   725 
   726 fun dfg_of_arLit (TConsLit(pol,(c,t,args))) =
   727       dfg_sign pol (c ^ "(" ^ t ^ paren_pack args ^ ")")
   728   | dfg_of_arLit (TVarLit(pol,(c,str))) =
   729       dfg_sign pol (c ^ "(" ^ str ^ ")")
   730     
   731 fun dfg_classrelLits sub sup =  "not(" ^ sub ^ "(T)), " ^ sup ^ "(T)";
   732 
   733 fun dfg_classrelClause (ClassrelClause {axiom_name,subclass,superclass,...}) =
   734   "clause(forall([T],\nor( " ^ dfg_classrelLits subclass superclass ^ ")),\n" ^
   735   axiom_name ^ ").\n\n";
   736       
   737 fun string_of_ar axiom_name = arclause_prefix ^ ascii_of axiom_name;
   738 
   739 fun dfg_arity_clause (ArityClause{axiom_name,kind,conclLit,premLits,...}) = 
   740   let val TConsLit(_, (_,_,tvars)) = conclLit
   741       val lits = map dfg_of_arLit (conclLit :: premLits)
   742   in
   743       "clause( %(" ^ name_of_kind kind ^ ")\n" ^ 
   744       dfg_forall tvars ("or( " ^ commas lits ^ ")") ^ ",\n" ^
   745       string_of_ar axiom_name ^ ").\n\n"
   746   end;
   747 
   748 (* write out a subgoal in DFG format to the file "xxxx_N"*)
   749 fun dfg_write_file thms filename (ax_tuples,classrel_clauses,arity_clauses) = 
   750   let 
   751     val _ = Output.debug ("Preparing to write the DFG file " ^ filename)
   752     val conjectures = make_conjecture_clauses thms
   753     val (clnames,axclauses) = ListPair.unzip (make_axiom_clauses ax_tuples)
   754     val (dfg_clss, tfree_litss) = ListPair.unzip (map clause2dfg conjectures)
   755     val clss = conjectures @ axclauses
   756     val funcs = funcs_of_clauses clss arity_clauses
   757     and preds = preds_of_clauses clss classrel_clauses arity_clauses
   758     and probname = Path.pack (Path.base (Path.unpack filename))
   759     val (axstrs, _) = ListPair.unzip (map clause2dfg axclauses)
   760     val tfree_clss = map dfg_tfree_clause (union_all tfree_litss) 
   761     val out = TextIO.openOut filename
   762   in
   763     TextIO.output (out, string_of_start probname); 
   764     TextIO.output (out, string_of_descrip probname); 
   765     TextIO.output (out, string_of_symbols (string_of_funcs funcs) (string_of_preds preds)); 
   766     TextIO.output (out, "list_of_clauses(axioms,cnf).\n");
   767     writeln_strs out axstrs;
   768     List.app (curry TextIO.output out o dfg_classrelClause) classrel_clauses;
   769     List.app (curry TextIO.output out o dfg_arity_clause) arity_clauses;
   770     TextIO.output (out, "end_of_list.\n\nlist_of_clauses(conjectures,cnf).\n");
   771     writeln_strs out tfree_clss;
   772     writeln_strs out dfg_clss;
   773     TextIO.output (out, "end_of_list.\n\nend_problem.\n");
   774     TextIO.closeOut out;
   775     clnames
   776   end;
   777 
   778 
   779 (**** Produce TPTP files ****)
   780 
   781 (*Attach sign in TPTP syntax: false means negate.*)
   782 fun tptp_sign true s = s
   783   | tptp_sign false s = "~ " ^ s
   784 
   785 fun tptp_of_equality pol ts =
   786   let val (s1,s2) = string_of_pair ts
   787       val eqop = if pol then " = " else " != "
   788   in  s1 ^ eqop ^ s2  end;
   789 
   790 fun tptp_literal (Literal(pol,Predicate("equal",_,ts))) = tptp_of_equality pol ts
   791   | tptp_literal (Literal(pol,pred)) = tptp_sign pol (string_of_predicate pred);
   792 
   793 fun tptp_of_typeLit (LTVar (s,ty))  = tptp_sign false (s ^ "(" ^ ty ^ ")")
   794   | tptp_of_typeLit (LTFree (s,ty)) = tptp_sign true  (s ^ "(" ^ ty ^ ")");
   795  
   796 fun gen_tptp_cls (cls_id,ax_name,knd,lits) = 
   797     "cnf(" ^ string_of_clausename (cls_id,ax_name) ^ "," ^ 
   798     name_of_kind knd ^ "," ^ tptp_pack lits ^ ").\n";
   799 
   800 fun tptp_type_lits (Clause {literals, types_sorts, ...}) = 
   801   let val (tvar_lits,tfree_lits) = add_typs_aux types_sorts
   802   in
   803       (map tptp_of_typeLit tvar_lits @ map tptp_literal literals,
   804        map tptp_of_typeLit tfree_lits)
   805   end; 
   806 
   807 fun clause2tptp (cls as Clause {clause_id, axiom_name, kind, ...}) =
   808     let val (lits,tfree_lits) = tptp_type_lits cls 
   809             (*"lits" includes the typing assumptions (TVars)*)
   810 	val cls_str = gen_tptp_cls(clause_id, axiom_name, kind, lits) 
   811     in
   812 	(cls_str,tfree_lits) 
   813     end;
   814 
   815 fun tptp_tfree_clause tfree_lit =
   816     "cnf(" ^ "tfree_tcs," ^ "negated_conjecture" ^ "," ^ tptp_pack[tfree_lit] ^ ").\n";
   817     
   818 fun tptp_of_arLit (TConsLit(b,(c,t,args))) =
   819       tptp_sign b (c ^ "(" ^ t ^ paren_pack args ^ ")")
   820   | tptp_of_arLit (TVarLit(b,(c,str))) =
   821       tptp_sign b (c ^ "(" ^ str ^ ")")
   822     
   823 fun tptp_arity_clause (ArityClause{axiom_name,kind,conclLit,premLits,...}) = 
   824   "cnf(" ^ string_of_ar axiom_name ^ "," ^ name_of_kind kind ^ "," ^ 
   825   tptp_pack (map tptp_of_arLit (conclLit :: premLits)) ^ ").\n";
   826 
   827 fun tptp_classrelLits sub sup = 
   828   let val tvar = "(T)"
   829   in  tptp_pack [tptp_sign false (sub^tvar), tptp_sign true (sup^tvar)]  end;
   830 
   831 fun tptp_classrelClause (ClassrelClause {axiom_name,subclass,superclass,...}) =
   832   "cnf(" ^ axiom_name ^ ",axiom," ^ tptp_classrelLits subclass superclass ^ ").\n" 
   833 
   834 (* write out a subgoal as tptp clauses to the file "xxxx_N"*)
   835 fun tptp_write_file thms filename (ax_tuples,classrel_clauses,arity_clauses) =
   836   let
   837     val _ = Output.debug ("Preparing to write the TPTP file " ^ filename)
   838     val clss = make_conjecture_clauses thms
   839     val (clnames,axclauses) = ListPair.unzip (make_axiom_clauses ax_tuples)
   840     val (tptp_clss,tfree_litss) = ListPair.unzip (map clause2tptp clss)
   841     val tfree_clss = map tptp_tfree_clause (foldl (op union_string) [] tfree_litss)
   842     val out = TextIO.openOut filename
   843   in
   844     List.app (curry TextIO.output out o #1 o clause2tptp) axclauses;
   845     writeln_strs out tfree_clss;
   846     writeln_strs out tptp_clss;
   847     List.app (curry TextIO.output out o tptp_classrelClause) classrel_clauses;
   848     List.app (curry TextIO.output out o tptp_arity_clause) arity_clauses;
   849     TextIO.closeOut out;
   850     clnames
   851   end;
   852 
   853 end;