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