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