src/HOL/Tools/metis_tools.ML
author wenzelm
Thu Oct 29 14:54:14 2009 +0100 (2009-10-29)
changeset 33305 a103fa7c19cc
parent 33243 17014b1b9353
child 33316 6a72af4e84b8
permissions -rw-r--r--
tuned;
wenzelm@23442
     1
(*  Title:      HOL/Tools/metis_tools.ML
wenzelm@23442
     2
    Author:     Kong W. Susanto and Lawrence C. Paulson, CU Computer Laboratory
wenzelm@23442
     3
    Copyright   Cambridge University 2007
wenzelm@23447
     4
wenzelm@29266
     5
HOL setup for the Metis prover.
wenzelm@23442
     6
*)
wenzelm@23442
     7
wenzelm@23442
     8
signature METIS_TOOLS =
wenzelm@23442
     9
sig
wenzelm@32955
    10
  val trace: bool Unsynchronized.ref
wenzelm@24309
    11
  val type_lits: bool Config.T
wenzelm@24319
    12
  val metis_tac: Proof.context -> thm list -> int -> tactic
wenzelm@24319
    13
  val metisF_tac: Proof.context -> thm list -> int -> tactic
paulson@32532
    14
  val metisFT_tac: Proof.context -> thm list -> int -> tactic
wenzelm@24319
    15
  val setup: theory -> theory
wenzelm@23442
    16
end
wenzelm@23442
    17
wenzelm@23442
    18
structure MetisTools: METIS_TOOLS =
wenzelm@23442
    19
struct
wenzelm@23442
    20
wenzelm@32956
    21
val trace = Unsynchronized.ref false;
wenzelm@32956
    22
fun trace_msg msg = if ! trace then tracing (msg ()) else ();
wenzelm@32955
    23
wenzelm@32956
    24
val (type_lits, type_lits_setup) = Attrib.config_bool "metis_type_lits" true;
wenzelm@23442
    25
wenzelm@32956
    26
datatype mode = FO | HO | FT  (*first-order, higher-order, fully-typed*)
paulson@32532
    27
wenzelm@32956
    28
(* ------------------------------------------------------------------------- *)
wenzelm@32956
    29
(* Useful Theorems                                                           *)
wenzelm@32956
    30
(* ------------------------------------------------------------------------- *)
wenzelm@32956
    31
val EXCLUDED_MIDDLE = rotate_prems 1 (read_instantiate @{context} [(("R", 0), "False")] notE);
wenzelm@32956
    32
val REFL_THM = incr_indexes 2 (Meson.make_meta_clause refl);  (*Rename from 0,1*)
wenzelm@32956
    33
val subst_em  = zero_var_indexes (subst RS EXCLUDED_MIDDLE);
wenzelm@32956
    34
val ssubst_em = read_instantiate @{context} [(("t", 0), "?s"), (("s", 0), "?t")] (sym RS subst_em);
wenzelm@23442
    35
wenzelm@32956
    36
(* ------------------------------------------------------------------------- *)
wenzelm@32956
    37
(* Useful Functions                                                          *)
wenzelm@32956
    38
(* ------------------------------------------------------------------------- *)
wenzelm@23442
    39
wenzelm@32956
    40
(* match untyped terms*)
wenzelm@32956
    41
fun untyped_aconv (Const(a,_))   (Const(b,_))   = (a=b)
wenzelm@32956
    42
  | untyped_aconv (Free(a,_))    (Free(b,_))    = (a=b)
wenzelm@32956
    43
  | untyped_aconv (Var((a,_),_)) (Var((b,_),_)) = (a=b)   (*the index is ignored!*)
wenzelm@32956
    44
  | untyped_aconv (Bound i)      (Bound j)      = (i=j)
wenzelm@32956
    45
  | untyped_aconv (Abs(a,_,t))  (Abs(b,_,u))    = (a=b) andalso untyped_aconv t u
wenzelm@32956
    46
  | untyped_aconv (t1$t2) (u1$u2)  = untyped_aconv t1 u1 andalso untyped_aconv t2 u2
wenzelm@32956
    47
  | untyped_aconv _              _              = false;
wenzelm@23442
    48
wenzelm@32956
    49
(* Finding the relative location of an untyped term within a list of terms *)
wenzelm@32956
    50
fun get_index lit =
wenzelm@32956
    51
  let val lit = Envir.eta_contract lit
wenzelm@32956
    52
      fun get n [] = raise Empty
wenzelm@32956
    53
        | get n (x::xs) = if untyped_aconv lit (Envir.eta_contract (HOLogic.dest_Trueprop x))
wenzelm@32956
    54
                          then n  else get (n+1) xs
wenzelm@32956
    55
  in get 1 end;
wenzelm@23442
    56
wenzelm@32956
    57
(* ------------------------------------------------------------------------- *)
wenzelm@32956
    58
(* HOL to FOL  (Isabelle to Metis)                                           *)
wenzelm@32956
    59
(* ------------------------------------------------------------------------- *)
wenzelm@23442
    60
wenzelm@32956
    61
fun fn_isa_to_met "equal" = "="
wenzelm@32956
    62
  | fn_isa_to_met x       = x;
wenzelm@23442
    63
wenzelm@32956
    64
fun metis_lit b c args = (b, (c, args));
wenzelm@23442
    65
wenzelm@32956
    66
fun hol_type_to_fol (ResClause.AtomV x) = Metis.Term.Var x
wenzelm@32956
    67
  | hol_type_to_fol (ResClause.AtomF x) = Metis.Term.Fn(x,[])
wenzelm@32956
    68
  | hol_type_to_fol (ResClause.Comp(tc,tps)) = Metis.Term.Fn(tc, map hol_type_to_fol tps);
wenzelm@23442
    69
wenzelm@32956
    70
(*These two functions insert type literals before the real literals. That is the
wenzelm@32956
    71
  opposite order from TPTP linkup, but maybe OK.*)
wenzelm@23442
    72
wenzelm@32956
    73
fun hol_term_to_fol_FO tm =
wenzelm@32956
    74
  case ResHolClause.strip_comb tm of
wenzelm@32956
    75
      (ResHolClause.CombConst(c,_,tys), tms) =>
wenzelm@32956
    76
        let val tyargs = map hol_type_to_fol tys
wenzelm@32956
    77
            val args   = map hol_term_to_fol_FO tms
wenzelm@32956
    78
        in Metis.Term.Fn (c, tyargs @ args) end
wenzelm@32956
    79
    | (ResHolClause.CombVar(v,_), []) => Metis.Term.Var v
wenzelm@32956
    80
    | _ => error "hol_term_to_fol_FO";
wenzelm@23442
    81
wenzelm@32994
    82
fun hol_term_to_fol_HO (ResHolClause.CombVar (a, _)) = Metis.Term.Var a
wenzelm@32994
    83
  | hol_term_to_fol_HO (ResHolClause.CombConst (a, _, tylist)) =
wenzelm@32994
    84
      Metis.Term.Fn (fn_isa_to_met a, map hol_type_to_fol tylist)
wenzelm@32994
    85
  | hol_term_to_fol_HO (ResHolClause.CombApp (tm1, tm2)) =
wenzelm@32994
    86
       Metis.Term.Fn (".", map hol_term_to_fol_HO [tm1, tm2]);
wenzelm@23442
    87
wenzelm@32956
    88
(*The fully-typed translation, to avoid type errors*)
wenzelm@32956
    89
fun wrap_type (tm, ty) = Metis.Term.Fn("ti", [tm, hol_type_to_fol ty]);
wenzelm@32956
    90
wenzelm@32956
    91
fun hol_term_to_fol_FT (ResHolClause.CombVar(a, ty)) =
wenzelm@32956
    92
      wrap_type (Metis.Term.Var a, ty)
wenzelm@32956
    93
  | hol_term_to_fol_FT (ResHolClause.CombConst(a, ty, _)) =
wenzelm@32956
    94
      wrap_type (Metis.Term.Fn(fn_isa_to_met a, []), ty)
wenzelm@32956
    95
  | hol_term_to_fol_FT (tm as ResHolClause.CombApp(tm1,tm2)) =
wenzelm@32956
    96
       wrap_type (Metis.Term.Fn(".", map hol_term_to_fol_FT [tm1,tm2]),
wenzelm@32956
    97
                  ResHolClause.type_of_combterm tm);
paulson@32532
    98
wenzelm@32956
    99
fun hol_literal_to_fol FO (ResHolClause.Literal (pol, tm)) =
wenzelm@32956
   100
      let val (ResHolClause.CombConst(p,_,tys), tms) = ResHolClause.strip_comb tm
wenzelm@32956
   101
          val tylits = if p = "equal" then [] else map hol_type_to_fol tys
wenzelm@32956
   102
          val lits = map hol_term_to_fol_FO tms
wenzelm@32956
   103
      in metis_lit pol (fn_isa_to_met p) (tylits @ lits) end
wenzelm@32956
   104
  | hol_literal_to_fol HO (ResHolClause.Literal (pol, tm)) =
wenzelm@32956
   105
     (case ResHolClause.strip_comb tm of
wenzelm@32956
   106
          (ResHolClause.CombConst("equal",_,_), tms) =>
wenzelm@32956
   107
            metis_lit pol "=" (map hol_term_to_fol_HO tms)
wenzelm@32956
   108
        | _ => metis_lit pol "{}" [hol_term_to_fol_HO tm])   (*hBOOL*)
wenzelm@32956
   109
  | hol_literal_to_fol FT (ResHolClause.Literal (pol, tm)) =
wenzelm@32956
   110
     (case ResHolClause.strip_comb tm of
wenzelm@32956
   111
          (ResHolClause.CombConst("equal",_,_), tms) =>
wenzelm@32956
   112
            metis_lit pol "=" (map hol_term_to_fol_FT tms)
wenzelm@32956
   113
        | _ => metis_lit pol "{}" [hol_term_to_fol_FT tm])   (*hBOOL*);
wenzelm@23442
   114
wenzelm@32956
   115
fun literals_of_hol_thm thy mode t =
wenzelm@32956
   116
      let val (lits, types_sorts) = ResHolClause.literals_of_term thy t
wenzelm@32956
   117
      in  (map (hol_literal_to_fol mode) lits, types_sorts) end;
wenzelm@23442
   118
wenzelm@32956
   119
(*Sign should be "true" for conjecture type constraints, "false" for type lits in clauses.*)
wenzelm@32956
   120
fun metis_of_typeLit pos (ResClause.LTVar (s,x))  = metis_lit pos s [Metis.Term.Var x]
wenzelm@32956
   121
  | metis_of_typeLit pos (ResClause.LTFree (s,x)) = metis_lit pos s [Metis.Term.Fn(x,[])];
wenzelm@23442
   122
wenzelm@32994
   123
fun default_sort _ (TVar _) = false
wenzelm@33035
   124
  | default_sort ctxt (TFree (x, s)) = (s = the_default [] (Variable.def_sort ctxt (x, ~1)));
wenzelm@23442
   125
wenzelm@32956
   126
fun metis_of_tfree tf =
wenzelm@32956
   127
  Metis.Thm.axiom (Metis.LiteralSet.singleton (metis_of_typeLit true tf));
paulson@24937
   128
wenzelm@32956
   129
fun hol_thm_to_fol is_conjecture ctxt mode th =
wenzelm@32956
   130
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   131
      val (mlits, types_sorts) =
wenzelm@32956
   132
             (literals_of_hol_thm thy mode o HOLogic.dest_Trueprop o prop_of) th
wenzelm@32956
   133
  in
wenzelm@32956
   134
      if is_conjecture then
wenzelm@32956
   135
          (Metis.Thm.axiom (Metis.LiteralSet.fromList mlits), ResClause.add_typs types_sorts)
wenzelm@32956
   136
      else
wenzelm@32956
   137
        let val tylits = ResClause.add_typs
wenzelm@32956
   138
                           (filter (not o default_sort ctxt) types_sorts)
wenzelm@32956
   139
            val mtylits = if Config.get ctxt type_lits
wenzelm@32956
   140
                          then map (metis_of_typeLit false) tylits else []
wenzelm@32956
   141
        in
wenzelm@32956
   142
          (Metis.Thm.axiom (Metis.LiteralSet.fromList(mtylits @ mlits)), [])
wenzelm@32956
   143
        end
wenzelm@32956
   144
  end;
wenzelm@23442
   145
wenzelm@32956
   146
(* ARITY CLAUSE *)
wenzelm@23442
   147
wenzelm@32956
   148
fun m_arity_cls (ResClause.TConsLit (c,t,args)) =
wenzelm@32956
   149
      metis_lit true (ResClause.make_type_class c) [Metis.Term.Fn(t, map Metis.Term.Var args)]
wenzelm@32956
   150
  | m_arity_cls (ResClause.TVarLit (c,str))     =
wenzelm@32956
   151
      metis_lit false (ResClause.make_type_class c) [Metis.Term.Var str];
wenzelm@23442
   152
wenzelm@32956
   153
(*TrueI is returned as the Isabelle counterpart because there isn't any.*)
wenzelm@32956
   154
fun arity_cls (ResClause.ArityClause{conclLit,premLits,...}) =
wenzelm@32956
   155
  (TrueI,
wenzelm@32956
   156
   Metis.Thm.axiom (Metis.LiteralSet.fromList (map m_arity_cls (conclLit :: premLits))));
wenzelm@23442
   157
wenzelm@32956
   158
(* CLASSREL CLAUSE *)
wenzelm@23442
   159
wenzelm@32956
   160
fun m_classrel_cls subclass superclass =
wenzelm@32956
   161
  [metis_lit false subclass [Metis.Term.Var "T"], metis_lit true superclass [Metis.Term.Var "T"]];
wenzelm@23442
   162
wenzelm@32994
   163
fun classrel_cls (ResClause.ClassrelClause {subclass, superclass, ...}) =
wenzelm@32956
   164
  (TrueI, Metis.Thm.axiom (Metis.LiteralSet.fromList (m_classrel_cls subclass superclass)));
wenzelm@23442
   165
wenzelm@32956
   166
(* ------------------------------------------------------------------------- *)
wenzelm@32956
   167
(* FOL to HOL  (Metis to Isabelle)                                           *)
wenzelm@32956
   168
(* ------------------------------------------------------------------------- *)
wenzelm@23442
   169
wenzelm@32956
   170
datatype term_or_type = Term of Term.term | Type of Term.typ;
wenzelm@23442
   171
wenzelm@32956
   172
fun terms_of [] = []
wenzelm@32956
   173
  | terms_of (Term t :: tts) = t :: terms_of tts
wenzelm@32956
   174
  | terms_of (Type _ :: tts) = terms_of tts;
wenzelm@23442
   175
wenzelm@32956
   176
fun types_of [] = []
wenzelm@32994
   177
  | types_of (Term (Term.Var ((a,idx), _)) :: tts) =
wenzelm@32956
   178
      if String.isPrefix "_" a then
wenzelm@32956
   179
          (*Variable generated by Metis, which might have been a type variable.*)
wenzelm@32994
   180
          TVar (("'" ^ a, idx), HOLogic.typeS) :: types_of tts
wenzelm@32956
   181
      else types_of tts
wenzelm@32956
   182
  | types_of (Term _ :: tts) = types_of tts
wenzelm@32956
   183
  | types_of (Type T :: tts) = T :: types_of tts;
wenzelm@23442
   184
wenzelm@32956
   185
fun apply_list rator nargs rands =
wenzelm@32956
   186
  let val trands = terms_of rands
wenzelm@32956
   187
  in  if length trands = nargs then Term (list_comb(rator, trands))
wenzelm@32956
   188
      else error
wenzelm@32956
   189
        ("apply_list: wrong number of arguments: " ^ Syntax.string_of_term_global Pure.thy rator ^
wenzelm@32956
   190
          " expected " ^ Int.toString nargs ^
wenzelm@32956
   191
          " received " ^ commas (map (Syntax.string_of_term_global Pure.thy) trands))
wenzelm@32956
   192
  end;
wenzelm@23442
   193
wenzelm@24500
   194
fun infer_types ctxt =
wenzelm@24500
   195
  Syntax.check_terms (ProofContext.set_mode ProofContext.mode_pattern ctxt);
wenzelm@25713
   196
wenzelm@32956
   197
(*We use 1 rather than 0 because variable references in clauses may otherwise conflict
wenzelm@32956
   198
  with variable constraints in the goal...at least, type inference often fails otherwise.
wenzelm@32956
   199
  SEE ALSO axiom_inf below.*)
wenzelm@32956
   200
fun mk_var (w,T) = Term.Var((w,1), T);
wenzelm@23442
   201
wenzelm@32956
   202
(*include the default sort, if available*)
wenzelm@32956
   203
fun mk_tfree ctxt w =
wenzelm@32956
   204
  let val ww = "'" ^ w
wenzelm@33035
   205
  in  TFree(ww, the_default HOLogic.typeS (Variable.def_sort ctxt (ww, ~1)))  end;
wenzelm@23442
   206
wenzelm@32956
   207
(*Remove the "apply" operator from an HO term*)
wenzelm@32956
   208
fun strip_happ args (Metis.Term.Fn(".",[t,u])) = strip_happ (u::args) t
wenzelm@32956
   209
  | strip_happ args x = (x, args);
wenzelm@23442
   210
wenzelm@32994
   211
fun fol_type_to_isa _ (Metis.Term.Var v) =
wenzelm@33227
   212
     (case ResReconstruct.strip_prefix ResClause.tvar_prefix v of
wenzelm@33227
   213
          SOME w => ResReconstruct.make_tvar w
wenzelm@33227
   214
        | NONE   => ResReconstruct.make_tvar v)
wenzelm@32956
   215
  | fol_type_to_isa ctxt (Metis.Term.Fn(x, tys)) =
wenzelm@33227
   216
     (case ResReconstruct.strip_prefix ResClause.tconst_prefix x of
wenzelm@33227
   217
          SOME tc => Term.Type (ResReconstruct.invert_type_const tc, map (fol_type_to_isa ctxt) tys)
wenzelm@32956
   218
        | NONE    =>
wenzelm@33227
   219
      case ResReconstruct.strip_prefix ResClause.tfree_prefix x of
wenzelm@32956
   220
          SOME tf => mk_tfree ctxt tf
wenzelm@32956
   221
        | NONE    => error ("fol_type_to_isa: " ^ x));
paulson@32532
   222
wenzelm@32956
   223
(*Maps metis terms to isabelle terms*)
wenzelm@32956
   224
fun fol_term_to_hol_RAW ctxt fol_tm =
wenzelm@32956
   225
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   226
      val _ = trace_msg (fn () => "fol_term_to_hol: " ^ Metis.Term.toString fol_tm)
wenzelm@32956
   227
      fun tm_to_tt (Metis.Term.Var v) =
wenzelm@33227
   228
             (case ResReconstruct.strip_prefix ResClause.tvar_prefix v of
wenzelm@33227
   229
                  SOME w => Type (ResReconstruct.make_tvar w)
wenzelm@32956
   230
                | NONE =>
wenzelm@33227
   231
              case ResReconstruct.strip_prefix ResClause.schematic_var_prefix v of
wenzelm@32956
   232
                  SOME w => Term (mk_var (w, HOLogic.typeT))
wenzelm@32956
   233
                | NONE   => Term (mk_var (v, HOLogic.typeT)) )
wenzelm@32956
   234
                    (*Var from Metis with a name like _nnn; possibly a type variable*)
wenzelm@32956
   235
        | tm_to_tt (Metis.Term.Fn ("{}", [arg])) = tm_to_tt arg   (*hBOOL*)
wenzelm@32956
   236
        | tm_to_tt (t as Metis.Term.Fn (".",_)) =
wenzelm@32956
   237
            let val (rator,rands) = strip_happ [] t
wenzelm@32956
   238
            in  case rator of
wenzelm@32956
   239
                    Metis.Term.Fn(fname,ts) => applic_to_tt (fname, ts @ rands)
wenzelm@32956
   240
                  | _ => case tm_to_tt rator of
wenzelm@32956
   241
                             Term t => Term (list_comb(t, terms_of (map tm_to_tt rands)))
wenzelm@32956
   242
                           | _ => error "tm_to_tt: HO application"
wenzelm@32956
   243
            end
wenzelm@32956
   244
        | tm_to_tt (Metis.Term.Fn (fname, args)) = applic_to_tt (fname,args)
wenzelm@32956
   245
      and applic_to_tt ("=",ts) =
wenzelm@32956
   246
            Term (list_comb(Const ("op =", HOLogic.typeT), terms_of (map tm_to_tt ts)))
wenzelm@32956
   247
        | applic_to_tt (a,ts) =
wenzelm@33227
   248
            case ResReconstruct.strip_prefix ResClause.const_prefix a of
wenzelm@32956
   249
                SOME b =>
wenzelm@33227
   250
                  let val c = ResReconstruct.invert_const b
wenzelm@33227
   251
                      val ntypes = ResReconstruct.num_typargs thy c
wenzelm@32956
   252
                      val nterms = length ts - ntypes
wenzelm@32956
   253
                      val tts = map tm_to_tt ts
wenzelm@32956
   254
                      val tys = types_of (List.take(tts,ntypes))
wenzelm@33227
   255
                      val ntyargs = ResReconstruct.num_typargs thy c
wenzelm@32956
   256
                  in if length tys = ntyargs then
wenzelm@32956
   257
                         apply_list (Const (c, dummyT)) nterms (List.drop(tts,ntypes))
wenzelm@32956
   258
                     else error ("Constant " ^ c ^ " expects " ^ Int.toString ntyargs ^
wenzelm@32956
   259
                                 " but gets " ^ Int.toString (length tys) ^
wenzelm@32956
   260
                                 " type arguments\n" ^
wenzelm@32956
   261
                                 cat_lines (map (Syntax.string_of_typ ctxt) tys) ^
wenzelm@32956
   262
                                 " the terms are \n" ^
wenzelm@32956
   263
                                 cat_lines (map (Syntax.string_of_term ctxt) (terms_of tts)))
wenzelm@32956
   264
                     end
wenzelm@32956
   265
              | NONE => (*Not a constant. Is it a type constructor?*)
wenzelm@33227
   266
            case ResReconstruct.strip_prefix ResClause.tconst_prefix a of
wenzelm@33227
   267
                SOME b =>
wenzelm@33227
   268
                  Type (Term.Type (ResReconstruct.invert_type_const b, types_of (map tm_to_tt ts)))
wenzelm@32956
   269
              | NONE => (*Maybe a TFree. Should then check that ts=[].*)
wenzelm@33227
   270
            case ResReconstruct.strip_prefix ResClause.tfree_prefix a of
wenzelm@32956
   271
                SOME b => Type (mk_tfree ctxt b)
wenzelm@32956
   272
              | NONE => (*a fixed variable? They are Skolem functions.*)
wenzelm@33227
   273
            case ResReconstruct.strip_prefix ResClause.fixed_var_prefix a of
wenzelm@32956
   274
                SOME b =>
wenzelm@32956
   275
                  let val opr = Term.Free(b, HOLogic.typeT)
wenzelm@32956
   276
                  in  apply_list opr (length ts) (map tm_to_tt ts)  end
wenzelm@32956
   277
              | NONE => error ("unexpected metis function: " ^ a)
wenzelm@32956
   278
  in  case tm_to_tt fol_tm of Term t => t | _ => error "fol_tm_to_tt: Term expected"  end;
wenzelm@23442
   279
wenzelm@32956
   280
(*Maps fully-typed metis terms to isabelle terms*)
wenzelm@32956
   281
fun fol_term_to_hol_FT ctxt fol_tm =
wenzelm@32956
   282
  let val _ = trace_msg (fn () => "fol_term_to_hol_FT: " ^ Metis.Term.toString fol_tm)
wenzelm@32994
   283
      fun cvt (Metis.Term.Fn ("ti", [Metis.Term.Var v, _])) =
wenzelm@33227
   284
             (case ResReconstruct.strip_prefix ResClause.schematic_var_prefix v of
wenzelm@32956
   285
                  SOME w =>  mk_var(w, dummyT)
wenzelm@32956
   286
                | NONE   => mk_var(v, dummyT))
wenzelm@32994
   287
        | cvt (Metis.Term.Fn ("ti", [Metis.Term.Fn ("=",[]), _])) =
wenzelm@32956
   288
            Const ("op =", HOLogic.typeT)
wenzelm@32956
   289
        | cvt (Metis.Term.Fn ("ti", [Metis.Term.Fn (x,[]), ty])) =
wenzelm@33227
   290
           (case ResReconstruct.strip_prefix ResClause.const_prefix x of
wenzelm@33227
   291
                SOME c => Const (ResReconstruct.invert_const c, dummyT)
wenzelm@32956
   292
              | NONE => (*Not a constant. Is it a fixed variable??*)
wenzelm@33227
   293
            case ResReconstruct.strip_prefix ResClause.fixed_var_prefix x of
wenzelm@32956
   294
                SOME v => Free (v, fol_type_to_isa ctxt ty)
wenzelm@32956
   295
              | NONE => error ("fol_term_to_hol_FT bad constant: " ^ x))
wenzelm@32956
   296
        | cvt (Metis.Term.Fn ("ti", [Metis.Term.Fn (".",[tm1,tm2]), _])) =
wenzelm@32956
   297
            cvt tm1 $ cvt tm2
wenzelm@32956
   298
        | cvt (Metis.Term.Fn (".",[tm1,tm2])) = (*untyped application*)
wenzelm@32956
   299
            cvt tm1 $ cvt tm2
wenzelm@32956
   300
        | cvt (Metis.Term.Fn ("{}", [arg])) = cvt arg   (*hBOOL*)
wenzelm@32956
   301
        | cvt (Metis.Term.Fn ("=", [tm1,tm2])) =
wenzelm@32956
   302
            list_comb(Const ("op =", HOLogic.typeT), map cvt [tm1,tm2])
wenzelm@32956
   303
        | cvt (t as Metis.Term.Fn (x, [])) =
wenzelm@33227
   304
           (case ResReconstruct.strip_prefix ResClause.const_prefix x of
wenzelm@33227
   305
                SOME c => Const (ResReconstruct.invert_const c, dummyT)
wenzelm@32956
   306
              | NONE => (*Not a constant. Is it a fixed variable??*)
wenzelm@33227
   307
            case ResReconstruct.strip_prefix ResClause.fixed_var_prefix x of
wenzelm@32956
   308
                SOME v => Free (v, dummyT)
wenzelm@33227
   309
              | NONE => (trace_msg (fn () => "fol_term_to_hol_FT bad const: " ^ x);
wenzelm@33227
   310
                  fol_term_to_hol_RAW ctxt t))
wenzelm@33227
   311
        | cvt t = (trace_msg (fn () => "fol_term_to_hol_FT bad term: " ^ Metis.Term.toString t);
wenzelm@33227
   312
            fol_term_to_hol_RAW ctxt t)
wenzelm@32956
   313
  in  cvt fol_tm   end;
paulson@32532
   314
wenzelm@32956
   315
fun fol_term_to_hol ctxt FO = fol_term_to_hol_RAW ctxt
wenzelm@32956
   316
  | fol_term_to_hol ctxt HO = fol_term_to_hol_RAW ctxt
wenzelm@32956
   317
  | fol_term_to_hol ctxt FT = fol_term_to_hol_FT ctxt;
paulson@32532
   318
wenzelm@32956
   319
fun fol_terms_to_hol ctxt mode fol_tms =
wenzelm@32956
   320
  let val ts = map (fol_term_to_hol ctxt mode) fol_tms
wenzelm@32956
   321
      val _ = trace_msg (fn () => "  calling type inference:")
wenzelm@32956
   322
      val _ = app (fn t => trace_msg (fn () => Syntax.string_of_term ctxt t)) ts
wenzelm@32956
   323
      val ts' = infer_types ctxt ts;
wenzelm@32956
   324
      val _ = app (fn t => trace_msg
wenzelm@32956
   325
                    (fn () => "  final term: " ^ Syntax.string_of_term ctxt t ^
wenzelm@32956
   326
                              "  of type  " ^ Syntax.string_of_typ ctxt (type_of t)))
wenzelm@32956
   327
                  ts'
wenzelm@32956
   328
  in  ts'  end;
wenzelm@23442
   329
wenzelm@32956
   330
fun mk_not (Const ("Not", _) $ b) = b
wenzelm@32956
   331
  | mk_not b = HOLogic.mk_not b;
wenzelm@23442
   332
wenzelm@32956
   333
val metis_eq = Metis.Term.Fn ("=", []);
paulson@32532
   334
wenzelm@32956
   335
(* ------------------------------------------------------------------------- *)
wenzelm@32956
   336
(* FOL step Inference Rules                                                  *)
wenzelm@32956
   337
(* ------------------------------------------------------------------------- *)
wenzelm@23442
   338
wenzelm@32956
   339
(*for debugging only*)
wenzelm@32956
   340
fun print_thpair (fth,th) =
wenzelm@32956
   341
  (trace_msg (fn () => "=============================================");
wenzelm@32956
   342
   trace_msg (fn () => "Metis: " ^ Metis.Thm.toString fth);
wenzelm@32956
   343
   trace_msg (fn () => "Isabelle: " ^ Display.string_of_thm_without_context th));
wenzelm@23442
   344
wenzelm@32956
   345
fun lookth thpairs (fth : Metis.Thm.thm) =
wenzelm@33035
   346
  the (AList.lookup (uncurry Metis.Thm.equal) thpairs fth)
wenzelm@32956
   347
  handle Option => error ("Failed to find a Metis theorem " ^ Metis.Thm.toString fth);
wenzelm@23442
   348
wenzelm@32956
   349
fun is_TrueI th = Thm.eq_thm(TrueI,th);
wenzelm@23442
   350
wenzelm@32956
   351
fun cterm_incr_types thy idx = cterm_of thy o (map_types (Logic.incr_tvar idx));
paulson@24974
   352
wenzelm@32956
   353
fun inst_excluded_middle thy i_atm =
wenzelm@32956
   354
  let val th = EXCLUDED_MIDDLE
wenzelm@32956
   355
      val [vx] = Term.add_vars (prop_of th) []
wenzelm@32956
   356
      val substs = [(cterm_of thy (Var vx), cterm_of thy i_atm)]
wenzelm@32956
   357
  in  cterm_instantiate substs th  end;
wenzelm@23442
   358
wenzelm@32956
   359
(* INFERENCE RULE: AXIOM *)
wenzelm@32994
   360
fun axiom_inf thpairs th = incr_indexes 1 (lookth thpairs th);
wenzelm@32956
   361
    (*This causes variables to have an index of 1 by default. SEE ALSO mk_var above.*)
wenzelm@23442
   362
wenzelm@32956
   363
(* INFERENCE RULE: ASSUME *)
wenzelm@32956
   364
fun assume_inf ctxt mode atm =
wenzelm@32956
   365
  inst_excluded_middle
wenzelm@32956
   366
    (ProofContext.theory_of ctxt)
wenzelm@32956
   367
    (singleton (fol_terms_to_hol ctxt mode) (Metis.Term.Fn atm));
wenzelm@23442
   368
wenzelm@32956
   369
(* INFERENCE RULE: INSTANTIATE (Subst). Type instantiations are ignored. Trying to reconstruct
wenzelm@32956
   370
   them admits new possibilities of errors, e.g. concerning sorts. Instead we try to arrange
wenzelm@32956
   371
   that new TVars are distinct and that types can be inferred from terms.*)
wenzelm@32956
   372
fun inst_inf ctxt mode thpairs fsubst th =
wenzelm@32956
   373
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   374
      val i_th   = lookth thpairs th
wenzelm@32956
   375
      val i_th_vars = Term.add_vars (prop_of i_th) []
wenzelm@33035
   376
      fun find_var x = the (List.find (fn ((a,_),_) => a=x) i_th_vars)
wenzelm@32956
   377
      fun subst_translation (x,y) =
wenzelm@32956
   378
            let val v = find_var x
wenzelm@32956
   379
                val t = fol_term_to_hol ctxt mode y (*we call infer_types below*)
wenzelm@32956
   380
            in  SOME (cterm_of thy (Var v), t)  end
wenzelm@32956
   381
            handle Option =>
wenzelm@32956
   382
                (trace_msg (fn() => "List.find failed for the variable " ^ x ^
wenzelm@32956
   383
                                       " in " ^ Display.string_of_thm ctxt i_th);
wenzelm@32956
   384
                 NONE)
wenzelm@32956
   385
      fun remove_typeinst (a, t) =
wenzelm@33227
   386
            case ResReconstruct.strip_prefix ResClause.schematic_var_prefix a of
wenzelm@32956
   387
                SOME b => SOME (b, t)
wenzelm@33227
   388
              | NONE   => case ResReconstruct.strip_prefix ResClause.tvar_prefix a of
wenzelm@32956
   389
                SOME _ => NONE          (*type instantiations are forbidden!*)
wenzelm@32956
   390
              | NONE   => SOME (a,t)    (*internal Metis var?*)
wenzelm@32956
   391
      val _ = trace_msg (fn () => "  isa th: " ^ Display.string_of_thm ctxt i_th)
wenzelm@32956
   392
      val substs = map_filter remove_typeinst (Metis.Subst.toList fsubst)
wenzelm@32956
   393
      val (vars,rawtms) = ListPair.unzip (map_filter subst_translation substs)
wenzelm@32956
   394
      val tms = infer_types ctxt rawtms;
wenzelm@32956
   395
      val ctm_of = cterm_incr_types thy (1 + Thm.maxidx_of i_th)
wenzelm@32956
   396
      val substs' = ListPair.zip (vars, map ctm_of tms)
wenzelm@32956
   397
      val _ = trace_msg (fn () =>
wenzelm@32956
   398
        cat_lines ("subst_translations:" ::
wenzelm@32956
   399
          (substs' |> map (fn (x, y) =>
wenzelm@32956
   400
            Syntax.string_of_term ctxt (term_of x) ^ " |-> " ^
wenzelm@32956
   401
            Syntax.string_of_term ctxt (term_of y)))));
wenzelm@32956
   402
  in  cterm_instantiate substs' i_th
wenzelm@32956
   403
      handle THM (msg, _, _) => error ("metis error (inst_inf): " ^ msg)
wenzelm@32956
   404
  end;
wenzelm@23442
   405
wenzelm@32956
   406
(* INFERENCE RULE: RESOLVE *)
wenzelm@25713
   407
wenzelm@32956
   408
(*Like RSN, but we rename apart only the type variables. Vars here typically have an index
wenzelm@32956
   409
  of 1, and the use of RSN would increase this typically to 3. Instantiations of those Vars
wenzelm@32956
   410
  could then fail. See comment on mk_var.*)
wenzelm@32956
   411
fun resolve_inc_tyvars(tha,i,thb) =
wenzelm@32956
   412
  let val tha = Drule.incr_type_indexes (1 + Thm.maxidx_of thb) tha
wenzelm@32956
   413
      val ths = Seq.list_of (Thm.bicompose false (false,tha,nprems_of tha) i thb)
wenzelm@32956
   414
  in
wenzelm@32956
   415
      case distinct Thm.eq_thm ths of
wenzelm@32956
   416
        [th] => th
wenzelm@32956
   417
      | _ => raise THM ("resolve_inc_tyvars: unique result expected", i, [tha,thb])
wenzelm@32956
   418
  end;
wenzelm@23442
   419
wenzelm@32956
   420
fun resolve_inf ctxt mode thpairs atm th1 th2 =
wenzelm@32956
   421
  let
wenzelm@32956
   422
    val i_th1 = lookth thpairs th1 and i_th2 = lookth thpairs th2
wenzelm@32956
   423
    val _ = trace_msg (fn () => "  isa th1 (pos): " ^ Display.string_of_thm ctxt i_th1)
wenzelm@32956
   424
    val _ = trace_msg (fn () => "  isa th2 (neg): " ^ Display.string_of_thm ctxt i_th2)
wenzelm@32956
   425
  in
wenzelm@32956
   426
    if is_TrueI i_th1 then i_th2 (*Trivial cases where one operand is type info*)
wenzelm@32956
   427
    else if is_TrueI i_th2 then i_th1
wenzelm@32956
   428
    else
wenzelm@32956
   429
      let
wenzelm@32956
   430
        val i_atm = singleton (fol_terms_to_hol ctxt mode) (Metis.Term.Fn atm)
wenzelm@32956
   431
        val _ = trace_msg (fn () => "  atom: " ^ Syntax.string_of_term ctxt i_atm)
wenzelm@32956
   432
        val prems_th1 = prems_of i_th1
wenzelm@32956
   433
        val prems_th2 = prems_of i_th2
wenzelm@32956
   434
        val index_th1 = get_index (mk_not i_atm) prems_th1
wenzelm@32956
   435
              handle Empty => error "Failed to find literal in th1"
wenzelm@32956
   436
        val _ = trace_msg (fn () => "  index_th1: " ^ Int.toString index_th1)
wenzelm@32956
   437
        val index_th2 = get_index i_atm prems_th2
wenzelm@32956
   438
              handle Empty => error "Failed to find literal in th2"
wenzelm@32956
   439
        val _ = trace_msg (fn () => "  index_th2: " ^ Int.toString index_th2)
wenzelm@32956
   440
    in  resolve_inc_tyvars (Meson.select_literal index_th1 i_th1, index_th2, i_th2)  end
wenzelm@32956
   441
  end;
wenzelm@23442
   442
wenzelm@32956
   443
(* INFERENCE RULE: REFL *)
wenzelm@32956
   444
val refl_x = cterm_of @{theory} (Var (hd (Term.add_vars (prop_of REFL_THM) [])));
wenzelm@32956
   445
val refl_idx = 1 + Thm.maxidx_of REFL_THM;
wenzelm@25713
   446
wenzelm@32956
   447
fun refl_inf ctxt mode t =
wenzelm@32956
   448
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   449
      val i_t = singleton (fol_terms_to_hol ctxt mode) t
wenzelm@32956
   450
      val _ = trace_msg (fn () => "  term: " ^ Syntax.string_of_term ctxt i_t)
wenzelm@32956
   451
      val c_t = cterm_incr_types thy refl_idx i_t
wenzelm@32956
   452
  in  cterm_instantiate [(refl_x, c_t)] REFL_THM  end;
wenzelm@23442
   453
wenzelm@32994
   454
fun get_ty_arg_size _ (Const ("op =", _)) = 0  (*equality has no type arguments*)
wenzelm@33227
   455
  | get_ty_arg_size thy (Const (c, _)) = (ResReconstruct.num_typargs thy c handle TYPE _ => 0)
wenzelm@32994
   456
  | get_ty_arg_size _ _ = 0;
wenzelm@23442
   457
wenzelm@32956
   458
(* INFERENCE RULE: EQUALITY *)
wenzelm@32994
   459
fun equality_inf ctxt mode (pos, atm) fp fr =
wenzelm@32956
   460
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   461
      val m_tm = Metis.Term.Fn atm
wenzelm@32956
   462
      val [i_atm,i_tm] = fol_terms_to_hol ctxt mode [m_tm, fr]
wenzelm@32956
   463
      val _ = trace_msg (fn () => "sign of the literal: " ^ Bool.toString pos)
wenzelm@32994
   464
      fun replace_item_list lx 0 (_::ls) = lx::ls
wenzelm@32956
   465
        | replace_item_list lx i (l::ls) = l :: replace_item_list lx (i-1) ls
wenzelm@32956
   466
      fun path_finder_FO tm [] = (tm, Term.Bound 0)
wenzelm@32956
   467
        | path_finder_FO tm (p::ps) =
wenzelm@32956
   468
            let val (tm1,args) = Term.strip_comb tm
wenzelm@32956
   469
                val adjustment = get_ty_arg_size thy tm1
wenzelm@32956
   470
                val p' = if adjustment > p then p else p-adjustment
wenzelm@32956
   471
                val tm_p = List.nth(args,p')
wenzelm@32956
   472
                  handle Subscript => error ("equality_inf: " ^ Int.toString p ^ " adj " ^
wenzelm@32956
   473
                    Int.toString adjustment  ^ " term " ^  Syntax.string_of_term ctxt tm)
wenzelm@32956
   474
                val _ = trace_msg (fn () => "path_finder: " ^ Int.toString p ^
wenzelm@32956
   475
                                      "  " ^ Syntax.string_of_term ctxt tm_p)
wenzelm@32956
   476
                val (r,t) = path_finder_FO tm_p ps
wenzelm@32956
   477
            in
wenzelm@32956
   478
                (r, list_comb (tm1, replace_item_list t p' args))
wenzelm@32956
   479
            end
wenzelm@32956
   480
      fun path_finder_HO tm [] = (tm, Term.Bound 0)
wenzelm@32956
   481
        | path_finder_HO (t$u) (0::ps) = (fn(x,y) => (x, y$u)) (path_finder_HO t ps)
wenzelm@32994
   482
        | path_finder_HO (t$u) (_::ps) = (fn(x,y) => (x, t$y)) (path_finder_HO u ps)
wenzelm@32956
   483
      fun path_finder_FT tm [] _ = (tm, Term.Bound 0)
wenzelm@32994
   484
        | path_finder_FT tm (0::ps) (Metis.Term.Fn ("ti", [t1, _])) =
wenzelm@32956
   485
            path_finder_FT tm ps t1
wenzelm@32994
   486
        | path_finder_FT (t$u) (0::ps) (Metis.Term.Fn (".", [t1, _])) =
wenzelm@32956
   487
            (fn(x,y) => (x, y$u)) (path_finder_FT t ps t1)
wenzelm@32994
   488
        | path_finder_FT (t$u) (1::ps) (Metis.Term.Fn (".", [_, t2])) =
wenzelm@32956
   489
            (fn(x,y) => (x, t$y)) (path_finder_FT u ps t2)
wenzelm@32956
   490
        | path_finder_FT tm ps t = error ("equality_inf, path_finder_FT: path = " ^
wenzelm@32956
   491
                                        space_implode " " (map Int.toString ps) ^
wenzelm@32956
   492
                                        " isa-term: " ^  Syntax.string_of_term ctxt tm ^
wenzelm@32956
   493
                                        " fol-term: " ^ Metis.Term.toString t)
wenzelm@32956
   494
      fun path_finder FO tm ps _ = path_finder_FO tm ps
wenzelm@32956
   495
        | path_finder HO (tm as Const("op =",_) $ _ $ _) (p::ps) _ =
wenzelm@32956
   496
             (*equality: not curried, as other predicates are*)
wenzelm@32956
   497
             if p=0 then path_finder_HO tm (0::1::ps)  (*select first operand*)
wenzelm@32956
   498
             else path_finder_HO tm (p::ps)        (*1 selects second operand*)
wenzelm@32994
   499
        | path_finder HO tm (_ :: ps) (Metis.Term.Fn ("{}", [_])) =
wenzelm@32956
   500
             path_finder_HO tm ps      (*if not equality, ignore head to skip hBOOL*)
wenzelm@32956
   501
        | path_finder FT (tm as Const("op =",_) $ _ $ _) (p::ps)
wenzelm@32956
   502
                            (Metis.Term.Fn ("=", [t1,t2])) =
wenzelm@32956
   503
             (*equality: not curried, as other predicates are*)
wenzelm@32956
   504
             if p=0 then path_finder_FT tm (0::1::ps)
wenzelm@32956
   505
                          (Metis.Term.Fn (".", [Metis.Term.Fn (".", [metis_eq,t1]), t2]))
wenzelm@32956
   506
                          (*select first operand*)
wenzelm@32956
   507
             else path_finder_FT tm (p::ps)
wenzelm@32956
   508
                   (Metis.Term.Fn (".", [metis_eq,t2]))
wenzelm@32956
   509
                   (*1 selects second operand*)
wenzelm@32994
   510
        | path_finder FT tm (_ :: ps) (Metis.Term.Fn ("{}", [t1])) = path_finder_FT tm ps t1
wenzelm@32956
   511
             (*if not equality, ignore head to skip the hBOOL predicate*)
wenzelm@32956
   512
        | path_finder FT tm ps t = path_finder_FT tm ps t  (*really an error case!*)
wenzelm@32956
   513
      fun path_finder_lit ((nt as Term.Const ("Not", _)) $ tm_a) idx =
wenzelm@32956
   514
            let val (tm, tm_rslt) = path_finder mode tm_a idx m_tm
wenzelm@32956
   515
            in (tm, nt $ tm_rslt) end
wenzelm@32956
   516
        | path_finder_lit tm_a idx = path_finder mode tm_a idx m_tm
wenzelm@32956
   517
      val (tm_subst, body) = path_finder_lit i_atm fp
wenzelm@32956
   518
      val tm_abs = Term.Abs("x", Term.type_of tm_subst, body)
wenzelm@32956
   519
      val _ = trace_msg (fn () => "abstraction: " ^ Syntax.string_of_term ctxt tm_abs)
wenzelm@32956
   520
      val _ = trace_msg (fn () => "i_tm: " ^ Syntax.string_of_term ctxt i_tm)
wenzelm@32956
   521
      val _ = trace_msg (fn () => "located term: " ^ Syntax.string_of_term ctxt tm_subst)
wenzelm@32956
   522
      val imax = maxidx_of_term (i_tm $ tm_abs $ tm_subst)  (*ill typed but gives right max*)
wenzelm@32956
   523
      val subst' = incr_indexes (imax+1) (if pos then subst_em else ssubst_em)
wenzelm@32956
   524
      val _ = trace_msg (fn () => "subst' " ^ Display.string_of_thm ctxt subst')
wenzelm@32956
   525
      val eq_terms = map (pairself (cterm_of thy))
wenzelm@33227
   526
        (ListPair.zip (OldTerm.term_vars (prop_of subst'), [tm_abs, tm_subst, i_tm]))
wenzelm@32956
   527
  in  cterm_instantiate eq_terms subst'  end;
wenzelm@23442
   528
wenzelm@32956
   529
val factor = Seq.hd o distinct_subgoals_tac;
paulson@28528
   530
wenzelm@32994
   531
fun step _ _ thpairs (fol_th, Metis.Proof.Axiom _) = factor (axiom_inf thpairs fol_th)
wenzelm@32994
   532
  | step ctxt mode _ (_, Metis.Proof.Assume f_atm) = assume_inf ctxt mode f_atm
wenzelm@32994
   533
  | step ctxt mode thpairs (_, Metis.Proof.Subst (f_subst, f_th1)) =
wenzelm@32956
   534
      factor (inst_inf ctxt mode thpairs f_subst f_th1)
wenzelm@32994
   535
  | step ctxt mode thpairs (_, Metis.Proof.Resolve(f_atm, f_th1, f_th2)) =
wenzelm@32956
   536
      factor (resolve_inf ctxt mode thpairs f_atm f_th1 f_th2)
wenzelm@32994
   537
  | step ctxt mode _ (_, Metis.Proof.Refl f_tm) = refl_inf ctxt mode f_tm
wenzelm@32994
   538
  | step ctxt mode _ (_, Metis.Proof.Equality (f_lit, f_p, f_r)) =
wenzelm@32994
   539
      equality_inf ctxt mode f_lit f_p f_r;
wenzelm@23442
   540
wenzelm@32994
   541
fun real_literal (_, (c, _)) = not (String.isPrefix ResClause.class_prefix c);
wenzelm@23442
   542
wenzelm@32994
   543
fun translate _ _ thpairs [] = thpairs
wenzelm@32956
   544
  | translate mode ctxt thpairs ((fol_th, inf) :: infpairs) =
wenzelm@32956
   545
      let val _ = trace_msg (fn () => "=============================================")
wenzelm@32956
   546
          val _ = trace_msg (fn () => "METIS THM: " ^ Metis.Thm.toString fol_th)
wenzelm@32956
   547
          val _ = trace_msg (fn () => "INFERENCE: " ^ Metis.Proof.inferenceToString inf)
wenzelm@32956
   548
          val th = Meson.flexflex_first_order (step ctxt mode thpairs (fol_th, inf))
wenzelm@32956
   549
          val _ = trace_msg (fn () => "ISABELLE THM: " ^ Display.string_of_thm ctxt th)
wenzelm@32956
   550
          val _ = trace_msg (fn () => "=============================================")
wenzelm@32994
   551
          val n_metis_lits =
wenzelm@32994
   552
            length (filter real_literal (Metis.LiteralSet.toList (Metis.Thm.clause fol_th)))
wenzelm@32956
   553
      in
wenzelm@32956
   554
          if nprems_of th = n_metis_lits then ()
wenzelm@32956
   555
          else error "Metis: proof reconstruction has gone wrong";
wenzelm@32956
   556
          translate mode ctxt ((fol_th, th) :: thpairs) infpairs
wenzelm@32956
   557
      end;
wenzelm@23442
   558
wenzelm@32956
   559
(*Determining which axiom clauses are actually used*)
wenzelm@32956
   560
fun used_axioms axioms (th, Metis.Proof.Axiom _) = SOME (lookth axioms th)
wenzelm@32994
   561
  | used_axioms _ _ = NONE;
paulson@24855
   562
wenzelm@32956
   563
(* ------------------------------------------------------------------------- *)
wenzelm@32956
   564
(* Translation of HO Clauses                                                 *)
wenzelm@32956
   565
(* ------------------------------------------------------------------------- *)
wenzelm@23442
   566
wenzelm@32956
   567
fun cnf_th thy th = hd (ResAxioms.cnf_axiom thy th);
wenzelm@23442
   568
wenzelm@32956
   569
val equal_imp_fequal' = cnf_th @{theory} @{thm equal_imp_fequal};
wenzelm@32956
   570
val fequal_imp_equal' = cnf_th @{theory} @{thm fequal_imp_equal};
wenzelm@23442
   571
wenzelm@32956
   572
val comb_I = cnf_th @{theory} ResHolClause.comb_I;
wenzelm@32956
   573
val comb_K = cnf_th @{theory} ResHolClause.comb_K;
wenzelm@32956
   574
val comb_B = cnf_th @{theory} ResHolClause.comb_B;
wenzelm@32956
   575
val comb_C = cnf_th @{theory} ResHolClause.comb_C;
wenzelm@32956
   576
val comb_S = cnf_th @{theory} ResHolClause.comb_S;
wenzelm@23442
   577
wenzelm@32956
   578
fun type_ext thy tms =
wenzelm@32956
   579
  let val subs = ResAtp.tfree_classes_of_terms tms
wenzelm@32956
   580
      val supers = ResAtp.tvar_classes_of_terms tms
wenzelm@32956
   581
      and tycons = ResAtp.type_consts_of_terms thy tms
wenzelm@32994
   582
      val (supers', arity_clauses) = ResClause.make_arity_clauses thy tycons supers
wenzelm@32956
   583
      val classrel_clauses = ResClause.make_classrel_clauses thy subs supers'
wenzelm@32956
   584
  in  map classrel_cls classrel_clauses @ map arity_cls arity_clauses
wenzelm@32956
   585
  end;
wenzelm@23442
   586
wenzelm@32956
   587
(* ------------------------------------------------------------------------- *)
wenzelm@32956
   588
(* Logic maps manage the interface between HOL and first-order logic.        *)
wenzelm@32956
   589
(* ------------------------------------------------------------------------- *)
wenzelm@23442
   590
wenzelm@32956
   591
type logic_map =
wenzelm@33243
   592
  {axioms : (Metis.Thm.thm * thm) list,
wenzelm@32956
   593
   tfrees : ResClause.type_literal list};
wenzelm@23442
   594
wenzelm@32994
   595
fun const_in_metis c (pred, tm_list) =
wenzelm@32956
   596
  let
wenzelm@32994
   597
    fun in_mterm (Metis.Term.Var _) = false
wenzelm@32956
   598
      | in_mterm (Metis.Term.Fn (".", tm_list)) = exists in_mterm tm_list
wenzelm@32956
   599
      | in_mterm (Metis.Term.Fn (nm, tm_list)) = c=nm orelse exists in_mterm tm_list
wenzelm@32994
   600
  in  c = pred orelse exists in_mterm tm_list  end;
wenzelm@23442
   601
wenzelm@32956
   602
(*Extract TFree constraints from context to include as conjecture clauses*)
wenzelm@32956
   603
fun init_tfrees ctxt =
wenzelm@32956
   604
  let fun add ((a,i),s) Ts = if i = ~1 then TFree(a,s) :: Ts else Ts
wenzelm@32956
   605
  in  ResClause.add_typs (Vartab.fold add (#2 (Variable.constraints_of ctxt)) []) end;
paulson@24937
   606
wenzelm@32956
   607
(*transform isabelle type / arity clause to metis clause *)
wenzelm@32956
   608
fun add_type_thm [] lmap = lmap
wenzelm@32956
   609
  | add_type_thm ((ith, mth) :: cls) {axioms, tfrees} =
wenzelm@32956
   610
      add_type_thm cls {axioms = (mth, ith) :: axioms,
wenzelm@32956
   611
                        tfrees = tfrees}
wenzelm@23442
   612
wenzelm@32956
   613
(*Insert non-logical axioms corresponding to all accumulated TFrees*)
wenzelm@32956
   614
fun add_tfrees {axioms, tfrees} : logic_map =
wenzelm@32956
   615
     {axioms = (map (fn tf => (metis_of_tfree tf, TrueI)) (distinct op= tfrees)) @ axioms,
wenzelm@32956
   616
      tfrees = tfrees};
wenzelm@25713
   617
wenzelm@32956
   618
fun string_of_mode FO = "FO"
wenzelm@32956
   619
  | string_of_mode HO = "HO"
wenzelm@32956
   620
  | string_of_mode FT = "FT"
paulson@32532
   621
wenzelm@32956
   622
(* Function to generate metis clauses, including comb and type clauses *)
wenzelm@32956
   623
fun build_map mode0 ctxt cls ths =
wenzelm@32956
   624
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   625
      (*The modes FO and FT are sticky. HO can be downgraded to FO.*)
wenzelm@32956
   626
      fun set_mode FO = FO
wenzelm@32956
   627
        | set_mode HO = if forall (Meson.is_fol_term thy o prop_of) (cls@ths) then FO else HO
wenzelm@32956
   628
        | set_mode FT = FT
wenzelm@32956
   629
      val mode = set_mode mode0
wenzelm@32956
   630
      (*transform isabelle clause to metis clause *)
wenzelm@32956
   631
      fun add_thm is_conjecture (ith, {axioms, tfrees}) : logic_map =
wenzelm@32956
   632
        let val (mth, tfree_lits) = hol_thm_to_fol is_conjecture ctxt mode ith
wenzelm@32956
   633
        in
wenzelm@32956
   634
           {axioms = (mth, Meson.make_meta_clause ith) :: axioms,
haftmann@33042
   635
            tfrees = union (op =) tfree_lits tfrees}
wenzelm@32956
   636
        end;
wenzelm@32956
   637
      val lmap0 = List.foldl (add_thm true)
wenzelm@32956
   638
                        {axioms = [], tfrees = init_tfrees ctxt} cls
wenzelm@32956
   639
      val lmap = List.foldl (add_thm false) (add_tfrees lmap0) ths
wenzelm@32956
   640
      val clause_lists = map (Metis.Thm.clause o #1) (#axioms lmap)
wenzelm@32994
   641
      fun used c = exists (Metis.LiteralSet.exists (const_in_metis c o #2)) clause_lists
wenzelm@32956
   642
      (*Now check for the existence of certain combinators*)
wenzelm@32956
   643
      val thI  = if used "c_COMBI" then [comb_I] else []
wenzelm@32956
   644
      val thK  = if used "c_COMBK" then [comb_K] else []
wenzelm@32956
   645
      val thB   = if used "c_COMBB" then [comb_B] else []
wenzelm@32956
   646
      val thC   = if used "c_COMBC" then [comb_C] else []
wenzelm@32956
   647
      val thS   = if used "c_COMBS" then [comb_S] else []
wenzelm@32956
   648
      val thEQ  = if used "c_fequal" then [fequal_imp_equal', equal_imp_fequal'] else []
wenzelm@32956
   649
      val lmap' = if mode=FO then lmap
wenzelm@32956
   650
                  else List.foldl (add_thm false) lmap (thEQ @ thS @ thC @ thB @ thK @ thI)
wenzelm@32956
   651
  in
wenzelm@32956
   652
      (mode, add_type_thm (type_ext thy (map prop_of (cls @ ths))) lmap')
wenzelm@32956
   653
  end;
wenzelm@23442
   654
wenzelm@32956
   655
fun refute cls =
wenzelm@32956
   656
    Metis.Resolution.loop (Metis.Resolution.new Metis.Resolution.default cls);
wenzelm@23442
   657
wenzelm@32956
   658
fun is_false t = t aconv (HOLogic.mk_Trueprop HOLogic.false_const);
wenzelm@23442
   659
wenzelm@32956
   660
fun common_thm ths1 ths2 = exists (member Thm.eq_thm ths1) (map Meson.make_meta_clause ths2);
paulson@24855
   661
wenzelm@32956
   662
exception METIS of string;
paulson@28233
   663
wenzelm@32956
   664
(* Main function to start metis prove and reconstruction *)
wenzelm@32956
   665
fun FOL_SOLVE mode ctxt cls ths0 =
wenzelm@32956
   666
  let val thy = ProofContext.theory_of ctxt
wenzelm@32956
   667
      val th_cls_pairs = map (fn th => (Thm.get_name_hint th, ResAxioms.cnf_axiom thy th)) ths0
wenzelm@32956
   668
      val ths = maps #2 th_cls_pairs
wenzelm@32956
   669
      val _ = trace_msg (fn () => "FOL_SOLVE: CONJECTURE CLAUSES")
wenzelm@32956
   670
      val _ = app (fn th => trace_msg (fn () => Display.string_of_thm ctxt th)) cls
wenzelm@32956
   671
      val _ = trace_msg (fn () => "THEOREM CLAUSES")
wenzelm@32956
   672
      val _ = app (fn th => trace_msg (fn () => Display.string_of_thm ctxt th)) ths
wenzelm@32956
   673
      val (mode, {axioms,tfrees}) = build_map mode ctxt cls ths
wenzelm@32956
   674
      val _ = if null tfrees then ()
wenzelm@32956
   675
              else (trace_msg (fn () => "TFREE CLAUSES");
wenzelm@32956
   676
                    app (fn tf => trace_msg (fn _ => ResClause.tptp_of_typeLit true tf)) tfrees)
wenzelm@32956
   677
      val _ = trace_msg (fn () => "CLAUSES GIVEN TO METIS")
wenzelm@32956
   678
      val thms = map #1 axioms
wenzelm@32956
   679
      val _ = app (fn th => trace_msg (fn () => Metis.Thm.toString th)) thms
wenzelm@32956
   680
      val _ = trace_msg (fn () => "mode = " ^ string_of_mode mode)
wenzelm@32956
   681
      val _ = trace_msg (fn () => "START METIS PROVE PROCESS")
wenzelm@32956
   682
  in
wenzelm@32956
   683
      case List.filter (is_false o prop_of) cls of
wenzelm@32956
   684
          false_th::_ => [false_th RS @{thm FalseE}]
wenzelm@32956
   685
        | [] =>
wenzelm@32956
   686
      case refute thms of
wenzelm@32956
   687
          Metis.Resolution.Contradiction mth =>
wenzelm@32956
   688
            let val _ = trace_msg (fn () => "METIS RECONSTRUCTION START: " ^
wenzelm@32956
   689
                          Metis.Thm.toString mth)
wenzelm@32956
   690
                val ctxt' = fold Variable.declare_constraints (map prop_of cls) ctxt
wenzelm@32956
   691
                             (*add constraints arising from converting goal to clause form*)
wenzelm@32956
   692
                val proof = Metis.Proof.proof mth
wenzelm@32956
   693
                val result = translate mode ctxt' axioms proof
wenzelm@32956
   694
                and used = map_filter (used_axioms axioms) proof
wenzelm@32956
   695
                val _ = trace_msg (fn () => "METIS COMPLETED...clauses actually used:")
wenzelm@32956
   696
                val _ = app (fn th => trace_msg (fn () => Display.string_of_thm ctxt th)) used
wenzelm@33305
   697
                val unused = th_cls_pairs |> map_filter (fn (name, cls) =>
wenzelm@33305
   698
                  if common_thm used cls then NONE else SOME name)
wenzelm@32956
   699
            in
wenzelm@32956
   700
                if null unused then ()
wenzelm@33305
   701
                else warning ("Metis: unused theorems " ^ commas_quote unused);
wenzelm@32956
   702
                case result of
wenzelm@32956
   703
                    (_,ith)::_ =>
wenzelm@32956
   704
                        (trace_msg (fn () => "success: " ^ Display.string_of_thm ctxt ith);
wenzelm@32956
   705
                         [ith])
wenzelm@32956
   706
                  | _ => (trace_msg (fn () => "Metis: no result");
wenzelm@32956
   707
                          [])
wenzelm@32956
   708
            end
wenzelm@32956
   709
        | Metis.Resolution.Satisfiable _ =>
wenzelm@32956
   710
            (trace_msg (fn () => "Metis: No first-order proof with the lemmas supplied");
wenzelm@32956
   711
             [])
wenzelm@32956
   712
  end;
wenzelm@23442
   713
wenzelm@32956
   714
fun metis_general_tac mode ctxt ths i st0 =
wenzelm@32956
   715
  let val _ = trace_msg (fn () =>
wenzelm@32956
   716
        "Metis called with theorems " ^ cat_lines (map (Display.string_of_thm ctxt) ths))
wenzelm@32956
   717
  in
wenzelm@32956
   718
     if exists_type ResAxioms.type_has_empty_sort (prop_of st0)
wenzelm@32956
   719
     then (warning "Proof state contains the empty sort"; Seq.empty)
wenzelm@32956
   720
     else
wenzelm@32956
   721
       (Meson.MESON ResAxioms.neg_clausify
wenzelm@32956
   722
         (fn cls => resolve_tac (FOL_SOLVE mode ctxt cls ths) 1) ctxt i
wenzelm@32956
   723
        THEN ResAxioms.expand_defs_tac st0) st0
wenzelm@32956
   724
  end
wenzelm@32956
   725
  handle METIS s => (warning ("Metis: " ^ s); Seq.empty);
wenzelm@23442
   726
wenzelm@32956
   727
val metis_tac = metis_general_tac HO;
wenzelm@32956
   728
val metisF_tac = metis_general_tac FO;
wenzelm@32956
   729
val metisFT_tac = metis_general_tac FT;
wenzelm@23442
   730
wenzelm@32956
   731
fun method name mode comment = Method.setup name (Attrib.thms >> (fn ths => fn ctxt =>
wenzelm@32956
   732
  SIMPLE_METHOD' (CHANGED_PROP o metis_general_tac mode ctxt ths))) comment;
wenzelm@23442
   733
wenzelm@32956
   734
val setup =
wenzelm@32956
   735
  type_lits_setup #>
wenzelm@32956
   736
  method @{binding metis} HO "METIS for FOL & HOL problems" #>
wenzelm@32956
   737
  method @{binding metisF} FO "METIS for FOL problems" #>
wenzelm@32956
   738
  method @{binding metisFT} FT "METIS With-fully typed translation" #>
wenzelm@32956
   739
  Method.setup @{binding finish_clausify}
wenzelm@32956
   740
    (Scan.succeed (K (SIMPLE_METHOD (ResAxioms.expand_defs_tac refl))))
wenzelm@32956
   741
    "cleanup after conversion to clauses";
wenzelm@23442
   742
wenzelm@23442
   743
end;