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