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