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