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