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