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