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