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