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