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