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