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