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