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