src/HOL/Tools/Metis/metis_translate.ML
author blanchet
Mon Jun 06 20:36:35 2011 +0200 (2011-06-06)
changeset 43173 b98daa96d043
parent 43160 d4f347508cd4
child 43174 f497a1e97d37
permissions -rw-r--r--
don't pass "~ " to new Metis
     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 type_literal = ATP_Translate.type_literal
    13   type type_sys = ATP_Translate.type_sys
    14 
    15   datatype mode = FO | HO | FT | MX
    16 
    17   datatype isa_thm =
    18     Isa_Reflexive_or_Trivial |
    19     Isa_Raw of thm
    20 
    21   type metis_problem =
    22     {axioms : (Metis_Thm.thm * isa_thm) list,
    23      tfrees : type_literal list,
    24      old_skolems : (string * term) list}
    25 
    26   val metis_equal : string
    27   val metis_predicator : string
    28   val metis_app_op : string
    29   val metis_type_tag : string
    30   val metis_generated_var_prefix : string
    31   val metis_name_table : ((string * int) * (string * bool)) list
    32   val reveal_old_skolem_terms : (string * term) list -> term -> term
    33   val string_of_mode : mode -> string
    34   val prepare_metis_problem :
    35     Proof.context -> mode -> type_sys option -> thm list -> thm list
    36     -> mode * int Symtab.table * metis_problem
    37 end
    38 
    39 structure Metis_Translate : METIS_TRANSLATE =
    40 struct
    41 
    42 open ATP_Problem
    43 open ATP_Translate
    44 
    45 val metis_equal = "="
    46 val metis_predicator = "{}"
    47 val metis_app_op = "."
    48 val metis_type_tag = ":"
    49 val metis_generated_var_prefix = "_"
    50 
    51 val metis_name_table =
    52   [((tptp_equal, 2), (metis_equal, false)),
    53    ((tptp_old_equal, 2), (metis_equal, false)),
    54    ((const_prefix ^ predicator_name, 1), (metis_predicator, false)),
    55    ((prefixed_app_op_name, 2), (metis_app_op, false)),
    56    ((prefixed_type_tag_name, 2), (metis_type_tag, true))]
    57 
    58 fun predicate_of thy ((@{const Not} $ P), pos) = predicate_of thy (P, not pos)
    59   | predicate_of thy (t, pos) =
    60     (combterm_from_term thy [] (Envir.eta_contract t), pos)
    61 
    62 fun literals_of_term1 args thy (@{const Trueprop} $ P) =
    63     literals_of_term1 args thy P
    64   | literals_of_term1 args thy (@{const HOL.disj} $ P $ Q) =
    65     literals_of_term1 (literals_of_term1 args thy P) thy Q
    66   | literals_of_term1 (lits, ts) thy P =
    67     let val ((pred, ts'), pol) = predicate_of thy (P, true) in
    68       ((pol, pred) :: lits, union (op =) ts ts')
    69     end
    70 val literals_of_term = literals_of_term1 ([], [])
    71 
    72 fun old_skolem_const_name i j num_T_args =
    73   old_skolem_const_prefix ^ Long_Name.separator ^
    74   (space_implode Long_Name.separator (map string_of_int [i, j, num_T_args]))
    75 
    76 fun conceal_old_skolem_terms i old_skolems t =
    77   if exists_Const (curry (op =) @{const_name Meson.skolem} o fst) t then
    78     let
    79       fun aux old_skolems
    80              (t as (Const (@{const_name Meson.skolem}, Type (_, [_, T])) $ _)) =
    81           let
    82             val (old_skolems, s) =
    83               if i = ~1 then
    84                 (old_skolems, @{const_name undefined})
    85               else case AList.find (op aconv) old_skolems t of
    86                 s :: _ => (old_skolems, s)
    87               | [] =>
    88                 let
    89                   val s = old_skolem_const_name i (length old_skolems)
    90                                                 (length (Term.add_tvarsT T []))
    91                 in ((s, t) :: old_skolems, s) end
    92           in (old_skolems, Const (s, T)) end
    93         | aux old_skolems (t1 $ t2) =
    94           let
    95             val (old_skolems, t1) = aux old_skolems t1
    96             val (old_skolems, t2) = aux old_skolems t2
    97           in (old_skolems, t1 $ t2) end
    98         | aux old_skolems (Abs (s, T, t')) =
    99           let val (old_skolems, t') = aux old_skolems t' in
   100             (old_skolems, Abs (s, T, t'))
   101           end
   102         | aux old_skolems t = (old_skolems, t)
   103     in aux old_skolems t end
   104   else
   105     (old_skolems, t)
   106 
   107 fun reveal_old_skolem_terms old_skolems =
   108   map_aterms (fn t as Const (s, _) =>
   109                  if String.isPrefix old_skolem_const_prefix s then
   110                    AList.lookup (op =) old_skolems s |> the
   111                    |> map_types Type_Infer.paramify_vars
   112                  else
   113                    t
   114                | t => t)
   115 
   116 
   117 (* ------------------------------------------------------------------------- *)
   118 (* HOL to FOL  (Isabelle to Metis)                                           *)
   119 (* ------------------------------------------------------------------------- *)
   120 
   121 (* first-order, higher-order, fully-typed, mode X (fleXible) *)
   122 datatype mode = FO | HO | FT | MX
   123 
   124 fun string_of_mode FO = "FO"
   125   | string_of_mode HO = "HO"
   126   | string_of_mode FT = "FT"
   127   | string_of_mode MX = "MX"
   128 
   129 fun fn_isa_to_met_sublevel "equal" = "c_fequal"
   130   | fn_isa_to_met_sublevel "c_False" = "c_fFalse"
   131   | fn_isa_to_met_sublevel "c_True" = "c_fTrue"
   132   | fn_isa_to_met_sublevel "c_Not" = "c_fNot"
   133   | fn_isa_to_met_sublevel "c_conj" = "c_fconj"
   134   | fn_isa_to_met_sublevel "c_disj" = "c_fdisj"
   135   | fn_isa_to_met_sublevel "c_implies" = "c_fimplies"
   136   | fn_isa_to_met_sublevel x = x
   137 
   138 fun fn_isa_to_met_toplevel "equal" = metis_equal
   139   | fn_isa_to_met_toplevel x = x
   140 
   141 fun metis_lit b c args = (b, (c, args));
   142 
   143 fun metis_term_from_typ (Type (s, Ts)) =
   144     Metis_Term.Fn (make_fixed_type_const s, map metis_term_from_typ Ts)
   145   | metis_term_from_typ (TFree (s, _)) =
   146     Metis_Term.Fn (make_fixed_type_var s, [])
   147   | metis_term_from_typ (TVar (x, _)) =
   148     Metis_Term.Var (make_schematic_type_var x)
   149 
   150 (*These two functions insert type literals before the real literals. That is the
   151   opposite order from TPTP linkup, but maybe OK.*)
   152 
   153 fun hol_term_to_fol_FO tm =
   154   case strip_combterm_comb tm of
   155       (CombConst ((c, _), _, Ts), tms) =>
   156         let val tyargs = map metis_term_from_typ Ts
   157             val args = map hol_term_to_fol_FO tms
   158         in Metis_Term.Fn (c, tyargs @ args) end
   159     | (CombVar ((v, _), _), []) => Metis_Term.Var v
   160     | _ => raise Fail "non-first-order combterm"
   161 
   162 fun hol_term_to_fol_HO (CombConst ((a, _), _, Ts)) =
   163     Metis_Term.Fn (fn_isa_to_met_sublevel a, map metis_term_from_typ Ts)
   164   | hol_term_to_fol_HO (CombVar ((s, _), _)) = Metis_Term.Var s
   165   | hol_term_to_fol_HO (CombApp (tm1, tm2)) =
   166     Metis_Term.Fn (metis_app_op, map hol_term_to_fol_HO [tm1, tm2])
   167 
   168 (*The fully-typed translation, to avoid type errors*)
   169 fun tag_with_type tm T =
   170   Metis_Term.Fn (metis_type_tag, [tm, metis_term_from_typ T])
   171 
   172 fun hol_term_to_fol_FT (CombVar ((s, _), ty)) =
   173     tag_with_type (Metis_Term.Var s) ty
   174   | hol_term_to_fol_FT (CombConst ((a, _), ty, _)) =
   175     tag_with_type (Metis_Term.Fn (fn_isa_to_met_sublevel a, [])) ty
   176   | hol_term_to_fol_FT (tm as CombApp (tm1,tm2)) =
   177     tag_with_type
   178         (Metis_Term.Fn (metis_app_op, map hol_term_to_fol_FT [tm1, tm2]))
   179         (combtyp_of tm)
   180 
   181 fun hol_literal_to_fol FO (pos, tm) =
   182       let
   183         val (CombConst((p, _), _, Ts), tms) = strip_combterm_comb tm
   184         val tylits = if p = "equal" then [] else map metis_term_from_typ Ts
   185         val lits = map hol_term_to_fol_FO tms
   186       in metis_lit pos (fn_isa_to_met_toplevel p) (tylits @ lits) end
   187   | hol_literal_to_fol HO (pos, tm) =
   188      (case strip_combterm_comb tm of
   189           (CombConst(("equal", _), _, _), tms) =>
   190             metis_lit pos metis_equal (map hol_term_to_fol_HO tms)
   191         | _ => metis_lit pos metis_predicator [hol_term_to_fol_HO tm])
   192   | hol_literal_to_fol FT (pos, tm) =
   193      (case strip_combterm_comb tm of
   194           (CombConst(("equal", _), _, _), tms) =>
   195             metis_lit pos metis_equal (map hol_term_to_fol_FT tms)
   196         | _ => metis_lit pos metis_predicator [hol_term_to_fol_FT tm])
   197 
   198 fun literals_of_hol_term thy mode t =
   199   let val (lits, types_sorts) = literals_of_term thy t in
   200     (map (hol_literal_to_fol mode) lits, types_sorts)
   201   end
   202 
   203 (*Sign should be "true" for conjecture type constraints, "false" for type lits in clauses.*)
   204 fun metis_of_type_literals pos (TyLitVar ((s, _), (s', _))) =
   205     metis_lit pos s [Metis_Term.Var s']
   206   | metis_of_type_literals pos (TyLitFree ((s, _), (s', _))) =
   207     metis_lit pos s [Metis_Term.Fn (s',[])]
   208 
   209 fun has_default_sort _ (TVar _) = false
   210   | has_default_sort ctxt (TFree (x, s)) =
   211     (s = the_default [] (Variable.def_sort ctxt (x, ~1)));
   212 
   213 fun metis_of_tfree tf =
   214   Metis_Thm.axiom (Metis_LiteralSet.singleton (metis_of_type_literals true tf));
   215 
   216 fun hol_thm_to_fol is_conjecture ctxt mode j old_skolems th =
   217   let
   218     val thy = Proof_Context.theory_of ctxt
   219     val (old_skolems, (mlits, types_sorts)) =
   220      th |> prop_of |> Logic.strip_imp_concl
   221         |> conceal_old_skolem_terms j old_skolems
   222         ||> (HOLogic.dest_Trueprop #> literals_of_hol_term thy mode)
   223   in
   224     if is_conjecture then
   225       (Metis_Thm.axiom (Metis_LiteralSet.fromList mlits),
   226        raw_type_literals_for_types types_sorts, old_skolems)
   227     else
   228       let
   229         val tylits = types_sorts |> filter_out (has_default_sort ctxt)
   230                                  |> raw_type_literals_for_types
   231         val mtylits = map (metis_of_type_literals false) tylits
   232       in
   233         (Metis_Thm.axiom (Metis_LiteralSet.fromList(mtylits @ mlits)), [],
   234          old_skolems)
   235       end
   236   end;
   237 
   238 (* ------------------------------------------------------------------------- *)
   239 (* Logic maps manage the interface between HOL and first-order logic.        *)
   240 (* ------------------------------------------------------------------------- *)
   241 
   242 datatype isa_thm =
   243   Isa_Reflexive_or_Trivial |
   244   Isa_Raw of thm
   245 
   246 type metis_problem =
   247   {axioms : (Metis_Thm.thm * isa_thm) list,
   248    tfrees : type_literal list,
   249    old_skolems : (string * term) list}
   250 
   251 fun is_quasi_fol_clause thy =
   252   Meson.is_fol_term thy o snd o conceal_old_skolem_terms ~1 [] o prop_of
   253 
   254 (*Extract TFree constraints from context to include as conjecture clauses*)
   255 fun init_tfrees ctxt =
   256   let fun add ((a,i),s) Ts = if i = ~1 then TFree(a,s) :: Ts else Ts in
   257     Vartab.fold add (#2 (Variable.constraints_of ctxt)) []
   258     |> raw_type_literals_for_types
   259   end;
   260 
   261 fun const_in_metis c (pred, tm_list) =
   262   let
   263     fun in_mterm (Metis_Term.Var _) = false
   264       | in_mterm (Metis_Term.Fn (nm, tm_list)) =
   265         c = nm orelse exists in_mterm tm_list
   266   in c = pred orelse exists in_mterm tm_list end
   267 
   268 (* ARITY CLAUSE *)
   269 fun m_arity_cls (TConsLit ((c, _), (t, _), args)) =
   270     metis_lit true c [Metis_Term.Fn(t, map (Metis_Term.Var o fst) args)]
   271   | m_arity_cls (TVarLit ((c, _), (s, _))) =
   272     metis_lit false c [Metis_Term.Var s]
   273 (* TrueI is returned as the Isabelle counterpart because there isn't any. *)
   274 fun arity_cls ({prem_lits, concl_lits, ...} : arity_clause) =
   275   (TrueI,
   276    Metis_Thm.axiom (Metis_LiteralSet.fromList
   277                         (map m_arity_cls (concl_lits :: prem_lits))));
   278 
   279 (* CLASSREL CLAUSE *)
   280 fun m_class_rel_cls (subclass, _) (superclass, _) =
   281   [metis_lit false subclass [Metis_Term.Var "T"],
   282    metis_lit true superclass [Metis_Term.Var "T"]]
   283 fun class_rel_cls ({subclass, superclass, ...} : class_rel_clause) =
   284   (TrueI, m_class_rel_cls subclass superclass
   285           |> Metis_LiteralSet.fromList |> Metis_Thm.axiom)
   286 
   287 fun type_ext thy tms =
   288   let
   289     val subs = tfree_classes_of_terms tms
   290     val supers = tvar_classes_of_terms tms
   291     val tycons = type_consts_of_terms thy tms
   292     val (supers', arity_clauses) = make_arity_clauses thy tycons supers
   293     val class_rel_clauses = make_class_rel_clauses thy subs supers'
   294   in map class_rel_cls class_rel_clauses @ map arity_cls arity_clauses end
   295 
   296 val proxy_defs = map (fst o snd o snd) proxy_table
   297 val prepare_helper =
   298   Meson.make_meta_clause #> rewrite_rule (map safe_mk_meta_eq proxy_defs)
   299 
   300 fun metis_name_from_atp s ary =
   301   AList.lookup (op =) metis_name_table (s, ary) |> the_default (s, false)
   302 fun metis_term_from_atp (ATerm (s, tms)) =
   303   if is_tptp_variable s then
   304     Metis_Term.Var s
   305   else
   306     let val (s, swap) = metis_name_from_atp s (length tms) in
   307       Metis_Term.Fn (s, tms |> map metis_term_from_atp |> swap ? rev)
   308     end
   309 fun metis_atom_from_atp (AAtom tm) =
   310     (case metis_term_from_atp tm of
   311        Metis_Term.Fn x => x
   312      | _ => raise Fail "non CNF -- expected function")
   313   | metis_atom_from_atp _ = raise Fail "not CNF -- expected atom"
   314 fun metis_literal_from_atp (AConn (ANot, [phi])) =
   315     (false, metis_atom_from_atp phi)
   316   | metis_literal_from_atp phi = (true, metis_atom_from_atp phi)
   317 fun metis_literals_from_atp (AConn (AOr, [phi1, phi2])) =
   318     uncurry (union (op =)) (pairself metis_literals_from_atp (phi1, phi2))
   319   | metis_literals_from_atp phi = [metis_literal_from_atp phi]
   320 fun metis_axiom_from_atp clauses (Formula (ident, _, phi, _, _)) =
   321     let
   322       fun some isa =
   323         SOME (phi |> metis_literals_from_atp |> Metis_LiteralSet.fromList
   324                   |> Metis_Thm.axiom, isa)
   325     in
   326       if ident = type_tag_idempotence_helper_name orelse
   327          String.isPrefix lightweight_tags_sym_formula_prefix ident then
   328         Isa_Reflexive_or_Trivial |> some
   329       else if String.isPrefix helper_prefix ident then
   330         case space_explode "_" ident  of
   331           _ :: const :: j :: _ =>
   332           nth (AList.lookup (op =) helper_table const |> the |> snd)
   333               (the (Int.fromString j) - 1)
   334           |> prepare_helper |> Isa_Raw |> some
   335         | _ => raise Fail ("malformed helper identifier " ^ quote ident)
   336       else case try (unprefix conjecture_prefix) ident of
   337         SOME s =>
   338         let val j = the (Int.fromString s) in
   339           if j = length clauses then NONE
   340           else Meson.make_meta_clause (nth clauses j) |> Isa_Raw |> some
   341         end
   342       | NONE => TrueI |> Isa_Raw |> some
   343     end
   344   | metis_axiom_from_atp _ _ = raise Fail "not CNF -- expected formula"
   345 
   346 val default_type_sys = Preds (Polymorphic, Nonmonotonic_Types, Lightweight)
   347 
   348 (* Function to generate metis clauses, including comb and type clauses *)
   349 fun prepare_metis_problem ctxt MX type_sys conj_clauses fact_clauses =
   350     let
   351       val type_sys = type_sys |> the_default default_type_sys
   352       val explicit_apply = NONE
   353       val clauses =
   354         conj_clauses @ fact_clauses
   355         |> (if polymorphism_of_type_sys type_sys = Polymorphic then
   356               I
   357             else
   358               map (pair 0)
   359               #> rpair ctxt
   360               #-> Monomorph.monomorph Monomorph.all_schematic_consts_of
   361               #> fst #> maps (map (zero_var_indexes o snd)))
   362       val (atp_problem, _, _, _, _, _, sym_tab) =
   363         prepare_atp_problem ctxt CNF Hypothesis Axiom type_sys explicit_apply
   364                             false false (map prop_of clauses) @{prop False} []
   365       val axioms =
   366         atp_problem |> maps (map_filter (metis_axiom_from_atp clauses) o snd)
   367     in
   368       (MX, sym_tab,
   369        {axioms = axioms, tfrees = [], old_skolems = [] (* FIXME ### *)})
   370     end
   371   | prepare_metis_problem ctxt mode _ conj_clauses fact_clauses =
   372     let
   373       val thy = Proof_Context.theory_of ctxt
   374       (* The modes FO and FT are sticky. HO can be downgraded to FO. *)
   375       val mode =
   376         if mode = HO andalso
   377            forall (forall (is_quasi_fol_clause thy))
   378                   [conj_clauses, fact_clauses] then
   379           FO
   380         else
   381           mode
   382       fun add_thm is_conjecture (isa_ith, metis_ith)
   383                   {axioms, tfrees, old_skolems} : metis_problem =
   384         let
   385           val (mth, tfree_lits, old_skolems) =
   386             hol_thm_to_fol is_conjecture ctxt mode (length axioms) old_skolems
   387                            metis_ith
   388         in
   389           {axioms = (mth, Isa_Raw isa_ith) :: axioms,
   390            tfrees = union (op =) tfree_lits tfrees, old_skolems = old_skolems}
   391         end;
   392       fun add_type_thm (ith, mth) {axioms, tfrees, old_skolems} =
   393         {axioms = (mth, Isa_Raw ith) :: axioms, tfrees = tfrees,
   394          old_skolems = old_skolems}
   395       fun add_tfrees {axioms, tfrees, old_skolems} =
   396         {axioms = map (rpair (Isa_Raw TrueI) o metis_of_tfree)
   397                       (distinct (op =) tfrees) @ axioms,
   398          tfrees = tfrees, old_skolems = old_skolems}
   399       val problem =
   400         {axioms = [], tfrees = init_tfrees ctxt, old_skolems = []}
   401         |> fold (add_thm true o `Meson.make_meta_clause) conj_clauses
   402         |> add_tfrees
   403         |> fold (add_thm false o `Meson.make_meta_clause) fact_clauses
   404       val clause_lists = map (Metis_Thm.clause o #1) (#axioms problem)
   405       fun is_used c =
   406         exists (Metis_LiteralSet.exists (const_in_metis c o #2)) clause_lists
   407       val problem =
   408         if mode = FO then
   409           problem
   410         else
   411           let
   412             val helper_ths =
   413               helper_table
   414               |> filter (is_used o prefix const_prefix o fst)
   415               |> maps (fn (_, (needs_full_types, thms)) =>
   416                           if needs_full_types andalso mode <> FT then []
   417                           else map (`prepare_helper) thms)
   418           in problem |> fold (add_thm false) helper_ths end
   419       val type_ths = type_ext thy (map prop_of (conj_clauses @ fact_clauses))
   420     in (mode, Symtab.empty, fold add_type_thm type_ths problem) end
   421 
   422 end;