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