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