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