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