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