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