src/HOL/Tools/ATP/atp_translate.ML
author blanchet
Fri, 18 Nov 2011 11:47:12 +0100
changeset 46441 6d95a66cce00
parent 46439 211a6e6cbc04
child 46650 eb7b74c7a69b
permissions -rw-r--r--
pull variables (Var) out of lambdas, so that the Isabelle theorems closely mirror the Metis lambda-lifted ones
wenzelm@44163
     1
(*  Title:      HOL/Tools/ATP/atp_translate.ML
blanchet@38506
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38506
     3
    Author:     Makarius
blanchet@38506
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38506
     5
blanchet@44734
     6
Translation of HOL to FOL for Metis and Sledgehammer.
blanchet@38506
     7
*)
blanchet@38506
     8
blanchet@43926
     9
signature ATP_TRANSLATE =
blanchet@38506
    10
sig
nik@44535
    11
  type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
blanchet@43977
    12
  type connective = ATP_Problem.connective
blanchet@43977
    13
  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
blanchet@46172
    14
  type atp_format = ATP_Problem.atp_format
blanchet@43580
    15
  type formula_kind = ATP_Problem.formula_kind
blanchet@38506
    16
  type 'a problem = 'a ATP_Problem.problem
blanchet@43926
    17
blanchet@44282
    18
  datatype locality =
blanchet@45651
    19
    General | Helper | Induction | Intro | Elim | Simp | Local | Assum | Chained
blanchet@43484
    20
blanchet@45349
    21
  datatype polymorphism = Polymorphic | Raw_Monomorphic | Mangled_Monomorphic
blanchet@46170
    22
  datatype soundness = Sound_Modulo_Infinity | Sound
blanchet@45673
    23
  datatype granularity = All_Vars | Positively_Naked_Vars | Ghost_Type_Arg_Vars
blanchet@43484
    24
  datatype type_level =
blanchet@45256
    25
    All_Types |
blanchet@45673
    26
    Noninf_Nonmono_Types of soundness * granularity |
blanchet@45673
    27
    Fin_Nonmono_Types of granularity |
blanchet@45256
    28
    Const_Arg_Types |
blanchet@44233
    29
    No_Types
blanchet@45650
    30
  type type_enc
blanchet@43484
    31
blanchet@45351
    32
  val type_tag_idempotence : bool Config.T
blanchet@45351
    33
  val type_tag_arguments : bool Config.T
blanchet@46384
    34
  val no_lamsN : string
blanchet@46384
    35
  val hide_lamsN : string
blanchet@46384
    36
  val lam_liftingN : string
blanchet@44959
    37
  val combinatorsN : string
blanchet@46384
    38
  val hybrid_lamsN : string
blanchet@46384
    39
  val keep_lamsN : string
blanchet@44367
    40
  val schematic_var_prefix : string
blanchet@44367
    41
  val fixed_var_prefix : string
blanchet@44367
    42
  val tvar_prefix : string
blanchet@44367
    43
  val tfree_prefix : string
blanchet@44367
    44
  val const_prefix : string
blanchet@44367
    45
  val type_const_prefix : string
blanchet@44367
    46
  val class_prefix : string
blanchet@46425
    47
  val lam_lifted_prefix : string
blanchet@46425
    48
  val lam_lifted_mono_prefix : string
blanchet@46425
    49
  val lam_lifted_poly_prefix : string
blanchet@43926
    50
  val skolem_const_prefix : string
blanchet@43926
    51
  val old_skolem_const_prefix : string
blanchet@43926
    52
  val new_skolem_const_prefix : string
blanchet@46425
    53
  val combinator_prefix : string
blanchet@43966
    54
  val type_decl_prefix : string
blanchet@43966
    55
  val sym_decl_prefix : string
blanchet@44860
    56
  val guards_sym_formula_prefix : string
blanchet@45255
    57
  val tags_sym_formula_prefix : string
blanchet@40445
    58
  val fact_prefix : string
blanchet@38506
    59
  val conjecture_prefix : string
blanchet@43750
    60
  val helper_prefix : string
blanchet@43966
    61
  val class_rel_clause_prefix : string
blanchet@43966
    62
  val arity_clause_prefix : string
blanchet@43966
    63
  val tfree_clause_prefix : string
blanchet@46425
    64
  val lam_fact_prefix : string
blanchet@43750
    65
  val typed_helper_suffix : string
blanchet@43966
    66
  val untyped_helper_suffix : string
blanchet@44000
    67
  val type_tag_idempotence_helper_name : string
blanchet@43807
    68
  val predicator_name : string
blanchet@43807
    69
  val app_op_name : string
blanchet@45255
    70
  val type_guard_name : string
blanchet@43945
    71
  val type_tag_name : string
blanchet@43803
    72
  val simple_type_prefix : string
blanchet@44015
    73
  val prefixed_predicator_name : string
blanchet@43971
    74
  val prefixed_app_op_name : string
blanchet@43971
    75
  val prefixed_type_tag_name : string
blanchet@44367
    76
  val ascii_of : string -> string
blanchet@44367
    77
  val unascii_of : string -> string
blanchet@46382
    78
  val unprefix_and_unascii : string -> string -> string option
blanchet@44000
    79
  val proxy_table : (string * (string * (thm * (string * string)))) list
blanchet@44000
    80
  val proxify_const : string -> (string * string) option
blanchet@44367
    81
  val invert_const : string -> string
blanchet@44367
    82
  val unproxify_const : string -> string
blanchet@43934
    83
  val new_skolem_var_name_from_const : string -> string
blanchet@44089
    84
  val atp_irrelevant_consts : string list
blanchet@44089
    85
  val atp_schematic_consts_of : term -> typ list Symtab.table
blanchet@44692
    86
  val is_type_enc_higher_order : type_enc -> bool
blanchet@44493
    87
  val polymorphism_of_type_enc : type_enc -> polymorphism
blanchet@44493
    88
  val level_of_type_enc : type_enc -> type_level
blanchet@45256
    89
  val is_type_enc_quasi_sound : type_enc -> bool
blanchet@44493
    90
  val is_type_enc_fairly_sound : type_enc -> bool
blanchet@45639
    91
  val type_enc_from_string : soundness -> string -> type_enc
blanchet@46172
    92
  val adjust_type_enc : atp_format -> type_enc -> type_enc
blanchet@43977
    93
  val mk_aconns :
blanchet@43977
    94
    connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
nik@44535
    95
  val unmangled_const : string -> string * (string, 'b) ho_term list
blanchet@43971
    96
  val unmangled_const_name : string -> string
blanchet@44035
    97
  val helper_table : ((string * bool) * thm list) list
blanchet@46385
    98
  val trans_lams_from_string :
blanchet@46385
    99
    Proof.context -> type_enc -> string -> term list -> term list * term list
blanchet@44372
   100
  val factsN : string
blanchet@40240
   101
  val prepare_atp_problem :
blanchet@46172
   102
    Proof.context -> atp_format -> formula_kind -> formula_kind -> type_enc
blanchet@45256
   103
    -> bool -> string -> bool -> bool -> term list -> term
blanchet@44959
   104
    -> ((string * locality) * term) list
blanchet@46422
   105
    -> string problem * string Symtab.table * (string * locality) list vector
blanchet@46422
   106
       * (string * term) list * int Symtab.table
blanchet@41561
   107
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38506
   108
end;
blanchet@38506
   109
blanchet@43926
   110
structure ATP_Translate : ATP_TRANSLATE =
blanchet@38506
   111
struct
blanchet@38506
   112
blanchet@43926
   113
open ATP_Util
blanchet@38506
   114
open ATP_Problem
blanchet@43926
   115
blanchet@43926
   116
type name = string * string
blanchet@43926
   117
blanchet@45351
   118
val type_tag_idempotence =
blanchet@45411
   119
  Attrib.setup_config_bool @{binding atp_type_tag_idempotence} (K false)
blanchet@45351
   120
val type_tag_arguments =
blanchet@45411
   121
  Attrib.setup_config_bool @{binding atp_type_tag_arguments} (K false)
blanchet@45351
   122
blanchet@46387
   123
val no_lamsN = "no_lams" (* used internally; undocumented *)
blanchet@46384
   124
val hide_lamsN = "hide_lams"
blanchet@46384
   125
val lam_liftingN = "lam_lifting"
blanchet@44959
   126
val combinatorsN = "combinators"
blanchet@46384
   127
val hybrid_lamsN = "hybrid_lams"
blanchet@46384
   128
val keep_lamsN = "keep_lams"
blanchet@44959
   129
blanchet@45480
   130
(* TFF1 is still in development, and it is still unclear whether symbols will be
blanchet@45480
   131
   allowed to have types like "$tType > $o" (i.e., "![A : $tType] : $o"), with
blanchet@46172
   132
   ghost type variables. *)
blanchet@46172
   133
val avoid_first_order_ghost_type_vars = true
blanchet@45480
   134
blanchet@43926
   135
val bound_var_prefix = "B_"
blanchet@45262
   136
val all_bound_var_prefix = "BA_"
blanchet@45262
   137
val exist_bound_var_prefix = "BE_"
blanchet@43926
   138
val schematic_var_prefix = "V_"
blanchet@43926
   139
val fixed_var_prefix = "v_"
blanchet@43926
   140
val tvar_prefix = "T_"
blanchet@43926
   141
val tfree_prefix = "t_"
blanchet@43926
   142
val const_prefix = "c_"
blanchet@43926
   143
val type_const_prefix = "tc_"
blanchet@45346
   144
val simple_type_prefix = "s_"
blanchet@43926
   145
val class_prefix = "cl_"
blanchet@43926
   146
blanchet@46380
   147
(* Freshness almost guaranteed! *)
blanchet@46380
   148
val atp_weak_prefix = "ATP:"
blanchet@46380
   149
blanchet@46425
   150
val lam_lifted_prefix = atp_weak_prefix ^ "Lam"
blanchet@46425
   151
val lam_lifted_mono_prefix = lam_lifted_prefix ^ "m"
blanchet@46425
   152
val lam_lifted_poly_prefix = lam_lifted_prefix ^ "p"
blanchet@44778
   153
blanchet@44734
   154
val skolem_const_prefix = "ATP" ^ Long_Name.separator ^ "Sko"
blanchet@43926
   155
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@43926
   156
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@43926
   157
blanchet@46425
   158
val combinator_prefix = "COMB"
blanchet@46425
   159
blanchet@43839
   160
val type_decl_prefix = "ty_"
blanchet@43839
   161
val sym_decl_prefix = "sy_"
blanchet@44860
   162
val guards_sym_formula_prefix = "gsy_"
blanchet@45255
   163
val tags_sym_formula_prefix = "tsy_"
blanchet@40445
   164
val fact_prefix = "fact_"
blanchet@38506
   165
val conjecture_prefix = "conj_"
blanchet@38506
   166
val helper_prefix = "help_"
blanchet@44000
   167
val class_rel_clause_prefix = "clar_"
blanchet@38506
   168
val arity_clause_prefix = "arity_"
blanchet@43926
   169
val tfree_clause_prefix = "tfree_"
blanchet@38506
   170
blanchet@46425
   171
val lam_fact_prefix = "ATP.lambda_"
blanchet@43750
   172
val typed_helper_suffix = "_T"
blanchet@43750
   173
val untyped_helper_suffix = "_U"
blanchet@44000
   174
val type_tag_idempotence_helper_name = helper_prefix ^ "ti_idem"
blanchet@43750
   175
blanchet@45346
   176
val predicator_name = "pp"
blanchet@45346
   177
val app_op_name = "aa"
blanchet@45346
   178
val type_guard_name = "gg"
blanchet@45346
   179
val type_tag_name = "tt"
blanchet@43402
   180
blanchet@44015
   181
val prefixed_predicator_name = const_prefix ^ predicator_name
blanchet@43971
   182
val prefixed_app_op_name = const_prefix ^ app_op_name
blanchet@43971
   183
val prefixed_type_tag_name = const_prefix ^ type_tag_name
blanchet@43971
   184
blanchet@43926
   185
(*Escaping of special characters.
blanchet@43926
   186
  Alphanumeric characters are left unchanged.
blanchet@43926
   187
  The character _ goes to __
blanchet@43926
   188
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@43926
   189
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
blanchet@43934
   190
val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
blanchet@43926
   191
blanchet@43926
   192
fun stringN_of_int 0 _ = ""
blanchet@43926
   193
  | stringN_of_int k n =
blanchet@43926
   194
    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
blanchet@43926
   195
blanchet@43926
   196
fun ascii_of_char c =
blanchet@43926
   197
  if Char.isAlphaNum c then
blanchet@43926
   198
    String.str c
blanchet@43926
   199
  else if c = #"_" then
blanchet@43926
   200
    "__"
blanchet@43926
   201
  else if #" " <= c andalso c <= #"/" then
blanchet@43926
   202
    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
blanchet@43926
   203
  else
blanchet@43926
   204
    (* fixed width, in case more digits follow *)
blanchet@43926
   205
    "_" ^ stringN_of_int 3 (Char.ord c)
blanchet@43926
   206
blanchet@43926
   207
val ascii_of = String.translate ascii_of_char
blanchet@43926
   208
blanchet@43926
   209
(** Remove ASCII armoring from names in proof files **)
blanchet@43926
   210
blanchet@43926
   211
(* We don't raise error exceptions because this code can run inside a worker
blanchet@43926
   212
   thread. Also, the errors are impossible. *)
blanchet@43926
   213
val unascii_of =
blanchet@43926
   214
  let
blanchet@43926
   215
    fun un rcs [] = String.implode(rev rcs)
blanchet@43926
   216
      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
blanchet@43926
   217
        (* Three types of _ escapes: __, _A to _P, _nnn *)
blanchet@44367
   218
      | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
blanchet@43926
   219
      | un rcs (#"_" :: c :: cs) =
blanchet@43926
   220
        if #"A" <= c andalso c<= #"P" then
blanchet@43926
   221
          (* translation of #" " to #"/" *)
blanchet@43926
   222
          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
blanchet@43926
   223
        else
blanchet@44367
   224
          let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
blanchet@43926
   225
            case Int.fromString (String.implode digits) of
blanchet@43926
   226
              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
blanchet@44367
   227
            | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
blanchet@43926
   228
          end
blanchet@43926
   229
      | un rcs (c :: cs) = un (c :: rcs) cs
blanchet@43926
   230
  in un [] o String.explode end
blanchet@43926
   231
blanchet@43926
   232
(* If string s has the prefix s1, return the result of deleting it,
blanchet@43926
   233
   un-ASCII'd. *)
blanchet@46382
   234
fun unprefix_and_unascii s1 s =
blanchet@43926
   235
  if String.isPrefix s1 s then
blanchet@43926
   236
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@43926
   237
  else
blanchet@43926
   238
    NONE
blanchet@43926
   239
blanchet@44000
   240
val proxy_table =
blanchet@44000
   241
  [("c_False", (@{const_name False}, (@{thm fFalse_def},
blanchet@44000
   242
       ("fFalse", @{const_name ATP.fFalse})))),
blanchet@44000
   243
   ("c_True", (@{const_name True}, (@{thm fTrue_def},
blanchet@44000
   244
       ("fTrue", @{const_name ATP.fTrue})))),
blanchet@44000
   245
   ("c_Not", (@{const_name Not}, (@{thm fNot_def},
blanchet@44000
   246
       ("fNot", @{const_name ATP.fNot})))),
blanchet@44000
   247
   ("c_conj", (@{const_name conj}, (@{thm fconj_def},
blanchet@44000
   248
       ("fconj", @{const_name ATP.fconj})))),
blanchet@44000
   249
   ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
blanchet@44000
   250
       ("fdisj", @{const_name ATP.fdisj})))),
blanchet@44000
   251
   ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
blanchet@44000
   252
       ("fimplies", @{const_name ATP.fimplies})))),
blanchet@44000
   253
   ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
nik@44537
   254
       ("fequal", @{const_name ATP.fequal})))),
nik@44537
   255
   ("c_All", (@{const_name All}, (@{thm fAll_def},
nik@44537
   256
       ("fAll", @{const_name ATP.fAll})))),
nik@44537
   257
   ("c_Ex", (@{const_name Ex}, (@{thm fEx_def},
nik@44537
   258
       ("fEx", @{const_name ATP.fEx}))))]
blanchet@43926
   259
blanchet@44000
   260
val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
blanchet@43926
   261
blanchet@43926
   262
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@43926
   263
   table unless you know what you are doing. *)
blanchet@43926
   264
val const_trans_table =
blanchet@43926
   265
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@43926
   266
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@43926
   267
   (@{const_name False}, "False"),
blanchet@43926
   268
   (@{const_name True}, "True"),
blanchet@43926
   269
   (@{const_name Not}, "Not"),
blanchet@43926
   270
   (@{const_name conj}, "conj"),
blanchet@43926
   271
   (@{const_name disj}, "disj"),
blanchet@43926
   272
   (@{const_name implies}, "implies"),
blanchet@43926
   273
   (@{const_name HOL.eq}, "equal"),
nik@44537
   274
   (@{const_name All}, "All"),
nik@44537
   275
   (@{const_name Ex}, "Ex"),
blanchet@43926
   276
   (@{const_name If}, "If"),
blanchet@43926
   277
   (@{const_name Set.member}, "member"),
blanchet@46425
   278
   (@{const_name Meson.COMBI}, combinator_prefix ^ "I"),
blanchet@46425
   279
   (@{const_name Meson.COMBK}, combinator_prefix ^ "K"),
blanchet@46425
   280
   (@{const_name Meson.COMBB}, combinator_prefix ^ "B"),
blanchet@46425
   281
   (@{const_name Meson.COMBC}, combinator_prefix ^ "C"),
blanchet@46425
   282
   (@{const_name Meson.COMBS}, combinator_prefix ^ "S")]
blanchet@43926
   283
  |> Symtab.make
blanchet@44000
   284
  |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
blanchet@43926
   285
blanchet@43926
   286
(* Invert the table of translations between Isabelle and ATPs. *)
blanchet@43926
   287
val const_trans_table_inv =
blanchet@43926
   288
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@43926
   289
val const_trans_table_unprox =
blanchet@43926
   290
  Symtab.empty
blanchet@44000
   291
  |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
blanchet@43926
   292
blanchet@43926
   293
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@43926
   294
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
blanchet@43926
   295
blanchet@43926
   296
fun lookup_const c =
blanchet@43926
   297
  case Symtab.lookup const_trans_table c of
blanchet@43926
   298
    SOME c' => c'
blanchet@43926
   299
  | NONE => ascii_of c
blanchet@43926
   300
blanchet@44489
   301
fun ascii_of_indexname (v, 0) = ascii_of v
blanchet@44489
   302
  | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
blanchet@43926
   303
blanchet@43926
   304
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@45262
   305
fun make_all_bound_var x = all_bound_var_prefix ^ ascii_of x
blanchet@45262
   306
fun make_exist_bound_var x = exist_bound_var_prefix ^ ascii_of x
blanchet@43926
   307
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@43926
   308
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
blanchet@43926
   309
blanchet@44489
   310
fun make_schematic_type_var (x, i) =
blanchet@45459
   311
  tvar_prefix ^ (ascii_of_indexname (unprefix "'" x, i))
blanchet@44489
   312
fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (unprefix "'" x))
blanchet@43926
   313
blanchet@46172
   314
(* "HOL.eq" and choice are mapped to the ATP's equivalents *)
nik@45451
   315
local
nik@45451
   316
  val choice_const = (fst o dest_Const o HOLogic.choice_const) Term.dummyT
nik@45451
   317
  fun default c = const_prefix ^ lookup_const c
nik@45451
   318
in
nik@45451
   319
  fun make_fixed_const _ @{const_name HOL.eq} = tptp_old_equal
blanchet@45618
   320
    | make_fixed_const (SOME (THF (_, _, THF_With_Choice))) c =
blanchet@45618
   321
      if c = choice_const then tptp_choice else default c
nik@45451
   322
    | make_fixed_const _ c = default c
nik@45451
   323
end
blanchet@43926
   324
blanchet@43926
   325
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
blanchet@43926
   326
blanchet@43926
   327
fun make_type_class clas = class_prefix ^ ascii_of clas
blanchet@43926
   328
blanchet@43934
   329
fun new_skolem_var_name_from_const s =
blanchet@43934
   330
  let val ss = s |> space_explode Long_Name.separator in
blanchet@43934
   331
    nth ss (length ss - 2)
blanchet@43934
   332
  end
blanchet@43934
   333
blanchet@44089
   334
(* These are either simplified away by "Meson.presimplify" (most of the time) or
blanchet@44089
   335
   handled specially via "fFalse", "fTrue", ..., "fequal". *)
blanchet@44089
   336
val atp_irrelevant_consts =
blanchet@44089
   337
  [@{const_name False}, @{const_name True}, @{const_name Not},
blanchet@44089
   338
   @{const_name conj}, @{const_name disj}, @{const_name implies},
blanchet@44089
   339
   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
blanchet@44089
   340
blanchet@44089
   341
val atp_monomorph_bad_consts =
blanchet@44089
   342
  atp_irrelevant_consts @
blanchet@44089
   343
  (* These are ignored anyway by the relevance filter (unless they appear in
blanchet@44089
   344
     higher-order places) but not by the monomorphizer. *)
blanchet@44089
   345
  [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
blanchet@44089
   346
   @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
blanchet@44089
   347
   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
blanchet@44089
   348
blanchet@44099
   349
fun add_schematic_const (x as (_, T)) =
blanchet@44099
   350
  Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
blanchet@44099
   351
val add_schematic_consts_of =
blanchet@44099
   352
  Term.fold_aterms (fn Const (x as (s, _)) =>
blanchet@44099
   353
                       not (member (op =) atp_monomorph_bad_consts s)
blanchet@44099
   354
                       ? add_schematic_const x
blanchet@44099
   355
                      | _ => I)
blanchet@44099
   356
fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
blanchet@44089
   357
blanchet@43926
   358
(** Definitions and functions for FOL clauses and formulas for TPTP **)
blanchet@43926
   359
blanchet@43926
   360
(** Isabelle arities **)
blanchet@43926
   361
blanchet@45483
   362
type arity_atom = name * name * name list
blanchet@43926
   363
blanchet@44104
   364
val type_class = the_single @{sort type}
blanchet@44104
   365
blanchet@43927
   366
type arity_clause =
blanchet@44367
   367
  {name : string,
blanchet@45483
   368
   prem_atoms : arity_atom list,
blanchet@45483
   369
   concl_atom : arity_atom}
blanchet@45483
   370
blanchet@45483
   371
fun add_prem_atom tvar =
blanchet@45483
   372
  fold (fn s => s <> type_class ? cons (`make_type_class s, `I tvar, []))
blanchet@43926
   373
blanchet@43926
   374
(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
blanchet@43926
   375
fun make_axiom_arity_clause (tcons, name, (cls, args)) =
blanchet@43926
   376
  let
blanchet@45459
   377
    val tvars = map (prefix tvar_prefix o string_of_int) (1 upto length args)
blanchet@43926
   378
    val tvars_srts = ListPair.zip (tvars, args)
blanchet@43926
   379
  in
blanchet@43927
   380
    {name = name,
blanchet@45483
   381
     prem_atoms = [] |> fold (uncurry add_prem_atom) tvars_srts,
blanchet@45483
   382
     concl_atom = (`make_type_class cls, `make_fixed_type_const tcons,
blanchet@45483
   383
                   tvars ~~ tvars)}
blanchet@43926
   384
  end
blanchet@43926
   385
blanchet@43926
   386
fun arity_clause _ _ (_, []) = []
blanchet@44366
   387
  | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
blanchet@44366
   388
    arity_clause seen n (tcons, ars)
blanchet@44366
   389
  | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
blanchet@44366
   390
    if member (op =) seen class then
blanchet@44366
   391
      (* multiple arities for the same (tycon, class) pair *)
blanchet@44366
   392
      make_axiom_arity_clause (tcons,
blanchet@44366
   393
          lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
blanchet@44366
   394
          ar) ::
blanchet@44366
   395
      arity_clause seen (n + 1) (tcons, ars)
blanchet@44366
   396
    else
blanchet@44366
   397
      make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
blanchet@44366
   398
                               ascii_of class, ar) ::
blanchet@44366
   399
      arity_clause (class :: seen) n (tcons, ars)
blanchet@43926
   400
blanchet@43926
   401
fun multi_arity_clause [] = []
blanchet@43926
   402
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@45643
   403
    arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
blanchet@43926
   404
blanchet@44489
   405
(* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
blanchet@44489
   406
   theory thy provided its arguments have the corresponding sorts. *)
blanchet@43926
   407
fun type_class_pairs thy tycons classes =
blanchet@43934
   408
  let
blanchet@43934
   409
    val alg = Sign.classes_of thy
blanchet@43934
   410
    fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@43934
   411
    fun add_class tycon class =
blanchet@43934
   412
      cons (class, domain_sorts tycon class)
blanchet@43934
   413
      handle Sorts.CLASS_ERROR _ => I
blanchet@43934
   414
    fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
blanchet@43934
   415
  in map try_classes tycons end
blanchet@43926
   416
blanchet@43926
   417
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@43926
   418
fun iter_type_class_pairs _ _ [] = ([], [])
blanchet@43926
   419
  | iter_type_class_pairs thy tycons classes =
blanchet@44104
   420
      let
blanchet@44104
   421
        fun maybe_insert_class s =
blanchet@44104
   422
          (s <> type_class andalso not (member (op =) classes s))
blanchet@44104
   423
          ? insert (op =) s
blanchet@44104
   424
        val cpairs = type_class_pairs thy tycons classes
blanchet@44104
   425
        val newclasses =
blanchet@44104
   426
          [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
blanchet@44104
   427
        val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
blanchet@44107
   428
      in (classes' @ classes, union (op =) cpairs' cpairs) end
blanchet@43926
   429
blanchet@43926
   430
fun make_arity_clauses thy tycons =
blanchet@43926
   431
  iter_type_class_pairs thy tycons ##> multi_arity_clause
blanchet@43926
   432
blanchet@43926
   433
blanchet@43926
   434
(** Isabelle class relations **)
blanchet@43926
   435
blanchet@43927
   436
type class_rel_clause =
blanchet@44367
   437
  {name : string,
blanchet@44367
   438
   subclass : name,
blanchet@44367
   439
   superclass : name}
blanchet@43926
   440
blanchet@44489
   441
(* Generate all pairs (sub, super) such that sub is a proper subclass of super
blanchet@44489
   442
   in theory "thy". *)
blanchet@43926
   443
fun class_pairs _ [] _ = []
blanchet@43926
   444
  | class_pairs thy subs supers =
blanchet@43926
   445
      let
blanchet@43926
   446
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@43926
   447
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@43926
   448
        fun add_supers sub = fold (add_super sub) supers
blanchet@43926
   449
      in fold add_supers subs [] end
blanchet@43926
   450
blanchet@44489
   451
fun make_class_rel_clause (sub, super) =
blanchet@44489
   452
  {name = sub ^ "_" ^ super, subclass = `make_type_class sub,
blanchet@43927
   453
   superclass = `make_type_class super}
blanchet@43926
   454
blanchet@43926
   455
fun make_class_rel_clauses thy subs supers =
blanchet@43934
   456
  map make_class_rel_clause (class_pairs thy subs supers)
blanchet@43926
   457
blanchet@44730
   458
(* intermediate terms *)
blanchet@44730
   459
datatype iterm =
blanchet@44730
   460
  IConst of name * typ * typ list |
blanchet@44730
   461
  IVar of name * typ |
blanchet@44730
   462
  IApp of iterm * iterm |
blanchet@44730
   463
  IAbs of (name * typ) * iterm
blanchet@43926
   464
blanchet@44730
   465
fun ityp_of (IConst (_, T, _)) = T
blanchet@44730
   466
  | ityp_of (IVar (_, T)) = T
blanchet@44730
   467
  | ityp_of (IApp (t1, _)) = snd (dest_funT (ityp_of t1))
blanchet@44730
   468
  | ityp_of (IAbs ((_, T), tm)) = T --> ityp_of tm
blanchet@43926
   469
blanchet@43926
   470
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@44730
   471
fun strip_iterm_comb u =
blanchet@44367
   472
  let
blanchet@44730
   473
    fun stripc (IApp (t, u), ts) = stripc (t, u :: ts)
blanchet@44367
   474
      | stripc x = x
blanchet@44367
   475
  in stripc (u, []) end
blanchet@43926
   476
blanchet@46187
   477
fun atomic_types_of T = fold_atyps (insert (op =)) T []
blanchet@43926
   478
blanchet@46380
   479
val tvar_a_str = "'a"
blanchet@46380
   480
val tvar_a = TVar ((tvar_a_str, 0), HOLogic.typeS)
blanchet@46380
   481
val tvar_a_name = (make_schematic_type_var (tvar_a_str, 0), tvar_a_str)
blanchet@46380
   482
val itself_name = `make_fixed_type_const @{type_name itself}
blanchet@46380
   483
val TYPE_name = `(make_fixed_const NONE) @{const_name TYPE}
blanchet@46380
   484
val tvar_a_atype = AType (tvar_a_name, [])
blanchet@46380
   485
val a_itself_atype = AType (itself_name, [tvar_a_atype])
blanchet@46380
   486
blanchet@43926
   487
fun new_skolem_const_name s num_T_args =
blanchet@43926
   488
  [new_skolem_const_prefix, s, string_of_int num_T_args]
blanchet@43926
   489
  |> space_implode Long_Name.separator
blanchet@43926
   490
blanchet@45458
   491
fun robust_const_type thy s =
blanchet@46380
   492
  if s = app_op_name then
blanchet@46380
   493
    Logic.varifyT_global @{typ "('a => 'b) => 'a => 'b"}
blanchet@46425
   494
  else if String.isPrefix lam_lifted_prefix s then
blanchet@46380
   495
    Logic.varifyT_global @{typ "'a => 'b"}
blanchet@46380
   496
  else
blanchet@46380
   497
    (* Old Skolems throw a "TYPE" exception here, which will be caught. *)
blanchet@46380
   498
    s |> Sign.the_const_type thy
blanchet@45458
   499
blanchet@45458
   500
(* This function only makes sense if "T" is as general as possible. *)
blanchet@45458
   501
fun robust_const_typargs thy (s, T) =
blanchet@46380
   502
  if s = app_op_name then
blanchet@46380
   503
    let val (T1, T2) = T |> domain_type |> dest_funT in [T1, T2] end
blanchet@46380
   504
  else if String.isPrefix old_skolem_const_prefix s then
blanchet@46380
   505
    [] |> Term.add_tvarsT T |> rev |> map TVar
blanchet@46425
   506
  else if String.isPrefix lam_lifted_prefix s then
blanchet@46425
   507
    if String.isPrefix lam_lifted_poly_prefix s then
blanchet@46382
   508
      let val (T1, T2) = T |> dest_funT in [T1, T2] end
blanchet@46382
   509
    else
blanchet@46382
   510
      []
blanchet@46380
   511
  else
blanchet@46380
   512
    (s, T) |> Sign.const_typargs thy
blanchet@45458
   513
blanchet@44730
   514
(* Converts an Isabelle/HOL term (with combinators) into an intermediate term.
blanchet@44730
   515
   Also accumulates sort infomation. *)
nik@45350
   516
fun iterm_from_term thy format bs (P $ Q) =
blanchet@43926
   517
    let
nik@45350
   518
      val (P', P_atomics_Ts) = iterm_from_term thy format bs P
nik@45350
   519
      val (Q', Q_atomics_Ts) = iterm_from_term thy format bs Q
blanchet@44730
   520
    in (IApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
nik@45350
   521
  | iterm_from_term thy format _ (Const (c, T)) =
nik@45350
   522
    (IConst (`(make_fixed_const (SOME format)) c, T,
blanchet@45458
   523
             robust_const_typargs thy (c, T)),
blanchet@46187
   524
     atomic_types_of T)
nik@45350
   525
  | iterm_from_term _ _ _ (Free (s, T)) =
blanchet@46380
   526
    (IConst (`make_fixed_var s, T, []), atomic_types_of T)
nik@45350
   527
  | iterm_from_term _ format _ (Var (v as (s, _), T)) =
blanchet@43926
   528
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@43926
   529
       let
blanchet@43926
   530
         val Ts = T |> strip_type |> swap |> op ::
blanchet@43926
   531
         val s' = new_skolem_const_name s (length Ts)
nik@45350
   532
       in IConst (`(make_fixed_const (SOME format)) s', T, Ts) end
blanchet@43926
   533
     else
blanchet@46187
   534
       IVar ((make_schematic_var v, s), T), atomic_types_of T)
nik@45350
   535
  | iterm_from_term _ _ bs (Bound j) =
blanchet@46187
   536
    nth bs j |> (fn (_, (name, T)) => (IConst (name, T, []), atomic_types_of T))
nik@45350
   537
  | iterm_from_term thy format bs (Abs (s, T, t)) =
nik@44537
   538
    let
nik@44537
   539
      fun vary s = s |> AList.defined (op =) bs s ? vary o Symbol.bump_string
nik@44537
   540
      val s = vary s
blanchet@45262
   541
      val name = `make_bound_var s
nik@45350
   542
      val (tm, atomic_Ts) = iterm_from_term thy format ((s, (name, T)) :: bs) t
blanchet@46187
   543
    in (IAbs ((name, T), tm), union (op =) atomic_Ts (atomic_types_of T)) end
blanchet@43926
   544
blanchet@44282
   545
datatype locality =
blanchet@45651
   546
  General | Helper | Induction | Intro | Elim | Simp | Local | Assum | Chained
blanchet@43926
   547
blanchet@44491
   548
datatype order = First_Order | Higher_Order
blanchet@45349
   549
datatype polymorphism = Polymorphic | Raw_Monomorphic | Mangled_Monomorphic
blanchet@46170
   550
datatype soundness = Sound_Modulo_Infinity | Sound
blanchet@45673
   551
datatype granularity = All_Vars | Positively_Naked_Vars | Ghost_Type_Arg_Vars
blanchet@43484
   552
datatype type_level =
blanchet@45256
   553
  All_Types |
blanchet@45673
   554
  Noninf_Nonmono_Types of soundness * granularity |
blanchet@45673
   555
  Fin_Nonmono_Types of granularity |
blanchet@45256
   556
  Const_Arg_Types |
blanchet@44233
   557
  No_Types
blanchet@43484
   558
blanchet@44493
   559
datatype type_enc =
blanchet@45455
   560
  Simple_Types of order * polymorphism * type_level |
blanchet@45639
   561
  Guards of polymorphism * type_level |
blanchet@45639
   562
  Tags of polymorphism * type_level
blanchet@45639
   563
blanchet@45639
   564
fun is_type_enc_higher_order (Simple_Types (Higher_Order, _, _)) = true
blanchet@45639
   565
  | is_type_enc_higher_order _ = false
blanchet@45639
   566
blanchet@45639
   567
fun polymorphism_of_type_enc (Simple_Types (_, poly, _)) = poly
blanchet@45639
   568
  | polymorphism_of_type_enc (Guards (poly, _)) = poly
blanchet@45639
   569
  | polymorphism_of_type_enc (Tags (poly, _)) = poly
blanchet@45639
   570
blanchet@45639
   571
fun level_of_type_enc (Simple_Types (_, _, level)) = level
blanchet@45639
   572
  | level_of_type_enc (Guards (_, level)) = level
blanchet@45639
   573
  | level_of_type_enc (Tags (_, level)) = level
blanchet@45639
   574
blanchet@45673
   575
fun granularity_of_type_level (Noninf_Nonmono_Types (_, grain)) = grain
blanchet@45673
   576
  | granularity_of_type_level (Fin_Nonmono_Types grain) = grain
blanchet@45673
   577
  | granularity_of_type_level _ = All_Vars
blanchet@45639
   578
blanchet@45639
   579
fun is_type_level_quasi_sound All_Types = true
blanchet@45639
   580
  | is_type_level_quasi_sound (Noninf_Nonmono_Types _) = true
blanchet@45639
   581
  | is_type_level_quasi_sound _ = false
blanchet@45639
   582
val is_type_enc_quasi_sound = is_type_level_quasi_sound o level_of_type_enc
blanchet@45639
   583
blanchet@45639
   584
fun is_type_level_fairly_sound (Fin_Nonmono_Types _) = true
blanchet@45639
   585
  | is_type_level_fairly_sound level = is_type_level_quasi_sound level
blanchet@45639
   586
val is_type_enc_fairly_sound = is_type_level_fairly_sound o level_of_type_enc
blanchet@45639
   587
blanchet@45639
   588
fun is_type_level_monotonicity_based (Noninf_Nonmono_Types _) = true
blanchet@45639
   589
  | is_type_level_monotonicity_based (Fin_Nonmono_Types _) = true
blanchet@45639
   590
  | is_type_level_monotonicity_based _ = false
blanchet@43484
   591
blanchet@45653
   592
(* "_query", "_bang", and "_at" are for the ASCII-challenged Metis and
blanchet@45653
   593
   Mirabelle. *)
blanchet@45653
   594
val queries = ["?", "_query"]
blanchet@45653
   595
val bangs = ["!", "_bang"]
blanchet@45653
   596
val ats = ["@", "_at"]
blanchet@45653
   597
blanchet@43559
   598
fun try_unsuffixes ss s =
blanchet@43559
   599
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@43559
   600
blanchet@45653
   601
fun try_nonmono constr suffixes fallback s =
blanchet@45653
   602
  case try_unsuffixes suffixes s of
blanchet@45653
   603
    SOME s =>
blanchet@45653
   604
    (case try_unsuffixes suffixes s of
blanchet@45673
   605
       SOME s => (constr Positively_Naked_Vars, s)
blanchet@45653
   606
     | NONE =>
blanchet@45653
   607
       case try_unsuffixes ats s of
blanchet@45673
   608
         SOME s => (constr Ghost_Type_Arg_Vars, s)
blanchet@45673
   609
       | NONE => (constr All_Vars, s))
blanchet@45653
   610
  | NONE => fallback s
blanchet@45639
   611
blanchet@45673
   612
fun is_incompatible_type_level poly level =
blanchet@45673
   613
  poly = Mangled_Monomorphic andalso
blanchet@45673
   614
  granularity_of_type_level level = Ghost_Type_Arg_Vars
blanchet@45672
   615
blanchet@45256
   616
fun type_enc_from_string soundness s =
blanchet@43587
   617
  (case try (unprefix "poly_") s of
blanchet@43587
   618
     SOME s => (SOME Polymorphic, s)
blanchet@43484
   619
   | NONE =>
blanchet@45349
   620
     case try (unprefix "raw_mono_") s of
blanchet@45349
   621
       SOME s => (SOME Raw_Monomorphic, s)
blanchet@43587
   622
     | NONE =>
blanchet@45349
   623
       case try (unprefix "mono_") s of
blanchet@43587
   624
         SOME s => (SOME Mangled_Monomorphic, s)
blanchet@43587
   625
       | NONE => (NONE, s))
blanchet@45653
   626
  ||> (pair All_Types
blanchet@45653
   627
       |> try_nonmono Fin_Nonmono_Types bangs
blanchet@45653
   628
       |> try_nonmono (curry Noninf_Nonmono_Types soundness) queries)
blanchet@45639
   629
  |> (fn (poly, (level, core)) =>
blanchet@45639
   630
         case (core, (poly, level)) of
blanchet@45639
   631
           ("simple", (SOME poly, _)) =>
blanchet@45606
   632
           (case (poly, level) of
blanchet@45606
   633
              (Polymorphic, All_Types) =>
blanchet@45606
   634
              Simple_Types (First_Order, Polymorphic, All_Types)
blanchet@45606
   635
            | (Mangled_Monomorphic, _) =>
blanchet@45673
   636
              if granularity_of_type_level level = All_Vars then
blanchet@45639
   637
                Simple_Types (First_Order, Mangled_Monomorphic, level)
blanchet@45639
   638
              else
blanchet@45639
   639
                raise Same.SAME
blanchet@45606
   640
            | _ => raise Same.SAME)
blanchet@45639
   641
         | ("simple_higher", (SOME poly, _)) =>
blanchet@45455
   642
           (case (poly, level) of
blanchet@45618
   643
              (Polymorphic, All_Types) =>
blanchet@45618
   644
              Simple_Types (Higher_Order, Polymorphic, All_Types)
blanchet@45618
   645
            | (_, Noninf_Nonmono_Types _) => raise Same.SAME
blanchet@45606
   646
            | (Mangled_Monomorphic, _) =>
blanchet@45673
   647
              if granularity_of_type_level level = All_Vars then
blanchet@45639
   648
                Simple_Types (Higher_Order, Mangled_Monomorphic, level)
blanchet@45639
   649
              else
blanchet@45639
   650
                raise Same.SAME
blanchet@45606
   651
            | _ => raise Same.SAME)
blanchet@45672
   652
         | ("guards", (SOME poly, _)) =>
blanchet@45673
   653
           if is_incompatible_type_level poly level then raise Same.SAME
blanchet@45672
   654
           else Guards (poly, level)
blanchet@45672
   655
         | ("tags", (SOME poly, _)) =>
blanchet@45673
   656
           if is_incompatible_type_level poly level then raise Same.SAME
blanchet@45672
   657
           else Tags (poly, level)
blanchet@45639
   658
         | ("args", (SOME poly, All_Types (* naja *))) =>
blanchet@45639
   659
           Guards (poly, Const_Arg_Types)
blanchet@45639
   660
         | ("erased", (NONE, All_Types (* naja *))) =>
blanchet@45639
   661
           Guards (Polymorphic, No_Types)
blanchet@43618
   662
         | _ => raise Same.SAME)
blanchet@45653
   663
  handle Same.SAME => error ("Unknown type encoding: " ^ quote s ^ ".")
blanchet@43484
   664
blanchet@45618
   665
fun adjust_type_enc (THF (TPTP_Monomorphic, _, _))
blanchet@45618
   666
                    (Simple_Types (order, _, level)) =
blanchet@45455
   667
    Simple_Types (order, Mangled_Monomorphic, level)
blanchet@45618
   668
  | adjust_type_enc (THF _) type_enc = type_enc
blanchet@45618
   669
  | adjust_type_enc (TFF (TPTP_Monomorphic, _)) (Simple_Types (_, _, level)) =
blanchet@45455
   670
    Simple_Types (First_Order, Mangled_Monomorphic, level)
blanchet@46174
   671
  | adjust_type_enc (DFG DFG_Sorted) (Simple_Types (_, _, level)) =
blanchet@46172
   672
    Simple_Types (First_Order, Mangled_Monomorphic, level)
blanchet@45618
   673
  | adjust_type_enc (TFF _) (Simple_Types (_, poly, level)) =
blanchet@45455
   674
    Simple_Types (First_Order, poly, level)
blanchet@45455
   675
  | adjust_type_enc format (Simple_Types (_, poly, level)) =
blanchet@45639
   676
    adjust_type_enc format (Guards (poly, level))
blanchet@45275
   677
  | adjust_type_enc CNF_UEQ (type_enc as Guards stuff) =
blanchet@45275
   678
    (if is_type_enc_fairly_sound type_enc then Tags else Guards) stuff
blanchet@45275
   679
  | adjust_type_enc _ type_enc = type_enc
blanchet@43942
   680
blanchet@46380
   681
fun constify_lifted (t $ u) = constify_lifted t $ constify_lifted u
blanchet@46380
   682
  | constify_lifted (Abs (s, T, t)) = Abs (s, T, constify_lifted t)
blanchet@46380
   683
  | constify_lifted (Free (x as (s, _))) =
blanchet@46425
   684
    (if String.isPrefix lam_lifted_prefix s then Const else Free) x
blanchet@46380
   685
  | constify_lifted t = t
blanchet@46380
   686
blanchet@46436
   687
(* Requires bound variables not to clash with any schematic variables (as should
blanchet@46436
   688
   be the case right after lambda-lifting). *)
blanchet@46441
   689
fun open_form (Const (@{const_name All}, _) $ Abs (s, T, t)) =
blanchet@46441
   690
    let
blanchet@46441
   691
      val names = Name.make_context (map fst (Term.add_var_names t []))
blanchet@46441
   692
      val (s, _) = Name.variant s names
blanchet@46441
   693
    in open_form (subst_bound (Var ((s, 0), T), t)) end
blanchet@46382
   694
  | open_form t = t
blanchet@46382
   695
blanchet@46425
   696
fun lift_lams_part_1 ctxt type_enc =
blanchet@46439
   697
  map close_form #> rpair ctxt
blanchet@44959
   698
  #-> Lambda_Lifting.lift_lambdas
blanchet@46435
   699
          (SOME ((if polymorphism_of_type_enc type_enc = Polymorphic then
blanchet@46435
   700
                    lam_lifted_poly_prefix
blanchet@46435
   701
                  else
blanchet@46435
   702
                    lam_lifted_mono_prefix) ^ "_a"))
blanchet@44959
   703
          Lambda_Lifting.is_quantifier
blanchet@46425
   704
  #> fst
blanchet@46425
   705
val lift_lams_part_2 = pairself (map (open_form o constify_lifted))
blanchet@46425
   706
val lift_lams = lift_lams_part_2 ooo lift_lams_part_1
blanchet@44959
   707
blanchet@44959
   708
fun intentionalize_def (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@44959
   709
    intentionalize_def t
blanchet@44959
   710
  | intentionalize_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
blanchet@44959
   711
    let
blanchet@44959
   712
      fun lam T t = Abs (Name.uu, T, t)
blanchet@44959
   713
      val (head, args) = strip_comb t ||> rev
blanchet@44959
   714
      val head_T = fastype_of head
blanchet@44959
   715
      val n = length args
blanchet@44959
   716
      val arg_Ts = head_T |> binder_types |> take n |> rev
blanchet@44959
   717
      val u = u |> subst_atomic (args ~~ map Bound (0 upto n - 1))
blanchet@44959
   718
    in HOLogic.eq_const head_T $ head $ fold lam arg_Ts u end
blanchet@44959
   719
  | intentionalize_def t = t
blanchet@44959
   720
blanchet@40358
   721
type translated_formula =
blanchet@44367
   722
  {name : string,
blanchet@44367
   723
   locality : locality,
blanchet@44367
   724
   kind : formula_kind,
blanchet@44730
   725
   iformula : (name, typ, iterm) formula,
blanchet@44367
   726
   atomic_types : typ list}
blanchet@38506
   727
blanchet@44730
   728
fun update_iformula f ({name, locality, kind, iformula, atomic_types}
blanchet@44730
   729
                       : translated_formula) =
blanchet@44730
   730
  {name = name, locality = locality, kind = kind, iformula = f iformula,
blanchet@43433
   731
   atomic_types = atomic_types} : translated_formula
blanchet@43413
   732
blanchet@44730
   733
fun fact_lift f ({iformula, ...} : translated_formula) = f iformula
blanchet@43429
   734
blanchet@43905
   735
fun insert_type ctxt get_T x xs =
blanchet@43905
   736
  let val T = get_T x in
blanchet@45258
   737
    if exists (type_instance ctxt T o get_T) xs then xs
blanchet@45258
   738
    else x :: filter_out (type_generalization ctxt T o get_T) xs
blanchet@43905
   739
  end
blanchet@43547
   740
blanchet@43618
   741
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@43618
   742
datatype type_arg_policy =
blanchet@43618
   743
  Explicit_Type_Args of bool |
blanchet@45642
   744
  Mangled_Type_Args |
blanchet@43618
   745
  No_Type_Args
blanchet@41384
   746
blanchet@44493
   747
fun type_arg_policy type_enc s =
blanchet@46186
   748
  let val poly = polymorphism_of_type_enc type_enc in
blanchet@45645
   749
    if s = type_tag_name then
blanchet@46186
   750
      if poly = Mangled_Monomorphic then Mangled_Type_Args
blanchet@46186
   751
      else Explicit_Type_Args false
blanchet@45645
   752
    else case type_enc of
blanchet@46186
   753
      Simple_Types (_, Polymorphic, _) => Explicit_Type_Args false
blanchet@46186
   754
    | Tags (_, All_Types) => No_Type_Args
blanchet@45645
   755
    | _ =>
blanchet@45645
   756
      let val level = level_of_type_enc type_enc in
blanchet@45645
   757
        if level = No_Types orelse s = @{const_name HOL.eq} orelse
blanchet@45645
   758
           (s = app_op_name andalso level = Const_Arg_Types) then
blanchet@45645
   759
          No_Type_Args
blanchet@46186
   760
        else if poly = Mangled_Monomorphic then
blanchet@45645
   761
          Mangled_Type_Args
blanchet@45645
   762
        else
blanchet@45673
   763
          Explicit_Type_Args
blanchet@45673
   764
              (level = All_Types orelse
blanchet@45673
   765
               granularity_of_type_level level = Ghost_Type_Arg_Vars)
blanchet@45645
   766
      end
blanchet@45645
   767
  end
blanchet@43088
   768
blanchet@45483
   769
(* Make atoms for sorted type variables. *)
blanchet@44104
   770
fun generic_add_sorts_on_type (_, []) = I
blanchet@44104
   771
  | generic_add_sorts_on_type ((x, i), s :: ss) =
blanchet@44104
   772
    generic_add_sorts_on_type ((x, i), ss)
blanchet@44104
   773
    #> (if s = the_single @{sort HOL.type} then
blanchet@43934
   774
          I
blanchet@43934
   775
        else if i = ~1 then
blanchet@45481
   776
          insert (op =) (`make_type_class s, `make_fixed_type_var x)
blanchet@43934
   777
        else
blanchet@45481
   778
          insert (op =) (`make_type_class s,
blanchet@45481
   779
                         (make_schematic_type_var (x, i), x)))
blanchet@44104
   780
fun add_sorts_on_tfree (TFree (s, S)) = generic_add_sorts_on_type ((s, ~1), S)
blanchet@44104
   781
  | add_sorts_on_tfree _ = I
blanchet@44104
   782
fun add_sorts_on_tvar (TVar z) = generic_add_sorts_on_type z
blanchet@44104
   783
  | add_sorts_on_tvar _ = I
blanchet@43926
   784
blanchet@45483
   785
fun type_class_formula type_enc class arg =
blanchet@45483
   786
  AAtom (ATerm (class, arg ::
blanchet@45483
   787
      (case type_enc of
blanchet@45618
   788
         Simple_Types (First_Order, Polymorphic, _) =>
blanchet@46172
   789
         if avoid_first_order_ghost_type_vars then [ATerm (TYPE_name, [arg])]
blanchet@45618
   790
         else []
blanchet@45483
   791
       | _ => [])))
blanchet@45483
   792
fun formulas_for_types type_enc add_sorts_on_typ Ts =
blanchet@44493
   793
  [] |> level_of_type_enc type_enc <> No_Types ? fold add_sorts_on_typ Ts
blanchet@45483
   794
     |> map (fn (class, name) =>
blanchet@45483
   795
                type_class_formula type_enc class (ATerm (name, [])))
blanchet@41385
   796
blanchet@43405
   797
fun mk_aconns c phis =
blanchet@43405
   798
  let val (phis', phi') = split_last phis in
blanchet@43405
   799
    fold_rev (mk_aconn c) phis' phi'
blanchet@43405
   800
  end
blanchet@38506
   801
fun mk_ahorn [] phi = phi
blanchet@43405
   802
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@43393
   803
fun mk_aquant _ [] phi = phi
blanchet@43393
   804
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@43393
   805
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@43393
   806
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38506
   807
blanchet@46186
   808
fun close_universally add_term_vars phi =
blanchet@41393
   809
  let
blanchet@46186
   810
    fun add_formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@46186
   811
        add_formula_vars (map fst xs @ bounds) phi
blanchet@46186
   812
      | add_formula_vars bounds (AConn (_, phis)) =
blanchet@46186
   813
        fold (add_formula_vars bounds) phis
blanchet@46186
   814
      | add_formula_vars bounds (AAtom tm) = add_term_vars bounds tm
blanchet@46186
   815
  in mk_aquant AForall (add_formula_vars [] phi []) phi end
blanchet@43393
   816
blanchet@46248
   817
fun add_term_vars bounds (ATerm (name as (s, _), tms)) =
blanchet@46248
   818
    (if is_tptp_variable s andalso
blanchet@46248
   819
        not (String.isPrefix tvar_prefix s) andalso
blanchet@46248
   820
        not (member (op =) bounds name) then
blanchet@46248
   821
       insert (op =) (name, NONE)
blanchet@46248
   822
     else
blanchet@46248
   823
       I)
blanchet@46248
   824
    #> fold (add_term_vars bounds) tms
blanchet@46248
   825
  | add_term_vars bounds (AAbs ((name, _), tm)) =
blanchet@46248
   826
    add_term_vars (name :: bounds) tm
blanchet@46272
   827
fun close_formula_universally phi = close_universally add_term_vars phi
blanchet@46186
   828
blanchet@46186
   829
fun add_iterm_vars bounds (IApp (tm1, tm2)) =
blanchet@46186
   830
    fold (add_iterm_vars bounds) [tm1, tm2]
blanchet@46186
   831
  | add_iterm_vars _ (IConst _) = I
blanchet@46186
   832
  | add_iterm_vars bounds (IVar (name, T)) =
blanchet@46186
   833
    not (member (op =) bounds name) ? insert (op =) (name, SOME T)
blanchet@46186
   834
  | add_iterm_vars bounds (IAbs (_, tm)) = add_iterm_vars bounds tm
blanchet@46186
   835
fun close_iformula_universally phi = close_universally add_iterm_vars phi
blanchet@41393
   836
blanchet@45458
   837
val fused_infinite_type_name = @{type_name ind} (* any infinite type *)
blanchet@45458
   838
val fused_infinite_type = Type (fused_infinite_type_name, [])
blanchet@45458
   839
blanchet@45458
   840
fun tvar_name (x as (s, _)) = (make_schematic_type_var x, s)
blanchet@43835
   841
nik@44535
   842
fun ho_term_from_typ format type_enc =
blanchet@43835
   843
  let
blanchet@43835
   844
    fun term (Type (s, Ts)) =
blanchet@44493
   845
      ATerm (case (is_type_enc_higher_order type_enc, s) of
blanchet@43835
   846
               (true, @{type_name bool}) => `I tptp_bool_type
blanchet@43835
   847
             | (true, @{type_name fun}) => `I tptp_fun_type
blanchet@45458
   848
             | _ => if s = fused_infinite_type_name andalso
blanchet@45106
   849
                       is_format_typed format then
blanchet@44019
   850
                      `I tptp_individual_type
blanchet@44019
   851
                    else
blanchet@44019
   852
                      `make_fixed_type_const s,
blanchet@43835
   853
             map term Ts)
blanchet@43835
   854
    | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
blanchet@45458
   855
    | term (TVar (x, _)) = ATerm (tvar_name x, [])
blanchet@43835
   856
  in term end
blanchet@43433
   857
nik@44535
   858
fun ho_term_for_type_arg format type_enc T =
nik@44535
   859
  if T = dummyT then NONE else SOME (ho_term_from_typ format type_enc T)
blanchet@44264
   860
blanchet@43433
   861
(* This shouldn't clash with anything else. *)
blanchet@43413
   862
val mangled_type_sep = "\000"
blanchet@43413
   863
blanchet@43433
   864
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@43433
   865
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@43626
   866
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@43626
   867
    ^ ")"
blanchet@44558
   868
  | generic_mangled_type_name _ _ = raise Fail "unexpected type abstraction"
blanchet@43413
   869
blanchet@45255
   870
fun mangled_type format type_enc =
blanchet@45255
   871
  generic_mangled_type_name fst o ho_term_from_typ format type_enc
blanchet@45255
   872
blanchet@43926
   873
fun make_simple_type s =
blanchet@43926
   874
  if s = tptp_bool_type orelse s = tptp_fun_type orelse
blanchet@43926
   875
     s = tptp_individual_type then
blanchet@43926
   876
    s
blanchet@43926
   877
  else
blanchet@43926
   878
    simple_type_prefix ^ ascii_of s
blanchet@43926
   879
nik@44535
   880
fun ho_type_from_ho_term type_enc pred_sym ary =
blanchet@43804
   881
  let
blanchet@45457
   882
    fun to_mangled_atype ty =
blanchet@43804
   883
      AType ((make_simple_type (generic_mangled_type_name fst ty),
blanchet@45457
   884
              generic_mangled_type_name snd ty), [])
blanchet@45457
   885
    fun to_poly_atype (ATerm (name, tys)) = AType (name, map to_poly_atype tys)
blanchet@45457
   886
      | to_poly_atype _ = raise Fail "unexpected type abstraction"
blanchet@45457
   887
    val to_atype =
blanchet@45457
   888
      if polymorphism_of_type_enc type_enc = Polymorphic then to_poly_atype
blanchet@45457
   889
      else to_mangled_atype
blanchet@43804
   890
    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
blanchet@43839
   891
    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
blanchet@43835
   892
      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
blanchet@44558
   893
      | to_fo _ _ = raise Fail "unexpected type abstraction"
blanchet@43835
   894
    fun to_ho (ty as ATerm ((s, _), tys)) =
nik@44535
   895
        if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
nik@44535
   896
      | to_ho _ = raise Fail "unexpected type abstraction"
blanchet@44493
   897
  in if is_type_enc_higher_order type_enc then to_ho else to_fo ary end
blanchet@43804
   898
nik@44536
   899
fun ho_type_from_typ format type_enc pred_sym ary =
nik@44535
   900
  ho_type_from_ho_term type_enc pred_sym ary
nik@44535
   901
  o ho_term_from_typ format type_enc
blanchet@43804
   902
blanchet@44493
   903
fun mangled_const_name format type_enc T_args (s, s') =
blanchet@43804
   904
  let
nik@44535
   905
    val ty_args = T_args |> map_filter (ho_term_for_type_arg format type_enc)
blanchet@43804
   906
    fun type_suffix f g =
blanchet@43804
   907
      fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@43804
   908
                o generic_mangled_type_name f) ty_args ""
blanchet@43804
   909
  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
blanchet@43413
   910
blanchet@43413
   911
val parse_mangled_ident =
blanchet@43413
   912
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@43413
   913
blanchet@43413
   914
fun parse_mangled_type x =
blanchet@43413
   915
  (parse_mangled_ident
blanchet@43413
   916
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@43413
   917
                    [] >> ATerm) x
blanchet@43413
   918
and parse_mangled_types x =
blanchet@43413
   919
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@43413
   920
blanchet@43413
   921
fun unmangled_type s =
blanchet@43413
   922
  s |> suffix ")" |> raw_explode
blanchet@43413
   923
    |> Scan.finite Symbol.stopper
blanchet@43413
   924
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@43413
   925
                                                quote s)) parse_mangled_type))
blanchet@43413
   926
    |> fst
blanchet@43413
   927
blanchet@43432
   928
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@43413
   929
fun unmangled_const s =
blanchet@43413
   930
  let val ss = space_explode mangled_type_sep s in
blanchet@43413
   931
    (hd ss, map unmangled_type (tl ss))
blanchet@43413
   932
  end
blanchet@43413
   933
blanchet@45644
   934
fun introduce_proxies_in_iterm type_enc =
blanchet@43439
   935
  let
blanchet@44858
   936
    fun tweak_ho_quant ho_quant T [IAbs _] = IConst (`I ho_quant, T, [])
blanchet@44858
   937
      | tweak_ho_quant ho_quant (T as Type (_, [p_T as Type (_, [x_T, _]), _]))
blanchet@44858
   938
                       _ =
blanchet@44858
   939
        (* Eta-expand "!!" and "??", to work around LEO-II 1.2.8 parser
blanchet@44858
   940
           limitation. This works in conjuction with special code in
blanchet@44858
   941
           "ATP_Problem" that uses the syntactic sugar "!" and "?" whenever
blanchet@44858
   942
           possible. *)
blanchet@44858
   943
        IAbs ((`I "P", p_T),
blanchet@44858
   944
              IApp (IConst (`I ho_quant, T, []),
blanchet@44858
   945
                    IAbs ((`I "X", x_T),
blanchet@44858
   946
                          IApp (IConst (`I "P", p_T, []),
blanchet@44858
   947
                                IConst (`I "X", x_T, [])))))
blanchet@44858
   948
      | tweak_ho_quant _ _ _ = raise Fail "unexpected type for quantifier"
blanchet@44858
   949
    fun intro top_level args (IApp (tm1, tm2)) =
blanchet@44858
   950
        IApp (intro top_level (tm2 :: args) tm1, intro false [] tm2)
blanchet@44858
   951
      | intro top_level args (IConst (name as (s, _), T, T_args)) =
blanchet@43441
   952
        (case proxify_const s of
blanchet@44000
   953
           SOME proxy_base =>
blanchet@44493
   954
           if top_level orelse is_type_enc_higher_order type_enc then
blanchet@43841
   955
             case (top_level, s) of
blanchet@44858
   956
               (_, "c_False") => IConst (`I tptp_false, T, [])
blanchet@44858
   957
             | (_, "c_True") => IConst (`I tptp_true, T, [])
blanchet@44858
   958
             | (false, "c_Not") => IConst (`I tptp_not, T, [])
blanchet@44858
   959
             | (false, "c_conj") => IConst (`I tptp_and, T, [])
blanchet@44858
   960
             | (false, "c_disj") => IConst (`I tptp_or, T, [])
blanchet@44858
   961
             | (false, "c_implies") => IConst (`I tptp_implies, T, [])
blanchet@44858
   962
             | (false, "c_All") => tweak_ho_quant tptp_ho_forall T args
blanchet@44858
   963
             | (false, "c_Ex") => tweak_ho_quant tptp_ho_exists T args
blanchet@43841
   964
             | (false, s) =>
blanchet@44968
   965
               if is_tptp_equal s andalso length args = 2 then
blanchet@44968
   966
                 IConst (`I tptp_equal, T, [])
blanchet@44968
   967
               else
blanchet@45453
   968
                 (* Use a proxy even for partially applied THF0 equality,
blanchet@45453
   969
                    because the LEO-II and Satallax parsers complain about not
blanchet@45453
   970
                    being able to infer the type of "=". *)
blanchet@44968
   971
                 IConst (proxy_base |>> prefix const_prefix, T, T_args)
blanchet@44858
   972
             | _ => IConst (name, T, [])
blanchet@43440
   973
           else
blanchet@44858
   974
             IConst (proxy_base |>> prefix const_prefix, T, T_args)
blanchet@46038
   975
          | NONE => if s = tptp_choice then tweak_ho_quant tptp_choice T args
blanchet@46038
   976
                    else IConst (name, T, T_args))
blanchet@44858
   977
      | intro _ _ (IAbs (bound, tm)) = IAbs (bound, intro false [] tm)
blanchet@44858
   978
      | intro _ _ tm = tm
blanchet@44858
   979
  in intro true [] end
blanchet@43439
   980
blanchet@45645
   981
fun mangle_type_args_in_iterm format type_enc =
blanchet@45645
   982
  if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
blanchet@45645
   983
    let
blanchet@45645
   984
      fun mangle (IApp (tm1, tm2)) = IApp (mangle tm1, mangle tm2)
blanchet@45645
   985
        | mangle (tm as IConst (_, _, [])) = tm
blanchet@45645
   986
        | mangle (tm as IConst (name as (s, _), T, T_args)) =
blanchet@46382
   987
          (case unprefix_and_unascii const_prefix s of
blanchet@45645
   988
             NONE => tm
blanchet@45645
   989
           | SOME s'' =>
blanchet@45645
   990
             case type_arg_policy type_enc (invert_const s'') of
blanchet@45645
   991
               Mangled_Type_Args =>
blanchet@45645
   992
               IConst (mangled_const_name format type_enc T_args name, T, [])
blanchet@45645
   993
             | _ => tm)
blanchet@45645
   994
        | mangle (IAbs (bound, tm)) = IAbs (bound, mangle tm)
blanchet@45645
   995
        | mangle tm = tm
blanchet@45645
   996
    in mangle end
blanchet@45645
   997
  else
blanchet@45645
   998
    I
blanchet@45645
   999
blanchet@45644
  1000
fun chop_fun 0 T = ([], T)
blanchet@45644
  1001
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@45644
  1002
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@45644
  1003
  | chop_fun _ T = ([], T)
blanchet@45644
  1004
blanchet@45645
  1005
fun filter_const_type_args _ _ _ [] = []
blanchet@45645
  1006
  | filter_const_type_args thy s ary T_args =
blanchet@45644
  1007
    let
blanchet@45644
  1008
      val U = robust_const_type thy s
blanchet@45644
  1009
      val arg_U_vars = fold Term.add_tvarsT (U |> chop_fun ary |> fst) []
blanchet@45644
  1010
      val U_args = (s, U) |> robust_const_typargs thy
blanchet@45644
  1011
    in
blanchet@45644
  1012
      U_args ~~ T_args
blanchet@45644
  1013
      |> map (fn (U, T) =>
blanchet@45644
  1014
                 if member (op =) arg_U_vars (dest_TVar U) then dummyT else T)
blanchet@45644
  1015
    end
blanchet@45644
  1016
    handle TYPE _ => T_args
blanchet@45644
  1017
blanchet@45645
  1018
fun filter_type_args_in_iterm thy type_enc =
blanchet@38506
  1019
  let
blanchet@45645
  1020
    fun filt ary (IApp (tm1, tm2)) = IApp (filt (ary + 1) tm1, filt 0 tm2)
blanchet@45645
  1021
      | filt _ (tm as IConst (_, _, [])) = tm
blanchet@45645
  1022
      | filt ary (IConst (name as (s, _), T, T_args)) =
blanchet@46382
  1023
        (case unprefix_and_unascii const_prefix s of
blanchet@45644
  1024
           NONE =>
blanchet@45645
  1025
           (name,
blanchet@45645
  1026
            if level_of_type_enc type_enc = No_Types orelse s = tptp_choice then
blanchet@45645
  1027
              []
blanchet@45645
  1028
            else
blanchet@45645
  1029
              T_args)
blanchet@45644
  1030
         | SOME s'' =>
blanchet@45644
  1031
           let
blanchet@45644
  1032
             val s'' = invert_const s''
blanchet@45644
  1033
             fun filter_T_args false = T_args
blanchet@45645
  1034
               | filter_T_args true = filter_const_type_args thy s'' ary T_args
blanchet@45644
  1035
           in
blanchet@45644
  1036
             case type_arg_policy type_enc s'' of
blanchet@45644
  1037
               Explicit_Type_Args drop_args => (name, filter_T_args drop_args)
blanchet@45644
  1038
             | No_Type_Args => (name, [])
blanchet@45645
  1039
             | Mangled_Type_Args => raise Fail "unexpected (un)mangled symbol"
blanchet@45644
  1040
           end)
blanchet@45644
  1041
        |> (fn (name, T_args) => IConst (name, T, T_args))
blanchet@45645
  1042
      | filt _ (IAbs (bound, tm)) = IAbs (bound, filt 0 tm)
blanchet@45645
  1043
      | filt _ tm = tm
blanchet@45645
  1044
  in filt 0 end
blanchet@45644
  1045
blanchet@45644
  1046
fun iformula_from_prop ctxt format type_enc eq_as_iff =
blanchet@45644
  1047
  let
blanchet@45644
  1048
    val thy = Proof_Context.theory_of ctxt
blanchet@46187
  1049
    fun do_term bs t atomic_Ts =
nik@45350
  1050
      iterm_from_term thy format bs (Envir.eta_contract t)
blanchet@45644
  1051
      |>> (introduce_proxies_in_iterm type_enc
blanchet@45645
  1052
           #> mangle_type_args_in_iterm format type_enc
blanchet@45644
  1053
           #> AAtom)
blanchet@46187
  1054
      ||> union (op =) atomic_Ts
blanchet@45262
  1055
    fun do_quant bs q pos s T t' =
blanchet@45262
  1056
      let
blanchet@45262
  1057
        val s = singleton (Name.variant_list (map fst bs)) s
blanchet@45262
  1058
        val universal = Option.map (q = AExists ? not) pos
blanchet@45262
  1059
        val name =
blanchet@45262
  1060
          s |> `(case universal of
blanchet@45262
  1061
                   SOME true => make_all_bound_var
blanchet@45262
  1062
                 | SOME false => make_exist_bound_var
blanchet@45262
  1063
                 | NONE => make_bound_var)
blanchet@45262
  1064
      in
blanchet@45262
  1065
        do_formula ((s, (name, T)) :: bs) pos t'
blanchet@45262
  1066
        #>> mk_aquant q [(name, SOME T)]
blanchet@46187
  1067
        ##> union (op =) (atomic_types_of T)
blanchet@38743
  1068
      end
blanchet@45262
  1069
    and do_conn bs c pos1 t1 pos2 t2 =
blanchet@45262
  1070
      do_formula bs pos1 t1 ##>> do_formula bs pos2 t2 #>> uncurry (mk_aconn c)
blanchet@45262
  1071
    and do_formula bs pos t =
blanchet@38506
  1072
      case t of
blanchet@45262
  1073
        @{const Trueprop} $ t1 => do_formula bs pos t1
blanchet@45262
  1074
      | @{const Not} $ t1 => do_formula bs (Option.map not pos) t1 #>> mk_anot
blanchet@38506
  1075
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@45262
  1076
        do_quant bs AForall pos s T t'
blanchet@46038
  1077
      | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@46038
  1078
        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
blanchet@38506
  1079
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@45262
  1080
        do_quant bs AExists pos s T t'
blanchet@46038
  1081
      | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@46038
  1082
        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
blanchet@45262
  1083
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd pos t1 pos t2
blanchet@45262
  1084
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr pos t1 pos t2
blanchet@45262
  1085
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@45262
  1086
        do_conn bs AImplies (Option.map not pos) t1 pos t2
haftmann@39093
  1087
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@45262
  1088
        if eq_as_iff then do_conn bs AIff NONE t1 NONE t2 else do_term bs t
blanchet@41388
  1089
      | _ => do_term bs t
blanchet@38506
  1090
  in do_formula [] end
blanchet@38506
  1091
blanchet@44105
  1092
fun presimplify_term _ [] t = t
blanchet@44105
  1093
  | presimplify_term ctxt presimp_consts t =
blanchet@44105
  1094
    t |> exists_Const (member (op =) presimp_consts o fst) t
blanchet@44105
  1095
         ? (Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
blanchet@44105
  1096
            #> Meson.presimplify ctxt
blanchet@44105
  1097
            #> prop_of)
blanchet@38506
  1098
blanchet@44734
  1099
fun concealed_bound_name j = atp_weak_prefix ^ string_of_int j
blanchet@38506
  1100
fun conceal_bounds Ts t =
blanchet@38506
  1101
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38506
  1102
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38506
  1103
fun reveal_bounds Ts =
blanchet@38506
  1104
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38506
  1105
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38506
  1106
blanchet@44106
  1107
fun is_fun_equality (@{const_name HOL.eq},
blanchet@44106
  1108
                     Type (_, [Type (@{type_name fun}, _), _])) = true
blanchet@44106
  1109
  | is_fun_equality _ = false
blanchet@44106
  1110
blanchet@43612
  1111
fun extensionalize_term ctxt t =
blanchet@44106
  1112
  if exists_Const is_fun_equality t then
blanchet@44106
  1113
    let val thy = Proof_Context.theory_of ctxt in
blanchet@44106
  1114
      t |> cterm_of thy |> Meson.extensionalize_conv ctxt
blanchet@44106
  1115
        |> prop_of |> Logic.dest_equals |> snd
blanchet@44106
  1116
    end
blanchet@44106
  1117
  else
blanchet@44106
  1118
    t
blanchet@38831
  1119
blanchet@44733
  1120
fun simple_translate_lambdas do_lambdas ctxt t =
blanchet@44734
  1121
  let val thy = Proof_Context.theory_of ctxt in
blanchet@44734
  1122
    if Meson.is_fol_term thy t then
blanchet@44734
  1123
      t
blanchet@44734
  1124
    else
blanchet@44734
  1125
      let
blanchet@45676
  1126
        fun trans Ts t =
blanchet@44734
  1127
          case t of
blanchet@45676
  1128
            @{const Not} $ t1 => @{const Not} $ trans Ts t1
blanchet@44734
  1129
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@45676
  1130
            t0 $ Abs (s, T, trans (T :: Ts) t')
blanchet@44734
  1131
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@45676
  1132
            trans Ts (t0 $ eta_expand Ts t1 1)
blanchet@44734
  1133
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@45676
  1134
            t0 $ Abs (s, T, trans (T :: Ts) t')
blanchet@44734
  1135
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@45676
  1136
            trans Ts (t0 $ eta_expand Ts t1 1)
blanchet@45676
  1137
          | (t0 as @{const HOL.conj}) $ t1 $ t2 =>
blanchet@45676
  1138
            t0 $ trans Ts t1 $ trans Ts t2
blanchet@45676
  1139
          | (t0 as @{const HOL.disj}) $ t1 $ t2 =>
blanchet@45676
  1140
            t0 $ trans Ts t1 $ trans Ts t2
blanchet@45676
  1141
          | (t0 as @{const HOL.implies}) $ t1 $ t2 =>
blanchet@45676
  1142
            t0 $ trans Ts t1 $ trans Ts t2
blanchet@44734
  1143
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@44734
  1144
              $ t1 $ t2 =>
blanchet@45676
  1145
            t0 $ trans Ts t1 $ trans Ts t2
blanchet@44734
  1146
          | _ =>
blanchet@44734
  1147
            if not (exists_subterm (fn Abs _ => true | _ => false) t) then t
blanchet@44734
  1148
            else t |> Envir.eta_contract |> do_lambdas ctxt Ts
blanchet@44734
  1149
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@45676
  1150
      in t |> trans [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@44734
  1151
  end
blanchet@44727
  1152
blanchet@44868
  1153
fun do_cheaply_conceal_lambdas Ts (t1 $ t2) =
blanchet@44868
  1154
    do_cheaply_conceal_lambdas Ts t1
blanchet@44868
  1155
    $ do_cheaply_conceal_lambdas Ts t2
blanchet@44868
  1156
  | do_cheaply_conceal_lambdas Ts (Abs (_, T, t)) =
blanchet@46425
  1157
    Const (lam_lifted_poly_prefix ^ serial_string (),
blanchet@46380
  1158
           T --> fastype_of1 (T :: Ts, t))
blanchet@44868
  1159
  | do_cheaply_conceal_lambdas _ t = t
blanchet@44691
  1160
blanchet@44733
  1161
fun do_introduce_combinators ctxt Ts t =
blanchet@44727
  1162
  let val thy = Proof_Context.theory_of ctxt in
blanchet@44776
  1163
    t |> conceal_bounds Ts
blanchet@44776
  1164
      |> cterm_of thy
blanchet@44776
  1165
      |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@44776
  1166
      |> prop_of |> Logic.dest_equals |> snd
blanchet@44776
  1167
      |> reveal_bounds Ts
blanchet@44727
  1168
  end
blanchet@44733
  1169
  (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@44868
  1170
  handle THM _ => t |> do_cheaply_conceal_lambdas Ts
blanchet@44733
  1171
val introduce_combinators = simple_translate_lambdas do_introduce_combinators
blanchet@44727
  1172
blanchet@46385
  1173
fun preprocess_abstractions_in_terms trans_lams facts =
blanchet@44733
  1174
  let
blanchet@44734
  1175
    val (facts, lambda_ts) =
blanchet@46385
  1176
      facts |> map (snd o snd) |> trans_lams
blanchet@44734
  1177
            |>> map2 (fn (name, (kind, _)) => fn t => (name, (kind, t))) facts
blanchet@46425
  1178
    val lam_facts =
blanchet@44734
  1179
      map2 (fn t => fn j =>
blanchet@46425
  1180
               ((lam_fact_prefix ^ Int.toString j, Helper), (Axiom, t)))
blanchet@44734
  1181
           lambda_ts (1 upto length lambda_ts)
blanchet@46425
  1182
  in (facts, lam_facts) end
blanchet@38506
  1183
blanchet@38506
  1184
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@43224
  1185
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38506
  1186
fun freeze_term t =
blanchet@38506
  1187
  let
blanchet@45676
  1188
    fun freeze (t $ u) = freeze t $ freeze u
blanchet@45676
  1189
      | freeze (Abs (s, T, t)) = Abs (s, T, freeze t)
blanchet@45676
  1190
      | freeze (Var ((s, i), T)) =
blanchet@44734
  1191
        Free (atp_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@45676
  1192
      | freeze t = t
blanchet@45676
  1193
  in t |> exists_subterm is_Var t ? freeze end
blanchet@38506
  1194
blanchet@46070
  1195
fun presimp_prop ctxt presimp_consts role t =
blanchet@46070
  1196
  (let
blanchet@46070
  1197
     val thy = Proof_Context.theory_of ctxt
blanchet@46070
  1198
     val t = t |> Envir.beta_eta_contract
blanchet@46070
  1199
               |> transform_elim_prop
blanchet@46070
  1200
               |> Object_Logic.atomize_term thy
blanchet@46070
  1201
     val need_trueprop = (fastype_of t = @{typ bool})
blanchet@46070
  1202
   in
blanchet@46070
  1203
     t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@46070
  1204
       |> Raw_Simplifier.rewrite_term thy (Meson.unfold_set_const_simps ctxt) []
blanchet@46070
  1205
       |> extensionalize_term ctxt
blanchet@46070
  1206
       |> presimplify_term ctxt presimp_consts
blanchet@46070
  1207
       |> HOLogic.dest_Trueprop
blanchet@46070
  1208
   end
blanchet@46070
  1209
   handle TERM _ => if role = Conjecture then @{term False} else @{term True})
blanchet@46070
  1210
  |> pair role
blanchet@43937
  1211
blanchet@45644
  1212
fun make_formula ctxt format type_enc eq_as_iff name loc kind t =
blanchet@43937
  1213
  let
blanchet@46187
  1214
    val (iformula, atomic_Ts) =
blanchet@45644
  1215
      iformula_from_prop ctxt format type_enc eq_as_iff
blanchet@45644
  1216
                         (SOME (kind <> Conjecture)) t []
blanchet@46187
  1217
      |>> close_iformula_universally
blanchet@38506
  1218
  in
blanchet@44730
  1219
    {name = name, locality = loc, kind = kind, iformula = iformula,
blanchet@46187
  1220
     atomic_types = atomic_Ts}
blanchet@38506
  1221
  end
blanchet@38506
  1222
blanchet@44731
  1223
fun make_fact ctxt format type_enc eq_as_iff ((name, loc), t) =
blanchet@45644
  1224
  case t |> make_formula ctxt format type_enc (eq_as_iff andalso format <> CNF)
blanchet@45644
  1225
                         name loc Axiom of
blanchet@45644
  1226
    formula as {iformula = AAtom (IConst ((s, _), _, _)), ...} =>
blanchet@45644
  1227
    if s = tptp_true then NONE else SOME formula
blanchet@45644
  1228
  | formula => SOME formula
blanchet@43432
  1229
blanchet@45317
  1230
fun s_not_trueprop (@{const Trueprop} $ t) = @{const Trueprop} $ s_not t
blanchet@46070
  1231
  | s_not_trueprop t =
blanchet@46070
  1232
    if fastype_of t = @{typ bool} then s_not t else @{prop False} (* too meta *)
blanchet@45317
  1233
blanchet@45644
  1234
fun make_conjecture ctxt format type_enc =
blanchet@45320
  1235
  map (fn ((name, loc), (kind, t)) =>
blanchet@45320
  1236
          t |> kind = Conjecture ? s_not_trueprop
blanchet@45644
  1237
            |> make_formula ctxt format type_enc (format <> CNF) name loc kind)
blanchet@38506
  1238
blanchet@43552
  1239
(** Finite and infinite type inference **)
blanchet@43552
  1240
blanchet@45676
  1241
fun tvar_footprint thy s ary =
blanchet@46382
  1242
  (case unprefix_and_unascii const_prefix s of
blanchet@45676
  1243
     SOME s =>
blanchet@45676
  1244
     s |> invert_const |> robust_const_type thy |> chop_fun ary |> fst
blanchet@45676
  1245
       |> map (fn T => Term.add_tvarsT T [] |> map fst)
blanchet@45676
  1246
   | NONE => [])
blanchet@45676
  1247
  handle TYPE _ => []
blanchet@45676
  1248
blanchet@45676
  1249
fun ghost_type_args thy s ary =
blanchet@45676
  1250
  let
blanchet@45676
  1251
    val footprint = tvar_footprint thy s ary
blanchet@45676
  1252
    fun ghosts _ [] = []
blanchet@45676
  1253
      | ghosts seen ((i, tvars) :: args) =
blanchet@45676
  1254
        ghosts (union (op =) seen tvars) args
blanchet@45676
  1255
        |> exists (not o member (op =) seen) tvars ? cons i
blanchet@45676
  1256
  in
blanchet@45676
  1257
    if forall null footprint then
blanchet@45676
  1258
      []
blanchet@45676
  1259
    else
blanchet@45676
  1260
      0 upto length footprint - 1 ~~ footprint
blanchet@45676
  1261
      |> sort (rev_order o list_ord Term_Ord.indexname_ord o pairself snd)
blanchet@45676
  1262
      |> ghosts []
blanchet@45676
  1263
  end
blanchet@45676
  1264
blanchet@45258
  1265
type monotonicity_info =
blanchet@45258
  1266
  {maybe_finite_Ts : typ list,
blanchet@45258
  1267
   surely_finite_Ts : typ list,
blanchet@45258
  1268
   maybe_infinite_Ts : typ list,
blanchet@45258
  1269
   surely_infinite_Ts : typ list,
blanchet@45258
  1270
   maybe_nonmono_Ts : typ list}
blanchet@45258
  1271
blanchet@45256
  1272
(* These types witness that the type classes they belong to allow infinite
blanchet@45256
  1273
   models and hence that any types with these type classes is monotonic. *)
blanchet@45256
  1274
val known_infinite_types =
blanchet@45492
  1275
  [@{typ nat}, HOLogic.intT, HOLogic.realT, @{typ "nat => bool"}]
blanchet@45256
  1276
blanchet@45355
  1277
fun is_type_kind_of_surely_infinite ctxt soundness cached_Ts T =
blanchet@45492
  1278
  soundness <> Sound andalso is_type_surely_infinite ctxt true cached_Ts T
blanchet@43755
  1279
blanchet@43552
  1280
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@43552
  1281
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@43552
  1282
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@43552
  1283
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@43552
  1284
blanchet@45258
  1285
fun should_encode_type _ (_ : monotonicity_info) All_Types _ = true
blanchet@45258
  1286
  | should_encode_type ctxt {maybe_finite_Ts, surely_infinite_Ts,
blanchet@45258
  1287
                             maybe_nonmono_Ts, ...}
blanchet@45673
  1288
                       (Noninf_Nonmono_Types (soundness, grain)) T =
blanchet@45673
  1289
    grain = Ghost_Type_Arg_Vars orelse
blanchet@45673
  1290
    (exists (type_intersect ctxt T) maybe_nonmono_Ts andalso
blanchet@45673
  1291
     not (exists (type_instance ctxt T) surely_infinite_Ts orelse
blanchet@45730
  1292
          (not (member (type_equiv ctxt) maybe_finite_Ts T) andalso
blanchet@45673
  1293
           is_type_kind_of_surely_infinite ctxt soundness surely_infinite_Ts
blanchet@45673
  1294
                                           T)))
blanchet@45258
  1295
  | should_encode_type ctxt {surely_finite_Ts, maybe_infinite_Ts,
blanchet@45258
  1296
                             maybe_nonmono_Ts, ...}
blanchet@45673
  1297
                       (Fin_Nonmono_Types grain) T =
blanchet@45673
  1298
    grain = Ghost_Type_Arg_Vars orelse
blanchet@45673
  1299
    (exists (type_intersect ctxt T) maybe_nonmono_Ts andalso
blanchet@45673
  1300
     (exists (type_generalization ctxt T) surely_finite_Ts orelse
blanchet@45730
  1301
      (not (member (type_equiv ctxt) maybe_infinite_Ts T) andalso
blanchet@45673
  1302
       is_type_surely_finite ctxt T)))
blanchet@43552
  1303
  | should_encode_type _ _ _ _ = false
blanchet@43552
  1304
blanchet@45639
  1305
fun should_guard_type ctxt mono (Guards (_, level)) should_guard_var T =
blanchet@45673
  1306
    should_guard_var () andalso should_encode_type ctxt mono level T
blanchet@45258
  1307
  | should_guard_type _ _ _ _ _ = false
blanchet@43552
  1308
blanchet@45262
  1309
fun is_maybe_universal_var (IConst ((s, _), _, _)) =
blanchet@45262
  1310
    String.isPrefix bound_var_prefix s orelse
blanchet@45262
  1311
    String.isPrefix all_bound_var_prefix s
blanchet@45262
  1312
  | is_maybe_universal_var (IVar _) = true
blanchet@45262
  1313
  | is_maybe_universal_var _ = false
blanchet@43707
  1314
blanchet@44232
  1315
datatype tag_site =
blanchet@44232
  1316
  Top_Level of bool option |
blanchet@44232
  1317
  Eq_Arg of bool option |
blanchet@45676
  1318
  Arg of string * int |
blanchet@44232
  1319
  Elsewhere
blanchet@43700
  1320
blanchet@44232
  1321
fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
blanchet@45639
  1322
  | should_tag_with_type ctxt mono (Tags (_, level)) site u T =
blanchet@45676
  1323
    (case granularity_of_type_level level of
blanchet@45676
  1324
       All_Vars => should_encode_type ctxt mono level T
blanchet@45676
  1325
     | grain =>
blanchet@45676
  1326
       case (site, is_maybe_universal_var u) of
blanchet@45676
  1327
         (Eq_Arg _, true) => should_encode_type ctxt mono level T
blanchet@45676
  1328
       | (Arg (s, j), true) =>
blanchet@45676
  1329
         grain = Ghost_Type_Arg_Vars andalso
blanchet@45676
  1330
         member (op =)
blanchet@45676
  1331
                (ghost_type_args (Proof_Context.theory_of ctxt) s (j + 1)) j
blanchet@45676
  1332
       | _ => false)
blanchet@43700
  1333
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@43552
  1334
blanchet@45458
  1335
fun fused_type ctxt mono level =
blanchet@43835
  1336
  let
blanchet@45258
  1337
    val should_encode = should_encode_type ctxt mono level
blanchet@45458
  1338
    fun fuse 0 T = if should_encode T then T else fused_infinite_type
blanchet@45458
  1339
      | fuse ary (Type (@{type_name fun}, [T1, T2])) =
blanchet@45458
  1340
        fuse 0 T1 --> fuse (ary - 1) T2
blanchet@45458
  1341
      | fuse _ _ = raise Fail "expected function type"
blanchet@45458
  1342
  in fuse end
blanchet@43552
  1343
blanchet@45307
  1344
(** predicators and application operators **)
blanchet@41561
  1345
blanchet@43445
  1346
type sym_info =
blanchet@45700
  1347
  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list,
blanchet@45700
  1348
   in_conj : bool}
blanchet@43434
  1349
blanchet@45700
  1350
fun default_sym_tab_entries type_enc =
blanchet@45700
  1351
  (make_fixed_const NONE @{const_name undefined},
blanchet@45700
  1352
       {pred_sym = false, min_ary = 0, max_ary = 0, types = [],
blanchet@45700
  1353
        in_conj = false}) ::
blanchet@45700
  1354
  ([tptp_false, tptp_true]
blanchet@45700
  1355
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = [],
blanchet@45700
  1356
                  in_conj = false})) @
blanchet@45700
  1357
  ([tptp_equal, tptp_old_equal]
blanchet@45700
  1358
   |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = [],
blanchet@45700
  1359
                  in_conj = false}))
blanchet@45700
  1360
  |> not (is_type_enc_higher_order type_enc)
blanchet@45700
  1361
     ? cons (prefixed_predicator_name,
blanchet@45700
  1362
             {pred_sym = true, min_ary = 1, max_ary = 1, types = [],
blanchet@45700
  1363
              in_conj = false})
blanchet@45700
  1364
blanchet@45700
  1365
fun sym_table_for_facts ctxt type_enc explicit_apply conjs facts =
blanchet@43429
  1366
  let
blanchet@45643
  1367
    fun consider_var_ary const_T var_T max_ary =
blanchet@43905
  1368
      let
blanchet@43905
  1369
        fun iter ary T =
blanchet@45258
  1370
          if ary = max_ary orelse type_instance ctxt var_T T orelse
blanchet@45258
  1371
             type_instance ctxt T var_T then
blanchet@44051
  1372
            ary
blanchet@44051
  1373
          else
blanchet@44051
  1374
            iter (ary + 1) (range_type T)
blanchet@43905
  1375
      in iter 0 const_T end
blanchet@45262
  1376
    fun add_universal_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@44042
  1377
      if explicit_apply = NONE andalso
blanchet@44042
  1378
         (can dest_funT T orelse T = @{typ bool}) then
blanchet@44042
  1379
        let
blanchet@44042
  1380
          val bool_vars' = bool_vars orelse body_type T = @{typ bool}
blanchet@45700
  1381
          fun repair_min_ary {pred_sym, min_ary, max_ary, types, in_conj} =
blanchet@44042
  1382
            {pred_sym = pred_sym andalso not bool_vars',
blanchet@45643
  1383
             min_ary = fold (fn T' => consider_var_ary T' T) types min_ary,
blanchet@45700
  1384
             max_ary = max_ary, types = types, in_conj = in_conj}
blanchet@44042
  1385
          val fun_var_Ts' =
blanchet@44042
  1386
            fun_var_Ts |> can dest_funT T ? insert_type ctxt I T
blanchet@44042
  1387
        in
blanchet@44042
  1388
          if bool_vars' = bool_vars andalso
blanchet@44042
  1389
             pointer_eq (fun_var_Ts', fun_var_Ts) then
blanchet@44042
  1390
            accum
blanchet@44008
  1391
          else
blanchet@45643
  1392
            ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_ary) sym_tab)
blanchet@44042
  1393
        end
blanchet@44042
  1394
      else
blanchet@44042
  1395
        accum
blanchet@45700
  1396
    fun add_fact_syms conj_fact =
blanchet@45700
  1397
      let
blanchet@45700
  1398
        fun add_iterm_syms top_level tm
blanchet@45700
  1399
                           (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@45700
  1400
          let val (head, args) = strip_iterm_comb tm in
blanchet@45700
  1401
            (case head of
blanchet@45700
  1402
               IConst ((s, _), T, _) =>
blanchet@45700
  1403
               if String.isPrefix bound_var_prefix s orelse
blanchet@45700
  1404
                  String.isPrefix all_bound_var_prefix s then
blanchet@45700
  1405
                 add_universal_var T accum
blanchet@45700
  1406
               else if String.isPrefix exist_bound_var_prefix s then
blanchet@45700
  1407
                 accum
blanchet@45700
  1408
               else
blanchet@45700
  1409
                 let val ary = length args in
blanchet@45700
  1410
                   ((bool_vars, fun_var_Ts),
blanchet@45700
  1411
                    case Symtab.lookup sym_tab s of
blanchet@45700
  1412
                      SOME {pred_sym, min_ary, max_ary, types, in_conj} =>
blanchet@45700
  1413
                      let
blanchet@45700
  1414
                        val pred_sym =
blanchet@45700
  1415
                          pred_sym andalso top_level andalso not bool_vars
blanchet@45700
  1416
                        val types' = types |> insert_type ctxt I T
blanchet@45700
  1417
                        val in_conj = in_conj orelse conj_fact
blanchet@45700
  1418
                        val min_ary =
blanchet@45700
  1419
                          if is_some explicit_apply orelse
blanchet@45700
  1420
                             pointer_eq (types', types) then
blanchet@45700
  1421
                            min_ary
blanchet@45700
  1422
                          else
blanchet@45700
  1423
                            fold (consider_var_ary T) fun_var_Ts min_ary
blanchet@45700
  1424
                      in
blanchet@45700
  1425
                        Symtab.update (s, {pred_sym = pred_sym,
blanchet@45700
  1426
                                           min_ary = Int.min (ary, min_ary),
blanchet@45700
  1427
                                           max_ary = Int.max (ary, max_ary),
blanchet@45700
  1428
                                           types = types', in_conj = in_conj})
blanchet@43905
  1429
                                      sym_tab
blanchet@45700
  1430
                      end
blanchet@45700
  1431
                    | NONE =>
blanchet@45700
  1432
                      let
blanchet@45700
  1433
                        val pred_sym = top_level andalso not bool_vars
blanchet@45700
  1434
                        val min_ary =
blanchet@45700
  1435
                          case explicit_apply of
blanchet@45700
  1436
                            SOME true => 0
blanchet@45700
  1437
                          | SOME false => ary
blanchet@45700
  1438
                          | NONE => fold (consider_var_ary T) fun_var_Ts ary
blanchet@45700
  1439
                      in
blanchet@45700
  1440
                        Symtab.update_new (s,
blanchet@45700
  1441
                            {pred_sym = pred_sym, min_ary = min_ary,
blanchet@45700
  1442
                             max_ary = ary, types = [T], in_conj = conj_fact})
blanchet@45700
  1443
                            sym_tab
blanchet@45700
  1444
                      end)
blanchet@45700
  1445
                 end
blanchet@45700
  1446
             | IVar (_, T) => add_universal_var T accum
blanchet@45700
  1447
             | IAbs ((_, T), tm) =>
blanchet@45700
  1448
               accum |> add_universal_var T |> add_iterm_syms false tm
blanchet@45700
  1449
             | _ => accum)
blanchet@45700
  1450
            |> fold (add_iterm_syms false) args
blanchet@45700
  1451
          end
blanchet@45700
  1452
      in K (add_iterm_syms true) |> formula_fold NONE |> fact_lift end
blanchet@45700
  1453
  in
blanchet@45700
  1454
    ((false, []), Symtab.empty)
blanchet@45700
  1455
    |> fold (add_fact_syms true) conjs
blanchet@45700
  1456
    |> fold (add_fact_syms false) facts
blanchet@45700
  1457
    |> snd
blanchet@45700
  1458
    |> fold Symtab.update (default_sym_tab_entries type_enc)
blanchet@45700
  1459
  end
blanchet@38506
  1460
blanchet@45643
  1461
fun min_ary_of sym_tab s =
blanchet@43429
  1462
  case Symtab.lookup sym_tab s of
blanchet@43445
  1463
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@43429
  1464
  | NONE =>
blanchet@46382
  1465
    case unprefix_and_unascii const_prefix s of
blanchet@43418
  1466
      SOME s =>
blanchet@43441
  1467
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@43807
  1468
        if s = predicator_name then 1
blanchet@43807
  1469
        else if s = app_op_name then 2
blanchet@45255
  1470
        else if s = type_guard_name then 1
blanchet@43428
  1471
        else 0
blanchet@43418
  1472
      end
blanchet@38506
  1473
    | NONE => 0
blanchet@38506
  1474
blanchet@38506
  1475
(* True if the constant ever appears outside of the top-level position in
blanchet@38506
  1476
   literals, or if it appears with different arities (e.g., because of different
blanchet@38506
  1477
   type instantiations). If false, the constant always receives all of its
blanchet@38506
  1478
   arguments and is used as a predicate. *)
blanchet@43429
  1479
fun is_pred_sym sym_tab s =
blanchet@43429
  1480
  case Symtab.lookup sym_tab s of
blanchet@43445
  1481
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@43445
  1482
    pred_sym andalso min_ary = max_ary
blanchet@43429
  1483
  | NONE => false
blanchet@38506
  1484
blanchet@45644
  1485
val app_op = `(make_fixed_const NONE) app_op_name
blanchet@43439
  1486
val predicator_combconst =
nik@45350
  1487
  IConst (`(make_fixed_const NONE) predicator_name, @{typ "bool => bool"}, [])
blanchet@45644
  1488
blanchet@45644
  1489
fun list_app head args = fold (curry (IApp o swap)) args head
blanchet@44730
  1490
fun predicator tm = IApp (predicator_combconst, tm)
blanchet@38506
  1491
blanchet@45645
  1492
fun firstorderize_fact thy format type_enc sym_tab =
blanchet@43415
  1493
  let
blanchet@45644
  1494
    fun do_app arg head =
blanchet@45644
  1495
      let
blanchet@45644
  1496
        val head_T = ityp_of head
blanchet@45644
  1497
        val (arg_T, res_T) = dest_funT head_T
blanchet@45644
  1498
        val app =
blanchet@45644
  1499
          IConst (app_op, head_T --> head_T, [arg_T, res_T])
blanchet@45645
  1500
          |> mangle_type_args_in_iterm format type_enc
blanchet@45644
  1501
      in list_app app [head, arg] end
blanchet@45644
  1502
    fun list_app_ops head args = fold do_app args head
blanchet@45644
  1503
    fun introduce_app_ops tm =
blanchet@44730
  1504
      case strip_iterm_comb tm of
blanchet@44730
  1505
        (head as IConst ((s, _), _, _), args) =>
blanchet@45644
  1506
        args |> map introduce_app_ops
blanchet@45643
  1507
             |> chop (min_ary_of sym_tab s)
blanchet@43415
  1508
             |>> list_app head
blanchet@45644
  1509
             |-> list_app_ops
blanchet@45644
  1510
      | (head, args) => list_app_ops head (map introduce_app_ops args)
blanchet@45644
  1511
    fun introduce_predicators tm =
blanchet@45644
  1512
      case strip_iterm_comb tm of
blanchet@45644
  1513
        (IConst ((s, _), _, _), _) =>
blanchet@45644
  1514
        if is_pred_sym sym_tab s then tm else predicator tm
blanchet@45644
  1515
      | _ => predicator tm
blanchet@45644
  1516
    val do_iterm =
blanchet@45644
  1517
      not (is_type_enc_higher_order type_enc)
blanchet@45644
  1518
      ? (introduce_app_ops #> introduce_predicators)
blanchet@45645
  1519
      #> filter_type_args_in_iterm thy type_enc
blanchet@45644
  1520
  in update_iformula (formula_map do_iterm) end
blanchet@43444
  1521
blanchet@43444
  1522
(** Helper facts **)
blanchet@43444
  1523
blanchet@45307
  1524
val not_ffalse = @{lemma "~ fFalse" by (unfold fFalse_def) fast}
blanchet@45307
  1525
val ftrue = @{lemma "fTrue" by (unfold fTrue_def) fast}
blanchet@45307
  1526
blanchet@44035
  1527
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@43926
  1528
val helper_table =
blanchet@44035
  1529
  [(("COMBI", false), @{thms Meson.COMBI_def}),
blanchet@44035
  1530
   (("COMBK", false), @{thms Meson.COMBK_def}),
blanchet@44035
  1531
   (("COMBB", false), @{thms Meson.COMBB_def}),
blanchet@44035
  1532
   (("COMBC", false), @{thms Meson.COMBC_def}),
blanchet@44035
  1533
   (("COMBS", false), @{thms Meson.COMBS_def}),
blanchet@45307
  1534
   ((predicator_name, false), [not_ffalse, ftrue]),
blanchet@45307
  1535
   (("fFalse", false), [not_ffalse]),
blanchet@44035
  1536
   (("fFalse", true), @{thms True_or_False}),
blanchet@45307
  1537
   (("fTrue", false), [ftrue]),
blanchet@44035
  1538
   (("fTrue", true), @{thms True_or_False}),
blanchet@44035
  1539
   (("fNot", false),
blanchet@44035
  1540
    @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@44035
  1541
           fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@44035
  1542
   (("fconj", false),
blanchet@44035
  1543
    @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@44035
  1544
        by (unfold fconj_def) fast+}),
blanchet@44035
  1545
   (("fdisj", false),
blanchet@44035
  1546
    @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@44035
  1547
        by (unfold fdisj_def) fast+}),
blanchet@44035
  1548
   (("fimplies", false),
blanchet@44051
  1549
    @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
blanchet@44035
  1550
        by (unfold fimplies_def) fast+}),
nik@44537
  1551
   (("fequal", true),
nik@44537
  1552
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
nik@44537
  1553
       However, this is done so for backward compatibility: Including the
nik@44537
  1554
       equality helpers by default in Metis breaks a few existing proofs. *)
nik@44537
  1555
    @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
nik@44537
  1556
           fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@44874
  1557
   (* Partial characterization of "fAll" and "fEx". A complete characterization
blanchet@44874
  1558
      would require the axiom of choice for replay with Metis. *)
blanchet@44874
  1559
   (("fAll", false), [@{lemma "~ fAll P | P x" by (auto simp: fAll_def)}]),
blanchet@44874
  1560
   (("fEx", false), [@{lemma "~ P x | fEx P" by (auto simp: fEx_def)}]),
blanchet@44035
  1561
   (("If", true), @{thms if_True if_False True_or_False})]
blanchet@44035
  1562
  |> map (apsnd (map zero_var_indexes))
blanchet@43926
  1563
blanchet@46225
  1564
fun atype_of_type_vars (Simple_Types (_, Polymorphic, _)) = SOME atype_of_types
blanchet@46225
  1565
  | atype_of_type_vars _ = NONE
blanchet@46225
  1566
blanchet@46187
  1567
fun bound_tvars type_enc Ts =
blanchet@46187
  1568
  mk_ahorn (formulas_for_types type_enc add_sorts_on_tvar Ts)
blanchet@46187
  1569
  #> mk_aquant AForall
blanchet@46187
  1570
        (map_filter (fn TVar (x as (s, _), _) =>
blanchet@46187
  1571
                        SOME ((make_schematic_type_var x, s),
blanchet@46225
  1572
                              atype_of_type_vars type_enc)
blanchet@46187
  1573
                      | _ => NONE) Ts)
blanchet@45263
  1574
blanchet@45263
  1575
fun eq_formula type_enc atomic_Ts pred_sym tm1 tm2 =
blanchet@45263
  1576
  (if pred_sym then AConn (AIff, [AAtom tm1, AAtom tm2])
blanchet@45263
  1577
   else AAtom (ATerm (`I tptp_equal, [tm1, tm2])))
blanchet@46248
  1578
  |> close_formula_universally
blanchet@45263
  1579
  |> bound_tvars type_enc atomic_Ts
blanchet@45263
  1580
nik@45350
  1581
val type_tag = `(make_fixed_const NONE) type_tag_name
blanchet@43971
  1582
blanchet@46172
  1583
fun type_tag_idempotence_fact format type_enc =
blanchet@43444
  1584
  let
blanchet@43444
  1585
    fun var s = ATerm (`I s, [])
blanchet@45267
  1586
    fun tag tm = ATerm (type_tag, [var "A", tm])
blanchet@45267
  1587
    val tagged_var = tag (var "X")
blanchet@43444
  1588
  in
blanchet@44000
  1589
    Formula (type_tag_idempotence_helper_name, Axiom,
blanchet@45264
  1590
             eq_formula type_enc [] false (tag tagged_var) tagged_var,
blanchet@46172
  1591
             isabelle_info format simpN, NONE)
blanchet@43444
  1592
  end
blanchet@43444
  1593
blanchet@44493
  1594
fun should_specialize_helper type_enc t =
blanchet@45348
  1595
  polymorphism_of_type_enc type_enc <> Polymorphic andalso
blanchet@44495
  1596
  level_of_type_enc type_enc <> No_Types andalso
blanchet@44495
  1597
  not (null (Term.hidden_polymorphism t))
blanchet@44000
  1598
blanchet@44729
  1599
fun helper_facts_for_sym ctxt format type_enc (s, {types, ...} : sym_info) =
blanchet@46382
  1600
  case unprefix_and_unascii const_prefix s of
blanchet@43444
  1601
    SOME mangled_s =>
blanchet@43444
  1602
    let
blanchet@43444
  1603
      val thy = Proof_Context.theory_of ctxt
blanchet@43444
  1604
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@44495
  1605
      fun dub needs_fairly_sound j k =
blanchet@44495
  1606
        (unmangled_s ^ "_" ^ string_of_int j ^ "_" ^ string_of_int k ^
blanchet@44495
  1607
         (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
blanchet@44495
  1608
         (if needs_fairly_sound then typed_helper_suffix
blanchet@44495
  1609
          else untyped_helper_suffix),
blanchet@44495
  1610
         Helper)
blanchet@44000
  1611
      fun dub_and_inst needs_fairly_sound (th, j) =
blanchet@44495
  1612
        let val t = prop_of th in
blanchet@44495
  1613
          if should_specialize_helper type_enc t then
blanchet@44495
  1614
            map (fn T => specialize_type thy (invert_const unmangled_s, T) t)
blanchet@44495
  1615
                types
blanchet@44495
  1616
          else
blanchet@44495
  1617
            [t]
blanchet@44495
  1618
        end
blanchet@44495
  1619
        |> map (fn (k, t) => (dub needs_fairly_sound j k, t)) o tag_list 1
blanchet@44731
  1620
      val make_facts = map_filter (make_fact ctxt format type_enc false)
blanchet@44493
  1621
      val fairly_sound = is_type_enc_fairly_sound type_enc
blanchet@43444
  1622
    in
blanchet@43926
  1623
      helper_table
blanchet@44035
  1624
      |> maps (fn ((helper_s, needs_fairly_sound), ths) =>
blanchet@44000
  1625
                  if helper_s <> unmangled_s orelse
blanchet@43765
  1626
                     (needs_fairly_sound andalso not fairly_sound) then
blanchet@43444
  1627
                    []
blanchet@43444
  1628
                  else
blanchet@43444
  1629
                    ths ~~ (1 upto length ths)
blanchet@44495
  1630
                    |> maps (dub_and_inst needs_fairly_sound)
blanchet@44000
  1631
                    |> make_facts)
blanchet@43444
  1632
    end
blanchet@43444
  1633
  | NONE => []
blanchet@44729
  1634
fun helper_facts_for_sym_table ctxt format type_enc sym_tab =
blanchet@44729
  1635
  Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_enc) sym_tab
blanchet@44729
  1636
                  []
blanchet@43444
  1637
blanchet@43926
  1638
(***************************************************************)
blanchet@43926
  1639
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@43926
  1640
(***************************************************************)
blanchet@43926
  1641
blanchet@43926
  1642
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@43926
  1643
blanchet@43926
  1644
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@43926
  1645
blanchet@43926
  1646
(* Remove this trivial type class (FIXME: similar code elsewhere) *)
blanchet@43926
  1647
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
blanchet@43926
  1648
blanchet@43934
  1649
fun classes_of_terms get_Ts =
blanchet@43962
  1650
  map (map snd o get_Ts)
blanchet@43934
  1651
  #> List.foldl add_classes Symtab.empty
blanchet@43934
  1652
  #> delete_type #> Symtab.keys
blanchet@43926
  1653
wenzelm@45004
  1654
val tfree_classes_of_terms = classes_of_terms Misc_Legacy.term_tfrees
wenzelm@45004
  1655
val tvar_classes_of_terms = classes_of_terms Misc_Legacy.term_tvars
blanchet@43926
  1656
blanchet@44489
  1657
fun fold_type_constrs f (Type (s, Ts)) x =
blanchet@44489
  1658
    fold (fold_type_constrs f) Ts (f (s, x))
blanchet@44030
  1659
  | fold_type_constrs _ _ x = x
blanchet@43926
  1660
blanchet@44778
  1661
(* Type constructors used to instantiate overloaded constants are the only ones
blanchet@44778
  1662
   needed. *)
blanchet@44030
  1663
fun add_type_constrs_in_term thy =
blanchet@43926
  1664
  let
blanchet@44029
  1665
    fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@44022
  1666
      | add (t $ u) = add t #> add u
blanchet@45602
  1667
      | add (Const x) =
blanchet@45602
  1668
        x |> robust_const_typargs thy |> fold (fold_type_constrs set_insert)
blanchet@44022
  1669
      | add (Abs (_, _, u)) = add u
blanchet@44022
  1670
      | add _ = I
blanchet@44022
  1671
  in add end
blanchet@43926
  1672
blanchet@44030
  1673
fun type_constrs_of_terms thy ts =
blanchet@44030
  1674
  Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
blanchet@43926
  1675
blanchet@46382
  1676
fun extract_lambda_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
blanchet@46382
  1677
    let val (head, args) = strip_comb t in
blanchet@46382
  1678
      (head |> dest_Const |> fst,
blanchet@46382
  1679
       fold_rev (fn t as Var ((s, _), T) =>
blanchet@46382
  1680
                    (fn u => Abs (s, T, abstract_over (t, u)))
blanchet@46382
  1681
                  | _ => raise Fail "expected Var") args u)
blanchet@46382
  1682
    end
blanchet@46382
  1683
  | extract_lambda_def _ = raise Fail "malformed lifted lambda"
blanchet@46379
  1684
blanchet@46385
  1685
fun trans_lams_from_string ctxt type_enc lam_trans =
blanchet@46385
  1686
  if lam_trans = no_lamsN then
blanchet@46385
  1687
    rpair []
blanchet@46385
  1688
  else if lam_trans = hide_lamsN then
blanchet@46385
  1689
    lift_lams ctxt type_enc ##> K []
blanchet@46385
  1690
  else if lam_trans = lam_liftingN then
blanchet@46385
  1691
    lift_lams ctxt type_enc
blanchet@46385
  1692
  else if lam_trans = combinatorsN then
blanchet@46385
  1693
    map (introduce_combinators ctxt) #> rpair []
blanchet@46385
  1694
  else if lam_trans = hybrid_lamsN then
blanchet@46425
  1695
    lift_lams_part_1 ctxt type_enc
blanchet@46385
  1696
    ##> maps (fn t => [t, introduce_combinators ctxt (intentionalize_def t)])
blanchet@46425
  1697
    #> lift_lams_part_2
blanchet@46385
  1698
  else if lam_trans = keep_lamsN then
blanchet@46385
  1699
    map (Envir.eta_contract) #> rpair []
blanchet@46385
  1700
  else
blanchet@46390
  1701
    error ("Unknown lambda translation scheme: " ^ quote lam_trans ^ ".")
blanchet@46385
  1702
blanchet@46385
  1703
fun translate_formulas ctxt format prem_kind type_enc lam_trans presimp hyp_ts
blanchet@46385
  1704
                       concl_t facts =
blanchet@43444
  1705
  let
blanchet@43444
  1706
    val thy = Proof_Context.theory_of ctxt
blanchet@46385
  1707
    val trans_lams = trans_lams_from_string ctxt type_enc lam_trans
blanchet@44105
  1708
    val presimp_consts = Meson.presimplified_consts ctxt
blanchet@44732
  1709
    val fact_ts = facts |> map snd
blanchet@43444
  1710
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@43444
  1711
       boost an ATP's performance (for some reason). *)
blanchet@44033
  1712
    val hyp_ts =
blanchet@44033
  1713
      hyp_ts
blanchet@44033
  1714
      |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
blanchet@44735
  1715
    val facts = facts |> map (apsnd (pair Axiom))
blanchet@44735
  1716
    val conjs =
blanchet@45317
  1717
      map (pair prem_kind) hyp_ts @ [(Conjecture, s_not_trueprop concl_t)]
blanchet@46039
  1718
      |> map (apsnd freeze_term)
blanchet@44734
  1719
      |> map2 (pair o rpair Local o string_of_int) (0 upto length hyp_ts)
blanchet@46425
  1720
    val ((conjs, facts), lam_facts) =
blanchet@46382
  1721
      (conjs, facts)
blanchet@46382
  1722
      |> presimp
blanchet@46382
  1723
         ? pairself (map (apsnd (uncurry (presimp_prop ctxt presimp_consts))))
blanchet@46385
  1724
      |> (if lam_trans = no_lamsN then
blanchet@46382
  1725
            rpair []
blanchet@46382
  1726
          else
blanchet@46382
  1727
            op @
blanchet@46385
  1728
            #> preprocess_abstractions_in_terms trans_lams
blanchet@46382
  1729
            #>> chop (length conjs))
blanchet@45644
  1730
    val conjs = conjs |> make_conjecture ctxt format type_enc
blanchet@44734
  1731
    val (fact_names, facts) =
blanchet@44735
  1732
      facts
blanchet@44734
  1733
      |> map_filter (fn (name, (_, t)) =>
blanchet@44734
  1734
                        make_fact ctxt format type_enc true (name, t)
blanchet@44734
  1735
                        |> Option.map (pair name))
blanchet@44732
  1736
      |> ListPair.unzip
blanchet@46425
  1737
    val lifted = lam_facts |> map (extract_lambda_def o snd o snd)
blanchet@46425
  1738
    val lam_facts =
blanchet@46425
  1739
      lam_facts |> map_filter (make_fact ctxt format type_enc true o apsnd snd)
blanchet@44732
  1740
    val all_ts = concl_t :: hyp_ts @ fact_ts
blanchet@43444
  1741
    val subs = tfree_classes_of_terms all_ts
blanchet@43444
  1742
    val supers = tvar_classes_of_terms all_ts
blanchet@44030
  1743
    val tycons = type_constrs_of_terms thy all_ts
blanchet@44732
  1744
    val (supers, arity_clauses) =
blanchet@44493
  1745
      if level_of_type_enc type_enc = No_Types then ([], [])
blanchet@43444
  1746
      else make_arity_clauses thy tycons supers
blanchet@44732
  1747
    val class_rel_clauses = make_class_rel_clauses thy subs supers
blanchet@43444
  1748
  in
blanchet@46379
  1749
    (fact_names |> map single, union (op =) subs supers, conjs,
blanchet@46425
  1750
     facts @ lam_facts, class_rel_clauses, arity_clauses, lifted)
blanchet@43444
  1751
  end
blanchet@43444
  1752
nik@45350
  1753
val type_guard = `(make_fixed_const NONE) type_guard_name
blanchet@43971
  1754
blanchet@45645
  1755
fun type_guard_iterm format type_enc T tm =
blanchet@45255
  1756
  IApp (IConst (type_guard, T --> @{typ bool}, [T])
blanchet@45645
  1757
        |> mangle_type_args_in_iterm format type_enc, tm)
blanchet@43444
  1758
blanchet@44282
  1759
fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
blanchet@44282
  1760
  | is_var_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
blanchet@43841
  1761
    accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
blanchet@44558
  1762
  | is_var_positively_naked_in_term _ _ _ _ = true
blanchet@45262
  1763
blanchet@45673
  1764
fun is_var_ghost_type_arg_in_term thy name pos tm accum =
blanchet@45673
  1765
  is_var_positively_naked_in_term name pos tm accum orelse
blanchet@45673
  1766
  let
blanchet@45673
  1767
    val var = ATerm (name, [])
blanchet@45673
  1768
    fun is_nasty_in_term (ATerm (_, [])) = false
blanchet@45673
  1769
      | is_nasty_in_term (ATerm ((s, _), tms)) =
blanchet@45673
  1770
        (member (op =) tms var andalso
blanchet@45673
  1771
         let val ary = length tms in
blanchet@45673
  1772
           case ghost_type_args thy s ary of
blanchet@45673
  1773
             [] => false
blanchet@45673
  1774
           | ghosts =>
blanchet@45673
  1775
             exists (fn (j, tm) => tm = var andalso member (op =) ghosts j)
blanchet@45673
  1776
                    (0 upto length tms - 1 ~~ tms)
blanchet@45673
  1777
         end) orelse
blanchet@45673
  1778
        exists is_nasty_in_term tms
blanchet@45673
  1779
      | is_nasty_in_term _ = true
blanchet@45673
  1780
  in is_nasty_in_term tm end
blanchet@45673
  1781
blanchet@45673
  1782
fun should_guard_var_in_formula thy level pos phi (SOME true) name =
blanchet@45673
  1783
    (case granularity_of_type_level level of
blanchet@45673
  1784
       All_Vars => true
blanchet@45673
  1785
     | Positively_Naked_Vars =>
blanchet@45673
  1786
       formula_fold pos (is_var_positively_naked_in_term name) phi false
blanchet@45673
  1787
     | Ghost_Type_Arg_Vars =>
blanchet@45673
  1788
       formula_fold pos (is_var_ghost_type_arg_in_term thy name) phi false)
blanchet@45673
  1789
  | should_guard_var_in_formula _ _ _ _ _ _ = true
blanchet@43705
  1790
blanchet@45264
  1791
fun should_generate_tag_bound_decl _ _ _ (SOME true) _ = false
blanchet@45639
  1792
  | should_generate_tag_bound_decl ctxt mono (Tags (_, level)) _ T =
blanchet@45673
  1793
    granularity_of_type_level level <> All_Vars andalso
blanchet@45650
  1794
    should_encode_type ctxt mono level T
blanchet@45264
  1795
  | should_generate_tag_bound_decl _ _ _ _ _ = false
blanchet@45263
  1796
nik@44536
  1797
fun mk_aterm format type_enc name T_args args =
nik@44536
  1798
  ATerm (name, map_filter (ho_term_for_type_arg format type_enc) T_args @ args)
blanchet@43835
  1799
blanchet@45258
  1800
fun tag_with_type ctxt format mono type_enc pos T tm =
blanchet@44730
  1801
  IConst (type_tag, T --> T, [T])
blanchet@45645
  1802
  |> mangle_type_args_in_iterm format type_enc
blanchet@45258
  1803
  |> ho_term_from_iterm ctxt format mono type_enc (Top_Level pos)
blanchet@44558
  1804
  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm])
blanchet@44558
  1805
       | _ => raise Fail "unexpected lambda-abstraction")
blanchet@45258
  1806
and ho_term_from_iterm ctxt format mono type_enc =
blanchet@43444
  1807
  let
blanchet@45676
  1808
    fun term site u =
blanchet@43803
  1809
      let
blanchet@44730
  1810
        val (head, args) = strip_iterm_comb u
nik@44536
  1811
        val pos =
nik@44536
  1812
          case site of
nik@44536
  1813
            Top_Level pos => pos
nik@44536
  1814
          | Eq_Arg pos => pos
blanchet@45676
  1815
          | _ => NONE
nik@44536
  1816
        val t =
blanchet@43803
  1817
          case head of
blanchet@44730
  1818
            IConst (name as (s, _), _, T_args) =>
nik@44536
  1819
            let
blanchet@45676
  1820
              fun arg_site j =
blanchet@45676
  1821
                if is_tptp_equal s then Eq_Arg pos else Arg (s, j)
nik@44536
  1822
            in
blanchet@45676
  1823
              mk_aterm format type_enc name T_args
blanchet@45676
  1824
                       (map2 (term o arg_site) (0 upto length args - 1) args)
nik@44536
  1825
            end
blanchet@44730
  1826
          | IVar (name, _) =>
blanchet@45676
  1827
            mk_aterm format type_enc name [] (map (term Elsewhere) args)
blanchet@44730
  1828
          | IAbs ((name, T), tm) =>
blanchet@44730
  1829
            AAbs ((name, ho_type_from_typ format type_enc true 0 T),
blanchet@45676
  1830
                  term Elsewhere tm)
blanchet@44730
  1831
          | IApp _ => raise Fail "impossible \"IApp\""
blanchet@44730
  1832
        val T = ityp_of u
blanchet@43803
  1833
      in
blanchet@45258
  1834
        t |> (if should_tag_with_type ctxt mono type_enc site u T then
blanchet@45258
  1835
                tag_with_type ctxt format mono type_enc pos T
blanchet@43803
  1836
              else
blanchet@43803
  1837
                I)
blanchet@43803
  1838
      end
blanchet@45676
  1839
  in term end
blanchet@45258
  1840
and formula_from_iformula ctxt format mono type_enc should_guard_var =
blanchet@43700
  1841
  let
blanchet@45673
  1842
    val thy = Proof_Context.theory_of ctxt
blanchet@45673
  1843
    val level = level_of_type_enc type_enc
blanchet@45258
  1844
    val do_term = ho_term_from_iterm ctxt format mono type_enc o Top_Level
blanchet@43444
  1845
    val do_bound_type =
blanchet@44493
  1846
      case type_enc of
blanchet@45673
  1847
        Simple_Types _ => fused_type ctxt mono level 0
nik@44536
  1848
        #> ho_type_from_typ format type_enc false 0 #> SOME
blanchet@43552
  1849
      | _ => K NONE
blanchet@43747
  1850
    fun do_out_of_bound_type pos phi universal (name, T) =
blanchet@45258
  1851
      if should_guard_type ctxt mono type_enc
blanchet@45673
  1852
             (fn () => should_guard_var thy level pos phi universal name) T then
blanchet@44730
  1853
        IVar (name, T)
blanchet@45645
  1854
        |> type_guard_iterm format type_enc T
blanchet@44232
  1855
        |> do_term pos |> AAtom |> SOME
blanchet@45264
  1856
      else if should_generate_tag_bound_decl ctxt mono type_enc universal T then
blanchet@45264
  1857
        let
blanchet@45264
  1858
          val var = ATerm (name, [])
blanchet@45360
  1859
          val tagged_var = var |> tag_with_type ctxt format mono type_enc pos T
blanchet@45264
  1860
        in SOME (AAtom (ATerm (`I tptp_equal, [tagged_var, var]))) end
blanchet@43444
  1861
      else
blanchet@43444
  1862
        NONE
blanchet@43747
  1863
    fun do_formula pos (AQuant (q, xs, phi)) =
blanchet@43747
  1864
        let
blanchet@43747
  1865
          val phi = phi |> do_formula pos
blanchet@43747
  1866
          val universal = Option.map (q = AExists ? not) pos
blanchet@43747
  1867
        in
blanchet@43705
  1868
          AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@43705
  1869
                                        | SOME T => do_bound_type T)),
blanchet@43705
  1870
                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@43705
  1871
                      (map_filter
blanchet@43705
  1872
                           (fn (_, NONE) => NONE
blanchet@43705
  1873
                             | (s, SOME T) =>
blanchet@43747
  1874
                               do_out_of_bound_type pos phi universal (s, T))
blanchet@43747
  1875
                           xs)
blanchet@43705
  1876
                      phi)
blanchet@43705
  1877
        end
blanchet@43747
  1878
      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
blanchet@44232
  1879
      | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
blanchet@44364
  1880
  in do_formula end
blanchet@43444
  1881
blanchet@43444
  1882
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@43444
  1883
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@43444
  1884
   the remote provers might care. *)
blanchet@45258
  1885
fun formula_line_for_fact ctxt format prefix encode freshen pos mono type_enc
blanchet@45258
  1886
                          (j, {name, locality, kind, iformula, atomic_types}) =
blanchet@44735
  1887
  (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name, kind,
blanchet@44730
  1888
   iformula
blanchet@45258
  1889
   |> formula_from_iformula ctxt format mono type_enc
blanchet@45258
  1890
                            should_guard_var_in_formula
blanchet@44730
  1891
                            (if pos then SOME true else NONE)
blanchet@46248
  1892
   |> close_formula_universally
blanchet@46186
  1893
   |> bound_tvars type_enc atomic_types,
blanchet@44364
  1894
   NONE,
blanchet@44364
  1895
   case locality of
blanchet@46172
  1896
     Intro => isabelle_info format introN
blanchet@46172
  1897
   | Elim => isabelle_info format elimN
blanchet@46172
  1898
   | Simp => isabelle_info format simpN
blanchet@44364
  1899
   | _ => NONE)
blanchet@44364
  1900
  |> Formula
blanchet@43444
  1901
blanchet@46172
  1902
fun formula_line_for_class_rel_clause format type_enc
blanchet@45457
  1903
        ({name, subclass, superclass, ...} : class_rel_clause) =
blanchet@45480
  1904
  let val ty_arg = ATerm (tvar_a_name, []) in
blanchet@43448
  1905
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@45480
  1906
             AConn (AImplies,
blanchet@45483
  1907
                    [type_class_formula type_enc subclass ty_arg,
blanchet@45483
  1908
                     type_class_formula type_enc superclass ty_arg])
blanchet@46248
  1909
             |> close_formula_universally,
blanchet@46172
  1910
             isabelle_info format introN, NONE)
blanchet@43444
  1911
  end
blanchet@43444
  1912
blanchet@45483
  1913
fun formula_from_arity_atom type_enc (class, t, args) =
blanchet@45483
  1914
  ATerm (t, map (fn arg => ATerm (arg, [])) args)
blanchet@45483
  1915
  |> type_class_formula type_enc class
blanchet@43444
  1916
blanchet@46172
  1917
fun formula_line_for_arity_clause format type_enc
blanchet@46225
  1918
        ({name, prem_atoms, concl_atom} : arity_clause) =
blanchet@44366
  1919
  Formula (arity_clause_prefix ^ name, Axiom,
blanchet@45483
  1920
           mk_ahorn (map (formula_from_arity_atom type_enc) prem_atoms)
blanchet@45483
  1921
                    (formula_from_arity_atom type_enc concl_atom)
blanchet@46225
  1922
           |> mk_aquant AForall
blanchet@46225
  1923
                  (map (rpair (atype_of_type_vars type_enc)) (#3 concl_atom)),
blanchet@46172
  1924
           isabelle_info format introN, NONE)
blanchet@43444
  1925
blanchet@45258
  1926
fun formula_line_for_conjecture ctxt format mono type_enc
blanchet@44730
  1927
        ({name, kind, iformula, atomic_types, ...} : translated_formula) =
blanchet@43448
  1928
  Formula (conjecture_prefix ^ name, kind,
blanchet@46187
  1929
           iformula
blanchet@46187
  1930
           |> formula_from_iformula ctxt format mono type_enc
blanchet@46187
  1931
                  should_guard_var_in_formula (SOME false)
blanchet@46248
  1932
           |> close_formula_universally
blanchet@46186
  1933
           |> bound_tvars type_enc atomic_types, NONE, NONE)
blanchet@43444
  1934
blanchet@45483
  1935
fun formula_line_for_free_type j phi =
blanchet@45483
  1936
  Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis, phi, NONE, NONE)
blanchet@45484
  1937
fun formula_lines_for_free_types type_enc (facts : translated_formula list) =
blanchet@43444
  1938
  let
blanchet@45483
  1939
    val phis =
blanchet@45483
  1940
      fold (union (op =)) (map #atomic_types facts) []
blanchet@45483
  1941
      |> formulas_for_types type_enc add_sorts_on_tfree
blanchet@45483
  1942
  in map2 formula_line_for_free_type (0 upto length phis - 1) phis end
blanchet@43444
  1943
blanchet@43444
  1944
(** Symbol declarations **)
blanchet@43415
  1945
blanchet@45618
  1946
fun decl_line_for_class order s =
blanchet@45459
  1947
  let val name as (s, _) = `make_type_class s in
blanchet@45480
  1948
    Decl (sym_decl_prefix ^ s, name,
blanchet@46172
  1949
          if order = First_Order andalso avoid_first_order_ghost_type_vars then
blanchet@45618
  1950
            ATyAbs ([tvar_a_name], AFun (a_itself_atype, bool_atype))
blanchet@45480
  1951
          else
blanchet@45618
  1952
            AFun (atype_of_types, bool_atype))
blanchet@45459
  1953
  end
blanchet@45459
  1954
blanchet@45459
  1955
fun decl_lines_for_classes type_enc classes =
blanchet@45459
  1956
  case type_enc of
blanchet@45618
  1957
    Simple_Types (order, Polymorphic, _) =>
blanchet@45618
  1958
    map (decl_line_for_class order) classes
blanchet@45459
  1959
  | _ => []
blanchet@45459
  1960
blanchet@45644
  1961
fun sym_decl_table_for_facts ctxt format type_enc sym_tab (conjs, facts) =
blanchet@43445
  1962
  let
blanchet@45700
  1963
    fun add_iterm_syms tm =
blanchet@44730
  1964
      let val (head, args) = strip_iterm_comb tm in
blanchet@43445
  1965
        (case head of
blanchet@44730
  1966
           IConst ((s, s'), T, T_args) =>
blanchet@45458
  1967
           let
blanchet@45700
  1968
             val (pred_sym, in_conj) =
blanchet@45700
  1969
               case Symtab.lookup sym_tab s of
blanchet@45724
  1970
                 SOME ({pred_sym, in_conj, ...} : sym_info) =>
blanchet@45724
  1971
                 (pred_sym, in_conj)
blanchet@45700
  1972
               | NONE => (false, false)
blanchet@45458
  1973
             val decl_sym =
blanchet@45458
  1974
               (case type_enc of
blanchet@45458
  1975
                  Guards _ => not pred_sym
blanchet@45458
  1976
                | _ => true) andalso
blanchet@45458
  1977
               is_tptp_user_symbol s
blanchet@45458
  1978
           in
blanchet@45458
  1979
             if decl_sym then
blanchet@43447
  1980
               Symtab.map_default (s, [])
blanchet@43755
  1981
                   (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
blanchet@43755
  1982
                                         in_conj))
blanchet@43445
  1983
             else
blanchet@43445
  1984
               I
blanchet@43445
  1985
           end
blanchet@45700
  1986
         | IAbs (_, tm) => add_iterm_syms tm
blanchet@43445
  1987
         | _ => I)
blanchet@45700
  1988
        #> fold add_iterm_syms args
blanchet@43445
  1989
      end
blanchet@45700
  1990
    val add_fact_syms = K add_iterm_syms |> formula_fold NONE |> fact_lift
blanchet@44837
  1991
    fun add_formula_var_types (AQuant (_, xs, phi)) =
blanchet@44837
  1992
        fold (fn (_, SOME T) => insert_type ctxt I T | _ => I) xs
blanchet@44837
  1993
        #> add_formula_var_types phi
blanchet@44837
  1994
      | add_formula_var_types (AConn (_, phis)) =
blanchet@44837
  1995
        fold add_formula_var_types phis
blanchet@44837
  1996
      | add_formula_var_types _ = I
blanchet@44837
  1997
    fun var_types () =
blanchet@44837
  1998
      if polymorphism_of_type_enc type_enc = Polymorphic then [tvar_a]
blanchet@44837
  1999
      else fold (fact_lift add_formula_var_types) (conjs @ facts) []
blanchet@44837
  2000
    fun add_undefined_const T =
blanchet@44855
  2001
      let
blanchet@44855
  2002
        val (s, s') =
blanchet@45480
  2003
          `(make_fixed_const NONE) @{const_name undefined}
blanchet@44872
  2004
          |> (case type_arg_policy type_enc @{const_name undefined} of
blanchet@45642
  2005
                Mangled_Type_Args => mangled_const_name format type_enc [T]
blanchet@44872
  2006
              | _ => I)
blanchet@44855
  2007
      in
blanchet@44855
  2008
        Symtab.map_default (s, [])
blanchet@44855
  2009
                           (insert_type ctxt #3 (s', [T], T, false, 0, false))
blanchet@44855
  2010
      end
blanchet@45480
  2011
    fun add_TYPE_const () =
blanchet@45480
  2012
      let val (s, s') = TYPE_name in
blanchet@45480
  2013
        Symtab.map_default (s, [])
blanchet@45480
  2014
            (insert_type ctxt #3
blanchet@45480
  2015
                         (s', [tvar_a], @{typ "'a itself"}, false, 0, false))
blanchet@45480
  2016
      end
blanchet@43568
  2017
  in
blanchet@43568
  2018
    Symtab.empty
blanchet@44493
  2019
    |> is_type_enc_fairly_sound type_enc
blanchet@45700
  2020
       ? (fold (fold add_fact_syms) [conjs, facts]
blanchet@44856
  2021
          #> (case type_enc of
blanchet@45654
  2022
                Simple_Types (First_Order, Polymorphic, _) => add_TYPE_const ()
blanchet@45654
  2023
              | Simple_Types _ => I
blanchet@44856
  2024
              | _ => fold add_undefined_const (var_types ())))
blanchet@43568
  2025
  end
blanchet@43445
  2026
blanchet@45258
  2027
(* We add "bool" in case the helper "True_or_False" is included later. *)
blanchet@45492
  2028
fun default_mono level =
blanchet@45258
  2029
  {maybe_finite_Ts = [@{typ bool}],
blanchet@45258
  2030
   surely_finite_Ts = [@{typ bool}],
blanchet@45258
  2031
   maybe_infinite_Ts = known_infinite_types,
blanchet@45492
  2032
   surely_infinite_Ts =
blanchet@45492
  2033
     case level of
blanchet@45639
  2034
       Noninf_Nonmono_Types (Sound, _) => []
blanchet@45492
  2035
     | _ => known_infinite_types,
blanchet@45258
  2036
   maybe_nonmono_Ts = [@{typ bool}]}
blanchet@45258
  2037
blanchet@43555
  2038
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@43555
  2039
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@45258
  2040
fun add_iterm_mononotonicity_info _ _ (SOME false) _ mono = mono
blanchet@45258
  2041
  | add_iterm_mononotonicity_info ctxt level _
blanchet@45258
  2042
        (IApp (IApp (IConst ((s, _), Type (_, [T, _]), _), tm1), tm2))
blanchet@45258
  2043
        (mono as {maybe_finite_Ts, surely_finite_Ts, maybe_infinite_Ts,
blanchet@45258
  2044
                  surely_infinite_Ts, maybe_nonmono_Ts}) =
blanchet@45262
  2045
    if is_tptp_equal s andalso exists is_maybe_universal_var [tm1, tm2] then
blanchet@45258
  2046
      case level of
blanchet@45639
  2047
        Noninf_Nonmono_Types (soundness, _) =>
blanchet@45258
  2048
        if exists (type_instance ctxt T) surely_infinite_Ts orelse
blanchet@45730
  2049
           member (type_equiv ctxt) maybe_finite_Ts T then
blanchet@45258
  2050
          mono
blanchet@45355
  2051
        else if is_type_kind_of_surely_infinite ctxt soundness
blanchet@45355
  2052
                                                surely_infinite_Ts T then
blanchet@45258
  2053
          {maybe_finite_Ts = maybe_finite_Ts,
blanchet@45258
  2054
           surely_finite_Ts = surely_finite_Ts,
blanchet@45258
  2055
           maybe_infinite_Ts = maybe_infinite_Ts,
blanchet@45258
  2056
           surely_infinite_Ts = surely_infinite_Ts |> insert_type ctxt I T,
blanchet@45258
  2057
           maybe_nonmono_Ts = maybe_nonmono_Ts}
blanchet@45258
  2058
        else
blanchet@45730
  2059
          {maybe_finite_Ts = maybe_finite_Ts |> insert (type_equiv ctxt) T,
blanchet@45258
  2060
           surely_finite_Ts = surely_finite_Ts,
blanchet@45258
  2061
           maybe_infinite_Ts = maybe_infinite_Ts,
blanchet@45258
  2062
           surely_infinite_Ts = surely_infinite_Ts,
blanchet@45258
  2063
           maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
blanchet@45639
  2064
      | Fin_Nonmono_Types _ =>
blanchet@45258
  2065
        if exists (type_instance ctxt T) surely_finite_Ts orelse
blanchet@45730
  2066
           member (type_equiv ctxt) maybe_infinite_Ts T then
blanchet@45258
  2067
          mono
blanchet@45258
  2068
        else if is_type_surely_finite ctxt T then
blanchet@45258
  2069
          {maybe_finite_Ts = maybe_finite_Ts,
blanchet@45258
  2070
           surely_finite_Ts = surely_finite_Ts |> insert_type ctxt I T,
blanchet@45258
  2071
           maybe_infinite_Ts = maybe_infinite_Ts,
blanchet@45258
  2072
           surely_infinite_Ts = surely_infinite_Ts,
blanchet@45258
  2073
           maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type ctxt I T}
blanchet@45258
  2074
        else
blanchet@45258
  2075
          {maybe_finite_Ts = maybe_finite_Ts,
blanchet@45258
  2076
           surely_finite_Ts = surely_finite_Ts,
blanchet@45730
  2077
           maybe_infinite_Ts = maybe_infinite_Ts |> insert (type_equiv ctxt) T,
blanchet@45258
  2078
           surely_infinite_Ts = surely_infinite_Ts,
blanchet@45258
  2079
           maybe_nonmono_Ts = maybe_nonmono_Ts}
blanchet@45258
  2080
      | _ => mono
blanchet@45258
  2081
    else
blanchet@45258
  2082
      mono
blanchet@45258
  2083
  | add_iterm_mononotonicity_info _ _ _ _ mono = mono
blanchet@45258
  2084
fun add_fact_mononotonicity_info ctxt level
blanchet@45258
  2085
        ({kind, iformula, ...} : translated_formula) =
blanchet@43705
  2086
  formula_fold (SOME (kind <> Conjecture))
blanchet@45258
  2087
               (add_iterm_mononotonicity_info ctxt level) iformula
blanchet@45258
  2088
fun mononotonicity_info_for_facts ctxt type_enc facts =
blanchet@44493
  2089
  let val level = level_of_type_enc type_enc in
blanchet@45492
  2090
    default_mono level
blanchet@45258
  2091
    |> is_type_level_monotonicity_based level
blanchet@45258
  2092
       ? fold (add_fact_mononotonicity_info ctxt level) facts
blanchet@43700
  2093
  end
blanchet@43547
  2094
blanchet@45356
  2095
fun add_iformula_monotonic_types ctxt mono type_enc =
blanchet@45356
  2096
  let
blanchet@45356
  2097
    val level = level_of_type_enc type_enc
blanchet@45356
  2098
    val should_encode = should_encode_type ctxt mono level
blanchet@45359
  2099
    fun add_type T = not (should_encode T) ? insert_type ctxt I T
blanchet@45361
  2100
    fun add_args (IApp (tm1, tm2)) = add_args tm1 #> add_term tm2
blanchet@45361
  2101
      | add_args _ = I
blanchet@45361
  2102
    and add_term tm = add_type (ityp_of tm) #> add_args tm
blanchet@45356
  2103
  in formula_fold NONE (K add_term) end
blanchet@45356
  2104
fun add_fact_monotonic_types ctxt mono type_enc =
blanchet@45356
  2105
  add_iformula_monotonic_types ctxt mono type_enc |> fact_lift
blanchet@45356
  2106
fun monotonic_types_for_facts ctxt mono type_enc facts =
blanchet@45673
  2107
  let val level = level_of_type_enc type_enc in
blanchet@45673
  2108
    [] |> (polymorphism_of_type_enc type_enc = Polymorphic andalso
blanchet@45673
  2109
           is_type_level_monotonicity_based level andalso
blanchet@45673
  2110
           granularity_of_type_level level <> Ghost_Type_Arg_Vars)
blanchet@45673
  2111
          ? fold (add_fact_monotonic_types ctxt mono type_enc) facts
blanchet@45673
  2112
  end
blanchet@45356
  2113
blanchet@45258
  2114
fun formula_line_for_guards_mono_type ctxt format mono type_enc T =
blanchet@45255
  2115
  Formula (guards_sym_formula_prefix ^
blanchet@45255
  2116
           ascii_of (mangled_type format type_enc T),
blanchet@45255
  2117
           Axiom,
blanchet@45255
  2118
           IConst (`make_bound_var "X", T, [])
blanchet@45645
  2119
           |> type_guard_iterm format type_enc T
blanchet@45255
  2120
           |> AAtom
blanchet@45258
  2121
           |> formula_from_iformula ctxt format mono type_enc
blanchet@45673
  2122
                                    (K (K (K (K (K (K true)))))) (SOME true)
blanchet@46248
  2123
           |> close_formula_universally
blanchet@46187
  2124
           |> bound_tvars type_enc (atomic_types_of T),
blanchet@46172
  2125
           isabelle_info format introN, NONE)
blanchet@45255
  2126
blanchet@45258
  2127
fun formula_line_for_tags_mono_type ctxt format mono type_enc T =
blanchet@45255
  2128
  let val x_var = ATerm (`make_bound_var "X", []) in
blanchet@45255
  2129
    Formula (tags_sym_formula_prefix ^
blanchet@45255
  2130
             ascii_of (mangled_type format type_enc T),
blanchet@45255
  2131
             Axiom,
blanchet@46187
  2132
             eq_formula type_enc (atomic_types_of T) false
blanchet@45258
  2133
                        (tag_with_type ctxt format mono type_enc NONE T x_var)
blanchet@45255
  2134
                        x_var,
blanchet@46172
  2135
             isabelle_info format simpN, NONE)
blanchet@45255
  2136
  end
blanchet@45255
  2137
blanchet@45258
  2138
fun problem_lines_for_mono_types ctxt format mono type_enc Ts =
blanchet@45255
  2139
  case type_enc of
blanchet@45255
  2140
    Simple_Types _ => []
blanchet@45255
  2141
  | Guards _ =>
blanchet@45258
  2142
    map (formula_line_for_guards_mono_type ctxt format mono type_enc) Ts
blanchet@45258
  2143
  | Tags _ => map (formula_line_for_tags_mono_type ctxt format mono type_enc) Ts
blanchet@45255
  2144
blanchet@45258
  2145
fun decl_line_for_sym ctxt format mono type_enc s
blanchet@43835
  2146
                      (s', T_args, T, pred_sym, ary, _) =
blanchet@43835
  2147
  let
blanchet@45458
  2148
    val thy = Proof_Context.theory_of ctxt
blanchet@45458
  2149
    val (T, T_args) =
blanchet@45458
  2150
      if null T_args then
blanchet@45458
  2151
        (T, [])
blanchet@46382
  2152
      else case unprefix_and_unascii const_prefix s of
blanchet@45458
  2153
        SOME s' =>
blanchet@45458
  2154
        let
blanchet@45458
  2155
          val s' = s' |> invert_const
blanchet@45458
  2156
          val T = s' |> robust_const_type thy
blanchet@45458
  2157
        in (T, robust_const_typargs thy (s', T)) end
blanchet@46380
  2158
      | NONE => raise Fail "unexpected type arguments"
blanchet@43835
  2159
  in
blanchet@43839
  2160
    Decl (sym_decl_prefix ^ s, (s, s'),
blanchet@45458
  2161
          T |> fused_type ctxt mono (level_of_type_enc type_enc) ary
blanchet@45458
  2162
            |> ho_type_from_typ format type_enc pred_sym ary
blanchet@45458
  2163
            |> not (null T_args)
blanchet@45458
  2164
               ? curry ATyAbs (map (tvar_name o fst o dest_TVar) T_args))
blanchet@43835
  2165
  end
blanchet@43450
  2166
blanchet@45258
  2167
fun formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono type_enc n s
blanchet@45258
  2168
                                     j (s', T_args, T, _, ary, in_conj) =
blanchet@43450
  2169
  let
blanchet@45673
  2170
    val thy = Proof_Context.theory_of ctxt
blanchet@43580
  2171
    val (kind, maybe_negate) =
blanchet@43580
  2172
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@43580
  2173
      else (Axiom, I)
blanchet@43618
  2174
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@45676
  2175
    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  2176
    val bounds =
blanchet@44730
  2177
      bound_names ~~ arg_Ts |> map (fn (name, T) => IConst (name, T, []))
blanchet@43450
  2178
    val bound_Ts =
blanchet@45673
  2179
      if exists (curry (op =) dummyT) T_args then
blanchet@45673
  2180
        case level_of_type_enc type_enc of
blanchet@45673
  2181
          All_Types => map SOME arg_Ts
blanchet@45673
  2182
        | level =>
blanchet@45673
  2183
          if granularity_of_type_level level = Ghost_Type_Arg_Vars then
blanchet@45673
  2184
            let val ghosts = ghost_type_args thy s ary in
blanchet@45673
  2185
              map2 (fn j => if member (op =) ghosts j then SOME else K NONE)
blanchet@45676
  2186
                   (0 upto ary - 1) arg_Ts
blanchet@45673
  2187
            end
blanchet@45673
  2188
          else
blanchet@45676
  2189
            replicate ary NONE
blanchet@45673
  2190
      else
blanchet@45676
  2191
        replicate ary NONE
blanchet@43450
  2192
  in
blanchet@44860
  2193
    Formula (guards_sym_formula_prefix ^ s ^
blanchet@43580
  2194
             (if n > 1 then "_" ^ string_of_int j else ""), kind,
blanchet@44730
  2195
             IConst ((s, s'), T, T_args)
blanchet@44730
  2196
             |> fold (curry (IApp o swap)) bounds
blanchet@45645
  2197
             |> type_guard_iterm format type_enc res_T
blanchet@43804
  2198
             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@45258
  2199
             |> formula_from_iformula ctxt format mono type_enc
blanchet@45673
  2200
                                      (K (K (K (K (K (K true)))))) (SOME true)
blanchet@46248
  2201
             |> close_formula_universally
blanchet@46187
  2202
             |> n > 1 ? bound_tvars type_enc (atomic_types_of T)
blanchet@43580
  2203
             |> maybe_negate,
blanchet@46172
  2204
             isabelle_info format introN, NONE)
blanchet@43450
  2205
  end
blanchet@43450
  2206
blanchet@45673
  2207
fun formula_lines_for_tags_sym_decl ctxt format conj_sym_kind mono type_enc n s
blanchet@45673
  2208
        (j, (s', T_args, T, pred_sym, ary, in_conj)) =
blanchet@43700
  2209
  let
blanchet@45676
  2210
    val thy = Proof_Context.theory_of ctxt
blanchet@45676
  2211
    val level = level_of_type_enc type_enc
blanchet@45676
  2212
    val grain = granularity_of_type_level level
blanchet@43700
  2213
    val ident_base =
blanchet@45255
  2214
      tags_sym_formula_prefix ^ s ^
blanchet@43966
  2215
      (if n > 1 then "_" ^ string_of_int j else "")
blanchet@43721
  2216
    val (kind, maybe_negate) =
blanchet@43721
  2217
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@43721
  2218
      else (Axiom, I)
blanchet@43700
  2219
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@45676
  2220
    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  2221
    val bounds = bound_names |> map (fn name => ATerm (name, []))
nik@44536
  2222
    val cst = mk_aterm format type_enc (s, s') T_args
blanchet@46187
  2223
    val eq = maybe_negate oo eq_formula type_enc (atomic_types_of T) pred_sym
blanchet@45676
  2224
    val should_encode = should_encode_type ctxt mono level
blanchet@45258
  2225
    val tag_with = tag_with_type ctxt format mono type_enc NONE
blanchet@43700
  2226
    val add_formula_for_res =
blanchet@43700
  2227
      if should_encode res_T then
blanchet@45676
  2228
        let
blanchet@45676
  2229
          val tagged_bounds =
blanchet@45676
  2230
            if grain = Ghost_Type_Arg_Vars then
blanchet@45676
  2231
              let val ghosts = ghost_type_args thy s ary in
blanchet@45676
  2232
                map2 (fn (j, arg_T) => member (op =) ghosts j ? tag_with arg_T)
blanchet@45676
  2233
                     (0 upto ary - 1 ~~ arg_Ts) bounds
blanchet@45676
  2234
              end
blanchet@45676
  2235
            else
blanchet@45676
  2236
              bounds
blanchet@45676
  2237
        in
blanchet@45676
  2238
          cons (Formula (ident_base ^ "_res", kind,
blanchet@45676
  2239
                         eq (tag_with res_T (cst bounds)) (cst tagged_bounds),
blanchet@46172
  2240
                         isabelle_info format simpN, NONE))
blanchet@45676
  2241
        end
blanchet@43700
  2242
      else
blanchet@43700
  2243
        I
blanchet@43700
  2244
    fun add_formula_for_arg k =
blanchet@43700
  2245
      let val arg_T = nth arg_Ts k in
blanchet@43700
  2246
        if should_encode arg_T then
blanchet@43700
  2247
          case chop k bounds of
blanchet@43700
  2248
            (bounds1, bound :: bounds2) =>
blanchet@43721
  2249
            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
blanchet@45255
  2250
                           eq (cst (bounds1 @ tag_with arg_T bound :: bounds2))
blanchet@45255
  2251
                              (cst bounds),
blanchet@46172
  2252
                           isabelle_info format simpN, NONE))
blanchet@43700
  2253
          | _ => raise Fail "expected nonempty tail"
blanchet@43700
  2254
        else
blanchet@43700
  2255
          I
blanchet@43700
  2256
      end
blanchet@43700
  2257
  in
blanchet@43705
  2258
    [] |> not pred_sym ? add_formula_for_res
blanchet@45676
  2259
       |> (Config.get ctxt type_tag_arguments andalso
blanchet@45676
  2260
           grain = Positively_Naked_Vars)
blanchet@45351
  2261
          ? fold add_formula_for_arg (ary - 1 downto 0)
blanchet@43700
  2262
  end
blanchet@43700
  2263
blanchet@43707
  2264
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@43707
  2265
blanchet@45258
  2266
fun problem_lines_for_sym_decls ctxt format conj_sym_kind mono type_enc
blanchet@45255
  2267
                                (s, decls) =
blanchet@44493
  2268
  case type_enc of
blanchet@43839
  2269
    Simple_Types _ =>
blanchet@45258
  2270
    decls |> map (decl_line_for_sym ctxt format mono type_enc s)
blanchet@45639
  2271
  | Guards (_, level) =>
blanchet@43839
  2272
    let
blanchet@43839
  2273
      val decls =
blanchet@43839
  2274
        case decls of
blanchet@43839
  2275
          decl :: (decls' as _ :: _) =>
blanchet@43839
  2276
          let val T = result_type_of_decl decl in
blanchet@45258
  2277
            if forall (type_generalization ctxt T o result_type_of_decl)
blanchet@45258
  2278
                      decls' then
blanchet@43839
  2279
              [decl]
blanchet@43839
  2280
            else
blanchet@43839
  2281
              decls
blanchet@43839
  2282
          end
blanchet@43839
  2283
        | _ => decls
blanchet@43839
  2284
      val n = length decls
blanchet@43839
  2285
      val decls =
blanchet@45258
  2286
        decls |> filter (should_encode_type ctxt mono level
blanchet@44264
  2287
                         o result_type_of_decl)
blanchet@43839
  2288
    in
blanchet@43839
  2289
      (0 upto length decls - 1, decls)
blanchet@45258
  2290
      |-> map2 (formula_line_for_guards_sym_decl ctxt format conj_sym_kind mono
blanchet@45258
  2291
                                                 type_enc n s)
blanchet@43839
  2292
    end
blanchet@45639
  2293
  | Tags (_, level) =>
blanchet@45673
  2294
    if granularity_of_type_level level = All_Vars then
blanchet@45639
  2295
      []
blanchet@45639
  2296
    else
blanchet@45639
  2297
      let val n = length decls in
blanchet@45639
  2298
        (0 upto n - 1 ~~ decls)
blanchet@45673
  2299
        |> maps (formula_lines_for_tags_sym_decl ctxt format conj_sym_kind mono
blanchet@45673
  2300
                                                 type_enc n s)
blanchet@45639
  2301
      end
blanchet@43450
  2302
blanchet@45258
  2303
fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono type_enc
blanchet@45356
  2304
                                     mono_Ts sym_decl_tab =
blanchet@45255
  2305
  let
blanchet@45255
  2306
    val syms = sym_decl_tab |> Symtab.dest |> sort_wrt fst
blanchet@45255
  2307
    val mono_lines =
blanchet@45258
  2308
      problem_lines_for_mono_types ctxt format mono type_enc mono_Ts
blanchet@45255
  2309
    val decl_lines =
blanchet@45255
  2310
      fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
blanchet@45258
  2311
                                                     mono type_enc)
blanchet@45255
  2312
               syms []
blanchet@45255
  2313
  in mono_lines @ decl_lines end
blanchet@43414
  2314
blanchet@45639
  2315
fun needs_type_tag_idempotence ctxt (Tags (poly, level)) =
blanchet@45351
  2316
    Config.get ctxt type_tag_idempotence andalso
blanchet@45639
  2317
    is_type_level_monotonicity_based level andalso
blanchet@45639
  2318
    poly <> Mangled_Monomorphic
blanchet@45351
  2319
  | needs_type_tag_idempotence _ _ = false
blanchet@43702
  2320
blanchet@43839
  2321
val implicit_declsN = "Should-be-implicit typings"
blanchet@43839
  2322
val explicit_declsN = "Explicit typings"
blanchet@41405
  2323
val factsN = "Relevant facts"
blanchet@41405
  2324
val class_relsN = "Class relationships"
blanchet@43414
  2325
val aritiesN = "Arities"
blanchet@41405
  2326
val helpersN = "Helper facts"
blanchet@41405
  2327
val conjsN = "Conjectures"
blanchet@41561
  2328
val free_typesN = "Type variables"
blanchet@41405
  2329
blanchet@45674
  2330
val explicit_apply_threshold = 50
blanchet@44100
  2331
blanchet@45256
  2332
fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_enc exporter
blanchet@46385
  2333
                        lam_trans readable_names preproc hyp_ts concl_t facts =
blanchet@38506
  2334
  let
blanchet@45645
  2335
    val thy = Proof_Context.theory_of ctxt
blanchet@45275
  2336
    val type_enc = type_enc |> adjust_type_enc format
blanchet@45674
  2337
    (* Forcing explicit applications is expensive for polymorphic encodings,
blanchet@45674
  2338
       because it takes only one existential variable ranging over "'a => 'b" to
blanchet@45674
  2339
       ruin everything. Hence we do it only if there are few facts. *)
blanchet@45674
  2340
    val explicit_apply =
blanchet@45674
  2341
      if polymorphism_of_type_enc type_enc <> Polymorphic orelse
blanchet@45674
  2342
         length facts <= explicit_apply_threshold then
blanchet@45674
  2343
        NONE
blanchet@45674
  2344
      else
blanchet@45674
  2345
        SOME false
blanchet@46385
  2346
    val lam_trans =
blanchet@46391
  2347
      if lam_trans = keep_lamsN andalso
blanchet@46391
  2348
         not (is_type_enc_higher_order type_enc) then
blanchet@46390
  2349
        error ("Lambda translation scheme incompatible with first-order \
blanchet@44959
  2350
               \encoding.")
blanchet@44959
  2351
      else
blanchet@46385
  2352
        lam_trans
blanchet@46379
  2353
    val (fact_names, classes, conjs, facts, class_rel_clauses, arity_clauses,
blanchet@46379
  2354
         lifted) =
blanchet@46385
  2355
      translate_formulas ctxt format prem_kind type_enc lam_trans preproc hyp_ts
blanchet@46385
  2356
                         concl_t facts
blanchet@45654
  2357
    val sym_tab =
blanchet@45700
  2358
      sym_table_for_facts ctxt type_enc explicit_apply conjs facts
blanchet@45258
  2359
    val mono = conjs @ facts |> mononotonicity_info_for_facts ctxt type_enc
blanchet@45645
  2360
    val firstorderize = firstorderize_fact thy format type_enc sym_tab
blanchet@45644
  2361
    val (conjs, facts) = (conjs, facts) |> pairself (map firstorderize)
blanchet@45700
  2362
    val sym_tab = sym_table_for_facts ctxt type_enc (SOME false) conjs facts
blanchet@43444
  2363
    val helpers =
blanchet@45644
  2364
      sym_tab |> helper_facts_for_sym_table ctxt format type_enc
blanchet@45644
  2365
              |> map firstorderize
blanchet@45356
  2366
    val mono_Ts =
blanchet@45356
  2367
      helpers @ conjs @ facts
blanchet@45356
  2368
      |> monotonic_types_for_facts ctxt mono type_enc
blanchet@45459
  2369
    val class_decl_lines = decl_lines_for_classes type_enc classes
blanchet@43550
  2370
    val sym_decl_lines =
blanchet@43596
  2371
      (conjs, helpers @ facts)
blanchet@45644
  2372
      |> sym_decl_table_for_facts ctxt format type_enc sym_tab
blanchet@45258
  2373
      |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind mono
blanchet@45356
  2374
                                               type_enc mono_Ts
blanchet@43750
  2375
    val helper_lines =
blanchet@43797
  2376
      0 upto length helpers - 1 ~~ helpers
blanchet@45258
  2377
      |> map (formula_line_for_fact ctxt format helper_prefix I false true mono
blanchet@45258
  2378
                                    type_enc)
blanchet@45351
  2379
      |> (if needs_type_tag_idempotence ctxt type_enc then
blanchet@46172
  2380
            cons (type_tag_idempotence_fact format type_enc)
blanchet@44000
  2381
          else
blanchet@44000
  2382
            I)
blanchet@43393
  2383
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43880
  2384
       FLOTTER hack. *)
blanchet@38506
  2385
    val problem =
blanchet@45459
  2386
      [(explicit_declsN, class_decl_lines @ sym_decl_lines),
blanchet@43797
  2387
       (factsN,
blanchet@44372
  2388
        map (formula_line_for_fact ctxt format fact_prefix ascii_of
blanchet@45459
  2389
                                   (not exporter) (not exporter) mono type_enc)
blanchet@43797
  2390
            (0 upto length facts - 1 ~~ facts)),
blanchet@45457
  2391
       (class_relsN,
blanchet@46172
  2392
        map (formula_line_for_class_rel_clause format type_enc)
blanchet@46172
  2393
            class_rel_clauses),
blanchet@46172
  2394
       (aritiesN,
blanchet@46172
  2395
        map (formula_line_for_arity_clause format type_enc) arity_clauses),
blanchet@43750
  2396
       (helpersN, helper_lines),
blanchet@43803
  2397
       (conjsN,
blanchet@45258
  2398
        map (formula_line_for_conjecture ctxt format mono type_enc) conjs),
blanchet@44493
  2399
       (free_typesN, formula_lines_for_free_types type_enc (facts @ conjs))]
blanchet@43414
  2400
    val problem =
blanchet@43432
  2401
      problem
blanchet@43933
  2402
      |> (case format of
blanchet@43933
  2403
            CNF => ensure_cnf_problem
blanchet@43933
  2404
          | CNF_UEQ => filter_cnf_ueq_problem
blanchet@45453
  2405
          | FOF => I
blanchet@45618
  2406
          | TFF (_, TPTP_Implicit) => I
blanchet@45618
  2407
          | THF (_, TPTP_Implicit, _) => I
blanchet@45453
  2408
          | _ => declare_undeclared_syms_in_atp_problem type_decl_prefix
blanchet@45453
  2409
                                                        implicit_declsN)
blanchet@43933
  2410
    val (problem, pool) = problem |> nice_atp_problem readable_names
blanchet@45643
  2411
    fun add_sym_ary (s, {min_ary, ...} : sym_info) =
blanchet@45644
  2412
      min_ary > 0 ? Symtab.insert (op =) (s, min_ary)
blanchet@38506
  2413
  in
blanchet@38506
  2414
    (problem,
blanchet@38506
  2415
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@43620
  2416
     fact_names |> Vector.fromList,
blanchet@46379
  2417
     lifted,
blanchet@45643
  2418
     Symtab.empty |> Symtab.fold add_sym_ary sym_tab)
blanchet@38506
  2419
  end
blanchet@38506
  2420
blanchet@41561
  2421
(* FUDGE *)
blanchet@41561
  2422
val conj_weight = 0.0
blanchet@42641
  2423
val hyp_weight = 0.1
blanchet@42641
  2424
val fact_min_weight = 0.2
blanchet@41561
  2425
val fact_max_weight = 1.0
blanchet@43479
  2426
val type_info_default_weight = 0.8
blanchet@41561
  2427
blanchet@41561
  2428
fun add_term_weights weight (ATerm (s, tms)) =
nik@44535
  2429
    is_tptp_user_symbol s ? Symtab.default (s, weight)
nik@44535
  2430
    #> fold (add_term_weights weight) tms
nik@44535
  2431
  | add_term_weights weight (AAbs (_, tm)) = add_term_weights weight tm
blanchet@43448
  2432
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@43705
  2433
    formula_fold NONE (K (add_term_weights weight)) phi
blanchet@43399
  2434
  | add_problem_line_weights _ _ = I
blanchet@41561
  2435
blanchet@41561
  2436
fun add_conjectures_weights [] = I
blanchet@41561
  2437
  | add_conjectures_weights conjs =
blanchet@41561
  2438
    let val (hyps, conj) = split_last conjs in
blanchet@41561
  2439
      add_problem_line_weights conj_weight conj
blanchet@41561
  2440
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41561
  2441
    end
blanchet@41561
  2442
blanchet@41561
  2443
fun add_facts_weights facts =
blanchet@41561
  2444
  let
blanchet@41561
  2445
    val num_facts = length facts
blanchet@41561
  2446
    fun weight_of j =
blanchet@41561
  2447
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41561
  2448
                        / Real.fromInt num_facts
blanchet@41561
  2449
  in
blanchet@41561
  2450
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41561
  2451
    |> fold (uncurry add_problem_line_weights)
blanchet@41561
  2452
  end
blanchet@41561
  2453
blanchet@41561
  2454
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41561
  2455
fun atp_problem_weights problem =
blanchet@43479
  2456
  let val get = these o AList.lookup (op =) problem in
blanchet@43479
  2457
    Symtab.empty
blanchet@43479
  2458
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@43479
  2459
    |> add_facts_weights (get factsN)
blanchet@43479
  2460
    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
blanchet@43839
  2461
            [explicit_declsN, class_relsN, aritiesN]
blanchet@43479
  2462
    |> Symtab.dest
blanchet@43479
  2463
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@43479
  2464
  end
blanchet@41561
  2465
blanchet@38506
  2466
end;