src/HOL/Tools/res_clause.ML
author mengj
Mon Nov 28 07:16:16 2005 +0100 (2005-11-28)
changeset 18275 86cefba6d325
parent 18218 9a7ffce389c3
child 18390 aaecdaef4c04
permissions -rw-r--r--
Only output types if !keep_types is true.
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory
     2 
     3     ID: $Id$
     4     Copyright 2004 University of Cambridge
     5 
     6 ML data structure for storing/printing FOL clauses and arity clauses.
     7 Typed equality is treated differently.
     8 *)
     9 
    10 (* works for writeoutclasimp on typed *)
    11 signature RES_CLAUSE =
    12   sig
    13   val keep_types : bool ref
    14   val special_equal : bool ref
    15   val tagged : bool ref
    16 
    17   exception ARCLAUSE of string
    18   exception CLAUSE of string * term
    19   type arityClause 
    20   type classrelClause
    21   type clause
    22   val init : theory -> unit
    23   val make_axiom_clause : Term.term -> string * int -> clause
    24   val make_conjecture_clauses : term list -> clause list
    25   val get_axiomName : clause ->  string
    26   val isTaut : clause -> bool
    27   val num_of_clauses : clause -> int
    28 
    29   val clause2dfg : clause -> string * string list
    30   val clauses2dfg : clause list -> string -> clause list -> clause list ->
    31 	   (string * int) list -> (string * int) list -> string
    32   val tfree_dfg_clause : string -> string
    33 
    34   val arity_clause_thy: theory -> arityClause list 
    35   val classrel_clauses_thy: theory -> classrelClause list 
    36 
    37   val tptp_arity_clause : arityClause -> string
    38   val tptp_classrelClause : classrelClause -> string
    39   val tptp_clause : clause -> string list
    40   val clause2tptp : clause -> string * string list
    41   val tfree_clause : string -> string
    42   val schematic_var_prefix : string
    43   val fixed_var_prefix : string
    44   val tvar_prefix : string
    45   val tfree_prefix : string
    46   val clause_prefix : string 
    47   val arclause_prefix : string
    48   val const_prefix : string
    49   val tconst_prefix : string 
    50   val class_prefix : string 
    51 
    52   val union_all : ''a list list -> ''a list
    53   val ascii_of : String.string -> String.string
    54   val paren_pack : string list -> string
    55   val bracket_pack : string list -> string
    56   val make_schematic_var : String.string * int -> string
    57   val make_fixed_var : String.string -> string
    58   val make_schematic_type_var : string * int -> string
    59   val make_fixed_type_var : string -> string
    60   val make_fixed_const : String.string -> string		
    61   val make_fixed_type_const : String.string -> string   
    62   val make_type_class : String.string -> string
    63   val isMeta : String.string -> bool
    64   
    65   type typ_var
    66   val mk_typ_var_sort : Term.typ -> typ_var * sort
    67   type type_literal
    68   val add_typs_aux2 : (typ_var * string list) list -> type_literal list * type_literal list
    69   val gen_tptp_cls : int * string * string * string -> string
    70   val gen_tptp_type_cls : int * string * string * string * int -> string
    71   val tptp_of_typeLit : type_literal -> string
    72 
    73   end;
    74 
    75 structure ResClause: RES_CLAUSE =
    76 struct
    77 
    78 (* Added for typed equality *)
    79 val special_equal = ref false; (* by default,equality does not carry type information *)
    80 val eq_typ_wrapper = "typeinfo"; (* default string *)
    81 
    82 
    83 val schematic_var_prefix = "V_";
    84 val fixed_var_prefix = "v_";
    85 
    86 val tvar_prefix = "T_";
    87 val tfree_prefix = "t_";
    88 
    89 val clause_prefix = "cls_"; 
    90 val arclause_prefix = "clsarity_" 
    91 val clrelclause_prefix = "clsrel_";
    92 
    93 val const_prefix = "c_";
    94 val tconst_prefix = "tc_"; 
    95 
    96 val class_prefix = "class_"; 
    97 
    98 
    99 fun union_all xss = foldl (op union) [] xss;
   100 
   101  
   102 (*Provide readable names for the more common symbolic functions*)
   103 val const_trans_table =
   104       Symtab.make [("op =", "equal"),
   105 	  	   ("op <=", "lessequals"),
   106 		   ("op <", "less"),
   107 		   ("op &", "and"),
   108 		   ("op |", "or"),
   109 		   ("op +", "plus"),
   110 		   ("op -", "minus"),
   111 		   ("op *", "times"),
   112 		   ("op -->", "implies"),
   113 		   ("{}", "emptyset"),
   114 		   ("op :", "in"),
   115 		   ("op Un", "union"),
   116 		   ("op Int", "inter")];
   117 
   118 val type_const_trans_table =
   119       Symtab.make [("*", "t_prod"),
   120 	  	   ("+", "t_sum"),
   121 		   ("~=>", "t_map")];
   122 
   123 (*Escaping of special characters.
   124   Alphanumeric characters are left unchanged.
   125   The character _ goes to __
   126   Characters in the range ASCII space to / go to _A to _P, respectively.
   127   Other printing characters go to _NNN where NNN is the decimal ASCII code.*)
   128 local
   129 
   130 val A_minus_space = Char.ord #"A" - Char.ord #" ";
   131 
   132 fun ascii_of_c c =
   133   if Char.isAlphaNum c then String.str c
   134   else if c = #"_" then "__"
   135   else if #" " <= c andalso c <= #"/" 
   136        then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
   137   else if Char.isPrint c then ("_" ^ Int.toString (Char.ord c))
   138   else ""
   139 
   140 in
   141 
   142 val ascii_of = String.translate ascii_of_c;
   143 
   144 end;
   145 
   146 (* convert a list of strings into one single string; surrounded by brackets *)
   147 fun paren_pack [] = ""   (*empty argument list*)
   148   | paren_pack strings = "(" ^ commas strings ^ ")";
   149 
   150 fun bracket_pack strings = "[" ^ commas strings ^ "]";
   151 
   152 
   153 (*Remove the initial ' character from a type variable, if it is present*)
   154 fun trim_type_var s =
   155   if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
   156   else error ("trim_type: Malformed type variable encountered: " ^ s);
   157 
   158 fun ascii_of_indexname (v,0) = ascii_of v
   159   | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ Int.toString i;
   160 
   161 fun make_schematic_var v = schematic_var_prefix ^ (ascii_of_indexname v);
   162 fun make_fixed_var x = fixed_var_prefix ^ (ascii_of x);
   163 
   164 fun make_schematic_type_var (x,i) = 
   165       tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
   166 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
   167 
   168 fun make_fixed_const c =
   169     case Symtab.lookup const_trans_table c of
   170         SOME c' => c'
   171       | NONE =>  const_prefix ^ ascii_of c;
   172 
   173 fun make_fixed_type_const c = 
   174     case Symtab.lookup type_const_trans_table c of
   175         SOME c' => c'
   176       | NONE =>  tconst_prefix ^ ascii_of c;
   177 
   178 fun make_type_class clas = class_prefix ^ ascii_of clas;
   179 
   180 
   181 
   182 (***** definitions and functions for FOL clauses, prepared for conversion into TPTP format or SPASS format. *****)
   183 
   184 val keep_types = ref true;
   185 
   186 datatype kind = Axiom | Hypothesis | Conjecture;
   187 fun name_of_kind Axiom = "axiom"
   188   | name_of_kind Hypothesis = "hypothesis"
   189   | name_of_kind Conjecture = "conjecture";
   190 
   191 type clause_id = int;
   192 type axiom_name = string;
   193 
   194 
   195 type polarity = bool;
   196 
   197 type indexname = Term.indexname;
   198 
   199 
   200 (* "tag" is used for vampire specific syntax  *)
   201 type tag = bool; 
   202 
   203 
   204 (**** Isabelle FOL clauses ****)
   205 
   206 val tagged = ref false;
   207 
   208 type pred_name = string;
   209 type sort = Term.sort;
   210 type fol_type = string;
   211 
   212 datatype type_literal = LTVar of string | LTFree of string;
   213 
   214 datatype folTerm = UVar of string * fol_type
   215                  | Fun of string * fol_type list * folTerm list;
   216 datatype predicate = Predicate of pred_name * fol_type list * folTerm list;
   217 
   218 datatype literal = Literal of polarity * predicate * tag;
   219 
   220 datatype typ_var = FOLTVar of indexname | FOLTFree of string;
   221 
   222 fun mk_typ_var_sort (TFree(a,s)) = (FOLTFree a,s)
   223   | mk_typ_var_sort (TVar(v,s)) = (FOLTVar v,s);
   224 
   225 
   226 
   227 (* ML datatype used to repsent one single clause: disjunction of literals. *)
   228 datatype clause = 
   229 	 Clause of {clause_id: clause_id,
   230 		    axiom_name: axiom_name,
   231 		    kind: kind,
   232 		    literals: literal list,
   233 		    types_sorts: (typ_var * sort) list, 
   234                     tvar_type_literals: type_literal list, 
   235                     tfree_type_literals: type_literal list ,
   236                     tvars: string list,
   237                     predicates: (string*int) list,
   238                     functions: (string*int) list};
   239 
   240 
   241 exception CLAUSE of string * term;
   242 
   243 
   244 (*** make clauses ***)
   245 
   246 fun isFalse (Literal (pol,Predicate(a,_,[]),_)) =
   247       (pol andalso a = "c_False") orelse
   248       (not pol andalso a = "c_True")
   249   | isFalse _ = false;
   250 
   251 fun isTrue (Literal (pol,Predicate(a,_,[]),_)) =
   252       (pol andalso a = "c_True") orelse
   253       (not pol andalso a = "c_False")
   254   | isTrue _ = false;
   255   
   256 fun isTaut (Clause {literals,...}) = exists isTrue literals;  
   257 
   258 fun make_clause (clause_id,axiom_name,kind,literals,
   259                  types_sorts,tvar_type_literals,
   260                  tfree_type_literals,tvars, predicates, functions) =
   261   if forall isFalse literals 
   262   then error "Problem too trivial for resolution (empty clause)"
   263   else
   264      Clause {clause_id = clause_id, axiom_name = axiom_name, kind = kind, 
   265              literals = literals, types_sorts = types_sorts,
   266              tvar_type_literals = tvar_type_literals,
   267              tfree_type_literals = tfree_type_literals,
   268              tvars = tvars, predicates = predicates, 
   269              functions = functions};
   270 
   271 
   272 (** Some Clause destructor functions **)
   273 
   274 fun string_of_kind (Clause cls) = name_of_kind (#kind cls);
   275 
   276 fun get_axiomName (Clause cls) = #axiom_name cls;
   277 
   278 fun get_clause_id (Clause cls) = #clause_id cls;
   279 
   280 fun funcs_of_cls (Clause cls) = #functions cls;
   281 
   282 fun preds_of_cls (Clause cls) = #predicates cls;
   283 
   284 
   285 (*Declarations of the current theory--to allow suppressing types.*)
   286 val const_typargs = ref (Library.K [] : (string*typ -> typ list));
   287 
   288 fun num_typargs(s,T) = if !keep_types then length (!const_typargs (s,T)) else 0;
   289 
   290 (*Initialize the type suppression mechanism with the current theory before
   291     producing any clauses!*)
   292 fun init thy = (const_typargs := Sign.const_typargs thy);
   293     
   294 
   295 (*Flatten a type to a string while accumulating sort constraints on the TFrees and
   296   TVars it contains.*)    
   297 fun type_of (Type (a, Ts)) = 
   298       let val (folTyps, (ts, funcs)) = types_of Ts 
   299 	  val t = make_fixed_type_const a
   300       in    
   301 	  ((t ^ paren_pack folTyps), (ts, (t, length Ts)::funcs))
   302       end
   303   | type_of (TFree (a,s)) = 
   304       let val t = make_fixed_type_var a
   305       in (t, ([((FOLTFree a),s)], [(t,0)])) end
   306   | type_of (TVar (v, s)) = (make_schematic_type_var v, ([((FOLTVar v),s)], []))
   307 and types_of Ts =
   308       let val foltyps_ts = map type_of Ts 
   309 	  val (folTyps,ts_funcs) = ListPair.unzip foltyps_ts
   310 	  val (ts, funcslist) = ListPair.unzip ts_funcs
   311       in    
   312 	  (folTyps, (union_all ts, union_all funcslist))
   313       end;
   314 
   315 
   316 fun const_types_of (c,T) = types_of (!const_typargs (c,T));
   317 
   318 (* Any variables created via the METAHYPS tactical should be treated as
   319    universal vars, although it is represented as "Free(...)" by Isabelle *)
   320 val isMeta = String.isPrefix "METAHYP1_"
   321 
   322 fun pred_name_type (Const(c,T)) = 
   323       let val (contys,(folTyps,funcs)) = const_types_of (c,T)
   324       in (make_fixed_const c, (contys,folTyps), funcs) end
   325   | pred_name_type (Free(x,T))  = 
   326       if isMeta x then raise CLAUSE("Predicate Not First Order 1", Free(x,T)) 
   327       else (make_fixed_var x, ([],[]), [])
   328   | pred_name_type (v as Var _) = raise CLAUSE("Predicate Not First Order 2", v)
   329   | pred_name_type t        = raise CLAUSE("Predicate input unexpected", t);
   330 
   331 
   332 (* For typed equality *)
   333 (* here "arg_typ" is the type of "="'s argument's type, not the type of the equality *)
   334 (* Find type of equality arg *)
   335 fun eq_arg_type (Type("fun",[T,_])) = 
   336     let val (folT,_) = type_of T;
   337     in  folT  end;
   338 
   339 fun fun_name_type (Const("op =",T)) args =   (*FIXME: Is this special treatment of = needed??*)
   340       let val t = make_fixed_const "op ="
   341       in (t, ([eq_arg_type T], []), [(t,2)]) end
   342   | fun_name_type (Const(c,T)) args = 
   343       let val t = make_fixed_const c
   344 	  val (contys, (folTyps,funcs)) = const_types_of (c,T)
   345 	  val arity = num_typargs(c,T) + length args
   346       in
   347 	  (t, (contys,folTyps), ((t,arity)::funcs))
   348       end
   349  | fun_name_type (Free(x,T)) args  = 
   350       let val t = make_fixed_var x
   351       in  (t, ([],[]), [(t, length args)]) end
   352   | fun_name_type f args = raise CLAUSE("Function Not First Order 1", f);
   353 
   354 
   355 fun term_of (Var(ind_nm,T)) = 
   356       let val (folType,(ts,funcs)) = type_of T
   357       in
   358 	  (UVar(make_schematic_var ind_nm, folType), (ts, funcs))
   359       end
   360   | term_of (Free(x,T)) = 
   361       let val (folType, (ts,funcs)) = type_of T
   362       in
   363 	  if isMeta x then (UVar(make_schematic_var(x,0),folType),
   364 			    (ts, ((make_schematic_var(x,0)),0)::funcs))
   365 	  else
   366 	      (Fun(make_fixed_var x, [folType], []), 
   367 	       (ts, ((make_fixed_var x),0)::funcs))
   368       end
   369   | term_of (Const(c,T)) =  (* impossible to be equality *)
   370       let val (contys, (folTyps,funcs)) = const_types_of (c,T)
   371       in
   372 	  (Fun(make_fixed_const c, contys, []),
   373 	   (folTyps, ((make_fixed_const c),0)::funcs))
   374       end    
   375   | term_of app = 
   376       let val (f,args) = strip_comb app
   377           val _ = case f of Const(_,_) => ()
   378 			  | Free(s,_)  => 
   379 			      if isMeta s 
   380 			      then raise CLAUSE("Function Not First Order 2", f)
   381 			      else ()
   382 			  | _ => raise CLAUSE("Function Not First Order 3", f);
   383 	  val (funName,(contys,ts1),funcs) = fun_name_type f args
   384 	  val (args',(ts2,funcs')) = terms_of args
   385       in
   386 	  (Fun(funName,contys,args'), 
   387 	   (union_all (ts1::ts2), 
   388 	    union_all(funcs::funcs')))
   389       end
   390   | term_of t = raise CLAUSE("Function Not First Order 4", t)
   391 and terms_of ts =  
   392       let val (args, ts_funcs) = ListPair.unzip (map term_of ts)
   393       in
   394 	  (args, ListPair.unzip ts_funcs)
   395       end
   396 
   397 
   398 fun pred_of (Const("op =", typ), args) =
   399       let val arg_typ = eq_arg_type typ 
   400 	  val (args',(ts,funcs)) = terms_of args
   401 	  val equal_name = make_fixed_const "op ="
   402       in
   403 	  (Predicate(equal_name,[arg_typ],args'),
   404 	   union_all ts, 
   405 	   [((make_fixed_var equal_name), 2)], 
   406 	   union_all funcs)
   407       end
   408   | pred_of (pred,args) = 
   409       let val (predName,(predType,ts1), pfuncs) = pred_name_type pred
   410 	  val (args',(ts2,ffuncs)) = terms_of args
   411 	  val ts3 = union_all (ts1::ts2)
   412 	  val ffuncs' = union_all ffuncs
   413 	  val newfuncs = pfuncs union ffuncs'
   414 	  val arity = 
   415 	    case pred of
   416 		Const (c,T) => num_typargs(c,T) + length args
   417 	      | _ => length args
   418       in
   419 	  (Predicate(predName,predType,args'), ts3, 
   420 	   [(predName, arity)], newfuncs)
   421       end;
   422 
   423 
   424 (*Treatment of literals, possibly negated or tagged*)
   425 fun predicate_of ((Const("Not",_) $ P), polarity, tag) =
   426       predicate_of (P, not polarity, tag)
   427   | predicate_of ((Const("HOL.tag",_) $ P), polarity, tag) =
   428       predicate_of (P, polarity, true)
   429   | predicate_of (term,polarity,tag) =
   430         (pred_of (strip_comb term), polarity, tag);
   431 
   432 fun literals_of_term1 args (Const("Trueprop",_) $ P) = literals_of_term1 args P
   433   | literals_of_term1 (args as (lits, ts, preds, funcs)) (Const("op |",_) $ P $ Q) = 
   434       let val (lits', ts', preds', funcs') = literals_of_term1 args P
   435       in
   436 	  literals_of_term1 (lits', ts', preds' union preds, funcs' union funcs) Q
   437       end
   438   | literals_of_term1 (lits, ts, preds, funcs) P =
   439       let val ((pred, ts', preds', funcs'), pol, tag) = predicate_of (P,true,false)
   440 	  val lits' = Literal(pol,pred,tag) :: lits
   441       in
   442 	  (lits', ts union ts', preds' union preds, funcs' union funcs)
   443       end;
   444 
   445 
   446 val literals_of_term = literals_of_term1 ([],[],[],[]);
   447 
   448 
   449 (* FIX: not sure what to do with these funcs *)
   450 
   451 (*Make literals for sorted type variables*) 
   452 fun sorts_on_typs (_, [])   = ([]) 
   453   | sorts_on_typs (v, "HOL.type" :: s) =
   454       sorts_on_typs (v,s)   (*Ignore sort "type"*)
   455   | sorts_on_typs ((FOLTVar indx), (s::ss)) =
   456       LTVar((make_type_class s) ^ 
   457         "(" ^ (make_schematic_type_var indx) ^ ")") :: 
   458       (sorts_on_typs ((FOLTVar indx), ss))
   459   | sorts_on_typs ((FOLTFree x), (s::ss)) =
   460       LTFree((make_type_class s) ^ "(" ^ (make_fixed_type_var x) ^ ")") :: 
   461       (sorts_on_typs ((FOLTFree x), ss));
   462 
   463 
   464 (*UGLY: seems to be parsing the "show sorts" output, removing anything that
   465   starts with a left parenthesis.*)
   466 fun remove_type str = hd (String.fields (fn c => c = #"(") str);
   467 
   468 fun pred_of_sort (LTVar x) = ((remove_type x),1)
   469 |   pred_of_sort (LTFree x) = ((remove_type x),1)
   470 
   471 
   472 
   473 
   474 (*Given a list of sorted type variables, return two separate lists.
   475   The first is for TVars, the second for TFrees.*)
   476 fun add_typs_aux [] preds  = ([],[], preds)
   477   | add_typs_aux ((FOLTVar indx,s)::tss) preds = 
   478       let val vs = sorts_on_typs (FOLTVar indx, s)
   479           val preds' = (map pred_of_sort vs)@preds
   480 	  val (vss,fss, preds'') = add_typs_aux tss preds'
   481       in
   482 	  (vs union vss, fss, preds'')
   483       end
   484   | add_typs_aux ((FOLTFree x,s)::tss) preds  =
   485       let val fs = sorts_on_typs (FOLTFree x, s)
   486           val preds' = (map pred_of_sort fs)@preds
   487 	  val (vss,fss, preds'') = add_typs_aux tss preds'
   488       in
   489 	  (vss, fs union fss, preds'')
   490       end;
   491 
   492 fun add_typs_aux2 [] = ([],[])
   493   | add_typs_aux2 ((FOLTVar indx,s)::tss) =
   494     let val vs = sorts_on_typs (FOLTVar indx,s)
   495 	val (vss,fss) = add_typs_aux2 tss
   496     in
   497 	(vs union vss,fss)
   498     end
   499   | add_typs_aux2 ((FOLTFree x,s)::tss) =
   500     let val fs = sorts_on_typs (FOLTFree x,s)
   501 	val (vss,fss) = add_typs_aux2 tss
   502     in
   503 	(vss,fs union fss)
   504     end;
   505 
   506 
   507 fun add_typs (Clause cls) preds  = add_typs_aux (#types_sorts cls) preds 
   508 
   509 
   510 (** make axiom clauses, hypothesis clauses and conjecture clauses. **)
   511 
   512 fun get_tvar_strs [] = []
   513   | get_tvar_strs ((FOLTVar indx,s)::tss) = 
   514       let val vstr = make_schematic_type_var indx
   515       in
   516 	  vstr ins (get_tvar_strs tss)
   517       end
   518   | get_tvar_strs((FOLTFree x,s)::tss) = distinct (get_tvar_strs tss)
   519 
   520 (* FIX add preds and funcs to add typs aux here *)
   521 
   522 fun make_axiom_clause_thm thm (ax_name,cls_id) =
   523     let val (lits,types_sorts, preds, funcs) = literals_of_term (prop_of thm)
   524 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds 
   525         val tvars = get_tvar_strs types_sorts
   526     in 
   527 	make_clause(cls_id,ax_name,Axiom,
   528 	            lits,types_sorts,tvar_lits,tfree_lits,
   529 	            tvars, preds, funcs)
   530     end;
   531 
   532 
   533 (* check if a clause is FOL first*)
   534 fun make_conjecture_clause n t =
   535     let val _ = check_is_fol_term t
   536 	    handle TERM("check_is_fol_term",_) => raise CLAUSE("Goal is not FOL",t)
   537 	val (lits,types_sorts, preds, funcs) = literals_of_term t
   538 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds 
   539         val tvars = get_tvar_strs types_sorts
   540     in
   541 	make_clause(n,"conjecture",Conjecture,
   542 	            lits,types_sorts,tvar_lits,tfree_lits,
   543 	            tvars, preds, funcs)
   544     end;
   545     
   546 fun make_conjecture_clauses_aux _ [] = []
   547   | make_conjecture_clauses_aux n (t::ts) =
   548       make_conjecture_clause n t :: make_conjecture_clauses_aux (n+1) ts
   549 
   550 val make_conjecture_clauses = make_conjecture_clauses_aux 0
   551 
   552 
   553 (*before converting an axiom clause to "clause" format, check if it is FOL*)
   554 fun make_axiom_clause term (ax_name,cls_id) =
   555     let val _ = check_is_fol_term term 
   556 	    handle TERM("check_is_fol_term",_) => raise CLAUSE("Axiom is not FOL", term) 
   557 	val (lits,types_sorts, preds,funcs) = literals_of_term term
   558 	val (tvar_lits,tfree_lits, preds) = add_typs_aux types_sorts preds
   559         val tvars = get_tvar_strs types_sorts	
   560     in 
   561 	make_clause(cls_id,ax_name,Axiom,
   562 	            lits,types_sorts,tvar_lits,tfree_lits,
   563 	            tvars, preds,funcs)
   564     end;
   565 
   566 
   567 
   568  
   569 (**** Isabelle arities ****)
   570 
   571 exception ARCLAUSE of string;
   572  
   573 
   574 type class = string; 
   575 type tcons = string; 
   576 
   577 
   578 datatype arLit = TConsLit of bool * (class * tcons * string list) | TVarLit of bool * (class * string);
   579  
   580 datatype arityClause =  
   581 	 ArityClause of {clause_id: clause_id,
   582 	  	         axiom_name: axiom_name,
   583 			 kind: kind,
   584 			 conclLit: arLit,
   585 			 premLits: arLit list};
   586 
   587 
   588 fun get_TVars 0 = []
   589   | get_TVars n = ("T_" ^ (Int.toString n)) :: get_TVars (n-1);
   590 
   591 
   592 
   593 fun pack_sort(_,[])  = raise ARCLAUSE("Empty Sort Found") 
   594   | pack_sort(tvar, [cls]) = [(make_type_class cls, tvar)] 
   595   | pack_sort(tvar, cls::srt) =  (make_type_class cls,tvar) :: (pack_sort(tvar, srt));
   596     
   597     
   598 fun make_TVarLit (b,(cls,str)) = TVarLit(b,(cls,str));
   599 fun make_TConsLit (b,(cls,tcons,tvars)) = TConsLit(b,(make_type_class cls,make_fixed_type_const tcons,tvars));
   600 
   601 fun make_axiom_arity_clause (tcons,n,(res,args)) =
   602    let val nargs = length args
   603        val tvars = get_TVars nargs
   604        val tvars_srts = ListPair.zip (tvars,args)
   605        val tvars_srts' = union_all(map pack_sort tvars_srts)
   606        val false_tvars_srts' = map (pair false) tvars_srts'
   607    in
   608       ArityClause {clause_id = n, kind = Axiom, 
   609                    axiom_name = tcons,
   610                    conclLit = make_TConsLit(true,(res,tcons,tvars)), 
   611                    premLits = map make_TVarLit false_tvars_srts'}
   612    end;
   613     
   614 (*The number of clauses generated from cls, including type clauses*)
   615 fun num_of_clauses (Clause cls) =
   616     let val num_tfree_lits = 
   617 	      if !keep_types then length (#tfree_type_literals cls)
   618 	      else 0
   619     in 	1 + num_tfree_lits  end;
   620 
   621 
   622 (**** Isabelle class relations ****)
   623 
   624 
   625 datatype classrelClause = 
   626 	 ClassrelClause of {clause_id: clause_id,
   627 			    subclass: class,
   628 			    superclass: class option};
   629 
   630 
   631 fun make_axiom_classrelClause n subclass superclass =
   632   ClassrelClause {clause_id = n,
   633                   subclass = subclass, superclass = superclass};
   634 
   635 
   636 fun classrelClauses_of_aux n sub [] = []
   637   | classrelClauses_of_aux n sub (sup::sups) =
   638       make_axiom_classrelClause n sub (SOME sup) :: classrelClauses_of_aux (n+1) sub sups;
   639 
   640 
   641 fun classrelClauses_of (sub,sups) = 
   642     case sups of [] => [make_axiom_classrelClause 0 sub NONE]
   643 	       | _ => classrelClauses_of_aux 0 sub sups;
   644 
   645 
   646 (***** Isabelle arities *****)
   647 
   648 
   649 fun arity_clause _ (tcons, []) = []
   650   | arity_clause n (tcons, ar::ars) =
   651       make_axiom_arity_clause (tcons,n,ar) :: 
   652       arity_clause (n+1) (tcons,ars);
   653 
   654 fun multi_arity_clause [] = []
   655   | multi_arity_clause (tcon_ar :: tcons_ars)  =
   656       arity_clause 0 tcon_ar  @  multi_arity_clause tcons_ars 
   657 
   658 fun arity_clause_thy thy =
   659   let val arities = #arities (Type.rep_tsig (Sign.tsig_of thy))
   660   in multi_arity_clause (Symtab.dest arities) end;
   661 
   662 
   663 (* Isabelle classes *)
   664 
   665 type classrelClauses = classrelClause list Symtab.table;
   666 
   667 val classrel_of = #2 o #classes o Type.rep_tsig o Sign.tsig_of;
   668 fun classrel_clauses_classrel (C: Sorts.classes) = map classrelClauses_of (Graph.dest C);
   669 val classrel_clauses_thy = List.concat o classrel_clauses_classrel o classrel_of;
   670 
   671 
   672 
   673 (****!!!! Changed for typed equality !!!!****)
   674 
   675 fun wrap_eq_type typ t = eq_typ_wrapper ^"(" ^ t ^ "," ^ typ ^ ")";
   676 
   677 (*Only need to wrap equality's arguments with "typeinfo" if the output clauses are typed 
   678  and if we specifically ask for types to be included.   *)
   679 fun string_of_equality (typ,terms) =
   680       let val [tstr1,tstr2] = map string_of_term terms
   681       in
   682 	  if !keep_types andalso !special_equal 
   683 	  then "equal(" ^ (wrap_eq_type typ tstr1) ^ "," ^ 
   684 		 	  (wrap_eq_type typ tstr2) ^ ")"
   685 	  else "equal(" ^ tstr1 ^ "," ^ tstr2 ^ ")"
   686       end
   687 and string_of_term (UVar(x,_)) = x
   688   | string_of_term (Fun("equal",[typ],terms)) = string_of_equality(typ,terms)
   689   | string_of_term (Fun (name,typs,[])) = name (*Overloaded consts like 0 don't get types!*)
   690   | string_of_term (Fun (name,typs,terms)) = 
   691       let val terms_as_strings = map string_of_term terms
   692 	  val typs' = if !keep_types then typs else []
   693       in  name ^ (paren_pack (terms_as_strings @ typs'))  end
   694   | string_of_term _ = error "string_of_term";      
   695 
   696 (* before output the string of the predicate, check if the predicate corresponds to an equality or not. *)
   697 fun string_of_predicate (Predicate("equal",[typ],terms)) = string_of_equality(typ,terms)
   698   | string_of_predicate (Predicate(name,typs,terms)) = 
   699       let val terms_as_strings = map string_of_term terms
   700 	  val typs' = if !keep_types then typs else []
   701       in  name ^ (paren_pack (terms_as_strings @ typs'))  end
   702   | string_of_predicate _ = error "string_of_predicate";      
   703 
   704 
   705 fun string_of_clausename (cls_id,ax_name) = 
   706     clause_prefix ^ ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   707 
   708 fun string_of_type_clsname (cls_id,ax_name,idx) = 
   709     string_of_clausename (cls_id,ax_name) ^ "_tcs" ^ (Int.toString idx);
   710     
   711 
   712 (********************************)
   713 (* Code for producing DFG files *)
   714 (********************************)
   715 
   716 fun dfg_literal (Literal(pol,pred,tag)) =
   717     let val pred_string = string_of_predicate pred
   718     in
   719 	if pol then pred_string else "not(" ^pred_string ^ ")"  
   720     end;
   721 
   722 
   723 (* FIX: what does this mean? *)
   724 (*fun dfg_of_typeLit (LTVar x) = "not(" ^ x ^ ")"
   725   | dfg_of_typeLit (LTFree x) = "(" ^ x ^ ")";*)
   726 
   727 fun dfg_of_typeLit (LTVar x) =  x 
   728   | dfg_of_typeLit (LTFree x) = x ;
   729  
   730 (*Make the string of universal quantifiers for a clause*)
   731 fun forall_open ([],[]) = ""
   732   | forall_open (vars,tvars) = "forall([" ^ (commas (tvars@vars))^ "],\n"
   733 
   734 fun forall_close ([],[]) = ""
   735   | forall_close (vars,tvars) = ")"
   736 
   737 fun gen_dfg_cls (cls_id,ax_name,knd,lits,tvars,vars) = 
   738     "clause( %(" ^ knd ^ ")\n" ^ forall_open(vars,tvars) ^ 
   739     "or(" ^ lits ^ ")" ^ forall_close(vars,tvars) ^ ",\n" ^ 
   740     string_of_clausename (cls_id,ax_name) ^  ").";
   741 
   742 fun gen_dfg_type_cls (cls_id,ax_name,knd,tfree_lit,idx,tvars,vars) = 
   743     "clause( %(" ^ knd ^ ")\n" ^ forall_open(vars,tvars) ^ 
   744     "or( " ^ tfree_lit ^ ")" ^ forall_close(vars,tvars) ^ ",\n" ^ 
   745     string_of_type_clsname (cls_id,ax_name,idx) ^  ").";
   746 
   747 fun dfg_clause_aux (Clause cls) = 
   748   let val lits = map dfg_literal (#literals cls)
   749       val tvar_lits_strs = 
   750 	  if !keep_types then map dfg_of_typeLit (#tvar_type_literals cls) 
   751 	  else []
   752       val tfree_lits =
   753           if !keep_types then map dfg_of_typeLit (#tfree_type_literals cls)
   754           else []
   755   in
   756       (tvar_lits_strs @ lits, tfree_lits)
   757   end; 
   758 
   759 
   760 fun dfg_folterms (Literal(pol,pred,tag)) = 
   761   let val Predicate (predname, _, folterms) = pred
   762   in  folterms  end
   763 
   764  
   765 fun get_uvars (UVar(a,typ)) = [a] 
   766 |   get_uvars (Fun (_,typ,tlist)) = union_all(map get_uvars tlist)
   767 
   768 
   769 fun is_uvar (UVar _) = true
   770 |   is_uvar (Fun _) = false;
   771 
   772 fun uvar_name (UVar(a,_)) = a
   773 |   uvar_name (Fun (a,_,_)) = raise CLAUSE("Not a variable", Const(a,dummyT));
   774 
   775 fun dfg_vars (Clause cls) =
   776     let val lits = #literals cls
   777         val folterms = List.concat (map dfg_folterms lits)
   778     in 
   779         union_all(map get_uvars folterms)
   780     end
   781 
   782 
   783 fun dfg_tvars (Clause cls) =(#tvars cls)
   784 
   785 
   786 	
   787 (* make this return funcs and preds too? *)
   788 fun string_of_predname (Predicate("equal",_,terms)) = "EQUALITY"
   789   | string_of_predname (Predicate(name,_,terms)) = name
   790     
   791 	
   792 
   793 fun concat_with sep []  = ""
   794   | concat_with sep [x] = "(" ^ x ^ ")"
   795   | concat_with sep (x::xs) = "(" ^ x ^ ")" ^  sep ^ (concat_with sep xs);
   796 
   797 fun dfg_pred (Literal(pol,pred,tag)) ax_name = 
   798     (string_of_predname pred) ^ " " ^ ax_name
   799 
   800 fun dfg_clause cls =
   801     let val (lits,tfree_lits) = dfg_clause_aux cls 
   802              (*"lits" includes the typing assumptions (TVars)*)
   803         val vars = dfg_vars cls
   804         val tvars = dfg_tvars cls
   805 	val knd = string_of_kind cls
   806 	val lits_str = commas lits
   807 	val cls_id = get_clause_id cls
   808 	val axname = get_axiomName cls
   809 	val cls_str = gen_dfg_cls(cls_id,axname,knd,lits_str,tvars, vars) 			
   810         fun typ_clss k [] = []
   811           | typ_clss k (tfree :: tfrees) = 
   812               (gen_dfg_type_cls(cls_id,axname,knd,tfree,k, tvars,vars)) :: 
   813               (typ_clss (k+1) tfrees)
   814     in 
   815 	cls_str :: (typ_clss 0 tfree_lits)
   816     end;
   817 
   818 fun string_of_arity (name, num) =  name ^ "," ^ (Int.toString num) 
   819 
   820 fun string_of_preds preds = 
   821   "predicates[" ^ (concat_with ", " (map string_of_arity preds)) ^ "].\n";
   822 
   823 fun string_of_funcs funcs =
   824   "functions[" ^ (concat_with ", " (map string_of_arity funcs)) ^ "].\n" ;
   825 
   826 
   827 fun string_of_symbols predstr funcstr = 
   828   "list_of_symbols.\n" ^ predstr  ^ funcstr  ^ "end_of_list.\n\n";
   829 
   830 
   831 fun string_of_axioms axstr = 
   832   "list_of_clauses(axioms,cnf).\n" ^ axstr ^ "end_of_list.\n\n";
   833 
   834 
   835 fun string_of_conjectures conjstr = 
   836   "list_of_clauses(conjectures,cnf).\n" ^ conjstr ^ "end_of_list.\n\n";
   837 
   838 fun string_of_descrip () = 
   839   "list_of_descriptions.\nname({*[ File     : ],[ Names    :]*}).\nauthor({*[ Source   :]*}).\nstatus(unknown).\ndescription({*[ Refs     :]*}).\nend_of_list.\n\n"
   840 
   841 
   842 fun string_of_start name = "%------------------------------------------------------------------------------\nbegin_problem(" ^ name ^ ").\n\n";
   843 
   844 
   845 fun string_of_end () = "end_problem.\n%------------------------------------------------------------------------------";
   846 
   847 
   848 fun clause2dfg cls =
   849     let val (lits,tfree_lits) = dfg_clause_aux cls 
   850             (*"lits" includes the typing assumptions (TVars)*)
   851 	val cls_id = get_clause_id cls
   852 	val ax_name = get_axiomName cls
   853         val vars = dfg_vars cls
   854         val tvars = dfg_tvars cls
   855         val funcs = funcs_of_cls cls
   856         val preds = preds_of_cls cls
   857 	val knd = string_of_kind cls
   858 	val lits_str = commas lits
   859 	val cls_str = gen_dfg_cls(cls_id,ax_name,knd,lits_str,tvars,vars) 
   860     in
   861 	(cls_str,tfree_lits) 
   862     end;
   863 
   864 
   865 
   866 fun tfree_dfg_clause tfree_lit =
   867   "clause( %(conjecture)\n" ^ "or( " ^ tfree_lit ^ "),\n" ^ "tfree_tcs" ^ ")."
   868 
   869 
   870 fun gen_dfg_file probname axioms conjectures funcs preds = 
   871     let val axstrs_tfrees = (map clause2dfg axioms)
   872 	val (axstrs, atfrees) = ListPair.unzip axstrs_tfrees
   873         val axstr = (space_implode "\n" axstrs) ^ "\n\n"
   874         val conjstrs_tfrees = (map clause2dfg conjectures)
   875 	val (conjstrs, atfrees) = ListPair.unzip conjstrs_tfrees
   876         val tfree_clss = map tfree_dfg_clause (union_all atfrees) 
   877         val conjstr = (space_implode "\n" (tfree_clss@conjstrs)) ^ "\n\n"
   878         val funcstr = string_of_funcs funcs
   879         val predstr = string_of_preds preds
   880     in
   881        (string_of_start probname) ^ (string_of_descrip ()) ^ 
   882        (string_of_symbols funcstr predstr) ^  
   883        (string_of_axioms axstr) ^
   884        (string_of_conjectures conjstr) ^ (string_of_end ())
   885     end;
   886    
   887 fun clauses2dfg [] probname axioms conjectures funcs preds = 
   888       let val funcs' = (union_all(map funcs_of_cls axioms)) @ funcs
   889 	  val preds' = (union_all(map preds_of_cls axioms)) @ preds
   890       in
   891 	 gen_dfg_file probname axioms conjectures funcs' preds' 
   892       end
   893  | clauses2dfg (cls::clss) probname axioms conjectures funcs preds = 
   894      let val (lits,tfree_lits) = dfg_clause_aux cls
   895 	       (*"lits" includes the typing assumptions (TVars)*)
   896 	 val cls_id = get_clause_id cls
   897 	 val ax_name = get_axiomName cls
   898 	 val vars = dfg_vars cls
   899 	 val tvars = dfg_tvars cls
   900 	 val funcs' = (funcs_of_cls cls) union funcs
   901 	 val preds' = (preds_of_cls cls) union preds
   902 	 val knd = string_of_kind cls
   903 	 val lits_str = concat_with ", " lits
   904 	 val axioms' = if knd = "axiom" then (cls::axioms) else axioms
   905 	 val conjectures' = 
   906 	     if knd = "conjecture" then (cls::conjectures) else conjectures
   907      in
   908 	 clauses2dfg clss probname axioms' conjectures' funcs' preds' 
   909      end;
   910 
   911 
   912 fun string_of_arClauseID (ArityClause {clause_id,axiom_name,...}) =
   913     arclause_prefix ^ ascii_of axiom_name ^ "_" ^ Int.toString clause_id;
   914 
   915 fun string_of_arKind (ArityClause arcls) = name_of_kind(#kind arcls);
   916 
   917 (*FIXME!!! currently is TPTP format!*)
   918 fun dfg_of_arLit (TConsLit(b,(c,t,args))) =
   919       let val pol = if b then "++" else "--"
   920 	  val arg_strs = paren_pack args
   921       in 
   922 	  pol ^ c ^ "(" ^ t ^ arg_strs ^ ")"
   923       end
   924   | dfg_of_arLit (TVarLit(b,(c,str))) =
   925       let val pol = if b then "++" else "--"
   926       in
   927 	  pol ^ c ^ "(" ^ str ^ ")"
   928       end;
   929     
   930 
   931 fun dfg_of_conclLit (ArityClause arcls) = dfg_of_arLit (#conclLit arcls);
   932      
   933 
   934 fun dfg_of_premLits (ArityClause arcls) = map dfg_of_arLit (#premLits arcls);
   935 		
   936 
   937 
   938 (*FIXME: would this have variables in a forall? *)
   939 
   940 fun dfg_arity_clause arcls = 
   941   let val arcls_id = string_of_arClauseID arcls
   942       val concl_lit = dfg_of_conclLit arcls
   943       val prems_lits = dfg_of_premLits arcls
   944       val knd = string_of_arKind arcls
   945       val all_lits = concl_lit :: prems_lits
   946   in
   947       "clause( %(" ^ knd ^ ")\n" ^  "or( " ^ (bracket_pack all_lits) ^ ")),\n" ^
   948        arcls_id ^  ")."
   949   end;
   950 
   951 
   952 (********************************)
   953 (* code to produce TPTP files   *)
   954 (********************************)
   955 
   956 fun tptp_literal (Literal(pol,pred,tag)) =
   957     let val pred_string = string_of_predicate pred
   958 	val tagged_pol = 
   959 	      if (tag andalso !tagged) then (if pol then "+++" else "---")
   960 	      else (if pol then "++" else "--")
   961      in
   962 	tagged_pol ^ pred_string
   963     end;
   964 
   965 fun tptp_of_typeLit (LTVar x) = "--" ^ x
   966   | tptp_of_typeLit (LTFree x) = "++" ^ x;
   967  
   968 
   969 fun gen_tptp_cls (cls_id,ax_name,knd,lits) = 
   970     "input_clause(" ^ string_of_clausename (cls_id,ax_name) ^ "," ^ 
   971     knd ^ "," ^ lits ^ ").";
   972 
   973 fun gen_tptp_type_cls (cls_id,ax_name,knd,tfree_lit,idx) = 
   974     "input_clause(" ^ string_of_type_clsname (cls_id,ax_name,idx) ^ "," ^ 
   975     knd ^ ",[" ^ tfree_lit ^ "]).";
   976 
   977 fun tptp_type_lits (Clause cls) = 
   978     let val lits = map tptp_literal (#literals cls)
   979 	val tvar_lits_strs =
   980 	      if !keep_types 
   981 	      then (map tptp_of_typeLit (#tvar_type_literals cls)) 
   982 	      else []
   983 	val tfree_lits = 
   984 	      if !keep_types
   985 	      then (map tptp_of_typeLit (#tfree_type_literals cls)) 
   986 	      else []
   987     in
   988 	(tvar_lits_strs @ lits, tfree_lits)
   989     end; 
   990 
   991 fun tptp_clause cls =
   992     let val (lits,tfree_lits) = tptp_type_lits cls 
   993             (*"lits" includes the typing assumptions (TVars)*)
   994 	val cls_id = get_clause_id cls
   995 	val ax_name = get_axiomName cls
   996 	val knd = string_of_kind cls
   997 	val lits_str = bracket_pack lits
   998 	val cls_str = gen_tptp_cls(cls_id,ax_name,knd,lits_str) 			 
   999 	fun typ_clss k [] = []
  1000           | typ_clss k (tfree :: tfrees) = 
  1001               gen_tptp_type_cls(cls_id,ax_name,knd,tfree,k) :: 
  1002               typ_clss (k+1) tfrees
  1003     in 
  1004 	cls_str :: (typ_clss 0 tfree_lits)
  1005     end;
  1006 
  1007 fun clause2tptp cls =
  1008     let val (lits,tfree_lits) = tptp_type_lits cls 
  1009             (*"lits" includes the typing assumptions (TVars)*)
  1010 	val cls_id = get_clause_id cls
  1011 	val ax_name = get_axiomName cls
  1012 	val knd = string_of_kind cls
  1013 	val lits_str = bracket_pack lits
  1014 	val cls_str = gen_tptp_cls(cls_id,ax_name,knd,lits_str) 
  1015     in
  1016 	(cls_str,tfree_lits) 
  1017     end;
  1018 
  1019 
  1020 fun tfree_clause tfree_lit =
  1021     "input_clause(" ^ "tfree_tcs," ^ "conjecture" ^ ",[" ^ tfree_lit ^ "]).";
  1022 
  1023 
  1024 fun tptp_of_arLit (TConsLit(b,(c,t,args))) =
  1025       let val pol = if b then "++" else "--"
  1026 	  val  arg_strs = paren_pack args
  1027       in 
  1028 	  pol ^ c ^ "(" ^ t ^ arg_strs ^ ")"
  1029       end
  1030   | tptp_of_arLit (TVarLit(b,(c,str))) =
  1031       let val pol = if b then "++" else "--"
  1032       in
  1033 	  pol ^ c ^ "(" ^ str ^ ")"
  1034       end;
  1035     
  1036 
  1037 fun tptp_of_conclLit (ArityClause arcls) = tptp_of_arLit (#conclLit arcls);
  1038      
  1039 fun tptp_of_premLits (ArityClause arcls) = map tptp_of_arLit (#premLits arcls);
  1040 		
  1041 fun tptp_arity_clause arcls = 
  1042     let val arcls_id = string_of_arClauseID arcls
  1043 	val concl_lit = tptp_of_conclLit arcls
  1044 	val prems_lits = tptp_of_premLits arcls
  1045 	val knd = string_of_arKind arcls
  1046 	val all_lits = concl_lit :: prems_lits
  1047     in
  1048 	"input_clause(" ^ arcls_id ^ "," ^ knd ^ "," ^ 
  1049 	(bracket_pack all_lits) ^ ")."
  1050     end;
  1051 
  1052 fun tptp_classrelLits sub sup = 
  1053     let val tvar = "(T)"
  1054     in 
  1055 	case sup of NONE => "[++" ^ sub ^ tvar ^ "]"
  1056 		  | (SOME supcls) =>  "[--" ^ sub ^ tvar ^ ",++" ^ supcls ^ tvar ^ "]"
  1057     end;
  1058 
  1059 
  1060 fun tptp_classrelClause (ClassrelClause {clause_id,subclass,superclass,...}) =
  1061     let val relcls_id = clrelclause_prefix ^ ascii_of subclass ^ "_" ^ 
  1062                         Int.toString clause_id
  1063 	val lits = tptp_classrelLits (make_type_class subclass) 
  1064 	                (Option.map make_type_class superclass)
  1065     in
  1066 	"input_clause(" ^ relcls_id ^ ",axiom," ^ lits ^ ")."
  1067     end; 
  1068 
  1069 end;