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