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