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