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