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