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