src/HOL/Tools/Metis/metis_reconstruct.ML
author blanchet
Tue, 31 May 2011 16:38:36 +0200
changeset 43935 269300fb83d0
parent 43934 40e50afbc203
child 43936 ccf1c09dea82
permissions -rw-r--r--
more work on new Metis
blanchet@40139
     1
(*  Title:      HOL/Tools/Metis/metis_reconstruct.ML
blanchet@39735
     2
    Author:     Kong W. Susanto, Cambridge University Computer Laboratory
blanchet@39735
     3
    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory
blanchet@39735
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@39735
     5
    Copyright   Cambridge University 2007
blanchet@39735
     6
blanchet@39735
     7
Proof reconstruction for Metis.
blanchet@39735
     8
*)
blanchet@39735
     9
blanchet@39735
    10
signature METIS_RECONSTRUCT =
blanchet@39735
    11
sig
blanchet@39737
    12
  type mode = Metis_Translate.mode
blanchet@39737
    13
blanchet@43521
    14
  exception METIS of string * string
blanchet@43521
    15
blanchet@40159
    16
  val trace : bool Config.T
blanchet@40159
    17
  val trace_msg : Proof.context -> (unit -> string) -> unit
blanchet@40913
    18
  val verbose : bool Config.T
blanchet@40913
    19
  val verbose_warning : Proof.context -> string -> unit
blanchet@39737
    20
  val lookth : (Metis_Thm.thm * 'a) list -> Metis_Thm.thm -> 'a
blanchet@40068
    21
  val untyped_aconv : term -> term -> bool
blanchet@39737
    22
  val replay_one_inference :
blanchet@43935
    23
    Proof.context -> mode -> (string * term) list -> int Symtab.table
blanchet@39737
    24
    -> Metis_Thm.thm * Metis_Proof.inference -> (Metis_Thm.thm * thm) list
blanchet@39737
    25
    -> (Metis_Thm.thm * thm) list
blanchet@40145
    26
  val discharge_skolem_premises :
blanchet@40145
    27
    Proof.context -> (thm * term) option list -> thm -> thm
blanchet@39735
    28
end;
blanchet@39735
    29
blanchet@39735
    30
structure Metis_Reconstruct : METIS_RECONSTRUCT =
blanchet@39735
    31
struct
blanchet@39735
    32
blanchet@43935
    33
open ATP_Problem
blanchet@43926
    34
open ATP_Translate
blanchet@43935
    35
open ATP_Reconstruct
blanchet@39737
    36
open Metis_Translate
blanchet@39737
    37
blanchet@43521
    38
exception METIS of string * string
blanchet@43521
    39
wenzelm@43487
    40
val trace = Attrib.setup_config_bool @{binding metis_trace} (K false)
wenzelm@43487
    41
val verbose = Attrib.setup_config_bool @{binding metis_verbose} (K true)
blanchet@40159
    42
blanchet@40159
    43
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@40913
    44
fun verbose_warning ctxt msg =
blanchet@43521
    45
  if Config.get ctxt verbose then warning ("Metis: " ^ msg) else ()
blanchet@39737
    46
blanchet@39738
    47
datatype term_or_type = SomeTerm of term | SomeType of typ
blanchet@39737
    48
blanchet@39737
    49
fun terms_of [] = []
blanchet@39738
    50
  | terms_of (SomeTerm t :: tts) = t :: terms_of tts
blanchet@39738
    51
  | terms_of (SomeType _ :: tts) = terms_of tts;
blanchet@39737
    52
blanchet@39737
    53
fun types_of [] = []
blanchet@39738
    54
  | types_of (SomeTerm (Var ((a,idx), _)) :: tts) =
blanchet@42962
    55
      if String.isPrefix metis_generated_var_prefix a then
blanchet@39737
    56
          (*Variable generated by Metis, which might have been a type variable.*)
blanchet@39737
    57
          TVar (("'" ^ a, idx), HOLogic.typeS) :: types_of tts
blanchet@39737
    58
      else types_of tts
blanchet@39738
    59
  | types_of (SomeTerm _ :: tts) = types_of tts
blanchet@39738
    60
  | types_of (SomeType T :: tts) = T :: types_of tts;
blanchet@39737
    61
blanchet@39737
    62
fun apply_list rator nargs rands =
blanchet@39737
    63
  let val trands = terms_of rands
blanchet@39738
    64
  in  if length trands = nargs then SomeTerm (list_comb(rator, trands))
blanchet@39737
    65
      else raise Fail
blanchet@39737
    66
        ("apply_list: wrong number of arguments: " ^ Syntax.string_of_term_global Pure.thy rator ^
wenzelm@41739
    67
          " expected " ^ string_of_int nargs ^
blanchet@39737
    68
          " received " ^ commas (map (Syntax.string_of_term_global Pure.thy) trands))
blanchet@39737
    69
  end;
blanchet@39737
    70
blanchet@39737
    71
fun infer_types ctxt =
wenzelm@43232
    72
  Syntax.check_terms (Proof_Context.set_mode Proof_Context.mode_pattern ctxt);
blanchet@39737
    73
blanchet@43935
    74
(* We use 1 rather than 0 because variable references in clauses may otherwise
blanchet@43935
    75
   conflict with variable constraints in the goal...at least, type inference
blanchet@43935
    76
   often fails otherwise. See also "axiom_inf" below. *)
blanchet@39738
    77
fun mk_var (w, T) = Var ((w, 1), T)
blanchet@39737
    78
blanchet@39737
    79
(*include the default sort, if available*)
blanchet@39737
    80
fun mk_tfree ctxt w =
blanchet@39737
    81
  let val ww = "'" ^ w
blanchet@39737
    82
  in  TFree(ww, the_default HOLogic.typeS (Variable.def_sort ctxt (ww, ~1)))  end;
blanchet@39737
    83
blanchet@39737
    84
(*Remove the "apply" operator from an HO term*)
blanchet@43935
    85
fun strip_happ args (Metis_Term.Fn (".", [t, u])) = strip_happ (u :: args) t
blanchet@43935
    86
  | strip_happ args x = (x, args)
blanchet@39737
    87
blanchet@39737
    88
fun make_tvar s = TVar (("'" ^ s, 0), HOLogic.typeS)
blanchet@39737
    89
blanchet@39737
    90
fun hol_type_from_metis_term _ (Metis_Term.Var v) =
blanchet@39737
    91
     (case strip_prefix_and_unascii tvar_prefix v of
blanchet@39737
    92
          SOME w => make_tvar w
blanchet@39737
    93
        | NONE   => make_tvar v)
blanchet@39737
    94
  | hol_type_from_metis_term ctxt (Metis_Term.Fn(x, tys)) =
blanchet@39737
    95
     (case strip_prefix_and_unascii type_const_prefix x of
blanchet@41388
    96
          SOME tc => Type (invert_const tc,
blanchet@39738
    97
                           map (hol_type_from_metis_term ctxt) tys)
blanchet@39737
    98
        | NONE    =>
blanchet@39737
    99
      case strip_prefix_and_unascii tfree_prefix x of
blanchet@39737
   100
          SOME tf => mk_tfree ctxt tf
blanchet@39737
   101
        | NONE    => raise Fail ("hol_type_from_metis_term: " ^ x));
blanchet@39737
   102
blanchet@39737
   103
(*Maps metis terms to isabelle terms*)
blanchet@43212
   104
fun hol_term_from_metis_PT ctxt fol_tm =
wenzelm@43232
   105
  let val thy = Proof_Context.theory_of ctxt
blanchet@40159
   106
      val _ = trace_msg ctxt (fn () => "hol_term_from_metis_PT: " ^
blanchet@40159
   107
                                       Metis_Term.toString fol_tm)
blanchet@39737
   108
      fun tm_to_tt (Metis_Term.Var v) =
blanchet@39737
   109
             (case strip_prefix_and_unascii tvar_prefix v of
blanchet@39738
   110
                  SOME w => SomeType (make_tvar w)
blanchet@39737
   111
                | NONE =>
blanchet@39737
   112
              case strip_prefix_and_unascii schematic_var_prefix v of
blanchet@39738
   113
                  SOME w => SomeTerm (mk_var (w, HOLogic.typeT))
blanchet@43134
   114
                | NONE   => SomeTerm (mk_var (v, HOLogic.typeT)))
blanchet@39737
   115
                    (*Var from Metis with a name like _nnn; possibly a type variable*)
blanchet@39737
   116
        | tm_to_tt (Metis_Term.Fn ("{}", [arg])) = tm_to_tt arg   (*hBOOL*)
blanchet@43935
   117
        | tm_to_tt (t as Metis_Term.Fn (".", _)) =
blanchet@43935
   118
            let val (rator,rands) = strip_happ [] t in
blanchet@43935
   119
              case rator of
blanchet@43935
   120
                Metis_Term.Fn(fname,ts) => applic_to_tt (fname, ts @ rands)
blanchet@43935
   121
              | _ => case tm_to_tt rator of
blanchet@43935
   122
                         SomeTerm t => SomeTerm (list_comb(t, terms_of (map tm_to_tt rands)))
blanchet@43935
   123
                       | _ => raise Fail "tm_to_tt: HO application"
blanchet@39737
   124
            end
blanchet@39737
   125
        | tm_to_tt (Metis_Term.Fn (fname, args)) = applic_to_tt (fname,args)
blanchet@39737
   126
      and applic_to_tt ("=",ts) =
blanchet@39738
   127
            SomeTerm (list_comb(Const (@{const_name HOL.eq}, HOLogic.typeT), terms_of (map tm_to_tt ts)))
blanchet@39737
   128
        | applic_to_tt (a,ts) =
blanchet@39737
   129
            case strip_prefix_and_unascii const_prefix a of
blanchet@39737
   130
                SOME b =>
blanchet@40067
   131
                  let
blanchet@43441
   132
                    val c = b |> invert_const |> unproxify_const
blanchet@40067
   133
                    val ntypes = num_type_args thy c
blanchet@40067
   134
                    val nterms = length ts - ntypes
blanchet@40067
   135
                    val tts = map tm_to_tt ts
blanchet@40067
   136
                    val tys = types_of (List.take(tts,ntypes))
blanchet@40120
   137
                    val t =
blanchet@40120
   138
                      if String.isPrefix new_skolem_const_prefix c then
blanchet@43212
   139
                        Var ((new_skolem_var_name_from_const c, 1),
blanchet@40120
   140
                             Type_Infer.paramify_vars (tl tys ---> hd tys))
blanchet@40120
   141
                      else
blanchet@40120
   142
                        Const (c, dummyT)
blanchet@39737
   143
                  in if length tys = ntypes then
blanchet@40067
   144
                         apply_list t nterms (List.drop(tts,ntypes))
blanchet@39737
   145
                     else
wenzelm@41739
   146
                       raise Fail ("Constant " ^ c ^ " expects " ^ string_of_int ntypes ^
wenzelm@41739
   147
                                   " but gets " ^ string_of_int (length tys) ^
blanchet@39737
   148
                                   " type arguments\n" ^
blanchet@39737
   149
                                   cat_lines (map (Syntax.string_of_typ ctxt) tys) ^
blanchet@39737
   150
                                   " the terms are \n" ^
blanchet@39737
   151
                                   cat_lines (map (Syntax.string_of_term ctxt) (terms_of tts)))
blanchet@39737
   152
                     end
blanchet@39737
   153
              | NONE => (*Not a constant. Is it a type constructor?*)
blanchet@39737
   154
            case strip_prefix_and_unascii type_const_prefix a of
blanchet@39737
   155
                SOME b =>
blanchet@41388
   156
                SomeType (Type (invert_const b, types_of (map tm_to_tt ts)))
blanchet@39737
   157
              | NONE => (*Maybe a TFree. Should then check that ts=[].*)
blanchet@39737
   158
            case strip_prefix_and_unascii tfree_prefix a of
blanchet@39738
   159
                SOME b => SomeType (mk_tfree ctxt b)
blanchet@39737
   160
              | NONE => (*a fixed variable? They are Skolem functions.*)
blanchet@39737
   161
            case strip_prefix_and_unascii fixed_var_prefix a of
blanchet@39737
   162
                SOME b =>
blanchet@39738
   163
                  let val opr = Free (b, HOLogic.typeT)
blanchet@39737
   164
                  in  apply_list opr (length ts) (map tm_to_tt ts)  end
blanchet@39737
   165
              | NONE => raise Fail ("unexpected metis function: " ^ a)
blanchet@39737
   166
  in
blanchet@39737
   167
    case tm_to_tt fol_tm of
blanchet@39738
   168
      SomeTerm t => t
blanchet@39738
   169
    | SomeType T => raise TYPE ("fol_tm_to_tt: Term expected", [T], [])
blanchet@39737
   170
  end
blanchet@39737
   171
blanchet@39737
   172
(*Maps fully-typed metis terms to isabelle terms*)
blanchet@43212
   173
fun hol_term_from_metis_FT ctxt fol_tm =
blanchet@40159
   174
  let val _ = trace_msg ctxt (fn () => "hol_term_from_metis_FT: " ^
blanchet@40159
   175
                                       Metis_Term.toString fol_tm)
blanchet@43208
   176
      fun do_const c =
blanchet@43441
   177
        let val c = c |> invert_const |> unproxify_const in
blanchet@43208
   178
          if String.isPrefix new_skolem_const_prefix c then
blanchet@43208
   179
            Var ((new_skolem_var_name_from_const c, 1), dummyT)
blanchet@43208
   180
          else
blanchet@43208
   181
            Const (c, dummyT)
blanchet@43208
   182
        end
blanchet@39737
   183
      fun cvt (Metis_Term.Fn ("ti", [Metis_Term.Var v, _])) =
blanchet@39737
   184
             (case strip_prefix_and_unascii schematic_var_prefix v of
blanchet@39737
   185
                  SOME w =>  mk_var(w, dummyT)
blanchet@39737
   186
                | NONE   => mk_var(v, dummyT))
blanchet@39737
   187
        | cvt (Metis_Term.Fn ("ti", [Metis_Term.Fn ("=",[]), _])) =
blanchet@39737
   188
            Const (@{const_name HOL.eq}, HOLogic.typeT)
blanchet@39737
   189
        | cvt (Metis_Term.Fn ("ti", [Metis_Term.Fn (x,[]), ty])) =
blanchet@39737
   190
           (case strip_prefix_and_unascii const_prefix x of
blanchet@43208
   191
                SOME c => do_const c
blanchet@39737
   192
              | NONE => (*Not a constant. Is it a fixed variable??*)
blanchet@39737
   193
            case strip_prefix_and_unascii fixed_var_prefix x of
blanchet@39737
   194
                SOME v => Free (v, hol_type_from_metis_term ctxt ty)
blanchet@39737
   195
              | NONE => raise Fail ("hol_term_from_metis_FT bad constant: " ^ x))
blanchet@43935
   196
        | cvt (Metis_Term.Fn ("ti", [Metis_Term.Fn (".", [tm1,tm2]), _])) =
blanchet@39737
   197
            cvt tm1 $ cvt tm2
blanchet@39737
   198
        | cvt (Metis_Term.Fn (".",[tm1,tm2])) = (*untyped application*)
blanchet@39737
   199
            cvt tm1 $ cvt tm2
blanchet@39737
   200
        | cvt (Metis_Term.Fn ("{}", [arg])) = cvt arg   (*hBOOL*)
blanchet@39737
   201
        | cvt (Metis_Term.Fn ("=", [tm1,tm2])) =
blanchet@39737
   202
            list_comb(Const (@{const_name HOL.eq}, HOLogic.typeT), map cvt [tm1,tm2])
blanchet@39737
   203
        | cvt (t as Metis_Term.Fn (x, [])) =
blanchet@39737
   204
           (case strip_prefix_and_unascii const_prefix x of
blanchet@43208
   205
                SOME c => do_const c
blanchet@39737
   206
              | NONE => (*Not a constant. Is it a fixed variable??*)
blanchet@39737
   207
            case strip_prefix_and_unascii fixed_var_prefix x of
blanchet@39737
   208
                SOME v => Free (v, dummyT)
blanchet@40159
   209
              | NONE => (trace_msg ctxt (fn () =>
blanchet@40159
   210
                                      "hol_term_from_metis_FT bad const: " ^ x);
blanchet@43212
   211
                         hol_term_from_metis_PT ctxt t))
blanchet@40159
   212
        | cvt t = (trace_msg ctxt (fn () =>
blanchet@40159
   213
                   "hol_term_from_metis_FT bad term: " ^ Metis_Term.toString t);
blanchet@43212
   214
                   hol_term_from_metis_PT ctxt t)
blanchet@39737
   215
  in fol_tm |> cvt end
blanchet@39737
   216
blanchet@43935
   217
fun atp_name_from_metis s =
blanchet@43935
   218
  case AList.find (op =) metis_name_table s of
blanchet@43935
   219
    [(s', ary)] => (s', SOME ary)
blanchet@43935
   220
  | _ => (s, NONE)
blanchet@43935
   221
fun atp_term_from_metis (Metis_Term.Fn (s, tms)) =
blanchet@43935
   222
    ATerm (fst (atp_name_from_metis s), map atp_term_from_metis tms)
blanchet@43935
   223
  | atp_term_from_metis (Metis_Term.Var s) = ATerm (s, [])
blanchet@39737
   224
blanchet@43935
   225
fun hol_term_from_metis_New sym_tab ctxt =
blanchet@43935
   226
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43935
   227
    atp_term_from_metis #> term_from_atp thy false sym_tab [](*###tfrees*) NONE
blanchet@43935
   228
  end
blanchet@43935
   229
blanchet@43935
   230
fun hol_term_from_metis FO _ = hol_term_from_metis_PT
blanchet@43935
   231
  | hol_term_from_metis HO _ = hol_term_from_metis_PT
blanchet@43935
   232
  | hol_term_from_metis FT _ = hol_term_from_metis_FT
blanchet@43935
   233
  | hol_term_from_metis New sym_tab = hol_term_from_metis_New sym_tab
blanchet@43935
   234
blanchet@43935
   235
fun hol_terms_from_metis ctxt mode old_skolems sym_tab fol_tms =
blanchet@43935
   236
  let val ts = map (hol_term_from_metis mode sym_tab ctxt) fol_tms
blanchet@40159
   237
      val _ = trace_msg ctxt (fn () => "  calling type inference:")
blanchet@40159
   238
      val _ = app (fn t => trace_msg ctxt
blanchet@40159
   239
                                     (fn () => Syntax.string_of_term ctxt t)) ts
blanchet@40067
   240
      val ts' = ts |> map (reveal_old_skolem_terms old_skolems)
blanchet@40067
   241
                   |> infer_types ctxt
blanchet@40159
   242
      val _ = app (fn t => trace_msg ctxt
blanchet@39737
   243
                    (fn () => "  final term: " ^ Syntax.string_of_term ctxt t ^
blanchet@39737
   244
                              "  of type  " ^ Syntax.string_of_typ ctxt (type_of t)))
blanchet@39737
   245
                  ts'
blanchet@39737
   246
  in  ts'  end;
blanchet@39737
   247
blanchet@39737
   248
(* ------------------------------------------------------------------------- *)
blanchet@39737
   249
(* FOL step Inference Rules                                                  *)
blanchet@39737
   250
(* ------------------------------------------------------------------------- *)
blanchet@39737
   251
blanchet@39737
   252
(*for debugging only*)
blanchet@39737
   253
(*
blanchet@40159
   254
fun print_thpair ctxt (fth,th) =
blanchet@40159
   255
  (trace_msg ctxt (fn () => "=============================================");
blanchet@40159
   256
   trace_msg ctxt (fn () => "Metis: " ^ Metis_Thm.toString fth);
blanchet@40159
   257
   trace_msg ctxt (fn () => "Isabelle: " ^ Display.string_of_thm_without_context th));
blanchet@39737
   258
*)
blanchet@39737
   259
blanchet@43935
   260
fun lookth th_pairs fth =
blanchet@43935
   261
  the (AList.lookup (uncurry Metis_Thm.equal) th_pairs fth)
blanchet@39737
   262
  handle Option.Option =>
blanchet@39737
   263
         raise Fail ("Failed to find Metis theorem " ^ Metis_Thm.toString fth)
blanchet@39737
   264
blanchet@39737
   265
fun cterm_incr_types thy idx = cterm_of thy o (map_types (Logic.incr_tvar idx));
blanchet@39737
   266
blanchet@39737
   267
(* INFERENCE RULE: AXIOM *)
blanchet@39737
   268
blanchet@43935
   269
(* This causes variables to have an index of 1 by default. See also "mk_var"
blanchet@43935
   270
   above. *)
blanchet@43935
   271
fun axiom_inf th_pairs th = Thm.incr_indexes 1 (lookth th_pairs th)
blanchet@39737
   272
blanchet@39737
   273
(* INFERENCE RULE: ASSUME *)
blanchet@39737
   274
blanchet@39737
   275
val EXCLUDED_MIDDLE = @{lemma "P ==> ~ P ==> False" by (rule notE)}
blanchet@39737
   276
blanchet@39737
   277
fun inst_excluded_middle thy i_atm =
blanchet@39737
   278
  let val th = EXCLUDED_MIDDLE
blanchet@39737
   279
      val [vx] = Term.add_vars (prop_of th) []
blanchet@39737
   280
      val substs = [(cterm_of thy (Var vx), cterm_of thy i_atm)]
blanchet@39737
   281
  in  cterm_instantiate substs th  end;
blanchet@39737
   282
blanchet@43935
   283
fun assume_inf ctxt mode old_skolems sym_tab atm =
blanchet@39737
   284
  inst_excluded_middle
wenzelm@43232
   285
      (Proof_Context.theory_of ctxt)
blanchet@43935
   286
      (singleton (hol_terms_from_metis ctxt mode old_skolems sym_tab)
blanchet@40502
   287
                 (Metis_Term.Fn atm))
blanchet@39737
   288
blanchet@39738
   289
(* INFERENCE RULE: INSTANTIATE (SUBST). Type instantiations are ignored. Trying
blanchet@39737
   290
   to reconstruct them admits new possibilities of errors, e.g. concerning
blanchet@39737
   291
   sorts. Instead we try to arrange that new TVars are distinct and that types
blanchet@39738
   292
   can be inferred from terms. *)
blanchet@39737
   293
blanchet@43935
   294
fun inst_inf ctxt mode old_skolems sym_tab th_pairs fsubst th =
wenzelm@43232
   295
  let val thy = Proof_Context.theory_of ctxt
blanchet@43935
   296
      val i_th = lookth th_pairs th
blanchet@39737
   297
      val i_th_vars = Term.add_vars (prop_of i_th) []
blanchet@39737
   298
      fun find_var x = the (List.find (fn ((a,_),_) => a=x) i_th_vars)
blanchet@39737
   299
      fun subst_translation (x,y) =
blanchet@39738
   300
        let val v = find_var x
blanchet@40067
   301
            (* We call "reveal_old_skolem_terms" and "infer_types" below. *)
blanchet@43935
   302
            val t = hol_term_from_metis mode sym_tab ctxt y
blanchet@39738
   303
        in  SOME (cterm_of thy (Var v), t)  end
blanchet@39738
   304
        handle Option.Option =>
blanchet@40159
   305
               (trace_msg ctxt (fn () => "\"find_var\" failed for " ^ x ^
blanchet@40159
   306
                                         " in " ^ Display.string_of_thm ctxt i_th);
blanchet@39738
   307
                NONE)
blanchet@39738
   308
             | TYPE _ =>
blanchet@40159
   309
               (trace_msg ctxt (fn () => "\"hol_term_from_metis\" failed for " ^ x ^
blanchet@40159
   310
                                         " in " ^ Display.string_of_thm ctxt i_th);
blanchet@39738
   311
                NONE)
blanchet@39737
   312
      fun remove_typeinst (a, t) =
blanchet@39737
   313
            case strip_prefix_and_unascii schematic_var_prefix a of
blanchet@39737
   314
                SOME b => SOME (b, t)
blanchet@39737
   315
              | NONE => case strip_prefix_and_unascii tvar_prefix a of
blanchet@39737
   316
                SOME _ => NONE          (*type instantiations are forbidden!*)
blanchet@39737
   317
              | NONE => SOME (a,t)    (*internal Metis var?*)
blanchet@40159
   318
      val _ = trace_msg ctxt (fn () => "  isa th: " ^ Display.string_of_thm ctxt i_th)
blanchet@39737
   319
      val substs = map_filter remove_typeinst (Metis_Subst.toList fsubst)
blanchet@39737
   320
      val (vars,rawtms) = ListPair.unzip (map_filter subst_translation substs)
blanchet@40067
   321
      val tms = rawtms |> map (reveal_old_skolem_terms old_skolems)
blanchet@40067
   322
                       |> infer_types ctxt
blanchet@39737
   323
      val ctm_of = cterm_incr_types thy (1 + Thm.maxidx_of i_th)
blanchet@39737
   324
      val substs' = ListPair.zip (vars, map ctm_of tms)
blanchet@40159
   325
      val _ = trace_msg ctxt (fn () =>
blanchet@39737
   326
        cat_lines ("subst_translations:" ::
blanchet@39737
   327
          (substs' |> map (fn (x, y) =>
blanchet@39737
   328
            Syntax.string_of_term ctxt (term_of x) ^ " |-> " ^
blanchet@39737
   329
            Syntax.string_of_term ctxt (term_of y)))));
blanchet@39737
   330
  in cterm_instantiate substs' i_th end
blanchet@43521
   331
  handle THM (msg, _, _) => raise METIS ("inst_inf", msg)
blanchet@43521
   332
       | ERROR msg => raise METIS ("inst_inf", msg)
blanchet@39737
   333
blanchet@39737
   334
(* INFERENCE RULE: RESOLVE *)
blanchet@39737
   335
blanchet@39737
   336
(* Like RSN, but we rename apart only the type variables. Vars here typically
blanchet@39737
   337
   have an index of 1, and the use of RSN would increase this typically to 3.
blanchet@39737
   338
   Instantiations of those Vars could then fail. See comment on "mk_var". *)
blanchet@39737
   339
fun resolve_inc_tyvars thy tha i thb =
blanchet@39737
   340
  let
blanchet@39737
   341
    val tha = Drule.incr_type_indexes (1 + Thm.maxidx_of thb) tha
blanchet@39737
   342
    fun aux tha thb =
blanchet@39737
   343
      case Thm.bicompose false (false, tha, nprems_of tha) i thb
blanchet@39737
   344
           |> Seq.list_of |> distinct Thm.eq_thm of
blanchet@39737
   345
        [th] => th
blanchet@39737
   346
      | _ => raise THM ("resolve_inc_tyvars: unique result expected", i,
blanchet@39737
   347
                        [tha, thb])
blanchet@39737
   348
  in
blanchet@39737
   349
    aux tha thb
blanchet@39737
   350
    handle TERM z =>
blanchet@39737
   351
           (* The unifier, which is invoked from "Thm.bicompose", will sometimes
blanchet@39737
   352
              refuse to unify "?a::?'a" with "?a::?'b" or "?a::nat" and throw a
blanchet@39737
   353
              "TERM" exception (with "add_ffpair" as first argument). We then
blanchet@39737
   354
              perform unification of the types of variables by hand and try
blanchet@39737
   355
              again. We could do this the first time around but this error
blanchet@39737
   356
              occurs seldom and we don't want to break existing proofs in subtle
blanchet@39737
   357
              ways or slow them down needlessly. *)
blanchet@39737
   358
           case [] |> fold (Term.add_vars o prop_of) [tha, thb]
blanchet@39737
   359
                   |> AList.group (op =)
blanchet@39737
   360
                   |> maps (fn ((s, _), T :: Ts) =>
blanchet@39737
   361
                               map (fn T' => (Free (s, T), Free (s, T'))) Ts)
blanchet@39737
   362
                   |> rpair (Envir.empty ~1)
blanchet@39737
   363
                   |-> fold (Pattern.unify thy)
blanchet@39737
   364
                   |> Envir.type_env |> Vartab.dest
blanchet@39737
   365
                   |> map (fn (x, (S, T)) =>
blanchet@39737
   366
                              pairself (ctyp_of thy) (TVar (x, S), T)) of
blanchet@39737
   367
             [] => raise TERM z
blanchet@39737
   368
           | ps => aux (instantiate (ps, []) tha) (instantiate (ps, []) thb)
blanchet@39737
   369
  end
blanchet@39737
   370
blanchet@40462
   371
fun s_not (@{const Not} $ t) = t
blanchet@40462
   372
  | s_not t = HOLogic.mk_not t
blanchet@40462
   373
fun simp_not_not (@{const Not} $ t) = s_not (simp_not_not t)
blanchet@40462
   374
  | simp_not_not t = t
blanchet@39737
   375
blanchet@39737
   376
(* Match untyped terms. *)
blanchet@39737
   377
fun untyped_aconv (Const (a, _)) (Const(b, _)) = (a = b)
blanchet@39737
   378
  | untyped_aconv (Free (a, _)) (Free (b, _)) = (a = b)
blanchet@39737
   379
  | untyped_aconv (Var ((a, _), _)) (Var ((b, _), _)) =
blanchet@39737
   380
    (a = b) (* The index is ignored, for some reason. *)
blanchet@39737
   381
  | untyped_aconv (Bound i) (Bound j) = (i = j)
blanchet@39737
   382
  | untyped_aconv (Abs (_, _, t)) (Abs (_, _, u)) = untyped_aconv t u
blanchet@39737
   383
  | untyped_aconv (t1 $ t2) (u1 $ u2) =
blanchet@39737
   384
    untyped_aconv t1 u1 andalso untyped_aconv t2 u2
blanchet@39737
   385
  | untyped_aconv _ _ = false
blanchet@39737
   386
blanchet@39737
   387
(* Finding the relative location of an untyped term within a list of terms *)
blanchet@40462
   388
fun index_of_literal lit haystack =
blanchet@39737
   389
  let
blanchet@40462
   390
    val normalize = simp_not_not o Envir.eta_contract
blanchet@40462
   391
    val match_lit =
blanchet@40462
   392
      HOLogic.dest_Trueprop #> normalize #> untyped_aconv (lit |> normalize)
blanchet@40462
   393
  in case find_index match_lit haystack of ~1 => raise Empty | n => n + 1 end
blanchet@39737
   394
blanchet@40074
   395
(* Permute a rule's premises to move the i-th premise to the last position. *)
blanchet@40074
   396
fun make_last i th =
blanchet@40074
   397
  let val n = nprems_of th
blanchet@40074
   398
  in  if 1 <= i andalso i <= n
blanchet@40074
   399
      then Thm.permute_prems (i-1) 1 th
blanchet@40074
   400
      else raise THM("select_literal", i, [th])
blanchet@40074
   401
  end;
blanchet@40074
   402
blanchet@43219
   403
(* Maps a rule that ends "... ==> P ==> False" to "... ==> ~ P" while avoiding
blanchet@43220
   404
   to create double negations. The "select" wrapper is a trick to ensure that
blanchet@43220
   405
   "P ==> ~ False ==> False" is rewritten to "P ==> False", not to "~ P". We
blanchet@43220
   406
   don't use this trick in general because it makes the proof object uglier than
blanchet@43220
   407
   necessary. FIXME. *)
blanchet@43220
   408
fun negate_head th =
blanchet@43220
   409
  if exists (fn t => t aconv @{prop "~ False"}) (prems_of th) then
blanchet@43220
   410
    (th RS @{thm select_FalseI})
blanchet@43220
   411
    |> fold (rewrite_rule o single)
blanchet@43220
   412
            @{thms not_atomize_select atomize_not_select}
blanchet@43220
   413
  else
blanchet@43220
   414
    th |> fold (rewrite_rule o single) @{thms not_atomize atomize_not}
blanchet@40074
   415
blanchet@40074
   416
(* Maps the clause  [P1,...Pn]==>False to [P1,...,P(i-1),P(i+1),...Pn] ==> ~P *)
blanchet@43219
   417
val select_literal = negate_head oo make_last
blanchet@40074
   418
blanchet@43935
   419
fun resolve_inf ctxt mode old_skolems sym_tab th_pairs atm th1 th2 =
blanchet@39737
   420
  let
wenzelm@43232
   421
    val thy = Proof_Context.theory_of ctxt
blanchet@43935
   422
    val (i_th1, i_th2) = pairself (lookth th_pairs) (th1, th2)
blanchet@40159
   423
    val _ = trace_msg ctxt (fn () => "  isa th1 (pos): " ^ Display.string_of_thm ctxt i_th1)
blanchet@40159
   424
    val _ = trace_msg ctxt (fn () => "  isa th2 (neg): " ^ Display.string_of_thm ctxt i_th2)
blanchet@39737
   425
  in
blanchet@39737
   426
    (* Trivial cases where one operand is type info *)
blanchet@39737
   427
    if Thm.eq_thm (TrueI, i_th1) then
blanchet@39737
   428
      i_th2
blanchet@39737
   429
    else if Thm.eq_thm (TrueI, i_th2) then
blanchet@39737
   430
      i_th1
blanchet@39737
   431
    else
blanchet@39737
   432
      let
blanchet@40462
   433
        val i_atm =
blanchet@43935
   434
          singleton (hol_terms_from_metis ctxt mode old_skolems sym_tab)
blanchet@40462
   435
                    (Metis_Term.Fn atm)
blanchet@40159
   436
        val _ = trace_msg ctxt (fn () => "  atom: " ^ Syntax.string_of_term ctxt i_atm)
blanchet@39737
   437
        val prems_th1 = prems_of i_th1
blanchet@39737
   438
        val prems_th2 = prems_of i_th2
blanchet@40462
   439
        val index_th1 =
blanchet@40462
   440
          index_of_literal (s_not i_atm) prems_th1
blanchet@40462
   441
          handle Empty => raise Fail "Failed to find literal in th1"
wenzelm@41739
   442
        val _ = trace_msg ctxt (fn () => "  index_th1: " ^ string_of_int index_th1)
blanchet@40462
   443
        val index_th2 =
blanchet@40462
   444
          index_of_literal i_atm prems_th2
blanchet@40462
   445
          handle Empty => raise Fail "Failed to find literal in th2"
wenzelm@41739
   446
        val _ = trace_msg ctxt (fn () => "  index_th2: " ^ string_of_int index_th2)
blanchet@39737
   447
    in
blanchet@43219
   448
      resolve_inc_tyvars thy (select_literal index_th1 i_th1) index_th2 i_th2
blanchet@43521
   449
      handle TERM (s, _) => raise METIS ("resolve_inf", s)
blanchet@39737
   450
    end
blanchet@39737
   451
  end;
blanchet@39737
   452
blanchet@39737
   453
(* INFERENCE RULE: REFL *)
blanchet@39737
   454
blanchet@39737
   455
val REFL_THM = Thm.incr_indexes 2 @{lemma "t ~= t ==> False" by simp}
blanchet@39737
   456
blanchet@39737
   457
val refl_x = cterm_of @{theory} (Var (hd (Term.add_vars (prop_of REFL_THM) [])));
blanchet@39737
   458
val refl_idx = 1 + Thm.maxidx_of REFL_THM;
blanchet@39737
   459
blanchet@43935
   460
fun refl_inf ctxt mode old_skolems sym_tab t =
blanchet@43935
   461
  let
blanchet@43935
   462
    val thy = Proof_Context.theory_of ctxt
blanchet@43935
   463
    val i_t = singleton (hol_terms_from_metis ctxt mode old_skolems sym_tab) t
blanchet@43935
   464
    val _ = trace_msg ctxt (fn () => "  term: " ^ Syntax.string_of_term ctxt i_t)
blanchet@43935
   465
    val c_t = cterm_incr_types thy refl_idx i_t
blanchet@43935
   466
  in cterm_instantiate [(refl_x, c_t)] REFL_THM end
blanchet@39737
   467
blanchet@39737
   468
(* INFERENCE RULE: EQUALITY *)
blanchet@39737
   469
blanchet@39737
   470
val subst_em = @{lemma "s = t ==> P s ==> ~ P t ==> False" by simp}
blanchet@39737
   471
val ssubst_em = @{lemma "s = t ==> P t ==> ~ P s ==> False" by simp}
blanchet@39737
   472
blanchet@39737
   473
val metis_eq = Metis_Term.Fn ("=", []);
blanchet@39737
   474
blanchet@43934
   475
(* Equality has no type arguments *)
blanchet@43934
   476
fun get_ty_arg_size _ (Const (@{const_name HOL.eq}, _)) = 0
blanchet@43934
   477
  | get_ty_arg_size thy (Const (s, _)) =
blanchet@43934
   478
    (num_type_args thy s handle TYPE _ => 0)
blanchet@43934
   479
  | get_ty_arg_size _ _ = 0
blanchet@39737
   480
blanchet@43935
   481
fun equality_inf ctxt mode old_skolems sym_tab (pos, atm) fp fr =
wenzelm@43232
   482
  let val thy = Proof_Context.theory_of ctxt
blanchet@39737
   483
      val m_tm = Metis_Term.Fn atm
blanchet@43935
   484
      val [i_atm, i_tm] =
blanchet@43935
   485
        hol_terms_from_metis ctxt mode old_skolems sym_tab [m_tm, fr]
blanchet@40159
   486
      val _ = trace_msg ctxt (fn () => "sign of the literal: " ^ Bool.toString pos)
blanchet@39737
   487
      fun replace_item_list lx 0 (_::ls) = lx::ls
blanchet@39737
   488
        | replace_item_list lx i (l::ls) = l :: replace_item_list lx (i-1) ls
blanchet@39738
   489
      fun path_finder_FO tm [] = (tm, Bound 0)
blanchet@39737
   490
        | path_finder_FO tm (p::ps) =
blanchet@39737
   491
            let val (tm1,args) = strip_comb tm
blanchet@39737
   492
                val adjustment = get_ty_arg_size thy tm1
blanchet@43935
   493
                val p' = if adjustment > p then p else p - adjustment
wenzelm@43235
   494
                val tm_p = nth args p'
blanchet@39737
   495
                  handle Subscript =>
blanchet@43521
   496
                         raise METIS ("equality_inf",
blanchet@43521
   497
                                      string_of_int p ^ " adj " ^
blanchet@43521
   498
                                      string_of_int adjustment ^ " term " ^
blanchet@43521
   499
                                      Syntax.string_of_term ctxt tm)
wenzelm@41739
   500
                val _ = trace_msg ctxt (fn () => "path_finder: " ^ string_of_int p ^
blanchet@39737
   501
                                      "  " ^ Syntax.string_of_term ctxt tm_p)
blanchet@39737
   502
                val (r,t) = path_finder_FO tm_p ps
blanchet@39737
   503
            in
blanchet@39737
   504
                (r, list_comb (tm1, replace_item_list t p' args))
blanchet@39737
   505
            end
blanchet@39738
   506
      fun path_finder_HO tm [] = (tm, Bound 0)
blanchet@39737
   507
        | path_finder_HO (t$u) (0::ps) = (fn(x,y) => (x, y$u)) (path_finder_HO t ps)
blanchet@39737
   508
        | path_finder_HO (t$u) (_::ps) = (fn(x,y) => (x, t$y)) (path_finder_HO u ps)
blanchet@39737
   509
        | path_finder_HO tm ps =
blanchet@39738
   510
          raise Fail ("Cannot replay Metis proof in Isabelle:\n" ^
blanchet@39738
   511
                      "equality_inf, path_finder_HO: path = " ^
wenzelm@41739
   512
                      space_implode " " (map string_of_int ps) ^
blanchet@39737
   513
                      " isa-term: " ^  Syntax.string_of_term ctxt tm)
blanchet@39738
   514
      fun path_finder_FT tm [] _ = (tm, Bound 0)
blanchet@39737
   515
        | path_finder_FT tm (0::ps) (Metis_Term.Fn ("ti", [t1, _])) =
blanchet@39737
   516
            path_finder_FT tm ps t1
blanchet@39737
   517
        | path_finder_FT (t$u) (0::ps) (Metis_Term.Fn (".", [t1, _])) =
blanchet@39737
   518
            (fn(x,y) => (x, y$u)) (path_finder_FT t ps t1)
blanchet@39737
   519
        | path_finder_FT (t$u) (1::ps) (Metis_Term.Fn (".", [_, t2])) =
blanchet@39737
   520
            (fn(x,y) => (x, t$y)) (path_finder_FT u ps t2)
blanchet@39737
   521
        | path_finder_FT tm ps t =
blanchet@39738
   522
          raise Fail ("Cannot replay Metis proof in Isabelle:\n" ^
blanchet@39738
   523
                      "equality_inf, path_finder_FT: path = " ^
wenzelm@41739
   524
                      space_implode " " (map string_of_int ps) ^
blanchet@39737
   525
                      " isa-term: " ^  Syntax.string_of_term ctxt tm ^
blanchet@39737
   526
                      " fol-term: " ^ Metis_Term.toString t)
blanchet@43935
   527
      fun path_finder_New tm [] _ = (tm, Bound 0)
blanchet@43935
   528
        | path_finder_New tm (p :: ps) (t as Metis_Term.Fn (s, ts)) =
blanchet@43935
   529
          let
blanchet@43935
   530
            val (tm1, args) = strip_comb tm
blanchet@43935
   531
            val adjustment =
blanchet@43935
   532
              case atp_name_from_metis s of
blanchet@43935
   533
                (_, SOME _) => 0
blanchet@43935
   534
              | (s', NONE) =>
blanchet@43935
   535
                length ts - the_default 0 (Symtab.lookup sym_tab s')
blanchet@43935
   536
            val p' = if adjustment > p then p else p - adjustment
blanchet@43935
   537
            val tm_p = nth args p'
blanchet@43935
   538
              handle Subscript =>
blanchet@43935
   539
                     raise METIS ("equality_inf",
blanchet@43935
   540
                                  string_of_int p ^ " adj " ^
blanchet@43935
   541
                                  string_of_int adjustment ^ " term " ^
blanchet@43935
   542
                                  Syntax.string_of_term ctxt tm)
blanchet@43935
   543
            val _ = trace_msg ctxt (fn () => "path_finder: " ^ string_of_int p ^
blanchet@43935
   544
                                  "  " ^ Syntax.string_of_term ctxt tm_p)
blanchet@43935
   545
            val (r, t) = path_finder_New tm_p ps t
blanchet@43935
   546
          in (r, list_comb (tm1, replace_item_list t p' args)) end
blanchet@43935
   547
        | path_finder_New tm ps t =
blanchet@43935
   548
          raise Fail ("Cannot replay Metis proof in Isabelle:\n" ^
blanchet@43935
   549
                      "equality_inf, path_finder_New: path = " ^
blanchet@43935
   550
                      space_implode " " (map string_of_int ps) ^
blanchet@43935
   551
                      " isa-term: " ^  Syntax.string_of_term ctxt tm ^
blanchet@43935
   552
                      " fol-term: " ^ Metis_Term.toString t)
blanchet@39737
   553
      fun path_finder FO tm ps _ = path_finder_FO tm ps
blanchet@39737
   554
        | path_finder HO (tm as Const(@{const_name HOL.eq},_) $ _ $ _) (p::ps) _ =
blanchet@39737
   555
             (*equality: not curried, as other predicates are*)
blanchet@39737
   556
             if p=0 then path_finder_HO tm (0::1::ps)  (*select first operand*)
blanchet@39737
   557
             else path_finder_HO tm (p::ps)        (*1 selects second operand*)
blanchet@39737
   558
        | path_finder HO tm (_ :: ps) (Metis_Term.Fn ("{}", [_])) =
blanchet@39737
   559
             path_finder_HO tm ps      (*if not equality, ignore head to skip hBOOL*)
blanchet@39737
   560
        | path_finder FT (tm as Const(@{const_name HOL.eq}, _) $ _ $ _) (p::ps)
blanchet@39737
   561
                            (Metis_Term.Fn ("=", [t1,t2])) =
blanchet@39737
   562
             (*equality: not curried, as other predicates are*)
blanchet@39737
   563
             if p=0 then path_finder_FT tm (0::1::ps)
blanchet@43935
   564
                          (Metis_Term.Fn (metis_app_op, [Metis_Term.Fn (metis_app_op, [metis_eq,t1]), t2]))
blanchet@39737
   565
                          (*select first operand*)
blanchet@39737
   566
             else path_finder_FT tm (p::ps)
blanchet@43935
   567
                   (Metis_Term.Fn (metis_app_op, [metis_eq, t2]))
blanchet@39737
   568
                   (*1 selects second operand*)
blanchet@39737
   569
        | path_finder FT tm (_ :: ps) (Metis_Term.Fn ("{}", [t1])) = path_finder_FT tm ps t1
blanchet@39737
   570
             (*if not equality, ignore head to skip the hBOOL predicate*)
blanchet@39737
   571
        | path_finder FT tm ps t = path_finder_FT tm ps t  (*really an error case!*)
blanchet@43935
   572
        | path_finder New tm ps t = path_finder_New tm ps t
blanchet@39737
   573
      fun path_finder_lit ((nt as Const (@{const_name Not}, _)) $ tm_a) idx =
blanchet@39737
   574
            let val (tm, tm_rslt) = path_finder mode tm_a idx m_tm
blanchet@39737
   575
            in (tm, nt $ tm_rslt) end
blanchet@39737
   576
        | path_finder_lit tm_a idx = path_finder mode tm_a idx m_tm
blanchet@39737
   577
      val (tm_subst, body) = path_finder_lit i_atm fp
blanchet@39738
   578
      val tm_abs = Abs ("x", type_of tm_subst, body)
blanchet@40159
   579
      val _ = trace_msg ctxt (fn () => "abstraction: " ^ Syntax.string_of_term ctxt tm_abs)
blanchet@40159
   580
      val _ = trace_msg ctxt (fn () => "i_tm: " ^ Syntax.string_of_term ctxt i_tm)
blanchet@40159
   581
      val _ = trace_msg ctxt (fn () => "located term: " ^ Syntax.string_of_term ctxt tm_subst)
blanchet@39737
   582
      val imax = maxidx_of_term (i_tm $ tm_abs $ tm_subst)  (*ill typed but gives right max*)
blanchet@39737
   583
      val subst' = Thm.incr_indexes (imax+1) (if pos then subst_em else ssubst_em)
blanchet@40159
   584
      val _ = trace_msg ctxt (fn () => "subst' " ^ Display.string_of_thm ctxt subst')
blanchet@39737
   585
      val eq_terms = map (pairself (cterm_of thy))
blanchet@39737
   586
        (ListPair.zip (OldTerm.term_vars (prop_of subst'), [tm_abs, tm_subst, i_tm]))
blanchet@39737
   587
  in  cterm_instantiate eq_terms subst'  end;
blanchet@39737
   588
blanchet@43935
   589
val factor = Seq.hd o distinct_subgoals_tac
blanchet@39737
   590
blanchet@43935
   591
fun one_step ctxt mode old_skolems sym_tab th_pairs p =
blanchet@39737
   592
  case p of
blanchet@43935
   593
    (fol_th, Metis_Proof.Axiom _) => axiom_inf th_pairs fol_th |> factor
blanchet@43935
   594
  | (_, Metis_Proof.Assume f_atm) =>
blanchet@43935
   595
    assume_inf ctxt mode old_skolems sym_tab f_atm
blanchet@39737
   596
  | (_, Metis_Proof.Metis_Subst (f_subst, f_th1)) =>
blanchet@43935
   597
    inst_inf ctxt mode old_skolems sym_tab th_pairs f_subst f_th1 |> factor
blanchet@39737
   598
  | (_, Metis_Proof.Resolve(f_atm, f_th1, f_th2)) =>
blanchet@43935
   599
    resolve_inf ctxt mode old_skolems sym_tab th_pairs f_atm f_th1 f_th2
blanchet@43935
   600
    |> factor
blanchet@43935
   601
  | (_, Metis_Proof.Refl f_tm) => refl_inf ctxt mode old_skolems sym_tab f_tm
blanchet@39737
   602
  | (_, Metis_Proof.Equality (f_lit, f_p, f_r)) =>
blanchet@43935
   603
    equality_inf ctxt mode old_skolems sym_tab f_lit f_p f_r
blanchet@39737
   604
blanchet@40074
   605
fun flexflex_first_order th =
blanchet@40074
   606
  case Thm.tpairs_of th of
blanchet@40074
   607
      [] => th
blanchet@40074
   608
    | pairs =>
blanchet@40074
   609
        let val thy = theory_of_thm th
blanchet@40074
   610
            val (_, tenv) =
blanchet@40074
   611
              fold (Pattern.first_order_match thy) pairs (Vartab.empty, Vartab.empty)
blanchet@40074
   612
            val t_pairs = map Meson.term_pair_of (Vartab.dest tenv)
blanchet@40074
   613
            val th' = Thm.instantiate ([], map (pairself (cterm_of thy)) t_pairs) th
blanchet@40074
   614
        in  th'  end
blanchet@40074
   615
        handle THM _ => th;
blanchet@39737
   616
blanchet@40076
   617
fun is_metis_literal_genuine (_, (s, _)) = not (String.isPrefix class_prefix s)
blanchet@40076
   618
fun is_isabelle_literal_genuine t =
blanchet@40134
   619
  case t of _ $ (Const (@{const_name Meson.skolem}, _) $ _) => false | _ => true
blanchet@40076
   620
blanchet@40076
   621
fun count p xs = fold (fn x => if p x then Integer.add 1 else I) xs 0
blanchet@40076
   622
blanchet@43204
   623
(* Seldomly needed hack. A Metis clause is represented as a set, so duplicate
blanchet@43204
   624
   disjuncts are impossible. In the Isabelle proof, in spite of efforts to
blanchet@43204
   625
   eliminate them, duplicates sometimes appear with slightly different (but
blanchet@43204
   626
   unifiable) types. *)
blanchet@43204
   627
fun resynchronize ctxt fol_th th =
blanchet@43204
   628
  let
blanchet@43204
   629
    val num_metis_lits =
blanchet@43204
   630
      count is_metis_literal_genuine
blanchet@43204
   631
            (Metis_LiteralSet.toList (Metis_Thm.clause fol_th))
blanchet@43204
   632
    val num_isabelle_lits = count is_isabelle_literal_genuine (prems_of th)
blanchet@43204
   633
  in
blanchet@43204
   634
    if num_metis_lits >= num_isabelle_lits then
blanchet@43204
   635
      th
blanchet@43204
   636
    else
blanchet@43204
   637
      let
blanchet@43204
   638
        val (prems0, concl) = th |> prop_of |> Logic.strip_horn
blanchet@43204
   639
        val prems = prems0 |> distinct (uncurry untyped_aconv)
blanchet@43204
   640
        val goal = Logic.list_implies (prems, concl)
blanchet@43204
   641
      in
blanchet@43204
   642
        if length prems = length prems0 then
blanchet@43521
   643
          raise METIS ("resynchronize", "Out of sync")
blanchet@43204
   644
        else
blanchet@43204
   645
          Goal.prove ctxt [] [] goal (K (cut_rules_tac [th] 1
blanchet@43204
   646
                                         THEN ALLGOALS assume_tac))
blanchet@43204
   647
          |> resynchronize ctxt fol_th
blanchet@43204
   648
      end
blanchet@43204
   649
  end
blanchet@43204
   650
blanchet@43935
   651
fun replay_one_inference ctxt mode old_skolems sym_tab (fol_th, inf) th_pairs =
blanchet@43935
   652
  if not (null th_pairs) andalso
blanchet@43935
   653
     prop_of (snd (hd th_pairs)) aconv @{prop False} then
blanchet@41110
   654
    (* Isabelle sometimes identifies literals (premises) that are distinct in
blanchet@41110
   655
       Metis (e.g., because of type variables). We give the Isabelle proof the
blanchet@41110
   656
       benefice of the doubt. *)
blanchet@43935
   657
    th_pairs
blanchet@41110
   658
  else
blanchet@41110
   659
    let
blanchet@41110
   660
      val _ = trace_msg ctxt
blanchet@41110
   661
                  (fn () => "=============================================")
blanchet@41110
   662
      val _ = trace_msg ctxt
blanchet@41110
   663
                  (fn () => "METIS THM: " ^ Metis_Thm.toString fol_th)
blanchet@41110
   664
      val _ = trace_msg ctxt
blanchet@41110
   665
                  (fn () => "INFERENCE: " ^ Metis_Proof.inferenceToString inf)
blanchet@43935
   666
      val th = one_step ctxt mode old_skolems sym_tab th_pairs (fol_th, inf)
blanchet@41110
   667
               |> flexflex_first_order
blanchet@43204
   668
               |> resynchronize ctxt fol_th
blanchet@41110
   669
      val _ = trace_msg ctxt
blanchet@41110
   670
                  (fn () => "ISABELLE THM: " ^ Display.string_of_thm ctxt th)
blanchet@41110
   671
      val _ = trace_msg ctxt
blanchet@41110
   672
                  (fn () => "=============================================")
blanchet@43935
   673
    in (fol_th, th) :: th_pairs end
blanchet@39737
   674
blanchet@43213
   675
(* It is normally sufficient to apply "assume_tac" to unify the conclusion with
blanchet@43213
   676
   one of the premises. Unfortunately, this sometimes yields "Variable
blanchet@43213
   677
   ?SK_a_b_c_x has two distinct types" errors. To avoid this, we instantiate the
blanchet@43213
   678
   variables before applying "assume_tac". Typical constraints are of the form
blanchet@43213
   679
     ?SK_a_b_c_x SK_d_e_f_y ... SK_a_b_c_x ... SK_g_h_i_z =?= SK_a_b_c_x,
blanchet@43213
   680
   where the nonvariables are goal parameters. *)
blanchet@43213
   681
fun unify_first_prem_with_concl thy i th =
blanchet@43213
   682
  let
blanchet@43213
   683
    val goal = Logic.get_goal (prop_of th) i |> Envir.beta_eta_contract
blanchet@43213
   684
    val prem = goal |> Logic.strip_assums_hyp |> hd
blanchet@43213
   685
    val concl = goal |> Logic.strip_assums_concl
blanchet@43213
   686
    fun pair_untyped_aconv (t1, t2) (u1, u2) =
blanchet@43213
   687
      untyped_aconv t1 u1 andalso untyped_aconv t2 u2
blanchet@43213
   688
    fun add_terms tp inst =
blanchet@43213
   689
      if exists (pair_untyped_aconv tp) inst then inst
blanchet@43213
   690
      else tp :: map (apsnd (subst_atomic [tp])) inst
blanchet@43213
   691
    fun is_flex t =
blanchet@43213
   692
      case strip_comb t of
blanchet@43213
   693
        (Var _, args) => forall is_Bound args
blanchet@43213
   694
      | _ => false
blanchet@43213
   695
    fun unify_flex flex rigid =
blanchet@43213
   696
      case strip_comb flex of
blanchet@43213
   697
        (Var (z as (_, T)), args) =>
blanchet@43213
   698
        add_terms (Var z,
blanchet@43213
   699
          fold_rev (curry absdummy) (take (length args) (binder_types T)) rigid)
blanchet@43213
   700
      | _ => I
blanchet@43213
   701
    fun unify_potential_flex comb atom =
blanchet@43213
   702
      if is_flex comb then unify_flex comb atom
blanchet@43213
   703
      else if is_Var atom then add_terms (atom, comb)
blanchet@43213
   704
      else I
blanchet@43213
   705
    fun unify_terms (t, u) =
blanchet@43213
   706
      case (t, u) of
blanchet@43213
   707
        (t1 $ t2, u1 $ u2) =>
blanchet@43213
   708
        if is_flex t then unify_flex t u
blanchet@43213
   709
        else if is_flex u then unify_flex u t
blanchet@43213
   710
        else fold unify_terms [(t1, u1), (t2, u2)]
blanchet@43213
   711
      | (_ $ _, _) => unify_potential_flex t u
blanchet@43213
   712
      | (_, _ $ _) => unify_potential_flex u t
blanchet@43213
   713
      | (Var _, _) => add_terms (t, u)
blanchet@43213
   714
      | (_, Var _) => add_terms (u, t)
blanchet@43213
   715
      | _ => I
blanchet@43215
   716
    val t_inst =
blanchet@43215
   717
      [] |> try (unify_terms (prem, concl) #> map (pairself (cterm_of thy)))
blanchet@43215
   718
         |> the_default [] (* FIXME *)
blanchet@43213
   719
  in th |> cterm_instantiate t_inst end
blanchet@40145
   720
blanchet@40145
   721
val copy_prem = @{lemma "P ==> (P ==> P ==> Q) ==> Q" by fast}
blanchet@40145
   722
blanchet@40145
   723
fun copy_prems_tac [] ns i =
blanchet@40145
   724
    if forall (curry (op =) 1) ns then all_tac else copy_prems_tac (rev ns) [] i
blanchet@40145
   725
  | copy_prems_tac (1 :: ms) ns i =
blanchet@40145
   726
    rotate_tac 1 i THEN copy_prems_tac ms (1 :: ns) i
blanchet@40145
   727
  | copy_prems_tac (m :: ms) ns i =
blanchet@40145
   728
    etac copy_prem i THEN copy_prems_tac ms (m div 2 :: (m + 1) div 2 :: ns) i
blanchet@40145
   729
blanchet@43135
   730
(* Metis generates variables of the form _nnn. *)
blanchet@43135
   731
val is_metis_fresh_variable = String.isPrefix "_"
blanchet@43135
   732
blanchet@40501
   733
fun instantiate_forall_tac thy t i st =
blanchet@40145
   734
  let
blanchet@40501
   735
    val params = Logic.strip_params (Logic.get_goal (prop_of st) i) |> rev
blanchet@40145
   736
    fun repair (t as (Var ((s, _), _))) =
blanchet@40501
   737
        (case find_index (fn (s', _) => s' = s) params of
blanchet@40145
   738
           ~1 => t
blanchet@40145
   739
         | j => Bound j)
blanchet@40504
   740
      | repair (t $ u) =
blanchet@40504
   741
        (case (repair t, repair u) of
blanchet@40504
   742
           (t as Bound j, u as Bound k) =>
blanchet@40504
   743
           (* This is a rather subtle trick to repair the discrepancy between
blanchet@40504
   744
              the fully skolemized term that MESON gives us (where existentials
blanchet@40504
   745
              were pulled out) and the reality. *)
blanchet@40504
   746
           if k > j then t else t $ u
blanchet@40504
   747
         | (t, u) => t $ u)
blanchet@40145
   748
      | repair t = t
blanchet@40145
   749
    val t' = t |> repair |> fold (curry absdummy) (map snd params)
blanchet@40145
   750
    fun do_instantiate th =
blanchet@43134
   751
      case Term.add_vars (prop_of th) []
blanchet@43135
   752
           |> filter_out ((Meson_Clausify.is_zapped_var_name orf
blanchet@43135
   753
                           is_metis_fresh_variable) o fst o fst) of
blanchet@43134
   754
        [] => th
blanchet@43135
   755
      | [var as (_, T)] =>
blanchet@43135
   756
        let
blanchet@43135
   757
          val var_binder_Ts = T |> binder_types |> take (length params) |> rev
blanchet@43135
   758
          val var_body_T = T |> funpow (length params) range_type
blanchet@43135
   759
          val tyenv =
blanchet@43135
   760
            Vartab.empty |> Type.raw_unifys (fastype_of t :: map snd params,
blanchet@43135
   761
                                             var_body_T :: var_binder_Ts)
blanchet@43135
   762
          val env =
blanchet@43135
   763
            Envir.Envir {maxidx = Vartab.fold (Integer.max o snd o fst) tyenv 0,
blanchet@43135
   764
                         tenv = Vartab.empty, tyenv = tyenv}
blanchet@43135
   765
          val ty_inst =
blanchet@43135
   766
            Vartab.fold (fn (x, (S, T)) =>
blanchet@43135
   767
                            cons (pairself (ctyp_of thy) (TVar (x, S), T)))
blanchet@43135
   768
                        tyenv []
blanchet@43135
   769
          val t_inst =
blanchet@43135
   770
            [pairself (cterm_of thy o Envir.norm_term env) (Var var, t')]
blanchet@43213
   771
        in th |> instantiate (ty_inst, t_inst) end
blanchet@43135
   772
      | _ => raise Fail "expected a single non-zapped, non-Metis Var"
blanchet@40145
   773
  in
blanchet@43135
   774
    (DETERM (etac @{thm allE} i THEN rotate_tac ~1 i)
blanchet@40501
   775
     THEN PRIMITIVE do_instantiate) st
blanchet@40145
   776
  end
blanchet@40145
   777
blanchet@41383
   778
fun fix_exists_tac t =
blanchet@40504
   779
  etac @{thm exE}
blanchet@40504
   780
  THEN' rename_tac [t |> dest_Var |> fst |> fst]
blanchet@40504
   781
blanchet@40504
   782
fun release_quantifier_tac thy (skolem, t) =
blanchet@41383
   783
  (if skolem then fix_exists_tac else instantiate_forall_tac thy) t
blanchet@40504
   784
blanchet@40501
   785
fun release_clusters_tac _ _ _ [] = K all_tac
blanchet@40501
   786
  | release_clusters_tac thy ax_counts substs
blanchet@40145
   787
                         ((ax_no, cluster_no) :: clusters) =
blanchet@40145
   788
    let
blanchet@40504
   789
      val cluster_of_var =
blanchet@40504
   790
        Meson_Clausify.cluster_of_zapped_var_name o fst o fst o dest_Var
blanchet@40504
   791
      fun in_right_cluster ((_, (cluster_no', _)), _) = cluster_no' = cluster_no
blanchet@40145
   792
      val cluster_substs =
blanchet@40145
   793
        substs
blanchet@40145
   794
        |> map_filter (fn (ax_no', (_, (_, tsubst))) =>
blanchet@40145
   795
                          if ax_no' = ax_no then
blanchet@40504
   796
                            tsubst |> map (apfst cluster_of_var)
blanchet@40504
   797
                                   |> filter (in_right_cluster o fst)
blanchet@40504
   798
                                   |> map (apfst snd)
blanchet@40504
   799
                                   |> SOME
blanchet@40504
   800
                          else
blanchet@40504
   801
                            NONE)
blanchet@40145
   802
      fun do_cluster_subst cluster_subst =
blanchet@40504
   803
        map (release_quantifier_tac thy) cluster_subst @ [rotate_tac 1]
blanchet@40145
   804
      val first_prem = find_index (fn (ax_no', _) => ax_no' = ax_no) substs
blanchet@40145
   805
    in
blanchet@40145
   806
      rotate_tac first_prem
blanchet@40145
   807
      THEN' (EVERY' (maps do_cluster_subst cluster_substs))
blanchet@40145
   808
      THEN' rotate_tac (~ first_prem - length cluster_substs)
blanchet@40501
   809
      THEN' release_clusters_tac thy ax_counts substs clusters
blanchet@40145
   810
    end
blanchet@40145
   811
blanchet@40507
   812
fun cluster_key ((ax_no, (cluster_no, index_no)), skolem) =
blanchet@40507
   813
  (ax_no, (cluster_no, (skolem, index_no)))
blanchet@40507
   814
fun cluster_ord p =
blanchet@40507
   815
  prod_ord int_ord (prod_ord int_ord (prod_ord bool_ord int_ord))
blanchet@40507
   816
           (pairself cluster_key p)
blanchet@40145
   817
blanchet@40145
   818
val tysubst_ord =
blanchet@40145
   819
  list_ord (prod_ord Term_Ord.fast_indexname_ord
blanchet@40145
   820
                     (prod_ord Term_Ord.sort_ord Term_Ord.typ_ord))
blanchet@40145
   821
blanchet@40145
   822
structure Int_Tysubst_Table =
blanchet@40145
   823
  Table(type key = int * (indexname * (sort * typ)) list
blanchet@40145
   824
        val ord = prod_ord int_ord tysubst_ord)
blanchet@40145
   825
blanchet@40145
   826
structure Int_Pair_Graph =
blanchet@40145
   827
  Graph(type key = int * int val ord = prod_ord int_ord int_ord)
blanchet@40145
   828
blanchet@43135
   829
fun shuffle_key (((axiom_no, (_, index_no)), _), _) = (axiom_no, index_no)
blanchet@40501
   830
fun shuffle_ord p = prod_ord int_ord int_ord (pairself shuffle_key p)
blanchet@40501
   831
blanchet@40145
   832
(* Attempts to derive the theorem "False" from a theorem of the form
blanchet@40145
   833
   "P1 ==> ... ==> Pn ==> False", where the "Pi"s are to be discharged using the
blanchet@40145
   834
   specified axioms. The axioms have leading "All" and "Ex" quantifiers, which
blanchet@40145
   835
   must be eliminated first. *)
blanchet@40145
   836
fun discharge_skolem_premises ctxt axioms prems_imp_false =
blanchet@40145
   837
  if prop_of prems_imp_false aconv @{prop False} then
blanchet@40145
   838
    prems_imp_false
blanchet@40145
   839
  else
blanchet@40145
   840
    let
wenzelm@43232
   841
      val thy = Proof_Context.theory_of ctxt
blanchet@40145
   842
      fun match_term p =
blanchet@40145
   843
        let
blanchet@40145
   844
          val (tyenv, tenv) =
blanchet@40145
   845
            Pattern.first_order_match thy p (Vartab.empty, Vartab.empty)
blanchet@40145
   846
          val tsubst =
blanchet@40145
   847
            tenv |> Vartab.dest
blanchet@42963
   848
                 |> filter (Meson_Clausify.is_zapped_var_name o fst o fst)
blanchet@40145
   849
                 |> sort (cluster_ord
blanchet@40145
   850
                          o pairself (Meson_Clausify.cluster_of_zapped_var_name
blanchet@40145
   851
                                      o fst o fst))
blanchet@40145
   852
                 |> map (Meson.term_pair_of
blanchet@40145
   853
                         #> pairself (Envir.subst_term_types tyenv))
blanchet@40145
   854
          val tysubst = tyenv |> Vartab.dest
blanchet@40145
   855
        in (tysubst, tsubst) end
blanchet@40145
   856
      fun subst_info_for_prem subgoal_no prem =
blanchet@40145
   857
        case prem of
blanchet@40145
   858
          _ $ (Const (@{const_name Meson.skolem}, _) $ (_ $ t $ num)) =>
blanchet@40145
   859
          let val ax_no = HOLogic.dest_nat num in
blanchet@40145
   860
            (ax_no, (subgoal_no,
blanchet@40145
   861
                     match_term (nth axioms ax_no |> the |> snd, t)))
blanchet@40145
   862
          end
blanchet@40145
   863
        | _ => raise TERM ("discharge_skolem_premises: Malformed premise",
blanchet@40145
   864
                           [prem])
blanchet@40145
   865
      fun cluster_of_var_name skolem s =
blanchet@42962
   866
        case try Meson_Clausify.cluster_of_zapped_var_name s of
blanchet@42962
   867
          NONE => NONE
blanchet@42962
   868
        | SOME ((ax_no, (cluster_no, _)), skolem') =>
blanchet@40145
   869
          if skolem' = skolem andalso cluster_no > 0 then
blanchet@40145
   870
            SOME (ax_no, cluster_no)
blanchet@40145
   871
          else
blanchet@40145
   872
            NONE
blanchet@40145
   873
      fun clusters_in_term skolem t =
blanchet@40145
   874
        Term.add_var_names t [] |> map_filter (cluster_of_var_name skolem o fst)
blanchet@40145
   875
      fun deps_for_term_subst (var, t) =
blanchet@40145
   876
        case clusters_in_term false var of
blanchet@40145
   877
          [] => NONE
blanchet@40145
   878
        | [(ax_no, cluster_no)] =>
blanchet@40145
   879
          SOME ((ax_no, cluster_no),
blanchet@40145
   880
                clusters_in_term true t
blanchet@40145
   881
                |> cluster_no > 1 ? cons (ax_no, cluster_no - 1))
blanchet@40145
   882
        | _ => raise TERM ("discharge_skolem_premises: Expected Var", [var])
blanchet@40145
   883
      val prems = Logic.strip_imp_prems (prop_of prems_imp_false)
blanchet@40145
   884
      val substs = prems |> map2 subst_info_for_prem (1 upto length prems)
blanchet@40145
   885
                         |> sort (int_ord o pairself fst)
blanchet@40145
   886
      val depss = maps (map_filter deps_for_term_subst o snd o snd o snd) substs
blanchet@40145
   887
      val clusters = maps (op ::) depss
blanchet@40145
   888
      val ordered_clusters =
blanchet@40145
   889
        Int_Pair_Graph.empty
blanchet@40145
   890
        |> fold Int_Pair_Graph.default_node (map (rpair ()) clusters)
blanchet@40145
   891
        |> fold Int_Pair_Graph.add_deps_acyclic depss
blanchet@40145
   892
        |> Int_Pair_Graph.topological_order
blanchet@40145
   893
        handle Int_Pair_Graph.CYCLES _ =>
blanchet@40399
   894
               error "Cannot replay Metis proof in Isabelle without \
blanchet@40399
   895
                     \\"Hilbert_Choice\"."
blanchet@40145
   896
      val ax_counts =
blanchet@40145
   897
        Int_Tysubst_Table.empty
blanchet@40145
   898
        |> fold (fn (ax_no, (_, (tysubst, _))) =>
blanchet@40145
   899
                    Int_Tysubst_Table.map_default ((ax_no, tysubst), 0)
blanchet@40145
   900
                                                  (Integer.add 1)) substs
blanchet@40145
   901
        |> Int_Tysubst_Table.dest
blanchet@43210
   902
      val needed_axiom_props =
blanchet@43210
   903
        0 upto length axioms - 1 ~~ axioms
blanchet@43210
   904
        |> map_filter (fn (_, NONE) => NONE
blanchet@43210
   905
                        | (ax_no, SOME (_, t)) =>
blanchet@43210
   906
                          if exists (fn ((ax_no', _), n) =>
blanchet@43210
   907
                                        ax_no' = ax_no andalso n > 0)
blanchet@43210
   908
                                    ax_counts then
blanchet@43210
   909
                            SOME t
blanchet@43210
   910
                          else
blanchet@43210
   911
                            NONE)
blanchet@43210
   912
      val outer_param_names =
blanchet@43210
   913
        [] |> fold Term.add_var_names needed_axiom_props
blanchet@43210
   914
           |> filter (Meson_Clausify.is_zapped_var_name o fst)
blanchet@43210
   915
           |> map (`(Meson_Clausify.cluster_of_zapped_var_name o fst))
blanchet@43210
   916
           |> filter (fn (((_, (cluster_no, _)), skolem), _) =>
blanchet@43210
   917
                         cluster_no = 0 andalso skolem)
blanchet@43210
   918
           |> sort shuffle_ord |> map (fst o snd)
blanchet@43134
   919
(* for debugging only:
blanchet@40145
   920
      fun string_for_subst_info (ax_no, (subgoal_no, (tysubst, tsubst))) =
blanchet@40145
   921
        "ax: " ^ string_of_int ax_no ^ "; asm: " ^ string_of_int subgoal_no ^
blanchet@40145
   922
        "; tysubst: " ^ PolyML.makestring tysubst ^ "; tsubst: {" ^
blanchet@40145
   923
        commas (map ((fn (s, t) => s ^ " |-> " ^ t)
blanchet@40145
   924
                     o pairself (Syntax.string_of_term ctxt)) tsubst) ^ "}"
blanchet@40507
   925
      val _ = tracing ("ORDERED CLUSTERS: " ^ PolyML.makestring ordered_clusters)
blanchet@40507
   926
      val _ = tracing ("AXIOM COUNTS: " ^ PolyML.makestring ax_counts)
blanchet@43210
   927
      val _ = tracing ("OUTER PARAMS: " ^ PolyML.makestring outer_param_names)
blanchet@40145
   928
      val _ = tracing ("SUBSTS (" ^ string_of_int (length substs) ^ "):\n" ^
blanchet@40145
   929
                       cat_lines (map string_for_subst_info substs))
blanchet@40145
   930
*)
blanchet@43135
   931
      fun cut_and_ex_tac axiom =
blanchet@43135
   932
        cut_rules_tac [axiom] 1
blanchet@43135
   933
        THEN TRY (REPEAT_ALL_NEW (etac @{thm exE}) 1)
blanchet@40145
   934
      fun rotation_for_subgoal i =
blanchet@40145
   935
        find_index (fn (_, (subgoal_no, _)) => subgoal_no = i) substs
blanchet@40145
   936
    in
blanchet@40145
   937
      Goal.prove ctxt [] [] @{prop False}
blanchet@43135
   938
          (K (DETERM (EVERY (map (cut_and_ex_tac o fst o the o nth axioms o fst
blanchet@43135
   939
                                  o fst) ax_counts)
blanchet@43135
   940
                      THEN rename_tac outer_param_names 1
blanchet@43135
   941
                      THEN copy_prems_tac (map snd ax_counts) [] 1)
blanchet@40501
   942
              THEN release_clusters_tac thy ax_counts substs ordered_clusters 1
blanchet@40145
   943
              THEN match_tac [prems_imp_false] 1
blanchet@40145
   944
              THEN ALLGOALS (fn i =>
blanchet@40145
   945
                       rtac @{thm Meson.skolem_COMBK_I} i
blanchet@40145
   946
                       THEN rotate_tac (rotation_for_subgoal i) i
blanchet@43213
   947
                       THEN PRIMITIVE (unify_first_prem_with_concl thy i)
blanchet@43135
   948
                       THEN assume_tac i
blanchet@43134
   949
                       THEN flexflex_tac)))
blanchet@40399
   950
      handle ERROR _ =>
blanchet@40399
   951
             error ("Cannot replay Metis proof in Isabelle:\n\
blanchet@40399
   952
                    \Error when discharging Skolem assumptions.")
blanchet@40145
   953
    end
blanchet@40145
   954
blanchet@39735
   955
end;