src/HOL/Tools/Sledgehammer/metis_translate.ML
author blanchet
Wed Sep 29 22:23:27 2010 +0200 (2010-09-29)
changeset 39886 8a9f0c97d550
parent 39720 0b93a954da4f
child 39887 74939e2afb95
permissions -rw-r--r--
first step towards a new skolemizer that doesn't require "Eps"
     1 (*  Title:      HOL/Tools/Sledgehammer/metis_translate.ML
     2     Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
     3     Author:     Kong W. Susanto, Cambridge University Computer Laboratory
     4     Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory
     5     Author:     Jasmin Blanchette, TU Muenchen
     6 
     7 Translation of HOL to FOL for Metis.
     8 *)
     9 
    10 signature METIS_TRANSLATE =
    11 sig
    12   type name = string * string
    13   datatype type_literal =
    14     TyLitVar of name * name |
    15     TyLitFree of name * name
    16   datatype arLit =
    17     TConsLit of name * name * name list |
    18     TVarLit of name * name
    19   datatype arity_clause =
    20     ArityClause of {name: string, conclLit: arLit, premLits: arLit list}
    21   datatype class_rel_clause =
    22     ClassRelClause of {name: string, subclass: name, superclass: name}
    23   datatype combtyp =
    24     CombTVar of name |
    25     CombTFree of name |
    26     CombType of name * combtyp list
    27   datatype combterm =
    28     CombConst of name * combtyp * combtyp list (* Const and Free *) |
    29     CombVar of name * combtyp |
    30     CombApp of combterm * combterm
    31   datatype fol_literal = FOLLiteral of bool * combterm
    32 
    33   datatype mode = FO | HO | FT
    34   type logic_map =
    35     {axioms: (Metis_Thm.thm * thm) list,
    36      tfrees: type_literal list,
    37      old_skolems: (string * term) list}
    38 
    39   val type_wrapper_name : string
    40   val bound_var_prefix : string
    41   val schematic_var_prefix: string
    42   val fixed_var_prefix: string
    43   val tvar_prefix: string
    44   val tfree_prefix: string
    45   val const_prefix: string
    46   val type_const_prefix: string
    47   val class_prefix: string
    48   val new_skolem_prefix : string
    49   val invert_const: string -> string
    50   val ascii_of: string -> string
    51   val unascii_of: string -> string
    52   val strip_prefix_and_unascii: string -> string -> string option
    53   val make_bound_var : string -> string
    54   val make_schematic_var : string * int -> string
    55   val make_fixed_var : string -> string
    56   val make_schematic_type_var : string * int -> string
    57   val make_fixed_type_var : string -> string
    58   val make_fixed_const : string -> string
    59   val make_fixed_type_const : string -> string
    60   val make_type_class : string -> string
    61   val num_type_args: theory -> string -> int
    62   val new_skolem_var_from_const: string -> indexname
    63   val type_literals_for_types : typ list -> type_literal list
    64   val make_class_rel_clauses :
    65     theory -> class list -> class list -> class_rel_clause list
    66   val make_arity_clauses :
    67     theory -> string list -> class list -> class list * arity_clause list
    68   val combtyp_of : combterm -> combtyp
    69   val strip_combterm_comb : combterm -> combterm * combterm list
    70   val combterm_from_term :
    71     theory -> int -> (string * typ) list -> term -> combterm * typ list
    72   val reveal_old_skolem_terms : (string * term) list -> term -> term
    73   val tfree_classes_of_terms : term list -> string list
    74   val tvar_classes_of_terms : term list -> string list
    75   val type_consts_of_terms : theory -> term list -> string list
    76   val string_of_mode : mode -> string
    77   val build_logic_map :
    78     mode -> Proof.context -> bool -> thm list -> thm list list
    79     -> mode * logic_map
    80 end
    81 
    82 structure Metis_Translate : METIS_TRANSLATE =
    83 struct
    84 
    85 val type_wrapper_name = "ti"
    86 
    87 val bound_var_prefix = "B_"
    88 val schematic_var_prefix = "V_"
    89 val fixed_var_prefix = "v_"
    90 
    91 val tvar_prefix = "T_";
    92 val tfree_prefix = "t_";
    93 
    94 val const_prefix = "c_";
    95 val type_const_prefix = "tc_";
    96 val class_prefix = "class_";
    97 
    98 val new_skolem_var_prefix = "SK?" (* purposedly won't parse *)
    99 
   100 val skolem_prefix = "Sledgehammer" ^ Long_Name.separator ^ "Sko"
   101 val old_skolem_prefix = skolem_prefix ^ "o"
   102 val new_skolem_prefix = skolem_prefix ^ "n"
   103 
   104 fun union_all xss = fold (union (op =)) xss []
   105 
   106 (* Readable names for the more common symbolic functions. Do not mess with the
   107    last nine entries of the table unless you know what you are doing. *)
   108 val const_trans_table =
   109   Symtab.make [(@{type_name Product_Type.prod}, "prod"),
   110                (@{type_name Sum_Type.sum}, "sum"),
   111                (@{const_name HOL.eq}, "equal"),
   112                (@{const_name HOL.conj}, "and"),
   113                (@{const_name HOL.disj}, "or"),
   114                (@{const_name HOL.implies}, "implies"),
   115                (@{const_name Set.member}, "member"),
   116                (@{const_name fequal}, "fequal"),
   117                (@{const_name COMBI}, "COMBI"),
   118                (@{const_name COMBK}, "COMBK"),
   119                (@{const_name COMBB}, "COMBB"),
   120                (@{const_name COMBC}, "COMBC"),
   121                (@{const_name COMBS}, "COMBS"),
   122                (@{const_name True}, "True"),
   123                (@{const_name False}, "False"),
   124                (@{const_name If}, "If")]
   125 
   126 (* Invert the table of translations between Isabelle and ATPs. *)
   127 val const_trans_table_inv =
   128   Symtab.update ("fequal", @{const_name HOL.eq})
   129                 (Symtab.make (map swap (Symtab.dest const_trans_table)))
   130 
   131 val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
   132 
   133 (*Escaping of special characters.
   134   Alphanumeric characters are left unchanged.
   135   The character _ goes to __
   136   Characters in the range ASCII space to / go to _A to _P, respectively.
   137   Other characters go to _nnn where nnn is the decimal ASCII code.*)
   138 val A_minus_space = Char.ord #"A" - Char.ord #" ";
   139 
   140 fun stringN_of_int 0 _ = ""
   141   | stringN_of_int k n = stringN_of_int (k-1) (n div 10) ^ Int.toString (n mod 10);
   142 
   143 fun ascii_of_c c =
   144   if Char.isAlphaNum c then String.str c
   145   else if c = #"_" then "__"
   146   else if #" " <= c andalso c <= #"/"
   147        then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
   148   else ("_" ^ stringN_of_int 3 (Char.ord c))  (*fixed width, in case more digits follow*)
   149 
   150 val ascii_of = String.translate ascii_of_c;
   151 
   152 (** Remove ASCII armouring from names in proof files **)
   153 
   154 (*We don't raise error exceptions because this code can run inside the watcher.
   155   Also, the errors are "impossible" (hah!)*)
   156 fun unascii_aux rcs [] = String.implode(rev rcs)
   157   | unascii_aux rcs [#"_"] = unascii_aux (#"_"::rcs) []  (*ERROR*)
   158       (*Three types of _ escapes: __, _A to _P, _nnn*)
   159   | unascii_aux rcs (#"_" :: #"_" :: cs) = unascii_aux (#"_"::rcs) cs
   160   | unascii_aux rcs (#"_" :: c :: cs) =
   161       if #"A" <= c andalso c<= #"P"  (*translation of #" " to #"/"*)
   162       then unascii_aux (Char.chr(Char.ord c - A_minus_space) :: rcs) cs
   163       else
   164         let val digits = List.take (c::cs, 3) handle Subscript => []
   165         in
   166             case Int.fromString (String.implode digits) of
   167                 NONE => unascii_aux (c:: #"_"::rcs) cs  (*ERROR*)
   168               | SOME n => unascii_aux (Char.chr n :: rcs) (List.drop (cs, 2))
   169         end
   170   | unascii_aux rcs (c::cs) = unascii_aux (c::rcs) cs
   171 val unascii_of = unascii_aux [] o String.explode
   172 
   173 (* If string s has the prefix s1, return the result of deleting it,
   174    un-ASCII'd. *)
   175 fun strip_prefix_and_unascii s1 s =
   176   if String.isPrefix s1 s then
   177     SOME (unascii_of (String.extract (s, size s1, NONE)))
   178   else
   179     NONE
   180 
   181 (*Remove the initial ' character from a type variable, if it is present*)
   182 fun trim_type_var s =
   183   if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
   184   else error ("trim_type: Malformed type variable encountered: " ^ s);
   185 
   186 fun ascii_of_indexname (v,0) = ascii_of v
   187   | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ Int.toString i;
   188 
   189 fun make_bound_var x = bound_var_prefix ^ ascii_of x
   190 fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
   191 fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
   192 
   193 fun make_schematic_type_var (x,i) =
   194       tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
   195 fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
   196 
   197 fun lookup_const c =
   198   case Symtab.lookup const_trans_table c of
   199     SOME c' => c'
   200   | NONE => ascii_of c
   201 
   202 (* HOL.eq MUST BE "equal" because it's built into ATPs. *)
   203 fun make_fixed_const @{const_name HOL.eq} = "equal"
   204   | make_fixed_const c = const_prefix ^ lookup_const c
   205 
   206 fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
   207 
   208 fun make_type_class clas = class_prefix ^ ascii_of clas;
   209 
   210 (* The number of type arguments of a constant, zero if it's monomorphic. For
   211    (instances of) Skolem pseudoconstants, this information is encoded in the
   212    constant name. *)
   213 fun num_type_args thy s =
   214   if String.isPrefix skolem_prefix s then
   215     s |> space_explode Long_Name.separator |> List.last |> Int.fromString |> the
   216   else
   217     (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
   218 
   219 fun new_skolem_var_from_const s =
   220   let
   221     val ss = s |> space_explode Long_Name.separator
   222     val n = length ss
   223   in (nth ss (n - 2), nth ss (n - 3) |> Int.fromString |> the) end
   224 
   225 
   226 (**** Definitions and functions for FOL clauses for TPTP format output ****)
   227 
   228 type name = string * string
   229 
   230 (**** Isabelle FOL clauses ****)
   231 
   232 (* The first component is the type class; the second is a TVar or TFree. *)
   233 datatype type_literal =
   234   TyLitVar of name * name |
   235   TyLitFree of name * name
   236 
   237 (*Make literals for sorted type variables*)
   238 fun sorts_on_typs_aux (_, [])   = []
   239   | sorts_on_typs_aux ((x,i),  s::ss) =
   240       let val sorts = sorts_on_typs_aux ((x,i), ss)
   241       in
   242           if s = "HOL.type" then sorts
   243           else if i = ~1 then TyLitFree (`make_type_class s, `make_fixed_type_var x) :: sorts
   244           else TyLitVar (`make_type_class s, (make_schematic_type_var (x,i), x)) :: sorts
   245       end;
   246 
   247 fun sorts_on_typs (TFree (a,s)) = sorts_on_typs_aux ((a,~1),s)
   248   | sorts_on_typs (TVar (v,s))  = sorts_on_typs_aux (v,s);
   249 
   250 (*Given a list of sorted type variables, return a list of type literals.*)
   251 fun type_literals_for_types Ts =
   252   fold (union (op =)) (map sorts_on_typs Ts) []
   253 
   254 (** make axiom and conjecture clauses. **)
   255 
   256 (**** Isabelle arities ****)
   257 
   258 datatype arLit =
   259   TConsLit of name * name * name list |
   260   TVarLit of name * name
   261 
   262 datatype arity_clause =
   263   ArityClause of {name: string, conclLit: arLit, premLits: arLit list}
   264 
   265 
   266 fun gen_TVars 0 = []
   267   | gen_TVars n = ("T_" ^ Int.toString n) :: gen_TVars (n-1);
   268 
   269 fun pack_sort(_,[])  = []
   270   | pack_sort(tvar, "HOL.type"::srt) = pack_sort (tvar, srt)   (*IGNORE sort "type"*)
   271   | pack_sort(tvar, cls::srt) =
   272     (`make_type_class cls, (tvar, tvar)) :: pack_sort (tvar, srt)
   273 
   274 (*Arity of type constructor tcon :: (arg1,...,argN)res*)
   275 fun make_axiom_arity_clause (tcons, name, (cls,args)) =
   276   let
   277     val tvars = gen_TVars (length args)
   278     val tvars_srts = ListPair.zip (tvars, args)
   279   in
   280     ArityClause {name = name,
   281                  conclLit = TConsLit (`make_type_class cls,
   282                                       `make_fixed_type_const tcons,
   283                                       tvars ~~ tvars),
   284                  premLits = map TVarLit (union_all (map pack_sort tvars_srts))}
   285   end
   286 
   287 
   288 (**** Isabelle class relations ****)
   289 
   290 datatype class_rel_clause =
   291   ClassRelClause of {name: string, subclass: name, superclass: name}
   292 
   293 (*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
   294 fun class_pairs _ [] _ = []
   295   | class_pairs thy subs supers =
   296       let
   297         val class_less = Sorts.class_less (Sign.classes_of thy)
   298         fun add_super sub super = class_less (sub, super) ? cons (sub, super)
   299         fun add_supers sub = fold (add_super sub) supers
   300       in fold add_supers subs [] end
   301 
   302 fun make_class_rel_clause (sub,super) =
   303   ClassRelClause {name = sub ^ "_" ^ super,
   304                   subclass = `make_type_class sub,
   305                   superclass = `make_type_class super}
   306 
   307 fun make_class_rel_clauses thy subs supers =
   308   map make_class_rel_clause (class_pairs thy subs supers);
   309 
   310 
   311 (** Isabelle arities **)
   312 
   313 fun arity_clause _ _ (_, []) = []
   314   | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
   315       arity_clause seen n (tcons,ars)
   316   | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
   317       if member (op =) seen class then (*multiple arities for the same tycon, class pair*)
   318           make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class ^ "_" ^ Int.toString n, ar) ::
   319           arity_clause seen (n+1) (tcons,ars)
   320       else
   321           make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class, ar) ::
   322           arity_clause (class::seen) n (tcons,ars)
   323 
   324 fun multi_arity_clause [] = []
   325   | multi_arity_clause ((tcons, ars) :: tc_arlists) =
   326       arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
   327 
   328 (*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy
   329   provided its arguments have the corresponding sorts.*)
   330 fun type_class_pairs thy tycons classes =
   331   let val alg = Sign.classes_of thy
   332       fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
   333       fun add_class tycon class =
   334         cons (class, domain_sorts tycon class)
   335         handle Sorts.CLASS_ERROR _ => I
   336       fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
   337   in  map try_classes tycons  end;
   338 
   339 (*Proving one (tycon, class) membership may require proving others, so iterate.*)
   340 fun iter_type_class_pairs _ _ [] = ([], [])
   341   | iter_type_class_pairs thy tycons classes =
   342       let val cpairs = type_class_pairs thy tycons classes
   343           val newclasses = union_all (union_all (union_all (map (map #2 o #2) cpairs)))
   344             |> subtract (op =) classes |> subtract (op =) HOLogic.typeS
   345           val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
   346       in (union (op =) classes' classes, union (op =) cpairs' cpairs) end;
   347 
   348 fun make_arity_clauses thy tycons classes =
   349   let val (classes', cpairs) = iter_type_class_pairs thy tycons classes
   350   in  (classes', multi_arity_clause cpairs)  end;
   351 
   352 datatype combtyp =
   353   CombTVar of name |
   354   CombTFree of name |
   355   CombType of name * combtyp list
   356 
   357 datatype combterm =
   358   CombConst of name * combtyp * combtyp list (* Const and Free *) |
   359   CombVar of name * combtyp |
   360   CombApp of combterm * combterm
   361 
   362 datatype fol_literal = FOLLiteral of bool * combterm
   363 
   364 (*********************************************************************)
   365 (* convert a clause with type Term.term to a clause with type clause *)
   366 (*********************************************************************)
   367 
   368 (*Result of a function type; no need to check that the argument type matches.*)
   369 fun result_type (CombType (_, [_, tp2])) = tp2
   370   | result_type _ = raise Fail "non-function type"
   371 
   372 fun combtyp_of (CombConst (_, tp, _)) = tp
   373   | combtyp_of (CombVar (_, tp)) = tp
   374   | combtyp_of (CombApp (t1, _)) = result_type (combtyp_of t1)
   375 
   376 (*gets the head of a combinator application, along with the list of arguments*)
   377 fun strip_combterm_comb u =
   378     let fun stripc (CombApp(t,u), ts) = stripc (t, u::ts)
   379         |   stripc  x =  x
   380     in stripc(u,[]) end
   381 
   382 fun combtype_of (Type (a, Ts)) =
   383     let val (folTypes, ts) = combtypes_of Ts in
   384       (CombType (`make_fixed_type_const a, folTypes), ts)
   385     end
   386   | combtype_of (tp as TFree (a, _)) = (CombTFree (`make_fixed_type_var a), [tp])
   387   | combtype_of (tp as TVar (x, _)) =
   388     (CombTVar (make_schematic_type_var x, string_of_indexname x), [tp])
   389 and combtypes_of Ts =
   390   let val (folTyps, ts) = ListPair.unzip (map combtype_of Ts) in
   391     (folTyps, union_all ts)
   392   end
   393 
   394 (* same as above, but no gathering of sort information *)
   395 fun simple_combtype_of (Type (a, Ts)) =
   396     CombType (`make_fixed_type_const a, map simple_combtype_of Ts)
   397   | simple_combtype_of (TFree (a, _)) = CombTFree (`make_fixed_type_var a)
   398   | simple_combtype_of (TVar (x, _)) =
   399     CombTVar (make_schematic_type_var x, string_of_indexname x)
   400 
   401 fun new_skolem_name th_no s num_T_args =
   402   [new_skolem_prefix, string_of_int th_no, s, string_of_int num_T_args]
   403   |> space_implode Long_Name.separator
   404 
   405 (* Converts a term (with combinators) into a combterm. Also accummulates sort
   406    infomation. *)
   407 fun combterm_from_term thy th_no bs (P $ Q) =
   408       let val (P', tsP) = combterm_from_term thy th_no bs P
   409           val (Q', tsQ) = combterm_from_term thy th_no bs Q
   410       in  (CombApp (P', Q'), union (op =) tsP tsQ)  end
   411   | combterm_from_term thy _ _ (Const (c, T)) =
   412       let
   413         val (tp, ts) = combtype_of T
   414         val tvar_list =
   415           (if String.isPrefix old_skolem_prefix c then
   416              [] |> Term.add_tvarsT T |> map TVar
   417            else
   418              (c, T) |> Sign.const_typargs thy)
   419           |> map simple_combtype_of
   420         val c' = CombConst (`make_fixed_const c, tp, tvar_list)
   421       in  (c',ts)  end
   422   | combterm_from_term _ _ _ (Free (v, T)) =
   423       let val (tp, ts) = combtype_of T
   424           val v' = CombConst (`make_fixed_var v, tp, [])
   425       in  (v',ts)  end
   426   | combterm_from_term _ th_no _ (Var (v as (s, _), T)) =
   427     let
   428       val (tp, ts) = combtype_of T
   429       val v' =
   430         if String.isPrefix new_skolem_var_prefix s then
   431           let
   432             val tys = T |> strip_type |> swap |> op ::
   433             val s' = new_skolem_name th_no s (length tys)
   434           in
   435             CombConst (`make_fixed_const s', tp, map simple_combtype_of tys)
   436           end
   437         else
   438           CombVar ((make_schematic_var v, string_of_indexname v), tp)
   439     in (v', ts) end
   440   | combterm_from_term _ _ bs (Bound j) =
   441       let
   442         val (s, T) = nth bs j
   443         val (tp, ts) = combtype_of T
   444         val v' = CombConst (`make_bound_var s, tp, [])
   445       in (v', ts) end
   446   | combterm_from_term _ _ _ (Abs _) = raise Fail "HOL clause: Abs"
   447 
   448 fun predicate_of thy th_no ((@{const Not} $ P), pos) =
   449     predicate_of thy th_no (P, not pos)
   450   | predicate_of thy th_no (t, pos) =
   451     (combterm_from_term thy th_no [] (Envir.eta_contract t), pos)
   452 
   453 fun literals_of_term1 args thy th_no (@{const Trueprop} $ P) =
   454     literals_of_term1 args thy th_no P
   455   | literals_of_term1 args thy th_no (@{const HOL.disj} $ P $ Q) =
   456     literals_of_term1 (literals_of_term1 args thy th_no P) thy th_no Q
   457   | literals_of_term1 (lits, ts) thy th_no P =
   458     let val ((pred, ts'), pol) = predicate_of thy th_no (P, true) in
   459       (FOLLiteral (pol, pred) :: lits, union (op =) ts ts')
   460     end
   461 val literals_of_term = literals_of_term1 ([], [])
   462 
   463 fun old_skolem_name i j num_T_args =
   464   old_skolem_prefix ^ Long_Name.separator ^
   465   (space_implode Long_Name.separator (map Int.toString [i, j, num_T_args]))
   466 
   467 fun conceal_old_skolem_terms i old_skolems t =
   468   if exists_Const (curry (op =) @{const_name skolem} o fst) t then
   469     let
   470       fun aux old_skolems
   471               (t as (Const (@{const_name skolem}, Type (_, [_, T])) $ _)) =
   472           let
   473             val (old_skolems, s) =
   474               if i = ~1 then
   475                 (old_skolems, @{const_name undefined})
   476               else case AList.find (op aconv) old_skolems t of
   477                 s :: _ => (old_skolems, s)
   478               | [] =>
   479                 let
   480                   val s = old_skolem_name i (length old_skolems)
   481                                           (length (Term.add_tvarsT T []))
   482                 in ((s, t) :: old_skolems, s) end
   483           in (old_skolems, Const (s, T)) end
   484         | aux old_skolems (t1 $ t2) =
   485           let
   486             val (old_skolems, t1) = aux old_skolems t1
   487             val (old_skolems, t2) = aux old_skolems t2
   488           in (old_skolems, t1 $ t2) end
   489         | aux old_skolems (Abs (s, T, t')) =
   490           let val (old_skolems, t') = aux old_skolems t' in
   491             (old_skolems, Abs (s, T, t'))
   492           end
   493         | aux old_skolems t = (old_skolems, t)
   494     in aux old_skolems t end
   495   else
   496     (old_skolems, t)
   497 
   498 fun reveal_old_skolem_terms old_skolems =
   499   map_aterms (fn t as Const (s, _) =>
   500                  if String.isPrefix old_skolem_prefix s then
   501                    AList.lookup (op =) old_skolems s |> the
   502                    |> map_types Type_Infer.paramify_vars
   503                  else
   504                    t
   505                | t => t)
   506 
   507 
   508 (***************************************************************)
   509 (* Type Classes Present in the Axiom or Conjecture Clauses     *)
   510 (***************************************************************)
   511 
   512 fun set_insert (x, s) = Symtab.update (x, ()) s
   513 
   514 fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
   515 
   516 (*Remove this trivial type class*)
   517 fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset;
   518 
   519 fun tfree_classes_of_terms ts =
   520   let val sorts_list = map (map #2 o OldTerm.term_tfrees) ts
   521   in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
   522 
   523 fun tvar_classes_of_terms ts =
   524   let val sorts_list = map (map #2 o OldTerm.term_tvars) ts
   525   in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
   526 
   527 (*fold type constructors*)
   528 fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
   529   | fold_type_consts _ _ x = x;
   530 
   531 (*Type constructors used to instantiate overloaded constants are the only ones needed.*)
   532 fun add_type_consts_in_term thy =
   533   let
   534     fun aux (Const x) =
   535         fold (fold_type_consts set_insert) (Sign.const_typargs thy x)
   536       | aux (Abs (_, _, u)) = aux u
   537       | aux (Const (@{const_name skolem}, _) $ _) = I
   538       | aux (t $ u) = aux t #> aux u
   539       | aux _ = I
   540   in aux end
   541 
   542 fun type_consts_of_terms thy ts =
   543   Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
   544 
   545 (* ------------------------------------------------------------------------- *)
   546 (* HOL to FOL  (Isabelle to Metis)                                           *)
   547 (* ------------------------------------------------------------------------- *)
   548 
   549 datatype mode = FO | HO | FT  (* first-order, higher-order, fully-typed *)
   550 
   551 fun string_of_mode FO = "FO"
   552   | string_of_mode HO = "HO"
   553   | string_of_mode FT = "FT"
   554 
   555 fun fn_isa_to_met_sublevel "equal" = "=" (* FIXME: "c_fequal" *)
   556   | fn_isa_to_met_sublevel x = x
   557 fun fn_isa_to_met_toplevel "equal" = "="
   558   | fn_isa_to_met_toplevel x = x
   559 
   560 fun metis_lit b c args = (b, (c, args));
   561 
   562 fun metis_term_from_combtyp (CombTVar (s, _)) = Metis_Term.Var s
   563   | metis_term_from_combtyp (CombTFree (s, _)) = Metis_Term.Fn (s, [])
   564   | metis_term_from_combtyp (CombType ((s, _), tps)) =
   565     Metis_Term.Fn (s, map metis_term_from_combtyp tps);
   566 
   567 (*These two functions insert type literals before the real literals. That is the
   568   opposite order from TPTP linkup, but maybe OK.*)
   569 
   570 fun hol_term_to_fol_FO tm =
   571   case strip_combterm_comb tm of
   572       (CombConst ((c, _), _, tys), tms) =>
   573         let val tyargs = map metis_term_from_combtyp tys
   574             val args   = map hol_term_to_fol_FO tms
   575         in Metis_Term.Fn (c, tyargs @ args) end
   576     | (CombVar ((v, _), _), []) => Metis_Term.Var v
   577     | _ => raise Fail "non-first-order combterm"
   578 
   579 fun hol_term_to_fol_HO (CombConst ((a, _), _, tylist)) =
   580       Metis_Term.Fn (fn_isa_to_met_sublevel a, map metis_term_from_combtyp tylist)
   581   | hol_term_to_fol_HO (CombVar ((s, _), _)) = Metis_Term.Var s
   582   | hol_term_to_fol_HO (CombApp (tm1, tm2)) =
   583        Metis_Term.Fn (".", map hol_term_to_fol_HO [tm1, tm2]);
   584 
   585 (*The fully-typed translation, to avoid type errors*)
   586 fun wrap_type (tm, ty) =
   587   Metis_Term.Fn (type_wrapper_name, [tm, metis_term_from_combtyp ty])
   588 
   589 fun hol_term_to_fol_FT (CombVar ((s, _), ty)) = wrap_type (Metis_Term.Var s, ty)
   590   | hol_term_to_fol_FT (CombConst((a, _), ty, _)) =
   591       wrap_type (Metis_Term.Fn(fn_isa_to_met_sublevel a, []), ty)
   592   | hol_term_to_fol_FT (tm as CombApp(tm1,tm2)) =
   593        wrap_type (Metis_Term.Fn(".", map hol_term_to_fol_FT [tm1,tm2]),
   594                   combtyp_of tm)
   595 
   596 fun hol_literal_to_fol FO (FOLLiteral (pos, tm)) =
   597       let val (CombConst((p, _), _, tys), tms) = strip_combterm_comb tm
   598           val tylits = if p = "equal" then [] else map metis_term_from_combtyp tys
   599           val lits = map hol_term_to_fol_FO tms
   600       in metis_lit pos (fn_isa_to_met_toplevel p) (tylits @ lits) end
   601   | hol_literal_to_fol HO (FOLLiteral (pos, tm)) =
   602      (case strip_combterm_comb tm of
   603           (CombConst(("equal", _), _, _), tms) =>
   604             metis_lit pos "=" (map hol_term_to_fol_HO tms)
   605         | _ => metis_lit pos "{}" [hol_term_to_fol_HO tm])   (*hBOOL*)
   606   | hol_literal_to_fol FT (FOLLiteral (pos, tm)) =
   607      (case strip_combterm_comb tm of
   608           (CombConst(("equal", _), _, _), tms) =>
   609             metis_lit pos "=" (map hol_term_to_fol_FT tms)
   610         | _ => metis_lit pos "{}" [hol_term_to_fol_FT tm])   (*hBOOL*);
   611 
   612 fun literals_of_hol_term thy th_no mode t =
   613       let val (lits, types_sorts) = literals_of_term thy th_no t
   614       in  (map (hol_literal_to_fol mode) lits, types_sorts) end;
   615 
   616 (*Sign should be "true" for conjecture type constraints, "false" for type lits in clauses.*)
   617 fun metis_of_type_literals pos (TyLitVar ((s, _), (s', _))) =
   618     metis_lit pos s [Metis_Term.Var s']
   619   | metis_of_type_literals pos (TyLitFree ((s, _), (s', _))) =
   620     metis_lit pos s [Metis_Term.Fn (s',[])]
   621 
   622 fun default_sort _ (TVar _) = false
   623   | default_sort ctxt (TFree (x, s)) = (s = the_default [] (Variable.def_sort ctxt (x, ~1)));
   624 
   625 fun metis_of_tfree tf =
   626   Metis_Thm.axiom (Metis_LiteralSet.singleton (metis_of_type_literals true tf));
   627 
   628 fun hol_thm_to_fol is_conjecture th_no ctxt type_lits mode j old_skolems th =
   629   let
   630     val thy = ProofContext.theory_of ctxt
   631     val (old_skolems, (mlits, types_sorts)) =
   632      th |> prop_of |> conceal_old_skolem_terms j old_skolems
   633         ||> (HOLogic.dest_Trueprop #> literals_of_hol_term thy th_no mode)
   634   in
   635     if is_conjecture then
   636       (Metis_Thm.axiom (Metis_LiteralSet.fromList mlits),
   637        type_literals_for_types types_sorts, old_skolems)
   638     else
   639       let
   640         val tylits = filter_out (default_sort ctxt) types_sorts
   641                      |> type_literals_for_types
   642         val mtylits =
   643           if type_lits then map (metis_of_type_literals false) tylits else []
   644       in
   645         (Metis_Thm.axiom (Metis_LiteralSet.fromList(mtylits @ mlits)), [],
   646          old_skolems)
   647       end
   648   end;
   649 
   650 val helpers =
   651   [("c_COMBI", (false, map (`I) @{thms COMBI_def})),
   652    ("c_COMBK", (false, map (`I) @{thms COMBK_def})),
   653    ("c_COMBB", (false, map (`I) @{thms COMBB_def})),
   654    ("c_COMBC", (false, map (`I) @{thms COMBC_def})),
   655    ("c_COMBS", (false, map (`I) @{thms COMBS_def})),
   656    ("c_fequal", (false, map (rpair @{thm equal_imp_equal})
   657                             @{thms fequal_imp_equal equal_imp_fequal})),
   658    ("c_True", (true, map (`I) @{thms True_or_False})),
   659    ("c_False", (true, map (`I) @{thms True_or_False})),
   660    ("c_If", (true, map (`I) @{thms if_True if_False True_or_False}))]
   661 
   662 (* ------------------------------------------------------------------------- *)
   663 (* Logic maps manage the interface between HOL and first-order logic.        *)
   664 (* ------------------------------------------------------------------------- *)
   665 
   666 type logic_map =
   667   {axioms: (Metis_Thm.thm * thm) list,
   668    tfrees: type_literal list,
   669    old_skolems: (string * term) list}
   670 
   671 fun is_quasi_fol_clause thy =
   672   Meson.is_fol_term thy o snd o conceal_old_skolem_terms ~1 [] o prop_of
   673 
   674 (*Extract TFree constraints from context to include as conjecture clauses*)
   675 fun init_tfrees ctxt =
   676   let fun add ((a,i),s) Ts = if i = ~1 then TFree(a,s) :: Ts else Ts in
   677     Vartab.fold add (#2 (Variable.constraints_of ctxt)) []
   678     |> type_literals_for_types
   679   end;
   680 
   681 (*Insert non-logical axioms corresponding to all accumulated TFrees*)
   682 fun add_tfrees {axioms, tfrees, old_skolems} : logic_map =
   683      {axioms = map (rpair TrueI o metis_of_tfree) (distinct (op =) tfrees) @
   684                axioms,
   685       tfrees = tfrees, old_skolems = old_skolems}
   686 
   687 (*transform isabelle type / arity clause to metis clause *)
   688 fun add_type_thm [] lmap = lmap
   689   | add_type_thm ((ith, mth) :: cls) {axioms, tfrees, old_skolems} =
   690       add_type_thm cls {axioms = (mth, ith) :: axioms, tfrees = tfrees,
   691                         old_skolems = old_skolems}
   692 
   693 fun const_in_metis c (pred, tm_list) =
   694   let
   695     fun in_mterm (Metis_Term.Var _) = false
   696       | in_mterm (Metis_Term.Fn (".", tm_list)) = exists in_mterm tm_list
   697       | in_mterm (Metis_Term.Fn (nm, tm_list)) = c=nm orelse exists in_mterm tm_list
   698   in  c = pred orelse exists in_mterm tm_list  end;
   699 
   700 (* ARITY CLAUSE *)
   701 fun m_arity_cls (TConsLit ((c, _), (t, _), args)) =
   702     metis_lit true c [Metis_Term.Fn(t, map (Metis_Term.Var o fst) args)]
   703   | m_arity_cls (TVarLit ((c, _), (s, _))) =
   704     metis_lit false c [Metis_Term.Var s]
   705 (*TrueI is returned as the Isabelle counterpart because there isn't any.*)
   706 fun arity_cls (ArityClause {conclLit, premLits, ...}) =
   707   (TrueI,
   708    Metis_Thm.axiom (Metis_LiteralSet.fromList (map m_arity_cls (conclLit :: premLits))));
   709 
   710 (* CLASSREL CLAUSE *)
   711 fun m_class_rel_cls (subclass, _) (superclass, _) =
   712   [metis_lit false subclass [Metis_Term.Var "T"], metis_lit true superclass [Metis_Term.Var "T"]];
   713 fun class_rel_cls (ClassRelClause {subclass, superclass, ...}) =
   714   (TrueI, Metis_Thm.axiom (Metis_LiteralSet.fromList (m_class_rel_cls subclass superclass)));
   715 
   716 fun type_ext thy tms =
   717   let val subs = tfree_classes_of_terms tms
   718       val supers = tvar_classes_of_terms tms
   719       and tycons = type_consts_of_terms thy tms
   720       val (supers', arity_clauses) = make_arity_clauses thy tycons supers
   721       val class_rel_clauses = make_class_rel_clauses thy subs supers'
   722   in  map class_rel_cls class_rel_clauses @ map arity_cls arity_clauses
   723   end;
   724 
   725 (* Function to generate metis clauses, including comb and type clauses *)
   726 fun build_logic_map mode0 ctxt type_lits cls thss =
   727   let val thy = ProofContext.theory_of ctxt
   728       (*The modes FO and FT are sticky. HO can be downgraded to FO.*)
   729       fun set_mode FO = FO
   730         | set_mode HO =
   731           if forall (forall (is_quasi_fol_clause thy)) (cls :: thss) then FO
   732           else HO
   733         | set_mode FT = FT
   734       val mode = set_mode mode0
   735       (*transform isabelle clause to metis clause *)
   736       fun add_thm th_no is_conjecture (metis_ith, isa_ith)
   737                   {axioms, tfrees, old_skolems} : logic_map =
   738         let
   739           val (mth, tfree_lits, old_skolems) =
   740             hol_thm_to_fol is_conjecture th_no ctxt type_lits mode (length axioms)
   741                            old_skolems metis_ith
   742         in
   743            {axioms = (mth, Meson.make_meta_clause isa_ith) :: axioms,
   744             tfrees = union (op =) tfree_lits tfrees, old_skolems = old_skolems}
   745         end;
   746       val lmap = {axioms = [], tfrees = init_tfrees ctxt, old_skolems = []}
   747                  |> fold (add_thm 0 true o `I) cls
   748                  |> add_tfrees
   749                  |> fold (fn (th_no, ths) => fold (add_thm th_no false o `I) ths)
   750                          (1 upto length thss ~~ thss)
   751       val clause_lists = map (Metis_Thm.clause o #1) (#axioms lmap)
   752       fun is_used c =
   753         exists (Metis_LiteralSet.exists (const_in_metis c o #2)) clause_lists
   754       val lmap =
   755         if mode = FO then
   756           lmap
   757         else
   758           let
   759             val helper_ths =
   760               helpers |> filter (is_used o fst)
   761                       |> maps (fn (c, (needs_full_types, thms)) =>
   762                                   if not (is_used c) orelse
   763                                      needs_full_types andalso mode <> FT then
   764                                     []
   765                                   else
   766                                     thms)
   767           in lmap |> fold (add_thm ~1 false) helper_ths end
   768   in
   769     (mode, add_type_thm (type_ext thy (maps (map prop_of) (cls :: thss))) lmap)
   770   end
   771 
   772 end;