src/HOL/Tools/Metis/metis_translate.ML
author blanchet
Fri May 20 18:01:46 2011 +0200 (2011-05-20)
changeset 42895 c8d9bce88f89
parent 42894 ce269ee43800
child 43000 bd424c3dde46
permissions -rw-r--r--
name tuning
blanchet@39958
     1
(*  Title:      HOL/Tools/Metis/metis_translate.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@39497
     3
    Author:     Kong W. Susanto, Cambridge University Computer Laboratory
blanchet@39497
     4
    Author:     Lawrence C. Paulson, Cambridge University Computer Laboratory
blanchet@36393
     5
    Author:     Jasmin Blanchette, TU Muenchen
paulson@15347
     6
blanchet@39494
     7
Translation of HOL to FOL for Metis.
paulson@15347
     8
*)
paulson@15347
     9
blanchet@39494
    10
signature METIS_TRANSLATE =
wenzelm@24310
    11
sig
blanchet@37577
    12
  type name = string * string
blanchet@42650
    13
blanchet@37577
    14
  datatype type_literal =
blanchet@37643
    15
    TyLitVar of name * name |
blanchet@37643
    16
    TyLitFree of name * name
blanchet@42895
    17
  datatype arity_literal =
blanchet@37643
    18
    TConsLit of name * name * name list |
blanchet@37643
    19
    TVarLit of name * name
blanchet@38028
    20
  datatype arity_clause =
blanchet@42895
    21
    ArityClause of
blanchet@42895
    22
      {name: string,
blanchet@42895
    23
       prem_lits: arity_literal list,
blanchet@42895
    24
       concl_lits: arity_literal}
blanchet@38028
    25
  datatype class_rel_clause =
blanchet@38105
    26
    ClassRelClause of {name: string, subclass: name, superclass: name}
blanchet@37577
    27
  datatype combterm =
blanchet@42562
    28
    CombConst of name * typ * typ list (* Const and Free *) |
blanchet@42562
    29
    CombVar of name * typ |
blanchet@37577
    30
    CombApp of combterm * combterm
blanchet@37923
    31
  datatype fol_literal = FOLLiteral of bool * combterm
blanchet@37577
    32
blanchet@39497
    33
  datatype mode = FO | HO | FT
blanchet@40157
    34
  type metis_problem =
blanchet@39497
    35
    {axioms: (Metis_Thm.thm * thm) list,
blanchet@39497
    36
     tfrees: type_literal list,
blanchet@39886
    37
     old_skolems: (string * term) list}
blanchet@39497
    38
blanchet@42098
    39
  val metis_generated_var_prefix : string
blanchet@41138
    40
  val type_tag_name : string
blanchet@37995
    41
  val bound_var_prefix : string
wenzelm@24310
    42
  val schematic_var_prefix: string
wenzelm@24310
    43
  val fixed_var_prefix: string
wenzelm@24310
    44
  val tvar_prefix: string
wenzelm@24310
    45
  val tfree_prefix: string
wenzelm@24310
    46
  val const_prefix: string
blanchet@37643
    47
  val type_const_prefix: string
wenzelm@24310
    48
  val class_prefix: string
blanchet@39896
    49
  val new_skolem_const_prefix : string
blanchet@42570
    50
  val proxify_const : string -> (string * string) option
blanchet@37572
    51
  val invert_const: string -> string
blanchet@42570
    52
  val unproxify_const: string -> string
wenzelm@24310
    53
  val ascii_of: string -> string
blanchet@38748
    54
  val unascii_of: string -> string
blanchet@38748
    55
  val strip_prefix_and_unascii: string -> string -> string option
blanchet@37995
    56
  val make_bound_var : string -> string
wenzelm@24310
    57
  val make_schematic_var : string * int -> string
paulson@18868
    58
  val make_fixed_var : string -> string
paulson@18868
    59
  val make_schematic_type_var : string * int -> string
wenzelm@24310
    60
  val make_fixed_type_var : string -> string
blanchet@37498
    61
  val make_fixed_const : string -> string
blanchet@37498
    62
  val make_fixed_type_const : string -> string
paulson@18868
    63
  val make_type_class : string -> string
blanchet@37618
    64
  val num_type_args: theory -> string -> int
blanchet@40259
    65
  val new_skolem_var_name_from_const : string -> string
blanchet@36966
    66
  val type_literals_for_types : typ list -> type_literal list
blanchet@39499
    67
  val make_class_rel_clauses :
blanchet@39499
    68
    theory -> class list -> class list -> class_rel_clause list
blanchet@39499
    69
  val make_arity_clauses :
blanchet@39499
    70
    theory -> string list -> class list -> class list * arity_clause list
blanchet@42562
    71
  val combtyp_of : combterm -> typ
blanchet@37577
    72
  val strip_combterm_comb : combterm -> combterm * combterm list
blanchet@42727
    73
  val atyps_of : typ -> typ list
blanchet@37995
    74
  val combterm_from_term :
blanchet@40145
    75
    theory -> (string * typ) list -> term -> combterm * typ list
blanchet@39886
    76
  val reveal_old_skolem_terms : (string * term) list -> term -> term
blanchet@37577
    77
  val tfree_classes_of_terms : term list -> string list
blanchet@37577
    78
  val tvar_classes_of_terms : term list -> string list
blanchet@37577
    79
  val type_consts_of_terms : theory -> term list -> string list
blanchet@39497
    80
  val string_of_mode : mode -> string
blanchet@42894
    81
  val metis_helpers : (string * (bool * thm list)) list
blanchet@40157
    82
  val prepare_metis_problem :
blanchet@39886
    83
    mode -> Proof.context -> bool -> thm list -> thm list list
blanchet@40157
    84
    -> mode * metis_problem
wenzelm@24310
    85
end
paulson@15347
    86
blanchet@39494
    87
structure Metis_Translate : METIS_TRANSLATE =
paulson@15347
    88
struct
paulson@15347
    89
blanchet@42098
    90
val metis_generated_var_prefix = "_"
blanchet@42098
    91
blanchet@41139
    92
val type_tag_name = "ti"
blanchet@37509
    93
blanchet@37995
    94
val bound_var_prefix = "B_"
blanchet@37995
    95
val schematic_var_prefix = "V_"
blanchet@37995
    96
val fixed_var_prefix = "v_"
paulson@15347
    97
paulson@17230
    98
val tvar_prefix = "T_";
paulson@17230
    99
val tfree_prefix = "t_";
paulson@15347
   100
paulson@17230
   101
val const_prefix = "c_";
blanchet@37643
   102
val type_const_prefix = "tc_";
wenzelm@24310
   103
val class_prefix = "class_";
paulson@15347
   104
blanchet@39896
   105
val skolem_const_prefix = "Sledgehammer" ^ Long_Name.separator ^ "Sko"
blanchet@39896
   106
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@39896
   107
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@39886
   108
blanchet@36218
   109
fun union_all xss = fold (union (op =)) xss []
paulson@17775
   110
blanchet@42563
   111
val metis_proxies =
blanchet@42570
   112
  [("c_False", (@{const_name False}, ("fFalse", @{const_name Metis.fFalse}))),
blanchet@42570
   113
   ("c_True", (@{const_name True}, ("fTrue", @{const_name Metis.fTrue}))),
blanchet@42570
   114
   ("c_Not", (@{const_name Not}, ("fNot", @{const_name Metis.fNot}))),
blanchet@42570
   115
   ("c_conj", (@{const_name conj}, ("fconj", @{const_name Metis.fconj}))),
blanchet@42570
   116
   ("c_disj", (@{const_name disj}, ("fdisj", @{const_name Metis.fdisj}))),
blanchet@42570
   117
   ("c_implies", (@{const_name implies},
blanchet@42570
   118
                  ("fimplies", @{const_name Metis.fimplies}))),
blanchet@42570
   119
   ("equal", (@{const_name HOL.eq}, ("fequal", @{const_name Metis.fequal})))]
blanchet@42570
   120
blanchet@42570
   121
val proxify_const = AList.lookup (op =) metis_proxies #> Option.map snd
blanchet@42563
   122
blanchet@36493
   123
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@41139
   124
   table unless you know what you are doing. *)
paulson@15347
   125
val const_trans_table =
blanchet@42563
   126
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@42563
   127
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@42563
   128
   (@{const_name False}, "False"),
blanchet@42563
   129
   (@{const_name True}, "True"),
blanchet@42563
   130
   (@{const_name Not}, "Not"),
blanchet@42563
   131
   (@{const_name conj}, "conj"),
blanchet@42563
   132
   (@{const_name disj}, "disj"),
blanchet@42563
   133
   (@{const_name implies}, "implies"),
blanchet@42563
   134
   (@{const_name HOL.eq}, "equal"),
blanchet@42563
   135
   (@{const_name If}, "If"),
blanchet@42563
   136
   (@{const_name Set.member}, "member"),
blanchet@42563
   137
   (@{const_name Meson.COMBI}, "COMBI"),
blanchet@42563
   138
   (@{const_name Meson.COMBK}, "COMBK"),
blanchet@42563
   139
   (@{const_name Meson.COMBB}, "COMBB"),
blanchet@42563
   140
   (@{const_name Meson.COMBC}, "COMBC"),
blanchet@42570
   141
   (@{const_name Meson.COMBS}, "COMBS")]
blanchet@42563
   142
  |> Symtab.make
blanchet@42570
   143
  |> fold (Symtab.update o swap o snd o snd) metis_proxies
paulson@15347
   144
blanchet@42570
   145
(* Invert the table of translations between Isabelle and Metis. *)
blanchet@37572
   146
val const_trans_table_inv =
blanchet@42570
   147
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@42570
   148
val const_trans_table_unprox =
blanchet@42570
   149
  Symtab.empty
blanchet@42572
   150
  |> fold (fn (_, (isa, (_, metis))) => Symtab.update (metis, isa))
blanchet@42570
   151
          metis_proxies
blanchet@37572
   152
blanchet@37572
   153
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@42570
   154
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
paulson@15347
   155
paulson@15610
   156
(*Escaping of special characters.
paulson@15610
   157
  Alphanumeric characters are left unchanged.
paulson@15610
   158
  The character _ goes to __
paulson@15610
   159
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@38738
   160
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
paulson@24183
   161
val A_minus_space = Char.ord #"A" - Char.ord #" ";
paulson@15610
   162
paulson@24183
   163
fun stringN_of_int 0 _ = ""
wenzelm@41491
   164
  | stringN_of_int k n = stringN_of_int (k-1) (n div 10) ^ string_of_int (n mod 10);
paulson@15610
   165
paulson@15347
   166
fun ascii_of_c c =
paulson@15610
   167
  if Char.isAlphaNum c then String.str c
paulson@15610
   168
  else if c = #"_" then "__"
wenzelm@24310
   169
  else if #" " <= c andalso c <= #"/"
paulson@15610
   170
       then "_" ^ String.str (Char.chr (Char.ord c + A_minus_space))
blanchet@38738
   171
  else ("_" ^ stringN_of_int 3 (Char.ord c))  (*fixed width, in case more digits follow*)
paulson@15347
   172
paulson@15610
   173
val ascii_of = String.translate ascii_of_c;
paulson@15610
   174
paulson@24183
   175
(** Remove ASCII armouring from names in proof files **)
paulson@24183
   176
paulson@24183
   177
(*We don't raise error exceptions because this code can run inside the watcher.
paulson@24183
   178
  Also, the errors are "impossible" (hah!)*)
blanchet@38748
   179
fun unascii_aux rcs [] = String.implode(rev rcs)
blanchet@38748
   180
  | unascii_aux rcs [#"_"] = unascii_aux (#"_"::rcs) []  (*ERROR*)
paulson@24183
   181
      (*Three types of _ escapes: __, _A to _P, _nnn*)
blanchet@38748
   182
  | unascii_aux rcs (#"_" :: #"_" :: cs) = unascii_aux (#"_"::rcs) cs
blanchet@38748
   183
  | unascii_aux rcs (#"_" :: c :: cs) =
paulson@24183
   184
      if #"A" <= c andalso c<= #"P"  (*translation of #" " to #"/"*)
blanchet@38748
   185
      then unascii_aux (Char.chr(Char.ord c - A_minus_space) :: rcs) cs
wenzelm@24310
   186
      else
paulson@24183
   187
        let val digits = List.take (c::cs, 3) handle Subscript => []
wenzelm@24310
   188
        in
paulson@24183
   189
            case Int.fromString (String.implode digits) of
blanchet@38748
   190
                NONE => unascii_aux (c:: #"_"::rcs) cs  (*ERROR*)
blanchet@38748
   191
              | SOME n => unascii_aux (Char.chr n :: rcs) (List.drop (cs, 2))
paulson@24183
   192
        end
blanchet@38748
   193
  | unascii_aux rcs (c::cs) = unascii_aux (c::rcs) cs
blanchet@38748
   194
val unascii_of = unascii_aux [] o String.explode
paulson@15347
   195
blanchet@37572
   196
(* If string s has the prefix s1, return the result of deleting it,
blanchet@37572
   197
   un-ASCII'd. *)
blanchet@38748
   198
fun strip_prefix_and_unascii s1 s =
blanchet@37572
   199
  if String.isPrefix s1 s then
blanchet@38748
   200
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@37572
   201
  else
blanchet@37572
   202
    NONE
blanchet@37572
   203
paulson@16925
   204
(*Remove the initial ' character from a type variable, if it is present*)
paulson@16925
   205
fun trim_type_var s =
paulson@16925
   206
  if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
blanchet@42650
   207
  else raise Fail ("trim_type: Malformed type variable encountered: " ^ s)
paulson@16925
   208
paulson@16903
   209
fun ascii_of_indexname (v,0) = ascii_of v
wenzelm@41491
   210
  | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ string_of_int i;
paulson@15347
   211
blanchet@37995
   212
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@37995
   213
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@37995
   214
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
paulson@15347
   215
wenzelm@24310
   216
fun make_schematic_type_var (x,i) =
paulson@16925
   217
      tvar_prefix ^ (ascii_of_indexname (trim_type_var x,i));
paulson@16925
   218
fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x));
paulson@15347
   219
blanchet@37498
   220
fun lookup_const c =
blanchet@37498
   221
  case Symtab.lookup const_trans_table c of
blanchet@37498
   222
    SOME c' => c'
blanchet@37498
   223
  | NONE => ascii_of c
paulson@23075
   224
haftmann@38864
   225
(* HOL.eq MUST BE "equal" because it's built into ATPs. *)
haftmann@38864
   226
fun make_fixed_const @{const_name HOL.eq} = "equal"
blanchet@37498
   227
  | make_fixed_const c = const_prefix ^ lookup_const c
paulson@18411
   228
blanchet@37643
   229
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
quigley@17150
   230
wenzelm@17261
   231
fun make_type_class clas = class_prefix ^ ascii_of clas;
quigley@17150
   232
blanchet@37618
   233
(* The number of type arguments of a constant, zero if it's monomorphic. For
blanchet@37618
   234
   (instances of) Skolem pseudoconstants, this information is encoded in the
blanchet@37618
   235
   constant name. *)
blanchet@37618
   236
fun num_type_args thy s =
blanchet@39896
   237
  if String.isPrefix skolem_const_prefix s then
blanchet@39499
   238
    s |> space_explode Long_Name.separator |> List.last |> Int.fromString |> the
blanchet@37618
   239
  else
blanchet@37618
   240
    (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
quigley@17150
   241
blanchet@40259
   242
fun new_skolem_var_name_from_const s =
blanchet@40145
   243
  let val ss = s |> space_explode Long_Name.separator in
blanchet@40259
   244
    nth ss (length ss - 2)
blanchet@40145
   245
  end
blanchet@39886
   246
blanchet@39886
   247
blanchet@37624
   248
(**** Definitions and functions for FOL clauses for TPTP format output ****)
blanchet@36169
   249
blanchet@37624
   250
type name = string * string
paulson@15347
   251
paulson@15347
   252
(**** Isabelle FOL clauses ****)
paulson@15347
   253
blanchet@36556
   254
(* The first component is the type class; the second is a TVar or TFree. *)
blanchet@36556
   255
datatype type_literal =
blanchet@37643
   256
  TyLitVar of name * name |
blanchet@37643
   257
  TyLitFree of name * name
paulson@15347
   258
wenzelm@24310
   259
(*Make literals for sorted type variables*)
paulson@24940
   260
fun sorts_on_typs_aux (_, [])   = []
paulson@24940
   261
  | sorts_on_typs_aux ((x,i),  s::ss) =
paulson@24940
   262
      let val sorts = sorts_on_typs_aux ((x,i), ss)
paulson@22643
   263
      in
blanchet@42893
   264
          if s = the_single @{sort HOL.type} then sorts
blanchet@37643
   265
          else if i = ~1 then TyLitFree (`make_type_class s, `make_fixed_type_var x) :: sorts
blanchet@37643
   266
          else TyLitVar (`make_type_class s, (make_schematic_type_var (x,i), x)) :: sorts
paulson@22643
   267
      end;
quigley@17150
   268
paulson@24940
   269
fun sorts_on_typs (TFree (a,s)) = sorts_on_typs_aux ((a,~1),s)
paulson@24940
   270
  | sorts_on_typs (TVar (v,s))  = sorts_on_typs_aux (v,s);
paulson@24940
   271
paulson@24937
   272
(*Given a list of sorted type variables, return a list of type literals.*)
blanchet@36966
   273
fun type_literals_for_types Ts =
blanchet@36966
   274
  fold (union (op =)) (map sorts_on_typs Ts) []
mengj@20015
   275
mengj@20015
   276
(** make axiom and conjecture clauses. **)
mengj@20015
   277
paulson@15347
   278
(**** Isabelle arities ****)
paulson@15347
   279
blanchet@42895
   280
datatype arity_literal =
blanchet@37643
   281
  TConsLit of name * name * name list |
blanchet@37643
   282
  TVarLit of name * name
wenzelm@24310
   283
blanchet@35865
   284
datatype arity_clause =
blanchet@42895
   285
  ArityClause of
blanchet@42895
   286
    {name: string,
blanchet@42895
   287
     prem_lits: arity_literal list,
blanchet@42895
   288
     concl_lits: arity_literal}
paulson@15347
   289
paulson@18798
   290
fun gen_TVars 0 = []
wenzelm@41491
   291
  | gen_TVars n = ("T_" ^ string_of_int n) :: gen_TVars (n-1);
paulson@15347
   292
paulson@18411
   293
fun pack_sort(_,[])  = []
blanchet@37643
   294
  | pack_sort(tvar, "HOL.type"::srt) = pack_sort (tvar, srt)   (*IGNORE sort "type"*)
blanchet@37643
   295
  | pack_sort(tvar, cls::srt) =
blanchet@42895
   296
    (`make_type_class cls, `I tvar) :: pack_sort (tvar, srt)
wenzelm@24310
   297
paulson@18411
   298
(*Arity of type constructor tcon :: (arg1,...,argN)res*)
blanchet@38105
   299
fun make_axiom_arity_clause (tcons, name, (cls,args)) =
blanchet@37643
   300
  let
blanchet@37643
   301
    val tvars = gen_TVars (length args)
blanchet@37643
   302
    val tvars_srts = ListPair.zip (tvars, args)
blanchet@37643
   303
  in
blanchet@39318
   304
    ArityClause {name = name,
blanchet@42895
   305
                 prem_lits = map TVarLit (union_all (map pack_sort tvars_srts)),
blanchet@42895
   306
                 concl_lits = TConsLit (`make_type_class cls,
blanchet@42895
   307
                                        `make_fixed_type_const tcons,
blanchet@42895
   308
                                        tvars ~~ tvars)}
blanchet@37643
   309
  end
paulson@15347
   310
paulson@15347
   311
paulson@15347
   312
(**** Isabelle class relations ****)
paulson@15347
   313
blanchet@37925
   314
datatype class_rel_clause =
blanchet@38105
   315
  ClassRelClause of {name: string, subclass: name, superclass: name}
wenzelm@24310
   316
paulson@21290
   317
(*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
blanchet@37498
   318
fun class_pairs _ [] _ = []
paulson@21432
   319
  | class_pairs thy subs supers =
blanchet@36218
   320
      let
blanchet@36218
   321
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@36218
   322
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@36218
   323
        fun add_supers sub = fold (add_super sub) supers
blanchet@36218
   324
      in fold add_supers subs [] end
paulson@15347
   325
blanchet@37925
   326
fun make_class_rel_clause (sub,super) =
blanchet@38105
   327
  ClassRelClause {name = sub ^ "_" ^ super,
blanchet@37643
   328
                  subclass = `make_type_class sub,
blanchet@38105
   329
                  superclass = `make_type_class super}
paulson@15347
   330
blanchet@37925
   331
fun make_class_rel_clauses thy subs supers =
blanchet@37925
   332
  map make_class_rel_clause (class_pairs thy subs supers);
paulson@18868
   333
paulson@18868
   334
paulson@18868
   335
(** Isabelle arities **)
paulson@17845
   336
blanchet@37498
   337
fun arity_clause _ _ (_, []) = []
blanchet@37498
   338
  | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
blanchet@37498
   339
      arity_clause seen n (tcons,ars)
blanchet@37498
   340
  | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
haftmann@36692
   341
      if member (op =) seen class then (*multiple arities for the same tycon, class pair*)
wenzelm@41491
   342
          make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class ^ "_" ^ string_of_int n, ar) ::
blanchet@37498
   343
          arity_clause seen (n+1) (tcons,ars)
paulson@21373
   344
      else
blanchet@37572
   345
          make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class, ar) ::
blanchet@37498
   346
          arity_clause (class::seen) n (tcons,ars)
paulson@17845
   347
blanchet@37498
   348
fun multi_arity_clause [] = []
blanchet@37498
   349
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@37498
   350
      arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
paulson@17845
   351
paulson@22643
   352
(*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy
paulson@22643
   353
  provided its arguments have the corresponding sorts.*)
paulson@21373
   354
fun type_class_pairs thy tycons classes =
paulson@21373
   355
  let val alg = Sign.classes_of thy
blanchet@36218
   356
      fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@36218
   357
      fun add_class tycon class =
blanchet@36218
   358
        cons (class, domain_sorts tycon class)
blanchet@36218
   359
        handle Sorts.CLASS_ERROR _ => I
blanchet@36218
   360
      fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
paulson@21373
   361
  in  map try_classes tycons  end;
paulson@21373
   362
paulson@22643
   363
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@37498
   364
fun iter_type_class_pairs _ _ [] = ([], [])
paulson@22643
   365
  | iter_type_class_pairs thy tycons classes =
paulson@22643
   366
      let val cpairs = type_class_pairs thy tycons classes
haftmann@33040
   367
          val newclasses = union_all (union_all (union_all (map (map #2 o #2) cpairs)))
haftmann@33040
   368
            |> subtract (op =) classes |> subtract (op =) HOLogic.typeS
wenzelm@24310
   369
          val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
haftmann@33042
   370
      in (union (op =) classes' classes, union (op =) cpairs' cpairs) end;
wenzelm@24310
   371
blanchet@37498
   372
fun make_arity_clauses thy tycons classes =
wenzelm@24310
   373
  let val (classes', cpairs) = iter_type_class_pairs thy tycons classes
blanchet@37498
   374
  in  (classes', multi_arity_clause cpairs)  end;
paulson@18863
   375
blanchet@37577
   376
datatype combterm =
blanchet@42562
   377
  CombConst of name * typ * typ list (* Const and Free *) |
blanchet@42562
   378
  CombVar of name * typ |
blanchet@37577
   379
  CombApp of combterm * combterm
blanchet@37577
   380
blanchet@37923
   381
datatype fol_literal = FOLLiteral of bool * combterm
blanchet@37577
   382
blanchet@37577
   383
(*********************************************************************)
blanchet@37577
   384
(* convert a clause with type Term.term to a clause with type clause *)
blanchet@37577
   385
(*********************************************************************)
blanchet@37577
   386
blanchet@42562
   387
fun combtyp_of (CombConst (_, T, _)) = T
blanchet@42562
   388
  | combtyp_of (CombVar (_, T)) = T
blanchet@42562
   389
  | combtyp_of (CombApp (t1, _)) = snd (dest_funT (combtyp_of t1))
blanchet@37577
   390
blanchet@37577
   391
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@37577
   392
fun strip_combterm_comb u =
blanchet@37577
   393
    let fun stripc (CombApp(t,u), ts) = stripc (t, u::ts)
blanchet@37577
   394
        |   stripc  x =  x
blanchet@37577
   395
    in stripc(u,[]) end
blanchet@37577
   396
blanchet@42562
   397
fun atyps_of T = fold_atyps (insert (op =)) T []
blanchet@37577
   398
blanchet@40145
   399
fun new_skolem_const_name s num_T_args =
blanchet@40145
   400
  [new_skolem_const_prefix, s, string_of_int num_T_args]
blanchet@39886
   401
  |> space_implode Long_Name.separator
blanchet@39886
   402
blanchet@40145
   403
(* Converts a term (with combinators) into a combterm. Also accumulates sort
blanchet@37995
   404
   infomation. *)
blanchet@40145
   405
fun combterm_from_term thy bs (P $ Q) =
blanchet@42570
   406
    let
blanchet@42570
   407
      val (P', P_atomics_Ts) = combterm_from_term thy bs P
blanchet@42570
   408
      val (Q', Q_atomics_Ts) = combterm_from_term thy bs Q
blanchet@42570
   409
    in (CombApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
blanchet@40145
   410
  | combterm_from_term thy _ (Const (c, T)) =
blanchet@42570
   411
    let
blanchet@42570
   412
      val tvar_list =
blanchet@42570
   413
        (if String.isPrefix old_skolem_const_prefix c then
blanchet@42570
   414
           [] |> Term.add_tvarsT T |> map TVar
blanchet@42570
   415
         else
blanchet@42570
   416
           (c, T) |> Sign.const_typargs thy)
blanchet@42570
   417
      val c' = CombConst (`make_fixed_const c, T, tvar_list)
blanchet@42570
   418
    in (c', atyps_of T) end
blanchet@40145
   419
  | combterm_from_term _ _ (Free (v, T)) =
blanchet@42570
   420
    (CombConst (`make_fixed_var v, T, []), atyps_of T)
blanchet@40145
   421
  | combterm_from_term _ _ (Var (v as (s, _), T)) =
blanchet@42570
   422
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@42570
   423
       let
blanchet@42570
   424
         val Ts = T |> strip_type |> swap |> op ::
blanchet@42570
   425
         val s' = new_skolem_const_name s (length Ts)
blanchet@42570
   426
       in CombConst (`make_fixed_const s', T, Ts) end
blanchet@42570
   427
     else
blanchet@42570
   428
       CombVar ((make_schematic_var v, s), T), atyps_of T)
blanchet@40145
   429
  | combterm_from_term _ bs (Bound j) =
blanchet@42570
   430
    nth bs j
blanchet@42570
   431
    |> (fn (s, T) => (CombConst (`make_bound_var s, T, []), atyps_of T))
blanchet@40145
   432
  | combterm_from_term _ _ (Abs _) = raise Fail "HOL clause: Abs"
blanchet@37577
   433
blanchet@40145
   434
fun predicate_of thy ((@{const Not} $ P), pos) = predicate_of thy (P, not pos)
blanchet@40145
   435
  | predicate_of thy (t, pos) =
blanchet@40145
   436
    (combterm_from_term thy [] (Envir.eta_contract t), pos)
blanchet@37577
   437
blanchet@40145
   438
fun literals_of_term1 args thy (@{const Trueprop} $ P) =
blanchet@40145
   439
    literals_of_term1 args thy P
blanchet@40145
   440
  | literals_of_term1 args thy (@{const HOL.disj} $ P $ Q) =
blanchet@40145
   441
    literals_of_term1 (literals_of_term1 args thy P) thy Q
blanchet@40145
   442
  | literals_of_term1 (lits, ts) thy P =
blanchet@40145
   443
    let val ((pred, ts'), pol) = predicate_of thy (P, true) in
blanchet@37923
   444
      (FOLLiteral (pol, pred) :: lits, union (op =) ts ts')
blanchet@37577
   445
    end
blanchet@37577
   446
val literals_of_term = literals_of_term1 ([], [])
blanchet@37577
   447
blanchet@39896
   448
fun old_skolem_const_name i j num_T_args =
blanchet@39896
   449
  old_skolem_const_prefix ^ Long_Name.separator ^
wenzelm@41491
   450
  (space_implode Long_Name.separator (map string_of_int [i, j, num_T_args]))
blanchet@37577
   451
blanchet@39886
   452
fun conceal_old_skolem_terms i old_skolems t =
blanchet@39953
   453
  if exists_Const (curry (op =) @{const_name Meson.skolem} o fst) t then
blanchet@37577
   454
    let
blanchet@39886
   455
      fun aux old_skolems
blanchet@39953
   456
             (t as (Const (@{const_name Meson.skolem}, Type (_, [_, T])) $ _)) =
blanchet@37577
   457
          let
blanchet@39886
   458
            val (old_skolems, s) =
blanchet@37577
   459
              if i = ~1 then
blanchet@39886
   460
                (old_skolems, @{const_name undefined})
blanchet@39886
   461
              else case AList.find (op aconv) old_skolems t of
blanchet@39886
   462
                s :: _ => (old_skolems, s)
blanchet@37577
   463
              | [] =>
blanchet@37577
   464
                let
blanchet@39896
   465
                  val s = old_skolem_const_name i (length old_skolems)
blanchet@39896
   466
                                                (length (Term.add_tvarsT T []))
blanchet@39886
   467
                in ((s, t) :: old_skolems, s) end
blanchet@39886
   468
          in (old_skolems, Const (s, T)) end
blanchet@39886
   469
        | aux old_skolems (t1 $ t2) =
blanchet@37577
   470
          let
blanchet@39886
   471
            val (old_skolems, t1) = aux old_skolems t1
blanchet@39886
   472
            val (old_skolems, t2) = aux old_skolems t2
blanchet@39886
   473
          in (old_skolems, t1 $ t2) end
blanchet@39886
   474
        | aux old_skolems (Abs (s, T, t')) =
blanchet@39886
   475
          let val (old_skolems, t') = aux old_skolems t' in
blanchet@39886
   476
            (old_skolems, Abs (s, T, t'))
blanchet@37577
   477
          end
blanchet@39886
   478
        | aux old_skolems t = (old_skolems, t)
blanchet@39886
   479
    in aux old_skolems t end
blanchet@37577
   480
  else
blanchet@39886
   481
    (old_skolems, t)
blanchet@37577
   482
blanchet@39886
   483
fun reveal_old_skolem_terms old_skolems =
blanchet@37632
   484
  map_aterms (fn t as Const (s, _) =>
blanchet@39896
   485
                 if String.isPrefix old_skolem_const_prefix s then
blanchet@39886
   486
                   AList.lookup (op =) old_skolems s |> the
blanchet@37632
   487
                   |> map_types Type_Infer.paramify_vars
blanchet@37632
   488
                 else
blanchet@37632
   489
                   t
blanchet@37632
   490
               | t => t)
blanchet@37632
   491
blanchet@37577
   492
blanchet@37577
   493
(***************************************************************)
blanchet@37577
   494
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@37577
   495
(***************************************************************)
blanchet@37577
   496
blanchet@37577
   497
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@37577
   498
blanchet@37577
   499
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@37577
   500
blanchet@37577
   501
(*Remove this trivial type class*)
blanchet@37577
   502
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset;
blanchet@37577
   503
blanchet@37577
   504
fun tfree_classes_of_terms ts =
blanchet@37577
   505
  let val sorts_list = map (map #2 o OldTerm.term_tfrees) ts
blanchet@37577
   506
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
blanchet@37577
   507
blanchet@37577
   508
fun tvar_classes_of_terms ts =
blanchet@37577
   509
  let val sorts_list = map (map #2 o OldTerm.term_tvars) ts
blanchet@37577
   510
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
blanchet@37577
   511
blanchet@37577
   512
(*fold type constructors*)
blanchet@37577
   513
fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
blanchet@37577
   514
  | fold_type_consts _ _ x = x;
blanchet@37577
   515
blanchet@37577
   516
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
blanchet@37577
   517
fun add_type_consts_in_term thy =
blanchet@37577
   518
  let
blanchet@38748
   519
    fun aux (Const x) =
blanchet@38748
   520
        fold (fold_type_consts set_insert) (Sign.const_typargs thy x)
blanchet@37577
   521
      | aux (Abs (_, _, u)) = aux u
blanchet@39953
   522
      | aux (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@37577
   523
      | aux (t $ u) = aux t #> aux u
blanchet@37577
   524
      | aux _ = I
blanchet@37577
   525
  in aux end
blanchet@37577
   526
blanchet@37577
   527
fun type_consts_of_terms thy ts =
blanchet@37577
   528
  Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
blanchet@37577
   529
blanchet@39497
   530
(* ------------------------------------------------------------------------- *)
blanchet@39497
   531
(* HOL to FOL  (Isabelle to Metis)                                           *)
blanchet@39497
   532
(* ------------------------------------------------------------------------- *)
blanchet@39497
   533
blanchet@39497
   534
datatype mode = FO | HO | FT  (* first-order, higher-order, fully-typed *)
blanchet@39497
   535
blanchet@39497
   536
fun string_of_mode FO = "FO"
blanchet@39497
   537
  | string_of_mode HO = "HO"
blanchet@39497
   538
  | string_of_mode FT = "FT"
blanchet@39497
   539
blanchet@42745
   540
fun fn_isa_to_met_sublevel "equal" = "c_fequal"
blanchet@41139
   541
  | fn_isa_to_met_sublevel "c_False" = "c_fFalse"
blanchet@41139
   542
  | fn_isa_to_met_sublevel "c_True" = "c_fTrue"
blanchet@41139
   543
  | fn_isa_to_met_sublevel "c_Not" = "c_fNot"
blanchet@41139
   544
  | fn_isa_to_met_sublevel "c_conj" = "c_fconj"
blanchet@41139
   545
  | fn_isa_to_met_sublevel "c_disj" = "c_fdisj"
blanchet@41139
   546
  | fn_isa_to_met_sublevel "c_implies" = "c_fimplies"
blanchet@39497
   547
  | fn_isa_to_met_sublevel x = x
blanchet@42758
   548
blanchet@39497
   549
fun fn_isa_to_met_toplevel "equal" = "="
blanchet@39497
   550
  | fn_isa_to_met_toplevel x = x
blanchet@39497
   551
blanchet@39497
   552
fun metis_lit b c args = (b, (c, args));
blanchet@39497
   553
blanchet@42562
   554
fun metis_term_from_typ (Type (s, Ts)) =
blanchet@42562
   555
    Metis_Term.Fn (make_fixed_type_const s, map metis_term_from_typ Ts)
blanchet@42562
   556
  | metis_term_from_typ (TFree (s, _)) =
blanchet@42562
   557
    Metis_Term.Fn (make_fixed_type_var s, [])
blanchet@42562
   558
  | metis_term_from_typ (TVar (x, _)) =
blanchet@42562
   559
    Metis_Term.Var (make_schematic_type_var x)
blanchet@39497
   560
blanchet@39497
   561
(*These two functions insert type literals before the real literals. That is the
blanchet@39497
   562
  opposite order from TPTP linkup, but maybe OK.*)
blanchet@39497
   563
blanchet@39497
   564
fun hol_term_to_fol_FO tm =
blanchet@39497
   565
  case strip_combterm_comb tm of
blanchet@42562
   566
      (CombConst ((c, _), _, Ts), tms) =>
blanchet@42562
   567
        let val tyargs = map metis_term_from_typ Ts
blanchet@42562
   568
            val args = map hol_term_to_fol_FO tms
blanchet@39497
   569
        in Metis_Term.Fn (c, tyargs @ args) end
blanchet@39497
   570
    | (CombVar ((v, _), _), []) => Metis_Term.Var v
blanchet@39497
   571
    | _ => raise Fail "non-first-order combterm"
blanchet@39497
   572
blanchet@42562
   573
fun hol_term_to_fol_HO (CombConst ((a, _), _, Ts)) =
blanchet@42562
   574
      Metis_Term.Fn (fn_isa_to_met_sublevel a, map metis_term_from_typ Ts)
blanchet@39497
   575
  | hol_term_to_fol_HO (CombVar ((s, _), _)) = Metis_Term.Var s
blanchet@39497
   576
  | hol_term_to_fol_HO (CombApp (tm1, tm2)) =
blanchet@39497
   577
       Metis_Term.Fn (".", map hol_term_to_fol_HO [tm1, tm2]);
blanchet@39497
   578
blanchet@39497
   579
(*The fully-typed translation, to avoid type errors*)
blanchet@42562
   580
fun tag_with_type tm T =
blanchet@42562
   581
  Metis_Term.Fn (type_tag_name, [tm, metis_term_from_typ T])
blanchet@39497
   582
blanchet@41138
   583
fun hol_term_to_fol_FT (CombVar ((s, _), ty)) =
blanchet@41138
   584
    tag_with_type (Metis_Term.Var s) ty
blanchet@41138
   585
  | hol_term_to_fol_FT (CombConst ((a, _), ty, _)) =
blanchet@41138
   586
    tag_with_type (Metis_Term.Fn (fn_isa_to_met_sublevel a, [])) ty
blanchet@41138
   587
  | hol_term_to_fol_FT (tm as CombApp (tm1,tm2)) =
blanchet@41138
   588
    tag_with_type (Metis_Term.Fn (".", map hol_term_to_fol_FT [tm1, tm2]))
blanchet@41138
   589
                  (combtyp_of tm)
blanchet@39497
   590
blanchet@39497
   591
fun hol_literal_to_fol FO (FOLLiteral (pos, tm)) =
blanchet@42562
   592
      let
blanchet@42562
   593
        val (CombConst((p, _), _, Ts), tms) = strip_combterm_comb tm
blanchet@42562
   594
        val tylits = if p = "equal" then [] else map metis_term_from_typ Ts
blanchet@42562
   595
        val lits = map hol_term_to_fol_FO tms
blanchet@39497
   596
      in metis_lit pos (fn_isa_to_met_toplevel p) (tylits @ lits) end
blanchet@39497
   597
  | hol_literal_to_fol HO (FOLLiteral (pos, tm)) =
blanchet@39497
   598
     (case strip_combterm_comb tm of
blanchet@39497
   599
          (CombConst(("equal", _), _, _), tms) =>
blanchet@39497
   600
            metis_lit pos "=" (map hol_term_to_fol_HO tms)
blanchet@39497
   601
        | _ => metis_lit pos "{}" [hol_term_to_fol_HO tm])   (*hBOOL*)
blanchet@39497
   602
  | hol_literal_to_fol FT (FOLLiteral (pos, tm)) =
blanchet@39497
   603
     (case strip_combterm_comb tm of
blanchet@39497
   604
          (CombConst(("equal", _), _, _), tms) =>
blanchet@39497
   605
            metis_lit pos "=" (map hol_term_to_fol_FT tms)
blanchet@39497
   606
        | _ => metis_lit pos "{}" [hol_term_to_fol_FT tm])   (*hBOOL*);
blanchet@39497
   607
blanchet@40145
   608
fun literals_of_hol_term thy mode t =
blanchet@40145
   609
  let val (lits, types_sorts) = literals_of_term thy t in
blanchet@40145
   610
    (map (hol_literal_to_fol mode) lits, types_sorts)
blanchet@40145
   611
  end
blanchet@39497
   612
blanchet@39497
   613
(*Sign should be "true" for conjecture type constraints, "false" for type lits in clauses.*)
blanchet@39497
   614
fun metis_of_type_literals pos (TyLitVar ((s, _), (s', _))) =
blanchet@39497
   615
    metis_lit pos s [Metis_Term.Var s']
blanchet@39497
   616
  | metis_of_type_literals pos (TyLitFree ((s, _), (s', _))) =
blanchet@39497
   617
    metis_lit pos s [Metis_Term.Fn (s',[])]
blanchet@39497
   618
blanchet@42352
   619
fun has_default_sort _ (TVar _) = false
blanchet@42352
   620
  | has_default_sort ctxt (TFree (x, s)) =
blanchet@42352
   621
    (s = the_default [] (Variable.def_sort ctxt (x, ~1)));
blanchet@39497
   622
blanchet@39497
   623
fun metis_of_tfree tf =
blanchet@39497
   624
  Metis_Thm.axiom (Metis_LiteralSet.singleton (metis_of_type_literals true tf));
blanchet@39497
   625
blanchet@40145
   626
fun hol_thm_to_fol is_conjecture ctxt type_lits mode j old_skolems th =
blanchet@39497
   627
  let
wenzelm@42361
   628
    val thy = Proof_Context.theory_of ctxt
blanchet@39886
   629
    val (old_skolems, (mlits, types_sorts)) =
blanchet@39888
   630
     th |> prop_of |> Logic.strip_imp_concl
blanchet@39888
   631
        |> conceal_old_skolem_terms j old_skolems
blanchet@40145
   632
        ||> (HOLogic.dest_Trueprop #> literals_of_hol_term thy mode)
blanchet@39497
   633
  in
blanchet@39497
   634
    if is_conjecture then
blanchet@39497
   635
      (Metis_Thm.axiom (Metis_LiteralSet.fromList mlits),
blanchet@39886
   636
       type_literals_for_types types_sorts, old_skolems)
blanchet@39497
   637
    else
blanchet@39497
   638
      let
blanchet@42352
   639
        val tylits = types_sorts |> filter_out (has_default_sort ctxt)
blanchet@42352
   640
                                 |> type_literals_for_types
blanchet@39497
   641
        val mtylits =
blanchet@39497
   642
          if type_lits then map (metis_of_type_literals false) tylits else []
blanchet@39497
   643
      in
blanchet@39497
   644
        (Metis_Thm.axiom (Metis_LiteralSet.fromList(mtylits @ mlits)), [],
blanchet@39886
   645
         old_skolems)
blanchet@39497
   646
      end
blanchet@39497
   647
  end;
blanchet@39497
   648
blanchet@42894
   649
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@41140
   650
val metis_helpers =
blanchet@42894
   651
  [("COMBI", (false, @{thms Meson.COMBI_def})),
blanchet@42894
   652
   ("COMBK", (false, @{thms Meson.COMBK_def})),
blanchet@42894
   653
   ("COMBB", (false, @{thms Meson.COMBB_def})),
blanchet@42894
   654
   ("COMBC", (false, @{thms Meson.COMBC_def})),
blanchet@42894
   655
   ("COMBS", (false, @{thms Meson.COMBS_def})),
blanchet@42561
   656
   ("fequal",
blanchet@42758
   657
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
blanchet@42758
   658
       However, this is done so for backward compatibility: Including the
blanchet@42758
   659
       equality helpers by default in Metis breaks a few existing proofs. *)
blanchet@42894
   660
    (true, @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@42894
   661
                  fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]})),
blanchet@42894
   662
   ("fFalse", (true, @{thms True_or_False})),
blanchet@42894
   663
   ("fFalse", (false, [@{lemma "~ fFalse" by (unfold fFalse_def) fast}])),
blanchet@42894
   664
   ("fTrue", (true, @{thms True_or_False})),
blanchet@42894
   665
   ("fTrue", (false, [@{lemma "fTrue" by (unfold fTrue_def) fast}])),
blanchet@42561
   666
   ("fNot",
blanchet@42894
   667
    (false, @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@42894
   668
                   fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]})),
blanchet@42561
   669
   ("fconj",
blanchet@42894
   670
    (false,
blanchet@42893
   671
     @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@42893
   672
         by (unfold fconj_def) fast+})),
blanchet@42561
   673
   ("fdisj",
blanchet@42894
   674
    (false,
blanchet@42893
   675
     @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@42893
   676
         by (unfold fdisj_def) fast+})),
blanchet@42561
   677
   ("fimplies",
blanchet@42894
   678
    (false, @{lemma "P | fimplies P Q" "~ Q | fimplies P Q"
blanchet@42894
   679
                    "~ fimplies P Q | ~ P | Q"
blanchet@42894
   680
                by (unfold fimplies_def) fast+})),
blanchet@42894
   681
   ("If", (true, @{thms if_True if_False True_or_False}))]
blanchet@39497
   682
blanchet@39497
   683
(* ------------------------------------------------------------------------- *)
blanchet@39497
   684
(* Logic maps manage the interface between HOL and first-order logic.        *)
blanchet@39497
   685
(* ------------------------------------------------------------------------- *)
blanchet@39497
   686
blanchet@40157
   687
type metis_problem =
blanchet@39497
   688
  {axioms: (Metis_Thm.thm * thm) list,
blanchet@39497
   689
   tfrees: type_literal list,
blanchet@39886
   690
   old_skolems: (string * term) list}
blanchet@39497
   691
blanchet@39497
   692
fun is_quasi_fol_clause thy =
blanchet@39886
   693
  Meson.is_fol_term thy o snd o conceal_old_skolem_terms ~1 [] o prop_of
blanchet@39497
   694
blanchet@39497
   695
(*Extract TFree constraints from context to include as conjecture clauses*)
blanchet@39497
   696
fun init_tfrees ctxt =
blanchet@39497
   697
  let fun add ((a,i),s) Ts = if i = ~1 then TFree(a,s) :: Ts else Ts in
blanchet@39497
   698
    Vartab.fold add (#2 (Variable.constraints_of ctxt)) []
blanchet@39497
   699
    |> type_literals_for_types
blanchet@39497
   700
  end;
blanchet@39497
   701
blanchet@39497
   702
(*Insert non-logical axioms corresponding to all accumulated TFrees*)
blanchet@40157
   703
fun add_tfrees {axioms, tfrees, old_skolems} : metis_problem =
blanchet@39497
   704
     {axioms = map (rpair TrueI o metis_of_tfree) (distinct (op =) tfrees) @
blanchet@39497
   705
               axioms,
blanchet@39886
   706
      tfrees = tfrees, old_skolems = old_skolems}
blanchet@39497
   707
blanchet@39497
   708
(*transform isabelle type / arity clause to metis clause *)
blanchet@39497
   709
fun add_type_thm [] lmap = lmap
blanchet@39886
   710
  | add_type_thm ((ith, mth) :: cls) {axioms, tfrees, old_skolems} =
blanchet@39497
   711
      add_type_thm cls {axioms = (mth, ith) :: axioms, tfrees = tfrees,
blanchet@39886
   712
                        old_skolems = old_skolems}
blanchet@39497
   713
blanchet@39497
   714
fun const_in_metis c (pred, tm_list) =
blanchet@39497
   715
  let
blanchet@39497
   716
    fun in_mterm (Metis_Term.Var _) = false
blanchet@41156
   717
      | in_mterm (Metis_Term.Fn (nm, tm_list)) =
blanchet@41156
   718
        c = nm orelse exists in_mterm tm_list
blanchet@41156
   719
  in c = pred orelse exists in_mterm tm_list end
blanchet@39497
   720
blanchet@39497
   721
(* ARITY CLAUSE *)
blanchet@39497
   722
fun m_arity_cls (TConsLit ((c, _), (t, _), args)) =
blanchet@39497
   723
    metis_lit true c [Metis_Term.Fn(t, map (Metis_Term.Var o fst) args)]
blanchet@39497
   724
  | m_arity_cls (TVarLit ((c, _), (s, _))) =
blanchet@39497
   725
    metis_lit false c [Metis_Term.Var s]
blanchet@39497
   726
(*TrueI is returned as the Isabelle counterpart because there isn't any.*)
blanchet@42895
   727
fun arity_cls (ArityClause {prem_lits, concl_lits, ...}) =
blanchet@39497
   728
  (TrueI,
blanchet@42895
   729
   Metis_Thm.axiom (Metis_LiteralSet.fromList
blanchet@42895
   730
                        (map m_arity_cls (concl_lits :: prem_lits))));
blanchet@39497
   731
blanchet@39497
   732
(* CLASSREL CLAUSE *)
blanchet@39497
   733
fun m_class_rel_cls (subclass, _) (superclass, _) =
blanchet@39497
   734
  [metis_lit false subclass [Metis_Term.Var "T"], metis_lit true superclass [Metis_Term.Var "T"]];
blanchet@39497
   735
fun class_rel_cls (ClassRelClause {subclass, superclass, ...}) =
blanchet@39497
   736
  (TrueI, Metis_Thm.axiom (Metis_LiteralSet.fromList (m_class_rel_cls subclass superclass)));
blanchet@39497
   737
blanchet@39497
   738
fun type_ext thy tms =
blanchet@39497
   739
  let val subs = tfree_classes_of_terms tms
blanchet@39497
   740
      val supers = tvar_classes_of_terms tms
blanchet@39497
   741
      and tycons = type_consts_of_terms thy tms
blanchet@39497
   742
      val (supers', arity_clauses) = make_arity_clauses thy tycons supers
blanchet@39497
   743
      val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@39497
   744
  in  map class_rel_cls class_rel_clauses @ map arity_cls arity_clauses
blanchet@39497
   745
  end;
blanchet@39497
   746
blanchet@39497
   747
(* Function to generate metis clauses, including comb and type clauses *)
blanchet@40157
   748
fun prepare_metis_problem mode0 ctxt type_lits cls thss =
wenzelm@42361
   749
  let val thy = Proof_Context.theory_of ctxt
blanchet@39497
   750
      (*The modes FO and FT are sticky. HO can be downgraded to FO.*)
blanchet@39497
   751
      fun set_mode FO = FO
blanchet@39497
   752
        | set_mode HO =
blanchet@39886
   753
          if forall (forall (is_quasi_fol_clause thy)) (cls :: thss) then FO
blanchet@39886
   754
          else HO
blanchet@39497
   755
        | set_mode FT = FT
blanchet@39497
   756
      val mode = set_mode mode0
blanchet@39497
   757
      (*transform isabelle clause to metis clause *)
blanchet@41139
   758
      fun add_thm is_conjecture (isa_ith, metis_ith)
blanchet@40157
   759
                  {axioms, tfrees, old_skolems} : metis_problem =
blanchet@39497
   760
        let
blanchet@39886
   761
          val (mth, tfree_lits, old_skolems) =
blanchet@40145
   762
            hol_thm_to_fol is_conjecture ctxt type_lits mode (length axioms)
blanchet@39886
   763
                           old_skolems metis_ith
blanchet@39497
   764
        in
blanchet@41139
   765
           {axioms = (mth, isa_ith) :: axioms,
blanchet@39886
   766
            tfrees = union (op =) tfree_lits tfrees, old_skolems = old_skolems}
blanchet@39497
   767
        end;
blanchet@39886
   768
      val lmap = {axioms = [], tfrees = init_tfrees ctxt, old_skolems = []}
blanchet@41139
   769
                 |> fold (add_thm true o `Meson.make_meta_clause) cls
blanchet@39497
   770
                 |> add_tfrees
blanchet@41139
   771
                 |> fold (fold (add_thm false o `Meson.make_meta_clause)) thss
blanchet@39497
   772
      val clause_lists = map (Metis_Thm.clause o #1) (#axioms lmap)
blanchet@39497
   773
      fun is_used c =
blanchet@39497
   774
        exists (Metis_LiteralSet.exists (const_in_metis c o #2)) clause_lists
blanchet@39497
   775
      val lmap =
blanchet@39497
   776
        if mode = FO then
blanchet@39497
   777
          lmap
blanchet@39497
   778
        else
blanchet@39497
   779
          let
blanchet@41156
   780
            val fdefs = @{thms fFalse_def fTrue_def fNot_def fconj_def fdisj_def
blanchet@41156
   781
                               fimplies_def fequal_def}
blanchet@41139
   782
            val prepare_helper =
blanchet@41139
   783
              zero_var_indexes
blanchet@41139
   784
              #> `(Meson.make_meta_clause
blanchet@41139
   785
                   #> rewrite_rule (map safe_mk_meta_eq fdefs))
blanchet@39497
   786
            val helper_ths =
blanchet@41140
   787
              metis_helpers
blanchet@42561
   788
              |> filter (is_used o prefix const_prefix o fst)
blanchet@42894
   789
              |> maps (fn (_, (needs_full_types, thms)) =>
blanchet@41140
   790
                          if needs_full_types andalso mode <> FT then []
blanchet@41140
   791
                          else map prepare_helper thms)
blanchet@40145
   792
          in lmap |> fold (add_thm false) helper_ths end
blanchet@39886
   793
  in
blanchet@39886
   794
    (mode, add_type_thm (type_ext thy (maps (map prop_of) (cls :: thss))) lmap)
blanchet@39886
   795
  end
blanchet@39497
   796
paulson@15347
   797
end;