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