src/HOL/Tools/Metis/metis_reconstruct.ML
author blanchet
Fri, 18 Nov 2011 11:47:12 +0100
changeset 46440 eb30a5490543
parent 46382 9b0f8ca4388e
child 47148 0b8b73b49848
permissions -rw-r--r--
wrap lambdas earlier, to get more control over beta/eta
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@45347
    12
  type type_enc = ATP_Translate.type_enc
blanchet@45347
    13
blanchet@43521
    14
  exception METIS of string * string
blanchet@43521
    15
blanchet@44000
    16
  val hol_clause_from_metis :
blanchet@46379
    17
    Proof.context -> type_enc -> int Symtab.table
blanchet@46379
    18
    -> (string * term) list * (string * term) list -> Metis_Thm.thm -> term
blanchet@39737
    19
  val lookth : (Metis_Thm.thm * 'a) list -> Metis_Thm.thm -> 'a
blanchet@39737
    20
  val replay_one_inference :
blanchet@46379
    21
    Proof.context -> type_enc
blanchet@46379
    22
    -> (string * term) list * (string * term) list -> int Symtab.table
blanchet@39737
    23
    -> Metis_Thm.thm * Metis_Proof.inference -> (Metis_Thm.thm * thm) list
blanchet@39737
    24
    -> (Metis_Thm.thm * thm) list
blanchet@40145
    25
  val discharge_skolem_premises :
blanchet@40145
    26
    Proof.context -> (thm * term) option list -> thm -> thm
blanchet@39735
    27
end;
blanchet@39735
    28
blanchet@39735
    29
structure Metis_Reconstruct : METIS_RECONSTRUCT =
blanchet@39735
    30
struct
blanchet@39735
    31
blanchet@43935
    32
open ATP_Problem
blanchet@43926
    33
open ATP_Translate
blanchet@43935
    34
open ATP_Reconstruct
blanchet@39737
    35
open Metis_Translate
blanchet@39737
    36
blanchet@43521
    37
exception METIS of string * string
blanchet@43521
    38
blanchet@45347
    39
fun atp_name_from_metis type_enc s =
blanchet@45347
    40
  case find_first (fn (_, (f, _)) => f type_enc = s) metis_name_table of
blanchet@43945
    41
    SOME ((s, _), (_, swap)) => (s, swap)
blanchet@43945
    42
  | _ => (s, false)
blanchet@45347
    43
fun atp_term_from_metis type_enc (Metis_Term.Fn (s, tms)) =
blanchet@45347
    44
    let val (s, swap) = atp_name_from_metis type_enc (Metis_Name.toString s) in
blanchet@45347
    45
      ATerm (s, tms |> map (atp_term_from_metis type_enc) |> swap ? rev)
blanchet@43945
    46
    end
blanchet@45347
    47
  | atp_term_from_metis _ (Metis_Term.Var s) = ATerm (Metis_Name.toString s, [])
blanchet@39737
    48
blanchet@45347
    49
fun hol_term_from_metis ctxt type_enc sym_tab =
blanchet@45347
    50
  atp_term_from_metis type_enc #> term_from_atp ctxt false sym_tab NONE
blanchet@43935
    51
blanchet@45347
    52
fun atp_literal_from_metis type_enc (pos, atom) =
blanchet@45347
    53
  atom |> Metis_Term.Fn |> atp_term_from_metis type_enc
blanchet@45347
    54
       |> AAtom |> not pos ? mk_anot
blanchet@45347
    55
fun atp_clause_from_metis _ [] = AAtom (ATerm (tptp_false, []))
blanchet@45347
    56
  | atp_clause_from_metis type_enc lits =
blanchet@45347
    57
    lits |> map (atp_literal_from_metis type_enc) |> mk_aconns AOr
blanchet@43977
    58
blanchet@46379
    59
fun polish_hol_terms ctxt (lifted, old_skolems) =
blanchet@46440
    60
  map (reveal_lam_lifted lifted #> reveal_old_skolem_terms old_skolems)
blanchet@44053
    61
  #> Syntax.check_terms (Proof_Context.set_mode Proof_Context.mode_pattern ctxt)
blanchet@44025
    62
blanchet@46379
    63
fun hol_clause_from_metis ctxt type_enc sym_tab concealed =
blanchet@44000
    64
  Metis_Thm.clause
blanchet@44000
    65
  #> Metis_LiteralSet.toList
blanchet@45347
    66
  #> atp_clause_from_metis type_enc
blanchet@44000
    67
  #> prop_from_atp ctxt false sym_tab
blanchet@46379
    68
  #> singleton (polish_hol_terms ctxt concealed)
blanchet@43977
    69
blanchet@46379
    70
fun hol_terms_from_metis ctxt type_enc concealed sym_tab fol_tms =
blanchet@45347
    71
  let val ts = map (hol_term_from_metis ctxt type_enc sym_tab) fol_tms
blanchet@40159
    72
      val _ = trace_msg ctxt (fn () => "  calling type inference:")
blanchet@40159
    73
      val _ = app (fn t => trace_msg ctxt
blanchet@40159
    74
                                     (fn () => Syntax.string_of_term ctxt t)) ts
blanchet@46379
    75
      val ts' = ts |> polish_hol_terms ctxt concealed
blanchet@40159
    76
      val _ = app (fn t => trace_msg ctxt
blanchet@39737
    77
                    (fn () => "  final term: " ^ Syntax.string_of_term ctxt t ^
blanchet@43969
    78
                              " of type " ^ Syntax.string_of_typ ctxt (type_of t)))
blanchet@39737
    79
                  ts'
blanchet@39737
    80
  in  ts'  end;
blanchet@39737
    81
blanchet@39737
    82
(* ------------------------------------------------------------------------- *)
blanchet@39737
    83
(* FOL step Inference Rules                                                  *)
blanchet@39737
    84
(* ------------------------------------------------------------------------- *)
blanchet@39737
    85
blanchet@39737
    86
(*for debugging only*)
blanchet@39737
    87
(*
blanchet@40159
    88
fun print_thpair ctxt (fth,th) =
blanchet@40159
    89
  (trace_msg ctxt (fn () => "=============================================");
blanchet@40159
    90
   trace_msg ctxt (fn () => "Metis: " ^ Metis_Thm.toString fth);
blanchet@40159
    91
   trace_msg ctxt (fn () => "Isabelle: " ^ Display.string_of_thm_without_context th));
blanchet@39737
    92
*)
blanchet@39737
    93
blanchet@43935
    94
fun lookth th_pairs fth =
blanchet@43935
    95
  the (AList.lookup (uncurry Metis_Thm.equal) th_pairs fth)
blanchet@39737
    96
  handle Option.Option =>
blanchet@39737
    97
         raise Fail ("Failed to find Metis theorem " ^ Metis_Thm.toString fth)
blanchet@39737
    98
blanchet@39737
    99
fun cterm_incr_types thy idx = cterm_of thy o (map_types (Logic.incr_tvar idx));
blanchet@39737
   100
blanchet@39737
   101
(* INFERENCE RULE: AXIOM *)
blanchet@39737
   102
blanchet@44053
   103
(* This causes variables to have an index of 1 by default. See also
blanchet@44053
   104
   "term_from_atp" in "ATP_Reconstruct". *)
blanchet@44053
   105
val axiom_inference = Thm.incr_indexes 1 oo lookth
blanchet@39737
   106
blanchet@39737
   107
(* INFERENCE RULE: ASSUME *)
blanchet@39737
   108
blanchet@39737
   109
val EXCLUDED_MIDDLE = @{lemma "P ==> ~ P ==> False" by (rule notE)}
blanchet@39737
   110
blanchet@44028
   111
fun inst_excluded_middle thy i_atom =
blanchet@39737
   112
  let val th = EXCLUDED_MIDDLE
blanchet@39737
   113
      val [vx] = Term.add_vars (prop_of th) []
blanchet@44028
   114
      val substs = [(cterm_of thy (Var vx), cterm_of thy i_atom)]
blanchet@39737
   115
  in  cterm_instantiate substs th  end;
blanchet@39737
   116
blanchet@46379
   117
fun assume_inference ctxt type_enc concealed sym_tab atom =
blanchet@39737
   118
  inst_excluded_middle
wenzelm@43232
   119
      (Proof_Context.theory_of ctxt)
blanchet@46379
   120
      (singleton (hol_terms_from_metis ctxt type_enc concealed sym_tab)
blanchet@44028
   121
                 (Metis_Term.Fn atom))
blanchet@39737
   122
blanchet@39738
   123
(* INFERENCE RULE: INSTANTIATE (SUBST). Type instantiations are ignored. Trying
blanchet@39737
   124
   to reconstruct them admits new possibilities of errors, e.g. concerning
blanchet@39737
   125
   sorts. Instead we try to arrange that new TVars are distinct and that types
blanchet@39738
   126
   can be inferred from terms. *)
blanchet@39737
   127
blanchet@46379
   128
fun inst_inference ctxt type_enc concealed sym_tab th_pairs fsubst th =
wenzelm@43232
   129
  let val thy = Proof_Context.theory_of ctxt
blanchet@43935
   130
      val i_th = lookth th_pairs th
blanchet@39737
   131
      val i_th_vars = Term.add_vars (prop_of i_th) []
blanchet@39737
   132
      fun find_var x = the (List.find (fn ((a,_),_) => a=x) i_th_vars)
blanchet@39737
   133
      fun subst_translation (x,y) =
blanchet@39738
   134
        let val v = find_var x
blanchet@46379
   135
            (* We call "polish_hol_terms" below. *)
blanchet@45347
   136
            val t = hol_term_from_metis ctxt type_enc sym_tab y
blanchet@39738
   137
        in  SOME (cterm_of thy (Var v), t)  end
blanchet@39738
   138
        handle Option.Option =>
blanchet@40159
   139
               (trace_msg ctxt (fn () => "\"find_var\" failed for " ^ x ^
blanchet@40159
   140
                                         " in " ^ Display.string_of_thm ctxt i_th);
blanchet@39738
   141
                NONE)
blanchet@39738
   142
             | TYPE _ =>
blanchet@40159
   143
               (trace_msg ctxt (fn () => "\"hol_term_from_metis\" failed for " ^ x ^
blanchet@40159
   144
                                         " in " ^ Display.string_of_thm ctxt i_th);
blanchet@39738
   145
                NONE)
blanchet@39737
   146
      fun remove_typeinst (a, t) =
blanchet@44109
   147
        let val a = Metis_Name.toString a in
blanchet@46382
   148
          case unprefix_and_unascii schematic_var_prefix a of
blanchet@44109
   149
            SOME b => SOME (b, t)
blanchet@44109
   150
          | NONE =>
blanchet@46382
   151
            case unprefix_and_unascii tvar_prefix a of
blanchet@44109
   152
              SOME _ => NONE (* type instantiations are forbidden *)
blanchet@44109
   153
            | NONE => SOME (a, t) (* internal Metis var? *)
blanchet@44109
   154
        end
blanchet@40159
   155
      val _ = trace_msg ctxt (fn () => "  isa th: " ^ Display.string_of_thm ctxt i_th)
blanchet@39737
   156
      val substs = map_filter remove_typeinst (Metis_Subst.toList fsubst)
blanchet@44025
   157
      val (vars, tms) =
blanchet@44025
   158
        ListPair.unzip (map_filter subst_translation substs)
blanchet@46379
   159
        ||> polish_hol_terms ctxt concealed
blanchet@39737
   160
      val ctm_of = cterm_incr_types thy (1 + Thm.maxidx_of i_th)
blanchet@39737
   161
      val substs' = ListPair.zip (vars, map ctm_of tms)
blanchet@40159
   162
      val _ = trace_msg ctxt (fn () =>
blanchet@39737
   163
        cat_lines ("subst_translations:" ::
blanchet@39737
   164
          (substs' |> map (fn (x, y) =>
blanchet@39737
   165
            Syntax.string_of_term ctxt (term_of x) ^ " |-> " ^
blanchet@39737
   166
            Syntax.string_of_term ctxt (term_of y)))));
blanchet@39737
   167
  in cterm_instantiate substs' i_th end
blanchet@44027
   168
  handle THM (msg, _, _) => raise METIS ("inst_inference", msg)
blanchet@44027
   169
       | ERROR msg => raise METIS ("inst_inference", msg)
blanchet@39737
   170
blanchet@39737
   171
(* INFERENCE RULE: RESOLVE *)
blanchet@39737
   172
wenzelm@44212
   173
(*Increment the indexes of only the type variables*)
wenzelm@44212
   174
fun incr_type_indexes inc th =
wenzelm@44212
   175
  let val tvs = Term.add_tvars (Thm.full_prop_of th) []
wenzelm@44212
   176
      and thy = Thm.theory_of_thm th
wenzelm@44212
   177
      fun inc_tvar ((a,i),s) = pairself (ctyp_of thy) (TVar ((a,i),s), TVar ((a,i+inc),s))
wenzelm@44212
   178
  in Thm.instantiate (map inc_tvar tvs, []) th end;
wenzelm@44212
   179
blanchet@39737
   180
(* Like RSN, but we rename apart only the type variables. Vars here typically
blanchet@39737
   181
   have an index of 1, and the use of RSN would increase this typically to 3.
blanchet@44171
   182
   Instantiations of those Vars could then fail. *)
blanchet@39737
   183
fun resolve_inc_tyvars thy tha i thb =
blanchet@39737
   184
  let
wenzelm@44212
   185
    val tha = incr_type_indexes (1 + Thm.maxidx_of thb) tha
blanchet@44230
   186
    fun aux (tha, thb) =
blanchet@39737
   187
      case Thm.bicompose false (false, tha, nprems_of tha) i thb
blanchet@39737
   188
           |> Seq.list_of |> distinct Thm.eq_thm of
blanchet@39737
   189
        [th] => th
blanchet@39737
   190
      | _ => raise THM ("resolve_inc_tyvars: unique result expected", i,
blanchet@39737
   191
                        [tha, thb])
blanchet@39737
   192
  in
blanchet@44230
   193
    aux (tha, thb)
blanchet@39737
   194
    handle TERM z =>
blanchet@39737
   195
           (* The unifier, which is invoked from "Thm.bicompose", will sometimes
blanchet@39737
   196
              refuse to unify "?a::?'a" with "?a::?'b" or "?a::nat" and throw a
blanchet@39737
   197
              "TERM" exception (with "add_ffpair" as first argument). We then
blanchet@39737
   198
              perform unification of the types of variables by hand and try
blanchet@39737
   199
              again. We could do this the first time around but this error
blanchet@39737
   200
              occurs seldom and we don't want to break existing proofs in subtle
blanchet@39737
   201
              ways or slow them down needlessly. *)
blanchet@39737
   202
           case [] |> fold (Term.add_vars o prop_of) [tha, thb]
blanchet@39737
   203
                   |> AList.group (op =)
blanchet@39737
   204
                   |> maps (fn ((s, _), T :: Ts) =>
blanchet@39737
   205
                               map (fn T' => (Free (s, T), Free (s, T'))) Ts)
blanchet@39737
   206
                   |> rpair (Envir.empty ~1)
blanchet@39737
   207
                   |-> fold (Pattern.unify thy)
blanchet@39737
   208
                   |> Envir.type_env |> Vartab.dest
blanchet@39737
   209
                   |> map (fn (x, (S, T)) =>
blanchet@39737
   210
                              pairself (ctyp_of thy) (TVar (x, S), T)) of
blanchet@39737
   211
             [] => raise TERM z
blanchet@44230
   212
           | ps => (tha, thb) |> pairself (Drule.instantiate_normalize (ps, []))
blanchet@44230
   213
                              |> aux
blanchet@39737
   214
  end
blanchet@39737
   215
blanchet@40462
   216
fun s_not (@{const Not} $ t) = t
blanchet@40462
   217
  | s_not t = HOLogic.mk_not t
blanchet@44036
   218
fun simp_not_not (@{const Trueprop} $ t) = @{const Trueprop} $ simp_not_not t
blanchet@44036
   219
  | simp_not_not (@{const Not} $ t) = s_not (simp_not_not t)
blanchet@40462
   220
  | simp_not_not t = t
blanchet@39737
   221
blanchet@44036
   222
val normalize_literal = simp_not_not o Envir.eta_contract
blanchet@44036
   223
blanchet@44028
   224
(* Find the relative location of an untyped term within a list of terms as a
blanchet@44028
   225
   1-based index. Returns 0 in case of failure. *)
blanchet@40462
   226
fun index_of_literal lit haystack =
blanchet@39737
   227
  let
blanchet@44036
   228
    fun match_lit normalize =
blanchet@43975
   229
      HOLogic.dest_Trueprop #> normalize
blanchet@44172
   230
      #> curry Term.aconv_untyped (lit |> normalize)
blanchet@44036
   231
  in
blanchet@44036
   232
    (case find_index (match_lit I) haystack of
blanchet@44036
   233
       ~1 => find_index (match_lit (simp_not_not o Envir.eta_contract)) haystack
blanchet@44036
   234
     | j => j) + 1
blanchet@44036
   235
  end
blanchet@39737
   236
blanchet@40074
   237
(* Permute a rule's premises to move the i-th premise to the last position. *)
blanchet@40074
   238
fun make_last i th =
blanchet@40074
   239
  let val n = nprems_of th
blanchet@40074
   240
  in  if 1 <= i andalso i <= n
blanchet@40074
   241
      then Thm.permute_prems (i-1) 1 th
blanchet@40074
   242
      else raise THM("select_literal", i, [th])
blanchet@40074
   243
  end;
blanchet@40074
   244
blanchet@43219
   245
(* Maps a rule that ends "... ==> P ==> False" to "... ==> ~ P" while avoiding
blanchet@43220
   246
   to create double negations. The "select" wrapper is a trick to ensure that
blanchet@43220
   247
   "P ==> ~ False ==> False" is rewritten to "P ==> False", not to "~ P". We
blanchet@43220
   248
   don't use this trick in general because it makes the proof object uglier than
blanchet@43220
   249
   necessary. FIXME. *)
blanchet@43220
   250
fun negate_head th =
blanchet@43220
   251
  if exists (fn t => t aconv @{prop "~ False"}) (prems_of th) then
blanchet@43220
   252
    (th RS @{thm select_FalseI})
blanchet@43220
   253
    |> fold (rewrite_rule o single)
blanchet@43220
   254
            @{thms not_atomize_select atomize_not_select}
blanchet@43220
   255
  else
blanchet@43220
   256
    th |> fold (rewrite_rule o single) @{thms not_atomize atomize_not}
blanchet@40074
   257
blanchet@40074
   258
(* Maps the clause  [P1,...Pn]==>False to [P1,...,P(i-1),P(i+1),...Pn] ==> ~P *)
blanchet@43219
   259
val select_literal = negate_head oo make_last
blanchet@40074
   260
blanchet@46379
   261
fun resolve_inference ctxt type_enc concealed sym_tab th_pairs atom th1 th2 =
blanchet@39737
   262
  let
blanchet@43935
   263
    val (i_th1, i_th2) = pairself (lookth th_pairs) (th1, th2)
blanchet@44028
   264
    val _ = trace_msg ctxt (fn () =>
blanchet@44028
   265
        "  isa th1 (pos): " ^ Display.string_of_thm ctxt i_th1 ^ "\n\
blanchet@44028
   266
        \  isa th2 (neg): " ^ Display.string_of_thm ctxt i_th2)
blanchet@39737
   267
  in
blanchet@39737
   268
    (* Trivial cases where one operand is type info *)
blanchet@39737
   269
    if Thm.eq_thm (TrueI, i_th1) then
blanchet@39737
   270
      i_th2
blanchet@39737
   271
    else if Thm.eq_thm (TrueI, i_th2) then
blanchet@39737
   272
      i_th1
blanchet@39737
   273
    else
blanchet@39737
   274
      let
blanchet@44028
   275
        val thy = Proof_Context.theory_of ctxt
blanchet@44028
   276
        val i_atom =
blanchet@46379
   277
          singleton (hol_terms_from_metis ctxt type_enc concealed sym_tab)
blanchet@44028
   278
                    (Metis_Term.Fn atom)
blanchet@44028
   279
        val _ = trace_msg ctxt (fn () =>
blanchet@44028
   280
                    "  atom: " ^ Syntax.string_of_term ctxt i_atom)
blanchet@44028
   281
      in
blanchet@44028
   282
        case index_of_literal (s_not i_atom) (prems_of i_th1) of
blanchet@44028
   283
          0 =>
blanchet@44028
   284
          (trace_msg ctxt (fn () => "Failed to find literal in \"th1\"");
blanchet@44028
   285
           i_th1)
blanchet@44028
   286
        | j1 =>
blanchet@44028
   287
          (trace_msg ctxt (fn () => "  index th1: " ^ string_of_int j1);
blanchet@44028
   288
           case index_of_literal i_atom (prems_of i_th2) of
blanchet@44028
   289
             0 =>
blanchet@44028
   290
             (trace_msg ctxt (fn () => "Failed to find literal in \"th2\"");
blanchet@44028
   291
              i_th2)
blanchet@44028
   292
           | j2 =>
blanchet@44028
   293
             (trace_msg ctxt (fn () => "  index th2: " ^ string_of_int j2);
blanchet@44028
   294
              resolve_inc_tyvars thy (select_literal j1 i_th1) j2 i_th2
blanchet@44028
   295
              handle TERM (s, _) => raise METIS ("resolve_inference", s)))
blanchet@44028
   296
      end
blanchet@44028
   297
  end
blanchet@39737
   298
blanchet@39737
   299
(* INFERENCE RULE: REFL *)
blanchet@39737
   300
blanchet@39737
   301
val REFL_THM = Thm.incr_indexes 2 @{lemma "t ~= t ==> False" by simp}
blanchet@39737
   302
blanchet@39737
   303
val refl_x = cterm_of @{theory} (Var (hd (Term.add_vars (prop_of REFL_THM) [])));
blanchet@39737
   304
val refl_idx = 1 + Thm.maxidx_of REFL_THM;
blanchet@39737
   305
blanchet@46379
   306
fun refl_inference ctxt type_enc concealed sym_tab t =
blanchet@43935
   307
  let
blanchet@43935
   308
    val thy = Proof_Context.theory_of ctxt
blanchet@45347
   309
    val i_t =
blanchet@46379
   310
      singleton (hol_terms_from_metis ctxt type_enc concealed sym_tab) t
blanchet@43935
   311
    val _ = trace_msg ctxt (fn () => "  term: " ^ Syntax.string_of_term ctxt i_t)
blanchet@43935
   312
    val c_t = cterm_incr_types thy refl_idx i_t
blanchet@43935
   313
  in cterm_instantiate [(refl_x, c_t)] REFL_THM end
blanchet@39737
   314
blanchet@39737
   315
(* INFERENCE RULE: EQUALITY *)
blanchet@39737
   316
blanchet@39737
   317
val subst_em = @{lemma "s = t ==> P s ==> ~ P t ==> False" by simp}
blanchet@39737
   318
val ssubst_em = @{lemma "s = t ==> P t ==> ~ P s ==> False" by simp}
blanchet@39737
   319
blanchet@46379
   320
fun equality_inference ctxt type_enc concealed sym_tab (pos, atom) fp fr =
wenzelm@43232
   321
  let val thy = Proof_Context.theory_of ctxt
blanchet@44028
   322
      val m_tm = Metis_Term.Fn atom
blanchet@44028
   323
      val [i_atom, i_tm] =
blanchet@46379
   324
        hol_terms_from_metis ctxt type_enc concealed sym_tab [m_tm, fr]
blanchet@40159
   325
      val _ = trace_msg ctxt (fn () => "sign of the literal: " ^ Bool.toString pos)
blanchet@39737
   326
      fun replace_item_list lx 0 (_::ls) = lx::ls
blanchet@39737
   327
        | replace_item_list lx i (l::ls) = l :: replace_item_list lx (i-1) ls
blanchet@44046
   328
      fun path_finder_fail tm ps t =
blanchet@44050
   329
        raise METIS ("equality_inference (path_finder)",
blanchet@44050
   330
                     "path = " ^ space_implode " " (map string_of_int ps) ^
blanchet@44050
   331
                     " isa-term: " ^ Syntax.string_of_term ctxt tm ^
blanchet@44050
   332
                     (case t of
blanchet@44050
   333
                        SOME t => " fol-term: " ^ Metis_Term.toString t
blanchet@44050
   334
                      | NONE => ""))
blanchet@44053
   335
      fun path_finder tm [] _ = (tm, Bound 0)
blanchet@44053
   336
        | path_finder tm (p :: ps) (t as Metis_Term.Fn (s, ts)) =
blanchet@44018
   337
          let
blanchet@44109
   338
            val s = s |> Metis_Name.toString
blanchet@46382
   339
                      |> perhaps (try (unprefix_and_unascii const_prefix
blanchet@44018
   340
                                       #> the #> unmangled_const_name))
blanchet@44018
   341
          in
blanchet@44018
   342
            if s = metis_predicator orelse s = predicator_name orelse
blanchet@45347
   343
               s = metis_systematic_type_tag orelse s = metis_ad_hoc_type_tag
blanchet@45347
   344
               orelse s = type_tag_name then
blanchet@44053
   345
              path_finder tm ps (nth ts p)
blanchet@44018
   346
            else if s = metis_app_op orelse s = app_op_name then
blanchet@43971
   347
              let
blanchet@43971
   348
                val (tm1, tm2) = dest_comb tm
blanchet@43971
   349
                val p' = p - (length ts - 2)
blanchet@43971
   350
              in
blanchet@43971
   351
                if p' = 0 then
blanchet@44053
   352
                  path_finder tm1 ps (nth ts p) ||> (fn y => y $ tm2)
blanchet@43971
   353
                else
blanchet@44053
   354
                  path_finder tm2 ps (nth ts p) ||> (fn y => tm1 $ y)
blanchet@43971
   355
              end
blanchet@43971
   356
            else
blanchet@43971
   357
              let
blanchet@43971
   358
                val (tm1, args) = strip_comb tm
blanchet@43971
   359
                val adjustment = length ts - length args
blanchet@43971
   360
                val p' = if adjustment > p then p else p - adjustment
blanchet@44046
   361
                val tm_p =
blanchet@44046
   362
                  nth args p'
wenzelm@44158
   363
                  handle General.Subscript => path_finder_fail tm (p :: ps) (SOME t)
blanchet@43971
   364
                val _ = trace_msg ctxt (fn () =>
blanchet@43971
   365
                    "path_finder: " ^ string_of_int p ^ "  " ^
blanchet@43971
   366
                    Syntax.string_of_term ctxt tm_p)
blanchet@44053
   367
                val (r, t) = path_finder tm_p ps (nth ts p)
blanchet@43971
   368
              in (r, list_comb (tm1, replace_item_list t p' args)) end
blanchet@43971
   369
          end
blanchet@44053
   370
        | path_finder tm ps t = path_finder_fail tm ps (SOME t)
blanchet@44053
   371
      val (tm_subst, body) = path_finder i_atom fp m_tm
blanchet@39738
   372
      val tm_abs = Abs ("x", type_of tm_subst, body)
blanchet@40159
   373
      val _ = trace_msg ctxt (fn () => "abstraction: " ^ Syntax.string_of_term ctxt tm_abs)
blanchet@40159
   374
      val _ = trace_msg ctxt (fn () => "i_tm: " ^ Syntax.string_of_term ctxt i_tm)
blanchet@40159
   375
      val _ = trace_msg ctxt (fn () => "located term: " ^ Syntax.string_of_term ctxt tm_subst)
blanchet@39737
   376
      val imax = maxidx_of_term (i_tm $ tm_abs $ tm_subst)  (*ill typed but gives right max*)
blanchet@39737
   377
      val subst' = Thm.incr_indexes (imax+1) (if pos then subst_em else ssubst_em)
blanchet@40159
   378
      val _ = trace_msg ctxt (fn () => "subst' " ^ Display.string_of_thm ctxt subst')
blanchet@39737
   379
      val eq_terms = map (pairself (cterm_of thy))
wenzelm@45004
   380
        (ListPair.zip (Misc_Legacy.term_vars (prop_of subst'), [tm_abs, tm_subst, i_tm]))
blanchet@39737
   381
  in  cterm_instantiate eq_terms subst'  end;
blanchet@39737
   382
blanchet@43935
   383
val factor = Seq.hd o distinct_subgoals_tac
blanchet@39737
   384
blanchet@46379
   385
fun one_step ctxt type_enc concealed sym_tab th_pairs p =
blanchet@39737
   386
  case p of
blanchet@44027
   387
    (fol_th, Metis_Proof.Axiom _) => axiom_inference th_pairs fol_th |> factor
blanchet@44028
   388
  | (_, Metis_Proof.Assume f_atom) =>
blanchet@46379
   389
    assume_inference ctxt type_enc concealed sym_tab f_atom
blanchet@39737
   390
  | (_, Metis_Proof.Metis_Subst (f_subst, f_th1)) =>
blanchet@46379
   391
    inst_inference ctxt type_enc concealed sym_tab th_pairs f_subst f_th1
blanchet@44027
   392
    |> factor
blanchet@44028
   393
  | (_, Metis_Proof.Resolve(f_atom, f_th1, f_th2)) =>
blanchet@46379
   394
    resolve_inference ctxt type_enc concealed sym_tab th_pairs f_atom f_th1
blanchet@45347
   395
                      f_th2
blanchet@43935
   396
    |> factor
blanchet@44027
   397
  | (_, Metis_Proof.Refl f_tm) =>
blanchet@46379
   398
    refl_inference ctxt type_enc concealed sym_tab f_tm
blanchet@39737
   399
  | (_, Metis_Proof.Equality (f_lit, f_p, f_r)) =>
blanchet@46379
   400
    equality_inference ctxt type_enc concealed sym_tab f_lit f_p f_r
blanchet@39737
   401
blanchet@40074
   402
fun flexflex_first_order th =
blanchet@40074
   403
  case Thm.tpairs_of th of
blanchet@40074
   404
      [] => th
blanchet@40074
   405
    | pairs =>
blanchet@40074
   406
        let val thy = theory_of_thm th
blanchet@40074
   407
            val (_, tenv) =
blanchet@40074
   408
              fold (Pattern.first_order_match thy) pairs (Vartab.empty, Vartab.empty)
blanchet@40074
   409
            val t_pairs = map Meson.term_pair_of (Vartab.dest tenv)
blanchet@40074
   410
            val th' = Thm.instantiate ([], map (pairself (cterm_of thy)) t_pairs) th
blanchet@40074
   411
        in  th'  end
blanchet@40074
   412
        handle THM _ => th;
blanchet@39737
   413
blanchet@44109
   414
fun is_metis_literal_genuine (_, (s, _)) =
blanchet@44109
   415
  not (String.isPrefix class_prefix (Metis_Name.toString s))
blanchet@40076
   416
fun is_isabelle_literal_genuine t =
blanchet@40134
   417
  case t of _ $ (Const (@{const_name Meson.skolem}, _) $ _) => false | _ => true
blanchet@40076
   418
blanchet@40076
   419
fun count p xs = fold (fn x => if p x then Integer.add 1 else I) xs 0
blanchet@40076
   420
blanchet@43204
   421
(* Seldomly needed hack. A Metis clause is represented as a set, so duplicate
blanchet@43204
   422
   disjuncts are impossible. In the Isabelle proof, in spite of efforts to
blanchet@43204
   423
   eliminate them, duplicates sometimes appear with slightly different (but
blanchet@43204
   424
   unifiable) types. *)
blanchet@43204
   425
fun resynchronize ctxt fol_th th =
blanchet@43204
   426
  let
blanchet@43204
   427
    val num_metis_lits =
blanchet@43204
   428
      count is_metis_literal_genuine
blanchet@43204
   429
            (Metis_LiteralSet.toList (Metis_Thm.clause fol_th))
blanchet@43204
   430
    val num_isabelle_lits = count is_isabelle_literal_genuine (prems_of th)
blanchet@43204
   431
  in
blanchet@43204
   432
    if num_metis_lits >= num_isabelle_lits then
blanchet@43204
   433
      th
blanchet@43204
   434
    else
blanchet@43204
   435
      let
blanchet@43204
   436
        val (prems0, concl) = th |> prop_of |> Logic.strip_horn
blanchet@44036
   437
        val prems = prems0 |> map normalize_literal
blanchet@44172
   438
                           |> distinct Term.aconv_untyped
blanchet@43204
   439
        val goal = Logic.list_implies (prems, concl)
blanchet@44036
   440
        val tac = cut_rules_tac [th] 1
blanchet@44036
   441
                  THEN rewrite_goals_tac @{thms not_not [THEN eq_reflection]}
blanchet@44036
   442
                  THEN ALLGOALS assume_tac
blanchet@43204
   443
      in
blanchet@43204
   444
        if length prems = length prems0 then
blanchet@43521
   445
          raise METIS ("resynchronize", "Out of sync")
blanchet@43204
   446
        else
blanchet@44036
   447
          Goal.prove ctxt [] [] goal (K tac)
blanchet@43204
   448
          |> resynchronize ctxt fol_th
blanchet@43204
   449
      end
blanchet@43204
   450
  end
blanchet@43204
   451
blanchet@46379
   452
fun replay_one_inference ctxt type_enc concealed sym_tab (fol_th, inf)
blanchet@45347
   453
                         th_pairs =
blanchet@43935
   454
  if not (null th_pairs) andalso
blanchet@43935
   455
     prop_of (snd (hd th_pairs)) aconv @{prop False} then
blanchet@41110
   456
    (* Isabelle sometimes identifies literals (premises) that are distinct in
blanchet@41110
   457
       Metis (e.g., because of type variables). We give the Isabelle proof the
blanchet@41110
   458
       benefice of the doubt. *)
blanchet@43935
   459
    th_pairs
blanchet@41110
   460
  else
blanchet@41110
   461
    let
blanchet@41110
   462
      val _ = trace_msg ctxt
blanchet@41110
   463
                  (fn () => "=============================================")
blanchet@41110
   464
      val _ = trace_msg ctxt
blanchet@41110
   465
                  (fn () => "METIS THM: " ^ Metis_Thm.toString fol_th)
blanchet@41110
   466
      val _ = trace_msg ctxt
blanchet@41110
   467
                  (fn () => "INFERENCE: " ^ Metis_Proof.inferenceToString inf)
blanchet@46379
   468
      val th = one_step ctxt type_enc concealed sym_tab th_pairs (fol_th, inf)
blanchet@41110
   469
               |> flexflex_first_order
blanchet@43204
   470
               |> resynchronize ctxt fol_th
blanchet@41110
   471
      val _ = trace_msg ctxt
blanchet@41110
   472
                  (fn () => "ISABELLE THM: " ^ Display.string_of_thm ctxt th)
blanchet@41110
   473
      val _ = trace_msg ctxt
blanchet@41110
   474
                  (fn () => "=============================================")
blanchet@43935
   475
    in (fol_th, th) :: th_pairs end
blanchet@39737
   476
blanchet@43213
   477
(* It is normally sufficient to apply "assume_tac" to unify the conclusion with
blanchet@43213
   478
   one of the premises. Unfortunately, this sometimes yields "Variable
blanchet@43213
   479
   ?SK_a_b_c_x has two distinct types" errors. To avoid this, we instantiate the
blanchet@43213
   480
   variables before applying "assume_tac". Typical constraints are of the form
blanchet@43213
   481
     ?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
   482
   where the nonvariables are goal parameters. *)
blanchet@43213
   483
fun unify_first_prem_with_concl thy i th =
blanchet@43213
   484
  let
blanchet@43213
   485
    val goal = Logic.get_goal (prop_of th) i |> Envir.beta_eta_contract
blanchet@43213
   486
    val prem = goal |> Logic.strip_assums_hyp |> hd
blanchet@43213
   487
    val concl = goal |> Logic.strip_assums_concl
blanchet@43213
   488
    fun pair_untyped_aconv (t1, t2) (u1, u2) =
blanchet@44172
   489
      Term.aconv_untyped (t1, u1) andalso Term.aconv_untyped (t2, u2)
blanchet@43213
   490
    fun add_terms tp inst =
blanchet@43213
   491
      if exists (pair_untyped_aconv tp) inst then inst
blanchet@43213
   492
      else tp :: map (apsnd (subst_atomic [tp])) inst
blanchet@43213
   493
    fun is_flex t =
blanchet@43213
   494
      case strip_comb t of
blanchet@43213
   495
        (Var _, args) => forall is_Bound args
blanchet@43213
   496
      | _ => false
blanchet@43213
   497
    fun unify_flex flex rigid =
blanchet@43213
   498
      case strip_comb flex of
blanchet@43213
   499
        (Var (z as (_, T)), args) =>
blanchet@43213
   500
        add_terms (Var z,
wenzelm@45112
   501
          fold_rev absdummy (take (length args) (binder_types T)) rigid)
blanchet@43213
   502
      | _ => I
blanchet@43213
   503
    fun unify_potential_flex comb atom =
blanchet@43213
   504
      if is_flex comb then unify_flex comb atom
blanchet@43213
   505
      else if is_Var atom then add_terms (atom, comb)
blanchet@43213
   506
      else I
blanchet@43213
   507
    fun unify_terms (t, u) =
blanchet@43213
   508
      case (t, u) of
blanchet@43213
   509
        (t1 $ t2, u1 $ u2) =>
blanchet@43213
   510
        if is_flex t then unify_flex t u
blanchet@43213
   511
        else if is_flex u then unify_flex u t
blanchet@43213
   512
        else fold unify_terms [(t1, u1), (t2, u2)]
blanchet@43213
   513
      | (_ $ _, _) => unify_potential_flex t u
blanchet@43213
   514
      | (_, _ $ _) => unify_potential_flex u t
blanchet@43213
   515
      | (Var _, _) => add_terms (t, u)
blanchet@43213
   516
      | (_, Var _) => add_terms (u, t)
blanchet@43213
   517
      | _ => I
blanchet@43215
   518
    val t_inst =
blanchet@43215
   519
      [] |> try (unify_terms (prem, concl) #> map (pairself (cterm_of thy)))
blanchet@43215
   520
         |> the_default [] (* FIXME *)
blanchet@43213
   521
  in th |> cterm_instantiate t_inst end
blanchet@40145
   522
blanchet@40145
   523
val copy_prem = @{lemma "P ==> (P ==> P ==> Q) ==> Q" by fast}
blanchet@40145
   524
blanchet@40145
   525
fun copy_prems_tac [] ns i =
blanchet@40145
   526
    if forall (curry (op =) 1) ns then all_tac else copy_prems_tac (rev ns) [] i
blanchet@40145
   527
  | copy_prems_tac (1 :: ms) ns i =
blanchet@40145
   528
    rotate_tac 1 i THEN copy_prems_tac ms (1 :: ns) i
blanchet@40145
   529
  | copy_prems_tac (m :: ms) ns i =
blanchet@40145
   530
    etac copy_prem i THEN copy_prems_tac ms (m div 2 :: (m + 1) div 2 :: ns) i
blanchet@40145
   531
blanchet@43135
   532
(* Metis generates variables of the form _nnn. *)
blanchet@43135
   533
val is_metis_fresh_variable = String.isPrefix "_"
blanchet@43135
   534
blanchet@40501
   535
fun instantiate_forall_tac thy t i st =
blanchet@40145
   536
  let
blanchet@40501
   537
    val params = Logic.strip_params (Logic.get_goal (prop_of st) i) |> rev
blanchet@40145
   538
    fun repair (t as (Var ((s, _), _))) =
blanchet@40501
   539
        (case find_index (fn (s', _) => s' = s) params of
blanchet@40145
   540
           ~1 => t
blanchet@40145
   541
         | j => Bound j)
blanchet@40504
   542
      | repair (t $ u) =
blanchet@40504
   543
        (case (repair t, repair u) of
blanchet@40504
   544
           (t as Bound j, u as Bound k) =>
blanchet@40504
   545
           (* This is a rather subtle trick to repair the discrepancy between
blanchet@40504
   546
              the fully skolemized term that MESON gives us (where existentials
blanchet@40504
   547
              were pulled out) and the reality. *)
blanchet@40504
   548
           if k > j then t else t $ u
blanchet@40504
   549
         | (t, u) => t $ u)
blanchet@40145
   550
      | repair t = t
wenzelm@45112
   551
    val t' = t |> repair |> fold (absdummy o snd) params
blanchet@40145
   552
    fun do_instantiate th =
blanchet@43134
   553
      case Term.add_vars (prop_of th) []
blanchet@43135
   554
           |> filter_out ((Meson_Clausify.is_zapped_var_name orf
blanchet@43135
   555
                           is_metis_fresh_variable) o fst o fst) of
blanchet@43134
   556
        [] => th
blanchet@43135
   557
      | [var as (_, T)] =>
blanchet@43135
   558
        let
blanchet@43135
   559
          val var_binder_Ts = T |> binder_types |> take (length params) |> rev
blanchet@43135
   560
          val var_body_T = T |> funpow (length params) range_type
blanchet@43135
   561
          val tyenv =
blanchet@43135
   562
            Vartab.empty |> Type.raw_unifys (fastype_of t :: map snd params,
blanchet@43135
   563
                                             var_body_T :: var_binder_Ts)
blanchet@43135
   564
          val env =
blanchet@43135
   565
            Envir.Envir {maxidx = Vartab.fold (Integer.max o snd o fst) tyenv 0,
blanchet@43135
   566
                         tenv = Vartab.empty, tyenv = tyenv}
blanchet@43135
   567
          val ty_inst =
blanchet@43135
   568
            Vartab.fold (fn (x, (S, T)) =>
blanchet@43135
   569
                            cons (pairself (ctyp_of thy) (TVar (x, S), T)))
blanchet@43135
   570
                        tyenv []
blanchet@43135
   571
          val t_inst =
blanchet@43135
   572
            [pairself (cterm_of thy o Envir.norm_term env) (Var var, t')]
wenzelm@44215
   573
        in th |> Drule.instantiate_normalize (ty_inst, t_inst) end
blanchet@43135
   574
      | _ => raise Fail "expected a single non-zapped, non-Metis Var"
blanchet@40145
   575
  in
blanchet@43135
   576
    (DETERM (etac @{thm allE} i THEN rotate_tac ~1 i)
blanchet@40501
   577
     THEN PRIMITIVE do_instantiate) st
blanchet@40145
   578
  end
blanchet@40145
   579
blanchet@41383
   580
fun fix_exists_tac t =
blanchet@44003
   581
  etac @{thm exE} THEN' rename_tac [t |> dest_Var |> fst |> fst]
blanchet@40504
   582
blanchet@40504
   583
fun release_quantifier_tac thy (skolem, t) =
blanchet@41383
   584
  (if skolem then fix_exists_tac else instantiate_forall_tac thy) t
blanchet@40504
   585
blanchet@40501
   586
fun release_clusters_tac _ _ _ [] = K all_tac
blanchet@40501
   587
  | release_clusters_tac thy ax_counts substs
blanchet@40145
   588
                         ((ax_no, cluster_no) :: clusters) =
blanchet@40145
   589
    let
blanchet@40504
   590
      val cluster_of_var =
blanchet@40504
   591
        Meson_Clausify.cluster_of_zapped_var_name o fst o fst o dest_Var
blanchet@40504
   592
      fun in_right_cluster ((_, (cluster_no', _)), _) = cluster_no' = cluster_no
blanchet@40145
   593
      val cluster_substs =
blanchet@40145
   594
        substs
blanchet@40145
   595
        |> map_filter (fn (ax_no', (_, (_, tsubst))) =>
blanchet@40145
   596
                          if ax_no' = ax_no then
blanchet@40504
   597
                            tsubst |> map (apfst cluster_of_var)
blanchet@40504
   598
                                   |> filter (in_right_cluster o fst)
blanchet@40504
   599
                                   |> map (apfst snd)
blanchet@40504
   600
                                   |> SOME
blanchet@40504
   601
                          else
blanchet@40504
   602
                            NONE)
blanchet@40145
   603
      fun do_cluster_subst cluster_subst =
blanchet@40504
   604
        map (release_quantifier_tac thy) cluster_subst @ [rotate_tac 1]
blanchet@40145
   605
      val first_prem = find_index (fn (ax_no', _) => ax_no' = ax_no) substs
blanchet@40145
   606
    in
blanchet@40145
   607
      rotate_tac first_prem
blanchet@40145
   608
      THEN' (EVERY' (maps do_cluster_subst cluster_substs))
blanchet@40145
   609
      THEN' rotate_tac (~ first_prem - length cluster_substs)
blanchet@40501
   610
      THEN' release_clusters_tac thy ax_counts substs clusters
blanchet@40145
   611
    end
blanchet@40145
   612
blanchet@40507
   613
fun cluster_key ((ax_no, (cluster_no, index_no)), skolem) =
blanchet@40507
   614
  (ax_no, (cluster_no, (skolem, index_no)))
blanchet@40507
   615
fun cluster_ord p =
blanchet@40507
   616
  prod_ord int_ord (prod_ord int_ord (prod_ord bool_ord int_ord))
blanchet@40507
   617
           (pairself cluster_key p)
blanchet@40145
   618
blanchet@40145
   619
val tysubst_ord =
blanchet@40145
   620
  list_ord (prod_ord Term_Ord.fast_indexname_ord
blanchet@40145
   621
                     (prod_ord Term_Ord.sort_ord Term_Ord.typ_ord))
blanchet@40145
   622
blanchet@40145
   623
structure Int_Tysubst_Table =
blanchet@40145
   624
  Table(type key = int * (indexname * (sort * typ)) list
blanchet@40145
   625
        val ord = prod_ord int_ord tysubst_ord)
blanchet@40145
   626
blanchet@40145
   627
structure Int_Pair_Graph =
blanchet@40145
   628
  Graph(type key = int * int val ord = prod_ord int_ord int_ord)
blanchet@40145
   629
blanchet@43135
   630
fun shuffle_key (((axiom_no, (_, index_no)), _), _) = (axiom_no, index_no)
blanchet@40501
   631
fun shuffle_ord p = prod_ord int_ord int_ord (pairself shuffle_key p)
blanchet@40501
   632
blanchet@40145
   633
(* Attempts to derive the theorem "False" from a theorem of the form
blanchet@40145
   634
   "P1 ==> ... ==> Pn ==> False", where the "Pi"s are to be discharged using the
blanchet@40145
   635
   specified axioms. The axioms have leading "All" and "Ex" quantifiers, which
blanchet@40145
   636
   must be eliminated first. *)
blanchet@40145
   637
fun discharge_skolem_premises ctxt axioms prems_imp_false =
blanchet@40145
   638
  if prop_of prems_imp_false aconv @{prop False} then
blanchet@40145
   639
    prems_imp_false
blanchet@40145
   640
  else
blanchet@40145
   641
    let
wenzelm@43232
   642
      val thy = Proof_Context.theory_of ctxt
blanchet@40145
   643
      fun match_term p =
blanchet@40145
   644
        let
blanchet@40145
   645
          val (tyenv, tenv) =
blanchet@40145
   646
            Pattern.first_order_match thy p (Vartab.empty, Vartab.empty)
blanchet@40145
   647
          val tsubst =
blanchet@40145
   648
            tenv |> Vartab.dest
blanchet@42963
   649
                 |> filter (Meson_Clausify.is_zapped_var_name o fst o fst)
blanchet@40145
   650
                 |> sort (cluster_ord
blanchet@40145
   651
                          o pairself (Meson_Clausify.cluster_of_zapped_var_name
blanchet@40145
   652
                                      o fst o fst))
blanchet@40145
   653
                 |> map (Meson.term_pair_of
blanchet@40145
   654
                         #> pairself (Envir.subst_term_types tyenv))
blanchet@40145
   655
          val tysubst = tyenv |> Vartab.dest
blanchet@40145
   656
        in (tysubst, tsubst) end
blanchet@40145
   657
      fun subst_info_for_prem subgoal_no prem =
blanchet@40145
   658
        case prem of
blanchet@40145
   659
          _ $ (Const (@{const_name Meson.skolem}, _) $ (_ $ t $ num)) =>
blanchet@40145
   660
          let val ax_no = HOLogic.dest_nat num in
blanchet@40145
   661
            (ax_no, (subgoal_no,
blanchet@40145
   662
                     match_term (nth axioms ax_no |> the |> snd, t)))
blanchet@40145
   663
          end
blanchet@40145
   664
        | _ => raise TERM ("discharge_skolem_premises: Malformed premise",
blanchet@40145
   665
                           [prem])
blanchet@40145
   666
      fun cluster_of_var_name skolem s =
blanchet@42962
   667
        case try Meson_Clausify.cluster_of_zapped_var_name s of
blanchet@42962
   668
          NONE => NONE
blanchet@42962
   669
        | SOME ((ax_no, (cluster_no, _)), skolem') =>
blanchet@40145
   670
          if skolem' = skolem andalso cluster_no > 0 then
blanchet@40145
   671
            SOME (ax_no, cluster_no)
blanchet@40145
   672
          else
blanchet@40145
   673
            NONE
blanchet@40145
   674
      fun clusters_in_term skolem t =
blanchet@40145
   675
        Term.add_var_names t [] |> map_filter (cluster_of_var_name skolem o fst)
blanchet@40145
   676
      fun deps_for_term_subst (var, t) =
blanchet@40145
   677
        case clusters_in_term false var of
blanchet@40145
   678
          [] => NONE
blanchet@40145
   679
        | [(ax_no, cluster_no)] =>
blanchet@40145
   680
          SOME ((ax_no, cluster_no),
blanchet@40145
   681
                clusters_in_term true t
blanchet@40145
   682
                |> cluster_no > 1 ? cons (ax_no, cluster_no - 1))
blanchet@40145
   683
        | _ => raise TERM ("discharge_skolem_premises: Expected Var", [var])
blanchet@40145
   684
      val prems = Logic.strip_imp_prems (prop_of prems_imp_false)
blanchet@40145
   685
      val substs = prems |> map2 subst_info_for_prem (1 upto length prems)
blanchet@40145
   686
                         |> sort (int_ord o pairself fst)
blanchet@40145
   687
      val depss = maps (map_filter deps_for_term_subst o snd o snd o snd) substs
blanchet@40145
   688
      val clusters = maps (op ::) depss
blanchet@40145
   689
      val ordered_clusters =
blanchet@40145
   690
        Int_Pair_Graph.empty
blanchet@40145
   691
        |> fold Int_Pair_Graph.default_node (map (rpair ()) clusters)
blanchet@40145
   692
        |> fold Int_Pair_Graph.add_deps_acyclic depss
blanchet@40145
   693
        |> Int_Pair_Graph.topological_order
blanchet@40145
   694
        handle Int_Pair_Graph.CYCLES _ =>
blanchet@40399
   695
               error "Cannot replay Metis proof in Isabelle without \
blanchet@40399
   696
                     \\"Hilbert_Choice\"."
blanchet@40145
   697
      val ax_counts =
blanchet@40145
   698
        Int_Tysubst_Table.empty
blanchet@40145
   699
        |> fold (fn (ax_no, (_, (tysubst, _))) =>
blanchet@44103
   700
                    Int_Tysubst_Table.map_default ((ax_no, tysubst), 0)
blanchet@40145
   701
                                                  (Integer.add 1)) substs
blanchet@40145
   702
        |> Int_Tysubst_Table.dest
blanchet@43210
   703
      val needed_axiom_props =
blanchet@43210
   704
        0 upto length axioms - 1 ~~ axioms
blanchet@43210
   705
        |> map_filter (fn (_, NONE) => NONE
blanchet@43210
   706
                        | (ax_no, SOME (_, t)) =>
blanchet@43210
   707
                          if exists (fn ((ax_no', _), n) =>
blanchet@43210
   708
                                        ax_no' = ax_no andalso n > 0)
blanchet@43210
   709
                                    ax_counts then
blanchet@43210
   710
                            SOME t
blanchet@43210
   711
                          else
blanchet@43210
   712
                            NONE)
blanchet@43210
   713
      val outer_param_names =
blanchet@43210
   714
        [] |> fold Term.add_var_names needed_axiom_props
blanchet@43210
   715
           |> filter (Meson_Clausify.is_zapped_var_name o fst)
blanchet@43210
   716
           |> map (`(Meson_Clausify.cluster_of_zapped_var_name o fst))
blanchet@43210
   717
           |> filter (fn (((_, (cluster_no, _)), skolem), _) =>
blanchet@43210
   718
                         cluster_no = 0 andalso skolem)
blanchet@43210
   719
           |> sort shuffle_ord |> map (fst o snd)
blanchet@43134
   720
(* for debugging only:
blanchet@40145
   721
      fun string_for_subst_info (ax_no, (subgoal_no, (tysubst, tsubst))) =
blanchet@40145
   722
        "ax: " ^ string_of_int ax_no ^ "; asm: " ^ string_of_int subgoal_no ^
blanchet@40145
   723
        "; tysubst: " ^ PolyML.makestring tysubst ^ "; tsubst: {" ^
blanchet@40145
   724
        commas (map ((fn (s, t) => s ^ " |-> " ^ t)
blanchet@40145
   725
                     o pairself (Syntax.string_of_term ctxt)) tsubst) ^ "}"
blanchet@40507
   726
      val _ = tracing ("ORDERED CLUSTERS: " ^ PolyML.makestring ordered_clusters)
blanchet@40507
   727
      val _ = tracing ("AXIOM COUNTS: " ^ PolyML.makestring ax_counts)
blanchet@43210
   728
      val _ = tracing ("OUTER PARAMS: " ^ PolyML.makestring outer_param_names)
blanchet@40145
   729
      val _ = tracing ("SUBSTS (" ^ string_of_int (length substs) ^ "):\n" ^
blanchet@40145
   730
                       cat_lines (map string_for_subst_info substs))
blanchet@40145
   731
*)
blanchet@43135
   732
      fun cut_and_ex_tac axiom =
blanchet@43135
   733
        cut_rules_tac [axiom] 1
blanchet@43135
   734
        THEN TRY (REPEAT_ALL_NEW (etac @{thm exE}) 1)
blanchet@40145
   735
      fun rotation_for_subgoal i =
blanchet@40145
   736
        find_index (fn (_, (subgoal_no, _)) => subgoal_no = i) substs
blanchet@40145
   737
    in
blanchet@40145
   738
      Goal.prove ctxt [] [] @{prop False}
blanchet@43135
   739
          (K (DETERM (EVERY (map (cut_and_ex_tac o fst o the o nth axioms o fst
blanchet@43135
   740
                                  o fst) ax_counts)
blanchet@43135
   741
                      THEN rename_tac outer_param_names 1
blanchet@43135
   742
                      THEN copy_prems_tac (map snd ax_counts) [] 1)
blanchet@40501
   743
              THEN release_clusters_tac thy ax_counts substs ordered_clusters 1
blanchet@40145
   744
              THEN match_tac [prems_imp_false] 1
blanchet@40145
   745
              THEN ALLGOALS (fn i =>
blanchet@40145
   746
                       rtac @{thm Meson.skolem_COMBK_I} i
blanchet@40145
   747
                       THEN rotate_tac (rotation_for_subgoal i) i
blanchet@43213
   748
                       THEN PRIMITIVE (unify_first_prem_with_concl thy i)
blanchet@43135
   749
                       THEN assume_tac i
blanchet@43134
   750
                       THEN flexflex_tac)))
blanchet@40399
   751
      handle ERROR _ =>
blanchet@40399
   752
             error ("Cannot replay Metis proof in Isabelle:\n\
blanchet@40399
   753
                    \Error when discharging Skolem assumptions.")
blanchet@40145
   754
    end
blanchet@40145
   755
blanchet@39735
   756
end;