src/HOL/Tools/ATP/atp_translate.ML
author blanchet
Mon Aug 22 15:02:45 2011 +0200 (2011-08-22)
changeset 44397 06375952f1fa
parent 44396 66b9b3fcd608
child 44398 d21f7e330ec8
permissions -rw-r--r--
cleaner handling of polymorphic monotonicity inference
wenzelm@43283
     1
(*  Title:      HOL/Tools/ATP/atp_translate.ML
blanchet@38282
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38282
     3
    Author:     Makarius
blanchet@38282
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38282
     5
blanchet@43863
     6
Translation of HOL to FOL for Metis and Sledgehammer.
blanchet@38282
     7
*)
blanchet@38282
     8
blanchet@43085
     9
signature ATP_TRANSLATE =
blanchet@38282
    10
sig
nik@43676
    11
  type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
blanchet@43136
    12
  type connective = ATP_Problem.connective
blanchet@43136
    13
  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
blanchet@42939
    14
  type format = ATP_Problem.format
blanchet@42709
    15
  type formula_kind = ATP_Problem.formula_kind
blanchet@38282
    16
  type 'a problem = 'a ATP_Problem.problem
blanchet@43085
    17
blanchet@43421
    18
  datatype locality =
blanchet@43421
    19
    General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
blanchet@43421
    20
    Chained
blanchet@42613
    21
blanchet@43624
    22
  datatype order = First_Order | Higher_Order
blanchet@42613
    23
  datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@44397
    24
  datatype soundness = Unsound | Sound_Modulo_Infiniteness | Sound
blanchet@42613
    25
  datatype type_level =
blanchet@44397
    26
    All_Types |
blanchet@44397
    27
    Noninf_Nonmono_Types of soundness |
blanchet@44397
    28
    Fin_Nonmono_Types |
blanchet@44397
    29
    Const_Arg_Types |
blanchet@43362
    30
    No_Types
blanchet@43128
    31
  datatype type_heaviness = Heavyweight | Lightweight
blanchet@42613
    32
blanchet@43626
    33
  datatype type_enc =
blanchet@43624
    34
    Simple_Types of order * type_level |
blanchet@43989
    35
    Guards of polymorphism * type_level * type_heaviness |
blanchet@42837
    36
    Tags of polymorphism * type_level * type_heaviness
blanchet@42613
    37
blanchet@44088
    38
  val no_lambdasN : string
blanchet@44088
    39
  val concealedN : string
blanchet@44088
    40
  val liftingN : string
blanchet@44088
    41
  val combinatorsN : string
blanchet@44088
    42
  val hybridN : string
blanchet@44088
    43
  val lambdasN : string
blanchet@44088
    44
  val smartN : string
blanchet@43085
    45
  val bound_var_prefix : string
blanchet@43496
    46
  val schematic_var_prefix : string
blanchet@43496
    47
  val fixed_var_prefix : string
blanchet@43496
    48
  val tvar_prefix : string
blanchet@43496
    49
  val tfree_prefix : string
blanchet@43496
    50
  val const_prefix : string
blanchet@43496
    51
  val type_const_prefix : string
blanchet@43496
    52
  val class_prefix : string
blanchet@43936
    53
  val polymorphic_free_prefix : string
blanchet@43085
    54
  val skolem_const_prefix : string
blanchet@43085
    55
  val old_skolem_const_prefix : string
blanchet@43085
    56
  val new_skolem_const_prefix : string
blanchet@43125
    57
  val type_decl_prefix : string
blanchet@43125
    58
  val sym_decl_prefix : string
blanchet@43989
    59
  val guards_sym_formula_prefix : string
blanchet@44396
    60
  val tags_sym_formula_prefix : string
blanchet@40204
    61
  val fact_prefix : string
blanchet@38282
    62
  val conjecture_prefix : string
blanchet@42881
    63
  val helper_prefix : string
blanchet@43125
    64
  val class_rel_clause_prefix : string
blanchet@43125
    65
  val arity_clause_prefix : string
blanchet@43125
    66
  val tfree_clause_prefix : string
blanchet@42881
    67
  val typed_helper_suffix : string
blanchet@43125
    68
  val untyped_helper_suffix : string
blanchet@43159
    69
  val type_tag_idempotence_helper_name : string
blanchet@42966
    70
  val predicator_name : string
blanchet@42966
    71
  val app_op_name : string
blanchet@44396
    72
  val type_guard_name : string
blanchet@43104
    73
  val type_tag_name : string
blanchet@42962
    74
  val simple_type_prefix : string
blanchet@43174
    75
  val prefixed_predicator_name : string
blanchet@43130
    76
  val prefixed_app_op_name : string
blanchet@43130
    77
  val prefixed_type_tag_name : string
blanchet@43496
    78
  val ascii_of : string -> string
blanchet@43496
    79
  val unascii_of : string -> string
blanchet@43085
    80
  val strip_prefix_and_unascii : string -> string -> string option
blanchet@43159
    81
  val proxy_table : (string * (string * (thm * (string * string)))) list
blanchet@43159
    82
  val proxify_const : string -> (string * string) option
blanchet@43496
    83
  val invert_const : string -> string
blanchet@43496
    84
  val unproxify_const : string -> string
blanchet@43093
    85
  val new_skolem_var_name_from_const : string -> string
blanchet@43248
    86
  val atp_irrelevant_consts : string list
blanchet@43248
    87
  val atp_schematic_consts_of : term -> typ list Symtab.table
blanchet@43085
    88
  val is_locality_global : locality -> bool
blanchet@44397
    89
  val type_enc_from_string : soundness -> string -> type_enc
blanchet@43828
    90
  val is_type_enc_higher_order : type_enc -> bool
blanchet@43626
    91
  val polymorphism_of_type_enc : type_enc -> polymorphism
blanchet@43626
    92
  val level_of_type_enc : type_enc -> type_level
blanchet@44397
    93
  val is_type_enc_quasi_sound : type_enc -> bool
blanchet@43626
    94
  val is_type_enc_fairly_sound : type_enc -> bool
blanchet@43626
    95
  val choose_format : format list -> type_enc -> format * type_enc
blanchet@43136
    96
  val mk_aconns :
blanchet@43136
    97
    connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
nik@43676
    98
  val unmangled_const : string -> string * (string, 'b) ho_term list
blanchet@43130
    99
  val unmangled_const_name : string -> string
blanchet@43194
   100
  val helper_table : ((string * bool) * thm list) list
blanchet@43501
   101
  val factsN : string
blanchet@40059
   102
  val prepare_atp_problem :
blanchet@44394
   103
    Proof.context -> format -> formula_kind -> formula_kind -> type_enc
blanchet@44397
   104
    -> bool -> string -> bool -> bool -> term list -> term
blanchet@44088
   105
    -> ((string * locality) * term) list
blanchet@42541
   106
    -> string problem * string Symtab.table * int * int
blanchet@43214
   107
       * (string * locality) list vector * int list * int Symtab.table
blanchet@41313
   108
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38282
   109
end;
blanchet@38282
   110
blanchet@43085
   111
structure ATP_Translate : ATP_TRANSLATE =
blanchet@38282
   112
struct
blanchet@38282
   113
blanchet@43085
   114
open ATP_Util
blanchet@38282
   115
open ATP_Problem
blanchet@43085
   116
blanchet@43085
   117
type name = string * string
blanchet@43085
   118
blanchet@44088
   119
val no_lambdasN = "no_lambdas"
blanchet@44088
   120
val concealedN = "concealed"
blanchet@44088
   121
val liftingN = "lifting"
blanchet@44088
   122
val combinatorsN = "combinators"
blanchet@44088
   123
val hybridN = "hybrid"
blanchet@44088
   124
val lambdasN = "lambdas"
blanchet@44088
   125
val smartN = "smart"
blanchet@44088
   126
blanchet@43828
   127
val generate_info = false (* experimental *)
blanchet@38282
   128
blanchet@43693
   129
fun isabelle_info s =
blanchet@43693
   130
  if generate_info then SOME (ATerm ("[]", [ATerm ("isabelle_" ^ s, [])]))
blanchet@43693
   131
  else NONE
blanchet@42879
   132
blanchet@43693
   133
val introN = "intro"
blanchet@43693
   134
val elimN = "elim"
blanchet@43693
   135
val simpN = "simp"
blanchet@42879
   136
blanchet@43085
   137
val bound_var_prefix = "B_"
blanchet@43085
   138
val schematic_var_prefix = "V_"
blanchet@43085
   139
val fixed_var_prefix = "v_"
blanchet@43085
   140
val tvar_prefix = "T_"
blanchet@43085
   141
val tfree_prefix = "t_"
blanchet@43085
   142
val const_prefix = "c_"
blanchet@43085
   143
val type_const_prefix = "tc_"
blanchet@43085
   144
val class_prefix = "cl_"
blanchet@43085
   145
blanchet@43936
   146
val polymorphic_free_prefix = "poly_free"
blanchet@43907
   147
blanchet@43863
   148
val skolem_const_prefix = "ATP" ^ Long_Name.separator ^ "Sko"
blanchet@43085
   149
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@43085
   150
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@43085
   151
blanchet@42998
   152
val type_decl_prefix = "ty_"
blanchet@42998
   153
val sym_decl_prefix = "sy_"
blanchet@43989
   154
val guards_sym_formula_prefix = "gsy_"
blanchet@44396
   155
val tags_sym_formula_prefix = "tsy_"
blanchet@40204
   156
val fact_prefix = "fact_"
blanchet@38282
   157
val conjecture_prefix = "conj_"
blanchet@38282
   158
val helper_prefix = "help_"
blanchet@43159
   159
val class_rel_clause_prefix = "clar_"
blanchet@38282
   160
val arity_clause_prefix = "arity_"
blanchet@43085
   161
val tfree_clause_prefix = "tfree_"
blanchet@38282
   162
blanchet@43863
   163
val lambda_fact_prefix = "ATP.lambda_"
blanchet@42881
   164
val typed_helper_suffix = "_T"
blanchet@42881
   165
val untyped_helper_suffix = "_U"
blanchet@43159
   166
val type_tag_idempotence_helper_name = helper_prefix ^ "ti_idem"
blanchet@42881
   167
blanchet@42966
   168
val predicator_name = "hBOOL"
blanchet@42966
   169
val app_op_name = "hAPP"
blanchet@44396
   170
val type_guard_name = "g"
blanchet@44396
   171
val type_tag_name = "t"
blanchet@42962
   172
val simple_type_prefix = "ty_"
blanchet@42531
   173
blanchet@43174
   174
val prefixed_predicator_name = const_prefix ^ predicator_name
blanchet@43130
   175
val prefixed_app_op_name = const_prefix ^ app_op_name
blanchet@43130
   176
val prefixed_type_tag_name = const_prefix ^ type_tag_name
blanchet@43130
   177
blanchet@38282
   178
(* Freshness almost guaranteed! *)
blanchet@43863
   179
val atp_weak_prefix = "ATP:"
blanchet@38282
   180
blanchet@43085
   181
(*Escaping of special characters.
blanchet@43085
   182
  Alphanumeric characters are left unchanged.
blanchet@43085
   183
  The character _ goes to __
blanchet@43085
   184
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@43085
   185
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
blanchet@43093
   186
val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
blanchet@43085
   187
blanchet@43085
   188
fun stringN_of_int 0 _ = ""
blanchet@43085
   189
  | stringN_of_int k n =
blanchet@43085
   190
    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
blanchet@43085
   191
blanchet@43085
   192
fun ascii_of_char c =
blanchet@43085
   193
  if Char.isAlphaNum c then
blanchet@43085
   194
    String.str c
blanchet@43085
   195
  else if c = #"_" then
blanchet@43085
   196
    "__"
blanchet@43085
   197
  else if #" " <= c andalso c <= #"/" then
blanchet@43085
   198
    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
blanchet@43085
   199
  else
blanchet@43085
   200
    (* fixed width, in case more digits follow *)
blanchet@43085
   201
    "_" ^ stringN_of_int 3 (Char.ord c)
blanchet@43085
   202
blanchet@43085
   203
val ascii_of = String.translate ascii_of_char
blanchet@43085
   204
blanchet@43085
   205
(** Remove ASCII armoring from names in proof files **)
blanchet@43085
   206
blanchet@43085
   207
(* We don't raise error exceptions because this code can run inside a worker
blanchet@43085
   208
   thread. Also, the errors are impossible. *)
blanchet@43085
   209
val unascii_of =
blanchet@43085
   210
  let
blanchet@43085
   211
    fun un rcs [] = String.implode(rev rcs)
blanchet@43085
   212
      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
blanchet@43085
   213
        (* Three types of _ escapes: __, _A to _P, _nnn *)
blanchet@43496
   214
      | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
blanchet@43085
   215
      | un rcs (#"_" :: c :: cs) =
blanchet@43085
   216
        if #"A" <= c andalso c<= #"P" then
blanchet@43085
   217
          (* translation of #" " to #"/" *)
blanchet@43085
   218
          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
blanchet@43085
   219
        else
blanchet@43496
   220
          let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
blanchet@43085
   221
            case Int.fromString (String.implode digits) of
blanchet@43085
   222
              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
blanchet@43496
   223
            | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
blanchet@43085
   224
          end
blanchet@43085
   225
      | un rcs (c :: cs) = un (c :: rcs) cs
blanchet@43085
   226
  in un [] o String.explode end
blanchet@43085
   227
blanchet@43085
   228
(* If string s has the prefix s1, return the result of deleting it,
blanchet@43085
   229
   un-ASCII'd. *)
blanchet@43085
   230
fun strip_prefix_and_unascii s1 s =
blanchet@43085
   231
  if String.isPrefix s1 s then
blanchet@43085
   232
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@43085
   233
  else
blanchet@43085
   234
    NONE
blanchet@43085
   235
blanchet@43159
   236
val proxy_table =
blanchet@43159
   237
  [("c_False", (@{const_name False}, (@{thm fFalse_def},
blanchet@43159
   238
       ("fFalse", @{const_name ATP.fFalse})))),
blanchet@43159
   239
   ("c_True", (@{const_name True}, (@{thm fTrue_def},
blanchet@43159
   240
       ("fTrue", @{const_name ATP.fTrue})))),
blanchet@43159
   241
   ("c_Not", (@{const_name Not}, (@{thm fNot_def},
blanchet@43159
   242
       ("fNot", @{const_name ATP.fNot})))),
blanchet@43159
   243
   ("c_conj", (@{const_name conj}, (@{thm fconj_def},
blanchet@43159
   244
       ("fconj", @{const_name ATP.fconj})))),
blanchet@43159
   245
   ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
blanchet@43159
   246
       ("fdisj", @{const_name ATP.fdisj})))),
blanchet@43159
   247
   ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
blanchet@43159
   248
       ("fimplies", @{const_name ATP.fimplies})))),
blanchet@43159
   249
   ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
nik@43678
   250
       ("fequal", @{const_name ATP.fequal})))),
nik@43678
   251
   ("c_All", (@{const_name All}, (@{thm fAll_def},
nik@43678
   252
       ("fAll", @{const_name ATP.fAll})))),
nik@43678
   253
   ("c_Ex", (@{const_name Ex}, (@{thm fEx_def},
nik@43678
   254
       ("fEx", @{const_name ATP.fEx}))))]
blanchet@43085
   255
blanchet@43159
   256
val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
blanchet@43085
   257
blanchet@43085
   258
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@43085
   259
   table unless you know what you are doing. *)
blanchet@43085
   260
val const_trans_table =
blanchet@43085
   261
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@43085
   262
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@43085
   263
   (@{const_name False}, "False"),
blanchet@43085
   264
   (@{const_name True}, "True"),
blanchet@43085
   265
   (@{const_name Not}, "Not"),
blanchet@43085
   266
   (@{const_name conj}, "conj"),
blanchet@43085
   267
   (@{const_name disj}, "disj"),
blanchet@43085
   268
   (@{const_name implies}, "implies"),
blanchet@43085
   269
   (@{const_name HOL.eq}, "equal"),
nik@43678
   270
   (@{const_name All}, "All"),
nik@43678
   271
   (@{const_name Ex}, "Ex"),
blanchet@43085
   272
   (@{const_name If}, "If"),
blanchet@43085
   273
   (@{const_name Set.member}, "member"),
blanchet@43085
   274
   (@{const_name Meson.COMBI}, "COMBI"),
blanchet@43085
   275
   (@{const_name Meson.COMBK}, "COMBK"),
blanchet@43085
   276
   (@{const_name Meson.COMBB}, "COMBB"),
blanchet@43085
   277
   (@{const_name Meson.COMBC}, "COMBC"),
blanchet@43085
   278
   (@{const_name Meson.COMBS}, "COMBS")]
blanchet@43085
   279
  |> Symtab.make
blanchet@43159
   280
  |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
blanchet@43085
   281
blanchet@43085
   282
(* Invert the table of translations between Isabelle and ATPs. *)
blanchet@43085
   283
val const_trans_table_inv =
blanchet@43085
   284
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@43085
   285
val const_trans_table_unprox =
blanchet@43085
   286
  Symtab.empty
blanchet@43159
   287
  |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
blanchet@43085
   288
blanchet@43085
   289
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@43085
   290
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
blanchet@43085
   291
blanchet@43085
   292
fun lookup_const c =
blanchet@43085
   293
  case Symtab.lookup const_trans_table c of
blanchet@43085
   294
    SOME c' => c'
blanchet@43085
   295
  | NONE => ascii_of c
blanchet@43085
   296
blanchet@43622
   297
fun ascii_of_indexname (v, 0) = ascii_of v
blanchet@43622
   298
  | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
blanchet@43085
   299
blanchet@43085
   300
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@43085
   301
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@43085
   302
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
blanchet@43085
   303
blanchet@43622
   304
fun make_schematic_type_var (x, i) =
blanchet@43622
   305
      tvar_prefix ^ (ascii_of_indexname (unprefix "'" x, i))
blanchet@43622
   306
fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (unprefix "'" x))
blanchet@43085
   307
blanchet@43622
   308
(* "HOL.eq" is mapped to the ATP's equality. *)
blanchet@43622
   309
fun make_fixed_const @{const_name HOL.eq} = tptp_old_equal
blanchet@43085
   310
  | make_fixed_const c = const_prefix ^ lookup_const c
blanchet@43085
   311
blanchet@43085
   312
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
blanchet@43085
   313
blanchet@43085
   314
fun make_type_class clas = class_prefix ^ ascii_of clas
blanchet@43085
   315
blanchet@43093
   316
fun new_skolem_var_name_from_const s =
blanchet@43093
   317
  let val ss = s |> space_explode Long_Name.separator in
blanchet@43093
   318
    nth ss (length ss - 2)
blanchet@43093
   319
  end
blanchet@43093
   320
blanchet@43248
   321
(* These are either simplified away by "Meson.presimplify" (most of the time) or
blanchet@43248
   322
   handled specially via "fFalse", "fTrue", ..., "fequal". *)
blanchet@43248
   323
val atp_irrelevant_consts =
blanchet@43248
   324
  [@{const_name False}, @{const_name True}, @{const_name Not},
blanchet@43248
   325
   @{const_name conj}, @{const_name disj}, @{const_name implies},
blanchet@43248
   326
   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
blanchet@43248
   327
blanchet@43248
   328
val atp_monomorph_bad_consts =
blanchet@43248
   329
  atp_irrelevant_consts @
blanchet@43248
   330
  (* These are ignored anyway by the relevance filter (unless they appear in
blanchet@43248
   331
     higher-order places) but not by the monomorphizer. *)
blanchet@43248
   332
  [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
blanchet@43248
   333
   @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
blanchet@43248
   334
   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
blanchet@43248
   335
blanchet@43258
   336
fun add_schematic_const (x as (_, T)) =
blanchet@43258
   337
  Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
blanchet@43258
   338
val add_schematic_consts_of =
blanchet@43258
   339
  Term.fold_aterms (fn Const (x as (s, _)) =>
blanchet@43258
   340
                       not (member (op =) atp_monomorph_bad_consts s)
blanchet@43258
   341
                       ? add_schematic_const x
blanchet@43258
   342
                      | _ => I)
blanchet@43258
   343
fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
blanchet@43248
   344
blanchet@43085
   345
(** Definitions and functions for FOL clauses and formulas for TPTP **)
blanchet@43085
   346
blanchet@43085
   347
(* The first component is the type class; the second is a "TVar" or "TFree". *)
blanchet@43085
   348
datatype type_literal =
blanchet@43085
   349
  TyLitVar of name * name |
blanchet@43085
   350
  TyLitFree of name * name
blanchet@43085
   351
blanchet@43085
   352
blanchet@43085
   353
(** Isabelle arities **)
blanchet@43085
   354
blanchet@43085
   355
datatype arity_literal =
blanchet@43085
   356
  TConsLit of name * name * name list |
blanchet@43085
   357
  TVarLit of name * name
blanchet@43085
   358
blanchet@43085
   359
fun gen_TVars 0 = []
blanchet@43093
   360
  | gen_TVars n = ("T_" ^ string_of_int n) :: gen_TVars (n-1)
blanchet@43085
   361
blanchet@43263
   362
val type_class = the_single @{sort type}
blanchet@43263
   363
blanchet@43263
   364
fun add_packed_sort tvar =
blanchet@43263
   365
  fold (fn s => s <> type_class ? cons (`make_type_class s, `I tvar))
blanchet@43085
   366
blanchet@43086
   367
type arity_clause =
blanchet@43496
   368
  {name : string,
blanchet@43496
   369
   prem_lits : arity_literal list,
blanchet@43496
   370
   concl_lits : arity_literal}
blanchet@43085
   371
blanchet@43085
   372
(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
blanchet@43085
   373
fun make_axiom_arity_clause (tcons, name, (cls, args)) =
blanchet@43085
   374
  let
blanchet@43085
   375
    val tvars = gen_TVars (length args)
blanchet@43085
   376
    val tvars_srts = ListPair.zip (tvars, args)
blanchet@43085
   377
  in
blanchet@43086
   378
    {name = name,
blanchet@43263
   379
     prem_lits = [] |> fold (uncurry add_packed_sort) tvars_srts |> map TVarLit,
blanchet@43086
   380
     concl_lits = TConsLit (`make_type_class cls,
blanchet@43086
   381
                            `make_fixed_type_const tcons,
blanchet@43086
   382
                            tvars ~~ tvars)}
blanchet@43085
   383
  end
blanchet@43085
   384
blanchet@43085
   385
fun arity_clause _ _ (_, []) = []
blanchet@43495
   386
  | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
blanchet@43495
   387
    arity_clause seen n (tcons, ars)
blanchet@43495
   388
  | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
blanchet@43495
   389
    if member (op =) seen class then
blanchet@43495
   390
      (* multiple arities for the same (tycon, class) pair *)
blanchet@43495
   391
      make_axiom_arity_clause (tcons,
blanchet@43495
   392
          lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
blanchet@43495
   393
          ar) ::
blanchet@43495
   394
      arity_clause seen (n + 1) (tcons, ars)
blanchet@43495
   395
    else
blanchet@43495
   396
      make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
blanchet@43495
   397
                               ascii_of class, ar) ::
blanchet@43495
   398
      arity_clause (class :: seen) n (tcons, ars)
blanchet@43085
   399
blanchet@43085
   400
fun multi_arity_clause [] = []
blanchet@43085
   401
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@43085
   402
      arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
blanchet@43085
   403
blanchet@43622
   404
(* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
blanchet@43622
   405
   theory thy provided its arguments have the corresponding sorts. *)
blanchet@43085
   406
fun type_class_pairs thy tycons classes =
blanchet@43093
   407
  let
blanchet@43093
   408
    val alg = Sign.classes_of thy
blanchet@43093
   409
    fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@43093
   410
    fun add_class tycon class =
blanchet@43093
   411
      cons (class, domain_sorts tycon class)
blanchet@43093
   412
      handle Sorts.CLASS_ERROR _ => I
blanchet@43093
   413
    fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
blanchet@43093
   414
  in map try_classes tycons end
blanchet@43085
   415
blanchet@43085
   416
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@43085
   417
fun iter_type_class_pairs _ _ [] = ([], [])
blanchet@43085
   418
  | iter_type_class_pairs thy tycons classes =
blanchet@43263
   419
      let
blanchet@43263
   420
        fun maybe_insert_class s =
blanchet@43263
   421
          (s <> type_class andalso not (member (op =) classes s))
blanchet@43263
   422
          ? insert (op =) s
blanchet@43263
   423
        val cpairs = type_class_pairs thy tycons classes
blanchet@43263
   424
        val newclasses =
blanchet@43263
   425
          [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
blanchet@43263
   426
        val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
blanchet@43266
   427
      in (classes' @ classes, union (op =) cpairs' cpairs) end
blanchet@43085
   428
blanchet@43085
   429
fun make_arity_clauses thy tycons =
blanchet@43085
   430
  iter_type_class_pairs thy tycons ##> multi_arity_clause
blanchet@43085
   431
blanchet@43085
   432
blanchet@43085
   433
(** Isabelle class relations **)
blanchet@43085
   434
blanchet@43086
   435
type class_rel_clause =
blanchet@43496
   436
  {name : string,
blanchet@43496
   437
   subclass : name,
blanchet@43496
   438
   superclass : name}
blanchet@43085
   439
blanchet@43622
   440
(* Generate all pairs (sub, super) such that sub is a proper subclass of super
blanchet@43622
   441
   in theory "thy". *)
blanchet@43085
   442
fun class_pairs _ [] _ = []
blanchet@43085
   443
  | class_pairs thy subs supers =
blanchet@43085
   444
      let
blanchet@43085
   445
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@43085
   446
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@43085
   447
        fun add_supers sub = fold (add_super sub) supers
blanchet@43085
   448
      in fold add_supers subs [] end
blanchet@43085
   449
blanchet@43622
   450
fun make_class_rel_clause (sub, super) =
blanchet@43622
   451
  {name = sub ^ "_" ^ super, subclass = `make_type_class sub,
blanchet@43086
   452
   superclass = `make_type_class super}
blanchet@43085
   453
blanchet@43085
   454
fun make_class_rel_clauses thy subs supers =
blanchet@43093
   455
  map make_class_rel_clause (class_pairs thy subs supers)
blanchet@43085
   456
blanchet@43859
   457
(* intermediate terms *)
blanchet@43859
   458
datatype iterm =
blanchet@43859
   459
  IConst of name * typ * typ list |
blanchet@43859
   460
  IVar of name * typ |
blanchet@43859
   461
  IApp of iterm * iterm |
blanchet@43859
   462
  IAbs of (name * typ) * iterm
blanchet@43085
   463
blanchet@43859
   464
fun ityp_of (IConst (_, T, _)) = T
blanchet@43859
   465
  | ityp_of (IVar (_, T)) = T
blanchet@43859
   466
  | ityp_of (IApp (t1, _)) = snd (dest_funT (ityp_of t1))
blanchet@43859
   467
  | ityp_of (IAbs ((_, T), tm)) = T --> ityp_of tm
blanchet@43085
   468
blanchet@43085
   469
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@43859
   470
fun strip_iterm_comb u =
blanchet@43496
   471
  let
blanchet@43859
   472
    fun stripc (IApp (t, u), ts) = stripc (t, u :: ts)
blanchet@43496
   473
      | stripc x = x
blanchet@43496
   474
  in stripc (u, []) end
blanchet@43085
   475
blanchet@43085
   476
fun atyps_of T = fold_atyps (insert (op =)) T []
blanchet@43085
   477
blanchet@43085
   478
fun new_skolem_const_name s num_T_args =
blanchet@43085
   479
  [new_skolem_const_prefix, s, string_of_int num_T_args]
blanchet@43085
   480
  |> space_implode Long_Name.separator
blanchet@43085
   481
blanchet@43859
   482
(* Converts an Isabelle/HOL term (with combinators) into an intermediate term.
blanchet@43859
   483
   Also accumulates sort infomation. *)
blanchet@43859
   484
fun iterm_from_term thy bs (P $ Q) =
blanchet@43085
   485
    let
blanchet@43859
   486
      val (P', P_atomics_Ts) = iterm_from_term thy bs P
blanchet@43859
   487
      val (Q', Q_atomics_Ts) = iterm_from_term thy bs Q
blanchet@43859
   488
    in (IApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
blanchet@43859
   489
  | iterm_from_term thy _ (Const (c, T)) =
blanchet@43907
   490
    (IConst (`make_fixed_const c, T,
blanchet@43907
   491
             if String.isPrefix old_skolem_const_prefix c then
blanchet@43907
   492
               [] |> Term.add_tvarsT T |> map TVar
blanchet@43907
   493
             else
blanchet@43907
   494
               (c, T) |> Sign.const_typargs thy),
blanchet@43907
   495
     atyps_of T)
blanchet@43907
   496
  | iterm_from_term _ _ (Free (s, T)) =
blanchet@43907
   497
    (IConst (`make_fixed_var s, T,
blanchet@43936
   498
             if String.isPrefix polymorphic_free_prefix s then [T] else []),
blanchet@43907
   499
     atyps_of T)
blanchet@43859
   500
  | iterm_from_term _ _ (Var (v as (s, _), T)) =
blanchet@43085
   501
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@43085
   502
       let
blanchet@43085
   503
         val Ts = T |> strip_type |> swap |> op ::
blanchet@43085
   504
         val s' = new_skolem_const_name s (length Ts)
blanchet@43859
   505
       in IConst (`make_fixed_const s', T, Ts) end
blanchet@43085
   506
     else
blanchet@43859
   507
       IVar ((make_schematic_var v, s), T), atyps_of T)
blanchet@43859
   508
  | iterm_from_term _ bs (Bound j) =
blanchet@43859
   509
    nth bs j |> (fn (s, T) => (IConst (`make_bound_var s, T, []), atyps_of T))
blanchet@43859
   510
  | iterm_from_term thy bs (Abs (s, T, t)) =
nik@43678
   511
    let
nik@43678
   512
      fun vary s = s |> AList.defined (op =) bs s ? vary o Symbol.bump_string
nik@43678
   513
      val s = vary s
blanchet@43859
   514
      val (tm, atomic_Ts) = iterm_from_term thy ((s, T) :: bs) t
nik@43678
   515
    in
blanchet@43859
   516
      (IAbs ((`make_bound_var s, T), tm),
nik@43677
   517
       union (op =) atomic_Ts (atyps_of T))
nik@43677
   518
    end
blanchet@43085
   519
blanchet@43421
   520
datatype locality =
blanchet@43421
   521
  General | Helper | Extensionality | Intro | Elim | Simp | Local | Assum |
blanchet@43421
   522
  Chained
blanchet@43085
   523
blanchet@43085
   524
(* (quasi-)underapproximation of the truth *)
blanchet@43085
   525
fun is_locality_global Local = false
blanchet@43085
   526
  | is_locality_global Assum = false
blanchet@43085
   527
  | is_locality_global Chained = false
blanchet@43085
   528
  | is_locality_global _ = true
blanchet@43085
   529
blanchet@43624
   530
datatype order = First_Order | Higher_Order
blanchet@42613
   531
datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@44397
   532
datatype soundness = Unsound | Sound_Modulo_Infiniteness | Sound
blanchet@42613
   533
datatype type_level =
blanchet@44397
   534
  All_Types |
blanchet@44397
   535
  Noninf_Nonmono_Types of soundness |
blanchet@44397
   536
  Fin_Nonmono_Types |
blanchet@44397
   537
  Const_Arg_Types |
blanchet@43362
   538
  No_Types
blanchet@43128
   539
datatype type_heaviness = Heavyweight | Lightweight
blanchet@42613
   540
blanchet@43626
   541
datatype type_enc =
blanchet@43624
   542
  Simple_Types of order * type_level |
blanchet@43989
   543
  Guards of polymorphism * type_level * type_heaviness |
blanchet@42837
   544
  Tags of polymorphism * type_level * type_heaviness
blanchet@42613
   545
blanchet@42689
   546
fun try_unsuffixes ss s =
blanchet@42689
   547
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@42689
   548
blanchet@44397
   549
fun type_enc_from_string soundness s =
blanchet@42722
   550
  (case try (unprefix "poly_") s of
blanchet@42722
   551
     SOME s => (SOME Polymorphic, s)
blanchet@42613
   552
   | NONE =>
blanchet@42613
   553
     case try (unprefix "mono_") s of
blanchet@42722
   554
       SOME s => (SOME Monomorphic, s)
blanchet@42722
   555
     | NONE =>
blanchet@42722
   556
       case try (unprefix "mangled_") s of
blanchet@42722
   557
         SOME s => (SOME Mangled_Monomorphic, s)
blanchet@42722
   558
       | NONE => (NONE, s))
blanchet@42613
   559
  ||> (fn s =>
blanchet@43624
   560
          (* "_query" and "_bang" are for the ASCII-challenged Metis and
blanchet@43624
   561
             Mirabelle. *)
blanchet@42689
   562
          case try_unsuffixes ["?", "_query"] s of
blanchet@44397
   563
            SOME s => (Noninf_Nonmono_Types soundness, s)
blanchet@42613
   564
          | NONE =>
blanchet@42689
   565
            case try_unsuffixes ["!", "_bang"] s of
blanchet@43362
   566
              SOME s => (Fin_Nonmono_Types, s)
blanchet@42613
   567
            | NONE => (All_Types, s))
blanchet@42828
   568
  ||> apsnd (fn s =>
blanchet@42837
   569
                case try (unsuffix "_heavy") s of
blanchet@43128
   570
                  SOME s => (Heavyweight, s)
blanchet@43128
   571
                | NONE => (Lightweight, s))
blanchet@42837
   572
  |> (fn (poly, (level, (heaviness, core))) =>
blanchet@42837
   573
         case (core, (poly, level, heaviness)) of
blanchet@43624
   574
           ("simple", (NONE, _, Lightweight)) =>
blanchet@43624
   575
           Simple_Types (First_Order, level)
blanchet@43624
   576
         | ("simple_higher", (NONE, _, Lightweight)) =>
blanchet@44397
   577
           (case level of
blanchet@44397
   578
              Noninf_Nonmono_Types _ => raise Same.SAME
blanchet@44397
   579
            | _ => Simple_Types (Higher_Order, level))
blanchet@43989
   580
         | ("guards", (SOME poly, _, _)) => Guards (poly, level, heaviness)
blanchet@42886
   581
         | ("tags", (SOME Polymorphic, _, _)) =>
blanchet@43361
   582
           Tags (Polymorphic, level, heaviness)
blanchet@42854
   583
         | ("tags", (SOME poly, _, _)) => Tags (poly, level, heaviness)
blanchet@43128
   584
         | ("args", (SOME poly, All_Types (* naja *), Lightweight)) =>
blanchet@43989
   585
           Guards (poly, Const_Arg_Types, Lightweight)
blanchet@43128
   586
         | ("erased", (NONE, All_Types (* naja *), Lightweight)) =>
blanchet@43989
   587
           Guards (Polymorphic, No_Types, Lightweight)
blanchet@42753
   588
         | _ => raise Same.SAME)
blanchet@42753
   589
  handle Same.SAME => error ("Unknown type system: " ^ quote s ^ ".")
blanchet@42613
   590
blanchet@43626
   591
fun is_type_enc_higher_order (Simple_Types (Higher_Order, _)) = true
blanchet@43626
   592
  | is_type_enc_higher_order _ = false
blanchet@43624
   593
blanchet@43626
   594
fun polymorphism_of_type_enc (Simple_Types _) = Mangled_Monomorphic
blanchet@43989
   595
  | polymorphism_of_type_enc (Guards (poly, _, _)) = poly
blanchet@43626
   596
  | polymorphism_of_type_enc (Tags (poly, _, _)) = poly
blanchet@42613
   597
blanchet@43626
   598
fun level_of_type_enc (Simple_Types (_, level)) = level
blanchet@43989
   599
  | level_of_type_enc (Guards (_, level, _)) = level
blanchet@43626
   600
  | level_of_type_enc (Tags (_, level, _)) = level
blanchet@42828
   601
blanchet@43626
   602
fun heaviness_of_type_enc (Simple_Types _) = Heavyweight
blanchet@43989
   603
  | heaviness_of_type_enc (Guards (_, _, heaviness)) = heaviness
blanchet@43626
   604
  | heaviness_of_type_enc (Tags (_, _, heaviness)) = heaviness
blanchet@42831
   605
blanchet@44397
   606
fun is_type_level_quasi_sound All_Types = true
blanchet@44397
   607
  | is_type_level_quasi_sound (Noninf_Nonmono_Types _) = true
blanchet@44397
   608
  | is_type_level_quasi_sound _ = false
blanchet@44397
   609
val is_type_enc_quasi_sound =
blanchet@44397
   610
  is_type_level_quasi_sound o level_of_type_enc
blanchet@42613
   611
blanchet@42613
   612
fun is_type_level_fairly_sound level =
blanchet@44397
   613
  is_type_level_quasi_sound level orelse level = Fin_Nonmono_Types
blanchet@43626
   614
val is_type_enc_fairly_sound = is_type_level_fairly_sound o level_of_type_enc
blanchet@42613
   615
blanchet@44397
   616
fun is_type_level_monotonicity_based (Noninf_Nonmono_Types _) = true
blanchet@44397
   617
  | is_type_level_monotonicity_based Fin_Nonmono_Types = true
blanchet@44397
   618
  | is_type_level_monotonicity_based _ = false
blanchet@44397
   619
blanchet@43624
   620
fun choose_format formats (Simple_Types (order, level)) =
blanchet@44235
   621
    (case find_first is_format_thf formats of
blanchet@44235
   622
       SOME format => (format, Simple_Types (order, level))
blanchet@44235
   623
     | NONE =>
blanchet@44235
   624
       if member (op =) formats TFF then
blanchet@44235
   625
         (TFF, Simple_Types (First_Order, level))
blanchet@44235
   626
       else
blanchet@44235
   627
         choose_format formats
blanchet@44235
   628
                       (Guards (Mangled_Monomorphic, level, Heavyweight)))
blanchet@43626
   629
  | choose_format formats type_enc =
blanchet@43101
   630
    (case hd formats of
blanchet@43101
   631
       CNF_UEQ =>
blanchet@43626
   632
       (CNF_UEQ, case type_enc of
blanchet@43989
   633
                   Guards stuff =>
blanchet@43989
   634
                   (if is_type_enc_fairly_sound type_enc then Tags else Guards)
blanchet@43101
   635
                       stuff
blanchet@43626
   636
                 | _ => type_enc)
blanchet@43626
   637
     | format => (format, type_enc))
blanchet@43101
   638
blanchet@44088
   639
fun lift_lambdas ctxt type_enc =
blanchet@44088
   640
  map (close_form o Envir.eta_contract) #> rpair ctxt
blanchet@44088
   641
  #-> Lambda_Lifting.lift_lambdas
blanchet@44088
   642
          (if polymorphism_of_type_enc type_enc = Polymorphic then
blanchet@44088
   643
             SOME polymorphic_free_prefix
blanchet@44088
   644
           else
blanchet@44088
   645
             NONE)
blanchet@44088
   646
          Lambda_Lifting.is_quantifier
blanchet@44088
   647
  #> fst
blanchet@44088
   648
blanchet@44088
   649
fun intentionalize_def (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@44088
   650
    intentionalize_def t
blanchet@44088
   651
  | intentionalize_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
blanchet@44088
   652
    let
blanchet@44088
   653
      fun lam T t = Abs (Name.uu, T, t)
blanchet@44088
   654
      val (head, args) = strip_comb t ||> rev
blanchet@44088
   655
      val head_T = fastype_of head
blanchet@44088
   656
      val n = length args
blanchet@44088
   657
      val arg_Ts = head_T |> binder_types |> take n |> rev
blanchet@44088
   658
      val u = u |> subst_atomic (args ~~ map Bound (0 upto n - 1))
blanchet@44088
   659
    in HOLogic.eq_const head_T $ head $ fold lam arg_Ts u end
blanchet@44088
   660
  | intentionalize_def t = t
blanchet@44088
   661
blanchet@40114
   662
type translated_formula =
blanchet@43496
   663
  {name : string,
blanchet@43496
   664
   locality : locality,
blanchet@43496
   665
   kind : formula_kind,
blanchet@43859
   666
   iformula : (name, typ, iterm) formula,
blanchet@43496
   667
   atomic_types : typ list}
blanchet@38282
   668
blanchet@43859
   669
fun update_iformula f ({name, locality, kind, iformula, atomic_types}
blanchet@43859
   670
                       : translated_formula) =
blanchet@43859
   671
  {name = name, locality = locality, kind = kind, iformula = f iformula,
blanchet@42562
   672
   atomic_types = atomic_types} : translated_formula
blanchet@42542
   673
blanchet@43859
   674
fun fact_lift f ({iformula, ...} : translated_formula) = f iformula
blanchet@42558
   675
blanchet@43064
   676
val type_instance = Sign.typ_instance o Proof_Context.theory_of
blanchet@43064
   677
blanchet@43064
   678
fun insert_type ctxt get_T x xs =
blanchet@43064
   679
  let val T = get_T x in
blanchet@43064
   680
    if exists (curry (type_instance ctxt) T o get_T) xs then xs
blanchet@43064
   681
    else x :: filter_out (curry (type_instance ctxt o swap) T o get_T) xs
blanchet@43064
   682
  end
blanchet@42677
   683
blanchet@42753
   684
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@42753
   685
datatype type_arg_policy =
blanchet@42753
   686
  Explicit_Type_Args of bool |
blanchet@42753
   687
  Mangled_Type_Args of bool |
blanchet@42753
   688
  No_Type_Args
blanchet@41136
   689
blanchet@42836
   690
fun should_drop_arg_type_args (Simple_Types _) =
blanchet@42836
   691
    false (* since TFF doesn't support overloading *)
blanchet@43626
   692
  | should_drop_arg_type_args type_enc =
blanchet@43626
   693
    level_of_type_enc type_enc = All_Types andalso
blanchet@43626
   694
    heaviness_of_type_enc type_enc = Heavyweight
blanchet@42831
   695
blanchet@43626
   696
fun type_arg_policy type_enc s =
blanchet@43628
   697
  if s = type_tag_name then
blanchet@43626
   698
    (if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
blanchet@43623
   699
       Mangled_Type_Args
blanchet@43623
   700
     else
blanchet@43623
   701
       Explicit_Type_Args) false
blanchet@43628
   702
  else case type_enc of
blanchet@43628
   703
    Tags (_, All_Types, Heavyweight) => No_Type_Args
blanchet@43628
   704
  | _ =>
blanchet@43628
   705
    if level_of_type_enc type_enc = No_Types orelse
blanchet@43628
   706
       s = @{const_name HOL.eq} orelse
blanchet@43628
   707
       (s = app_op_name andalso
blanchet@43628
   708
        level_of_type_enc type_enc = Const_Arg_Types) then
blanchet@43628
   709
      No_Type_Args
blanchet@43628
   710
    else
blanchet@43628
   711
      should_drop_arg_type_args type_enc
blanchet@43628
   712
      |> (if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
blanchet@43628
   713
            Mangled_Type_Args
blanchet@43628
   714
          else
blanchet@43628
   715
            Explicit_Type_Args)
blanchet@42227
   716
blanchet@43628
   717
(* Make literals for sorted type variables. *)
blanchet@43263
   718
fun generic_add_sorts_on_type (_, []) = I
blanchet@43263
   719
  | generic_add_sorts_on_type ((x, i), s :: ss) =
blanchet@43263
   720
    generic_add_sorts_on_type ((x, i), ss)
blanchet@43263
   721
    #> (if s = the_single @{sort HOL.type} then
blanchet@43093
   722
          I
blanchet@43093
   723
        else if i = ~1 then
blanchet@43263
   724
          insert (op =) (TyLitFree (`make_type_class s, `make_fixed_type_var x))
blanchet@43093
   725
        else
blanchet@43263
   726
          insert (op =) (TyLitVar (`make_type_class s,
blanchet@43263
   727
                                   (make_schematic_type_var (x, i), x))))
blanchet@43263
   728
fun add_sorts_on_tfree (TFree (s, S)) = generic_add_sorts_on_type ((s, ~1), S)
blanchet@43263
   729
  | add_sorts_on_tfree _ = I
blanchet@43263
   730
fun add_sorts_on_tvar (TVar z) = generic_add_sorts_on_type z
blanchet@43263
   731
  | add_sorts_on_tvar _ = I
blanchet@43085
   732
blanchet@43626
   733
fun type_literals_for_types type_enc add_sorts_on_typ Ts =
blanchet@43626
   734
  [] |> level_of_type_enc type_enc <> No_Types ? fold add_sorts_on_typ Ts
blanchet@41137
   735
blanchet@42534
   736
fun mk_aconns c phis =
blanchet@42534
   737
  let val (phis', phi') = split_last phis in
blanchet@42534
   738
    fold_rev (mk_aconn c) phis' phi'
blanchet@42534
   739
  end
blanchet@38282
   740
fun mk_ahorn [] phi = phi
blanchet@42534
   741
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@42522
   742
fun mk_aquant _ [] phi = phi
blanchet@42522
   743
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@42522
   744
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@42522
   745
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38282
   746
blanchet@42522
   747
fun close_universally atom_vars phi =
blanchet@41145
   748
  let
blanchet@41145
   749
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@42526
   750
        formula_vars (map fst xs @ bounds) phi
blanchet@41145
   751
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@42522
   752
      | formula_vars bounds (AAtom tm) =
blanchet@42526
   753
        union (op =) (atom_vars tm []
blanchet@42526
   754
                      |> filter_out (member (op =) bounds o fst))
blanchet@42522
   755
  in mk_aquant AForall (formula_vars [] phi []) phi end
blanchet@42522
   756
blanchet@43859
   757
fun iterm_vars (IApp (tm1, tm2)) = fold iterm_vars [tm1, tm2]
blanchet@43859
   758
  | iterm_vars (IConst _) = I
blanchet@43859
   759
  | iterm_vars (IVar (name, T)) = insert (op =) (name, SOME T)
blanchet@43859
   760
  | iterm_vars (IAbs (_, tm)) = iterm_vars tm
blanchet@43859
   761
fun close_iformula_universally phi = close_universally iterm_vars phi
blanchet@42522
   762
nik@43676
   763
fun term_vars bounds (ATerm (name as (s, _), tms)) =
nik@43676
   764
    (is_tptp_variable s andalso not (member (op =) bounds name))
nik@43676
   765
    ? insert (op =) (name, NONE) #> fold (term_vars bounds) tms
nik@43676
   766
  | term_vars bounds (AAbs ((name, _), tm)) = term_vars (name :: bounds) tm
nik@43676
   767
fun close_formula_universally phi = close_universally (term_vars []) phi
blanchet@41145
   768
blanchet@42994
   769
val homo_infinite_type_name = @{type_name ind} (* any infinite type *)
blanchet@42994
   770
val homo_infinite_type = Type (homo_infinite_type_name, [])
blanchet@42994
   771
nik@43676
   772
fun ho_term_from_typ format type_enc =
blanchet@42994
   773
  let
blanchet@42994
   774
    fun term (Type (s, Ts)) =
blanchet@43626
   775
      ATerm (case (is_type_enc_higher_order type_enc, s) of
blanchet@42994
   776
               (true, @{type_name bool}) => `I tptp_bool_type
blanchet@42994
   777
             | (true, @{type_name fun}) => `I tptp_fun_type
blanchet@43178
   778
             | _ => if s = homo_infinite_type_name andalso
blanchet@44235
   779
                       is_format_typed format then
blanchet@43178
   780
                      `I tptp_individual_type
blanchet@43178
   781
                    else
blanchet@43178
   782
                      `make_fixed_type_const s,
blanchet@42994
   783
             map term Ts)
blanchet@42994
   784
    | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
blanchet@42994
   785
    | term (TVar ((x as (s, _)), _)) =
blanchet@42994
   786
      ATerm ((make_schematic_type_var x, s), [])
blanchet@42994
   787
  in term end
blanchet@42562
   788
nik@43676
   789
fun ho_term_for_type_arg format type_enc T =
nik@43676
   790
  if T = dummyT then NONE else SOME (ho_term_from_typ format type_enc T)
blanchet@43401
   791
blanchet@42562
   792
(* This shouldn't clash with anything else. *)
blanchet@42542
   793
val mangled_type_sep = "\000"
blanchet@42542
   794
blanchet@42562
   795
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@42562
   796
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@42761
   797
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@42761
   798
    ^ ")"
blanchet@43692
   799
  | generic_mangled_type_name _ _ = raise Fail "unexpected type abstraction"
blanchet@42542
   800
blanchet@44396
   801
fun mangled_type format type_enc =
blanchet@44396
   802
  generic_mangled_type_name fst o ho_term_from_typ format type_enc
blanchet@44396
   803
blanchet@42998
   804
val bool_atype = AType (`I tptp_bool_type)
blanchet@42998
   805
blanchet@43085
   806
fun make_simple_type s =
blanchet@43085
   807
  if s = tptp_bool_type orelse s = tptp_fun_type orelse
blanchet@43085
   808
     s = tptp_individual_type then
blanchet@43085
   809
    s
blanchet@43085
   810
  else
blanchet@43085
   811
    simple_type_prefix ^ ascii_of s
blanchet@43085
   812
nik@43676
   813
fun ho_type_from_ho_term type_enc pred_sym ary =
blanchet@42963
   814
  let
blanchet@42963
   815
    fun to_atype ty =
blanchet@42963
   816
      AType ((make_simple_type (generic_mangled_type_name fst ty),
blanchet@42963
   817
              generic_mangled_type_name snd ty))
blanchet@42963
   818
    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
blanchet@42998
   819
    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
blanchet@42994
   820
      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
blanchet@43692
   821
      | to_fo _ _ = raise Fail "unexpected type abstraction"
blanchet@42994
   822
    fun to_ho (ty as ATerm ((s, _), tys)) =
nik@43676
   823
        if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
nik@43676
   824
      | to_ho _ = raise Fail "unexpected type abstraction"
blanchet@43626
   825
  in if is_type_enc_higher_order type_enc then to_ho else to_fo ary end
blanchet@42963
   826
nik@43677
   827
fun ho_type_from_typ format type_enc pred_sym ary =
nik@43676
   828
  ho_type_from_ho_term type_enc pred_sym ary
nik@43676
   829
  o ho_term_from_typ format type_enc
blanchet@42963
   830
blanchet@43626
   831
fun mangled_const_name format type_enc T_args (s, s') =
blanchet@42963
   832
  let
nik@43676
   833
    val ty_args = T_args |> map_filter (ho_term_for_type_arg format type_enc)
blanchet@42963
   834
    fun type_suffix f g =
blanchet@42963
   835
      fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@42963
   836
                o generic_mangled_type_name f) ty_args ""
blanchet@42963
   837
  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
blanchet@42542
   838
blanchet@42542
   839
val parse_mangled_ident =
blanchet@42542
   840
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@42542
   841
blanchet@42542
   842
fun parse_mangled_type x =
blanchet@42542
   843
  (parse_mangled_ident
blanchet@42542
   844
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@42542
   845
                    [] >> ATerm) x
blanchet@42542
   846
and parse_mangled_types x =
blanchet@42542
   847
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@42542
   848
blanchet@42542
   849
fun unmangled_type s =
blanchet@42542
   850
  s |> suffix ")" |> raw_explode
blanchet@42542
   851
    |> Scan.finite Symbol.stopper
blanchet@42542
   852
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@42542
   853
                                                quote s)) parse_mangled_type))
blanchet@42542
   854
    |> fst
blanchet@42542
   855
blanchet@42561
   856
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@42542
   857
fun unmangled_const s =
blanchet@42542
   858
  let val ss = space_explode mangled_type_sep s in
blanchet@42542
   859
    (hd ss, map unmangled_type (tl ss))
blanchet@42542
   860
  end
blanchet@42542
   861
blanchet@43626
   862
fun introduce_proxies type_enc =
blanchet@42568
   863
  let
blanchet@43987
   864
    fun tweak_ho_quant ho_quant T [IAbs _] = IConst (`I ho_quant, T, [])
blanchet@43987
   865
      | tweak_ho_quant ho_quant (T as Type (_, [p_T as Type (_, [x_T, _]), _]))
blanchet@43987
   866
                       _ =
blanchet@43987
   867
        (* Eta-expand "!!" and "??", to work around LEO-II 1.2.8 parser
blanchet@43987
   868
           limitation. This works in conjuction with special code in
blanchet@43987
   869
           "ATP_Problem" that uses the syntactic sugar "!" and "?" whenever
blanchet@43987
   870
           possible. *)
blanchet@43987
   871
        IAbs ((`I "P", p_T),
blanchet@43987
   872
              IApp (IConst (`I ho_quant, T, []),
blanchet@43987
   873
                    IAbs ((`I "X", x_T),
blanchet@43987
   874
                          IApp (IConst (`I "P", p_T, []),
blanchet@43987
   875
                                IConst (`I "X", x_T, [])))))
blanchet@43987
   876
      | tweak_ho_quant _ _ _ = raise Fail "unexpected type for quantifier"
blanchet@43987
   877
    fun intro top_level args (IApp (tm1, tm2)) =
blanchet@43987
   878
        IApp (intro top_level (tm2 :: args) tm1, intro false [] tm2)
blanchet@43987
   879
      | intro top_level args (IConst (name as (s, _), T, T_args)) =
blanchet@42570
   880
        (case proxify_const s of
blanchet@43159
   881
           SOME proxy_base =>
blanchet@43626
   882
           if top_level orelse is_type_enc_higher_order type_enc then
blanchet@43000
   883
             case (top_level, s) of
blanchet@43987
   884
               (_, "c_False") => IConst (`I tptp_false, T, [])
blanchet@43987
   885
             | (_, "c_True") => IConst (`I tptp_true, T, [])
blanchet@43987
   886
             | (false, "c_Not") => IConst (`I tptp_not, T, [])
blanchet@43987
   887
             | (false, "c_conj") => IConst (`I tptp_and, T, [])
blanchet@43987
   888
             | (false, "c_disj") => IConst (`I tptp_or, T, [])
blanchet@43987
   889
             | (false, "c_implies") => IConst (`I tptp_implies, T, [])
blanchet@43987
   890
             | (false, "c_All") => tweak_ho_quant tptp_ho_forall T args
blanchet@43987
   891
             | (false, "c_Ex") => tweak_ho_quant tptp_ho_exists T args
blanchet@43000
   892
             | (false, s) =>
blanchet@44097
   893
               if is_tptp_equal s andalso length args = 2 then
blanchet@44097
   894
                 IConst (`I tptp_equal, T, [])
blanchet@44097
   895
               else
blanchet@44097
   896
                 (* Use a proxy even for partially applied THF equality, because
blanchet@44097
   897
                    the LEO-II and Satallax parsers complain about not being
blanchet@44097
   898
                    able to infer the type of "=". *)
blanchet@44097
   899
                 IConst (proxy_base |>> prefix const_prefix, T, T_args)
blanchet@43987
   900
             | _ => IConst (name, T, [])
blanchet@42569
   901
           else
blanchet@43987
   902
             IConst (proxy_base |>> prefix const_prefix, T, T_args)
blanchet@43987
   903
          | NONE => IConst (name, T, T_args))
blanchet@43987
   904
      | intro _ _ (IAbs (bound, tm)) = IAbs (bound, intro false [] tm)
blanchet@43987
   905
      | intro _ _ tm = tm
blanchet@43987
   906
  in intro true [] end
blanchet@42568
   907
blanchet@43859
   908
fun iformula_from_prop thy type_enc eq_as_iff =
blanchet@38282
   909
  let
blanchet@42568
   910
    fun do_term bs t atomic_types =
blanchet@43859
   911
      iterm_from_term thy bs (Envir.eta_contract t)
blanchet@43626
   912
      |>> (introduce_proxies type_enc #> AAtom)
blanchet@42568
   913
      ||> union (op =) atomic_types
blanchet@38282
   914
    fun do_quant bs q s T t' =
wenzelm@43324
   915
      let val s = singleton (Name.variant_list (map fst bs)) s in
blanchet@38518
   916
        do_formula ((s, T) :: bs) t'
blanchet@42562
   917
        #>> mk_aquant q [(`make_bound_var s, SOME T)]
blanchet@38518
   918
      end
blanchet@38282
   919
    and do_conn bs c t1 t2 =
blanchet@43198
   920
      do_formula bs t1 ##>> do_formula bs t2 #>> uncurry (mk_aconn c)
blanchet@38282
   921
    and do_formula bs t =
blanchet@38282
   922
      case t of
blanchet@43096
   923
        @{const Trueprop} $ t1 => do_formula bs t1
blanchet@43096
   924
      | @{const Not} $ t1 => do_formula bs t1 #>> mk_anot
blanchet@38282
   925
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38282
   926
        do_quant bs AForall s T t'
blanchet@38282
   927
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38282
   928
        do_quant bs AExists s T t'
haftmann@38795
   929
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@38795
   930
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@38786
   931
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@38864
   932
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@41140
   933
        if eq_as_iff then do_conn bs AIff t1 t2 else do_term bs t
blanchet@41140
   934
      | _ => do_term bs t
blanchet@38282
   935
  in do_formula [] end
blanchet@38282
   936
blanchet@43264
   937
fun presimplify_term _ [] t = t
blanchet@43264
   938
  | presimplify_term ctxt presimp_consts t =
blanchet@43264
   939
    t |> exists_Const (member (op =) presimp_consts o fst) t
blanchet@43264
   940
         ? (Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
blanchet@43264
   941
            #> Meson.presimplify ctxt
blanchet@43264
   942
            #> prop_of)
blanchet@38282
   943
blanchet@43863
   944
fun concealed_bound_name j = atp_weak_prefix ^ string_of_int j
blanchet@38282
   945
fun conceal_bounds Ts t =
blanchet@38282
   946
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38282
   947
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38282
   948
fun reveal_bounds Ts =
blanchet@38282
   949
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38282
   950
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38282
   951
blanchet@43265
   952
fun is_fun_equality (@{const_name HOL.eq},
blanchet@43265
   953
                     Type (_, [Type (@{type_name fun}, _), _])) = true
blanchet@43265
   954
  | is_fun_equality _ = false
blanchet@43265
   955
blanchet@42747
   956
fun extensionalize_term ctxt t =
blanchet@43265
   957
  if exists_Const is_fun_equality t then
blanchet@43265
   958
    let val thy = Proof_Context.theory_of ctxt in
blanchet@43265
   959
      t |> cterm_of thy |> Meson.extensionalize_conv ctxt
blanchet@43265
   960
        |> prop_of |> Logic.dest_equals |> snd
blanchet@43265
   961
    end
blanchet@43265
   962
  else
blanchet@43265
   963
    t
blanchet@38608
   964
blanchet@43862
   965
fun simple_translate_lambdas do_lambdas ctxt t =
blanchet@43863
   966
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43863
   967
    if Meson.is_fol_term thy t then
blanchet@43863
   968
      t
blanchet@43863
   969
    else
blanchet@43863
   970
      let
blanchet@43863
   971
        fun aux Ts t =
blanchet@43863
   972
          case t of
blanchet@43863
   973
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@43863
   974
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@43863
   975
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@43863
   976
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@43863
   977
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@43863
   978
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@43863
   979
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@43863
   980
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@43863
   981
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@43863
   982
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@43863
   983
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@43863
   984
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
blanchet@43863
   985
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@43863
   986
              $ t1 $ t2 =>
blanchet@43863
   987
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@43863
   988
          | _ =>
blanchet@43863
   989
            if not (exists_subterm (fn Abs _ => true | _ => false) t) then t
blanchet@43863
   990
            else t |> Envir.eta_contract |> do_lambdas ctxt Ts
blanchet@43863
   991
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@43863
   992
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@43863
   993
  end
blanchet@43856
   994
blanchet@43997
   995
fun do_cheaply_conceal_lambdas Ts (t1 $ t2) =
blanchet@43997
   996
    do_cheaply_conceal_lambdas Ts t1
blanchet@43997
   997
    $ do_cheaply_conceal_lambdas Ts t2
blanchet@43997
   998
  | do_cheaply_conceal_lambdas Ts (Abs (_, T, t)) =
blanchet@43997
   999
    Free (polymorphic_free_prefix ^ serial_string (),
blanchet@43997
  1000
          T --> fastype_of1 (T :: Ts, t))
blanchet@43997
  1001
  | do_cheaply_conceal_lambdas _ t = t
blanchet@43856
  1002
blanchet@43862
  1003
fun do_introduce_combinators ctxt Ts t =
wenzelm@42361
  1004
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43905
  1005
    t |> conceal_bounds Ts
blanchet@43905
  1006
      |> cterm_of thy
blanchet@43905
  1007
      |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@43905
  1008
      |> prop_of |> Logic.dest_equals |> snd
blanchet@43905
  1009
      |> reveal_bounds Ts
blanchet@38491
  1010
  end
blanchet@43862
  1011
  (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@43997
  1012
  handle THM _ => t |> do_cheaply_conceal_lambdas Ts
blanchet@43862
  1013
val introduce_combinators = simple_translate_lambdas do_introduce_combinators
blanchet@43862
  1014
blanchet@43864
  1015
fun preprocess_abstractions_in_terms trans_lambdas facts =
blanchet@43862
  1016
  let
blanchet@43863
  1017
    val (facts, lambda_ts) =
blanchet@43863
  1018
      facts |> map (snd o snd) |> trans_lambdas 
blanchet@43863
  1019
            |>> map2 (fn (name, (kind, _)) => fn t => (name, (kind, t))) facts
blanchet@43863
  1020
    val lambda_facts =
blanchet@43863
  1021
      map2 (fn t => fn j =>
blanchet@43863
  1022
               ((lambda_fact_prefix ^ Int.toString j, Helper), (Axiom, t)))
blanchet@43863
  1023
           lambda_ts (1 upto length lambda_ts)
blanchet@43863
  1024
  in (facts, lambda_facts) end
blanchet@38282
  1025
blanchet@38282
  1026
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@42353
  1027
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38282
  1028
fun freeze_term t =
blanchet@38282
  1029
  let
blanchet@38282
  1030
    fun aux (t $ u) = aux t $ aux u
blanchet@38282
  1031
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38282
  1032
      | aux (Var ((s, i), T)) =
blanchet@43863
  1033
        Free (atp_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38282
  1034
      | aux t = t
blanchet@38282
  1035
  in t |> exists_subterm is_Var t ? aux end
blanchet@38282
  1036
blanchet@43863
  1037
fun presimp_prop ctxt presimp_consts t =
blanchet@38282
  1038
  let
wenzelm@42361
  1039
    val thy = Proof_Context.theory_of ctxt
blanchet@38608
  1040
    val t = t |> Envir.beta_eta_contract
blanchet@42944
  1041
              |> transform_elim_prop
blanchet@41211
  1042
              |> Object_Logic.atomize_term thy
blanchet@42563
  1043
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@43096
  1044
  in
blanchet@43096
  1045
    t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@43096
  1046
      |> Raw_Simplifier.rewrite_term thy (Meson.unfold_set_const_simps ctxt) []
blanchet@43096
  1047
      |> extensionalize_term ctxt
blanchet@43264
  1048
      |> presimplify_term ctxt presimp_consts
blanchet@43120
  1049
      |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@43096
  1050
  end
blanchet@43096
  1051
blanchet@43096
  1052
(* making fact and conjecture formulas *)
blanchet@43626
  1053
fun make_formula thy type_enc eq_as_iff name loc kind t =
blanchet@43096
  1054
  let
blanchet@43859
  1055
    val (iformula, atomic_types) =
blanchet@43859
  1056
      iformula_from_prop thy type_enc eq_as_iff t []
blanchet@38282
  1057
  in
blanchet@43859
  1058
    {name = name, locality = loc, kind = kind, iformula = iformula,
blanchet@42562
  1059
     atomic_types = atomic_types}
blanchet@38282
  1060
  end
blanchet@38282
  1061
blanchet@43860
  1062
fun make_fact ctxt format type_enc eq_as_iff ((name, loc), t) =
blanchet@43096
  1063
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43860
  1064
    case t |> make_formula thy type_enc (eq_as_iff andalso format <> CNF) name
blanchet@43624
  1065
                           loc Axiom of
blanchet@43859
  1066
      formula as {iformula = AAtom (IConst ((s, _), _, _)), ...} =>
blanchet@43096
  1067
      if s = tptp_true then NONE else SOME formula
blanchet@43295
  1068
    | formula => SOME formula
blanchet@43096
  1069
  end
blanchet@42561
  1070
blanchet@43860
  1071
fun make_conjecture ctxt format type_enc ps =
blanchet@43096
  1072
  let
blanchet@43096
  1073
    val thy = Proof_Context.theory_of ctxt
blanchet@43860
  1074
    val last = length ps - 1
blanchet@43096
  1075
  in
blanchet@43863
  1076
    map2 (fn j => fn ((name, loc), (kind, t)) =>
blanchet@43863
  1077
             t |> make_formula thy type_enc (format <> CNF) name loc kind
blanchet@43860
  1078
               |> (j <> last) = (kind = Conjecture) ? update_iformula mk_anot)
blanchet@43860
  1079
         (0 upto last) ps
blanchet@38613
  1080
  end
blanchet@38282
  1081
blanchet@42682
  1082
(** Finite and infinite type inference **)
blanchet@42682
  1083
blanchet@44397
  1084
(* These types witness that the type classes they belong to allow infinite
blanchet@44397
  1085
   models and hence that any types with these type classes is monotonic. *)
blanchet@44397
  1086
val known_infinite_types =
blanchet@44397
  1087
  [@{typ nat}, Type ("Int.int", []), @{typ "nat => bool"}]
blanchet@44397
  1088
blanchet@44397
  1089
fun is_type_infinite ctxt soundness locality T =
blanchet@44397
  1090
  (* Unlike virtually any other polymorphic fact whose type variables can be
blanchet@44397
  1091
     instantiated by a known infinite type, extensionality actually encodes a
blanchet@44397
  1092
     cardinality constraints. *)
blanchet@44397
  1093
  soundness <> Sound andalso
blanchet@44397
  1094
  is_type_surely_infinite ctxt
blanchet@44397
  1095
      (if soundness = Unsound andalso locality <> Extensionality then
blanchet@44397
  1096
         known_infinite_types
blanchet@44397
  1097
       else
blanchet@44397
  1098
         []) T
blanchet@42886
  1099
blanchet@42682
  1100
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@42682
  1101
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@42682
  1102
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@42682
  1103
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@42682
  1104
blanchet@44397
  1105
fun should_encode_type _ _ All_Types _ = true
blanchet@44397
  1106
  | should_encode_type ctxt nonmono_Ts (Noninf_Nonmono_Types soundness) T =
blanchet@44397
  1107
    exists (curry (type_instance ctxt) T) nonmono_Ts andalso
blanchet@44397
  1108
    not (is_type_infinite ctxt soundness General T)
blanchet@44397
  1109
  | should_encode_type ctxt nonmono_Ts Fin_Nonmono_Types T =
blanchet@44397
  1110
    exists (curry (type_instance ctxt) T) nonmono_Ts andalso
blanchet@44393
  1111
    is_type_surely_finite ctxt T
blanchet@42682
  1112
  | should_encode_type _ _ _ _ = false
blanchet@42682
  1113
blanchet@44397
  1114
fun should_predicate_on_type ctxt nonmono_Ts
blanchet@44397
  1115
        (Guards (_, level, heaviness)) should_predicate_on_var T =
blanchet@43128
  1116
    (heaviness = Heavyweight orelse should_predicate_on_var ()) andalso
blanchet@42878
  1117
    should_encode_type ctxt nonmono_Ts level T
blanchet@42834
  1118
  | should_predicate_on_type _ _ _ _ _ = false
blanchet@42682
  1119
blanchet@43859
  1120
fun is_var_or_bound_var (IConst ((s, _), _, _)) =
blanchet@42836
  1121
    String.isPrefix bound_var_prefix s
blanchet@43859
  1122
  | is_var_or_bound_var (IVar _) = true
blanchet@42836
  1123
  | is_var_or_bound_var _ = false
blanchet@42836
  1124
blanchet@43361
  1125
datatype tag_site =
blanchet@43361
  1126
  Top_Level of bool option |
blanchet@43361
  1127
  Eq_Arg of bool option |
blanchet@43361
  1128
  Elsewhere
blanchet@42829
  1129
blanchet@43361
  1130
fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
blanchet@44397
  1131
  | should_tag_with_type ctxt nonmono_Ts (Tags (_, level, heaviness)) site
blanchet@43361
  1132
                         u T =
blanchet@42837
  1133
    (case heaviness of
blanchet@43128
  1134
       Heavyweight => should_encode_type ctxt nonmono_Ts level T
blanchet@43128
  1135
     | Lightweight =>
blanchet@42836
  1136
       case (site, is_var_or_bound_var u) of
blanchet@44397
  1137
         (Eq_Arg _, true) => should_encode_type ctxt nonmono_Ts level T
blanchet@42829
  1138
       | _ => false)
blanchet@42829
  1139
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@42682
  1140
blanchet@42994
  1141
fun homogenized_type ctxt nonmono_Ts level =
blanchet@42994
  1142
  let
blanchet@42994
  1143
    val should_encode = should_encode_type ctxt nonmono_Ts level
blanchet@42994
  1144
    fun homo 0 T = if should_encode T then T else homo_infinite_type
blanchet@42994
  1145
      | homo ary (Type (@{type_name fun}, [T1, T2])) =
blanchet@42994
  1146
        homo 0 T1 --> homo (ary - 1) T2
blanchet@42994
  1147
      | homo _ _ = raise Fail "expected function type"
blanchet@42994
  1148
  in homo end
blanchet@42682
  1149
blanchet@42573
  1150
(** "hBOOL" and "hAPP" **)
blanchet@41313
  1151
blanchet@42574
  1152
type sym_info =
blanchet@43064
  1153
  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list}
blanchet@42563
  1154
blanchet@43859
  1155
fun add_iterm_syms_to_table ctxt explicit_apply =
blanchet@42558
  1156
  let
blanchet@43064
  1157
    fun consider_var_arity const_T var_T max_ary =
blanchet@43064
  1158
      let
blanchet@43064
  1159
        fun iter ary T =
blanchet@43210
  1160
          if ary = max_ary orelse type_instance ctxt (var_T, T) orelse
blanchet@43210
  1161
             type_instance ctxt (T, var_T) then
blanchet@43210
  1162
            ary
blanchet@43210
  1163
          else
blanchet@43210
  1164
            iter (ary + 1) (range_type T)
blanchet@43064
  1165
      in iter 0 const_T end
blanchet@43201
  1166
    fun add_var_or_bound_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@43201
  1167
      if explicit_apply = NONE andalso
blanchet@43201
  1168
         (can dest_funT T orelse T = @{typ bool}) then
blanchet@43201
  1169
        let
blanchet@43201
  1170
          val bool_vars' = bool_vars orelse body_type T = @{typ bool}
blanchet@43201
  1171
          fun repair_min_arity {pred_sym, min_ary, max_ary, types} =
blanchet@43201
  1172
            {pred_sym = pred_sym andalso not bool_vars',
blanchet@43213
  1173
             min_ary = fold (fn T' => consider_var_arity T' T) types min_ary,
blanchet@43201
  1174
             max_ary = max_ary, types = types}
blanchet@43201
  1175
          val fun_var_Ts' =
blanchet@43201
  1176
            fun_var_Ts |> can dest_funT T ? insert_type ctxt I T
blanchet@43201
  1177
        in
blanchet@43201
  1178
          if bool_vars' = bool_vars andalso
blanchet@43201
  1179
             pointer_eq (fun_var_Ts', fun_var_Ts) then
blanchet@43201
  1180
            accum
blanchet@43167
  1181
          else
blanchet@43213
  1182
            ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_arity) sym_tab)
blanchet@43201
  1183
        end
blanchet@43201
  1184
      else
blanchet@43201
  1185
        accum
blanchet@43201
  1186
    fun add top_level tm (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@43859
  1187
      let val (head, args) = strip_iterm_comb tm in
blanchet@42558
  1188
        (case head of
blanchet@43859
  1189
           IConst ((s, _), T, _) =>
blanchet@42558
  1190
           if String.isPrefix bound_var_prefix s then
blanchet@43201
  1191
             add_var_or_bound_var T accum
blanchet@42558
  1192
           else
blanchet@43139
  1193
             let val ary = length args in
blanchet@43201
  1194
               ((bool_vars, fun_var_Ts),
blanchet@43064
  1195
                case Symtab.lookup sym_tab s of
blanchet@43064
  1196
                  SOME {pred_sym, min_ary, max_ary, types} =>
blanchet@43064
  1197
                  let
blanchet@43201
  1198
                    val pred_sym =
blanchet@43201
  1199
                      pred_sym andalso top_level andalso not bool_vars
blanchet@43064
  1200
                    val types' = types |> insert_type ctxt I T
blanchet@43064
  1201
                    val min_ary =
blanchet@43064
  1202
                      if is_some explicit_apply orelse
blanchet@43064
  1203
                         pointer_eq (types', types) then
blanchet@43064
  1204
                        min_ary
blanchet@43064
  1205
                      else
blanchet@43201
  1206
                        fold (consider_var_arity T) fun_var_Ts min_ary
blanchet@43064
  1207
                  in
blanchet@43201
  1208
                    Symtab.update (s, {pred_sym = pred_sym,
blanchet@43064
  1209
                                       min_ary = Int.min (ary, min_ary),
blanchet@43064
  1210
                                       max_ary = Int.max (ary, max_ary),
blanchet@43064
  1211
                                       types = types'})
blanchet@43064
  1212
                                  sym_tab
blanchet@43064
  1213
                  end
blanchet@43064
  1214
                | NONE =>
blanchet@43064
  1215
                  let
blanchet@43201
  1216
                    val pred_sym = top_level andalso not bool_vars
blanchet@43064
  1217
                    val min_ary =
blanchet@43064
  1218
                      case explicit_apply of
blanchet@43064
  1219
                        SOME true => 0
blanchet@43064
  1220
                      | SOME false => ary
blanchet@43201
  1221
                      | NONE => fold (consider_var_arity T) fun_var_Ts ary
blanchet@43064
  1222
                  in
blanchet@43201
  1223
                    Symtab.update_new (s, {pred_sym = pred_sym,
blanchet@43064
  1224
                                           min_ary = min_ary, max_ary = ary,
blanchet@43064
  1225
                                           types = [T]})
blanchet@43064
  1226
                                      sym_tab
blanchet@43064
  1227
                  end)
blanchet@43064
  1228
             end
blanchet@43859
  1229
         | IVar (_, T) => add_var_or_bound_var T accum
blanchet@43859
  1230
         | IAbs ((_, T), tm) => accum |> add_var_or_bound_var T |> add false tm
blanchet@43064
  1231
         | _ => accum)
blanchet@43064
  1232
        |> fold (add false) args
blanchet@42558
  1233
      end
blanchet@43064
  1234
  in add true end
blanchet@43064
  1235
fun add_fact_syms_to_table ctxt explicit_apply =
blanchet@43064
  1236
  fact_lift (formula_fold NONE
blanchet@43859
  1237
                          (K (add_iterm_syms_to_table ctxt explicit_apply)))
blanchet@38282
  1238
blanchet@43966
  1239
val tvar_a = TVar (("'a", 0), HOLogic.typeS)
blanchet@43966
  1240
blanchet@43139
  1241
val default_sym_tab_entries : (string * sym_info) list =
blanchet@43174
  1242
  (prefixed_predicator_name,
blanchet@43139
  1243
   {pred_sym = true, min_ary = 1, max_ary = 1, types = []}) ::
blanchet@43984
  1244
  (make_fixed_const @{const_name undefined},
blanchet@43966
  1245
   {pred_sym = false, min_ary = 0, max_ary = 0, types = []}) ::
blanchet@42568
  1246
  ([tptp_false, tptp_true]
blanchet@43139
  1247
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = []})) @
blanchet@43139
  1248
  ([tptp_equal, tptp_old_equal]
blanchet@43139
  1249
   |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = []}))
blanchet@41140
  1250
blanchet@43064
  1251
fun sym_table_for_facts ctxt explicit_apply facts =
blanchet@43201
  1252
  ((false, []), Symtab.empty)
blanchet@43201
  1253
  |> fold (add_fact_syms_to_table ctxt explicit_apply) facts |> snd
blanchet@43139
  1254
  |> fold Symtab.update default_sym_tab_entries
blanchet@38282
  1255
blanchet@42558
  1256
fun min_arity_of sym_tab s =
blanchet@42558
  1257
  case Symtab.lookup sym_tab s of
blanchet@42574
  1258
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@42558
  1259
  | NONE =>
blanchet@42558
  1260
    case strip_prefix_and_unascii const_prefix s of
blanchet@42547
  1261
      SOME s =>
blanchet@42570
  1262
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@42966
  1263
        if s = predicator_name then 1
blanchet@42966
  1264
        else if s = app_op_name then 2
blanchet@44396
  1265
        else if s = type_guard_name then 1
blanchet@42557
  1266
        else 0
blanchet@42547
  1267
      end
blanchet@42544
  1268
    | NONE => 0
blanchet@38282
  1269
blanchet@38282
  1270
(* True if the constant ever appears outside of the top-level position in
blanchet@38282
  1271
   literals, or if it appears with different arities (e.g., because of different
blanchet@38282
  1272
   type instantiations). If false, the constant always receives all of its
blanchet@38282
  1273
   arguments and is used as a predicate. *)
blanchet@42558
  1274
fun is_pred_sym sym_tab s =
blanchet@42558
  1275
  case Symtab.lookup sym_tab s of
blanchet@42574
  1276
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@42574
  1277
    pred_sym andalso min_ary = max_ary
blanchet@42558
  1278
  | NONE => false
blanchet@38282
  1279
blanchet@42568
  1280
val predicator_combconst =
blanchet@43859
  1281
  IConst (`make_fixed_const predicator_name, @{typ "bool => bool"}, [])
blanchet@43859
  1282
fun predicator tm = IApp (predicator_combconst, tm)
blanchet@42542
  1283
blanchet@43859
  1284
fun introduce_predicators_in_iterm sym_tab tm =
blanchet@43859
  1285
  case strip_iterm_comb tm of
blanchet@43859
  1286
    (IConst ((s, _), _, _), _) =>
blanchet@42568
  1287
    if is_pred_sym sym_tab s then tm else predicator tm
blanchet@42568
  1288
  | _ => predicator tm
blanchet@42542
  1289
blanchet@43859
  1290
fun list_app head args = fold (curry (IApp o swap)) args head
blanchet@42544
  1291
blanchet@43130
  1292
val app_op = `make_fixed_const app_op_name
blanchet@43130
  1293
blanchet@42544
  1294
fun explicit_app arg head =
blanchet@42544
  1295
  let
blanchet@43859
  1296
    val head_T = ityp_of head
blanchet@42693
  1297
    val (arg_T, res_T) = dest_funT head_T
blanchet@43859
  1298
    val explicit_app = IConst (app_op, head_T --> head_T, [arg_T, res_T])
blanchet@42544
  1299
  in list_app explicit_app [head, arg] end
blanchet@42544
  1300
fun list_explicit_app head args = fold explicit_app args head
blanchet@38282
  1301
blanchet@43859
  1302
fun introduce_explicit_apps_in_iterm sym_tab =
blanchet@42544
  1303
  let
blanchet@42544
  1304
    fun aux tm =
blanchet@43859
  1305
      case strip_iterm_comb tm of
blanchet@43859
  1306
        (head as IConst ((s, _), _, _), args) =>
blanchet@42544
  1307
        args |> map aux
blanchet@42557
  1308
             |> chop (min_arity_of sym_tab s)
blanchet@42544
  1309
             |>> list_app head
blanchet@42544
  1310
             |-> list_explicit_app
blanchet@42544
  1311
      | (head, args) => list_explicit_app head (map aux args)
blanchet@42544
  1312
  in aux end
blanchet@38282
  1313
blanchet@42753
  1314
fun chop_fun 0 T = ([], T)
blanchet@42753
  1315
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@42753
  1316
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@42753
  1317
  | chop_fun _ _ = raise Fail "unexpected non-function"
blanchet@42753
  1318
blanchet@42780
  1319
fun filter_type_args _ _ _ [] = []
blanchet@42780
  1320
  | filter_type_args thy s arity T_args =
blanchet@42834
  1321
    let
blanchet@42834
  1322
      (* will throw "TYPE" for pseudo-constants *)
blanchet@42966
  1323
      val U = if s = app_op_name then
blanchet@42834
  1324
                @{typ "('a => 'b) => 'a => 'b"} |> Logic.varifyT_global
blanchet@42834
  1325
              else
blanchet@42834
  1326
                s |> Sign.the_const_type thy
blanchet@42834
  1327
    in
blanchet@42781
  1328
      case Term.add_tvarsT (U |> chop_fun arity |> snd) [] of
blanchet@42781
  1329
        [] => []
blanchet@42781
  1330
      | res_U_vars =>
blanchet@42781
  1331
        let val U_args = (s, U) |> Sign.const_typargs thy in
blanchet@42781
  1332
          U_args ~~ T_args
blanchet@43401
  1333
          |> map (fn (U, T) =>
blanchet@43401
  1334
                     if member (op =) res_U_vars (dest_TVar U) then T
blanchet@43401
  1335
                     else dummyT)
blanchet@42781
  1336
        end
blanchet@42780
  1337
    end
blanchet@42780
  1338
    handle TYPE _ => T_args
blanchet@42753
  1339
blanchet@43859
  1340
fun enforce_type_arg_policy_in_iterm ctxt format type_enc =
blanchet@42753
  1341
  let
blanchet@42753
  1342
    val thy = Proof_Context.theory_of ctxt
blanchet@43859
  1343
    fun aux arity (IApp (tm1, tm2)) = IApp (aux (arity + 1) tm1, aux 0 tm2)
blanchet@43859
  1344
      | aux arity (IConst (name as (s, _), T, T_args)) =
blanchet@43179
  1345
        (case strip_prefix_and_unascii const_prefix s of
blanchet@43961
  1346
           NONE =>
blanchet@43961
  1347
           (name, if level_of_type_enc type_enc = No_Types then [] else T_args)
blanchet@43179
  1348
         | SOME s'' =>
blanchet@43179
  1349
           let
blanchet@43179
  1350
             val s'' = invert_const s''
blanchet@43179
  1351
             fun filtered_T_args false = T_args
blanchet@43179
  1352
               | filtered_T_args true = filter_type_args thy s'' arity T_args
blanchet@43179
  1353
           in
blanchet@43626
  1354
             case type_arg_policy type_enc s'' of
blanchet@43179
  1355
               Explicit_Type_Args drop_args =>
blanchet@43179
  1356
               (name, filtered_T_args drop_args)
blanchet@43179
  1357
             | Mangled_Type_Args drop_args =>
blanchet@43626
  1358
               (mangled_const_name format type_enc (filtered_T_args drop_args)
blanchet@43179
  1359
                                   name, [])
blanchet@43179
  1360
             | No_Type_Args => (name, [])
blanchet@43179
  1361
           end)
blanchet@43859
  1362
        |> (fn (name, T_args) => IConst (name, T, T_args))
blanchet@43859
  1363
      | aux _ (IAbs (bound, tm)) = IAbs (bound, aux 0 tm)
blanchet@42753
  1364
      | aux _ tm = tm
blanchet@42753
  1365
  in aux 0 end
blanchet@42573
  1366
blanchet@43859
  1367
fun repair_iterm ctxt format type_enc sym_tab =
blanchet@43626
  1368
  not (is_type_enc_higher_order type_enc)
blanchet@43859
  1369
  ? (introduce_explicit_apps_in_iterm sym_tab
blanchet@43859
  1370
     #> introduce_predicators_in_iterm sym_tab)
blanchet@43859
  1371
  #> enforce_type_arg_policy_in_iterm ctxt format type_enc
blanchet@43626
  1372
fun repair_fact ctxt format type_enc sym_tab =
blanchet@43859
  1373
  update_iformula (formula_map (repair_iterm ctxt format type_enc sym_tab))
blanchet@42573
  1374
blanchet@42573
  1375
(** Helper facts **)
blanchet@42573
  1376
blanchet@43194
  1377
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@43085
  1378
val helper_table =
blanchet@43194
  1379
  [(("COMBI", false), @{thms Meson.COMBI_def}),
blanchet@43194
  1380
   (("COMBK", false), @{thms Meson.COMBK_def}),
blanchet@43194
  1381
   (("COMBB", false), @{thms Meson.COMBB_def}),
blanchet@43194
  1382
   (("COMBC", false), @{thms Meson.COMBC_def}),
blanchet@43194
  1383
   (("COMBS", false), @{thms Meson.COMBS_def}),
blanchet@43194
  1384
   (("fFalse", false), [@{lemma "~ fFalse" by (unfold fFalse_def) fast}]),
blanchet@43194
  1385
   (("fFalse", true), @{thms True_or_False}),
blanchet@43194
  1386
   (("fTrue", false), [@{lemma "fTrue" by (unfold fTrue_def) fast}]),
blanchet@43194
  1387
   (("fTrue", true), @{thms True_or_False}),
blanchet@43194
  1388
   (("fNot", false),
blanchet@43194
  1389
    @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@43194
  1390
           fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@43194
  1391
   (("fconj", false),
blanchet@43194
  1392
    @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@43194
  1393
        by (unfold fconj_def) fast+}),
blanchet@43194
  1394
   (("fdisj", false),
blanchet@43194
  1395
    @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@43194
  1396
        by (unfold fdisj_def) fast+}),
blanchet@43194
  1397
   (("fimplies", false),
blanchet@43210
  1398
    @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
blanchet@43194
  1399
        by (unfold fimplies_def) fast+}),
nik@43678
  1400
   (("fequal", true),
nik@43678
  1401
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
nik@43678
  1402
       However, this is done so for backward compatibility: Including the
nik@43678
  1403
       equality helpers by default in Metis breaks a few existing proofs. *)
nik@43678
  1404
    @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
nik@43678
  1405
           fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}),
blanchet@44003
  1406
   (* Partial characterization of "fAll" and "fEx". A complete characterization
blanchet@44003
  1407
      would require the axiom of choice for replay with Metis. *)
blanchet@44003
  1408
   (("fAll", false), [@{lemma "~ fAll P | P x" by (auto simp: fAll_def)}]),
blanchet@44003
  1409
   (("fEx", false), [@{lemma "~ P x | fEx P" by (auto simp: fEx_def)}]),
blanchet@43194
  1410
   (("If", true), @{thms if_True if_False True_or_False})]
blanchet@43194
  1411
  |> map (apsnd (map zero_var_indexes))
blanchet@43085
  1412
blanchet@43130
  1413
val type_tag = `make_fixed_const type_tag_name
blanchet@43130
  1414
blanchet@43159
  1415
fun type_tag_idempotence_fact () =
blanchet@42573
  1416
  let
blanchet@42573
  1417
    fun var s = ATerm (`I s, [])
blanchet@43159
  1418
    fun tag tm = ATerm (type_tag, [var "T", tm])
blanchet@43207
  1419
    val tagged_a = tag (var "A")
blanchet@42573
  1420
  in
blanchet@43159
  1421
    Formula (type_tag_idempotence_helper_name, Axiom,
blanchet@43207
  1422
             AAtom (ATerm (`I tptp_equal, [tag tagged_a, tagged_a]))
blanchet@43693
  1423
             |> close_formula_universally, isabelle_info simpN, NONE)
blanchet@42573
  1424
  end
blanchet@42573
  1425
blanchet@43626
  1426
fun should_specialize_helper type_enc t =
blanchet@43628
  1427
  polymorphism_of_type_enc type_enc = Mangled_Monomorphic andalso
blanchet@43628
  1428
  level_of_type_enc type_enc <> No_Types andalso
blanchet@43628
  1429
  not (null (Term.hidden_polymorphism t))
blanchet@43159
  1430
blanchet@43858
  1431
fun helper_facts_for_sym ctxt format type_enc (s, {types, ...} : sym_info) =
blanchet@42573
  1432
  case strip_prefix_and_unascii const_prefix s of
blanchet@42573
  1433
    SOME mangled_s =>
blanchet@42573
  1434
    let
blanchet@42573
  1435
      val thy = Proof_Context.theory_of ctxt
blanchet@42573
  1436
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@43628
  1437
      fun dub needs_fairly_sound j k =
blanchet@43628
  1438
        (unmangled_s ^ "_" ^ string_of_int j ^ "_" ^ string_of_int k ^
blanchet@43628
  1439
         (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
blanchet@43628
  1440
         (if needs_fairly_sound then typed_helper_suffix
blanchet@43628
  1441
          else untyped_helper_suffix),
blanchet@43628
  1442
         Helper)
blanchet@43159
  1443
      fun dub_and_inst needs_fairly_sound (th, j) =
blanchet@43628
  1444
        let val t = prop_of th in
blanchet@43628
  1445
          if should_specialize_helper type_enc t then
blanchet@43628
  1446
            map (fn T => specialize_type thy (invert_const unmangled_s, T) t)
blanchet@43628
  1447
                types
blanchet@43628
  1448
          else
blanchet@43628
  1449
            [t]
blanchet@43628
  1450
        end
blanchet@43628
  1451
        |> map (fn (k, t) => (dub needs_fairly_sound j k, t)) o tag_list 1
blanchet@43860
  1452
      val make_facts = map_filter (make_fact ctxt format type_enc false)
blanchet@43626
  1453
      val fairly_sound = is_type_enc_fairly_sound type_enc
blanchet@42573
  1454
    in
blanchet@43085
  1455
      helper_table
blanchet@43194
  1456
      |> maps (fn ((helper_s, needs_fairly_sound), ths) =>
blanchet@43159
  1457
                  if helper_s <> unmangled_s orelse
blanchet@42894
  1458
                     (needs_fairly_sound andalso not fairly_sound) then
blanchet@42573
  1459
                    []
blanchet@42573
  1460
                  else
blanchet@42573
  1461
                    ths ~~ (1 upto length ths)
blanchet@43628
  1462
                    |> maps (dub_and_inst needs_fairly_sound)
blanchet@43159
  1463
                    |> make_facts)
blanchet@42573
  1464
    end
blanchet@42573
  1465
  | NONE => []
blanchet@43858
  1466
fun helper_facts_for_sym_table ctxt format type_enc sym_tab =
blanchet@43858
  1467
  Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_enc) sym_tab
blanchet@43858
  1468
                  []
blanchet@42573
  1469
blanchet@43085
  1470
(***************************************************************)
blanchet@43085
  1471
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@43085
  1472
(***************************************************************)
blanchet@43085
  1473
blanchet@43085
  1474
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@43085
  1475
blanchet@43085
  1476
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@43085
  1477
blanchet@43085
  1478
(* Remove this trivial type class (FIXME: similar code elsewhere) *)
blanchet@43085
  1479
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
blanchet@43085
  1480
blanchet@43093
  1481
fun classes_of_terms get_Ts =
blanchet@43121
  1482
  map (map snd o get_Ts)
blanchet@43093
  1483
  #> List.foldl add_classes Symtab.empty
blanchet@43093
  1484
  #> delete_type #> Symtab.keys
blanchet@43085
  1485
wenzelm@44121
  1486
val tfree_classes_of_terms = classes_of_terms Misc_Legacy.term_tfrees
wenzelm@44121
  1487
val tvar_classes_of_terms = classes_of_terms Misc_Legacy.term_tvars
blanchet@43085
  1488
blanchet@43622
  1489
fun fold_type_constrs f (Type (s, Ts)) x =
blanchet@43622
  1490
    fold (fold_type_constrs f) Ts (f (s, x))
blanchet@43189
  1491
  | fold_type_constrs _ _ x = x
blanchet@43085
  1492
blanchet@43907
  1493
(* Type constructors used to instantiate overloaded constants are the only ones
blanchet@43907
  1494
   needed. *)
blanchet@43189
  1495
fun add_type_constrs_in_term thy =
blanchet@43085
  1496
  let
blanchet@43188
  1497
    fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@43181
  1498
      | add (t $ u) = add t #> add u
blanchet@43188
  1499
      | add (Const (x as (s, _))) =
blanchet@43188
  1500
        if String.isPrefix skolem_const_prefix s then I
blanchet@43189
  1501
        else x |> Sign.const_typargs thy |> fold (fold_type_constrs set_insert)
blanchet@43907
  1502
      | add (Free (s, T)) =
blanchet@43936
  1503
        if String.isPrefix polymorphic_free_prefix s then
blanchet@43907
  1504
          T |> fold_type_constrs set_insert
blanchet@43907
  1505
        else
blanchet@43907
  1506
          I
blanchet@43181
  1507
      | add (Abs (_, _, u)) = add u
blanchet@43181
  1508
      | add _ = I
blanchet@43181
  1509
  in add end
blanchet@43085
  1510
blanchet@43189
  1511
fun type_constrs_of_terms thy ts =
blanchet@43189
  1512
  Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
blanchet@43085
  1513
blanchet@43856
  1514
fun translate_formulas ctxt format prem_kind type_enc trans_lambdas preproc
blanchet@43828
  1515
                       hyp_ts concl_t facts =
blanchet@42573
  1516
  let
blanchet@42573
  1517
    val thy = Proof_Context.theory_of ctxt
blanchet@43264
  1518
    val presimp_consts = Meson.presimplified_consts ctxt
blanchet@43861
  1519
    val fact_ts = facts |> map snd
blanchet@42573
  1520
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@42573
  1521
       boost an ATP's performance (for some reason). *)
blanchet@43192
  1522
    val hyp_ts =
blanchet@43192
  1523
      hyp_ts
blanchet@43192
  1524
      |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
blanchet@43864
  1525
    val facts = facts |> map (apsnd (pair Axiom))
blanchet@43864
  1526
    val conjs =
blanchet@43861
  1527
      map (pair prem_kind) hyp_ts @ [(Conjecture, concl_t)]
blanchet@43863
  1528
      |> map2 (pair o rpair Local o string_of_int) (0 upto length hyp_ts)
blanchet@43864
  1529
    val ((conjs, facts), lambdas) =
blanchet@43864
  1530
      if preproc then
blanchet@43864
  1531
        conjs @ facts
blanchet@43864
  1532
        |> map (apsnd (apsnd (presimp_prop ctxt presimp_consts)))
blanchet@43864
  1533
        |> preprocess_abstractions_in_terms trans_lambdas
blanchet@43864
  1534
        |>> chop (length conjs)
blanchet@43864
  1535
        |>> apfst (map (apsnd (apsnd freeze_term)))
blanchet@43864
  1536
      else
blanchet@43864
  1537
        ((conjs, facts), [])
blanchet@43864
  1538
    val conjs = conjs |> make_conjecture ctxt format type_enc
blanchet@43863
  1539
    val (fact_names, facts) =
blanchet@43864
  1540
      facts
blanchet@43863
  1541
      |> map_filter (fn (name, (_, t)) =>
blanchet@43863
  1542
                        make_fact ctxt format type_enc true (name, t)
blanchet@43863
  1543
                        |> Option.map (pair name))
blanchet@43861
  1544
      |> ListPair.unzip
blanchet@43863
  1545
    val lambdas =
blanchet@43864
  1546
      lambdas |> map_filter (make_fact ctxt format type_enc true o apsnd snd)
blanchet@43861
  1547
    val all_ts = concl_t :: hyp_ts @ fact_ts
blanchet@42573
  1548
    val subs = tfree_classes_of_terms all_ts
blanchet@42573
  1549
    val supers = tvar_classes_of_terms all_ts
blanchet@43189
  1550
    val tycons = type_constrs_of_terms thy all_ts
blanchet@43861
  1551
    val (supers, arity_clauses) =
blanchet@43626
  1552
      if level_of_type_enc type_enc = No_Types then ([], [])
blanchet@42573
  1553
      else make_arity_clauses thy tycons supers
blanchet@43861
  1554
    val class_rel_clauses = make_class_rel_clauses thy subs supers
blanchet@42573
  1555
  in
blanchet@43863
  1556
    (fact_names |> map single,
blanchet@43863
  1557
     (conjs, facts @ lambdas, class_rel_clauses, arity_clauses))
blanchet@42573
  1558
  end
blanchet@42573
  1559
blanchet@42573
  1560
fun fo_literal_from_type_literal (TyLitVar (class, name)) =
blanchet@42573
  1561
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@42573
  1562
  | fo_literal_from_type_literal (TyLitFree (class, name)) =
blanchet@42573
  1563
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@42573
  1564
blanchet@42573
  1565
fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@42573
  1566
blanchet@44396
  1567
val type_guard = `make_fixed_const type_guard_name
blanchet@43130
  1568
blanchet@44396
  1569
fun type_guard_iterm ctxt format type_enc T tm =
blanchet@44396
  1570
  IApp (IConst (type_guard, T --> @{typ bool}, [T])
blanchet@43859
  1571
        |> enforce_type_arg_policy_in_iterm ctxt format type_enc, tm)
blanchet@42573
  1572
blanchet@43421
  1573
fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
blanchet@43421
  1574
  | is_var_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
blanchet@43000
  1575
    accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
blanchet@43692
  1576
  | is_var_positively_naked_in_term _ _ _ _ = true
blanchet@43493
  1577
fun should_predicate_on_var_in_formula pos phi (SOME true) name =
blanchet@43421
  1578
    formula_fold pos (is_var_positively_naked_in_term name) phi false
blanchet@43493
  1579
  | should_predicate_on_var_in_formula _ _ _ _ = true
blanchet@42834
  1580
nik@43677
  1581
fun mk_aterm format type_enc name T_args args =
nik@43677
  1582
  ATerm (name, map_filter (ho_term_for_type_arg format type_enc) T_args @ args)
blanchet@42994
  1583
blanchet@43626
  1584
fun tag_with_type ctxt format nonmono_Ts type_enc pos T tm =
blanchet@43859
  1585
  IConst (type_tag, T --> T, [T])
blanchet@43859
  1586
  |> enforce_type_arg_policy_in_iterm ctxt format type_enc
blanchet@43859
  1587
  |> ho_term_from_iterm ctxt format nonmono_Ts type_enc (Top_Level pos)
blanchet@43692
  1588
  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm])
blanchet@43692
  1589
       | _ => raise Fail "unexpected lambda-abstraction")
blanchet@43859
  1590
and ho_term_from_iterm ctxt format nonmono_Ts type_enc =
blanchet@42573
  1591
  let
blanchet@42962
  1592
    fun aux site u =
blanchet@42962
  1593
      let
blanchet@43859
  1594
        val (head, args) = strip_iterm_comb u
nik@43677
  1595
        val pos =
blanchet@43361
  1596
          case site of
nik@43677
  1597
            Top_Level pos => pos
nik@43677
  1598
          | Eq_Arg pos => pos
nik@43677
  1599
          | Elsewhere => NONE
nik@43677
  1600
        val t =
nik@43677
  1601
          case head of
blanchet@43859
  1602
            IConst (name as (s, _), _, T_args) =>
nik@43677
  1603
            let
nik@43677
  1604
              val arg_site = if is_tptp_equal s then Eq_Arg pos else Elsewhere
nik@43677
  1605
            in
nik@43677
  1606
              mk_aterm format type_enc name T_args (map (aux arg_site) args)
nik@43677
  1607
            end
blanchet@43859
  1608
          | IVar (name, _) =>
blanchet@43859
  1609
            mk_aterm format type_enc name [] (map (aux Elsewhere) args)
blanchet@43859
  1610
          | IAbs ((name, T), tm) =>
blanchet@43859
  1611
            AAbs ((name, ho_type_from_typ format type_enc true 0 T),
blanchet@43859
  1612
                  aux Elsewhere tm)
blanchet@43859
  1613
          | IApp _ => raise Fail "impossible \"IApp\""
blanchet@43859
  1614
        val T = ityp_of u
blanchet@42962
  1615
      in
blanchet@43626
  1616
        t |> (if should_tag_with_type ctxt nonmono_Ts type_enc site u T then
blanchet@43626
  1617
                tag_with_type ctxt format nonmono_Ts type_enc pos T
blanchet@42962
  1618
              else
blanchet@42962
  1619
                I)
blanchet@42962
  1620
      end
blanchet@42962
  1621
  in aux end
blanchet@43859
  1622
and formula_from_iformula ctxt format nonmono_Ts type_enc
blanchet@43859
  1623
                          should_predicate_on_var =
blanchet@42829
  1624
  let
blanchet@43860
  1625
    val do_term = ho_term_from_iterm ctxt format nonmono_Ts type_enc o Top_Level
blanchet@42573
  1626
    val do_bound_type =
blanchet@43626
  1627
      case type_enc of
blanchet@43624
  1628
        Simple_Types (_, level) =>
blanchet@42994
  1629
        homogenized_type ctxt nonmono_Ts level 0
nik@43677
  1630
        #> ho_type_from_typ format type_enc false 0 #> SOME
blanchet@42682
  1631
      | _ => K NONE
blanchet@42878
  1632
    fun do_out_of_bound_type pos phi universal (name, T) =
blanchet@43626
  1633
      if should_predicate_on_type ctxt nonmono_Ts type_enc
blanchet@42878
  1634
             (fn () => should_predicate_on_var pos phi universal name) T then
blanchet@43859
  1635
        IVar (name, T)
blanchet@44396
  1636
        |> type_guard_iterm ctxt format type_enc T
blanchet@43361
  1637
        |> do_term pos |> AAtom |> SOME
blanchet@42573
  1638
      else
blanchet@42573
  1639
        NONE
blanchet@42878
  1640
    fun do_formula pos (AQuant (q, xs, phi)) =
blanchet@42878
  1641
        let
blanchet@42878
  1642
          val phi = phi |> do_formula pos
blanchet@42878
  1643
          val universal = Option.map (q = AExists ? not) pos
blanchet@42878
  1644
        in
blanchet@42834
  1645
          AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@42834
  1646
                                        | SOME T => do_bound_type T)),
blanchet@42834
  1647
                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@42834
  1648
                      (map_filter
blanchet@42834
  1649
                           (fn (_, NONE) => NONE
blanchet@42834
  1650
                             | (s, SOME T) =>
blanchet@42878
  1651
                               do_out_of_bound_type pos phi universal (s, T))
blanchet@42878
  1652
                           xs)
blanchet@42834
  1653
                      phi)
blanchet@42834
  1654
        end
blanchet@42878
  1655
      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
blanchet@43361
  1656
      | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
blanchet@43493
  1657
  in do_formula end
blanchet@42573
  1658
blanchet@43626
  1659
fun bound_tvars type_enc Ts =
blanchet@42727
  1660
  mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
blanchet@43626
  1661
                (type_literals_for_types type_enc add_sorts_on_tvar Ts))
blanchet@42727
  1662
blanchet@42573
  1663
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@42573
  1664
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@42573
  1665
   the remote provers might care. *)
blanchet@43501
  1666
fun formula_line_for_fact ctxt format prefix encode freshen pos nonmono_Ts
blanchet@43859
  1667
        type_enc (j, {name, locality, kind, iformula, atomic_types}) =
blanchet@43864
  1668
  (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name, kind,
blanchet@43859
  1669
   iformula
blanchet@43859
  1670
   |> close_iformula_universally
blanchet@43859
  1671
   |> formula_from_iformula ctxt format nonmono_Ts type_enc
blanchet@43859
  1672
                            should_predicate_on_var_in_formula
blanchet@43859
  1673
                            (if pos then SOME true else NONE)
blanchet@43626
  1674
   |> bound_tvars type_enc atomic_types
blanchet@43493
  1675
   |> close_formula_universally,
blanchet@43493
  1676
   NONE,
blanchet@43493
  1677
   case locality of
blanchet@43693
  1678
     Intro => isabelle_info introN
blanchet@43693
  1679
   | Elim => isabelle_info elimN
blanchet@43693
  1680
   | Simp => isabelle_info simpN
blanchet@43493
  1681
   | _ => NONE)
blanchet@43493
  1682
  |> Formula
blanchet@42573
  1683
blanchet@43086
  1684
fun formula_line_for_class_rel_clause ({name, subclass, superclass, ...}
blanchet@43086
  1685
                                       : class_rel_clause) =
blanchet@42573
  1686
  let val ty_arg = ATerm (`I "T", []) in
blanchet@42577
  1687
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@42573
  1688
             AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@42573
  1689
                               AAtom (ATerm (superclass, [ty_arg]))])
blanchet@43693
  1690
             |> close_formula_universally, isabelle_info introN, NONE)
blanchet@42573
  1691
  end
blanchet@42573
  1692
blanchet@42573
  1693
fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
blanchet@42573
  1694
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@42573
  1695
  | fo_literal_from_arity_literal (TVarLit (c, sort)) =
blanchet@42573
  1696
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@42573
  1697
blanchet@43086
  1698
fun formula_line_for_arity_clause ({name, prem_lits, concl_lits, ...}
blanchet@43086
  1699
                                   : arity_clause) =
blanchet@43495
  1700
  Formula (arity_clause_prefix ^ name, Axiom,
blanchet@42573
  1701
           mk_ahorn (map (formula_from_fo_literal o apfst not
blanchet@42895
  1702
                          o fo_literal_from_arity_literal) prem_lits)
blanchet@42573
  1703
                    (formula_from_fo_literal
blanchet@42895
  1704
                         (fo_literal_from_arity_literal concl_lits))
blanchet@43693
  1705
           |> close_formula_universally, isabelle_info introN, NONE)
blanchet@42573
  1706
blanchet@43626
  1707
fun formula_line_for_conjecture ctxt format nonmono_Ts type_enc
blanchet@43859
  1708
        ({name, kind, iformula, atomic_types, ...} : translated_formula) =
blanchet@42577
  1709
  Formula (conjecture_prefix ^ name, kind,
blanchet@43859
  1710
           formula_from_iformula ctxt format nonmono_Ts type_enc
blanchet@43493
  1711
               should_predicate_on_var_in_formula (SOME false)
blanchet@43859
  1712
               (close_iformula_universally iformula)
blanchet@43626
  1713
           |> bound_tvars type_enc atomic_types
blanchet@42573
  1714
           |> close_formula_universally, NONE, NONE)
blanchet@42573
  1715
blanchet@43626
  1716
fun free_type_literals type_enc ({atomic_types, ...} : translated_formula) =
blanchet@43626
  1717
  atomic_types |> type_literals_for_types type_enc add_sorts_on_tfree
blanchet@42573
  1718
               |> map fo_literal_from_type_literal
blanchet@42573
  1719
blanchet@42573
  1720
fun formula_line_for_free_type j lit =
blanchet@43085
  1721
  Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis,
blanchet@42573
  1722
           formula_from_fo_literal lit, NONE, NONE)
blanchet@43626
  1723
fun formula_lines_for_free_types type_enc facts =
blanchet@42573
  1724
  let
blanchet@43626
  1725
    val litss = map (free_type_literals type_enc) facts
blanchet@42573
  1726
    val lits = fold (union (op =)) litss []
blanchet@42573
  1727
  in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
blanchet@42573
  1728
blanchet@42573
  1729
(** Symbol declarations **)
blanchet@42544
  1730
blanchet@43626
  1731
fun should_declare_sym type_enc pred_sym s =
blanchet@42998
  1732
  is_tptp_user_symbol s andalso not (String.isPrefix bound_var_prefix s) andalso
blanchet@43626
  1733
  (case type_enc of
blanchet@44396
  1734
     Guards _ => not pred_sym
blanchet@44396
  1735
   | _ => true)
blanchet@38282
  1736
blanchet@43984
  1737
fun sym_decl_table_for_facts ctxt format type_enc repaired_sym_tab
blanchet@43984
  1738
                             (conjs, facts) =
blanchet@42574
  1739
  let
blanchet@43966
  1740
    fun add_iterm_syms in_conj tm =
blanchet@43859
  1741
      let val (head, args) = strip_iterm_comb tm in
blanchet@42574
  1742
        (case head of
blanchet@43859
  1743
           IConst ((s, s'), T, T_args) =>
blanchet@42574
  1744
           let val pred_sym = is_pred_sym repaired_sym_tab s in
blanchet@43626
  1745
             if should_declare_sym type_enc pred_sym s then
blanchet@42576
  1746
               Symtab.map_default (s, [])
blanchet@42886
  1747
                   (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
blanchet@42886
  1748
                                         in_conj))
blanchet@42574
  1749
             else
blanchet@42574
  1750
               I
blanchet@42574
  1751
           end
blanchet@43966
  1752
         | IAbs (_, tm) => add_iterm_syms in_conj tm
blanchet@42574
  1753
         | _ => I)
blanchet@43966
  1754
        #> fold (add_iterm_syms in_conj) args
blanchet@42574
  1755
      end
blanchet@43966
  1756
    fun add_fact_syms in_conj =
blanchet@43966
  1757
      fact_lift (formula_fold NONE (K (add_iterm_syms in_conj)))
blanchet@43966
  1758
    fun add_formula_var_types (AQuant (_, xs, phi)) =
blanchet@43966
  1759
        fold (fn (_, SOME T) => insert_type ctxt I T | _ => I) xs
blanchet@43966
  1760
        #> add_formula_var_types phi
blanchet@43966
  1761
      | add_formula_var_types (AConn (_, phis)) =
blanchet@43966
  1762
        fold add_formula_var_types phis
blanchet@43966
  1763
      | add_formula_var_types _ = I
blanchet@43966
  1764
    fun var_types () =
blanchet@43966
  1765
      if polymorphism_of_type_enc type_enc = Polymorphic then [tvar_a]
blanchet@43966
  1766
      else fold (fact_lift add_formula_var_types) (conjs @ facts) []
blanchet@43966
  1767
    fun add_undefined_const T =
blanchet@43984
  1768
      let
blanchet@43984
  1769
        val (s, s') =
blanchet@43984
  1770
          `make_fixed_const @{const_name undefined}
blanchet@44001
  1771
          |> (case type_arg_policy type_enc @{const_name undefined} of
blanchet@44001
  1772
                Mangled_Type_Args _ => mangled_const_name format type_enc [T]
blanchet@44001
  1773
              | _ => I)
blanchet@43984
  1774
      in
blanchet@43984
  1775
        Symtab.map_default (s, [])
blanchet@43984
  1776
                           (insert_type ctxt #3 (s', [T], T, false, 0, false))
blanchet@43984
  1777
      end
blanchet@42698
  1778
  in
blanchet@42698
  1779
    Symtab.empty
blanchet@43626
  1780
    |> is_type_enc_fairly_sound type_enc
blanchet@43966
  1781
       ? (fold (add_fact_syms true) conjs
blanchet@43966
  1782
          #> fold (add_fact_syms false) facts
blanchet@43985
  1783
          #> (case type_enc of
blanchet@43985
  1784
                Simple_Types _ => I
blanchet@43985
  1785
              | _ => fold add_undefined_const (var_types ())))
blanchet@42698
  1786
  end
blanchet@42533
  1787
blanchet@42685
  1788
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@42685
  1789
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@44397
  1790
fun add_iterm_nonmonotonic_types _ _ _ (SOME false) _ = I
blanchet@44397
  1791
  | add_iterm_nonmonotonic_types ctxt level locality _
blanchet@43859
  1792
        (IApp (IApp (IConst ((s, _), Type (_, [T, _]), _), tm1), tm2)) =
blanchet@43000
  1793
    (is_tptp_equal s andalso exists is_var_or_bound_var [tm1, tm2] andalso
blanchet@42829
  1794
     (case level of
blanchet@44397
  1795
        Noninf_Nonmono_Types soundness =>
blanchet@44397
  1796
        (* The second conjunct about globality is not strictly necessary, but it
blanchet@44397
  1797
           helps prevent finding proofs that are only sound "modulo
blanchet@44397
  1798
           infiniteness". For example, if the conjecture is
blanchet@44397
  1799
           "EX x y::nat. x ~= y", its untyped negation "ALL x y. x = y" would
blanchet@44397
  1800
           lead to a nonsensical proof that we can't replay. *)
blanchet@44397
  1801
        not (is_type_infinite ctxt soundness locality T
blanchet@44397
  1802
             (* andalso is_locality_global locality *))
blanchet@44393
  1803
      | Fin_Nonmono_Types => is_type_surely_finite ctxt T
blanchet@44397
  1804
      | _ => true)) ? insert_type ctxt I T
blanchet@44397
  1805
  | add_iterm_nonmonotonic_types _ _ _ _ _ = I
blanchet@44397
  1806
fun add_fact_nonmonotonic_types ctxt level
blanchet@43859
  1807
        ({kind, locality, iformula, ...} : translated_formula) =
blanchet@42834
  1808
  formula_fold (SOME (kind <> Conjecture))
blanchet@44397
  1809
               (add_iterm_nonmonotonic_types ctxt level locality) iformula
blanchet@44397
  1810
fun nonmonotonic_types_for_facts ctxt type_enc facts =
blanchet@43626
  1811
  let val level = level_of_type_enc type_enc in
blanchet@44397
  1812
    if is_type_level_monotonicity_based level then
blanchet@44397
  1813
      [] |> fold (add_fact_nonmonotonic_types ctxt level) facts
blanchet@42886
  1814
         (* We must add "bool" in case the helper "True_or_False" is added
blanchet@44397
  1815
            later. *)
blanchet@42886
  1816
         |> insert_type ctxt I @{typ bool}
blanchet@42886
  1817
    else
blanchet@42886
  1818
      []
blanchet@42829
  1819
  end
blanchet@42677
  1820
blanchet@44396
  1821
(* FIXME: do the right thing for existentials! *)
blanchet@44396
  1822
fun formula_line_for_guards_mono_type ctxt format nonmono_Ts type_enc T =
blanchet@44396
  1823
  Formula (guards_sym_formula_prefix ^
blanchet@44396
  1824
           ascii_of (mangled_type format type_enc T),
blanchet@44396
  1825
           Axiom,
blanchet@44396
  1826
           IConst (`make_bound_var "X", T, [])
blanchet@44396
  1827
           |> type_guard_iterm ctxt format type_enc T
blanchet@44396
  1828
           |> AAtom
blanchet@44396
  1829
           |> formula_from_iformula ctxt format nonmono_Ts type_enc
blanchet@44396
  1830
                                    (K (K (K (K true)))) (SOME true)
blanchet@44396
  1831
           |> bound_tvars type_enc (atyps_of T)
blanchet@44396
  1832
           |> close_formula_universally,
blanchet@44396
  1833
           isabelle_info introN, NONE)
blanchet@44396
  1834
blanchet@44396
  1835
fun eq_formula type_enc atomic_Ts pred_sym tm1 tm2 =
blanchet@44396
  1836
  (if pred_sym then AConn (AIff, [AAtom tm1, AAtom tm2])
blanchet@44396
  1837
   else AAtom (ATerm (`I tptp_equal, [tm1, tm2])))
blanchet@44396
  1838
  |> bound_tvars type_enc atomic_Ts
blanchet@44396
  1839
  |> close_formula_universally
blanchet@44396
  1840
blanchet@44396
  1841
fun formula_line_for_tags_mono_type ctxt format nonmono_Ts type_enc T =
blanchet@44396
  1842
  let val x_var = ATerm (`make_bound_var "X", []) in
blanchet@44396
  1843
    Formula (tags_sym_formula_prefix ^
blanchet@44396
  1844
             ascii_of (mangled_type format type_enc T),
blanchet@44396
  1845
             Axiom,
blanchet@44396
  1846
             eq_formula type_enc (atyps_of T) false
blanchet@44396
  1847
                        (tag_with_type ctxt format nonmono_Ts type_enc NONE T
blanchet@44396
  1848
                                       x_var)
blanchet@44396
  1849
                        x_var,
blanchet@44396
  1850
             isabelle_info simpN, NONE)
blanchet@44396
  1851
  end
blanchet@44396
  1852
blanchet@44396
  1853
fun problem_lines_for_mono_types ctxt format nonmono_Ts type_enc Ts =
blanchet@44396
  1854
  case type_enc of
blanchet@44396
  1855
    Simple_Types _ => []
blanchet@44396
  1856
  | Guards _ =>
blanchet@44396
  1857
    map (formula_line_for_guards_mono_type ctxt format nonmono_Ts type_enc) Ts
blanchet@44396
  1858
  | Tags _ =>
blanchet@44396
  1859
    map (formula_line_for_tags_mono_type ctxt format nonmono_Ts type_enc) Ts
blanchet@44396
  1860
blanchet@43626
  1861
fun decl_line_for_sym ctxt format nonmono_Ts type_enc s
blanchet@42994
  1862
                      (s', T_args, T, pred_sym, ary, _) =
blanchet@42994
  1863
  let
blanchet@43178
  1864
    val (T_arg_Ts, level) =
blanchet@43626
  1865
      case type_enc of
blanchet@43624
  1866
        Simple_Types (_, level) => ([], level)
blanchet@43178
  1867
      | _ => (replicate (length T_args) homo_infinite_type, No_Types)
blanchet@42994
  1868
  in
blanchet@42998
  1869
    Decl (sym_decl_prefix ^ s, (s, s'),
blanchet@42994
  1870
          (T_arg_Ts ---> (T |> homogenized_type ctxt nonmono_Ts level ary))
nik@43677
  1871
          |> ho_type_from_typ format type_enc pred_sym (length T_arg_Ts + ary))
blanchet@42994
  1872
  end
blanchet@42579
  1873
blanchet@43989
  1874
fun formula_line_for_guards_sym_decl ctxt format conj_sym_kind nonmono_Ts
blanchet@44396
  1875
        type_enc n s j (s', T_args, T, _, ary, in_conj) =
blanchet@42579
  1876
  let
blanchet@42709
  1877
    val (kind, maybe_negate) =
blanchet@42709
  1878
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@42709
  1879
      else (Axiom, I)
blanchet@42753
  1880
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43399
  1881
    val num_args = length arg_Ts
blanchet@42579
  1882
    val bound_names =
blanchet@43399
  1883
      1 upto num_args |> map (`I o make_bound_var o string_of_int)
blanchet@42829
  1884
    val bounds =
blanchet@43859
  1885
      bound_names ~~ arg_Ts |> map (fn (name, T) => IConst (name, T, []))
blanchet@43907
  1886
    val sym_needs_arg_types = exists (curry (op =) dummyT) T_args
blanchet@43401
  1887
    fun should_keep_arg_type T =
blanchet@44393
  1888
      sym_needs_arg_types andalso
blanchet@44393
  1889
      should_predicate_on_type ctxt nonmono_Ts type_enc (K true) T
blanchet@42579
  1890
    val bound_Ts =
blanchet@43401
  1891
      arg_Ts |> map (fn T => if should_keep_arg_type T then SOME T else NONE)
blanchet@42579
  1892
  in
blanchet@43989
  1893
    Formula (guards_sym_formula_prefix ^ s ^
blanchet@42709
  1894
             (if n > 1 then "_" ^ string_of_int j else ""), kind,
blanchet@43859
  1895
             IConst ((s, s'), T, T_args)
blanchet@43859
  1896
             |> fold (curry (IApp o swap)) bounds
blanchet@44396
  1897
             |> type_guard_iterm ctxt format type_enc res_T
blanchet@42963
  1898
             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@44396
  1899
             |> formula_from_iformula ctxt format nonmono_Ts type_enc
blanchet@43859
  1900
                                      (K (K (K (K true)))) (SOME true)
blanchet@43626
  1901
             |> n > 1 ? bound_tvars type_enc (atyps_of T)
blanchet@42709
  1902
             |> close_formula_universally
blanchet@42709
  1903
             |> maybe_negate,
blanchet@43693
  1904
             isabelle_info introN, NONE)
blanchet@42579
  1905
  end
blanchet@42579
  1906
blanchet@43129
  1907
fun formula_lines_for_lightweight_tags_sym_decl ctxt format conj_sym_kind
blanchet@44396
  1908
        nonmono_Ts type_enc n s (j, (s', T_args, T, pred_sym, ary, in_conj)) =
blanchet@42829
  1909
  let
blanchet@42829
  1910
    val ident_base =
blanchet@44396
  1911
      tags_sym_formula_prefix ^ s ^
blanchet@43125
  1912
      (if n > 1 then "_" ^ string_of_int j else "")
blanchet@42852
  1913
    val (kind, maybe_negate) =
blanchet@42852
  1914
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@42852
  1915
      else (Axiom, I)
blanchet@42829
  1916
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@42829
  1917
    val bound_names =
blanchet@42829
  1918
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@42829
  1919
    val bounds = bound_names |> map (fn name => ATerm (name, []))
nik@43677
  1920
    val cst = mk_aterm format type_enc (s, s') T_args
blanchet@44396
  1921
    val eq = maybe_negate oo eq_formula type_enc (atyps_of T) pred_sym
blanchet@44396
  1922
    val should_encode = should_encode_type ctxt nonmono_Ts All_Types
blanchet@44396
  1923
    val tag_with = tag_with_type ctxt format nonmono_Ts type_enc NONE
blanchet@42829
  1924
    val add_formula_for_res =
blanchet@42829
  1925
      if should_encode res_T then
blanchet@42852
  1926
        cons (Formula (ident_base ^ "_res", kind,
blanchet@44396
  1927
                       eq (tag_with res_T (cst bounds)) (cst bounds),
blanchet@43693
  1928
                       isabelle_info simpN, NONE))
blanchet@42829
  1929
      else
blanchet@42829
  1930
        I
blanchet@42829
  1931
    fun add_formula_for_arg k =
blanchet@42829
  1932
      let val arg_T = nth arg_Ts k in
blanchet@42829
  1933
        if should_encode arg_T then
blanchet@42829
  1934
          case chop k bounds of
blanchet@42829
  1935
            (bounds1, bound :: bounds2) =>
blanchet@42852
  1936
            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
blanchet@44396
  1937
                           eq (cst (bounds1 @ tag_with arg_T bound :: bounds2))
blanchet@44396
  1938
                              (cst bounds),
blanchet@43693
  1939
                           isabelle_info simpN, NONE))
blanchet@42829
  1940
          | _ => raise Fail "expected nonempty tail"
blanchet@42829
  1941
        else
blanchet@42829
  1942
          I
blanchet@42829
  1943
      end
blanchet@42829
  1944
  in
blanchet@42834
  1945
    [] |> not pred_sym ? add_formula_for_res
blanchet@42829
  1946
       |> fold add_formula_for_arg (ary - 1 downto 0)
blanchet@42829
  1947
  end
blanchet@42829
  1948
blanchet@42836
  1949
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@42836
  1950
blanchet@44396
  1951
fun problem_lines_for_sym_decls ctxt format conj_sym_kind nonmono_Ts type_enc
blanchet@44396
  1952
                                (s, decls) =
blanchet@43626
  1953
  case type_enc of
blanchet@42998
  1954
    Simple_Types _ =>
blanchet@43626
  1955
    decls |> map (decl_line_for_sym ctxt format nonmono_Ts type_enc s)
blanchet@43989
  1956
  | Guards _ =>
blanchet@42998
  1957
    let
blanchet@42998
  1958
      val decls =
blanchet@42998
  1959
        case decls of
blanchet@42998
  1960
          decl :: (decls' as _ :: _) =>
blanchet@42998
  1961
          let val T = result_type_of_decl decl in
blanchet@42998
  1962
            if forall (curry (type_instance ctxt o swap) T
blanchet@42998
  1963
                       o result_type_of_decl) decls' then
blanchet@42998
  1964
              [decl]
blanchet@42998
  1965
            else
blanchet@42998
  1966
              decls
blanchet@42998
  1967
          end
blanchet@42998
  1968
        | _ => decls
blanchet@42998
  1969
      val n = length decls
blanchet@42998
  1970
      val decls =
blanchet@44396
  1971
        decls |> filter (should_encode_type ctxt nonmono_Ts
blanchet@44396
  1972
                             (level_of_type_enc type_enc)
blanchet@43401
  1973
                         o result_type_of_decl)
blanchet@42998
  1974
    in
blanchet@42998
  1975
      (0 upto length decls - 1, decls)
blanchet@43989
  1976
      |-> map2 (formula_line_for_guards_sym_decl ctxt format conj_sym_kind
blanchet@44396
  1977
                                                 nonmono_Ts type_enc n s)
blanchet@42998
  1978
    end
blanchet@42998
  1979
  | Tags (_, _, heaviness) =>
blanchet@42998
  1980
    (case heaviness of
blanchet@43128
  1981
       Heavyweight => []
blanchet@43128
  1982
     | Lightweight =>
blanchet@42998
  1983
       let val n = length decls in
blanchet@42998
  1984
         (0 upto n - 1 ~~ decls)
blanchet@43129
  1985
         |> maps (formula_lines_for_lightweight_tags_sym_decl ctxt format
blanchet@44396
  1986
                      conj_sym_kind nonmono_Ts type_enc n s)
blanchet@42998
  1987
       end)
blanchet@42579
  1988
blanchet@42956
  1989
fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind nonmono_Ts
blanchet@44396
  1990
                                     type_enc sym_decl_tab =
blanchet@44396
  1991
  let
blanchet@44396
  1992
    val syms = sym_decl_tab |> Symtab.dest |> sort_wrt fst
blanchet@44396
  1993
    val mono_Ts =
blanchet@44396
  1994
      if polymorphism_of_type_enc type_enc = Polymorphic then
blanchet@44396
  1995
        syms |> maps (map result_type_of_decl o snd)
blanchet@44396
  1996
             |> filter_out (should_encode_type ctxt nonmono_Ts
blanchet@44396
  1997
                                (level_of_type_enc type_enc))
blanchet@44396
  1998
             |> rpair [] |-> fold (insert_type ctxt I)
blanchet@44396
  1999
      else
blanchet@44396
  2000
        []
blanchet@44396
  2001
    val mono_lines =
blanchet@44396
  2002
      problem_lines_for_mono_types ctxt format nonmono_Ts type_enc mono_Ts
blanchet@44396
  2003
    val decl_lines =
blanchet@44396
  2004
      fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
blanchet@44396
  2005
                                                     nonmono_Ts type_enc)
blanchet@44396
  2006
               syms []
blanchet@44396
  2007
  in mono_lines @ decl_lines end
blanchet@42543
  2008
blanchet@43185
  2009
fun needs_type_tag_idempotence (Tags (poly, level, heaviness)) =
blanchet@43185
  2010
    poly <> Mangled_Monomorphic andalso
blanchet@43185
  2011
    ((level = All_Types andalso heaviness = Lightweight) orelse
blanchet@44397
  2012
     is_type_level_monotonicity_based level)
blanchet@43159
  2013
  | needs_type_tag_idempotence _ = false
blanchet@42831
  2014
blanchet@42939
  2015
fun offset_of_heading_in_problem _ [] j = j
blanchet@42939
  2016
  | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
blanchet@42939
  2017
    if heading = needle then j
blanchet@42939
  2018
    else offset_of_heading_in_problem needle problem (j + length lines)
blanchet@42939
  2019
blanchet@42998
  2020
val implicit_declsN = "Should-be-implicit typings"
blanchet@42998
  2021
val explicit_declsN = "Explicit typings"
blanchet@41157
  2022
val factsN = "Relevant facts"
blanchet@41157
  2023
val class_relsN = "Class relationships"
blanchet@42543
  2024
val aritiesN = "Arities"
blanchet@41157
  2025
val helpersN = "Helper facts"
blanchet@41157
  2026
val conjsN = "Conjectures"
blanchet@41313
  2027
val free_typesN = "Type variables"
blanchet@41157
  2028
blanchet@43828
  2029
val explicit_apply = NONE (* for experiments *)
blanchet@43259
  2030
blanchet@44397
  2031
fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_enc exporter
blanchet@44397
  2032
        lambda_trans readable_names preproc hyp_ts concl_t facts =
blanchet@38282
  2033
  let
blanchet@43626
  2034
    val (format, type_enc) = choose_format [format] type_enc
blanchet@44088
  2035
    val lambda_trans =
blanchet@44088
  2036
      if lambda_trans = smartN then
blanchet@44088
  2037
        if is_type_enc_higher_order type_enc then lambdasN else combinatorsN
blanchet@44088
  2038
      else if lambda_trans = lambdasN andalso
blanchet@44088
  2039
              not (is_type_enc_higher_order type_enc) then
blanchet@44088
  2040
        error ("Lambda translation method incompatible with first-order \
blanchet@44088
  2041
               \encoding.")
blanchet@44088
  2042
      else
blanchet@44088
  2043
        lambda_trans
blanchet@44088
  2044
    val trans_lambdas =
blanchet@44088
  2045
      if lambda_trans = no_lambdasN then
blanchet@44088
  2046
        rpair []
blanchet@44088
  2047
      else if lambda_trans = concealedN then
blanchet@44088
  2048
        lift_lambdas ctxt type_enc ##> K []
blanchet@44088
  2049
      else if lambda_trans = liftingN then
blanchet@44088
  2050
        lift_lambdas ctxt type_enc
blanchet@44088
  2051
      else if lambda_trans = combinatorsN then
blanchet@44088
  2052
        map (introduce_combinators ctxt) #> rpair []
blanchet@44088
  2053
      else if lambda_trans = hybridN then
blanchet@44088
  2054
        lift_lambdas ctxt type_enc
blanchet@44088
  2055
        ##> maps (fn t => [t, introduce_combinators ctxt
blanchet@44088
  2056
                                  (intentionalize_def t)])
blanchet@44088
  2057
      else if lambda_trans = lambdasN then
blanchet@44088
  2058
        map (Envir.eta_contract) #> rpair []
blanchet@44088
  2059
      else
blanchet@44088
  2060
        error ("Unknown lambda translation method: " ^
blanchet@44088
  2061
               quote lambda_trans ^ ".")
blanchet@41313
  2062
    val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
blanchet@43856
  2063
      translate_formulas ctxt format prem_kind type_enc trans_lambdas preproc
blanchet@43828
  2064
                         hyp_ts concl_t facts
blanchet@43064
  2065
    val sym_tab = conjs @ facts |> sym_table_for_facts ctxt explicit_apply
blanchet@44397
  2066
    val nonmono_Ts = conjs @ facts |> nonmonotonic_types_for_facts ctxt type_enc
blanchet@43626
  2067
    val repair = repair_fact ctxt format type_enc sym_tab
blanchet@42682
  2068
    val (conjs, facts) = (conjs, facts) |> pairself (map repair)
blanchet@43064
  2069
    val repaired_sym_tab =
blanchet@43064
  2070
      conjs @ facts |> sym_table_for_facts ctxt (SOME false)
blanchet@42573
  2071
    val helpers =
blanchet@43858
  2072
      repaired_sym_tab |> helper_facts_for_sym_table ctxt format type_enc
blanchet@43858
  2073
                       |> map repair
blanchet@42680
  2074
    val sym_decl_lines =
blanchet@42731
  2075
      (conjs, helpers @ facts)
blanchet@43984
  2076
      |> sym_decl_table_for_facts ctxt format type_enc repaired_sym_tab
blanchet@43401
  2077
      |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind nonmono_Ts
blanchet@44396
  2078
                                               type_enc
blanchet@42881
  2079
    val helper_lines =
blanchet@42956
  2080
      0 upto length helpers - 1 ~~ helpers
blanchet@43501
  2081
      |> map (formula_line_for_fact ctxt format helper_prefix I false true
blanchet@44396
  2082
                                    nonmono_Ts type_enc)
blanchet@43626
  2083
      |> (if needs_type_tag_idempotence type_enc then
blanchet@43159
  2084
            cons (type_tag_idempotence_fact ())
blanchet@43159
  2085
          else
blanchet@43159
  2086
            I)
blanchet@42522
  2087
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43039
  2088
       FLOTTER hack. *)
blanchet@38282
  2089
    val problem =
blanchet@42998
  2090
      [(explicit_declsN, sym_decl_lines),
blanchet@42956
  2091
       (factsN,
blanchet@43501
  2092
        map (formula_line_for_fact ctxt format fact_prefix ascii_of
blanchet@43501
  2093
                                   (not exporter) (not exporter) nonmono_Ts
blanchet@43626
  2094
                                   type_enc)
blanchet@42956
  2095
            (0 upto length facts - 1 ~~ facts)),
blanchet@42545
  2096
       (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
blanchet@42545
  2097
       (aritiesN, map formula_line_for_arity_clause arity_clauses),
blanchet@42881
  2098
       (helpersN, helper_lines),
blanchet@42962
  2099
       (conjsN,
blanchet@43626
  2100
        map (formula_line_for_conjecture ctxt format nonmono_Ts type_enc)
blanchet@42962
  2101
            conjs),
blanchet@43626
  2102
       (free_typesN, formula_lines_for_free_types type_enc (facts @ conjs))]
blanchet@42543
  2103
    val problem =
blanchet@42561
  2104
      problem
blanchet@43092
  2105
      |> (case format of
blanchet@43092
  2106
            CNF => ensure_cnf_problem
blanchet@43092
  2107
          | CNF_UEQ => filter_cnf_ueq_problem
blanchet@43092
  2108
          | _ => I)
blanchet@42998
  2109
      |> (if is_format_typed format then
blanchet@42998
  2110
            declare_undeclared_syms_in_atp_problem type_decl_prefix
blanchet@42998
  2111
                                                   implicit_declsN
blanchet@42998
  2112
          else
blanchet@42998
  2113
            I)
blanchet@43092
  2114
    val (problem, pool) = problem |> nice_atp_problem readable_names
blanchet@42881
  2115
    val helpers_offset = offset_of_heading_in_problem helpersN problem 0
blanchet@42881
  2116
    val typed_helpers =
blanchet@42881
  2117
      map_filter (fn (j, {name, ...}) =>
blanchet@42881
  2118
                     if String.isSuffix typed_helper_suffix name then SOME j
blanchet@42881
  2119
                     else NONE)
blanchet@42881
  2120
                 ((helpers_offset + 1 upto helpers_offset + length helpers)
blanchet@42881
  2121
                  ~~ helpers)
blanchet@42778
  2122
    fun add_sym_arity (s, {min_ary, ...} : sym_info) =
blanchet@42755
  2123
      if min_ary > 0 then
blanchet@42755
  2124
        case strip_prefix_and_unascii const_prefix s of
blanchet@42755
  2125
          SOME s => Symtab.insert (op =) (s, min_ary)
blanchet@42755
  2126
        | NONE => I
blanchet@42755
  2127
      else
blanchet@42755
  2128
        I
blanchet@38282
  2129
  in
blanchet@38282
  2130
    (problem,
blanchet@38282
  2131
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@42585
  2132
     offset_of_heading_in_problem conjsN problem 0,
blanchet@42541
  2133
     offset_of_heading_in_problem factsN problem 0,
blanchet@42755
  2134
     fact_names |> Vector.fromList,
blanchet@42881
  2135
     typed_helpers,
blanchet@42755
  2136
     Symtab.empty |> Symtab.fold add_sym_arity sym_tab)
blanchet@38282
  2137
  end
blanchet@38282
  2138
blanchet@41313
  2139
(* FUDGE *)
blanchet@41313
  2140
val conj_weight = 0.0
blanchet@41770
  2141
val hyp_weight = 0.1
blanchet@41770
  2142
val fact_min_weight = 0.2
blanchet@41313
  2143
val fact_max_weight = 1.0
blanchet@42608
  2144
val type_info_default_weight = 0.8
blanchet@41313
  2145
blanchet@41313
  2146
fun add_term_weights weight (ATerm (s, tms)) =
nik@43676
  2147
    is_tptp_user_symbol s ? Symtab.default (s, weight)
nik@43676
  2148
    #> fold (add_term_weights weight) tms
nik@43676
  2149
  | add_term_weights weight (AAbs (_, tm)) = add_term_weights weight tm
blanchet@42577
  2150
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@42834
  2151
    formula_fold NONE (K (add_term_weights weight)) phi
blanchet@42528
  2152
  | add_problem_line_weights _ _ = I
blanchet@41313
  2153
blanchet@41313
  2154
fun add_conjectures_weights [] = I
blanchet@41313
  2155
  | add_conjectures_weights conjs =
blanchet@41313
  2156
    let val (hyps, conj) = split_last conjs in
blanchet@41313
  2157
      add_problem_line_weights conj_weight conj
blanchet@41313
  2158
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41313
  2159
    end
blanchet@41313
  2160
blanchet@41313
  2161
fun add_facts_weights facts =
blanchet@41313
  2162
  let
blanchet@41313
  2163
    val num_facts = length facts
blanchet@41313
  2164
    fun weight_of j =
blanchet@41313
  2165
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41313
  2166
                        / Real.fromInt num_facts
blanchet@41313
  2167
  in
blanchet@41313
  2168
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41313
  2169
    |> fold (uncurry add_problem_line_weights)
blanchet@41313
  2170
  end
blanchet@41313
  2171
blanchet@41313
  2172
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41313
  2173
fun atp_problem_weights problem =
blanchet@42608
  2174
  let val get = these o AList.lookup (op =) problem in
blanchet@42608
  2175
    Symtab.empty
blanchet@42608
  2176
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@42608
  2177
    |> add_facts_weights (get factsN)
blanchet@42608
  2178
    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
blanchet@42998
  2179
            [explicit_declsN, class_relsN, aritiesN]
blanchet@42608
  2180
    |> Symtab.dest
blanchet@42608
  2181
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@42608
  2182
  end
blanchet@41313
  2183
blanchet@38282
  2184
end;