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