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