src/HOL/Tools/ATP/atp_translate.ML
author blanchet
Fri Jul 01 15:53:37 2011 +0200 (2011-07-01)
changeset 43622 80673841372b
parent 43572 ae612a423dad
child 43623 e096b1effbbb
permissions -rw-r--r--
tuning
wenzelm@43283
     1
(*  Title:      HOL/Tools/ATP/atp_translate.ML
blanchet@38282
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38282
     3
    Author:     Makarius
blanchet@38282
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38282
     5
blanchet@39494
     6
Translation of HOL to FOL for Sledgehammer.
blanchet@38282
     7
*)
blanchet@38282
     8
blanchet@43085
     9
signature ATP_TRANSLATE =
blanchet@38282
    10
sig
blanchet@42227
    11
  type 'a fo_term = 'a ATP_Problem.fo_term
blanchet@43136
    12
  type connective = ATP_Problem.connective
blanchet@43136
    13
  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
blanchet@42939
    14
  type format = ATP_Problem.format
blanchet@42709
    15
  type formula_kind = ATP_Problem.formula_kind
blanchet@38282
    16
  type 'a problem = 'a ATP_Problem.problem
blanchet@43085
    17
blanchet@43421
    18
  datatype locality =
blanchet@43421
    19
    General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
blanchet@43421
    20
    Chained
blanchet@42613
    21
blanchet@42613
    22
  datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@42613
    23
  datatype type_level =
blanchet@43362
    24
    All_Types | Noninf_Nonmono_Types | Fin_Nonmono_Types | Const_Arg_Types |
blanchet@43362
    25
    No_Types
blanchet@43128
    26
  datatype type_heaviness = Heavyweight | Lightweight
blanchet@42613
    27
blanchet@43102
    28
  datatype type_sys =
blanchet@42722
    29
    Simple_Types of type_level |
blanchet@42837
    30
    Preds of polymorphism * type_level * type_heaviness |
blanchet@42837
    31
    Tags of polymorphism * type_level * type_heaviness
blanchet@42613
    32
blanchet@43085
    33
  val bound_var_prefix : string
blanchet@43496
    34
  val schematic_var_prefix : string
blanchet@43496
    35
  val fixed_var_prefix : string
blanchet@43496
    36
  val tvar_prefix : string
blanchet@43496
    37
  val tfree_prefix : string
blanchet@43496
    38
  val const_prefix : string
blanchet@43496
    39
  val type_const_prefix : string
blanchet@43496
    40
  val class_prefix : string
blanchet@43085
    41
  val skolem_const_prefix : string
blanchet@43085
    42
  val old_skolem_const_prefix : string
blanchet@43085
    43
  val new_skolem_const_prefix : string
blanchet@43125
    44
  val type_decl_prefix : string
blanchet@43125
    45
  val sym_decl_prefix : string
blanchet@43125
    46
  val preds_sym_formula_prefix : string
blanchet@43129
    47
  val lightweight_tags_sym_formula_prefix : string
blanchet@40204
    48
  val fact_prefix : string
blanchet@38282
    49
  val conjecture_prefix : string
blanchet@42881
    50
  val helper_prefix : string
blanchet@43125
    51
  val class_rel_clause_prefix : string
blanchet@43125
    52
  val arity_clause_prefix : string
blanchet@43125
    53
  val tfree_clause_prefix : string
blanchet@42881
    54
  val typed_helper_suffix : string
blanchet@43125
    55
  val untyped_helper_suffix : string
blanchet@43159
    56
  val type_tag_idempotence_helper_name : string
blanchet@42966
    57
  val predicator_name : string
blanchet@42966
    58
  val app_op_name : string
blanchet@43104
    59
  val type_tag_name : string
blanchet@42966
    60
  val type_pred_name : string
blanchet@42962
    61
  val simple_type_prefix : string
blanchet@43174
    62
  val prefixed_predicator_name : string
blanchet@43130
    63
  val prefixed_app_op_name : string
blanchet@43130
    64
  val prefixed_type_tag_name : string
blanchet@43496
    65
  val ascii_of : string -> string
blanchet@43496
    66
  val unascii_of : string -> string
blanchet@43085
    67
  val strip_prefix_and_unascii : string -> string -> string option
blanchet@43159
    68
  val proxy_table : (string * (string * (thm * (string * string)))) list
blanchet@43159
    69
  val proxify_const : string -> (string * string) option
blanchet@43496
    70
  val invert_const : string -> string
blanchet@43496
    71
  val unproxify_const : string -> string
blanchet@43093
    72
  val new_skolem_var_name_from_const : string -> string
blanchet@43093
    73
  val num_type_args : theory -> string -> int
blanchet@43248
    74
  val atp_irrelevant_consts : string list
blanchet@43248
    75
  val atp_schematic_consts_of : term -> typ list Symtab.table
blanchet@43085
    76
  val is_locality_global : locality -> bool
blanchet@43102
    77
  val type_sys_from_string : string -> type_sys
blanchet@43102
    78
  val polymorphism_of_type_sys : type_sys -> polymorphism
blanchet@43102
    79
  val level_of_type_sys : type_sys -> type_level
blanchet@43102
    80
  val is_type_sys_virtually_sound : type_sys -> bool
blanchet@43102
    81
  val is_type_sys_fairly_sound : type_sys -> bool
blanchet@43102
    82
  val choose_format : format list -> type_sys -> format * type_sys
blanchet@43136
    83
  val mk_aconns :
blanchet@43136
    84
    connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
blanchet@43496
    85
  val unmangled_const : string -> string * string fo_term list
blanchet@43130
    86
  val unmangled_const_name : string -> string
blanchet@43194
    87
  val helper_table : ((string * bool) * thm list) list
blanchet@43501
    88
  val factsN : string
blanchet@40059
    89
  val prepare_atp_problem :
blanchet@43572
    90
    Proof.context -> format -> formula_kind -> formula_kind -> type_sys -> bool
blanchet@43304
    91
    -> bool -> bool -> bool -> term list -> term
blanchet@43304
    92
    -> ((string * locality) * term) list
blanchet@42541
    93
    -> string problem * string Symtab.table * int * int
blanchet@43214
    94
       * (string * locality) list vector * int list * int Symtab.table
blanchet@41313
    95
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38282
    96
end;
blanchet@38282
    97
blanchet@43085
    98
structure ATP_Translate : ATP_TRANSLATE =
blanchet@38282
    99
struct
blanchet@38282
   100
blanchet@43085
   101
open ATP_Util
blanchet@38282
   102
open ATP_Problem
blanchet@43085
   103
blanchet@43085
   104
type name = string * string
blanchet@43085
   105
blanchet@42640
   106
(* experimental *)
blanchet@42640
   107
val generate_useful_info = false
blanchet@38282
   108
blanchet@42879
   109
fun useful_isabelle_info s =
blanchet@42879
   110
  if generate_useful_info then
blanchet@42879
   111
    SOME (ATerm ("[]", [ATerm ("isabelle_" ^ s, [])]))
blanchet@42879
   112
  else
blanchet@42879
   113
    NONE
blanchet@42879
   114
blanchet@42879
   115
val intro_info = useful_isabelle_info "intro"
blanchet@42879
   116
val elim_info = useful_isabelle_info "elim"
blanchet@42879
   117
val simp_info = useful_isabelle_info "simp"
blanchet@42879
   118
blanchet@43085
   119
val bound_var_prefix = "B_"
blanchet@43085
   120
val schematic_var_prefix = "V_"
blanchet@43085
   121
val fixed_var_prefix = "v_"
blanchet@43085
   122
blanchet@43085
   123
val tvar_prefix = "T_"
blanchet@43085
   124
val tfree_prefix = "t_"
blanchet@43085
   125
blanchet@43085
   126
val const_prefix = "c_"
blanchet@43085
   127
val type_const_prefix = "tc_"
blanchet@43085
   128
val class_prefix = "cl_"
blanchet@43085
   129
blanchet@43085
   130
val skolem_const_prefix = "Sledgehammer" ^ Long_Name.separator ^ "Sko"
blanchet@43085
   131
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@43085
   132
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@43085
   133
blanchet@42998
   134
val type_decl_prefix = "ty_"
blanchet@42998
   135
val sym_decl_prefix = "sy_"
blanchet@43125
   136
val preds_sym_formula_prefix = "psy_"
blanchet@43129
   137
val lightweight_tags_sym_formula_prefix = "tsy_"
blanchet@40204
   138
val fact_prefix = "fact_"
blanchet@38282
   139
val conjecture_prefix = "conj_"
blanchet@38282
   140
val helper_prefix = "help_"
blanchet@43159
   141
val class_rel_clause_prefix = "clar_"
blanchet@38282
   142
val arity_clause_prefix = "arity_"
blanchet@43085
   143
val tfree_clause_prefix = "tfree_"
blanchet@38282
   144
blanchet@42881
   145
val typed_helper_suffix = "_T"
blanchet@42881
   146
val untyped_helper_suffix = "_U"
blanchet@43159
   147
val type_tag_idempotence_helper_name = helper_prefix ^ "ti_idem"
blanchet@42881
   148
blanchet@42966
   149
val predicator_name = "hBOOL"
blanchet@42966
   150
val app_op_name = "hAPP"
blanchet@43104
   151
val type_tag_name = "ti"
blanchet@42966
   152
val type_pred_name = "is"
blanchet@42962
   153
val simple_type_prefix = "ty_"
blanchet@42531
   154
blanchet@43174
   155
val prefixed_predicator_name = const_prefix ^ predicator_name
blanchet@43130
   156
val prefixed_app_op_name = const_prefix ^ app_op_name
blanchet@43130
   157
val prefixed_type_tag_name = const_prefix ^ type_tag_name
blanchet@43130
   158
blanchet@38282
   159
(* Freshness almost guaranteed! *)
blanchet@38282
   160
val sledgehammer_weak_prefix = "Sledgehammer:"
blanchet@38282
   161
blanchet@43085
   162
(*Escaping of special characters.
blanchet@43085
   163
  Alphanumeric characters are left unchanged.
blanchet@43085
   164
  The character _ goes to __
blanchet@43085
   165
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@43085
   166
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
blanchet@43093
   167
val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
blanchet@43085
   168
blanchet@43085
   169
fun stringN_of_int 0 _ = ""
blanchet@43085
   170
  | stringN_of_int k n =
blanchet@43085
   171
    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
blanchet@43085
   172
blanchet@43085
   173
fun ascii_of_char c =
blanchet@43085
   174
  if Char.isAlphaNum c then
blanchet@43085
   175
    String.str c
blanchet@43085
   176
  else if c = #"_" then
blanchet@43085
   177
    "__"
blanchet@43085
   178
  else if #" " <= c andalso c <= #"/" then
blanchet@43085
   179
    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
blanchet@43085
   180
  else
blanchet@43085
   181
    (* fixed width, in case more digits follow *)
blanchet@43085
   182
    "_" ^ stringN_of_int 3 (Char.ord c)
blanchet@43085
   183
blanchet@43085
   184
val ascii_of = String.translate ascii_of_char
blanchet@43085
   185
blanchet@43085
   186
(** Remove ASCII armoring from names in proof files **)
blanchet@43085
   187
blanchet@43085
   188
(* We don't raise error exceptions because this code can run inside a worker
blanchet@43085
   189
   thread. Also, the errors are impossible. *)
blanchet@43085
   190
val unascii_of =
blanchet@43085
   191
  let
blanchet@43085
   192
    fun un rcs [] = String.implode(rev rcs)
blanchet@43085
   193
      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
blanchet@43085
   194
        (* Three types of _ escapes: __, _A to _P, _nnn *)
blanchet@43496
   195
      | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
blanchet@43085
   196
      | un rcs (#"_" :: c :: cs) =
blanchet@43085
   197
        if #"A" <= c andalso c<= #"P" then
blanchet@43085
   198
          (* translation of #" " to #"/" *)
blanchet@43085
   199
          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
blanchet@43085
   200
        else
blanchet@43496
   201
          let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
blanchet@43085
   202
            case Int.fromString (String.implode digits) of
blanchet@43085
   203
              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
blanchet@43496
   204
            | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
blanchet@43085
   205
          end
blanchet@43085
   206
      | un rcs (c :: cs) = un (c :: rcs) cs
blanchet@43085
   207
  in un [] o String.explode end
blanchet@43085
   208
blanchet@43085
   209
(* If string s has the prefix s1, return the result of deleting it,
blanchet@43085
   210
   un-ASCII'd. *)
blanchet@43085
   211
fun strip_prefix_and_unascii s1 s =
blanchet@43085
   212
  if String.isPrefix s1 s then
blanchet@43085
   213
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@43085
   214
  else
blanchet@43085
   215
    NONE
blanchet@43085
   216
blanchet@43159
   217
val proxy_table =
blanchet@43159
   218
  [("c_False", (@{const_name False}, (@{thm fFalse_def},
blanchet@43159
   219
       ("fFalse", @{const_name ATP.fFalse})))),
blanchet@43159
   220
   ("c_True", (@{const_name True}, (@{thm fTrue_def},
blanchet@43159
   221
       ("fTrue", @{const_name ATP.fTrue})))),
blanchet@43159
   222
   ("c_Not", (@{const_name Not}, (@{thm fNot_def},
blanchet@43159
   223
       ("fNot", @{const_name ATP.fNot})))),
blanchet@43159
   224
   ("c_conj", (@{const_name conj}, (@{thm fconj_def},
blanchet@43159
   225
       ("fconj", @{const_name ATP.fconj})))),
blanchet@43159
   226
   ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
blanchet@43159
   227
       ("fdisj", @{const_name ATP.fdisj})))),
blanchet@43159
   228
   ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
blanchet@43159
   229
       ("fimplies", @{const_name ATP.fimplies})))),
blanchet@43159
   230
   ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
blanchet@43159
   231
       ("fequal", @{const_name ATP.fequal}))))]
blanchet@43085
   232
blanchet@43159
   233
val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
blanchet@43085
   234
blanchet@43085
   235
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@43085
   236
   table unless you know what you are doing. *)
blanchet@43085
   237
val const_trans_table =
blanchet@43085
   238
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@43085
   239
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@43085
   240
   (@{const_name False}, "False"),
blanchet@43085
   241
   (@{const_name True}, "True"),
blanchet@43085
   242
   (@{const_name Not}, "Not"),
blanchet@43085
   243
   (@{const_name conj}, "conj"),
blanchet@43085
   244
   (@{const_name disj}, "disj"),
blanchet@43085
   245
   (@{const_name implies}, "implies"),
blanchet@43085
   246
   (@{const_name HOL.eq}, "equal"),
blanchet@43085
   247
   (@{const_name If}, "If"),
blanchet@43085
   248
   (@{const_name Set.member}, "member"),
blanchet@43085
   249
   (@{const_name Meson.COMBI}, "COMBI"),
blanchet@43085
   250
   (@{const_name Meson.COMBK}, "COMBK"),
blanchet@43085
   251
   (@{const_name Meson.COMBB}, "COMBB"),
blanchet@43085
   252
   (@{const_name Meson.COMBC}, "COMBC"),
blanchet@43085
   253
   (@{const_name Meson.COMBS}, "COMBS")]
blanchet@43085
   254
  |> Symtab.make
blanchet@43159
   255
  |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
blanchet@43085
   256
blanchet@43085
   257
(* Invert the table of translations between Isabelle and ATPs. *)
blanchet@43085
   258
val const_trans_table_inv =
blanchet@43085
   259
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@43085
   260
val const_trans_table_unprox =
blanchet@43085
   261
  Symtab.empty
blanchet@43159
   262
  |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
blanchet@43085
   263
blanchet@43085
   264
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@43085
   265
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
blanchet@43085
   266
blanchet@43085
   267
fun lookup_const c =
blanchet@43085
   268
  case Symtab.lookup const_trans_table c of
blanchet@43085
   269
    SOME c' => c'
blanchet@43085
   270
  | NONE => ascii_of c
blanchet@43085
   271
blanchet@43622
   272
fun ascii_of_indexname (v, 0) = ascii_of v
blanchet@43622
   273
  | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
blanchet@43085
   274
blanchet@43085
   275
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@43085
   276
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@43085
   277
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
blanchet@43085
   278
blanchet@43622
   279
fun make_schematic_type_var (x, i) =
blanchet@43622
   280
      tvar_prefix ^ (ascii_of_indexname (unprefix "'" x, i))
blanchet@43622
   281
fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (unprefix "'" x))
blanchet@43085
   282
blanchet@43622
   283
(* "HOL.eq" is mapped to the ATP's equality. *)
blanchet@43622
   284
fun make_fixed_const @{const_name HOL.eq} = tptp_old_equal
blanchet@43085
   285
  | make_fixed_const c = const_prefix ^ lookup_const c
blanchet@43085
   286
blanchet@43085
   287
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
blanchet@43085
   288
blanchet@43085
   289
fun make_type_class clas = class_prefix ^ ascii_of clas
blanchet@43085
   290
blanchet@43093
   291
fun new_skolem_var_name_from_const s =
blanchet@43093
   292
  let val ss = s |> space_explode Long_Name.separator in
blanchet@43093
   293
    nth ss (length ss - 2)
blanchet@43093
   294
  end
blanchet@43093
   295
blanchet@43093
   296
(* The number of type arguments of a constant, zero if it's monomorphic. For
blanchet@43093
   297
   (instances of) Skolem pseudoconstants, this information is encoded in the
blanchet@43093
   298
   constant name. *)
blanchet@43093
   299
fun num_type_args thy s =
blanchet@43093
   300
  if String.isPrefix skolem_const_prefix s then
blanchet@43093
   301
    s |> space_explode Long_Name.separator |> List.last |> Int.fromString |> the
blanchet@43093
   302
  else
blanchet@43093
   303
    (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
blanchet@43093
   304
blanchet@43248
   305
(* These are either simplified away by "Meson.presimplify" (most of the time) or
blanchet@43248
   306
   handled specially via "fFalse", "fTrue", ..., "fequal". *)
blanchet@43248
   307
val atp_irrelevant_consts =
blanchet@43248
   308
  [@{const_name False}, @{const_name True}, @{const_name Not},
blanchet@43248
   309
   @{const_name conj}, @{const_name disj}, @{const_name implies},
blanchet@43248
   310
   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
blanchet@43248
   311
blanchet@43248
   312
val atp_monomorph_bad_consts =
blanchet@43248
   313
  atp_irrelevant_consts @
blanchet@43248
   314
  (* These are ignored anyway by the relevance filter (unless they appear in
blanchet@43248
   315
     higher-order places) but not by the monomorphizer. *)
blanchet@43248
   316
  [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
blanchet@43248
   317
   @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
blanchet@43248
   318
   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
blanchet@43248
   319
blanchet@43258
   320
fun add_schematic_const (x as (_, T)) =
blanchet@43258
   321
  Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
blanchet@43258
   322
val add_schematic_consts_of =
blanchet@43258
   323
  Term.fold_aterms (fn Const (x as (s, _)) =>
blanchet@43258
   324
                       not (member (op =) atp_monomorph_bad_consts s)
blanchet@43258
   325
                       ? add_schematic_const x
blanchet@43258
   326
                      | _ => I)
blanchet@43258
   327
fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
blanchet@43248
   328
blanchet@43085
   329
(** Definitions and functions for FOL clauses and formulas for TPTP **)
blanchet@43085
   330
blanchet@43085
   331
(* The first component is the type class; the second is a "TVar" or "TFree". *)
blanchet@43085
   332
datatype type_literal =
blanchet@43085
   333
  TyLitVar of name * name |
blanchet@43085
   334
  TyLitFree of name * name
blanchet@43085
   335
blanchet@43085
   336
blanchet@43085
   337
(** Isabelle arities **)
blanchet@43085
   338
blanchet@43085
   339
datatype arity_literal =
blanchet@43085
   340
  TConsLit of name * name * name list |
blanchet@43085
   341
  TVarLit of name * name
blanchet@43085
   342
blanchet@43085
   343
fun gen_TVars 0 = []
blanchet@43093
   344
  | gen_TVars n = ("T_" ^ string_of_int n) :: gen_TVars (n-1)
blanchet@43085
   345
blanchet@43263
   346
val type_class = the_single @{sort type}
blanchet@43263
   347
blanchet@43263
   348
fun add_packed_sort tvar =
blanchet@43263
   349
  fold (fn s => s <> type_class ? cons (`make_type_class s, `I tvar))
blanchet@43085
   350
blanchet@43086
   351
type arity_clause =
blanchet@43496
   352
  {name : string,
blanchet@43496
   353
   prem_lits : arity_literal list,
blanchet@43496
   354
   concl_lits : arity_literal}
blanchet@43085
   355
blanchet@43085
   356
(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
blanchet@43085
   357
fun make_axiom_arity_clause (tcons, name, (cls, args)) =
blanchet@43085
   358
  let
blanchet@43085
   359
    val tvars = gen_TVars (length args)
blanchet@43085
   360
    val tvars_srts = ListPair.zip (tvars, args)
blanchet@43085
   361
  in
blanchet@43086
   362
    {name = name,
blanchet@43263
   363
     prem_lits = [] |> fold (uncurry add_packed_sort) tvars_srts |> map TVarLit,
blanchet@43086
   364
     concl_lits = TConsLit (`make_type_class cls,
blanchet@43086
   365
                            `make_fixed_type_const tcons,
blanchet@43086
   366
                            tvars ~~ tvars)}
blanchet@43085
   367
  end
blanchet@43085
   368
blanchet@43085
   369
fun arity_clause _ _ (_, []) = []
blanchet@43495
   370
  | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
blanchet@43495
   371
    arity_clause seen n (tcons, ars)
blanchet@43495
   372
  | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
blanchet@43495
   373
    if member (op =) seen class then
blanchet@43495
   374
      (* multiple arities for the same (tycon, class) pair *)
blanchet@43495
   375
      make_axiom_arity_clause (tcons,
blanchet@43495
   376
          lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
blanchet@43495
   377
          ar) ::
blanchet@43495
   378
      arity_clause seen (n + 1) (tcons, ars)
blanchet@43495
   379
    else
blanchet@43495
   380
      make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
blanchet@43495
   381
                               ascii_of class, ar) ::
blanchet@43495
   382
      arity_clause (class :: seen) n (tcons, ars)
blanchet@43085
   383
blanchet@43085
   384
fun multi_arity_clause [] = []
blanchet@43085
   385
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@43085
   386
      arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
blanchet@43085
   387
blanchet@43622
   388
(* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
blanchet@43622
   389
   theory thy provided its arguments have the corresponding sorts. *)
blanchet@43085
   390
fun type_class_pairs thy tycons classes =
blanchet@43093
   391
  let
blanchet@43093
   392
    val alg = Sign.classes_of thy
blanchet@43093
   393
    fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@43093
   394
    fun add_class tycon class =
blanchet@43093
   395
      cons (class, domain_sorts tycon class)
blanchet@43093
   396
      handle Sorts.CLASS_ERROR _ => I
blanchet@43093
   397
    fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
blanchet@43093
   398
  in map try_classes tycons end
blanchet@43085
   399
blanchet@43085
   400
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@43085
   401
fun iter_type_class_pairs _ _ [] = ([], [])
blanchet@43085
   402
  | iter_type_class_pairs thy tycons classes =
blanchet@43263
   403
      let
blanchet@43263
   404
        fun maybe_insert_class s =
blanchet@43263
   405
          (s <> type_class andalso not (member (op =) classes s))
blanchet@43263
   406
          ? insert (op =) s
blanchet@43263
   407
        val cpairs = type_class_pairs thy tycons classes
blanchet@43263
   408
        val newclasses =
blanchet@43263
   409
          [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
blanchet@43263
   410
        val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
blanchet@43266
   411
      in (classes' @ classes, union (op =) cpairs' cpairs) end
blanchet@43085
   412
blanchet@43085
   413
fun make_arity_clauses thy tycons =
blanchet@43085
   414
  iter_type_class_pairs thy tycons ##> multi_arity_clause
blanchet@43085
   415
blanchet@43085
   416
blanchet@43085
   417
(** Isabelle class relations **)
blanchet@43085
   418
blanchet@43086
   419
type class_rel_clause =
blanchet@43496
   420
  {name : string,
blanchet@43496
   421
   subclass : name,
blanchet@43496
   422
   superclass : name}
blanchet@43085
   423
blanchet@43622
   424
(* Generate all pairs (sub, super) such that sub is a proper subclass of super
blanchet@43622
   425
   in theory "thy". *)
blanchet@43085
   426
fun class_pairs _ [] _ = []
blanchet@43085
   427
  | class_pairs thy subs supers =
blanchet@43085
   428
      let
blanchet@43085
   429
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@43085
   430
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@43085
   431
        fun add_supers sub = fold (add_super sub) supers
blanchet@43085
   432
      in fold add_supers subs [] end
blanchet@43085
   433
blanchet@43622
   434
fun make_class_rel_clause (sub, super) =
blanchet@43622
   435
  {name = sub ^ "_" ^ super, subclass = `make_type_class sub,
blanchet@43086
   436
   superclass = `make_type_class super}
blanchet@43085
   437
blanchet@43085
   438
fun make_class_rel_clauses thy subs supers =
blanchet@43093
   439
  map make_class_rel_clause (class_pairs thy subs supers)
blanchet@43085
   440
blanchet@43085
   441
datatype combterm =
blanchet@43085
   442
  CombConst of name * typ * typ list |
blanchet@43085
   443
  CombVar of name * typ |
blanchet@43085
   444
  CombApp of combterm * combterm
blanchet@43085
   445
blanchet@43085
   446
fun combtyp_of (CombConst (_, T, _)) = T
blanchet@43085
   447
  | combtyp_of (CombVar (_, T)) = T
blanchet@43085
   448
  | combtyp_of (CombApp (t1, _)) = snd (dest_funT (combtyp_of t1))
blanchet@43085
   449
blanchet@43085
   450
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@43085
   451
fun strip_combterm_comb u =
blanchet@43496
   452
  let
blanchet@43496
   453
    fun stripc (CombApp (t, u), ts) = stripc (t, u :: ts)
blanchet@43496
   454
      | stripc x = x
blanchet@43496
   455
  in stripc (u, []) end
blanchet@43085
   456
blanchet@43085
   457
fun atyps_of T = fold_atyps (insert (op =)) T []
blanchet@43085
   458
blanchet@43085
   459
fun new_skolem_const_name s num_T_args =
blanchet@43085
   460
  [new_skolem_const_prefix, s, string_of_int num_T_args]
blanchet@43085
   461
  |> space_implode Long_Name.separator
blanchet@43085
   462
blanchet@43085
   463
(* Converts a term (with combinators) into a combterm. Also accumulates sort
blanchet@43085
   464
   infomation. *)
blanchet@43085
   465
fun combterm_from_term thy bs (P $ Q) =
blanchet@43085
   466
    let
blanchet@43085
   467
      val (P', P_atomics_Ts) = combterm_from_term thy bs P
blanchet@43085
   468
      val (Q', Q_atomics_Ts) = combterm_from_term thy bs Q
blanchet@43085
   469
    in (CombApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
blanchet@43085
   470
  | combterm_from_term thy _ (Const (c, T)) =
blanchet@43085
   471
    let
blanchet@43085
   472
      val tvar_list =
blanchet@43085
   473
        (if String.isPrefix old_skolem_const_prefix c then
blanchet@43085
   474
           [] |> Term.add_tvarsT T |> map TVar
blanchet@43085
   475
         else
blanchet@43085
   476
           (c, T) |> Sign.const_typargs thy)
blanchet@43085
   477
      val c' = CombConst (`make_fixed_const c, T, tvar_list)
blanchet@43085
   478
    in (c', atyps_of T) end
blanchet@43085
   479
  | combterm_from_term _ _ (Free (v, T)) =
blanchet@43085
   480
    (CombConst (`make_fixed_var v, T, []), atyps_of T)
blanchet@43085
   481
  | combterm_from_term _ _ (Var (v as (s, _), T)) =
blanchet@43085
   482
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@43085
   483
       let
blanchet@43085
   484
         val Ts = T |> strip_type |> swap |> op ::
blanchet@43085
   485
         val s' = new_skolem_const_name s (length Ts)
blanchet@43085
   486
       in CombConst (`make_fixed_const s', T, Ts) end
blanchet@43085
   487
     else
blanchet@43085
   488
       CombVar ((make_schematic_var v, s), T), atyps_of T)
blanchet@43085
   489
  | combterm_from_term _ bs (Bound j) =
blanchet@43085
   490
    nth bs j
blanchet@43085
   491
    |> (fn (s, T) => (CombConst (`make_bound_var s, T, []), atyps_of T))
blanchet@43085
   492
  | combterm_from_term _ _ (Abs _) = raise Fail "HOL clause: Abs"
blanchet@43085
   493
blanchet@43421
   494
datatype locality =
blanchet@43421
   495
  General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
blanchet@43421
   496
  Chained
blanchet@43085
   497
blanchet@43085
   498
(* (quasi-)underapproximation of the truth *)
blanchet@43085
   499
fun is_locality_global Local = false
blanchet@43085
   500
  | is_locality_global Assum = false
blanchet@43085
   501
  | is_locality_global Chained = false
blanchet@43085
   502
  | is_locality_global _ = true
blanchet@43085
   503
blanchet@42613
   504
datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@42613
   505
datatype type_level =
blanchet@43362
   506
  All_Types | Noninf_Nonmono_Types | Fin_Nonmono_Types | Const_Arg_Types |
blanchet@43362
   507
  No_Types
blanchet@43128
   508
datatype type_heaviness = Heavyweight | Lightweight
blanchet@42613
   509
blanchet@43102
   510
datatype type_sys =
blanchet@42722
   511
  Simple_Types of type_level |
blanchet@42837
   512
  Preds of polymorphism * type_level * type_heaviness |
blanchet@42837
   513
  Tags of polymorphism * type_level * type_heaviness
blanchet@42613
   514
blanchet@42689
   515
fun try_unsuffixes ss s =
blanchet@42689
   516
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@42689
   517
blanchet@42613
   518
fun type_sys_from_string s =
blanchet@42722
   519
  (case try (unprefix "poly_") s of
blanchet@42722
   520
     SOME s => (SOME Polymorphic, s)
blanchet@42613
   521
   | NONE =>
blanchet@42613
   522
     case try (unprefix "mono_") s of
blanchet@42722
   523
       SOME s => (SOME Monomorphic, s)
blanchet@42722
   524
     | NONE =>
blanchet@42722
   525
       case try (unprefix "mangled_") s of
blanchet@42722
   526
         SOME s => (SOME Mangled_Monomorphic, s)
blanchet@42722
   527
       | NONE => (NONE, s))
blanchet@42613
   528
  ||> (fn s =>
blanchet@42689
   529
          (* "_query" and "_bang" are for the ASCII-challenged Mirabelle. *)
blanchet@42689
   530
          case try_unsuffixes ["?", "_query"] s of
blanchet@43362
   531
            SOME s => (Noninf_Nonmono_Types, s)
blanchet@42613
   532
          | NONE =>
blanchet@42689
   533
            case try_unsuffixes ["!", "_bang"] s of
blanchet@43362
   534
              SOME s => (Fin_Nonmono_Types, s)
blanchet@42613
   535
            | NONE => (All_Types, s))
blanchet@42828
   536
  ||> apsnd (fn s =>
blanchet@42837
   537
                case try (unsuffix "_heavy") s of
blanchet@43128
   538
                  SOME s => (Heavyweight, s)
blanchet@43128
   539
                | NONE => (Lightweight, s))
blanchet@42837
   540
  |> (fn (poly, (level, (heaviness, core))) =>
blanchet@42837
   541
         case (core, (poly, level, heaviness)) of
blanchet@43128
   542
           ("simple", (NONE, _, Lightweight)) => Simple_Types level
blanchet@42854
   543
         | ("preds", (SOME poly, _, _)) => Preds (poly, level, heaviness)
blanchet@42886
   544
         | ("tags", (SOME Polymorphic, _, _)) =>
blanchet@43361
   545
           Tags (Polymorphic, level, heaviness)
blanchet@42854
   546
         | ("tags", (SOME poly, _, _)) => Tags (poly, level, heaviness)
blanchet@43128
   547
         | ("args", (SOME poly, All_Types (* naja *), Lightweight)) =>
blanchet@43128
   548
           Preds (poly, Const_Arg_Types, Lightweight)
blanchet@43128
   549
         | ("erased", (NONE, All_Types (* naja *), Lightweight)) =>
blanchet@43128
   550
           Preds (Polymorphic, No_Types, Lightweight)
blanchet@42753
   551
         | _ => raise Same.SAME)
blanchet@42753
   552
  handle Same.SAME => error ("Unknown type system: " ^ quote s ^ ".")
blanchet@42613
   553
blanchet@42722
   554
fun polymorphism_of_type_sys (Simple_Types _) = Mangled_Monomorphic
blanchet@42828
   555
  | polymorphism_of_type_sys (Preds (poly, _, _)) = poly
blanchet@42828
   556
  | polymorphism_of_type_sys (Tags (poly, _, _)) = poly
blanchet@42613
   557
blanchet@42722
   558
fun level_of_type_sys (Simple_Types level) = level
blanchet@42828
   559
  | level_of_type_sys (Preds (_, level, _)) = level
blanchet@42828
   560
  | level_of_type_sys (Tags (_, level, _)) = level
blanchet@42828
   561
blanchet@43128
   562
fun heaviness_of_type_sys (Simple_Types _) = Heavyweight
blanchet@42837
   563
  | heaviness_of_type_sys (Preds (_, _, heaviness)) = heaviness
blanchet@42837
   564
  | heaviness_of_type_sys (Tags (_, _, heaviness)) = heaviness
blanchet@42831
   565
blanchet@42687
   566
fun is_type_level_virtually_sound level =
blanchet@43362
   567
  level = All_Types orelse level = Noninf_Nonmono_Types
blanchet@42613
   568
val is_type_sys_virtually_sound =
blanchet@42613
   569
  is_type_level_virtually_sound o level_of_type_sys
blanchet@42613
   570
blanchet@42613
   571
fun is_type_level_fairly_sound level =
blanchet@43362
   572
  is_type_level_virtually_sound level orelse level = Fin_Nonmono_Types
blanchet@42613
   573
val is_type_sys_fairly_sound = is_type_level_fairly_sound o level_of_type_sys
blanchet@42613
   574
blanchet@42994
   575
fun is_setting_higher_order THF (Simple_Types _) = true
blanchet@42994
   576
  | is_setting_higher_order _ _ = false
blanchet@42994
   577
blanchet@43101
   578
fun choose_format formats (Simple_Types level) =
blanchet@43101
   579
    if member (op =) formats THF then (THF, Simple_Types level)
blanchet@43101
   580
    else if member (op =) formats TFF then (TFF, Simple_Types level)
blanchet@43128
   581
    else choose_format formats (Preds (Mangled_Monomorphic, level, Heavyweight))
blanchet@43101
   582
  | choose_format formats type_sys =
blanchet@43101
   583
    (case hd formats of
blanchet@43101
   584
       CNF_UEQ =>
blanchet@43101
   585
       (CNF_UEQ, case type_sys of
blanchet@43101
   586
                   Preds stuff =>
blanchet@43289
   587
                   (if is_type_sys_fairly_sound type_sys then Tags else Preds)
blanchet@43101
   588
                       stuff
blanchet@43101
   589
                 | _ => type_sys)
blanchet@43101
   590
     | format => (format, type_sys))
blanchet@43101
   591
blanchet@40114
   592
type translated_formula =
blanchet@43496
   593
  {name : string,
blanchet@43496
   594
   locality : locality,
blanchet@43496
   595
   kind : formula_kind,
blanchet@43496
   596
   combformula : (name, typ, combterm) formula,
blanchet@43496
   597
   atomic_types : typ list}
blanchet@38282
   598
blanchet@42640
   599
fun update_combformula f ({name, locality, kind, combformula, atomic_types}
blanchet@42640
   600
                          : translated_formula) =
blanchet@42640
   601
  {name = name, locality = locality, kind = kind, combformula = f combformula,
blanchet@42562
   602
   atomic_types = atomic_types} : translated_formula
blanchet@42542
   603
blanchet@42558
   604
fun fact_lift f ({combformula, ...} : translated_formula) = f combformula
blanchet@42558
   605
blanchet@43064
   606
val type_instance = Sign.typ_instance o Proof_Context.theory_of
blanchet@43064
   607
blanchet@43064
   608
fun insert_type ctxt get_T x xs =
blanchet@43064
   609
  let val T = get_T x in
blanchet@43064
   610
    if exists (curry (type_instance ctxt) T o get_T) xs then xs
blanchet@43064
   611
    else x :: filter_out (curry (type_instance ctxt o swap) T o get_T) xs
blanchet@43064
   612
  end
blanchet@42677
   613
blanchet@42753
   614
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@42753
   615
datatype type_arg_policy =
blanchet@42753
   616
  Explicit_Type_Args of bool |
blanchet@42753
   617
  Mangled_Type_Args of bool |
blanchet@42753
   618
  No_Type_Args
blanchet@41136
   619
blanchet@42836
   620
fun should_drop_arg_type_args (Simple_Types _) =
blanchet@42836
   621
    false (* since TFF doesn't support overloading *)
blanchet@42836
   622
  | should_drop_arg_type_args type_sys =
blanchet@42836
   623
    level_of_type_sys type_sys = All_Types andalso
blanchet@43128
   624
    heaviness_of_type_sys type_sys = Heavyweight
blanchet@42831
   625
blanchet@43128
   626
fun general_type_arg_policy (Tags (_, All_Types, Heavyweight)) = No_Type_Args
blanchet@43105
   627
  | general_type_arg_policy type_sys =
blanchet@43105
   628
    if level_of_type_sys type_sys = No_Types then
blanchet@43105
   629
      No_Type_Args
blanchet@43105
   630
    else if polymorphism_of_type_sys type_sys = Mangled_Monomorphic then
blanchet@43105
   631
      Mangled_Type_Args (should_drop_arg_type_args type_sys)
blanchet@43105
   632
    else
blanchet@43105
   633
      Explicit_Type_Args (should_drop_arg_type_args type_sys)
blanchet@42563
   634
blanchet@42951
   635
fun type_arg_policy type_sys s =
blanchet@42951
   636
  if s = @{const_name HOL.eq} orelse
blanchet@42966
   637
     (s = app_op_name andalso level_of_type_sys type_sys = Const_Arg_Types) then
blanchet@42951
   638
    No_Type_Args
blanchet@43105
   639
  else if s = type_tag_name then
blanchet@43105
   640
    Explicit_Type_Args false
blanchet@42951
   641
  else
blanchet@42951
   642
    general_type_arg_policy type_sys
blanchet@42227
   643
blanchet@43085
   644
(*Make literals for sorted type variables*)
blanchet@43263
   645
fun generic_add_sorts_on_type (_, []) = I
blanchet@43263
   646
  | generic_add_sorts_on_type ((x, i), s :: ss) =
blanchet@43263
   647
    generic_add_sorts_on_type ((x, i), ss)
blanchet@43263
   648
    #> (if s = the_single @{sort HOL.type} then
blanchet@43093
   649
          I
blanchet@43093
   650
        else if i = ~1 then
blanchet@43263
   651
          insert (op =) (TyLitFree (`make_type_class s, `make_fixed_type_var x))
blanchet@43093
   652
        else
blanchet@43263
   653
          insert (op =) (TyLitVar (`make_type_class s,
blanchet@43263
   654
                                   (make_schematic_type_var (x, i), x))))
blanchet@43263
   655
fun add_sorts_on_tfree (TFree (s, S)) = generic_add_sorts_on_type ((s, ~1), S)
blanchet@43263
   656
  | add_sorts_on_tfree _ = I
blanchet@43263
   657
fun add_sorts_on_tvar (TVar z) = generic_add_sorts_on_type z
blanchet@43263
   658
  | add_sorts_on_tvar _ = I
blanchet@43085
   659
blanchet@43263
   660
fun type_literals_for_types type_sys add_sorts_on_typ Ts =
blanchet@43263
   661
  [] |> level_of_type_sys type_sys <> No_Types ? fold add_sorts_on_typ Ts
blanchet@41137
   662
blanchet@42534
   663
fun mk_aconns c phis =
blanchet@42534
   664
  let val (phis', phi') = split_last phis in
blanchet@42534
   665
    fold_rev (mk_aconn c) phis' phi'
blanchet@42534
   666
  end
blanchet@38282
   667
fun mk_ahorn [] phi = phi
blanchet@42534
   668
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@42522
   669
fun mk_aquant _ [] phi = phi
blanchet@42522
   670
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@42522
   671
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@42522
   672
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38282
   673
blanchet@42522
   674
fun close_universally atom_vars phi =
blanchet@41145
   675
  let
blanchet@41145
   676
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@42526
   677
        formula_vars (map fst xs @ bounds) phi
blanchet@41145
   678
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@42522
   679
      | formula_vars bounds (AAtom tm) =
blanchet@42526
   680
        union (op =) (atom_vars tm []
blanchet@42526
   681
                      |> filter_out (member (op =) bounds o fst))
blanchet@42522
   682
  in mk_aquant AForall (formula_vars [] phi []) phi end
blanchet@42522
   683
blanchet@42531
   684
fun combterm_vars (CombApp (tm1, tm2)) = fold combterm_vars [tm1, tm2]
blanchet@42522
   685
  | combterm_vars (CombConst _) = I
blanchet@42574
   686
  | combterm_vars (CombVar (name, T)) = insert (op =) (name, SOME T)
blanchet@42674
   687
fun close_combformula_universally phi = close_universally combterm_vars phi
blanchet@42522
   688
blanchet@42522
   689
fun term_vars (ATerm (name as (s, _), tms)) =
blanchet@42998
   690
  is_tptp_variable s ? insert (op =) (name, NONE) #> fold term_vars tms
blanchet@42674
   691
fun close_formula_universally phi = close_universally term_vars phi
blanchet@41145
   692
blanchet@42994
   693
val homo_infinite_type_name = @{type_name ind} (* any infinite type *)
blanchet@42994
   694
val homo_infinite_type = Type (homo_infinite_type_name, [])
blanchet@42994
   695
blanchet@43178
   696
fun fo_term_from_typ format type_sys =
blanchet@42994
   697
  let
blanchet@42994
   698
    fun term (Type (s, Ts)) =
blanchet@43178
   699
      ATerm (case (is_setting_higher_order format type_sys, s) of
blanchet@42994
   700
               (true, @{type_name bool}) => `I tptp_bool_type
blanchet@42994
   701
             | (true, @{type_name fun}) => `I tptp_fun_type
blanchet@43178
   702
             | _ => if s = homo_infinite_type_name andalso
blanchet@43178
   703
                       (format = TFF orelse format = THF) then
blanchet@43178
   704
                      `I tptp_individual_type
blanchet@43178
   705
                    else
blanchet@43178
   706
                      `make_fixed_type_const s,
blanchet@42994
   707
             map term Ts)
blanchet@42994
   708
    | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
blanchet@42994
   709
    | term (TVar ((x as (s, _)), _)) =
blanchet@42994
   710
      ATerm ((make_schematic_type_var x, s), [])
blanchet@42994
   711
  in term end
blanchet@42562
   712
blanchet@43401
   713
fun fo_term_for_type_arg format type_sys T =
blanchet@43401
   714
  if T = dummyT then NONE else SOME (fo_term_from_typ format type_sys T)
blanchet@43401
   715
blanchet@42562
   716
(* This shouldn't clash with anything else. *)
blanchet@42542
   717
val mangled_type_sep = "\000"
blanchet@42542
   718
blanchet@42562
   719
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@42562
   720
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@42761
   721
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@42761
   722
    ^ ")"
blanchet@42542
   723
blanchet@42998
   724
val bool_atype = AType (`I tptp_bool_type)
blanchet@42998
   725
blanchet@43085
   726
fun make_simple_type s =
blanchet@43085
   727
  if s = tptp_bool_type orelse s = tptp_fun_type orelse
blanchet@43085
   728
     s = tptp_individual_type then
blanchet@43085
   729
    s
blanchet@43085
   730
  else
blanchet@43085
   731
    simple_type_prefix ^ ascii_of s
blanchet@43085
   732
blanchet@43178
   733
fun ho_type_from_fo_term format type_sys pred_sym ary =
blanchet@42963
   734
  let
blanchet@42963
   735
    fun to_atype ty =
blanchet@42963
   736
      AType ((make_simple_type (generic_mangled_type_name fst ty),
blanchet@42963
   737
              generic_mangled_type_name snd ty))
blanchet@42963
   738
    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
blanchet@42998
   739
    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
blanchet@42994
   740
      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
blanchet@42994
   741
    fun to_ho (ty as ATerm ((s, _), tys)) =
blanchet@42994
   742
      if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
blanchet@43178
   743
  in if is_setting_higher_order format type_sys then to_ho else to_fo ary end
blanchet@42963
   744
blanchet@43178
   745
fun mangled_type format type_sys pred_sym ary =
blanchet@43178
   746
  ho_type_from_fo_term format type_sys pred_sym ary
blanchet@43178
   747
  o fo_term_from_typ format type_sys
blanchet@42963
   748
blanchet@43178
   749
fun mangled_const_name format type_sys T_args (s, s') =
blanchet@42963
   750
  let
blanchet@43401
   751
    val ty_args = T_args |> map_filter (fo_term_for_type_arg format type_sys)
blanchet@42963
   752
    fun type_suffix f g =
blanchet@42963
   753
      fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@42963
   754
                o generic_mangled_type_name f) ty_args ""
blanchet@42963
   755
  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
blanchet@42542
   756
blanchet@42542
   757
val parse_mangled_ident =
blanchet@42542
   758
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@42542
   759
blanchet@42542
   760
fun parse_mangled_type x =
blanchet@42542
   761
  (parse_mangled_ident
blanchet@42542
   762
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@42542
   763
                    [] >> ATerm) x
blanchet@42542
   764
and parse_mangled_types x =
blanchet@42542
   765
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@42542
   766
blanchet@42542
   767
fun unmangled_type s =
blanchet@42542
   768
  s |> suffix ")" |> raw_explode
blanchet@42542
   769
    |> Scan.finite Symbol.stopper
blanchet@42542
   770
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@42542
   771
                                                quote s)) parse_mangled_type))
blanchet@42542
   772
    |> fst
blanchet@42542
   773
blanchet@42561
   774
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@42542
   775
fun unmangled_const s =
blanchet@42542
   776
  let val ss = space_explode mangled_type_sep s in
blanchet@42542
   777
    (hd ss, map unmangled_type (tl ss))
blanchet@42542
   778
  end
blanchet@42542
   779
blanchet@43017
   780
fun introduce_proxies format type_sys =
blanchet@42568
   781
  let
blanchet@43017
   782
    fun intro top_level (CombApp (tm1, tm2)) =
blanchet@43017
   783
        CombApp (intro top_level tm1, intro false tm2)
blanchet@43017
   784
      | intro top_level (CombConst (name as (s, _), T, T_args)) =
blanchet@42570
   785
        (case proxify_const s of
blanchet@43159
   786
           SOME proxy_base =>
blanchet@43000
   787
           if top_level orelse is_setting_higher_order format type_sys then
blanchet@43000
   788
             case (top_level, s) of
blanchet@43000
   789
               (_, "c_False") => (`I tptp_false, [])
blanchet@43000
   790
             | (_, "c_True") => (`I tptp_true, [])
blanchet@43000
   791
             | (false, "c_Not") => (`I tptp_not, [])
blanchet@43000
   792
             | (false, "c_conj") => (`I tptp_and, [])
blanchet@43000
   793
             | (false, "c_disj") => (`I tptp_or, [])
blanchet@43000
   794
             | (false, "c_implies") => (`I tptp_implies, [])
blanchet@43000
   795
             | (false, s) =>
blanchet@43017
   796
               if is_tptp_equal s then (`I tptp_equal, [])
blanchet@43017
   797
               else (proxy_base |>> prefix const_prefix, T_args)
blanchet@43000
   798
             | _ => (name, [])
blanchet@42569
   799
           else
blanchet@42574
   800
             (proxy_base |>> prefix const_prefix, T_args)
blanchet@42574
   801
          | NONE => (name, T_args))
blanchet@42574
   802
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43017
   803
      | intro _ tm = tm
blanchet@43017
   804
  in intro true end
blanchet@42568
   805
blanchet@42994
   806
fun combformula_from_prop thy format type_sys eq_as_iff =
blanchet@38282
   807
  let
blanchet@42568
   808
    fun do_term bs t atomic_types =
blanchet@41140
   809
      combterm_from_term thy bs (Envir.eta_contract t)
blanchet@42994
   810
      |>> (introduce_proxies format type_sys #> AAtom)
blanchet@42568
   811
      ||> union (op =) atomic_types
blanchet@38282
   812
    fun do_quant bs q s T t' =
wenzelm@43324
   813
      let val s = singleton (Name.variant_list (map fst bs)) s in
blanchet@38518
   814
        do_formula ((s, T) :: bs) t'
blanchet@42562
   815
        #>> mk_aquant q [(`make_bound_var s, SOME T)]
blanchet@38518
   816
      end
blanchet@38282
   817
    and do_conn bs c t1 t2 =
blanchet@43198
   818
      do_formula bs t1 ##>> do_formula bs t2 #>> uncurry (mk_aconn c)
blanchet@38282
   819
    and do_formula bs t =
blanchet@38282
   820
      case t of
blanchet@43096
   821
        @{const Trueprop} $ t1 => do_formula bs t1
blanchet@43096
   822
      | @{const Not} $ t1 => do_formula bs t1 #>> mk_anot
blanchet@38282
   823
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38282
   824
        do_quant bs AForall s T t'
blanchet@38282
   825
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38282
   826
        do_quant bs AExists s T t'
haftmann@38795
   827
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@38795
   828
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@38786
   829
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@38864
   830
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@41140
   831
        if eq_as_iff then do_conn bs AIff t1 t2 else do_term bs t
blanchet@41140
   832
      | _ => do_term bs t
blanchet@38282
   833
  in do_formula [] end
blanchet@38282
   834
blanchet@43264
   835
fun presimplify_term _ [] t = t
blanchet@43264
   836
  | presimplify_term ctxt presimp_consts t =
blanchet@43264
   837
    t |> exists_Const (member (op =) presimp_consts o fst) t
blanchet@43264
   838
         ? (Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
blanchet@43264
   839
            #> Meson.presimplify ctxt
blanchet@43264
   840
            #> prop_of)
blanchet@38282
   841
wenzelm@41491
   842
fun concealed_bound_name j = sledgehammer_weak_prefix ^ string_of_int j
blanchet@38282
   843
fun conceal_bounds Ts t =
blanchet@38282
   844
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38282
   845
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38282
   846
fun reveal_bounds Ts =
blanchet@38282
   847
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38282
   848
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38282
   849
blanchet@43265
   850
fun is_fun_equality (@{const_name HOL.eq},
blanchet@43265
   851
                     Type (_, [Type (@{type_name fun}, _), _])) = true
blanchet@43265
   852
  | is_fun_equality _ = false
blanchet@43265
   853
blanchet@42747
   854
fun extensionalize_term ctxt t =
blanchet@43265
   855
  if exists_Const is_fun_equality t then
blanchet@43265
   856
    let val thy = Proof_Context.theory_of ctxt in
blanchet@43265
   857
      t |> cterm_of thy |> Meson.extensionalize_conv ctxt
blanchet@43265
   858
        |> prop_of |> Logic.dest_equals |> snd
blanchet@43265
   859
    end
blanchet@43265
   860
  else
blanchet@43265
   861
    t
blanchet@38608
   862
blanchet@38282
   863
fun introduce_combinators_in_term ctxt kind t =
wenzelm@42361
   864
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38491
   865
    if Meson.is_fol_term thy t then
blanchet@38491
   866
      t
blanchet@38491
   867
    else
blanchet@38491
   868
      let
blanchet@38491
   869
        fun aux Ts t =
blanchet@38491
   870
          case t of
blanchet@38491
   871
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38491
   872
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38491
   873
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38652
   874
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@38652
   875
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@38491
   876
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38491
   877
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38652
   878
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@38652
   879
            aux Ts (t0 $ eta_expand Ts t1 1)
haftmann@38795
   880
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38795
   881
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38786
   882
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@38864
   883
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@38491
   884
              $ t1 $ t2 =>
blanchet@38491
   885
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@38491
   886
          | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38491
   887
                   t
blanchet@38491
   888
                 else
blanchet@38491
   889
                   t |> conceal_bounds Ts
blanchet@38491
   890
                     |> Envir.eta_contract
blanchet@38491
   891
                     |> cterm_of thy
blanchet@39890
   892
                     |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@38491
   893
                     |> prop_of |> Logic.dest_equals |> snd
blanchet@38491
   894
                     |> reveal_bounds Ts
blanchet@39370
   895
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@38491
   896
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@38491
   897
      handle THM _ =>
blanchet@38491
   898
             (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38613
   899
             if kind = Conjecture then HOLogic.false_const
blanchet@38613
   900
             else HOLogic.true_const
blanchet@38491
   901
  end
blanchet@38282
   902
blanchet@38282
   903
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@42353
   904
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38282
   905
fun freeze_term t =
blanchet@38282
   906
  let
blanchet@38282
   907
    fun aux (t $ u) = aux t $ aux u
blanchet@38282
   908
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38282
   909
      | aux (Var ((s, i), T)) =
blanchet@38282
   910
        Free (sledgehammer_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38282
   911
      | aux t = t
blanchet@38282
   912
  in t |> exists_subterm is_Var t ? aux end
blanchet@38282
   913
blanchet@43264
   914
fun preprocess_prop ctxt presimp_consts kind t =
blanchet@38282
   915
  let
wenzelm@42361
   916
    val thy = Proof_Context.theory_of ctxt
blanchet@38608
   917
    val t = t |> Envir.beta_eta_contract
blanchet@42944
   918
              |> transform_elim_prop
blanchet@41211
   919
              |> Object_Logic.atomize_term thy
blanchet@42563
   920
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@43096
   921
  in
blanchet@43096
   922
    t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@43096
   923
      |> Raw_Simplifier.rewrite_term thy (Meson.unfold_set_const_simps ctxt) []
blanchet@43096
   924
      |> extensionalize_term ctxt
blanchet@43264
   925
      |> presimplify_term ctxt presimp_consts
blanchet@43120
   926
      |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@43096
   927
      |> introduce_combinators_in_term ctxt kind
blanchet@43096
   928
  end
blanchet@43096
   929
blanchet@43096
   930
(* making fact and conjecture formulas *)
blanchet@43096
   931
fun make_formula thy format type_sys eq_as_iff name loc kind t =
blanchet@43096
   932
  let
blanchet@42962
   933
    val (combformula, atomic_types) =
blanchet@42994
   934
      combformula_from_prop thy format type_sys eq_as_iff t []
blanchet@38282
   935
  in
blanchet@42640
   936
    {name = name, locality = loc, kind = kind, combformula = combformula,
blanchet@42562
   937
     atomic_types = atomic_types}
blanchet@38282
   938
  end
blanchet@38282
   939
blanchet@43295
   940
fun make_fact ctxt format type_sys eq_as_iff preproc presimp_consts
blanchet@42994
   941
              ((name, loc), t) =
blanchet@43096
   942
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43295
   943
    case t |> preproc ? preprocess_prop ctxt presimp_consts Axiom
blanchet@43295
   944
           |> make_formula thy format type_sys (eq_as_iff andalso format <> CNF)
blanchet@43295
   945
                           name loc Axiom of
blanchet@43295
   946
      formula as {combformula = AAtom (CombConst ((s, _), _, _)), ...} =>
blanchet@43096
   947
      if s = tptp_true then NONE else SOME formula
blanchet@43295
   948
    | formula => SOME formula
blanchet@43096
   949
  end
blanchet@42561
   950
blanchet@43264
   951
fun make_conjecture ctxt format prem_kind type_sys preproc presimp_consts ts =
blanchet@43096
   952
  let
blanchet@43096
   953
    val thy = Proof_Context.theory_of ctxt
blanchet@43096
   954
    val last = length ts - 1
blanchet@43096
   955
  in
blanchet@42709
   956
    map2 (fn j => fn t =>
blanchet@42709
   957
             let
blanchet@42709
   958
               val (kind, maybe_negate) =
blanchet@42709
   959
                 if j = last then
blanchet@42709
   960
                   (Conjecture, I)
blanchet@42709
   961
                 else
blanchet@42709
   962
                   (prem_kind,
blanchet@42709
   963
                    if prem_kind = Conjecture then update_combformula mk_anot
blanchet@42709
   964
                    else I)
blanchet@42709
   965
              in
blanchet@43264
   966
                t |> preproc ?
blanchet@43264
   967
                     (preprocess_prop ctxt presimp_consts kind #> freeze_term)
blanchet@43193
   968
                  |> make_formula thy format type_sys (format <> CNF)
blanchet@43293
   969
                                  (string_of_int j) Local kind
blanchet@42962
   970
                  |> maybe_negate
blanchet@42709
   971
              end)
blanchet@38613
   972
         (0 upto last) ts
blanchet@38613
   973
  end
blanchet@38282
   974
blanchet@42682
   975
(** Finite and infinite type inference **)
blanchet@42682
   976
blanchet@42886
   977
fun deep_freeze_atyp (TVar (_, S)) = TFree ("v", S)
blanchet@42886
   978
  | deep_freeze_atyp T = T
blanchet@42886
   979
val deep_freeze_type = map_atyps deep_freeze_atyp
blanchet@42886
   980
blanchet@42682
   981
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@42682
   982
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@42682
   983
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@42682
   984
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@42682
   985
blanchet@42886
   986
fun should_encode_type ctxt (nonmono_Ts as _ :: _) _ T =
blanchet@42886
   987
    exists (curry (type_instance ctxt) (deep_freeze_type T)) nonmono_Ts
blanchet@42836
   988
  | should_encode_type _ _ All_Types _ = true
blanchet@43572
   989
  | should_encode_type ctxt _ Fin_Nonmono_Types T =
blanchet@43572
   990
    is_type_surely_finite ctxt false T
blanchet@42682
   991
  | should_encode_type _ _ _ _ = false
blanchet@42682
   992
blanchet@42837
   993
fun should_predicate_on_type ctxt nonmono_Ts (Preds (_, level, heaviness))
blanchet@42834
   994
                             should_predicate_on_var T =
blanchet@43128
   995
    (heaviness = Heavyweight orelse should_predicate_on_var ()) andalso
blanchet@42878
   996
    should_encode_type ctxt nonmono_Ts level T
blanchet@42834
   997
  | should_predicate_on_type _ _ _ _ _ = false
blanchet@42682
   998
blanchet@42836
   999
fun is_var_or_bound_var (CombConst ((s, _), _, _)) =
blanchet@42836
  1000
    String.isPrefix bound_var_prefix s
blanchet@42836
  1001
  | is_var_or_bound_var (CombVar _) = true
blanchet@42836
  1002
  | is_var_or_bound_var _ = false
blanchet@42836
  1003
blanchet@43361
  1004
datatype tag_site =
blanchet@43361
  1005
  Top_Level of bool option |
blanchet@43361
  1006
  Eq_Arg of bool option |
blanchet@43361
  1007
  Elsewhere
blanchet@42829
  1008
blanchet@43361
  1009
fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
blanchet@43361
  1010
  | should_tag_with_type ctxt nonmono_Ts (Tags (poly, level, heaviness)) site
blanchet@43361
  1011
                         u T =
blanchet@42837
  1012
    (case heaviness of
blanchet@43128
  1013
       Heavyweight => should_encode_type ctxt nonmono_Ts level T
blanchet@43128
  1014
     | Lightweight =>
blanchet@42836
  1015
       case (site, is_var_or_bound_var u) of
blanchet@43361
  1016
         (Eq_Arg pos, true) =>
blanchet@43361
  1017
         (* The first disjunct prevents a subtle soundness issue explained in
blanchet@43361
  1018
            Blanchette's Ph.D. thesis. See also
blanchet@43361
  1019
            "formula_lines_for_lightweight_tags_sym_decl". *)
blanchet@43361
  1020
         (pos <> SOME false andalso poly = Polymorphic andalso
blanchet@43361
  1021
          level <> All_Types andalso heaviness = Lightweight andalso
blanchet@43361
  1022
          exists (fn T' => type_instance ctxt (T', T)) nonmono_Ts) orelse
blanchet@43361
  1023
         should_encode_type ctxt nonmono_Ts level T
blanchet@42829
  1024
       | _ => false)
blanchet@42829
  1025
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@42682
  1026
blanchet@42994
  1027
fun homogenized_type ctxt nonmono_Ts level =
blanchet@42994
  1028
  let
blanchet@42994
  1029
    val should_encode = should_encode_type ctxt nonmono_Ts level
blanchet@42994
  1030
    fun homo 0 T = if should_encode T then T else homo_infinite_type
blanchet@42994
  1031
      | homo ary (Type (@{type_name fun}, [T1, T2])) =
blanchet@42994
  1032
        homo 0 T1 --> homo (ary - 1) T2
blanchet@42994
  1033
      | homo _ _ = raise Fail "expected function type"
blanchet@42994
  1034
  in homo end
blanchet@42682
  1035
blanchet@42573
  1036
(** "hBOOL" and "hAPP" **)
blanchet@41313
  1037
blanchet@42574
  1038
type sym_info =
blanchet@43064
  1039
  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list}
blanchet@42563
  1040
blanchet@43064
  1041
fun add_combterm_syms_to_table ctxt explicit_apply =
blanchet@42558
  1042
  let
blanchet@43064
  1043
    fun consider_var_arity const_T var_T max_ary =
blanchet@43064
  1044
      let
blanchet@43064
  1045
        fun iter ary T =
blanchet@43210
  1046
          if ary = max_ary orelse type_instance ctxt (var_T, T) orelse
blanchet@43210
  1047
             type_instance ctxt (T, var_T) then
blanchet@43210
  1048
            ary
blanchet@43210
  1049
          else
blanchet@43210
  1050
            iter (ary + 1) (range_type T)
blanchet@43064
  1051
      in iter 0 const_T end
blanchet@43201
  1052
    fun add_var_or_bound_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@43201
  1053
      if explicit_apply = NONE andalso
blanchet@43201
  1054
         (can dest_funT T orelse T = @{typ bool}) then
blanchet@43201
  1055
        let
blanchet@43201
  1056
          val bool_vars' = bool_vars orelse body_type T = @{typ bool}
blanchet@43201
  1057
          fun repair_min_arity {pred_sym, min_ary, max_ary, types} =
blanchet@43201
  1058
            {pred_sym = pred_sym andalso not bool_vars',
blanchet@43213
  1059
             min_ary = fold (fn T' => consider_var_arity T' T) types min_ary,
blanchet@43201
  1060
             max_ary = max_ary, types = types}
blanchet@43201
  1061
          val fun_var_Ts' =
blanchet@43201
  1062
            fun_var_Ts |> can dest_funT T ? insert_type ctxt I T
blanchet@43201
  1063
        in
blanchet@43201
  1064
          if bool_vars' = bool_vars andalso
blanchet@43201
  1065
             pointer_eq (fun_var_Ts', fun_var_Ts) then
blanchet@43201
  1066
            accum
blanchet@43167
  1067
          else
blanchet@43213
  1068
            ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_arity) sym_tab)
blanchet@43201
  1069
        end
blanchet@43201
  1070
      else
blanchet@43201
  1071
        accum
blanchet@43201
  1072
    fun add top_level tm (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@43201
  1073
      let val (head, args) = strip_combterm_comb tm in
blanchet@42558
  1074
        (case head of
blanchet@42563
  1075
           CombConst ((s, _), T, _) =>
blanchet@42558
  1076
           if String.isPrefix bound_var_prefix s then
blanchet@43201
  1077
             add_var_or_bound_var T accum
blanchet@42558
  1078
           else
blanchet@43139
  1079
             let val ary = length args in
blanchet@43201
  1080
               ((bool_vars, fun_var_Ts),
blanchet@43064
  1081
                case Symtab.lookup sym_tab s of
blanchet@43064
  1082
                  SOME {pred_sym, min_ary, max_ary, types} =>
blanchet@43064
  1083
                  let
blanchet@43201
  1084
                    val pred_sym =
blanchet@43201
  1085
                      pred_sym andalso top_level andalso not bool_vars
blanchet@43064
  1086
                    val types' = types |> insert_type ctxt I T
blanchet@43064
  1087
                    val min_ary =
blanchet@43064
  1088
                      if is_some explicit_apply orelse
blanchet@43064
  1089
                         pointer_eq (types', types) then
blanchet@43064
  1090
                        min_ary
blanchet@43064
  1091
                      else
blanchet@43201
  1092
                        fold (consider_var_arity T) fun_var_Ts min_ary
blanchet@43064
  1093
                  in
blanchet@43201
  1094
                    Symtab.update (s, {pred_sym = pred_sym,
blanchet@43064
  1095
                                       min_ary = Int.min (ary, min_ary),
blanchet@43064
  1096
                                       max_ary = Int.max (ary, max_ary),
blanchet@43064
  1097
                                       types = types'})
blanchet@43064
  1098
                                  sym_tab
blanchet@43064
  1099
                  end
blanchet@43064
  1100
                | NONE =>
blanchet@43064
  1101
                  let
blanchet@43201
  1102
                    val pred_sym = top_level andalso not bool_vars
blanchet@43064
  1103
                    val min_ary =
blanchet@43064
  1104
                      case explicit_apply of
blanchet@43064
  1105
                        SOME true => 0
blanchet@43064
  1106
                      | SOME false => ary
blanchet@43201
  1107
                      | NONE => fold (consider_var_arity T) fun_var_Ts ary
blanchet@43064
  1108
                  in
blanchet@43201
  1109
                    Symtab.update_new (s, {pred_sym = pred_sym,
blanchet@43064
  1110
                                           min_ary = min_ary, max_ary = ary,
blanchet@43064
  1111
                                           types = [T]})
blanchet@43064
  1112
                                      sym_tab
blanchet@43064
  1113
                  end)
blanchet@43064
  1114
             end
blanchet@43201
  1115
         | CombVar (_, T) => add_var_or_bound_var T accum
blanchet@43064
  1116
         | _ => accum)
blanchet@43064
  1117
        |> fold (add false) args
blanchet@42558
  1118
      end
blanchet@43064
  1119
  in add true end
blanchet@43064
  1120
fun add_fact_syms_to_table ctxt explicit_apply =
blanchet@43064
  1121
  fact_lift (formula_fold NONE
blanchet@43064
  1122
                          (K (add_combterm_syms_to_table ctxt explicit_apply)))
blanchet@38282
  1123
blanchet@43139
  1124
val default_sym_tab_entries : (string * sym_info) list =
blanchet@43174
  1125
  (prefixed_predicator_name,
blanchet@43139
  1126
   {pred_sym = true, min_ary = 1, max_ary = 1, types = []}) ::
blanchet@42568
  1127
  ([tptp_false, tptp_true]
blanchet@43139
  1128
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = []})) @
blanchet@43139
  1129
  ([tptp_equal, tptp_old_equal]
blanchet@43139
  1130
   |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = []}))
blanchet@41140
  1131
blanchet@43064
  1132
fun sym_table_for_facts ctxt explicit_apply facts =
blanchet@43201
  1133
  ((false, []), Symtab.empty)
blanchet@43201
  1134
  |> fold (add_fact_syms_to_table ctxt explicit_apply) facts |> snd
blanchet@43139
  1135
  |> fold Symtab.update default_sym_tab_entries
blanchet@38282
  1136
blanchet@42558
  1137
fun min_arity_of sym_tab s =
blanchet@42558
  1138
  case Symtab.lookup sym_tab s of
blanchet@42574
  1139
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@42558
  1140
  | NONE =>
blanchet@42558
  1141
    case strip_prefix_and_unascii const_prefix s of
blanchet@42547
  1142
      SOME s =>
blanchet@42570
  1143
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@42966
  1144
        if s = predicator_name then 1
blanchet@42966
  1145
        else if s = app_op_name then 2
blanchet@42966
  1146
        else if s = type_pred_name then 1
blanchet@42557
  1147
        else 0
blanchet@42547
  1148
      end
blanchet@42544
  1149
    | NONE => 0
blanchet@38282
  1150
blanchet@38282
  1151
(* True if the constant ever appears outside of the top-level position in
blanchet@38282
  1152
   literals, or if it appears with different arities (e.g., because of different
blanchet@38282
  1153
   type instantiations). If false, the constant always receives all of its
blanchet@38282
  1154
   arguments and is used as a predicate. *)
blanchet@42558
  1155
fun is_pred_sym sym_tab s =
blanchet@42558
  1156
  case Symtab.lookup sym_tab s of
blanchet@42574
  1157
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@42574
  1158
    pred_sym andalso min_ary = max_ary
blanchet@42558
  1159
  | NONE => false
blanchet@38282
  1160
blanchet@42568
  1161
val predicator_combconst =
blanchet@42966
  1162
  CombConst (`make_fixed_const predicator_name, @{typ "bool => bool"}, [])
blanchet@42568
  1163
fun predicator tm = CombApp (predicator_combconst, tm)
blanchet@42542
  1164
blanchet@42568
  1165
fun introduce_predicators_in_combterm sym_tab tm =
blanchet@42542
  1166
  case strip_combterm_comb tm of
blanchet@42542
  1167
    (CombConst ((s, _), _, _), _) =>
blanchet@42568
  1168
    if is_pred_sym sym_tab s then tm else predicator tm
blanchet@42568
  1169
  | _ => predicator tm
blanchet@42542
  1170
blanchet@42544
  1171
fun list_app head args = fold (curry (CombApp o swap)) args head
blanchet@42544
  1172
blanchet@43130
  1173
val app_op = `make_fixed_const app_op_name
blanchet@43130
  1174
blanchet@42544
  1175
fun explicit_app arg head =
blanchet@42544
  1176
  let
blanchet@42562
  1177
    val head_T = combtyp_of head
blanchet@42693
  1178
    val (arg_T, res_T) = dest_funT head_T
blanchet@42544
  1179
    val explicit_app =
blanchet@43130
  1180
      CombConst (app_op, head_T --> head_T, [arg_T, res_T])
blanchet@42544
  1181
  in list_app explicit_app [head, arg] end
blanchet@42544
  1182
fun list_explicit_app head args = fold explicit_app args head
blanchet@38282
  1183
blanchet@42565
  1184
fun introduce_explicit_apps_in_combterm sym_tab =
blanchet@42544
  1185
  let
blanchet@42544
  1186
    fun aux tm =
blanchet@42544
  1187
      case strip_combterm_comb tm of
blanchet@42544
  1188
        (head as CombConst ((s, _), _, _), args) =>
blanchet@42544
  1189
        args |> map aux
blanchet@42557
  1190
             |> chop (min_arity_of sym_tab s)
blanchet@42544
  1191
             |>> list_app head
blanchet@42544
  1192
             |-> list_explicit_app
blanchet@42544
  1193
      | (head, args) => list_explicit_app head (map aux args)
blanchet@42544
  1194
  in aux end
blanchet@38282
  1195
blanchet@42753
  1196
fun chop_fun 0 T = ([], T)
blanchet@42753
  1197
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@42753
  1198
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@42753
  1199
  | chop_fun _ _ = raise Fail "unexpected non-function"
blanchet@42753
  1200
blanchet@42780
  1201
fun filter_type_args _ _ _ [] = []
blanchet@42780
  1202
  | filter_type_args thy s arity T_args =
blanchet@42834
  1203
    let
blanchet@42834
  1204
      (* will throw "TYPE" for pseudo-constants *)
blanchet@42966
  1205
      val U = if s = app_op_name then
blanchet@42834
  1206
                @{typ "('a => 'b) => 'a => 'b"} |> Logic.varifyT_global
blanchet@42834
  1207
              else
blanchet@42834
  1208
                s |> Sign.the_const_type thy
blanchet@42834
  1209
    in
blanchet@42781
  1210
      case Term.add_tvarsT (U |> chop_fun arity |> snd) [] of
blanchet@42781
  1211
        [] => []
blanchet@42781
  1212
      | res_U_vars =>
blanchet@42781
  1213
        let val U_args = (s, U) |> Sign.const_typargs thy in
blanchet@42781
  1214
          U_args ~~ T_args
blanchet@43401
  1215
          |> map (fn (U, T) =>
blanchet@43401
  1216
                     if member (op =) res_U_vars (dest_TVar U) then T
blanchet@43401
  1217
                     else dummyT)
blanchet@42781
  1218
        end
blanchet@42780
  1219
    end
blanchet@42780
  1220
    handle TYPE _ => T_args
blanchet@42753
  1221
blanchet@43179
  1222
fun enforce_type_arg_policy_in_combterm ctxt format type_sys =
blanchet@42753
  1223
  let
blanchet@42753
  1224
    val thy = Proof_Context.theory_of ctxt
blanchet@42753
  1225
    fun aux arity (CombApp (tm1, tm2)) =
blanchet@42753
  1226
        CombApp (aux (arity + 1) tm1, aux 0 tm2)
blanchet@42753
  1227
      | aux arity (CombConst (name as (s, _), T, T_args)) =
blanchet@43179
  1228
        (case strip_prefix_and_unascii const_prefix s of
blanchet@43179
  1229
           NONE => (name, T_args)
blanchet@43179
  1230
         | SOME s'' =>
blanchet@43179
  1231
           let
blanchet@43179
  1232
             val s'' = invert_const s''
blanchet@43179
  1233
             fun filtered_T_args false = T_args
blanchet@43179
  1234
               | filtered_T_args true = filter_type_args thy s'' arity T_args
blanchet@43179
  1235
           in
blanchet@43179
  1236
             case type_arg_policy type_sys s'' of
blanchet@43179
  1237
               Explicit_Type_Args drop_args =>
blanchet@43179
  1238
               (name, filtered_T_args drop_args)
blanchet@43179
  1239
             | Mangled_Type_Args drop_args =>
blanchet@43179
  1240
               (mangled_const_name format type_sys (filtered_T_args drop_args)
blanchet@43179
  1241
                                   name, [])
blanchet@43179
  1242
             | No_Type_Args => (name, [])
blanchet@43179
  1243
           end)
blanchet@43179
  1244
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@42753
  1245
      | aux _ tm = tm
blanchet@42753
  1246
  in aux 0 end
blanchet@42573
  1247
blanchet@43179
  1248
fun repair_combterm ctxt format type_sys sym_tab =
blanchet@42994
  1249
  not (is_setting_higher_order format type_sys)
blanchet@42994
  1250
  ? (introduce_explicit_apps_in_combterm sym_tab
blanchet@42994
  1251
     #> introduce_predicators_in_combterm sym_tab)
blanchet@43179
  1252
  #> enforce_type_arg_policy_in_combterm ctxt format type_sys
blanchet@43179
  1253
fun repair_fact ctxt format type_sys sym_tab =
blanchet@42701
  1254
  update_combformula (formula_map
blanchet@43179
  1255
      (repair_combterm ctxt format type_sys sym_tab))
blanchet@42573
  1256
blanchet@42573
  1257
(** Helper facts **)
blanchet@42573
  1258
blanchet@43194
  1259
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@43085
  1260
val helper_table =
blanchet@43194
  1261
  [(("COMBI", false), @{thms Meson.COMBI_def}),
blanchet@43194
  1262
   (("COMBK", false), @{thms Meson.COMBK_def}),
blanchet@43194
  1263
   (("COMBB", false), @{thms Meson.COMBB_def}),
blanchet@43194
  1264
   (("COMBC", false), @{thms Meson.COMBC_def}),
blanchet@43194
  1265
   (("COMBS", false), @{thms Meson.COMBS_def}),
blanchet@43194
  1266
   (("fequal", true),
blanchet@43085
  1267
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
blanchet@43085
  1268
       However, this is done so for backward compatibility: Including the
blanchet@43085
  1269
       equality helpers by default in Metis breaks a few existing proofs. *)
blanchet@43194
  1270
    @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@43194
  1271
           fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@43194
  1272
   (("fFalse", false), [@{lemma "~ fFalse" by (unfold fFalse_def) fast}]),
blanchet@43194
  1273
   (("fFalse", true), @{thms True_or_False}),
blanchet@43194
  1274
   (("fTrue", false), [@{lemma "fTrue" by (unfold fTrue_def) fast}]),
blanchet@43194
  1275
   (("fTrue", true), @{thms True_or_False}),
blanchet@43194
  1276
   (("fNot", false),
blanchet@43194
  1277
    @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@43194
  1278
           fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@43194
  1279
   (("fconj", false),
blanchet@43194
  1280
    @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@43194
  1281
        by (unfold fconj_def) fast+}),
blanchet@43194
  1282
   (("fdisj", false),
blanchet@43194
  1283
    @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@43194
  1284
        by (unfold fdisj_def) fast+}),
blanchet@43194
  1285
   (("fimplies", false),
blanchet@43210
  1286
    @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
blanchet@43194
  1287
        by (unfold fimplies_def) fast+}),
blanchet@43194
  1288
   (("If", true), @{thms if_True if_False True_or_False})]
blanchet@43194
  1289
  |> map (apsnd (map zero_var_indexes))
blanchet@43085
  1290
blanchet@43130
  1291
val type_tag = `make_fixed_const type_tag_name
blanchet@43130
  1292
blanchet@43159
  1293
fun type_tag_idempotence_fact () =
blanchet@42573
  1294
  let
blanchet@42573
  1295
    fun var s = ATerm (`I s, [])
blanchet@43159
  1296
    fun tag tm = ATerm (type_tag, [var "T", tm])
blanchet@43207
  1297
    val tagged_a = tag (var "A")
blanchet@42573
  1298
  in
blanchet@43159
  1299
    Formula (type_tag_idempotence_helper_name, Axiom,
blanchet@43207
  1300
             AAtom (ATerm (`I tptp_equal, [tag tagged_a, tagged_a]))
blanchet@42879
  1301
             |> close_formula_universally, simp_info, NONE)
blanchet@42573
  1302
  end
blanchet@42573
  1303
blanchet@43159
  1304
fun should_specialize_helper type_sys t =
blanchet@43159
  1305
  case general_type_arg_policy type_sys of
blanchet@43159
  1306
    Mangled_Type_Args _ => not (null (Term.hidden_polymorphism t))
blanchet@43159
  1307
  | _ => false
blanchet@43159
  1308
blanchet@43064
  1309
fun helper_facts_for_sym ctxt format type_sys (s, {types, ...} : sym_info) =
blanchet@42573
  1310
  case strip_prefix_and_unascii const_prefix s of
blanchet@42573
  1311
    SOME mangled_s =>
blanchet@42573
  1312
    let
blanchet@42573
  1313
      val thy = Proof_Context.theory_of ctxt
blanchet@42573
  1314
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@43159
  1315
      fun dub_and_inst needs_fairly_sound (th, j) =
blanchet@43159
  1316
        ((unmangled_s ^ "_" ^ string_of_int j ^
blanchet@43159
  1317
          (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
blanchet@42893
  1318
          (if needs_fairly_sound then typed_helper_suffix
blanchet@42881
  1319
           else untyped_helper_suffix),
blanchet@43421
  1320
          Helper),
blanchet@42573
  1321
         let val t = th |> prop_of in
blanchet@43159
  1322
           t |> should_specialize_helper type_sys t
blanchet@43064
  1323
                ? (case types of
blanchet@43064
  1324
                     [T] => specialize_type thy (invert_const unmangled_s, T)
blanchet@43064
  1325
                   | _ => I)
blanchet@42573
  1326
         end)
blanchet@43159
  1327
      val make_facts =
blanchet@43295
  1328
        map_filter (make_fact ctxt format type_sys false false [])
blanchet@42893
  1329
      val fairly_sound = is_type_sys_fairly_sound type_sys
blanchet@42573
  1330
    in
blanchet@43085
  1331
      helper_table
blanchet@43194
  1332
      |> maps (fn ((helper_s, needs_fairly_sound), ths) =>
blanchet@43159
  1333
                  if helper_s <> unmangled_s orelse
blanchet@42894
  1334
                     (needs_fairly_sound andalso not fairly_sound) then
blanchet@42573
  1335
                    []
blanchet@42573
  1336
                  else
blanchet@42573
  1337
                    ths ~~ (1 upto length ths)
blanchet@43159
  1338
                    |> map (dub_and_inst needs_fairly_sound)
blanchet@43159
  1339
                    |> make_facts)
blanchet@42573
  1340
    end
blanchet@42573
  1341
  | NONE => []
blanchet@42962
  1342
fun helper_facts_for_sym_table ctxt format type_sys sym_tab =
blanchet@42962
  1343
  Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_sys) sym_tab
blanchet@42962
  1344
                  []
blanchet@42573
  1345
blanchet@43085
  1346
(***************************************************************)
blanchet@43085
  1347
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@43085
  1348
(***************************************************************)
blanchet@43085
  1349
blanchet@43085
  1350
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@43085
  1351
blanchet@43085
  1352
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@43085
  1353
blanchet@43085
  1354
(* Remove this trivial type class (FIXME: similar code elsewhere) *)
blanchet@43085
  1355
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
blanchet@43085
  1356
blanchet@43093
  1357
fun classes_of_terms get_Ts =
blanchet@43121
  1358
  map (map snd o get_Ts)
blanchet@43093
  1359
  #> List.foldl add_classes Symtab.empty
blanchet@43093
  1360
  #> delete_type #> Symtab.keys
blanchet@43085
  1361
blanchet@43093
  1362
val tfree_classes_of_terms = classes_of_terms OldTerm.term_tfrees
blanchet@43093
  1363
val tvar_classes_of_terms = classes_of_terms OldTerm.term_tvars
blanchet@43085
  1364
blanchet@43622
  1365
fun fold_type_constrs f (Type (s, Ts)) x =
blanchet@43622
  1366
    fold (fold_type_constrs f) Ts (f (s, x))
blanchet@43189
  1367
  | fold_type_constrs _ _ x = x
blanchet@43085
  1368
blanchet@43085
  1369
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
blanchet@43189
  1370
fun add_type_constrs_in_term thy =
blanchet@43085
  1371
  let
blanchet@43188
  1372
    fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@43181
  1373
      | add (t $ u) = add t #> add u
blanchet@43188
  1374
      | add (Const (x as (s, _))) =
blanchet@43188
  1375
        if String.isPrefix skolem_const_prefix s then I
blanchet@43189
  1376
        else x |> Sign.const_typargs thy |> fold (fold_type_constrs set_insert)
blanchet@43181
  1377
      | add (Abs (_, _, u)) = add u
blanchet@43181
  1378
      | add _ = I
blanchet@43181
  1379
  in add end
blanchet@43085
  1380
blanchet@43189
  1381
fun type_constrs_of_terms thy ts =
blanchet@43189
  1382
  Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
blanchet@43085
  1383
blanchet@43096
  1384
fun translate_formulas ctxt format prem_kind type_sys preproc hyp_ts concl_t
blanchet@43214
  1385
                       facts =
blanchet@42573
  1386
  let
blanchet@42573
  1387
    val thy = Proof_Context.theory_of ctxt
blanchet@43222
  1388
    val fact_ts = facts |> map snd
blanchet@43264
  1389
    val presimp_consts = Meson.presimplified_consts ctxt
blanchet@43295
  1390
    val make_fact = make_fact ctxt format type_sys true preproc presimp_consts
blanchet@42573
  1391
    val (facts, fact_names) =
blanchet@43264
  1392
      facts |> map (fn (name, t) => (name, t) |> make_fact |> rpair name)
blanchet@43214
  1393
            |> map_filter (try (apfst the))
blanchet@43214
  1394
            |> ListPair.unzip
blanchet@42573
  1395
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@42573
  1396
       boost an ATP's performance (for some reason). *)
blanchet@43192
  1397
    val hyp_ts =
blanchet@43192
  1398
      hyp_ts
blanchet@43192
  1399
      |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
blanchet@42573
  1400
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@42573
  1401
    val all_ts = goal_t :: fact_ts
blanchet@42573
  1402
    val subs = tfree_classes_of_terms all_ts
blanchet@42573
  1403
    val supers = tvar_classes_of_terms all_ts
blanchet@43189
  1404
    val tycons = type_constrs_of_terms thy all_ts
blanchet@42994
  1405
    val conjs =
blanchet@43096
  1406
      hyp_ts @ [concl_t]
blanchet@43264
  1407
      |> make_conjecture ctxt format prem_kind type_sys preproc presimp_consts
blanchet@42573
  1408
    val (supers', arity_clauses) =
blanchet@42589
  1409
      if level_of_type_sys type_sys = No_Types then ([], [])
blanchet@42573
  1410
      else make_arity_clauses thy tycons supers
blanchet@42573
  1411
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@42573
  1412
  in
blanchet@42573
  1413
    (fact_names |> map single, (conjs, facts, class_rel_clauses, arity_clauses))
blanchet@42573
  1414
  end
blanchet@42573
  1415
blanchet@42573
  1416
fun fo_literal_from_type_literal (TyLitVar (class, name)) =
blanchet@42573
  1417
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@42573
  1418
  | fo_literal_from_type_literal (TyLitFree (class, name)) =
blanchet@42573
  1419
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@42573
  1420
blanchet@42573
  1421
fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@42573
  1422
blanchet@43130
  1423
val type_pred = `make_fixed_const type_pred_name
blanchet@43130
  1424
blanchet@43179
  1425
fun type_pred_combterm ctxt format type_sys T tm =
blanchet@43179
  1426
  CombApp (CombConst (type_pred, T --> @{typ bool}, [T])
blanchet@43179
  1427
           |> enforce_type_arg_policy_in_combterm ctxt format type_sys, tm)
blanchet@42573
  1428
blanchet@43421
  1429
fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
blanchet@43421
  1430
  | is_var_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
blanchet@43000
  1431
    accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
blanchet@43493
  1432
fun should_predicate_on_var_in_formula pos phi (SOME true) name =
blanchet@43421
  1433
    formula_fold pos (is_var_positively_naked_in_term name) phi false
blanchet@43493
  1434
  | should_predicate_on_var_in_formula _ _ _ _ = true
blanchet@42834
  1435
blanchet@43178
  1436
fun mk_const_aterm format type_sys x T_args args =
blanchet@43401
  1437
  ATerm (x, map_filter (fo_term_for_type_arg format type_sys) T_args @ args)
blanchet@42994
  1438
blanchet@43361
  1439
fun tag_with_type ctxt format nonmono_Ts type_sys pos T tm =
blanchet@43130
  1440
  CombConst (type_tag, T --> T, [T])
blanchet@43179
  1441
  |> enforce_type_arg_policy_in_combterm ctxt format type_sys
blanchet@43361
  1442
  |> term_from_combterm ctxt format nonmono_Ts type_sys (Top_Level pos)
blanchet@42829
  1443
  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm]))
blanchet@42962
  1444
and term_from_combterm ctxt format nonmono_Ts type_sys =
blanchet@42573
  1445
  let
blanchet@42962
  1446
    fun aux site u =
blanchet@42962
  1447
      let
blanchet@42962
  1448
        val (head, args) = strip_combterm_comb u
blanchet@42962
  1449
        val (x as (s, _), T_args) =
blanchet@42962
  1450
          case head of
blanchet@42962
  1451
            CombConst (name, _, T_args) => (name, T_args)
blanchet@42962
  1452
          | CombVar (name, _) => (name, [])
blanchet@42962
  1453
          | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@43361
  1454
        val (pos, arg_site) =
blanchet@43361
  1455
          case site of
blanchet@43361
  1456
            Top_Level pos =>
blanchet@43361
  1457
            (pos, if is_tptp_equal s then Eq_Arg pos else Elsewhere)
blanchet@43361
  1458
          | Eq_Arg pos => (pos, Elsewhere)
blanchet@43361
  1459
          | Elsewhere => (NONE, Elsewhere)
blanchet@43178
  1460
        val t = mk_const_aterm format type_sys x T_args
blanchet@43178
  1461
                    (map (aux arg_site) args)
blanchet@42962
  1462
        val T = combtyp_of u
blanchet@42962
  1463
      in
blanchet@42962
  1464
        t |> (if should_tag_with_type ctxt nonmono_Ts type_sys site u T then
blanchet@43361
  1465
                tag_with_type ctxt format nonmono_Ts type_sys pos T
blanchet@42962
  1466
              else
blanchet@42962
  1467
                I)
blanchet@42962
  1468
      end
blanchet@42962
  1469
  in aux end
blanchet@42962
  1470
and formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@42962
  1471
                             should_predicate_on_var =
blanchet@42829
  1472
  let
blanchet@43361
  1473
    fun do_term pos =
blanchet@43361
  1474
      term_from_combterm ctxt format nonmono_Ts type_sys (Top_Level pos)
blanchet@42573
  1475
    val do_bound_type =
blanchet@42682
  1476
      case type_sys of
blanchet@42722
  1477
        Simple_Types level =>
blanchet@42994
  1478
        homogenized_type ctxt nonmono_Ts level 0
blanchet@43178
  1479
        #> mangled_type format type_sys false 0 #> SOME
blanchet@42682
  1480
      | _ => K NONE
blanchet@42878
  1481
    fun do_out_of_bound_type pos phi universal (name, T) =
blanchet@42834
  1482
      if should_predicate_on_type ctxt nonmono_Ts type_sys
blanchet@42878
  1483
             (fn () => should_predicate_on_var pos phi universal name) T then
blanchet@42834
  1484
        CombVar (name, T)
blanchet@43179
  1485
        |> type_pred_combterm ctxt format type_sys T
blanchet@43361
  1486
        |> do_term pos |> AAtom |> SOME
blanchet@42573
  1487
      else
blanchet@42573
  1488
        NONE
blanchet@42878
  1489
    fun do_formula pos (AQuant (q, xs, phi)) =
blanchet@42878
  1490
        let
blanchet@42878
  1491
          val phi = phi |> do_formula pos
blanchet@42878
  1492
          val universal = Option.map (q = AExists ? not) pos
blanchet@42878
  1493
        in
blanchet@42834
  1494
          AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@42834
  1495
                                        | SOME T => do_bound_type T)),
blanchet@42834
  1496
                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@42834
  1497
                      (map_filter
blanchet@42834
  1498
                           (fn (_, NONE) => NONE
blanchet@42834
  1499
                             | (s, SOME T) =>
blanchet@42878
  1500
                               do_out_of_bound_type pos phi universal (s, T))
blanchet@42878
  1501
                           xs)
blanchet@42834
  1502
                      phi)
blanchet@42834
  1503
        end
blanchet@42878
  1504
      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
blanchet@43361
  1505
      | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
blanchet@43493
  1506
  in do_formula end
blanchet@42573
  1507
blanchet@43098
  1508
fun bound_tvars type_sys Ts =
blanchet@42727
  1509
  mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
blanchet@43263
  1510
                (type_literals_for_types type_sys add_sorts_on_tvar Ts))
blanchet@42727
  1511
blanchet@42573
  1512
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@42573
  1513
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@42573
  1514
   the remote provers might care. *)
blanchet@43501
  1515
fun formula_line_for_fact ctxt format prefix encode freshen pos nonmono_Ts
blanchet@43501
  1516
        type_sys (j, {name, locality, kind, combformula, atomic_types}) =
blanchet@43501
  1517
  (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name,
blanchet@43493
  1518
   kind,
blanchet@43493
  1519
   combformula
blanchet@43493
  1520
   |> close_combformula_universally
blanchet@43493
  1521
   |> formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43493
  1522
                               should_predicate_on_var_in_formula
blanchet@43501
  1523
                               (if pos then SOME true else NONE)
blanchet@43493
  1524
   |> bound_tvars type_sys atomic_types
blanchet@43493
  1525
   |> close_formula_universally,
blanchet@43493
  1526
   NONE,
blanchet@43493
  1527
   case locality of
blanchet@43493
  1528
     Intro => intro_info
blanchet@43493
  1529
   | Elim => elim_info
blanchet@43493
  1530
   | Simp => simp_info
blanchet@43493
  1531
   | _ => NONE)
blanchet@43493
  1532
  |> Formula
blanchet@42573
  1533
blanchet@43086
  1534
fun formula_line_for_class_rel_clause ({name, subclass, superclass, ...}
blanchet@43086
  1535
                                       : class_rel_clause) =
blanchet@42573
  1536
  let val ty_arg = ATerm (`I "T", []) in
blanchet@42577
  1537
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@42573
  1538
             AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@42573
  1539
                               AAtom (ATerm (superclass, [ty_arg]))])
blanchet@42879
  1540
             |> close_formula_universally, intro_info, NONE)
blanchet@42573
  1541
  end
blanchet@42573
  1542
blanchet@42573
  1543
fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
blanchet@42573
  1544
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@42573
  1545
  | fo_literal_from_arity_literal (TVarLit (c, sort)) =
blanchet@42573
  1546
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@42573
  1547
blanchet@43086
  1548
fun formula_line_for_arity_clause ({name, prem_lits, concl_lits, ...}
blanchet@43086
  1549
                                   : arity_clause) =
blanchet@43495
  1550
  Formula (arity_clause_prefix ^ name, Axiom,
blanchet@42573
  1551
           mk_ahorn (map (formula_from_fo_literal o apfst not
blanchet@42895
  1552
                          o fo_literal_from_arity_literal) prem_lits)
blanchet@42573
  1553
                    (formula_from_fo_literal
blanchet@42895
  1554
                         (fo_literal_from_arity_literal concl_lits))
blanchet@42879
  1555
           |> close_formula_universally, intro_info, NONE)
blanchet@42573
  1556
blanchet@42962
  1557
fun formula_line_for_conjecture ctxt format nonmono_Ts type_sys
blanchet@43098
  1558
        ({name, kind, combformula, atomic_types, ...} : translated_formula) =
blanchet@42577
  1559
  Formula (conjecture_prefix ^ name, kind,
blanchet@42962
  1560
           formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43493
  1561
               should_predicate_on_var_in_formula (SOME false)
blanchet@42939
  1562
               (close_combformula_universally combformula)
blanchet@43098
  1563
           |> bound_tvars type_sys atomic_types
blanchet@42573
  1564
           |> close_formula_universally, NONE, NONE)
blanchet@42573
  1565
blanchet@43098
  1566
fun free_type_literals type_sys ({atomic_types, ...} : translated_formula) =
blanchet@43263
  1567
  atomic_types |> type_literals_for_types type_sys add_sorts_on_tfree
blanchet@42573
  1568
               |> map fo_literal_from_type_literal
blanchet@42573
  1569
blanchet@42573
  1570
fun formula_line_for_free_type j lit =
blanchet@43085
  1571
  Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis,
blanchet@42573
  1572
           formula_from_fo_literal lit, NONE, NONE)
blanchet@43098
  1573
fun formula_lines_for_free_types type_sys facts =
blanchet@42573
  1574
  let
blanchet@43098
  1575
    val litss = map (free_type_literals type_sys) facts
blanchet@42573
  1576
    val lits = fold (union (op =)) litss []
blanchet@42573
  1577
  in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
blanchet@42573
  1578
blanchet@42573
  1579
(** Symbol declarations **)
blanchet@42544
  1580
blanchet@42574
  1581
fun should_declare_sym type_sys pred_sym s =
blanchet@42998
  1582
  is_tptp_user_symbol s andalso not (String.isPrefix bound_var_prefix s) andalso
blanchet@42894
  1583
  (case type_sys of
blanchet@42894
  1584
     Simple_Types _ => true
blanchet@43128
  1585
   | Tags (_, _, Lightweight) => true
blanchet@42894
  1586
   | _ => not pred_sym)
blanchet@38282
  1587
blanchet@42886
  1588
fun sym_decl_table_for_facts ctxt type_sys repaired_sym_tab (conjs, facts) =
blanchet@42574
  1589
  let
blanchet@42698
  1590
    fun add_combterm in_conj tm =
blanchet@42574
  1591
      let val (head, args) = strip_combterm_comb tm in
blanchet@42574
  1592
        (case head of
blanchet@42574
  1593
           CombConst ((s, s'), T, T_args) =>
blanchet@42574
  1594
           let val pred_sym = is_pred_sym repaired_sym_tab s in
blanchet@42574
  1595
             if should_declare_sym type_sys pred_sym s then
blanchet@42576
  1596
               Symtab.map_default (s, [])
blanchet@42886
  1597
                   (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
blanchet@42886
  1598
                                         in_conj))
blanchet@42574
  1599
             else
blanchet@42574
  1600
               I
blanchet@42574
  1601
           end
blanchet@42574
  1602
         | _ => I)
blanchet@42698
  1603
        #> fold (add_combterm in_conj) args
blanchet@42574
  1604
      end
blanchet@42698
  1605
    fun add_fact in_conj =
blanchet@42834
  1606
      fact_lift (formula_fold NONE (K (add_combterm in_conj)))
blanchet@42698
  1607
  in
blanchet@42698
  1608
    Symtab.empty
blanchet@42698
  1609
    |> is_type_sys_fairly_sound type_sys
blanchet@42698
  1610
       ? (fold (add_fact true) conjs #> fold (add_fact false) facts)
blanchet@42698
  1611
  end
blanchet@42533
  1612
blanchet@42685
  1613
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@42685
  1614
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@43572
  1615
fun add_combterm_nonmonotonic_types _ _ _ _ (SOME false) _ = I
blanchet@43572
  1616
  | add_combterm_nonmonotonic_types ctxt level sound locality _
blanchet@43179
  1617
        (CombApp (CombApp (CombConst ((s, _), Type (_, [T, _]), _), tm1),
blanchet@43179
  1618
                           tm2)) =
blanchet@43000
  1619
    (is_tptp_equal s andalso exists is_var_or_bound_var [tm1, tm2] andalso
blanchet@42829
  1620
     (case level of
blanchet@43362
  1621
        Noninf_Nonmono_Types =>
blanchet@43293
  1622
        not (is_locality_global locality) orelse
blanchet@43572
  1623
        not (is_type_surely_infinite ctxt sound T)
blanchet@43572
  1624
      | Fin_Nonmono_Types => is_type_surely_finite ctxt false T
blanchet@42886
  1625
      | _ => true)) ? insert_type ctxt I (deep_freeze_type T)
blanchet@43572
  1626
  | add_combterm_nonmonotonic_types _ _ _ _ _ _ = I
blanchet@43572
  1627
fun add_fact_nonmonotonic_types ctxt level sound
blanchet@43572
  1628
        ({kind, locality, combformula, ...} : translated_formula) =
blanchet@42834
  1629
  formula_fold (SOME (kind <> Conjecture))
blanchet@43572
  1630
               (add_combterm_nonmonotonic_types ctxt level sound locality)
blanchet@43572
  1631
               combformula
blanchet@43572
  1632
fun nonmonotonic_types_for_facts ctxt type_sys sound facts =
blanchet@42829
  1633
  let val level = level_of_type_sys type_sys in
blanchet@43362
  1634
    if level = Noninf_Nonmono_Types orelse level = Fin_Nonmono_Types then
blanchet@43572
  1635
      [] |> fold (add_fact_nonmonotonic_types ctxt level sound) facts
blanchet@42886
  1636
         (* We must add "bool" in case the helper "True_or_False" is added
blanchet@42886
  1637
            later. In addition, several places in the code rely on the list of
blanchet@42886
  1638
            nonmonotonic types not being empty. *)
blanchet@42886
  1639
         |> insert_type ctxt I @{typ bool}
blanchet@42886
  1640
    else
blanchet@42886
  1641
      []
blanchet@42829
  1642
  end
blanchet@42677
  1643
blanchet@42994
  1644
fun decl_line_for_sym ctxt format nonmono_Ts type_sys s
blanchet@42994
  1645
                      (s', T_args, T, pred_sym, ary, _) =
blanchet@42994
  1646
  let
blanchet@43178
  1647
    val (T_arg_Ts, level) =
blanchet@42994
  1648
      case type_sys of
blanchet@43178
  1649
        Simple_Types level => ([], level)
blanchet@43178
  1650
      | _ => (replicate (length T_args) homo_infinite_type, No_Types)
blanchet@42994
  1651
  in
blanchet@42998
  1652
    Decl (sym_decl_prefix ^ s, (s, s'),
blanchet@42994
  1653
          (T_arg_Ts ---> (T |> homogenized_type ctxt nonmono_Ts level ary))
blanchet@43178
  1654
          |> mangled_type format type_sys pred_sym (length T_arg_Ts + ary))
blanchet@42994
  1655
  end
blanchet@42579
  1656
blanchet@43125
  1657
fun formula_line_for_preds_sym_decl ctxt format conj_sym_kind nonmono_Ts
blanchet@43401
  1658
        poly_nonmono_Ts type_sys n s j (s', T_args, T, _, ary, in_conj) =
blanchet@42579
  1659
  let
blanchet@42709
  1660
    val (kind, maybe_negate) =
blanchet@42709
  1661
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@42709
  1662
      else (Axiom, I)
blanchet@42753
  1663
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43399
  1664
    val num_args = length arg_Ts
blanchet@42579
  1665
    val bound_names =
blanchet@43399
  1666
      1 upto num_args |> map (`I o make_bound_var o string_of_int)
blanchet@42829
  1667
    val bounds =
blanchet@42579
  1668
      bound_names ~~ arg_Ts |> map (fn (name, T) => CombConst (name, T, []))
blanchet@43401
  1669
    val sym_needs_arg_types = n > 1 orelse exists (curry (op =) dummyT) T_args
blanchet@43401
  1670
    fun should_keep_arg_type T =
blanchet@43401
  1671
      sym_needs_arg_types orelse
blanchet@43401
  1672
      not (should_predicate_on_type ctxt nonmono_Ts type_sys (K false) T)
blanchet@42579
  1673
    val bound_Ts =
blanchet@43401
  1674
      arg_Ts |> map (fn T => if should_keep_arg_type T then SOME T else NONE)
blanchet@42579
  1675
  in
blanchet@43125
  1676
    Formula (preds_sym_formula_prefix ^ s ^
blanchet@42709
  1677
             (if n > 1 then "_" ^ string_of_int j else ""), kind,
blanchet@42579
  1678
             CombConst ((s, s'), T, T_args)
blanchet@42829
  1679
             |> fold (curry (CombApp o swap)) bounds
blanchet@43179
  1680
             |> type_pred_combterm ctxt format type_sys res_T
blanchet@42963
  1681
             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@43401
  1682
             |> formula_from_combformula ctxt format poly_nonmono_Ts type_sys
blanchet@43493
  1683
                                         (K (K (K (K true)))) (SOME true)
blanchet@43098
  1684
             |> n > 1 ? bound_tvars type_sys (atyps_of T)
blanchet@42709
  1685
             |> close_formula_universally
blanchet@42709
  1686
             |> maybe_negate,
blanchet@42879
  1687
             intro_info, NONE)
blanchet@42579
  1688
  end
blanchet@42579
  1689
blanchet@43129
  1690
fun formula_lines_for_lightweight_tags_sym_decl ctxt format conj_sym_kind
blanchet@43401
  1691
        poly_nonmono_Ts type_sys n s
blanchet@43401
  1692
        (j, (s', T_args, T, pred_sym, ary, in_conj)) =
blanchet@42829
  1693
  let
blanchet@42829
  1694
    val ident_base =
blanchet@43129
  1695
      lightweight_tags_sym_formula_prefix ^ s ^
blanchet@43125
  1696
      (if n > 1 then "_" ^ string_of_int j else "")
blanchet@42852
  1697
    val (kind, maybe_negate) =
blanchet@42852
  1698
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@42852
  1699
      else (Axiom, I)
blanchet@42829
  1700
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@42829
  1701
    val bound_names =
blanchet@42829
  1702
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@42829
  1703
    val bounds = bound_names |> map (fn name => ATerm (name, []))
blanchet@43178
  1704
    val cst = mk_const_aterm format type_sys (s, s') T_args
blanchet@42830
  1705
    val atomic_Ts = atyps_of T
blanchet@42834
  1706
    fun eq tms =
blanchet@42834
  1707
      (if pred_sym then AConn (AIff, map AAtom tms)
blanchet@43000
  1708
       else AAtom (ATerm (`I tptp_equal, tms)))
blanchet@43098
  1709
      |> bound_tvars type_sys atomic_Ts
blanchet@42830
  1710
      |> close_formula_universally
blanchet@42852
  1711
      |> maybe_negate
blanchet@43361
  1712
    (* See also "should_tag_with_type". *)
blanchet@43361
  1713
    fun should_encode T =
blanchet@43401
  1714
      should_encode_type ctxt poly_nonmono_Ts All_Types T orelse
blanchet@43361
  1715
      (case type_sys of
blanchet@43361
  1716
         Tags (Polymorphic, level, Lightweight) =>
blanchet@43361
  1717
         level <> All_Types andalso Monomorph.typ_has_tvars T
blanchet@43361
  1718
       | _ => false)
blanchet@43401
  1719
    val tag_with = tag_with_type ctxt format poly_nonmono_Ts type_sys NONE
blanchet@42829
  1720
    val add_formula_for_res =
blanchet@42829
  1721
      if should_encode res_T then
blanchet@42852
  1722
        cons (Formula (ident_base ^ "_res", kind,
blanchet@42994
  1723
                       eq [tag_with res_T (cst bounds), cst bounds],
blanchet@42879
  1724
                       simp_info, NONE))
blanchet@42829
  1725
      else
blanchet@42829
  1726
        I
blanchet@42829
  1727
    fun add_formula_for_arg k =
blanchet@42829
  1728
      let val arg_T = nth arg_Ts k in
blanchet@42829
  1729
        if should_encode arg_T then
blanchet@42829
  1730
          case chop k bounds of
blanchet@42829
  1731
            (bounds1, bound :: bounds2) =>
blanchet@42852
  1732
            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
blanchet@42994
  1733
                           eq [cst (bounds1 @ tag_with arg_T bound :: bounds2),
blanchet@42994
  1734
                               cst bounds],
blanchet@42879
  1735
                           simp_info, NONE))
blanchet@42829
  1736
          | _ => raise Fail "expected nonempty tail"
blanchet@42829
  1737
        else
blanchet@42829
  1738
          I
blanchet@42829
  1739
      end
blanchet@42829
  1740
  in
blanchet@42834
  1741
    [] |> not pred_sym ? add_formula_for_res
blanchet@42829
  1742
       |> fold add_formula_for_arg (ary - 1 downto 0)
blanchet@42829
  1743
  end
blanchet@42829
  1744
blanchet@42836
  1745
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@42836
  1746
blanchet@43401
  1747
fun problem_lines_for_sym_decls ctxt format conj_sym_kind nonmono_Ts
blanchet@43401
  1748
                                poly_nonmono_Ts type_sys (s, decls) =
blanchet@42998
  1749
  case type_sys of
blanchet@42998
  1750
    Simple_Types _ =>
blanchet@42998
  1751
    decls |> map (decl_line_for_sym ctxt format nonmono_Ts type_sys s)
blanchet@42998
  1752
  | Preds _ =>
blanchet@42998
  1753
    let
blanchet@42998
  1754
      val decls =
blanchet@42998
  1755
        case decls of
blanchet@42998
  1756
          decl :: (decls' as _ :: _) =>
blanchet@42998
  1757
          let val T = result_type_of_decl decl in
blanchet@42998
  1758
            if forall (curry (type_instance ctxt o swap) T
blanchet@42998
  1759
                       o result_type_of_decl) decls' then
blanchet@42998
  1760
              [decl]
blanchet@42998
  1761
            else
blanchet@42998
  1762
              decls
blanchet@42998
  1763
          end
blanchet@42998
  1764
        | _ => decls
blanchet@42998
  1765
      val n = length decls
blanchet@42998
  1766
      val decls =
blanchet@43401
  1767
        decls |> filter (should_predicate_on_type ctxt poly_nonmono_Ts type_sys
blanchet@43401
  1768
                                                  (K true)
blanchet@43401
  1769
                         o result_type_of_decl)
blanchet@42998
  1770
    in
blanchet@42998
  1771
      (0 upto length decls - 1, decls)
blanchet@43125
  1772
      |-> map2 (formula_line_for_preds_sym_decl ctxt format conj_sym_kind
blanchet@43401
  1773
                   nonmono_Ts poly_nonmono_Ts type_sys n s)
blanchet@42998
  1774
    end
blanchet@42998
  1775
  | Tags (_, _, heaviness) =>
blanchet@42998
  1776
    (case heaviness of
blanchet@43128
  1777
       Heavyweight => []
blanchet@43128
  1778
     | Lightweight =>
blanchet@42998
  1779
       let val n = length decls in
blanchet@42998
  1780
         (0 upto n - 1 ~~ decls)
blanchet@43129
  1781
         |> maps (formula_lines_for_lightweight_tags_sym_decl ctxt format
blanchet@43401
  1782
                      conj_sym_kind poly_nonmono_Ts type_sys n s)
blanchet@42998
  1783
       end)
blanchet@42579
  1784
blanchet@42956
  1785
fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind nonmono_Ts
blanchet@43401
  1786
                                     poly_nonmono_Ts type_sys sym_decl_tab =
blanchet@42998
  1787
  sym_decl_tab
blanchet@42998
  1788
  |> Symtab.dest
blanchet@42998
  1789
  |> sort_wrt fst
blanchet@42998
  1790
  |> rpair []
blanchet@42998
  1791
  |-> fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
blanchet@43401
  1792
                             nonmono_Ts poly_nonmono_Ts type_sys)
blanchet@42543
  1793
blanchet@43185
  1794
fun needs_type_tag_idempotence (Tags (poly, level, heaviness)) =
blanchet@43185
  1795
    poly <> Mangled_Monomorphic andalso
blanchet@43185
  1796
    ((level = All_Types andalso heaviness = Lightweight) orelse
blanchet@43362
  1797
     level = Noninf_Nonmono_Types orelse level = Fin_Nonmono_Types)
blanchet@43159
  1798
  | needs_type_tag_idempotence _ = false
blanchet@42831
  1799
blanchet@42939
  1800
fun offset_of_heading_in_problem _ [] j = j
blanchet@42939
  1801
  | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
blanchet@42939
  1802
    if heading = needle then j
blanchet@42939
  1803
    else offset_of_heading_in_problem needle problem (j + length lines)
blanchet@42939
  1804
blanchet@42998
  1805
val implicit_declsN = "Should-be-implicit typings"
blanchet@42998
  1806
val explicit_declsN = "Explicit typings"
blanchet@41157
  1807
val factsN = "Relevant facts"
blanchet@41157
  1808
val class_relsN = "Class relationships"
blanchet@42543
  1809
val aritiesN = "Arities"
blanchet@41157
  1810
val helpersN = "Helper facts"
blanchet@41157
  1811
val conjsN = "Conjectures"
blanchet@41313
  1812
val free_typesN = "Type variables"
blanchet@41157
  1813
blanchet@43259
  1814
val explicit_apply = NONE (* for experimental purposes *)
blanchet@43259
  1815
blanchet@43572
  1816
fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_sys sound
blanchet@43493
  1817
        exporter readable_names preproc hyp_ts concl_t facts =
blanchet@38282
  1818
  let
blanchet@43101
  1819
    val (format, type_sys) = choose_format [format] type_sys
blanchet@41313
  1820
    val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
blanchet@43096
  1821
      translate_formulas ctxt format prem_kind type_sys preproc hyp_ts concl_t
blanchet@43096
  1822
                         facts
blanchet@43064
  1823
    val sym_tab = conjs @ facts |> sym_table_for_facts ctxt explicit_apply
blanchet@43572
  1824
    val nonmono_Ts =
blanchet@43572
  1825
      conjs @ facts |> nonmonotonic_types_for_facts ctxt type_sys sound
blanchet@43179
  1826
    val repair = repair_fact ctxt format type_sys sym_tab
blanchet@42682
  1827
    val (conjs, facts) = (conjs, facts) |> pairself (map repair)
blanchet@43064
  1828
    val repaired_sym_tab =
blanchet@43064
  1829
      conjs @ facts |> sym_table_for_facts ctxt (SOME false)
blanchet@42573
  1830
    val helpers =
blanchet@42962
  1831
      repaired_sym_tab |> helper_facts_for_sym_table ctxt format type_sys
blanchet@42962
  1832
                       |> map repair
blanchet@43401
  1833
    val poly_nonmono_Ts =
blanchet@43213
  1834
      if null nonmono_Ts orelse nonmono_Ts = [@{typ bool}] orelse
blanchet@42894
  1835
         polymorphism_of_type_sys type_sys <> Polymorphic then
blanchet@42894
  1836
        nonmono_Ts
blanchet@42894
  1837
      else
blanchet@42894
  1838
        [TVar (("'a", 0), HOLogic.typeS)]
blanchet@42680
  1839
    val sym_decl_lines =
blanchet@42731
  1840
      (conjs, helpers @ facts)
blanchet@42886
  1841
      |> sym_decl_table_for_facts ctxt type_sys repaired_sym_tab
blanchet@43401
  1842
      |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind nonmono_Ts
blanchet@43401
  1843
                                               poly_nonmono_Ts type_sys
blanchet@42881
  1844
    val helper_lines =
blanchet@42956
  1845
      0 upto length helpers - 1 ~~ helpers
blanchet@43501
  1846
      |> map (formula_line_for_fact ctxt format helper_prefix I false true
blanchet@43401
  1847
                                    poly_nonmono_Ts type_sys)
blanchet@43159
  1848
      |> (if needs_type_tag_idempotence type_sys then
blanchet@43159
  1849
            cons (type_tag_idempotence_fact ())
blanchet@43159
  1850
          else
blanchet@43159
  1851
            I)
blanchet@42522
  1852
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43039
  1853
       FLOTTER hack. *)
blanchet@38282
  1854
    val problem =
blanchet@42998
  1855
      [(explicit_declsN, sym_decl_lines),
blanchet@42956
  1856
       (factsN,
blanchet@43501
  1857
        map (formula_line_for_fact ctxt format fact_prefix ascii_of
blanchet@43501
  1858
                                   (not exporter) (not exporter) nonmono_Ts
blanchet@43501
  1859
                                   type_sys)
blanchet@42956
  1860
            (0 upto length facts - 1 ~~ facts)),
blanchet@42545
  1861
       (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
blanchet@42545
  1862
       (aritiesN, map formula_line_for_arity_clause arity_clauses),
blanchet@42881
  1863
       (helpersN, helper_lines),
blanchet@42962
  1864
       (conjsN,
blanchet@42962
  1865
        map (formula_line_for_conjecture ctxt format nonmono_Ts type_sys)
blanchet@42962
  1866
            conjs),
blanchet@43098
  1867
       (free_typesN, formula_lines_for_free_types type_sys (facts @ conjs))]
blanchet@42543
  1868
    val problem =
blanchet@42561
  1869
      problem
blanchet@43092
  1870
      |> (case format of
blanchet@43092
  1871
            CNF => ensure_cnf_problem
blanchet@43092
  1872
          | CNF_UEQ => filter_cnf_ueq_problem
blanchet@43092
  1873
          | _ => I)
blanchet@42998
  1874
      |> (if is_format_typed format then
blanchet@42998
  1875
            declare_undeclared_syms_in_atp_problem type_decl_prefix
blanchet@42998
  1876
                                                   implicit_declsN
blanchet@42998
  1877
          else
blanchet@42998
  1878
            I)
blanchet@43092
  1879
    val (problem, pool) = problem |> nice_atp_problem readable_names
blanchet@42881
  1880
    val helpers_offset = offset_of_heading_in_problem helpersN problem 0
blanchet@42881
  1881
    val typed_helpers =
blanchet@42881
  1882
      map_filter (fn (j, {name, ...}) =>
blanchet@42881
  1883
                     if String.isSuffix typed_helper_suffix name then SOME j
blanchet@42881
  1884
                     else NONE)
blanchet@42881
  1885
                 ((helpers_offset + 1 upto helpers_offset + length helpers)
blanchet@42881
  1886
                  ~~ helpers)
blanchet@42778
  1887
    fun add_sym_arity (s, {min_ary, ...} : sym_info) =
blanchet@42755
  1888
      if min_ary > 0 then
blanchet@42755
  1889
        case strip_prefix_and_unascii const_prefix s of
blanchet@42755
  1890
          SOME s => Symtab.insert (op =) (s, min_ary)
blanchet@42755
  1891
        | NONE => I
blanchet@42755
  1892
      else
blanchet@42755
  1893
        I
blanchet@38282
  1894
  in
blanchet@38282
  1895
    (problem,
blanchet@38282
  1896
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@42585
  1897
     offset_of_heading_in_problem conjsN problem 0,
blanchet@42541
  1898
     offset_of_heading_in_problem factsN problem 0,
blanchet@42755
  1899
     fact_names |> Vector.fromList,
blanchet@42881
  1900
     typed_helpers,
blanchet@42755
  1901
     Symtab.empty |> Symtab.fold add_sym_arity sym_tab)
blanchet@38282
  1902
  end
blanchet@38282
  1903
blanchet@41313
  1904
(* FUDGE *)
blanchet@41313
  1905
val conj_weight = 0.0
blanchet@41770
  1906
val hyp_weight = 0.1
blanchet@41770
  1907
val fact_min_weight = 0.2
blanchet@41313
  1908
val fact_max_weight = 1.0
blanchet@42608
  1909
val type_info_default_weight = 0.8
blanchet@41313
  1910
blanchet@41313
  1911
fun add_term_weights weight (ATerm (s, tms)) =
blanchet@42998
  1912
  is_tptp_user_symbol s ? Symtab.default (s, weight)
blanchet@41313
  1913
  #> fold (add_term_weights weight) tms
blanchet@42577
  1914
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@42834
  1915
    formula_fold NONE (K (add_term_weights weight)) phi
blanchet@42528
  1916
  | add_problem_line_weights _ _ = I
blanchet@41313
  1917
blanchet@41313
  1918
fun add_conjectures_weights [] = I
blanchet@41313
  1919
  | add_conjectures_weights conjs =
blanchet@41313
  1920
    let val (hyps, conj) = split_last conjs in
blanchet@41313
  1921
      add_problem_line_weights conj_weight conj
blanchet@41313
  1922
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41313
  1923
    end
blanchet@41313
  1924
blanchet@41313
  1925
fun add_facts_weights facts =
blanchet@41313
  1926
  let
blanchet@41313
  1927
    val num_facts = length facts
blanchet@41313
  1928
    fun weight_of j =
blanchet@41313
  1929
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41313
  1930
                        / Real.fromInt num_facts
blanchet@41313
  1931
  in
blanchet@41313
  1932
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41313
  1933
    |> fold (uncurry add_problem_line_weights)
blanchet@41313
  1934
  end
blanchet@41313
  1935
blanchet@41313
  1936
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41313
  1937
fun atp_problem_weights problem =
blanchet@42608
  1938
  let val get = these o AList.lookup (op =) problem in
blanchet@42608
  1939
    Symtab.empty
blanchet@42608
  1940
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@42608
  1941
    |> add_facts_weights (get factsN)
blanchet@42608
  1942
    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
blanchet@42998
  1943
            [explicit_declsN, class_relsN, aritiesN]
blanchet@42608
  1944
    |> Symtab.dest
blanchet@42608
  1945
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@42608
  1946
  end
blanchet@41313
  1947
blanchet@38282
  1948
end;