src/HOL/Tools/res_hol_clause.ML
author haftmann
Wed Jun 07 16:55:39 2006 +0200 (2006-06-07)
changeset 19818 5c5c1208a3fa
parent 19745 df6fd56d63a9
child 19964 73704ba4bed1
permissions -rw-r--r--
adding case theorems for code generator
     1 (* ID: $Id$ 
     2    Author: Jia Meng, NICTA
     3 
     4 FOL clauses translated from HOL formulae.  Combinators are used to represent lambda terms.
     5 
     6 *)
     7 
     8 structure ResHolClause =
     9 
    10 struct
    11 
    12 
    13 val include_combS = ref false;
    14 val include_min_comb = ref false;
    15 
    16 val const_typargs = ref (Library.K [] : (string*typ -> typ list));
    17 
    18 fun init thy = (include_combS:=false;include_min_comb:=false;const_typargs := Sign.const_typargs thy);
    19 
    20 
    21 
    22 (**********************************************************************)
    23 (* convert a Term.term with lambdas into a Term.term with combinators *) 
    24 (**********************************************************************)
    25 
    26 fun is_free (Bound(a)) n = (a = n)
    27   | is_free (Abs(x,_,b)) n = (is_free b (n+1))
    28   | is_free (P $ Q) n = ((is_free P n) orelse (is_free Q n))
    29   | is_free _ _ = false;
    30 
    31 
    32 exception LAM2COMB of term;
    33 
    34 exception BND of term;
    35 
    36 fun decre_bndVar (Bound n) = Bound (n-1)
    37   | decre_bndVar (P $ Q) = (decre_bndVar P) $ (decre_bndVar Q)
    38   | decre_bndVar t =
    39     case t of Const(_,_) => t
    40 	    | Free(_,_) => t
    41 	    | Var(_,_) => t
    42 	    | Abs(_,_,_) => raise BND(t); (*should not occur*)
    43 
    44 
    45 (*******************************************)
    46 fun lam2comb (Abs(x,tp,Bound 0)) _ = 
    47     let val tpI = Type("fun",[tp,tp])
    48     in 
    49 	include_min_comb:=true;
    50 	Const("COMBI",tpI) 
    51     end
    52   | lam2comb (Abs(x,tp,Bound n)) Bnds = 
    53     let val (Bound n') = decre_bndVar (Bound n)
    54 	val tb = List.nth(Bnds,n')
    55 	val tK = Type("fun",[tb,Type("fun",[tp,tb])])
    56     in
    57 	include_min_comb:=true;
    58 	Const("COMBK",tK) $ (Bound n')
    59     end
    60   | lam2comb (Abs(x,t1,Const(c,t2))) _ = 
    61     let val tK = Type("fun",[t2,Type("fun",[t1,t2])])
    62     in 
    63 	include_min_comb:=true;
    64 	Const("COMBK",tK) $ Const(c,t2) 
    65     end
    66   | lam2comb (Abs(x,t1,Free(v,t2))) _ =
    67     let val tK = Type("fun",[t2,Type("fun",[t1,t2])])
    68     in
    69 	include_min_comb:=true;
    70 	Const("COMBK",tK) $ Free(v,t2)
    71     end
    72   | lam2comb (Abs(x,t1,Var(ind,t2))) _=
    73     let val tK = Type("fun",[t2,Type("fun",[t1,t2])])
    74     in
    75 	include_min_comb:=true;
    76 	Const("COMBK",tK) $ Var(ind,t2)
    77     end
    78   | lam2comb (t as (Abs(x,t1,P$(Bound 0)))) Bnds =
    79     let val nfreeP = not(is_free P 0)
    80 	val tr = Term.type_of1(t1::Bnds,P)
    81     in
    82 	if nfreeP then (decre_bndVar P)
    83 	else (
    84 	      let val tI = Type("fun",[t1,t1])
    85 		  val P' = lam2comb (Abs(x,t1,P)) Bnds
    86 		  val tp' = Term.type_of1(Bnds,P')
    87 		  val tS = Type("fun",[tp',Type("fun",[tI,tr])])
    88 	      in
    89 		  include_min_comb:=true;
    90 		  include_combS:=true;
    91 		  Const("COMBS",tS) $ P' $ Const("COMBI",tI)
    92 	      end)
    93     end
    94 	    
    95   | lam2comb (t as (Abs(x,t1,P$Q))) Bnds =
    96     let val (nfreeP,nfreeQ) = (not(is_free P 0),not(is_free Q 0))
    97 	val tpq = Term.type_of1(t1::Bnds, P$Q) 
    98     in
    99 	if(nfreeP andalso nfreeQ) then (
   100 	    let val tK = Type("fun",[tpq,Type("fun",[t1,tpq])])
   101 		val PQ' = decre_bndVar(P $ Q)
   102 	    in 
   103 		include_min_comb:=true;
   104 		Const("COMBK",tK) $ PQ'
   105 	    end)
   106 	else (
   107 	      if nfreeP then (
   108 			       let val Q' = lam2comb (Abs(x,t1,Q)) Bnds
   109 				   val P' = decre_bndVar P
   110 				   val tp = Term.type_of1(Bnds,P')
   111 				   val tq' = Term.type_of1(Bnds, Q')
   112 				   val tB = Type("fun",[tp,Type("fun",[tq',Type("fun",[t1,tpq])])])
   113 			       in
   114 				   include_min_comb:=true;
   115 				   Const("COMBB",tB) $ P' $ Q' 
   116 			       end)
   117 	      else (
   118 		    if nfreeQ then (
   119 				    let val P' = lam2comb (Abs(x,t1,P)) Bnds
   120 					val Q' = decre_bndVar Q
   121 					val tq = Term.type_of1(Bnds,Q')
   122 					val tp' = Term.type_of1(Bnds, P')
   123 					val tC = Type("fun",[tp',Type("fun",[tq,Type("fun",[t1,tpq])])])
   124 				    in
   125 					include_min_comb:=true;
   126 					Const("COMBC",tC) $ P' $ Q'
   127 				    end)
   128 		    else(
   129 			 let val P' = lam2comb (Abs(x,t1,P)) Bnds
   130 			     val Q' = lam2comb (Abs(x,t1,Q)) Bnds
   131 			     val tp' = Term.type_of1(Bnds,P')
   132 			     val tq' = Term.type_of1(Bnds,Q')
   133 			     val tS = Type("fun",[tp',Type("fun",[tq',Type("fun",[t1,tpq])])])
   134 			 in
   135 			     include_min_comb:=true;
   136 			     include_combS:=true;
   137 			     Const("COMBS",tS) $ P' $ Q'
   138 			 end)))
   139     end
   140   | lam2comb (t as (Abs(x,t1,_))) _ = raise LAM2COMB (t);
   141 
   142 	     
   143 
   144 (*********************)
   145 
   146 fun to_comb (Abs(x,tp,b)) Bnds =
   147     let val b' = to_comb b (tp::Bnds)
   148     in lam2comb (Abs(x,tp,b')) Bnds end
   149   | to_comb (P $ Q) Bnds = ((to_comb P Bnds) $ (to_comb Q Bnds))
   150   | to_comb t _ = t;
   151  
   152     
   153 fun comb_of t = to_comb t [];
   154 
   155 
   156 (* print a term containing combinators, used for debugging *)
   157 exception TERM_COMB of term;
   158 
   159 fun string_of_term (Const(c,t)) = c
   160   | string_of_term (Free(v,t)) = v
   161   | string_of_term (Var((x,n),t)) =
   162     let val xn = x ^ "_" ^ (string_of_int n)
   163     in xn end
   164   | string_of_term (P $ Q) =
   165     let val P' = string_of_term P
   166 	val Q' = string_of_term Q
   167     in
   168 	"(" ^ P' ^ " " ^ Q' ^ ")" end
   169   | string_of_term t =  raise TERM_COMB (t);
   170 
   171 
   172 
   173 (******************************************************)
   174 (* data types for typed combinator expressions        *)
   175 (******************************************************)
   176 
   177 type axiom_name = string;
   178 datatype kind = Axiom | Conjecture;
   179 fun name_of_kind Axiom = "axiom"
   180   | name_of_kind Conjecture = "conjecture";
   181 
   182 type polarity = bool;
   183 type indexname = Term.indexname;
   184 type clause_id = int;
   185 type csort = Term.sort;
   186 type ctyp = ResClause.fol_type;
   187 
   188 val string_of_ctyp = ResClause.string_of_fol_type;
   189 
   190 type ctyp_var = ResClause.typ_var;
   191 
   192 type ctype_literal = ResClause.type_literal;
   193 
   194 
   195 datatype combterm = CombConst of string * ctyp * ctyp list
   196 		  | CombFree of string * ctyp
   197 		  | CombVar of string * ctyp
   198 		  | CombApp of combterm * combterm * ctyp
   199 		  | Bool of combterm;
   200 datatype literal = Literal of polarity * combterm;
   201 
   202 
   203 
   204 datatype clause = 
   205 	 Clause of {clause_id: clause_id,
   206 		    axiom_name: axiom_name,
   207 		    kind: kind,
   208 		    literals: literal list,
   209 		    ctypes_sorts: (ctyp_var * csort) list, 
   210                     ctvar_type_literals: ctype_literal list, 
   211                     ctfree_type_literals: ctype_literal list};
   212 
   213 
   214 
   215 fun string_of_kind (Clause cls) = name_of_kind (#kind cls);
   216 fun get_axiomName (Clause cls) = #axiom_name cls;
   217 fun get_clause_id (Clause cls) = #clause_id cls;
   218 
   219 fun get_literals (c as Clause(cls)) = #literals cls;
   220 
   221 
   222 
   223 exception TERM_ORD of string
   224 
   225 fun term_ord (CombVar(_,_),CombVar(_,_)) = EQUAL
   226   | term_ord (CombVar(_,_),_) = LESS
   227   | term_ord (CombFree(_,_),CombVar(_,_)) = GREATER
   228   | term_ord (CombFree(f1,tp1),CombFree(f2,tp2)) = 
   229     let val ord1 = string_ord(f1,f2)
   230     in
   231 	case ord1 of EQUAL => ResClause.types_ord ([tp1],[tp2])
   232 		   | _ => ord1
   233     end
   234   | term_ord (CombFree(_,_),_) = LESS
   235   | term_ord (CombConst(_,_,_),CombVar(_,_)) = GREATER
   236   | term_ord (CombConst(_,_,_),CombFree(_,_)) = GREATER
   237   | term_ord (CombConst(c1,tp1,_),CombConst(c2,tp2,_)) = 
   238     let val ord1 = string_ord (c1,c2)
   239     in
   240 	case ord1 of EQUAL => ResClause.types_ord ([tp1],[tp2])
   241 		   | _ => ord1
   242     end
   243   | term_ord (CombConst(_,_,_),_) = LESS
   244   | term_ord (CombApp(_,_,_),Bool(_)) = raise TERM_ORD("bool")
   245   | term_ord (CombApp(f1,arg1,tp1),CombApp(f2,arg2,tp2)) =
   246     let val ord1 = term_ord (f1,f2)
   247 	val ord2 = case ord1 of EQUAL => term_ord (arg1,arg2)
   248 			      | _ => ord1
   249     in
   250 	case ord2 of EQUAL => ResClause.types_ord ([tp1],[tp2])
   251 		   | _ => ord2
   252     end
   253   | term_ord (CombApp(_,_,_),_) = GREATER
   254   | term_ord (Bool(_),_) = raise TERM_ORD("bool");
   255 
   256 fun predicate_ord (Bool(t1),Bool(t2)) = term_ord (t1,t2)
   257 
   258 
   259 fun literal_ord (Literal(false,_),Literal(true,_)) = LESS
   260   | literal_ord (Literal(true,_),Literal(false,_)) = GREATER
   261   | literal_ord (Literal(_,pred1),Literal(_,pred2)) = predicate_ord(pred1,pred2);
   262 
   263 fun sort_lits lits = sort literal_ord lits;
   264 
   265 (*********************************************************************)
   266 (* convert a clause with type Term.term to a clause with type clause *)
   267 (*********************************************************************)
   268 
   269 fun isFalse (Literal(pol,Bool(CombConst(c,_,_)))) =
   270     (pol andalso c = "c_False") orelse
   271     (not pol andalso c = "c_True")
   272   | isFalse _ = false;
   273 
   274 
   275 fun isTrue (Literal (pol,Bool(CombConst(c,_,_)))) =
   276       (pol andalso c = "c_True") orelse
   277       (not pol andalso c = "c_False")
   278   | isTrue _ = false;
   279   
   280 fun isTaut (Clause {literals,...}) = exists isTrue literals;  
   281 
   282 
   283 
   284 fun make_clause(clause_id,axiom_name,kind,literals,ctypes_sorts,ctvar_type_literals,ctfree_type_literals) =
   285     if forall isFalse literals
   286     then error "Problem too trivial for resolution (empty clause)"
   287     else
   288 	Clause {clause_id = clause_id, axiom_name = axiom_name, kind = kind,
   289 		literals = literals, ctypes_sorts = ctypes_sorts, 
   290 		ctvar_type_literals = ctvar_type_literals,
   291 		ctfree_type_literals = ctfree_type_literals};
   292 
   293 fun type_of (Type (a, Ts)) =
   294     let val (folTypes,ts) = types_of Ts
   295 	val t = ResClause.make_fixed_type_const a
   296     in
   297 	(ResClause.mk_fol_type("Comp",t,folTypes),ts)
   298     end
   299   | type_of (tp as (TFree(a,s))) =
   300     let val t = ResClause.make_fixed_type_var a
   301     in
   302 	(ResClause.mk_fol_type("Fixed",t,[]),[ResClause.mk_typ_var_sort tp])
   303     end
   304   | type_of (tp as (TVar(v,s))) =
   305     let val t = ResClause.make_schematic_type_var v
   306     in
   307 	(ResClause.mk_fol_type("Var",t,[]),[ResClause.mk_typ_var_sort tp])
   308     end
   309 
   310 and types_of Ts =
   311     let val foltyps_ts = map type_of Ts
   312 	val (folTyps,ts) = ListPair.unzip foltyps_ts
   313     in
   314 	(folTyps,ResClause.union_all ts)
   315     end;
   316 
   317 (* same as above, but no gathering of sort information *)
   318 fun simp_type_of (Type (a, Ts)) = 
   319     let val typs = map simp_type_of Ts
   320 	val t = ResClause.make_fixed_type_const a
   321     in
   322 	ResClause.mk_fol_type("Comp",t,typs)
   323     end
   324   | simp_type_of (TFree (a,s)) = ResClause.mk_fol_type("Fixed",ResClause.make_fixed_type_var a,[])
   325   | simp_type_of (TVar (v,s)) = ResClause.mk_fol_type("Var",ResClause.make_schematic_type_var v,[]);
   326 
   327 fun comb_typ ("COMBI",t) = 
   328     let val t' = domain_type t
   329     in
   330 	[simp_type_of t']
   331     end
   332   | comb_typ ("COMBK",t) = 
   333     let val a = domain_type t
   334 	val b = domain_type (range_type t)
   335     in
   336 	map simp_type_of [a,b]
   337     end
   338   | comb_typ ("COMBS",t) = 
   339     let val t' = domain_type t
   340 	val a = domain_type t'
   341 	val b = domain_type (range_type t')
   342 	val c = range_type (range_type t')
   343     in 
   344 	map simp_type_of [a,b,c]
   345     end
   346   | comb_typ ("COMBB",t) = 
   347     let val ab = domain_type t
   348 	val ca = domain_type (range_type t)
   349 	val a = domain_type ab
   350 	val b = range_type ab
   351 	val c = domain_type ca
   352     in
   353 	map simp_type_of [a,b,c]
   354     end
   355   | comb_typ ("COMBC",t) =
   356     let val t1 = domain_type t
   357 	val a = domain_type t1
   358 	val b = domain_type (range_type t1)
   359 	val c = range_type (range_type t1)
   360     in
   361 	map simp_type_of [a,b,c]
   362     end;
   363 
   364 fun const_type_of ("COMBI",t) = 
   365     let val (tp,ts) = type_of t
   366 	val I_var = comb_typ ("COMBI",t)
   367     in
   368 	(tp,ts,I_var)
   369     end
   370   | const_type_of ("COMBK",t) =
   371     let val (tp,ts) = type_of t
   372 	val K_var = comb_typ ("COMBK",t)
   373     in
   374 	(tp,ts,K_var)
   375     end
   376   | const_type_of ("COMBS",t) =
   377     let val (tp,ts) = type_of t
   378 	val S_var = comb_typ ("COMBS",t)
   379     in
   380 	(tp,ts,S_var)
   381     end
   382   | const_type_of ("COMBB",t) =
   383     let val (tp,ts) = type_of t
   384 	val B_var = comb_typ ("COMBB",t)
   385     in
   386 	(tp,ts,B_var)
   387     end
   388   | const_type_of ("COMBC",t) =
   389     let val (tp,ts) = type_of t
   390 	val C_var = comb_typ ("COMBC",t)
   391     in
   392 	(tp,ts,C_var)
   393     end
   394   | const_type_of (c,t) =
   395     let val (tp,ts) = type_of t
   396 	val tvars = !const_typargs(c,t)
   397 	val tvars' = map simp_type_of tvars
   398     in
   399 	(tp,ts,tvars')
   400     end;
   401 
   402 fun is_bool_type (Type("bool",[])) = true
   403   | is_bool_type _ = false;
   404 
   405 
   406 (* convert a Term.term (with combinators) into a combterm, also accummulate sort info *)
   407 fun combterm_of (Const(c,t)) =
   408     let val (tp,ts,tvar_list) = const_type_of (c,t)
   409 	val is_bool = is_bool_type t
   410 	val c' = CombConst(ResClause.make_fixed_const c,tp,tvar_list)
   411 	val c'' = if is_bool then Bool(c') else c'
   412     in
   413 	(c'',ts)
   414     end
   415   | combterm_of (Free(v,t)) =
   416     let val (tp,ts) = type_of t
   417 	val is_bool = is_bool_type t
   418 	val v' = if ResClause.isMeta v then CombVar(ResClause.make_schematic_var(v,0),tp)
   419 		 else CombFree(ResClause.make_fixed_var v,tp)
   420 	val v'' = if is_bool then Bool(v') else v'
   421     in
   422 	(v'',ts)
   423     end
   424   | combterm_of (Var(v,t)) =
   425     let val (tp,ts) = type_of t
   426 	val is_bool = is_bool_type t
   427 	val v' = CombVar(ResClause.make_schematic_var v,tp)
   428 	val v'' = if is_bool then Bool(v') else v'
   429     in
   430 	(v'',ts)
   431     end
   432   | combterm_of (t as (P $ Q)) =
   433     let val (P',tsP) = combterm_of P
   434 	val (Q',tsQ) = combterm_of Q
   435 	val tp = Term.type_of t
   436 	val tp' = simp_type_of tp
   437 	val is_bool = is_bool_type tp
   438 	val t' = CombApp(P',Q',tp')
   439 	val t'' = if is_bool then Bool(t') else t'
   440     in
   441 	(t'',tsP union tsQ)
   442     end;
   443 
   444 fun predicate_of ((Const("Not",_) $ P), polarity) =
   445     predicate_of (P, not polarity)
   446   | predicate_of (term,polarity) = (combterm_of term,polarity);
   447 
   448 
   449 fun literals_of_term1 args (Const("Trueprop",_) $ P) = literals_of_term1 args P
   450   | literals_of_term1 args (Const("op |",_) $ P $ Q) = 
   451     let val args' = literals_of_term1 args P
   452     in
   453 	literals_of_term1 args' Q
   454     end
   455   | literals_of_term1 (lits,ts) P =
   456     let val ((pred,ts'),pol) = predicate_of (P,true)
   457 	val lits' = Literal(pol,pred)::lits
   458     in
   459 	(lits',ts union ts')
   460     end;
   461 
   462 
   463 fun literals_of_term P = literals_of_term1 ([],[]) P;
   464 
   465 
   466 (* making axiom and conjecture clauses *)
   467 fun make_axiom_clause thm (ax_name,cls_id) =
   468     let val term = prop_of thm
   469 	val term' = comb_of term
   470 	val (lits,ctypes_sorts) = literals_of_term term'
   471 	val lits' = sort_lits lits
   472 	val (ctvar_lits,ctfree_lits) = ResClause.add_typs_aux ctypes_sorts
   473     in
   474 	make_clause(cls_id,ax_name,Axiom,
   475 		    lits',ctypes_sorts,ctvar_lits,ctfree_lits)
   476     end;
   477 
   478 fun make_axiom_clauses [] = []
   479   | make_axiom_clauses ((thm,(name,id))::thms) =
   480     let val cls = make_axiom_clause thm (name,id)
   481 	val clss = make_axiom_clauses thms
   482     in
   483 	if isTaut cls then clss else (cls::clss)
   484     end;
   485 
   486 
   487 fun make_conjecture_clause n thm =
   488     let val t = prop_of thm
   489 	val t' = comb_of t
   490 	val (lits,ctypes_sorts) = literals_of_term t'
   491 	val (ctvar_lits,ctfree_lits) = ResClause.add_typs_aux ctypes_sorts
   492     in
   493 	make_clause(n,"conjecture",Conjecture,lits,ctypes_sorts,ctvar_lits,ctfree_lits)
   494     end;
   495 
   496 
   497 
   498 fun make_conjecture_clauses_aux _ [] = []
   499   | make_conjecture_clauses_aux n (t::ts) =
   500     make_conjecture_clause n t :: make_conjecture_clauses_aux (n+1) ts;
   501 
   502 val make_conjecture_clauses = make_conjecture_clauses_aux 0;
   503 
   504 
   505 (**********************************************************************)
   506 (* convert clause into ATP specific formats:                          *)
   507 (* TPTP used by Vampire and E                                         *)
   508 (* DFG used by SPASS                                                  *)
   509 (**********************************************************************)
   510 
   511 val type_wrapper = "typeinfo";
   512 
   513 datatype type_level = T_FULL | T_PARTIAL | T_CONST | T_NONE;
   514 
   515 val typ_level = ref T_CONST;
   516 
   517 fun full_types () = (typ_level:=T_FULL);
   518 fun partial_types () = (typ_level:=T_PARTIAL);
   519 fun const_types_only () = (typ_level:=T_CONST);
   520 fun no_types () = (typ_level:=T_NONE);
   521 
   522 
   523 fun find_typ_level () = !typ_level;
   524 
   525 fun wrap_type (c,t) = 
   526     case !typ_level of T_FULL => type_wrapper ^ (ResClause.paren_pack [c,t])
   527 		     | _ => c;
   528     
   529 
   530 val bool_tp = ResClause.make_fixed_type_const "bool";
   531 
   532 val app_str = "hAPP";
   533 
   534 val bool_str = "hBOOL";
   535 
   536 exception STRING_OF_COMBTERM of int;
   537 
   538 (* convert literals of clauses into strings *)
   539 fun string_of_combterm1_aux _ (CombConst(c,tp,_)) = 
   540     let val tp' = string_of_ctyp tp
   541 	val c' = if c = "equal" then "fequal" else c
   542     in
   543 	(wrap_type (c',tp'),tp')
   544     end
   545   | string_of_combterm1_aux _ (CombFree(v,tp)) = 
   546     let val tp' = string_of_ctyp tp
   547     in
   548 	(wrap_type (v,tp'),tp')
   549     end
   550   | string_of_combterm1_aux _ (CombVar(v,tp)) = 
   551     let val tp' = string_of_ctyp tp
   552     in
   553 	(wrap_type (v,tp'),tp')
   554     end
   555   | string_of_combterm1_aux is_pred (CombApp(t1,t2,tp)) =
   556     let val (s1,tp1) = string_of_combterm1_aux is_pred t1
   557 	val (s2,tp2) = string_of_combterm1_aux is_pred t2
   558 	val tp' = ResClause.string_of_fol_type tp
   559 	val r =	case !typ_level of T_FULL => type_wrapper ^  (ResClause.paren_pack [(app_str ^ (ResClause.paren_pack [s1,s2])),tp'])
   560 				 | T_PARTIAL => app_str ^ (ResClause.paren_pack [s1,s2,tp1])
   561 				 | T_NONE => app_str ^ (ResClause.paren_pack [s1,s2])
   562 				 | T_CONST => raise STRING_OF_COMBTERM (1) (*should not happen, if happened may be a bug*)
   563     in	(r,tp')
   564 
   565     end
   566   | string_of_combterm1_aux is_pred (Bool(CombApp(CombApp(CombConst("equal",tp,tps),t1,tp1),t2,tp2))) =
   567     if is_pred then 
   568 	let val (s1,_) = string_of_combterm1_aux false t1
   569 	    val (s2,_) = string_of_combterm1_aux false t2
   570 	in
   571 	    ("equal" ^ (ResClause.paren_pack [s1,s2]),bool_tp)
   572 	end
   573     else
   574 	let val (t,_) = string_of_combterm1_aux false (CombApp(CombApp(CombConst("equal",tp,tps),t1,tp1),t2,tp2))
   575 	in
   576 	    (t,bool_tp)
   577 	end
   578   | string_of_combterm1_aux is_pred (Bool(t)) = 
   579     let val (t',_) = string_of_combterm1_aux false t
   580 	val r = if is_pred then bool_str ^ (ResClause.paren_pack [t'])
   581 		else t'
   582     in
   583 	(r,bool_tp)
   584     end;
   585 
   586 fun string_of_combterm1 is_pred term = fst (string_of_combterm1_aux is_pred term);
   587 
   588 fun string_of_combterm2 _ (CombConst(c,tp,tvars)) = 
   589     let val tvars' = map string_of_ctyp tvars
   590 	val c' = if c = "equal" then "fequal" else c
   591     in
   592 	c' ^ (ResClause.paren_pack tvars')
   593     end
   594   | string_of_combterm2 _ (CombFree(v,tp)) = v
   595   | string_of_combterm2 _ (CombVar(v,tp)) = v
   596   | string_of_combterm2 is_pred (CombApp(t1,t2,tp)) =
   597     let val s1 = string_of_combterm2 is_pred t1
   598 	val s2 = string_of_combterm2 is_pred t2
   599     in
   600 	app_str ^ (ResClause.paren_pack [s1,s2])
   601     end
   602   | string_of_combterm2 is_pred (Bool(CombApp(CombApp(CombConst("equal",tp,tps),t1,tp1),t2,tp2))) =
   603     if is_pred then 
   604 	let val s1 = string_of_combterm2 false t1
   605 	    val s2 = string_of_combterm2 false t2
   606 	in
   607 	    ("equal" ^ (ResClause.paren_pack [s1,s2]))
   608 	end
   609     else
   610 	string_of_combterm2 false (CombApp(CombApp(CombConst("equal",tp,tps),t1,tp1),t2,tp2))
   611  
   612   | string_of_combterm2 is_pred (Bool(t)) = 
   613     let val t' = string_of_combterm2 false t
   614     in
   615 	if is_pred then bool_str ^ (ResClause.paren_pack [t'])
   616 	else t'
   617     end;
   618 
   619 
   620 
   621 fun string_of_combterm is_pred term = 
   622     case !typ_level of T_CONST => string_of_combterm2 is_pred term
   623 		     | _ => string_of_combterm1 is_pred term;
   624 
   625 
   626 fun string_of_clausename (cls_id,ax_name) = 
   627     ResClause.clause_prefix ^ ResClause.ascii_of ax_name ^ "_" ^ Int.toString cls_id;
   628 
   629 fun string_of_type_clsname (cls_id,ax_name,idx) = 
   630     string_of_clausename (cls_id,ax_name) ^ "_tcs" ^ (Int.toString idx);
   631 
   632 
   633 (* tptp format *)
   634 
   635 fun tptp_literal (Literal(pol,pred)) =
   636     let val pred_string = string_of_combterm true pred
   637 	val pol_str = if pol then "++" else "--"
   638     in
   639 	pol_str ^ pred_string
   640     end;
   641 
   642  
   643 fun tptp_type_lits (Clause cls) = 
   644     let val lits = map tptp_literal (#literals cls)
   645 	val ctvar_lits_strs =
   646 	    case !typ_level of T_NONE => []
   647 			     | _ => (map ResClause.tptp_of_typeLit (#ctvar_type_literals cls)) 
   648 	val ctfree_lits = 
   649 	    case !typ_level of T_NONE => []
   650 			     | _ => (map ResClause.tptp_of_typeLit (#ctfree_type_literals cls)) 
   651     in
   652 	(ctvar_lits_strs @ lits, ctfree_lits)
   653     end; 
   654     
   655     
   656 fun clause2tptp cls =
   657     let val (lits,ctfree_lits) = tptp_type_lits cls
   658 	val cls_id = get_clause_id cls
   659 	val ax_name = get_axiomName cls
   660 	val knd = string_of_kind cls
   661 	val lits_str = ResClause.bracket_pack lits
   662 	val cls_str = ResClause.gen_tptp_cls(cls_id,ax_name,knd,lits_str)
   663     in
   664 	(cls_str,ctfree_lits)
   665     end;
   666 
   667 
   668 (* dfg format *)
   669 fun dfg_literal (Literal(pol,pred)) = ResClause.dfg_sign pol (string_of_combterm true pred);
   670 
   671 fun dfg_clause_aux (Clause{literals, ctypes_sorts, ...}) = 
   672   let val lits = map dfg_literal literals
   673       val (tvar_lits,tfree_lits) = ResClause.add_typs_aux ctypes_sorts
   674       val tvar_lits_strs = 
   675 	  case !typ_level of T_NONE => [] 
   676 			    | _ => map ResClause.dfg_of_typeLit tvar_lits
   677       val tfree_lits =
   678           case !typ_level of T_NONE => []
   679 			    | _ => map ResClause.dfg_of_typeLit tfree_lits 
   680   in
   681       (tvar_lits_strs @ lits, tfree_lits)
   682   end; 
   683 
   684 fun get_uvars (CombConst(_,_,_)) vars = vars
   685   | get_uvars (CombFree(_,_)) vars = vars
   686   | get_uvars (CombVar(v,tp)) vars = (v::vars)
   687   | get_uvars (CombApp(P,Q,tp)) vars = get_uvars P (get_uvars Q vars)
   688   | get_uvars (Bool(c)) vars = get_uvars c vars;
   689 
   690 
   691 fun get_uvars_l (Literal(_,c)) = get_uvars c [];
   692 
   693 fun dfg_vars (Clause {literals,...}) = ResClause.union_all (map get_uvars_l literals);
   694  
   695 fun clause2dfg (cls as Clause{axiom_name,clause_id,kind,ctypes_sorts,...}) =
   696     let val (lits,tfree_lits) = dfg_clause_aux cls 
   697         val vars = dfg_vars cls
   698         val tvars = ResClause.get_tvar_strs ctypes_sorts
   699 	val knd = name_of_kind kind
   700 	val lits_str = commas lits
   701 	val cls_str = ResClause.gen_dfg_cls(clause_id, axiom_name, knd, lits_str, tvars@vars) 
   702     in (cls_str, tfree_lits) end;
   703 
   704 
   705 fun init_combs (comb,funcs) =
   706     case !typ_level of T_CONST => 
   707 		       (case comb of "c_COMBK" => Symtab.update (comb,2) funcs
   708 				   | "c_COMBS" => Symtab.update (comb,3) funcs
   709 				   | "c_COMBI" => Symtab.update (comb,1) funcs
   710 				   | "c_COMBB" => Symtab.update (comb,3) funcs
   711 				   | "c_COMBC" => Symtab.update (comb,3) funcs
   712 				   | _ => funcs)
   713 		     | _ => Symtab.update (comb,0) funcs;
   714 
   715 fun init_funcs_tab funcs = 
   716     let val tp = !typ_level
   717 	val funcs0 = foldl init_combs funcs ["c_COMBK","c_COMBS","c_COMBI","c_COMBB","c_COMBC"]
   718 	val funcs1 = case tp of T_PARTIAL => Symtab.update ("hAPP",3) funcs0
   719 				      | _ => Symtab.update ("hAPP",2) funcs0
   720 	val funcs2 = case tp of T_FULL => Symtab.update ("typeinfo",2) funcs1
   721 				      | _ => funcs1
   722     in
   723 	case tp of T_CONST => Symtab.update ("fequal",1) (Symtab.update ("hEXTENT",2) funcs2)
   724 			 | _ => Symtab.update ("fequal",0) (Symtab.update ("hEXTENT",0) funcs2)
   725     end;
   726 
   727 
   728 fun add_funcs (CombConst(c,_,tvars),funcs) =
   729     if c = "equal" then foldl ResClause.add_foltype_funcs funcs tvars
   730     else
   731 	(case !typ_level of T_CONST => foldl ResClause.add_foltype_funcs (Symtab.update(c,length tvars) funcs) tvars
   732 			  | _ => foldl ResClause.add_foltype_funcs (Symtab.update(c,0) funcs) tvars)
   733   | add_funcs (CombFree(v,ctp),funcs) = ResClause.add_foltype_funcs (ctp,Symtab.update (v,0) funcs) 
   734   | add_funcs (CombVar(_,ctp),funcs) = ResClause.add_foltype_funcs (ctp,funcs)
   735   | add_funcs (CombApp(P,Q,_),funcs) = add_funcs(P,add_funcs (Q,funcs))
   736   | add_funcs (Bool(t),funcs) = add_funcs (t,funcs);
   737 
   738 
   739 fun add_literal_funcs (Literal(_,c), funcs) = add_funcs (c,funcs);
   740 
   741 fun add_clause_funcs (Clause {literals, ...}, funcs) =
   742     foldl add_literal_funcs funcs literals
   743     handle Symtab.DUP a => raise ERROR ("function " ^ a ^ " has multiple arities")
   744 
   745 fun funcs_of_clauses clauses arity_clauses =
   746     Symtab.dest (foldl ResClause.add_arityClause_funcs 
   747                        (foldl add_clause_funcs (init_funcs_tab Symtab.empty) clauses)
   748                        arity_clauses)
   749 
   750 fun preds_of clsrel_clauses arity_clauses = 
   751     Symtab.dest
   752 	(foldl ResClause.add_classrelClause_preds 
   753 	       (foldl ResClause.add_arityClause_preds
   754 		      (Symtab.update ("hBOOL",1) Symtab.empty)
   755 		      arity_clauses)
   756 	       clsrel_clauses)
   757 
   758 
   759 (**********************************************************************)
   760 (* clause equalities and hashing functions                            *)
   761 (**********************************************************************)
   762 
   763 
   764 fun combterm_eq (CombConst(c1,tp1,tps1),CombConst(c2,tp2,tps2)) vtvars =
   765     let val (eq1,vtvars1) = if c1 = c2 then ResClause.types_eq (tps1,tps2) vtvars
   766 			    else (false,vtvars)
   767     in
   768 	(eq1,vtvars1)
   769     end
   770   | combterm_eq (CombConst(_,_,_),_) vtvars = (false,vtvars)
   771   | combterm_eq (CombFree(a1,tp1),CombFree(a2,tp2)) vtvars = 
   772     if a1 = a2 then ResClause.types_eq ([tp1],[tp2]) vtvars
   773     else (false,vtvars)
   774   | combterm_eq (CombFree(_,_),_) vtvars = (false,vtvars)
   775   | combterm_eq (CombVar(v1,tp1),CombVar(v2,tp2)) (vars,tvars) = 
   776     (case ResClause.check_var_pairs(v1,v2) vars of 0 => ResClause.types_eq ([tp1],[tp2]) ((v1,v2)::vars,tvars)
   777 						 | 1 => ResClause.types_eq ([tp1],[tp2]) (vars,tvars)
   778 						 | 2 => (false,(vars,tvars)))
   779   | combterm_eq (CombVar(_,_),_) vtvars = (false,vtvars)
   780   | combterm_eq (CombApp(f1,arg1,tp1),CombApp(f2,arg2,tp2)) vtvars =
   781     let val (eq1,vtvars1) = combterm_eq (f1,f2) vtvars
   782 	val (eq2,vtvars2) = if eq1 then combterm_eq (arg1,arg2) vtvars1
   783 			    else (eq1,vtvars1)
   784     in
   785 	if eq2 then ResClause.types_eq ([tp1],[tp2]) vtvars2
   786 	else (eq2,vtvars2)
   787     end
   788   | combterm_eq (CombApp(_,_,_),_) vtvars = (false,vtvars)
   789   | combterm_eq (Bool(t1),Bool(t2)) vtvars = combterm_eq (t1,t2) vtvars
   790   | combterm_eq (Bool(_),_) vtvars = (false,vtvars);
   791 
   792 fun lit_eq (Literal(pol1,pred1),Literal(pol2,pred2)) vtvars =
   793     if (pol1 = pol2) then combterm_eq (pred1,pred2) vtvars
   794     else (false,vtvars);
   795 
   796 fun lits_eq ([],[]) vtvars = (true,vtvars)
   797   | lits_eq (l1::ls1,l2::ls2) vtvars = 
   798     let val (eq1,vtvars1) = lit_eq (l1,l2) vtvars
   799     in
   800 	if eq1 then lits_eq (ls1,ls2) vtvars1
   801 	else (false,vtvars1)
   802     end;
   803 
   804 fun clause_eq (cls1,cls2) =
   805     let val lits1 = get_literals cls1
   806 	val lits2 = get_literals cls2
   807     in
   808 	length lits1 = length lits2 andalso #1 (lits_eq (lits1,lits2) ([],[]))
   809     end;
   810 
   811 val xor_words = List.foldl Word.xorb 0w0;
   812 
   813 fun hash_combterm (CombVar(_,_),w) = w
   814   | hash_combterm (CombFree(f,_),w) = Polyhash.hashw_string(f,w)
   815   | hash_combterm (CombConst(c,tp,tps),w) = Polyhash.hashw_string(c,w)
   816   | hash_combterm (CombApp(f,arg,tp),w) = hash_combterm (arg, hash_combterm (f,w))
   817   | hash_combterm (Bool(t),w) = hash_combterm (t,w);
   818 
   819 fun hash_literal (Literal(true,pred)) = hash_combterm(pred,0w0)
   820   | hash_literal (Literal(false,pred)) = Word.notb(hash_combterm(pred,0w0));
   821 
   822 fun hash_clause clause = xor_words (map hash_literal (get_literals clause));
   823 
   824 (**********************************************************************)
   825 (* write clauses to files                                             *)
   826 (**********************************************************************)
   827 
   828 (* tptp format *)
   829 
   830 fun read_in fs = map (File.read o File.unpack_platform_path) fs; 
   831 
   832 fun get_helper_clauses_tptp () =
   833   let val tlevel = case !typ_level of 
   834 		       T_FULL => (Output.debug "Fully-typed HOL"; 
   835 				  "~~/src/HOL/Tools/atp-inputs/full_")
   836 		     | T_PARTIAL => (Output.debug "Partially-typed HOL"; 
   837 				     "~~/src/HOL/Tools/atp-inputs/par_")
   838 		     | T_CONST => (Output.debug "Const-only-typed HOL"; 
   839 				   "~~/src/HOL/Tools/atp-inputs/const_")
   840 		     | T_NONE => (Output.debug "Untyped HOL"; 
   841 				  "~~/src/HOL/Tools/atp-inputs/u_")
   842       val helpers = if !include_combS 
   843                     then (Output.debug "Include combinator S"; 
   844                           ["helper1.tptp","comb_inclS.tptp"]) 
   845                     else if !include_min_comb 
   846                     then (Output.debug "Include min combinators"; 
   847                           ["helper1.tptp","comb_noS.tptp"])
   848 		    else (Output.debug "No combinator is used"; ["helper1.tptp"])
   849       val t_helpers = map (curry (op ^) tlevel) helpers
   850   in
   851       read_in t_helpers
   852   end;
   853 	
   854 						  
   855 (* write TPTP format to a single file *)
   856 (* when "get_helper_clauses" is called, "include_combS" and "include_min_comb" should have correct values already *)
   857 fun tptp_write_file thms filename (axclauses,classrel_clauses,arity_clauses) =
   858     let val clss = make_conjecture_clauses thms
   859 	val axclauses' = make_axiom_clauses axclauses
   860 	val (tptp_clss,tfree_litss) = ListPair.unzip (map clause2tptp clss)
   861 	val tfree_clss = map ResClause.tptp_tfree_clause (foldl (op union_string) [] tfree_litss)
   862 	val out = TextIO.openOut filename
   863 	val helper_clauses = get_helper_clauses_tptp ()
   864     in
   865 	List.app (curry TextIO.output out o #1 o clause2tptp) axclauses';
   866 	ResClause.writeln_strs out tfree_clss;
   867 	ResClause.writeln_strs out tptp_clss;
   868 	List.app (curry TextIO.output out o ResClause.tptp_classrelClause) classrel_clauses;
   869 	List.app (curry TextIO.output out o ResClause.tptp_arity_clause) arity_clauses;
   870 	List.app (curry TextIO.output out) helper_clauses;
   871 	TextIO.closeOut out
   872     end;
   873 
   874 
   875 (* dfg format *)
   876 fun get_helper_clauses_dfg () = 
   877  let val tlevel = case !typ_level of 
   878                       T_FULL => (Output.debug "Fully-typed HOL"; 
   879                                  "~~/src/HOL/Tools/atp-inputs/full_")
   880 		    | T_PARTIAL => (Output.debug "Partially-typed HOL"; 
   881 		                    "~~/src/HOL/Tools/atp-inputs/par_")
   882 		    | T_CONST => (Output.debug "Const-only-typed HOL"; 
   883 		                  "~~/src/HOL/Tools/atp-inputs/const_")
   884 		    | T_NONE => (Output.debug "Untyped HOL"; 
   885 		                 "~~/src/HOL/Tools/atp-inputs/u_")
   886      val helpers = if !include_combS 
   887                    then (Output.debug "Include combinator S"; 
   888                          ["helper1.dfg","comb_inclS.dfg"]) else
   889 		   if !include_min_comb 
   890 		   then (Output.debug "Include min combinators"; 
   891 		         ["helper1.dfg","comb_noS.dfg"])
   892 		   else (Output.debug "No combinator is used"; ["helper1.dfg"])
   893      val t_helpers = map (curry (op ^) tlevel) helpers
   894  in
   895      read_in t_helpers
   896  end;
   897 
   898 
   899 fun dfg_write_file  thms filename (axclauses,classrel_clauses,arity_clauses) =
   900     let val _ = Output.debug ("Preparing to write the DFG file " ^ filename) 
   901 	val conjectures = make_conjecture_clauses thms
   902 	val axclauses' = make_axiom_clauses axclauses
   903 	val (dfg_clss,tfree_litss) = ListPair.unzip (map clause2dfg conjectures)
   904 	val clss = conjectures @ axclauses'
   905 	val funcs = funcs_of_clauses clss arity_clauses
   906 	and preds = preds_of classrel_clauses arity_clauses
   907 	and probname = Path.pack (Path.base (Path.unpack filename))
   908 	val (axstrs,_) =  ListPair.unzip (map clause2dfg axclauses')
   909 	val tfree_clss = map ResClause.dfg_tfree_clause (ResClause.union_all tfree_litss)
   910 	val out = TextIO.openOut filename
   911 	val helper_clauses = get_helper_clauses_dfg ()
   912     in
   913 	TextIO.output (out, ResClause.string_of_start probname); 
   914 	TextIO.output (out, ResClause.string_of_descrip probname); 
   915 	TextIO.output (out, ResClause.string_of_symbols (ResClause.string_of_funcs funcs) (ResClause.string_of_preds preds)); 
   916 	TextIO.output (out, "list_of_clauses(axioms,cnf).\n");
   917 	ResClause.writeln_strs out axstrs;
   918 	List.app (curry TextIO.output out o ResClause.dfg_classrelClause) classrel_clauses;
   919 	List.app (curry TextIO.output out o ResClause.dfg_arity_clause) arity_clauses;
   920 	ResClause.writeln_strs out helper_clauses;
   921 	TextIO.output (out, "end_of_list.\n\nlist_of_clauses(conjectures,cnf).\n");
   922 	ResClause.writeln_strs out tfree_clss;
   923 	ResClause.writeln_strs out dfg_clss;
   924 	TextIO.output (out, "end_of_list.\n\nend_problem.\n");
   925 	TextIO.closeOut out
   926     end;
   927 
   928 end