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