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