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