src/HOL/Tools/ATP/atp_problem_generate.ML
author blanchet
Tue, 26 Jun 2012 11:14:40 +0200
changeset 49148 a5ab5964065f
parent 49147 9aa0fad4e864
child 49149 fa23e699494c
permissions -rw-r--r--
implement polymorphic DFG output, without type classes for now
blanchet@47148
     1
(*  Title:      HOL/Tools/ATP/atp_problem_generate.ML
blanchet@38506
     2
    Author:     Fabian Immler, TU Muenchen
blanchet@38506
     3
    Author:     Makarius
blanchet@38506
     4
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@38506
     5
blanchet@44734
     6
Translation of HOL to FOL for Metis and Sledgehammer.
blanchet@38506
     7
*)
blanchet@38506
     8
blanchet@47148
     9
signature ATP_PROBLEM_GENERATE =
blanchet@38506
    10
sig
nik@44535
    11
  type ('a, 'b) ho_term = ('a, 'b) ATP_Problem.ho_term
blanchet@43977
    12
  type connective = ATP_Problem.connective
blanchet@43977
    13
  type ('a, 'b, 'c) formula = ('a, 'b, 'c) ATP_Problem.formula
blanchet@46172
    14
  type atp_format = ATP_Problem.atp_format
blanchet@48990
    15
  type formula_role = ATP_Problem.formula_role
blanchet@38506
    16
  type 'a problem = 'a ATP_Problem.problem
blanchet@43926
    17
blanchet@48961
    18
  datatype mode = Metis | Sledgehammer | Sledgehammer_Aggressive | Exporter
blanchet@48961
    19
blanchet@47168
    20
  datatype scope = Global | Local | Assum | Chained
blanchet@47933
    21
  datatype status =
blanchet@48019
    22
    General | Induction | Intro | Inductive | Elim | Simp | Def
blanchet@47168
    23
  type stature = scope * status
blanchet@43484
    24
blanchet@47129
    25
  datatype strictness = Strict | Non_Strict
blanchet@49110
    26
  datatype granularity = All_Vars | Positively_Naked_Vars | Undercover_Vars
blanchet@43484
    27
  datatype type_level =
blanchet@45256
    28
    All_Types |
blanchet@49107
    29
    Nonmono_Types of strictness * granularity |
blanchet@49107
    30
    Const_Types of bool (* "?" *) |
blanchet@44233
    31
    No_Types
blanchet@45650
    32
  type type_enc
blanchet@43484
    33
blanchet@46384
    34
  val no_lamsN : string
blanchet@46384
    35
  val hide_lamsN : string
blanchet@47193
    36
  val liftingN : string
blanchet@47193
    37
  val combsN : string
blanchet@47193
    38
  val combs_and_liftingN : string
blanchet@47193
    39
  val combs_or_liftingN : string
blanchet@46384
    40
  val lam_liftingN : string
blanchet@46384
    41
  val keep_lamsN : string
blanchet@44367
    42
  val schematic_var_prefix : string
blanchet@44367
    43
  val fixed_var_prefix : string
blanchet@44367
    44
  val tvar_prefix : string
blanchet@44367
    45
  val tfree_prefix : string
blanchet@44367
    46
  val const_prefix : string
blanchet@44367
    47
  val type_const_prefix : string
blanchet@44367
    48
  val class_prefix : string
blanchet@46425
    49
  val lam_lifted_prefix : string
blanchet@46425
    50
  val lam_lifted_mono_prefix : string
blanchet@46425
    51
  val lam_lifted_poly_prefix : string
blanchet@43926
    52
  val skolem_const_prefix : string
blanchet@43926
    53
  val old_skolem_const_prefix : string
blanchet@43926
    54
  val new_skolem_const_prefix : string
blanchet@46425
    55
  val combinator_prefix : string
blanchet@43966
    56
  val type_decl_prefix : string
blanchet@43966
    57
  val sym_decl_prefix : string
blanchet@44860
    58
  val guards_sym_formula_prefix : string
blanchet@45255
    59
  val tags_sym_formula_prefix : string
blanchet@40445
    60
  val fact_prefix : string
blanchet@38506
    61
  val conjecture_prefix : string
blanchet@43750
    62
  val helper_prefix : string
blanchet@43966
    63
  val class_rel_clause_prefix : string
blanchet@43966
    64
  val arity_clause_prefix : string
blanchet@43966
    65
  val tfree_clause_prefix : string
blanchet@46425
    66
  val lam_fact_prefix : string
blanchet@43750
    67
  val typed_helper_suffix : string
blanchet@43966
    68
  val untyped_helper_suffix : string
blanchet@43807
    69
  val predicator_name : string
blanchet@43807
    70
  val app_op_name : string
blanchet@45255
    71
  val type_guard_name : string
blanchet@43945
    72
  val type_tag_name : string
blanchet@47263
    73
  val native_type_prefix : string
blanchet@44015
    74
  val prefixed_predicator_name : string
blanchet@43971
    75
  val prefixed_app_op_name : string
blanchet@43971
    76
  val prefixed_type_tag_name : string
blanchet@44367
    77
  val ascii_of : string -> string
blanchet@44367
    78
  val unascii_of : string -> string
blanchet@46382
    79
  val unprefix_and_unascii : string -> string -> string option
blanchet@44000
    80
  val proxy_table : (string * (string * (thm * (string * string)))) list
blanchet@44000
    81
  val proxify_const : string -> (string * string) option
blanchet@44367
    82
  val invert_const : string -> string
blanchet@44367
    83
  val unproxify_const : string -> string
blanchet@43934
    84
  val new_skolem_var_name_from_const : string -> string
blanchet@44089
    85
  val atp_irrelevant_consts : string list
blanchet@44089
    86
  val atp_schematic_consts_of : term -> typ list Symtab.table
blanchet@44692
    87
  val is_type_enc_higher_order : type_enc -> bool
blanchet@49146
    88
  val is_type_enc_polymorphic : type_enc -> bool
blanchet@44493
    89
  val level_of_type_enc : type_enc -> type_level
blanchet@49104
    90
  val is_type_enc_sound : type_enc -> bool
blanchet@47129
    91
  val type_enc_from_string : strictness -> string -> type_enc
blanchet@46172
    92
  val adjust_type_enc : atp_format -> type_enc -> type_enc
blanchet@43977
    93
  val mk_aconns :
blanchet@43977
    94
    connective -> ('a, 'b, 'c) formula list -> ('a, 'b, 'c) formula
nik@44535
    95
  val unmangled_const : string -> string * (string, 'b) ho_term list
blanchet@47220
    96
  val unmangled_const_name : string -> string list
blanchet@48961
    97
  val helper_table : ((string * bool) * (status * thm) list) list
blanchet@46385
    98
  val trans_lams_from_string :
blanchet@46385
    99
    Proof.context -> type_enc -> string -> term list -> term list * term list
blanchet@44372
   100
  val factsN : string
blanchet@40240
   101
  val prepare_atp_problem :
blanchet@48990
   102
    Proof.context -> atp_format -> formula_role -> type_enc -> mode -> string
blanchet@48927
   103
    -> bool -> bool -> bool -> term list -> term
blanchet@47168
   104
    -> ((string * stature) * term) list
blanchet@47168
   105
    -> string problem * string Symtab.table * (string * stature) list vector
blanchet@46422
   106
       * (string * term) list * int Symtab.table
blanchet@47901
   107
  val atp_problem_selection_weights : string problem -> (string * real) list
blanchet@47909
   108
  val atp_problem_term_order_info : string problem -> (string * int) list
blanchet@38506
   109
end;
blanchet@38506
   110
blanchet@47148
   111
structure ATP_Problem_Generate : ATP_PROBLEM_GENERATE =
blanchet@38506
   112
struct
blanchet@38506
   113
blanchet@43926
   114
open ATP_Util
blanchet@38506
   115
open ATP_Problem
blanchet@43926
   116
blanchet@43926
   117
type name = string * string
blanchet@43926
   118
blanchet@48961
   119
datatype mode = Metis | Sledgehammer | Sledgehammer_Aggressive | Exporter
blanchet@48961
   120
blanchet@48638
   121
datatype scope = Global | Local | Assum | Chained
blanchet@48638
   122
datatype status = General | Induction | Intro | Inductive | Elim | Simp | Def
blanchet@48638
   123
type stature = scope * status
blanchet@48638
   124
blanchet@48638
   125
datatype order =
blanchet@48638
   126
  First_Order |
blanchet@49019
   127
  Higher_Order of thf_choice
blanchet@49146
   128
datatype phantom_policy = Without_Phantom_Type_Vars | With_Phantom_Type_Vars
blanchet@49146
   129
datatype polymorphism =
blanchet@49146
   130
  Type_Class_Polymorphic |
blanchet@49146
   131
  Raw_Polymorphic of phantom_policy |
blanchet@49146
   132
  Raw_Monomorphic |
blanchet@49146
   133
  Mangled_Monomorphic
blanchet@48638
   134
datatype strictness = Strict | Non_Strict
blanchet@49110
   135
datatype granularity = All_Vars | Positively_Naked_Vars | Undercover_Vars
blanchet@48638
   136
datatype type_level =
blanchet@48638
   137
  All_Types |
blanchet@49107
   138
  Nonmono_Types of strictness * granularity |
blanchet@49107
   139
  Const_Types of bool |
blanchet@48638
   140
  No_Types
blanchet@48638
   141
blanchet@48638
   142
datatype type_enc =
blanchet@48638
   143
  Native of order * polymorphism * type_level |
blanchet@48638
   144
  Guards of polymorphism * type_level |
blanchet@48638
   145
  Tags of polymorphism * type_level
blanchet@48638
   146
blanchet@48638
   147
fun is_type_enc_native (Native _) = true
blanchet@48638
   148
  | is_type_enc_native _ = false
blanchet@48638
   149
fun is_type_enc_higher_order (Native (Higher_Order _, _, _)) = true
blanchet@48638
   150
  | is_type_enc_higher_order _ = false
blanchet@48638
   151
blanchet@48638
   152
fun polymorphism_of_type_enc (Native (_, poly, _)) = poly
blanchet@48638
   153
  | polymorphism_of_type_enc (Guards (poly, _)) = poly
blanchet@48638
   154
  | polymorphism_of_type_enc (Tags (poly, _)) = poly
blanchet@48638
   155
blanchet@49146
   156
fun is_type_enc_polymorphic type_enc =
blanchet@49146
   157
  case polymorphism_of_type_enc type_enc of
blanchet@49146
   158
    Raw_Polymorphic _ => true
blanchet@49146
   159
  | Type_Class_Polymorphic => true
blanchet@49146
   160
  | _ => false
blanchet@49146
   161
blanchet@48638
   162
fun level_of_type_enc (Native (_, _, level)) = level
blanchet@48638
   163
  | level_of_type_enc (Guards (_, level)) = level
blanchet@48638
   164
  | level_of_type_enc (Tags (_, level)) = level
blanchet@48638
   165
blanchet@49107
   166
fun granularity_of_type_level (Nonmono_Types (_, grain)) = grain
blanchet@48638
   167
  | granularity_of_type_level _ = All_Vars
blanchet@48638
   168
blanchet@49104
   169
fun is_type_level_sound All_Types = true
blanchet@49107
   170
  | is_type_level_sound (Nonmono_Types _) = true
blanchet@49104
   171
  | is_type_level_sound _ = false
blanchet@49104
   172
val is_type_enc_sound = is_type_level_sound o level_of_type_enc
blanchet@48638
   173
blanchet@49107
   174
fun is_type_level_monotonicity_based (Nonmono_Types _) = true
blanchet@48638
   175
  | is_type_level_monotonicity_based _ = false
blanchet@48638
   176
blanchet@46387
   177
val no_lamsN = "no_lams" (* used internally; undocumented *)
blanchet@46384
   178
val hide_lamsN = "hide_lams"
blanchet@47193
   179
val liftingN = "lifting"
blanchet@47193
   180
val combsN = "combs"
blanchet@47193
   181
val combs_and_liftingN = "combs_and_lifting"
blanchet@47193
   182
val combs_or_liftingN = "combs_or_lifting"
blanchet@46384
   183
val keep_lamsN = "keep_lams"
blanchet@47193
   184
val lam_liftingN = "lam_lifting" (* legacy *)
blanchet@44959
   185
blanchet@43926
   186
val bound_var_prefix = "B_"
blanchet@48021
   187
val all_bound_var_prefix = "A_"
blanchet@48021
   188
val exist_bound_var_prefix = "E_"
blanchet@43926
   189
val schematic_var_prefix = "V_"
blanchet@43926
   190
val fixed_var_prefix = "v_"
blanchet@43926
   191
val tvar_prefix = "T_"
blanchet@43926
   192
val tfree_prefix = "t_"
blanchet@43926
   193
val const_prefix = "c_"
blanchet@43926
   194
val type_const_prefix = "tc_"
blanchet@47263
   195
val native_type_prefix = "n_"
blanchet@43926
   196
val class_prefix = "cl_"
blanchet@43926
   197
blanchet@46380
   198
(* Freshness almost guaranteed! *)
blanchet@47220
   199
val atp_prefix = "ATP" ^ Long_Name.separator
blanchet@46380
   200
val atp_weak_prefix = "ATP:"
blanchet@46380
   201
blanchet@46425
   202
val lam_lifted_prefix = atp_weak_prefix ^ "Lam"
blanchet@46425
   203
val lam_lifted_mono_prefix = lam_lifted_prefix ^ "m"
blanchet@46425
   204
val lam_lifted_poly_prefix = lam_lifted_prefix ^ "p"
blanchet@44778
   205
blanchet@47220
   206
val skolem_const_prefix = atp_prefix ^ "Sko"
blanchet@43926
   207
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@43926
   208
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@43926
   209
blanchet@46425
   210
val combinator_prefix = "COMB"
blanchet@46425
   211
blanchet@43839
   212
val type_decl_prefix = "ty_"
blanchet@43839
   213
val sym_decl_prefix = "sy_"
blanchet@44860
   214
val guards_sym_formula_prefix = "gsy_"
blanchet@45255
   215
val tags_sym_formula_prefix = "tsy_"
blanchet@47237
   216
val uncurried_alias_eq_prefix = "unc_"
blanchet@40445
   217
val fact_prefix = "fact_"
blanchet@38506
   218
val conjecture_prefix = "conj_"
blanchet@38506
   219
val helper_prefix = "help_"
blanchet@44000
   220
val class_rel_clause_prefix = "clar_"
blanchet@38506
   221
val arity_clause_prefix = "arity_"
blanchet@43926
   222
val tfree_clause_prefix = "tfree_"
blanchet@38506
   223
blanchet@46425
   224
val lam_fact_prefix = "ATP.lambda_"
blanchet@43750
   225
val typed_helper_suffix = "_T"
blanchet@43750
   226
val untyped_helper_suffix = "_U"
blanchet@43750
   227
blanchet@45346
   228
val predicator_name = "pp"
blanchet@45346
   229
val app_op_name = "aa"
blanchet@45346
   230
val type_guard_name = "gg"
blanchet@45346
   231
val type_tag_name = "tt"
blanchet@43402
   232
blanchet@44015
   233
val prefixed_predicator_name = const_prefix ^ predicator_name
blanchet@43971
   234
val prefixed_app_op_name = const_prefix ^ app_op_name
blanchet@43971
   235
val prefixed_type_tag_name = const_prefix ^ type_tag_name
blanchet@43971
   236
blanchet@43926
   237
(*Escaping of special characters.
blanchet@43926
   238
  Alphanumeric characters are left unchanged.
blanchet@43926
   239
  The character _ goes to __
blanchet@43926
   240
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@43926
   241
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
blanchet@43934
   242
val upper_a_minus_space = Char.ord #"A" - Char.ord #" "
blanchet@43926
   243
blanchet@43926
   244
fun stringN_of_int 0 _ = ""
blanchet@43926
   245
  | stringN_of_int k n =
blanchet@43926
   246
    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
blanchet@43926
   247
blanchet@43926
   248
fun ascii_of_char c =
blanchet@43926
   249
  if Char.isAlphaNum c then
blanchet@43926
   250
    String.str c
blanchet@43926
   251
  else if c = #"_" then
blanchet@43926
   252
    "__"
blanchet@43926
   253
  else if #" " <= c andalso c <= #"/" then
blanchet@43926
   254
    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
blanchet@43926
   255
  else
blanchet@43926
   256
    (* fixed width, in case more digits follow *)
blanchet@43926
   257
    "_" ^ stringN_of_int 3 (Char.ord c)
blanchet@43926
   258
blanchet@43926
   259
val ascii_of = String.translate ascii_of_char
blanchet@43926
   260
blanchet@43926
   261
(** Remove ASCII armoring from names in proof files **)
blanchet@43926
   262
blanchet@43926
   263
(* We don't raise error exceptions because this code can run inside a worker
blanchet@43926
   264
   thread. Also, the errors are impossible. *)
blanchet@43926
   265
val unascii_of =
blanchet@43926
   266
  let
blanchet@48990
   267
    fun un rcs [] = String.implode (rev rcs)
blanchet@43926
   268
      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
blanchet@43926
   269
        (* Three types of _ escapes: __, _A to _P, _nnn *)
blanchet@44367
   270
      | un rcs (#"_" :: #"_" :: cs) = un (#"_" :: rcs) cs
blanchet@43926
   271
      | un rcs (#"_" :: c :: cs) =
blanchet@43926
   272
        if #"A" <= c andalso c<= #"P" then
blanchet@43926
   273
          (* translation of #" " to #"/" *)
blanchet@43926
   274
          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
blanchet@43926
   275
        else
blanchet@44367
   276
          let val digits = List.take (c :: cs, 3) handle General.Subscript => [] in
blanchet@43926
   277
            case Int.fromString (String.implode digits) of
blanchet@43926
   278
              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
blanchet@44367
   279
            | NONE => un (c :: #"_" :: rcs) cs (* ERROR *)
blanchet@43926
   280
          end
blanchet@43926
   281
      | un rcs (c :: cs) = un (c :: rcs) cs
blanchet@43926
   282
  in un [] o String.explode end
blanchet@43926
   283
blanchet@43926
   284
(* If string s has the prefix s1, return the result of deleting it,
blanchet@43926
   285
   un-ASCII'd. *)
blanchet@46382
   286
fun unprefix_and_unascii s1 s =
blanchet@43926
   287
  if String.isPrefix s1 s then
blanchet@43926
   288
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@43926
   289
  else
blanchet@43926
   290
    NONE
blanchet@43926
   291
blanchet@44000
   292
val proxy_table =
blanchet@44000
   293
  [("c_False", (@{const_name False}, (@{thm fFalse_def},
blanchet@44000
   294
       ("fFalse", @{const_name ATP.fFalse})))),
blanchet@44000
   295
   ("c_True", (@{const_name True}, (@{thm fTrue_def},
blanchet@44000
   296
       ("fTrue", @{const_name ATP.fTrue})))),
blanchet@44000
   297
   ("c_Not", (@{const_name Not}, (@{thm fNot_def},
blanchet@44000
   298
       ("fNot", @{const_name ATP.fNot})))),
blanchet@44000
   299
   ("c_conj", (@{const_name conj}, (@{thm fconj_def},
blanchet@44000
   300
       ("fconj", @{const_name ATP.fconj})))),
blanchet@44000
   301
   ("c_disj", (@{const_name disj}, (@{thm fdisj_def},
blanchet@44000
   302
       ("fdisj", @{const_name ATP.fdisj})))),
blanchet@44000
   303
   ("c_implies", (@{const_name implies}, (@{thm fimplies_def},
blanchet@44000
   304
       ("fimplies", @{const_name ATP.fimplies})))),
blanchet@44000
   305
   ("equal", (@{const_name HOL.eq}, (@{thm fequal_def},
nik@44537
   306
       ("fequal", @{const_name ATP.fequal})))),
nik@44537
   307
   ("c_All", (@{const_name All}, (@{thm fAll_def},
nik@44537
   308
       ("fAll", @{const_name ATP.fAll})))),
nik@44537
   309
   ("c_Ex", (@{const_name Ex}, (@{thm fEx_def},
nik@44537
   310
       ("fEx", @{const_name ATP.fEx}))))]
blanchet@43926
   311
blanchet@44000
   312
val proxify_const = AList.lookup (op =) proxy_table #> Option.map (snd o snd)
blanchet@43926
   313
blanchet@43926
   314
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@43926
   315
   table unless you know what you are doing. *)
blanchet@43926
   316
val const_trans_table =
blanchet@43926
   317
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@43926
   318
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@43926
   319
   (@{const_name False}, "False"),
blanchet@43926
   320
   (@{const_name True}, "True"),
blanchet@43926
   321
   (@{const_name Not}, "Not"),
blanchet@43926
   322
   (@{const_name conj}, "conj"),
blanchet@43926
   323
   (@{const_name disj}, "disj"),
blanchet@43926
   324
   (@{const_name implies}, "implies"),
blanchet@43926
   325
   (@{const_name HOL.eq}, "equal"),
nik@44537
   326
   (@{const_name All}, "All"),
nik@44537
   327
   (@{const_name Ex}, "Ex"),
blanchet@43926
   328
   (@{const_name If}, "If"),
blanchet@43926
   329
   (@{const_name Set.member}, "member"),
blanchet@46425
   330
   (@{const_name Meson.COMBI}, combinator_prefix ^ "I"),
blanchet@46425
   331
   (@{const_name Meson.COMBK}, combinator_prefix ^ "K"),
blanchet@46425
   332
   (@{const_name Meson.COMBB}, combinator_prefix ^ "B"),
blanchet@46425
   333
   (@{const_name Meson.COMBC}, combinator_prefix ^ "C"),
blanchet@46425
   334
   (@{const_name Meson.COMBS}, combinator_prefix ^ "S")]
blanchet@43926
   335
  |> Symtab.make
blanchet@44000
   336
  |> fold (Symtab.update o swap o snd o snd o snd) proxy_table
blanchet@43926
   337
blanchet@43926
   338
(* Invert the table of translations between Isabelle and ATPs. *)
blanchet@43926
   339
val const_trans_table_inv =
blanchet@43926
   340
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@43926
   341
val const_trans_table_unprox =
blanchet@43926
   342
  Symtab.empty
blanchet@44000
   343
  |> fold (fn (_, (isa, (_, (_, atp)))) => Symtab.update (atp, isa)) proxy_table
blanchet@43926
   344
blanchet@43926
   345
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@43926
   346
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
blanchet@43926
   347
blanchet@43926
   348
fun lookup_const c =
blanchet@43926
   349
  case Symtab.lookup const_trans_table c of
blanchet@43926
   350
    SOME c' => c'
blanchet@43926
   351
  | NONE => ascii_of c
blanchet@43926
   352
blanchet@44489
   353
fun ascii_of_indexname (v, 0) = ascii_of v
blanchet@44489
   354
  | ascii_of_indexname (v, i) = ascii_of v ^ "_" ^ string_of_int i
blanchet@43926
   355
blanchet@43926
   356
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@45262
   357
fun make_all_bound_var x = all_bound_var_prefix ^ ascii_of x
blanchet@45262
   358
fun make_exist_bound_var x = exist_bound_var_prefix ^ ascii_of x
blanchet@43926
   359
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@43926
   360
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
blanchet@43926
   361
blanchet@49148
   362
fun make_tvar (s, i) = tvar_prefix ^ (ascii_of_indexname (unprefix "'" s, i))
blanchet@49148
   363
fun make_tfree s = tfree_prefix ^ (ascii_of (unprefix "'" s))
blanchet@49148
   364
fun tvar_name (x as (s, _)) = (make_tvar x, s)
blanchet@43926
   365
blanchet@46172
   366
(* "HOL.eq" and choice are mapped to the ATP's equivalents *)
nik@45451
   367
local
nik@45451
   368
  val choice_const = (fst o dest_Const o HOLogic.choice_const) Term.dummyT
nik@45451
   369
  fun default c = const_prefix ^ lookup_const c
nik@45451
   370
in
nik@45451
   371
  fun make_fixed_const _ @{const_name HOL.eq} = tptp_old_equal
blanchet@48638
   372
    | make_fixed_const (SOME (Native (Higher_Order THF_With_Choice, _, _))) c =
blanchet@45618
   373
      if c = choice_const then tptp_choice else default c
nik@45451
   374
    | make_fixed_const _ c = default c
nik@45451
   375
end
blanchet@43926
   376
blanchet@43926
   377
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
blanchet@43926
   378
blanchet@43926
   379
fun make_type_class clas = class_prefix ^ ascii_of clas
blanchet@43926
   380
blanchet@43934
   381
fun new_skolem_var_name_from_const s =
blanchet@43934
   382
  let val ss = s |> space_explode Long_Name.separator in
blanchet@43934
   383
    nth ss (length ss - 2)
blanchet@43934
   384
  end
blanchet@43934
   385
blanchet@44089
   386
(* These are either simplified away by "Meson.presimplify" (most of the time) or
blanchet@44089
   387
   handled specially via "fFalse", "fTrue", ..., "fequal". *)
blanchet@44089
   388
val atp_irrelevant_consts =
blanchet@44089
   389
  [@{const_name False}, @{const_name True}, @{const_name Not},
blanchet@44089
   390
   @{const_name conj}, @{const_name disj}, @{const_name implies},
blanchet@44089
   391
   @{const_name HOL.eq}, @{const_name If}, @{const_name Let}]
blanchet@44089
   392
blanchet@44089
   393
val atp_monomorph_bad_consts =
blanchet@44089
   394
  atp_irrelevant_consts @
blanchet@44089
   395
  (* These are ignored anyway by the relevance filter (unless they appear in
blanchet@44089
   396
     higher-order places) but not by the monomorphizer. *)
blanchet@44089
   397
  [@{const_name all}, @{const_name "==>"}, @{const_name "=="},
blanchet@44089
   398
   @{const_name Trueprop}, @{const_name All}, @{const_name Ex},
blanchet@44089
   399
   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}]
blanchet@44089
   400
blanchet@44099
   401
fun add_schematic_const (x as (_, T)) =
blanchet@44099
   402
  Monomorph.typ_has_tvars T ? Symtab.insert_list (op =) x
blanchet@44099
   403
val add_schematic_consts_of =
blanchet@44099
   404
  Term.fold_aterms (fn Const (x as (s, _)) =>
blanchet@44099
   405
                       not (member (op =) atp_monomorph_bad_consts s)
blanchet@44099
   406
                       ? add_schematic_const x
blanchet@44099
   407
                      | _ => I)
blanchet@44099
   408
fun atp_schematic_consts_of t = add_schematic_consts_of t Symtab.empty
blanchet@44089
   409
blanchet@49148
   410
val tvar_a_str = "'a"
blanchet@49148
   411
val tvar_a = TVar ((tvar_a_str, 0), HOLogic.typeS)
blanchet@49148
   412
val tvar_a_name = tvar_name (tvar_a_str, 0)
blanchet@49148
   413
val itself_name = `make_fixed_type_const @{type_name itself}
blanchet@49148
   414
val TYPE_name = `(make_fixed_const NONE) @{const_name TYPE}
blanchet@49148
   415
val tvar_a_atype = AType (tvar_a_name, [])
blanchet@49148
   416
val a_itself_atype = AType (itself_name, [tvar_a_atype])
blanchet@49148
   417
blanchet@43926
   418
(** Definitions and functions for FOL clauses and formulas for TPTP **)
blanchet@43926
   419
blanchet@43926
   420
(** Isabelle arities **)
blanchet@43926
   421
blanchet@44104
   422
val type_class = the_single @{sort type}
blanchet@44104
   423
blanchet@43927
   424
type arity_clause =
blanchet@44367
   425
  {name : string,
blanchet@49148
   426
   prems : (string * typ) list,
blanchet@49148
   427
   concl : string * typ}
blanchet@45483
   428
blanchet@49148
   429
fun add_prem_atom T = fold (fn s => s <> type_class ? cons (s, T))
blanchet@43926
   430
blanchet@43926
   431
(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
blanchet@49148
   432
fun make_axiom_arity_clause (tc, name, (class, args)) =
blanchet@43926
   433
  let
blanchet@49148
   434
    val tvars =
blanchet@49148
   435
      map (fn j => TVar ((tvar_a_str, j), @{sort HOL.type}))
blanchet@49148
   436
          (1 upto length args)
blanchet@43926
   437
  in
blanchet@49148
   438
    {name = name, prems = fold (uncurry add_prem_atom) (tvars ~~ args) [],
blanchet@49148
   439
     concl = (class, Type (tc, tvars))}
blanchet@43926
   440
  end
blanchet@43926
   441
blanchet@43926
   442
fun arity_clause _ _ (_, []) = []
blanchet@44366
   443
  | arity_clause seen n (tcons, ("HOL.type", _) :: ars) =  (* ignore *)
blanchet@44366
   444
    arity_clause seen n (tcons, ars)
blanchet@44366
   445
  | arity_clause seen n (tcons, (ar as (class, _)) :: ars) =
blanchet@44366
   446
    if member (op =) seen class then
blanchet@44366
   447
      (* multiple arities for the same (tycon, class) pair *)
blanchet@44366
   448
      make_axiom_arity_clause (tcons,
blanchet@44366
   449
          lookup_const tcons ^ "___" ^ ascii_of class ^ "_" ^ string_of_int n,
blanchet@44366
   450
          ar) ::
blanchet@44366
   451
      arity_clause seen (n + 1) (tcons, ars)
blanchet@44366
   452
    else
blanchet@44366
   453
      make_axiom_arity_clause (tcons, lookup_const tcons ^ "___" ^
blanchet@44366
   454
                               ascii_of class, ar) ::
blanchet@44366
   455
      arity_clause (class :: seen) n (tcons, ars)
blanchet@43926
   456
blanchet@43926
   457
fun multi_arity_clause [] = []
blanchet@43926
   458
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@45643
   459
    arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
blanchet@43926
   460
blanchet@44489
   461
(* Generate all pairs (tycon, class, sorts) such that tycon belongs to class in
blanchet@44489
   462
   theory thy provided its arguments have the corresponding sorts. *)
blanchet@43926
   463
fun type_class_pairs thy tycons classes =
blanchet@43934
   464
  let
blanchet@43934
   465
    val alg = Sign.classes_of thy
blanchet@43934
   466
    fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@43934
   467
    fun add_class tycon class =
blanchet@43934
   468
      cons (class, domain_sorts tycon class)
blanchet@43934
   469
      handle Sorts.CLASS_ERROR _ => I
blanchet@43934
   470
    fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
blanchet@43934
   471
  in map try_classes tycons end
blanchet@43926
   472
blanchet@43926
   473
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@43926
   474
fun iter_type_class_pairs _ _ [] = ([], [])
blanchet@43926
   475
  | iter_type_class_pairs thy tycons classes =
blanchet@44104
   476
      let
blanchet@44104
   477
        fun maybe_insert_class s =
blanchet@44104
   478
          (s <> type_class andalso not (member (op =) classes s))
blanchet@44104
   479
          ? insert (op =) s
blanchet@44104
   480
        val cpairs = type_class_pairs thy tycons classes
blanchet@44104
   481
        val newclasses =
blanchet@44104
   482
          [] |> fold (fold (fold (fold maybe_insert_class) o snd) o snd) cpairs
blanchet@44104
   483
        val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
blanchet@44107
   484
      in (classes' @ classes, union (op =) cpairs' cpairs) end
blanchet@43926
   485
blanchet@43926
   486
fun make_arity_clauses thy tycons =
blanchet@43926
   487
  iter_type_class_pairs thy tycons ##> multi_arity_clause
blanchet@43926
   488
blanchet@43926
   489
blanchet@43926
   490
(** Isabelle class relations **)
blanchet@43926
   491
blanchet@43927
   492
type class_rel_clause =
blanchet@44367
   493
  {name : string,
blanchet@49148
   494
   subclass : string,
blanchet@49148
   495
   superclass : string}
blanchet@43926
   496
blanchet@44489
   497
(* Generate all pairs (sub, super) such that sub is a proper subclass of super
blanchet@44489
   498
   in theory "thy". *)
blanchet@43926
   499
fun class_pairs _ [] _ = []
blanchet@43926
   500
  | class_pairs thy subs supers =
blanchet@43926
   501
      let
blanchet@43926
   502
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@43926
   503
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@43926
   504
        fun add_supers sub = fold (add_super sub) supers
blanchet@43926
   505
      in fold add_supers subs [] end
blanchet@43926
   506
blanchet@44489
   507
fun make_class_rel_clause (sub, super) =
blanchet@49148
   508
  {name = sub ^ "_" ^ super, subclass = sub, superclass = super}
blanchet@43926
   509
blanchet@43926
   510
fun make_class_rel_clauses thy subs supers =
blanchet@43934
   511
  map make_class_rel_clause (class_pairs thy subs supers)
blanchet@43926
   512
blanchet@44730
   513
(* intermediate terms *)
blanchet@44730
   514
datatype iterm =
blanchet@44730
   515
  IConst of name * typ * typ list |
blanchet@44730
   516
  IVar of name * typ |
blanchet@44730
   517
  IApp of iterm * iterm |
blanchet@44730
   518
  IAbs of (name * typ) * iterm
blanchet@43926
   519
blanchet@44730
   520
fun ityp_of (IConst (_, T, _)) = T
blanchet@44730
   521
  | ityp_of (IVar (_, T)) = T
blanchet@44730
   522
  | ityp_of (IApp (t1, _)) = snd (dest_funT (ityp_of t1))
blanchet@44730
   523
  | ityp_of (IAbs ((_, T), tm)) = T --> ityp_of tm
blanchet@43926
   524
blanchet@43926
   525
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@44730
   526
fun strip_iterm_comb u =
blanchet@44367
   527
  let
blanchet@44730
   528
    fun stripc (IApp (t, u), ts) = stripc (t, u :: ts)
blanchet@44367
   529
      | stripc x = x
blanchet@44367
   530
  in stripc (u, []) end
blanchet@43926
   531
blanchet@46187
   532
fun atomic_types_of T = fold_atyps (insert (op =)) T []
blanchet@43926
   533
blanchet@43926
   534
fun new_skolem_const_name s num_T_args =
blanchet@43926
   535
  [new_skolem_const_prefix, s, string_of_int num_T_args]
wenzelm@47582
   536
  |> Long_Name.implode
blanchet@43926
   537
blanchet@48947
   538
val alpha_to_beta = Logic.varifyT_global @{typ "'a => 'b"}
blanchet@48947
   539
val alpha_to_beta_to_alpha_to_beta = alpha_to_beta --> alpha_to_beta
blanchet@48947
   540
blanchet@45458
   541
fun robust_const_type thy s =
blanchet@46380
   542
  if s = app_op_name then
blanchet@48947
   543
    alpha_to_beta_to_alpha_to_beta
blanchet@46425
   544
  else if String.isPrefix lam_lifted_prefix s then
blanchet@48947
   545
    alpha_to_beta
blanchet@46380
   546
  else
blanchet@46380
   547
    (* Old Skolems throw a "TYPE" exception here, which will be caught. *)
blanchet@46380
   548
    s |> Sign.the_const_type thy
blanchet@45458
   549
blanchet@47513
   550
val robust_const_ary =
blanchet@47513
   551
  let
blanchet@47513
   552
    fun ary (Type (@{type_name fun}, [_, T])) = 1 + ary T
blanchet@47513
   553
      | ary _ = 0
blanchet@47513
   554
  in ary oo robust_const_type end
blanchet@47513
   555
blanchet@45458
   556
(* This function only makes sense if "T" is as general as possible. *)
blanchet@45458
   557
fun robust_const_typargs thy (s, T) =
blanchet@46380
   558
  if s = app_op_name then
blanchet@46380
   559
    let val (T1, T2) = T |> domain_type |> dest_funT in [T1, T2] end
blanchet@46380
   560
  else if String.isPrefix old_skolem_const_prefix s then
blanchet@46380
   561
    [] |> Term.add_tvarsT T |> rev |> map TVar
blanchet@46425
   562
  else if String.isPrefix lam_lifted_prefix s then
blanchet@46425
   563
    if String.isPrefix lam_lifted_poly_prefix s then
blanchet@46382
   564
      let val (T1, T2) = T |> dest_funT in [T1, T2] end
blanchet@46382
   565
    else
blanchet@46382
   566
      []
blanchet@46380
   567
  else
blanchet@46380
   568
    (s, T) |> Sign.const_typargs thy
blanchet@45458
   569
blanchet@44730
   570
(* Converts an Isabelle/HOL term (with combinators) into an intermediate term.
blanchet@44730
   571
   Also accumulates sort infomation. *)
blanchet@48638
   572
fun iterm_from_term thy type_enc bs (P $ Q) =
blanchet@43926
   573
    let
blanchet@48638
   574
      val (P', P_atomics_Ts) = iterm_from_term thy type_enc bs P
blanchet@48638
   575
      val (Q', Q_atomics_Ts) = iterm_from_term thy type_enc bs Q
blanchet@44730
   576
    in (IApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
blanchet@48638
   577
  | iterm_from_term thy type_enc _ (Const (c, T)) =
blanchet@48638
   578
    (IConst (`(make_fixed_const (SOME type_enc)) c, T,
blanchet@45458
   579
             robust_const_typargs thy (c, T)),
blanchet@46187
   580
     atomic_types_of T)
nik@45350
   581
  | iterm_from_term _ _ _ (Free (s, T)) =
blanchet@46380
   582
    (IConst (`make_fixed_var s, T, []), atomic_types_of T)
blanchet@48638
   583
  | iterm_from_term _ type_enc _ (Var (v as (s, _), T)) =
blanchet@43926
   584
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@43926
   585
       let
blanchet@43926
   586
         val Ts = T |> strip_type |> swap |> op ::
blanchet@43926
   587
         val s' = new_skolem_const_name s (length Ts)
blanchet@48638
   588
       in IConst (`(make_fixed_const (SOME type_enc)) s', T, Ts) end
blanchet@43926
   589
     else
blanchet@46187
   590
       IVar ((make_schematic_var v, s), T), atomic_types_of T)
nik@45350
   591
  | iterm_from_term _ _ bs (Bound j) =
blanchet@46187
   592
    nth bs j |> (fn (_, (name, T)) => (IConst (name, T, []), atomic_types_of T))
blanchet@48638
   593
  | iterm_from_term thy type_enc bs (Abs (s, T, t)) =
nik@44537
   594
    let
nik@44537
   595
      fun vary s = s |> AList.defined (op =) bs s ? vary o Symbol.bump_string
nik@44537
   596
      val s = vary s
blanchet@45262
   597
      val name = `make_bound_var s
blanchet@48638
   598
      val (tm, atomic_Ts) =
blanchet@48638
   599
        iterm_from_term thy type_enc ((s, (name, T)) :: bs) t
blanchet@46187
   600
    in (IAbs ((name, T), tm), union (op =) atomic_Ts (atomic_types_of T)) end
blanchet@43926
   601
blanchet@49104
   602
(* "_query" and "_at" are for the ASCII-challenged Metis and Mirabelle. *)
blanchet@45653
   603
val queries = ["?", "_query"]
blanchet@45653
   604
val ats = ["@", "_at"]
blanchet@45653
   605
blanchet@43559
   606
fun try_unsuffixes ss s =
blanchet@43559
   607
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@43559
   608
blanchet@47129
   609
fun type_enc_from_string strictness s =
blanchet@49146
   610
  (case try (unprefix "tc_") s of
blanchet@49146
   611
     SOME s => (SOME Type_Class_Polymorphic, s)
blanchet@43484
   612
   | NONE =>
blanchet@49146
   613
       case try (unprefix "poly_") s of
blanchet@49146
   614
         (* It's still unclear whether all TFF1 implementations will support
blanchet@49146
   615
            type signatures such as "!>[A : $tType] : $o", with phantom type
blanchet@49146
   616
            variables. *)
blanchet@49146
   617
         SOME s => (SOME (Raw_Polymorphic With_Phantom_Type_Vars), s)
blanchet@49146
   618
       | NONE =>
blanchet@49146
   619
         case try (unprefix "raw_mono_") s of
blanchet@49146
   620
           SOME s => (SOME Raw_Monomorphic, s)
blanchet@49146
   621
         | NONE =>
blanchet@49146
   622
           case try (unprefix "mono_") s of
blanchet@49146
   623
             SOME s => (SOME Mangled_Monomorphic, s)
blanchet@49146
   624
           | NONE => (NONE, s))
blanchet@49107
   625
  ||> (fn s =>
blanchet@49107
   626
          case try_unsuffixes queries s of
blanchet@49107
   627
          SOME s =>
blanchet@49107
   628
          (case try_unsuffixes queries s of
blanchet@49107
   629
             SOME s => (Nonmono_Types (strictness, Positively_Naked_Vars), s)
blanchet@49107
   630
           | NONE =>
blanchet@49107
   631
             case try_unsuffixes ats s of
blanchet@49110
   632
               SOME s => (Nonmono_Types (strictness, Undercover_Vars), s)
blanchet@49107
   633
             | NONE => (Nonmono_Types (strictness, All_Vars), s))
blanchet@49107
   634
         | NONE => (All_Types, s))
blanchet@45639
   635
  |> (fn (poly, (level, core)) =>
blanchet@45639
   636
         case (core, (poly, level)) of
blanchet@47263
   637
           ("native", (SOME poly, _)) =>
blanchet@45606
   638
           (case (poly, level) of
blanchet@49146
   639
              (Mangled_Monomorphic, _) =>
blanchet@45673
   640
              if granularity_of_type_level level = All_Vars then
blanchet@48637
   641
                Native (First_Order, Mangled_Monomorphic, level)
blanchet@45639
   642
              else
blanchet@45639
   643
                raise Same.SAME
blanchet@49146
   644
            | (Raw_Monomorphic, _) => raise Same.SAME
blanchet@49146
   645
            | (poly, All_Types) => Native (First_Order, poly, All_Types))
blanchet@47263
   646
         | ("native_higher", (SOME poly, _)) =>
blanchet@45455
   647
           (case (poly, level) of
blanchet@49146
   648
              (_, Nonmono_Types _) => raise Same.SAME
blanchet@45606
   649
            | (Mangled_Monomorphic, _) =>
blanchet@45673
   650
              if granularity_of_type_level level = All_Vars then
blanchet@48638
   651
                Native (Higher_Order THF_With_Choice, Mangled_Monomorphic,
blanchet@48638
   652
                        level)
blanchet@45639
   653
              else
blanchet@45639
   654
                raise Same.SAME
blanchet@49146
   655
            | (Raw_Monomorphic, _) => raise Same.SAME
blanchet@49146
   656
            | (poly, All_Types) =>
blanchet@49146
   657
              Native (Higher_Order THF_With_Choice, poly, All_Types))
blanchet@45672
   658
         | ("guards", (SOME poly, _)) =>
blanchet@46820
   659
           if poly = Mangled_Monomorphic andalso
blanchet@49110
   660
              granularity_of_type_level level = Undercover_Vars then
blanchet@46820
   661
             raise Same.SAME
blanchet@46820
   662
           else
blanchet@46820
   663
             Guards (poly, level)
blanchet@45672
   664
         | ("tags", (SOME poly, _)) =>
blanchet@49110
   665
           if granularity_of_type_level level = Undercover_Vars then
blanchet@46820
   666
             raise Same.SAME
blanchet@46820
   667
           else
blanchet@46820
   668
             Tags (poly, level)
blanchet@45639
   669
         | ("args", (SOME poly, All_Types (* naja *))) =>
blanchet@49107
   670
           Guards (poly, Const_Types false)
blanchet@49107
   671
         | ("args", (SOME poly, Nonmono_Types (_, All_Vars) (* naja *))) =>
blanchet@49107
   672
           if poly = Mangled_Monomorphic then raise Same.SAME
blanchet@49107
   673
           else Guards (poly, Const_Types true)
blanchet@45639
   674
         | ("erased", (NONE, All_Types (* naja *))) =>
blanchet@49146
   675
           Guards (Raw_Polymorphic With_Phantom_Type_Vars, No_Types)
blanchet@43618
   676
         | _ => raise Same.SAME)
blanchet@45653
   677
  handle Same.SAME => error ("Unknown type encoding: " ^ quote s ^ ".")
blanchet@43484
   678
blanchet@48638
   679
fun adjust_order THF_Without_Choice (Higher_Order _) =
blanchet@48638
   680
    Higher_Order THF_Without_Choice
blanchet@48638
   681
  | adjust_order _ type_enc = type_enc
blanchet@48638
   682
blanchet@49145
   683
fun adjust_type_enc (THF (Polymorphic, _, choice, _))
blanchet@48638
   684
                    (Native (order, poly, level)) =
blanchet@49019
   685
    Native (adjust_order choice order, poly, level)
blanchet@49145
   686
  | adjust_type_enc (THF (Monomorphic, _, choice, _))
blanchet@48638
   687
                         (Native (order, _, level)) =
blanchet@49019
   688
    Native (adjust_order choice order, Mangled_Monomorphic, level)
blanchet@49145
   689
  | adjust_type_enc (TFF (Monomorphic, _)) (Native (_, _, level)) =
blanchet@48637
   690
    Native (First_Order, Mangled_Monomorphic, level)
blanchet@49146
   691
  | adjust_type_enc (DFG Polymorphic) (Native (_, poly, level)) =
blanchet@49146
   692
    Native (First_Order, poly, level)
blanchet@49146
   693
  | adjust_type_enc (DFG Monomorphic) (Native (_, _, level)) =
blanchet@48637
   694
    Native (First_Order, Mangled_Monomorphic, level)
blanchet@48637
   695
  | adjust_type_enc (TFF _) (Native (_, poly, level)) =
blanchet@48637
   696
    Native (First_Order, poly, level)
blanchet@48637
   697
  | adjust_type_enc format (Native (_, poly, level)) =
blanchet@45639
   698
    adjust_type_enc format (Guards (poly, level))
blanchet@45275
   699
  | adjust_type_enc CNF_UEQ (type_enc as Guards stuff) =
blanchet@49104
   700
    (if is_type_enc_sound type_enc then Tags else Guards) stuff
blanchet@45275
   701
  | adjust_type_enc _ type_enc = type_enc
blanchet@43942
   702
blanchet@47689
   703
fun is_fol_term t =
blanchet@47689
   704
  case t of
blanchet@47689
   705
    @{const Not} $ t1 => is_fol_term t1
blanchet@47689
   706
  | Const (@{const_name All}, _) $ Abs (_, _, t') => is_fol_term t'
blanchet@47689
   707
  | Const (@{const_name All}, _) $ t1 => is_fol_term t1
blanchet@47689
   708
  | Const (@{const_name Ex}, _) $ Abs (_, _, t') => is_fol_term t'
blanchet@47689
   709
  | Const (@{const_name Ex}, _) $ t1 => is_fol_term t1
blanchet@47689
   710
  | @{const HOL.conj} $ t1 $ t2 => is_fol_term t1 andalso is_fol_term t2
blanchet@47689
   711
  | @{const HOL.disj} $ t1 $ t2 => is_fol_term t1 andalso is_fol_term t2
blanchet@47689
   712
  | @{const HOL.implies} $ t1 $ t2 => is_fol_term t1 andalso is_fol_term t2
blanchet@47689
   713
  | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@47689
   714
    is_fol_term t1 andalso is_fol_term t2
blanchet@47689
   715
  | _ => not (exists_subterm (fn Abs _ => true | _ => false) t)
blanchet@47689
   716
blanchet@47689
   717
fun simple_translate_lambdas do_lambdas ctxt t =
blanchet@47689
   718
  if is_fol_term t then
blanchet@47689
   719
    t
blanchet@47689
   720
  else
blanchet@47689
   721
    let
blanchet@47689
   722
      fun trans Ts t =
blanchet@47689
   723
        case t of
blanchet@47689
   724
          @{const Not} $ t1 => @{const Not} $ trans Ts t1
blanchet@47689
   725
        | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@47689
   726
          t0 $ Abs (s, T, trans (T :: Ts) t')
blanchet@47689
   727
        | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@47689
   728
          trans Ts (t0 $ eta_expand Ts t1 1)
blanchet@47689
   729
        | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@47689
   730
          t0 $ Abs (s, T, trans (T :: Ts) t')
blanchet@47689
   731
        | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@47689
   732
          trans Ts (t0 $ eta_expand Ts t1 1)
blanchet@47689
   733
        | (t0 as @{const HOL.conj}) $ t1 $ t2 =>
blanchet@47689
   734
          t0 $ trans Ts t1 $ trans Ts t2
blanchet@47689
   735
        | (t0 as @{const HOL.disj}) $ t1 $ t2 =>
blanchet@47689
   736
          t0 $ trans Ts t1 $ trans Ts t2
blanchet@47689
   737
        | (t0 as @{const HOL.implies}) $ t1 $ t2 =>
blanchet@47689
   738
          t0 $ trans Ts t1 $ trans Ts t2
blanchet@47689
   739
        | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@47689
   740
            $ t1 $ t2 =>
blanchet@47689
   741
          t0 $ trans Ts t1 $ trans Ts t2
blanchet@47689
   742
        | _ =>
blanchet@47689
   743
          if not (exists_subterm (fn Abs _ => true | _ => false) t) then t
blanchet@47689
   744
          else t |> Envir.eta_contract |> do_lambdas ctxt Ts
blanchet@47689
   745
      val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@47689
   746
    in t |> trans [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@47689
   747
blanchet@47689
   748
fun do_cheaply_conceal_lambdas Ts (t1 $ t2) =
blanchet@47689
   749
    do_cheaply_conceal_lambdas Ts t1
blanchet@47689
   750
    $ do_cheaply_conceal_lambdas Ts t2
blanchet@47689
   751
  | do_cheaply_conceal_lambdas Ts (Abs (_, T, t)) =
blanchet@47689
   752
    Const (lam_lifted_poly_prefix ^ serial_string (),
blanchet@47689
   753
           T --> fastype_of1 (T :: Ts, t))
blanchet@47689
   754
  | do_cheaply_conceal_lambdas _ t = t
blanchet@47689
   755
blanchet@47689
   756
fun concealed_bound_name j = atp_weak_prefix ^ string_of_int j
blanchet@47689
   757
fun conceal_bounds Ts t =
blanchet@47689
   758
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@47689
   759
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@47689
   760
fun reveal_bounds Ts =
blanchet@47689
   761
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@47689
   762
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@47689
   763
blanchet@47689
   764
fun do_introduce_combinators ctxt Ts t =
blanchet@47689
   765
  let val thy = Proof_Context.theory_of ctxt in
blanchet@47689
   766
    t |> conceal_bounds Ts
blanchet@47689
   767
      |> cterm_of thy
blanchet@47689
   768
      |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@47689
   769
      |> prop_of |> Logic.dest_equals |> snd
blanchet@47689
   770
      |> reveal_bounds Ts
blanchet@47689
   771
  end
blanchet@47689
   772
  (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@47689
   773
  handle THM _ => t |> do_cheaply_conceal_lambdas Ts
blanchet@47689
   774
val introduce_combinators = simple_translate_lambdas do_introduce_combinators
blanchet@47689
   775
blanchet@46380
   776
fun constify_lifted (t $ u) = constify_lifted t $ constify_lifted u
blanchet@46380
   777
  | constify_lifted (Abs (s, T, t)) = Abs (s, T, constify_lifted t)
blanchet@46380
   778
  | constify_lifted (Free (x as (s, _))) =
blanchet@46425
   779
    (if String.isPrefix lam_lifted_prefix s then Const else Free) x
blanchet@46380
   780
  | constify_lifted t = t
blanchet@46380
   781
blanchet@46425
   782
fun lift_lams_part_1 ctxt type_enc =
blanchet@46439
   783
  map close_form #> rpair ctxt
blanchet@44959
   784
  #-> Lambda_Lifting.lift_lambdas
blanchet@49146
   785
          (SOME ((if is_type_enc_polymorphic type_enc then
blanchet@46435
   786
                    lam_lifted_poly_prefix
blanchet@46435
   787
                  else
blanchet@46435
   788
                    lam_lifted_mono_prefix) ^ "_a"))
blanchet@44959
   789
          Lambda_Lifting.is_quantifier
blanchet@46425
   790
  #> fst
blanchet@47689
   791
blanchet@47689
   792
fun lift_lams_part_2 ctxt (facts, lifted) =
blanchet@47689
   793
  (facts, lifted)
blanchet@47689
   794
  (* Lambda-lifting sometimes leaves some lambdas around; we need some way to get rid
blanchet@47689
   795
     of them *)
blanchet@47689
   796
  |> pairself (map (introduce_combinators ctxt))
blanchet@47689
   797
  |> pairself (map constify_lifted)
blanchet@48589
   798
  (* Requires bound variables not to clash with any schematic variables (as
blanchet@48589
   799
     should be the case right after lambda-lifting). *)
blanchet@47689
   800
  |>> map (open_form (unprefix close_form_prefix))
blanchet@47689
   801
  ||> map (open_form I)
blanchet@47689
   802
blanchet@47689
   803
fun lift_lams ctxt = lift_lams_part_2 ctxt oo lift_lams_part_1 ctxt
blanchet@44959
   804
blanchet@44959
   805
fun intentionalize_def (Const (@{const_name All}, _) $ Abs (_, _, t)) =
blanchet@44959
   806
    intentionalize_def t
blanchet@44959
   807
  | intentionalize_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
blanchet@44959
   808
    let
blanchet@44959
   809
      fun lam T t = Abs (Name.uu, T, t)
blanchet@44959
   810
      val (head, args) = strip_comb t ||> rev
blanchet@44959
   811
      val head_T = fastype_of head
blanchet@44959
   812
      val n = length args
blanchet@44959
   813
      val arg_Ts = head_T |> binder_types |> take n |> rev
blanchet@44959
   814
      val u = u |> subst_atomic (args ~~ map Bound (0 upto n - 1))
blanchet@44959
   815
    in HOLogic.eq_const head_T $ head $ fold lam arg_Ts u end
blanchet@44959
   816
  | intentionalize_def t = t
blanchet@44959
   817
blanchet@48996
   818
type ifact =
blanchet@44367
   819
  {name : string,
blanchet@47168
   820
   stature : stature,
blanchet@48990
   821
   role : formula_role,
blanchet@44730
   822
   iformula : (name, typ, iterm) formula,
blanchet@44367
   823
   atomic_types : typ list}
blanchet@38506
   824
blanchet@48996
   825
fun update_iformula f ({name, stature, role, iformula, atomic_types} : ifact) =
blanchet@48990
   826
  {name = name, stature = stature, role = role, iformula = f iformula,
blanchet@48996
   827
   atomic_types = atomic_types} : ifact
blanchet@43413
   828
blanchet@48996
   829
fun ifact_lift f ({iformula, ...} : ifact) = f iformula
blanchet@43429
   830
blanchet@48021
   831
fun insert_type thy get_T x xs =
blanchet@43905
   832
  let val T = get_T x in
blanchet@48021
   833
    if exists (type_instance thy T o get_T) xs then xs
blanchet@48021
   834
    else x :: filter_out (type_generalization thy T o get_T) xs
blanchet@43905
   835
  end
blanchet@43547
   836
blanchet@43618
   837
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@43618
   838
datatype type_arg_policy =
blanchet@45642
   839
  Mangled_Type_Args |
blanchet@49103
   840
  All_Type_Args |
blanchet@49103
   841
  Noninferable_Type_Args |
blanchet@49103
   842
  Constr_Type_Args |
blanchet@43618
   843
  No_Type_Args
blanchet@41384
   844
blanchet@49103
   845
fun type_arg_policy constrs type_enc s =
blanchet@46186
   846
  let val poly = polymorphism_of_type_enc type_enc in
blanchet@45645
   847
    if s = type_tag_name then
blanchet@49103
   848
      if poly = Mangled_Monomorphic then Mangled_Type_Args else All_Type_Args
blanchet@45645
   849
    else case type_enc of
blanchet@49146
   850
      Native (_, Raw_Polymorphic _, _) => All_Type_Args
blanchet@49146
   851
    | Native (_, Type_Class_Polymorphic, _) => All_Type_Args
blanchet@46186
   852
    | Tags (_, All_Types) => No_Type_Args
blanchet@45645
   853
    | _ =>
blanchet@45645
   854
      let val level = level_of_type_enc type_enc in
blanchet@45645
   855
        if level = No_Types orelse s = @{const_name HOL.eq} orelse
blanchet@49107
   856
           (case level of Const_Types _ => s = app_op_name | _ => false) then
blanchet@45645
   857
          No_Type_Args
blanchet@46186
   858
        else if poly = Mangled_Monomorphic then
blanchet@45645
   859
          Mangled_Type_Args
blanchet@49103
   860
        else if level = All_Types orelse
blanchet@49110
   861
                granularity_of_type_level level = Undercover_Vars then
blanchet@49103
   862
          Noninferable_Type_Args
blanchet@49107
   863
        else if member (op =) constrs s andalso level <> Const_Types false then
blanchet@49103
   864
          Constr_Type_Args
blanchet@45645
   865
        else
blanchet@49103
   866
          All_Type_Args
blanchet@45645
   867
      end
blanchet@45645
   868
  end
blanchet@43088
   869
blanchet@47166
   870
val fused_infinite_type_name = "ATP.fused_inf" (* shouldn't clash *)
blanchet@45458
   871
val fused_infinite_type = Type (fused_infinite_type_name, [])
blanchet@45458
   872
blanchet@48638
   873
fun ho_term_from_typ type_enc =
blanchet@43835
   874
  let
blanchet@43835
   875
    fun term (Type (s, Ts)) =
blanchet@49147
   876
      ATerm ((case (is_type_enc_higher_order type_enc, s) of
blanchet@49147
   877
                (true, @{type_name bool}) => `I tptp_bool_type
blanchet@49147
   878
              | (true, @{type_name fun}) => `I tptp_fun_type
blanchet@49147
   879
              | _ => if s = fused_infinite_type_name andalso
blanchet@49147
   880
                        is_type_enc_native type_enc then
blanchet@49147
   881
                       `I tptp_individual_type
blanchet@49147
   882
                     else
blanchet@49147
   883
                       `make_fixed_type_const s,
blanchet@49147
   884
              []), map term Ts)
blanchet@49148
   885
    | term (TFree (s, _)) = ATerm ((`make_tfree s, []), [])
blanchet@49147
   886
    | term (TVar (x, _)) = ATerm ((tvar_name x, []), [])
blanchet@43835
   887
  in term end
blanchet@43433
   888
blanchet@48638
   889
fun ho_term_for_type_arg type_enc T =
blanchet@48638
   890
  if T = dummyT then NONE else SOME (ho_term_from_typ type_enc T)
blanchet@44264
   891
blanchet@43433
   892
(* This shouldn't clash with anything else. *)
blanchet@47237
   893
val uncurried_alias_sep = "\000"
blanchet@47220
   894
val mangled_type_sep = "\001"
blanchet@47220
   895
blanchet@47237
   896
val ascii_of_uncurried_alias_sep = ascii_of uncurried_alias_sep
blanchet@43413
   897
blanchet@49147
   898
(* ### FIXME: insane *)
blanchet@49147
   899
fun generic_mangled_type_name f (ATerm ((name, _), [])) = f name
blanchet@49147
   900
  | generic_mangled_type_name f (ATerm ((name, _), tys)) =
blanchet@43626
   901
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@43626
   902
    ^ ")"
blanchet@44558
   903
  | generic_mangled_type_name _ _ = raise Fail "unexpected type abstraction"
blanchet@43413
   904
blanchet@48638
   905
fun mangled_type type_enc =
blanchet@48638
   906
  generic_mangled_type_name fst o ho_term_from_typ type_enc
blanchet@45255
   907
blanchet@47263
   908
fun make_native_type s =
blanchet@43926
   909
  if s = tptp_bool_type orelse s = tptp_fun_type orelse
blanchet@43926
   910
     s = tptp_individual_type then
blanchet@43926
   911
    s
blanchet@43926
   912
  else
blanchet@47263
   913
    native_type_prefix ^ ascii_of s
blanchet@43926
   914
nik@44535
   915
fun ho_type_from_ho_term type_enc pred_sym ary =
blanchet@43804
   916
  let
blanchet@45457
   917
    fun to_mangled_atype ty =
blanchet@47263
   918
      AType ((make_native_type (generic_mangled_type_name fst ty),
blanchet@45457
   919
              generic_mangled_type_name snd ty), [])
blanchet@49147
   920
    fun to_poly_atype (ATerm ((name, []), tys)) =
blanchet@49147
   921
        AType (name, map to_poly_atype tys)
blanchet@45457
   922
      | to_poly_atype _ = raise Fail "unexpected type abstraction"
blanchet@45457
   923
    val to_atype =
blanchet@49146
   924
      if is_type_enc_polymorphic type_enc then to_poly_atype
blanchet@45457
   925
      else to_mangled_atype
blanchet@43804
   926
    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
blanchet@43839
   927
    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
blanchet@43835
   928
      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
blanchet@44558
   929
      | to_fo _ _ = raise Fail "unexpected type abstraction"
blanchet@49147
   930
    fun to_ho (ty as ATerm (((s, _), []), tys)) =
nik@44535
   931
        if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
nik@44535
   932
      | to_ho _ = raise Fail "unexpected type abstraction"
blanchet@44493
   933
  in if is_type_enc_higher_order type_enc then to_ho else to_fo ary end
blanchet@43804
   934
blanchet@48638
   935
fun ho_type_from_typ type_enc pred_sym ary =
nik@44535
   936
  ho_type_from_ho_term type_enc pred_sym ary
blanchet@48638
   937
  o ho_term_from_typ type_enc
blanchet@43804
   938
blanchet@49148
   939
(* Make atoms for sorted type variables. *)
blanchet@49148
   940
fun generic_add_sorts_on_type _ [] = I
blanchet@49148
   941
  | generic_add_sorts_on_type T (s :: ss) =
blanchet@49148
   942
    generic_add_sorts_on_type T ss
blanchet@49148
   943
    #> (if s = the_single @{sort HOL.type} then I else insert (op =) (s, T))
blanchet@49148
   944
fun add_sorts_on_tfree (T as TFree (_, S)) = generic_add_sorts_on_type T S
blanchet@49148
   945
  | add_sorts_on_tfree _ = I
blanchet@49148
   946
fun add_sorts_on_tvar (T as TVar (_, S)) = generic_add_sorts_on_type T S
blanchet@49148
   947
  | add_sorts_on_tvar _ = I
blanchet@49148
   948
blanchet@49148
   949
fun process_type_args type_enc T_args =
blanchet@49148
   950
  if is_type_enc_native type_enc then
blanchet@49148
   951
    (map (ho_type_from_typ type_enc false 0) T_args, [])
blanchet@49148
   952
  else
blanchet@49148
   953
    ([], map_filter (ho_term_for_type_arg type_enc) T_args)
blanchet@49148
   954
blanchet@49148
   955
fun type_class_atom type_enc (class, T) =
blanchet@49148
   956
  let
blanchet@49148
   957
    val class = `make_type_class class
blanchet@49148
   958
    val (ty_args, tm_args) = process_type_args type_enc [T]
blanchet@49148
   959
    val tm_args =
blanchet@49148
   960
      tm_args @
blanchet@49148
   961
      (case type_enc of
blanchet@49148
   962
         Native (First_Order, Raw_Polymorphic Without_Phantom_Type_Vars, _) =>
blanchet@49148
   963
         [ATerm ((TYPE_name, ty_args), [])]
blanchet@49148
   964
       | _ => [])
blanchet@49148
   965
  in AAtom (ATerm ((class, ty_args), tm_args)) end
blanchet@49148
   966
fun formulas_for_types type_enc add_sorts_on_typ Ts =
blanchet@49148
   967
  [] |> level_of_type_enc type_enc <> No_Types ? fold add_sorts_on_typ Ts
blanchet@49148
   968
     |> map (type_class_atom type_enc)
blanchet@49148
   969
blanchet@49148
   970
fun mk_aconns c phis =
blanchet@49148
   971
  let val (phis', phi') = split_last phis in
blanchet@49148
   972
    fold_rev (mk_aconn c) phis' phi'
blanchet@49148
   973
  end
blanchet@49148
   974
blanchet@49148
   975
fun mk_ahorn [] phi = phi
blanchet@49148
   976
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@49148
   977
blanchet@49148
   978
fun mk_aquant _ [] phi = phi
blanchet@49148
   979
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@49148
   980
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@49148
   981
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@49148
   982
blanchet@49148
   983
fun mk_atyquant _ [] phi = phi
blanchet@49148
   984
  | mk_atyquant q xs (phi as ATyQuant (q', xs', phi')) =
blanchet@49148
   985
    if q = q' then ATyQuant (q, xs @ xs', phi') else ATyQuant (q, xs, phi)
blanchet@49148
   986
  | mk_atyquant q xs phi = ATyQuant (q, xs, phi)
blanchet@49148
   987
blanchet@49148
   988
fun close_universally add_term_vars phi =
blanchet@49148
   989
  let
blanchet@49148
   990
    fun add_formula_vars bounds (ATyQuant (_, _, phi)) =
blanchet@49148
   991
        add_formula_vars bounds phi
blanchet@49148
   992
      | add_formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@49148
   993
        add_formula_vars (map fst xs @ bounds) phi
blanchet@49148
   994
      | add_formula_vars bounds (AConn (_, phis)) =
blanchet@49148
   995
        fold (add_formula_vars bounds) phis
blanchet@49148
   996
      | add_formula_vars bounds (AAtom tm) = add_term_vars bounds tm
blanchet@49148
   997
  in mk_aquant AForall (add_formula_vars [] phi []) phi end
blanchet@49148
   998
blanchet@49148
   999
fun add_term_vars bounds (ATerm ((name as (s, _), _), tms)) =
blanchet@49148
  1000
    (if is_tptp_variable s andalso
blanchet@49148
  1001
        not (String.isPrefix tvar_prefix s) andalso
blanchet@49148
  1002
        not (member (op =) bounds name) then
blanchet@49148
  1003
       insert (op =) (name, NONE)
blanchet@49148
  1004
     else
blanchet@49148
  1005
       I)
blanchet@49148
  1006
    #> fold (add_term_vars bounds) tms
blanchet@49148
  1007
  | add_term_vars bounds (AAbs (((name, _), tm), args)) =
blanchet@49148
  1008
    add_term_vars (name :: bounds) tm #> fold (add_term_vars bounds) args
blanchet@49148
  1009
fun close_formula_universally phi = close_universally add_term_vars phi
blanchet@49148
  1010
blanchet@49148
  1011
fun add_iterm_vars bounds (IApp (tm1, tm2)) =
blanchet@49148
  1012
    fold (add_iterm_vars bounds) [tm1, tm2]
blanchet@49148
  1013
  | add_iterm_vars _ (IConst _) = I
blanchet@49148
  1014
  | add_iterm_vars bounds (IVar (name, T)) =
blanchet@49148
  1015
    not (member (op =) bounds name) ? insert (op =) (name, SOME T)
blanchet@49148
  1016
  | add_iterm_vars bounds (IAbs (_, tm)) = add_iterm_vars bounds tm
blanchet@49148
  1017
blanchet@49148
  1018
fun close_iformula_universally phi = close_universally add_iterm_vars phi
blanchet@49148
  1019
blanchet@47237
  1020
fun aliased_uncurried ary (s, s') =
blanchet@47237
  1021
  (s ^ ascii_of_uncurried_alias_sep ^ string_of_int ary, s' ^ string_of_int ary)
blanchet@47237
  1022
fun unaliased_uncurried (s, s') =
blanchet@47237
  1023
  case space_explode uncurried_alias_sep s of
blanchet@47220
  1024
    [_] => (s, s')
blanchet@47220
  1025
  | [s1, s2] => (s1, unsuffix s2 s')
blanchet@47220
  1026
  | _ => raise Fail "ill-formed explicit application alias"
blanchet@47220
  1027
blanchet@47220
  1028
fun raw_mangled_const_name type_name ty_args (s, s') =
blanchet@43804
  1029
  let
blanchet@43804
  1030
    fun type_suffix f g =
blanchet@47220
  1031
      fold_rev (curry (op ^) o g o prefix mangled_type_sep o type_name f)
blanchet@47220
  1032
               ty_args ""
blanchet@43804
  1033
  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
blanchet@48638
  1034
fun mangled_const_name type_enc =
blanchet@48638
  1035
  map_filter (ho_term_for_type_arg type_enc)
blanchet@47220
  1036
  #> raw_mangled_const_name generic_mangled_type_name
blanchet@43413
  1037
blanchet@43413
  1038
val parse_mangled_ident =
blanchet@43413
  1039
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@43413
  1040
blanchet@43413
  1041
fun parse_mangled_type x =
blanchet@43413
  1042
  (parse_mangled_ident
blanchet@43413
  1043
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@49147
  1044
                    [] >> (ATerm o apfst (rpair []))) x
blanchet@43413
  1045
and parse_mangled_types x =
blanchet@43413
  1046
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@43413
  1047
blanchet@43413
  1048
fun unmangled_type s =
blanchet@43413
  1049
  s |> suffix ")" |> raw_explode
blanchet@43413
  1050
    |> Scan.finite Symbol.stopper
blanchet@43413
  1051
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@43413
  1052
                                                quote s)) parse_mangled_type))
blanchet@43413
  1053
    |> fst
blanchet@43413
  1054
blanchet@47220
  1055
fun unmangled_const_name s =
blanchet@47237
  1056
  (s, s) |> unaliased_uncurried |> fst |> space_explode mangled_type_sep
blanchet@43413
  1057
fun unmangled_const s =
blanchet@47220
  1058
  let val ss = unmangled_const_name s in
blanchet@43413
  1059
    (hd ss, map unmangled_type (tl ss))
blanchet@43413
  1060
  end
blanchet@43413
  1061
blanchet@45644
  1062
fun introduce_proxies_in_iterm type_enc =
blanchet@43439
  1063
  let
blanchet@44858
  1064
    fun tweak_ho_quant ho_quant T [IAbs _] = IConst (`I ho_quant, T, [])
blanchet@44858
  1065
      | tweak_ho_quant ho_quant (T as Type (_, [p_T as Type (_, [x_T, _]), _]))
blanchet@44858
  1066
                       _ =
blanchet@44858
  1067
        (* Eta-expand "!!" and "??", to work around LEO-II 1.2.8 parser
blanchet@44858
  1068
           limitation. This works in conjuction with special code in
blanchet@44858
  1069
           "ATP_Problem" that uses the syntactic sugar "!" and "?" whenever
blanchet@44858
  1070
           possible. *)
blanchet@44858
  1071
        IAbs ((`I "P", p_T),
blanchet@44858
  1072
              IApp (IConst (`I ho_quant, T, []),
blanchet@44858
  1073
                    IAbs ((`I "X", x_T),
blanchet@44858
  1074
                          IApp (IConst (`I "P", p_T, []),
blanchet@44858
  1075
                                IConst (`I "X", x_T, [])))))
blanchet@44858
  1076
      | tweak_ho_quant _ _ _ = raise Fail "unexpected type for quantifier"
blanchet@44858
  1077
    fun intro top_level args (IApp (tm1, tm2)) =
blanchet@44858
  1078
        IApp (intro top_level (tm2 :: args) tm1, intro false [] tm2)
blanchet@44858
  1079
      | intro top_level args (IConst (name as (s, _), T, T_args)) =
blanchet@43441
  1080
        (case proxify_const s of
blanchet@44000
  1081
           SOME proxy_base =>
blanchet@44493
  1082
           if top_level orelse is_type_enc_higher_order type_enc then
blanchet@43841
  1083
             case (top_level, s) of
blanchet@44858
  1084
               (_, "c_False") => IConst (`I tptp_false, T, [])
blanchet@44858
  1085
             | (_, "c_True") => IConst (`I tptp_true, T, [])
blanchet@44858
  1086
             | (false, "c_Not") => IConst (`I tptp_not, T, [])
blanchet@44858
  1087
             | (false, "c_conj") => IConst (`I tptp_and, T, [])
blanchet@44858
  1088
             | (false, "c_disj") => IConst (`I tptp_or, T, [])
blanchet@44858
  1089
             | (false, "c_implies") => IConst (`I tptp_implies, T, [])
blanchet@44858
  1090
             | (false, "c_All") => tweak_ho_quant tptp_ho_forall T args
blanchet@44858
  1091
             | (false, "c_Ex") => tweak_ho_quant tptp_ho_exists T args
blanchet@43841
  1092
             | (false, s) =>
blanchet@48926
  1093
               if is_tptp_equal s then
blanchet@48926
  1094
                 if length args = 2 then
blanchet@48926
  1095
                   IConst (`I tptp_equal, T, [])
blanchet@48926
  1096
                 else
blanchet@48926
  1097
                   (* Eta-expand partially applied THF equality, because the
blanchet@48926
  1098
                      LEO-II and Satallax parsers complain about not being able to
blanchet@48926
  1099
                      infer the type of "=". *)
blanchet@48926
  1100
                   let val i_T = domain_type T in
blanchet@48926
  1101
                     IAbs ((`I "Y", i_T),
blanchet@48926
  1102
                           IAbs ((`I "Z", i_T),
blanchet@48926
  1103
                                 IApp (IApp (IConst (`I tptp_equal, T, []),
blanchet@48926
  1104
                                             IConst (`I "Y", i_T, [])),
blanchet@48926
  1105
                                       IConst (`I "Z", i_T, []))))
blanchet@48926
  1106
                   end
blanchet@44968
  1107
               else
blanchet@48926
  1108
                 IConst (name, T, [])
blanchet@44858
  1109
             | _ => IConst (name, T, [])
blanchet@43440
  1110
           else
blanchet@44858
  1111
             IConst (proxy_base |>> prefix const_prefix, T, T_args)
blanchet@46038
  1112
          | NONE => if s = tptp_choice then tweak_ho_quant tptp_choice T args
blanchet@46038
  1113
                    else IConst (name, T, T_args))
blanchet@44858
  1114
      | intro _ _ (IAbs (bound, tm)) = IAbs (bound, intro false [] tm)
blanchet@44858
  1115
      | intro _ _ tm = tm
blanchet@44858
  1116
  in intro true [] end
blanchet@43439
  1117
blanchet@48638
  1118
fun mangle_type_args_in_const type_enc (name as (s, _)) T_args =
blanchet@47220
  1119
  case unprefix_and_unascii const_prefix s of
blanchet@47220
  1120
    NONE => (name, T_args)
blanchet@47220
  1121
  | SOME s'' =>
blanchet@47220
  1122
    case type_arg_policy [] type_enc (invert_const s'') of
blanchet@48638
  1123
      Mangled_Type_Args => (mangled_const_name type_enc T_args name, [])
blanchet@47220
  1124
    | _ => (name, T_args)
blanchet@48638
  1125
fun mangle_type_args_in_iterm type_enc =
blanchet@45645
  1126
  if polymorphism_of_type_enc type_enc = Mangled_Monomorphic then
blanchet@45645
  1127
    let
blanchet@45645
  1128
      fun mangle (IApp (tm1, tm2)) = IApp (mangle tm1, mangle tm2)
blanchet@45645
  1129
        | mangle (tm as IConst (_, _, [])) = tm
blanchet@47220
  1130
        | mangle (IConst (name, T, T_args)) =
blanchet@48638
  1131
          mangle_type_args_in_const type_enc name T_args
blanchet@47220
  1132
          |> (fn (name, T_args) => IConst (name, T, T_args))
blanchet@45645
  1133
        | mangle (IAbs (bound, tm)) = IAbs (bound, mangle tm)
blanchet@45645
  1134
        | mangle tm = tm
blanchet@45645
  1135
    in mangle end
blanchet@45645
  1136
  else
blanchet@45645
  1137
    I
blanchet@45645
  1138
blanchet@45644
  1139
fun chop_fun 0 T = ([], T)
blanchet@45644
  1140
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@45644
  1141
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@45644
  1142
  | chop_fun _ T = ([], T)
blanchet@45644
  1143
blanchet@49103
  1144
fun infer_type_args _ _ _ _ [] = []
blanchet@49103
  1145
  | infer_type_args maybe_not thy s binders_of T_args =
blanchet@45644
  1146
    let
blanchet@45644
  1147
      val U = robust_const_type thy s
blanchet@49103
  1148
      val arg_U_vars = fold Term.add_tvarsT (binders_of U) []
blanchet@49103
  1149
      fun filt (U, T) =
blanchet@49103
  1150
        if maybe_not (member (op =) arg_U_vars (dest_TVar U)) then dummyT else T
blanchet@45644
  1151
      val U_args = (s, U) |> robust_const_typargs thy
blanchet@49103
  1152
    in map filt (U_args ~~ T_args) end
blanchet@45644
  1153
    handle TYPE _ => T_args
blanchet@45644
  1154
blanchet@47220
  1155
fun filter_type_args_in_const _ _ _ _ _ [] = []
blanchet@49103
  1156
  | filter_type_args_in_const thy constrs type_enc ary s T_args =
blanchet@47220
  1157
    case unprefix_and_unascii const_prefix s of
blanchet@47220
  1158
      NONE =>
blanchet@47220
  1159
      if level_of_type_enc type_enc = No_Types orelse s = tptp_choice then []
blanchet@47220
  1160
      else T_args
blanchet@47220
  1161
    | SOME s'' =>
blanchet@49103
  1162
      let val s'' = invert_const s'' in
blanchet@49103
  1163
        case type_arg_policy constrs type_enc s'' of
blanchet@49103
  1164
          Mangled_Type_Args => raise Fail "unexpected (un)mangled symbol"
blanchet@49103
  1165
        | All_Type_Args => T_args
blanchet@49103
  1166
        | Noninferable_Type_Args =>
blanchet@49103
  1167
          infer_type_args I thy s'' (fst o chop_fun ary) T_args
blanchet@49103
  1168
        | Constr_Type_Args => infer_type_args not thy s'' binder_types T_args
blanchet@47220
  1169
        | No_Type_Args => []
blanchet@47220
  1170
      end
blanchet@49103
  1171
fun filter_type_args_in_iterm thy constrs type_enc =
blanchet@38506
  1172
  let
blanchet@45645
  1173
    fun filt ary (IApp (tm1, tm2)) = IApp (filt (ary + 1) tm1, filt 0 tm2)
blanchet@45645
  1174
      | filt ary (IConst (name as (s, _), T, T_args)) =
blanchet@49103
  1175
        filter_type_args_in_const thy constrs type_enc ary s T_args
blanchet@47220
  1176
        |> (fn T_args => IConst (name, T, T_args))
blanchet@45645
  1177
      | filt _ (IAbs (bound, tm)) = IAbs (bound, filt 0 tm)
blanchet@45645
  1178
      | filt _ tm = tm
blanchet@45645
  1179
  in filt 0 end
blanchet@45644
  1180
blanchet@48920
  1181
fun iformula_from_prop ctxt type_enc iff_for_eq =
blanchet@45644
  1182
  let
blanchet@45644
  1183
    val thy = Proof_Context.theory_of ctxt
blanchet@46187
  1184
    fun do_term bs t atomic_Ts =
blanchet@48638
  1185
      iterm_from_term thy type_enc bs (Envir.eta_contract t)
blanchet@45644
  1186
      |>> (introduce_proxies_in_iterm type_enc
blanchet@48638
  1187
           #> mangle_type_args_in_iterm type_enc #> AAtom)
blanchet@46187
  1188
      ||> union (op =) atomic_Ts
blanchet@45262
  1189
    fun do_quant bs q pos s T t' =
blanchet@45262
  1190
      let
blanchet@45262
  1191
        val s = singleton (Name.variant_list (map fst bs)) s
blanchet@45262
  1192
        val universal = Option.map (q = AExists ? not) pos
blanchet@45262
  1193
        val name =
blanchet@45262
  1194
          s |> `(case universal of
blanchet@45262
  1195
                   SOME true => make_all_bound_var
blanchet@45262
  1196
                 | SOME false => make_exist_bound_var
blanchet@45262
  1197
                 | NONE => make_bound_var)
blanchet@45262
  1198
      in
blanchet@45262
  1199
        do_formula ((s, (name, T)) :: bs) pos t'
blanchet@45262
  1200
        #>> mk_aquant q [(name, SOME T)]
blanchet@46187
  1201
        ##> union (op =) (atomic_types_of T)
blanchet@38743
  1202
      end
blanchet@45262
  1203
    and do_conn bs c pos1 t1 pos2 t2 =
blanchet@45262
  1204
      do_formula bs pos1 t1 ##>> do_formula bs pos2 t2 #>> uncurry (mk_aconn c)
blanchet@45262
  1205
    and do_formula bs pos t =
blanchet@38506
  1206
      case t of
blanchet@45262
  1207
        @{const Trueprop} $ t1 => do_formula bs pos t1
blanchet@45262
  1208
      | @{const Not} $ t1 => do_formula bs (Option.map not pos) t1 #>> mk_anot
blanchet@38506
  1209
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@45262
  1210
        do_quant bs AForall pos s T t'
blanchet@46038
  1211
      | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@46038
  1212
        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
blanchet@38506
  1213
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@45262
  1214
        do_quant bs AExists pos s T t'
blanchet@46038
  1215
      | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@46038
  1216
        do_formula bs pos (t0 $ eta_expand (map (snd o snd) bs) t1 1)
blanchet@45262
  1217
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd pos t1 pos t2
blanchet@45262
  1218
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr pos t1 pos t2
blanchet@45262
  1219
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@45262
  1220
        do_conn bs AImplies (Option.map not pos) t1 pos t2
haftmann@39093
  1221
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@48920
  1222
        if iff_for_eq then do_conn bs AIff NONE t1 NONE t2 else do_term bs t
blanchet@41388
  1223
      | _ => do_term bs t
blanchet@38506
  1224
  in do_formula [] end
blanchet@38506
  1225
blanchet@48022
  1226
fun presimplify_term thy t =
blanchet@48022
  1227
  if exists_Const (member (op =) Meson.presimplified_consts o fst) t then
blanchet@48022
  1228
    t |> Skip_Proof.make_thm thy
blanchet@48022
  1229
      |> Meson.presimplify
blanchet@48022
  1230
      |> prop_of
blanchet@48022
  1231
  else
blanchet@48022
  1232
    t
blanchet@38506
  1233
blanchet@46385
  1234
fun preprocess_abstractions_in_terms trans_lams facts =
blanchet@44733
  1235
  let
blanchet@44734
  1236
    val (facts, lambda_ts) =
blanchet@46385
  1237
      facts |> map (snd o snd) |> trans_lams
blanchet@48990
  1238
            |>> map2 (fn (name, (role, _)) => fn t => (name, (role, t))) facts
blanchet@46425
  1239
    val lam_facts =
blanchet@44734
  1240
      map2 (fn t => fn j =>
blanchet@48019
  1241
               ((lam_fact_prefix ^ Int.toString j, (Global, Def)), (Axiom, t)))
blanchet@44734
  1242
           lambda_ts (1 upto length lambda_ts)
blanchet@46425
  1243
  in (facts, lam_facts) end
blanchet@38506
  1244
blanchet@38506
  1245
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@43224
  1246
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38506
  1247
fun freeze_term t =
blanchet@38506
  1248
  let
blanchet@45676
  1249
    fun freeze (t $ u) = freeze t $ freeze u
blanchet@45676
  1250
      | freeze (Abs (s, T, t)) = Abs (s, T, freeze t)
blanchet@45676
  1251
      | freeze (Var ((s, i), T)) =
blanchet@44734
  1252
        Free (atp_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@45676
  1253
      | freeze t = t
blanchet@45676
  1254
  in t |> exists_subterm is_Var t ? freeze end
blanchet@38506
  1255
blanchet@48639
  1256
fun presimp_prop ctxt type_enc t =
blanchet@48584
  1257
  let
blanchet@48584
  1258
    val thy = Proof_Context.theory_of ctxt
blanchet@48584
  1259
    val t = t |> Envir.beta_eta_contract
blanchet@48584
  1260
              |> transform_elim_prop
blanchet@48584
  1261
              |> Object_Logic.atomize_term thy
blanchet@48584
  1262
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@48928
  1263
    val is_ho = is_type_enc_higher_order type_enc
blanchet@48584
  1264
  in
blanchet@48584
  1265
    t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@48969
  1266
      |> (if is_ho then unextensionalize_def
blanchet@48969
  1267
          else cong_extensionalize_term thy #> abs_extensionalize_term ctxt)
blanchet@48584
  1268
      |> presimplify_term thy
blanchet@48584
  1269
      |> HOLogic.dest_Trueprop
blanchet@48584
  1270
  end
blanchet@48584
  1271
  handle TERM _ => @{const True}
blanchet@43937
  1272
blanchet@48920
  1273
(* Satallax prefers "=" to "<=>" (for definitions) and Metis (CNF) requires "="
blanchet@48920
  1274
   for obscure technical reasons. *)
blanchet@48920
  1275
fun should_use_iff_for_eq CNF _ = false
blanchet@48920
  1276
  | should_use_iff_for_eq (THF _) format = not (is_type_enc_higher_order format)
blanchet@48920
  1277
  | should_use_iff_for_eq _ _ = true
blanchet@48920
  1278
blanchet@48990
  1279
fun make_formula ctxt format type_enc iff_for_eq name stature role t =
blanchet@43937
  1280
  let
blanchet@48920
  1281
    val iff_for_eq = iff_for_eq andalso should_use_iff_for_eq format type_enc
blanchet@46187
  1282
    val (iformula, atomic_Ts) =
blanchet@48990
  1283
      iformula_from_prop ctxt type_enc iff_for_eq (SOME (role <> Conjecture)) t
blanchet@48638
  1284
                         []
blanchet@46187
  1285
      |>> close_iformula_universally
blanchet@38506
  1286
  in
blanchet@48990
  1287
    {name = name, stature = stature, role = role, iformula = iformula,
blanchet@46187
  1288
     atomic_types = atomic_Ts}
blanchet@38506
  1289
  end
blanchet@38506
  1290
blanchet@49019
  1291
fun is_format_with_defs (THF (_, _, _, THF_With_Defs)) = true
blanchet@49019
  1292
  | is_format_with_defs _ = false
blanchet@49019
  1293
blanchet@48986
  1294
fun make_fact ctxt format type_enc iff_for_eq
blanchet@48986
  1295
              ((name, stature as (_, status)), t) =
blanchet@48986
  1296
  let
blanchet@48986
  1297
    val role =
blanchet@49019
  1298
      if is_format_with_defs format andalso status = Def andalso
blanchet@49006
  1299
         is_legitimate_tptp_def t then
blanchet@48986
  1300
        Definition
blanchet@48986
  1301
      else
blanchet@48986
  1302
        Axiom
blanchet@48986
  1303
  in
blanchet@48986
  1304
    case t |> make_formula ctxt format type_enc iff_for_eq name stature role of
blanchet@48986
  1305
      formula as {iformula = AAtom (IConst ((s, _), _, _)), ...} =>
blanchet@48986
  1306
      if s = tptp_true then NONE else SOME formula
blanchet@48986
  1307
    | formula => SOME formula
blanchet@48986
  1308
  end
blanchet@43432
  1309
blanchet@48584
  1310
fun s_not_prop (@{const Trueprop} $ t) = @{const Trueprop} $ s_not t
blanchet@48584
  1311
  | s_not_prop (@{const "==>"} $ t $ @{prop False}) = t
blanchet@48584
  1312
  | s_not_prop t = @{const "==>"} $ t $ @{prop False}
blanchet@45317
  1313
blanchet@45644
  1314
fun make_conjecture ctxt format type_enc =
blanchet@48990
  1315
  map (fn ((name, stature), (role, t)) =>
blanchet@48996
  1316
          let
blanchet@49094
  1317
            (* FIXME: The commented-out code is a hack to get decent performance
blanchet@49094
  1318
               out of LEO-II on the TPTP THF benchmarks. *)
blanchet@48996
  1319
            val role =
blanchet@49094
  1320
              if (* is_format_with_defs format andalso *)
blanchet@49006
  1321
                 role <> Conjecture andalso is_legitimate_tptp_def t then
blanchet@48996
  1322
                Definition
blanchet@48996
  1323
              else
blanchet@48996
  1324
                role
blanchet@48996
  1325
          in
blanchet@48996
  1326
            t |> role = Conjecture ? s_not
blanchet@48996
  1327
              |> make_formula ctxt format type_enc true name stature role
blanchet@48996
  1328
          end)
blanchet@38506
  1329
blanchet@43552
  1330
(** Finite and infinite type inference **)
blanchet@43552
  1331
blanchet@45676
  1332
fun tvar_footprint thy s ary =
blanchet@46382
  1333
  (case unprefix_and_unascii const_prefix s of
blanchet@45676
  1334
     SOME s =>
blanchet@45676
  1335
     s |> invert_const |> robust_const_type thy |> chop_fun ary |> fst
blanchet@45676
  1336
       |> map (fn T => Term.add_tvarsT T [] |> map fst)
blanchet@45676
  1337
   | NONE => [])
blanchet@45676
  1338
  handle TYPE _ => []
blanchet@45676
  1339
blanchet@49095
  1340
fun type_arg_cover thy s ary =
blanchet@46819
  1341
  if is_tptp_equal s then
blanchet@46819
  1342
    0 upto ary - 1
blanchet@46819
  1343
  else
blanchet@46819
  1344
    let
blanchet@46819
  1345
      val footprint = tvar_footprint thy s ary
blanchet@46819
  1346
      val eq = (s = @{const_name HOL.eq})
blanchet@49095
  1347
      fun cover _ [] = []
blanchet@49095
  1348
        | cover seen ((i, tvars) :: args) =
blanchet@49095
  1349
          cover (union (op =) seen tvars) args
blanchet@46819
  1350
          |> (eq orelse exists (fn tvar => not (member (op =) seen tvar)) tvars)
blanchet@46819
  1351
             ? cons i
blanchet@46819
  1352
    in
blanchet@46819
  1353
      if forall null footprint then
blanchet@46819
  1354
        []
blanchet@46819
  1355
      else
blanchet@46819
  1356
        0 upto length footprint - 1 ~~ footprint
blanchet@46819
  1357
        |> sort (rev_order o list_ord Term_Ord.indexname_ord o pairself snd)
blanchet@49095
  1358
        |> cover []
blanchet@46819
  1359
    end
blanchet@45676
  1360
blanchet@45258
  1361
type monotonicity_info =
blanchet@45258
  1362
  {maybe_finite_Ts : typ list,
blanchet@45258
  1363
   surely_infinite_Ts : typ list,
blanchet@45258
  1364
   maybe_nonmono_Ts : typ list}
blanchet@45258
  1365
blanchet@45256
  1366
(* These types witness that the type classes they belong to allow infinite
blanchet@45256
  1367
   models and hence that any types with these type classes is monotonic. *)
blanchet@45256
  1368
val known_infinite_types =
blanchet@45492
  1369
  [@{typ nat}, HOLogic.intT, HOLogic.realT, @{typ "nat => bool"}]
blanchet@45256
  1370
blanchet@47129
  1371
fun is_type_kind_of_surely_infinite ctxt strictness cached_Ts T =
blanchet@47129
  1372
  strictness <> Strict andalso is_type_surely_infinite ctxt true cached_Ts T
blanchet@43755
  1373
blanchet@43552
  1374
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@43552
  1375
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@43552
  1376
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@43552
  1377
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@43552
  1378
blanchet@45258
  1379
fun should_encode_type _ (_ : monotonicity_info) All_Types _ = true
blanchet@45258
  1380
  | should_encode_type ctxt {maybe_finite_Ts, surely_infinite_Ts,
blanchet@45258
  1381
                             maybe_nonmono_Ts, ...}
blanchet@49107
  1382
                       (Nonmono_Types (strictness, grain)) T =
blanchet@48021
  1383
    let val thy = Proof_Context.theory_of ctxt in
blanchet@49110
  1384
      grain = Undercover_Vars orelse
blanchet@48021
  1385
      (exists (type_intersect thy T) maybe_nonmono_Ts andalso
blanchet@48021
  1386
       not (exists (type_instance thy T) surely_infinite_Ts orelse
blanchet@48021
  1387
            (not (member (type_equiv thy) maybe_finite_Ts T) andalso
blanchet@48021
  1388
             is_type_kind_of_surely_infinite ctxt strictness surely_infinite_Ts
blanchet@48021
  1389
                                             T)))
blanchet@48021
  1390
    end
blanchet@43552
  1391
  | should_encode_type _ _ _ _ = false
blanchet@43552
  1392
blanchet@45639
  1393
fun should_guard_type ctxt mono (Guards (_, level)) should_guard_var T =
blanchet@45673
  1394
    should_guard_var () andalso should_encode_type ctxt mono level T
blanchet@45258
  1395
  | should_guard_type _ _ _ _ _ = false
blanchet@43552
  1396
blanchet@45262
  1397
fun is_maybe_universal_var (IConst ((s, _), _, _)) =
blanchet@45262
  1398
    String.isPrefix bound_var_prefix s orelse
blanchet@45262
  1399
    String.isPrefix all_bound_var_prefix s
blanchet@45262
  1400
  | is_maybe_universal_var (IVar _) = true
blanchet@45262
  1401
  | is_maybe_universal_var _ = false
blanchet@43707
  1402
blanchet@46818
  1403
datatype site =
blanchet@44232
  1404
  Top_Level of bool option |
blanchet@44232
  1405
  Eq_Arg of bool option |
blanchet@44232
  1406
  Elsewhere
blanchet@43700
  1407
blanchet@46820
  1408
fun should_tag_with_type _ _ _ (Top_Level _) _ _ = false
blanchet@46820
  1409
  | should_tag_with_type ctxt mono (Tags (_, level)) site u T =
blanchet@46820
  1410
    if granularity_of_type_level level = All_Vars then
blanchet@46820
  1411
      should_encode_type ctxt mono level T
blanchet@46820
  1412
    else
blanchet@46820
  1413
      (case (site, is_maybe_universal_var u) of
blanchet@46820
  1414
         (Eq_Arg _, true) => should_encode_type ctxt mono level T
blanchet@45676
  1415
       | _ => false)
blanchet@46820
  1416
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@43552
  1417
blanchet@45458
  1418
fun fused_type ctxt mono level =
blanchet@43835
  1419
  let
blanchet@45258
  1420
    val should_encode = should_encode_type ctxt mono level
blanchet@45458
  1421
    fun fuse 0 T = if should_encode T then T else fused_infinite_type
blanchet@45458
  1422
      | fuse ary (Type (@{type_name fun}, [T1, T2])) =
blanchet@45458
  1423
        fuse 0 T1 --> fuse (ary - 1) T2
blanchet@45458
  1424
      | fuse _ _ = raise Fail "expected function type"
blanchet@45458
  1425
  in fuse end
blanchet@43552
  1426
blanchet@45307
  1427
(** predicators and application operators **)
blanchet@41561
  1428
blanchet@43445
  1429
type sym_info =
blanchet@45700
  1430
  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list,
blanchet@45700
  1431
   in_conj : bool}
blanchet@43434
  1432
blanchet@45700
  1433
fun default_sym_tab_entries type_enc =
blanchet@45700
  1434
  (make_fixed_const NONE @{const_name undefined},
blanchet@45700
  1435
       {pred_sym = false, min_ary = 0, max_ary = 0, types = [],
blanchet@45700
  1436
        in_conj = false}) ::
blanchet@45700
  1437
  ([tptp_false, tptp_true]
blanchet@45700
  1438
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = [],
blanchet@45700
  1439
                  in_conj = false})) @
blanchet@45700
  1440
  ([tptp_equal, tptp_old_equal]
blanchet@45700
  1441
   |> map (rpair {pred_sym = true, min_ary = 2, max_ary = 2, types = [],
blanchet@45700
  1442
                  in_conj = false}))
blanchet@45700
  1443
  |> not (is_type_enc_higher_order type_enc)
blanchet@45700
  1444
     ? cons (prefixed_predicator_name,
blanchet@45700
  1445
             {pred_sym = true, min_ary = 1, max_ary = 1, types = [],
blanchet@45700
  1446
              in_conj = false})
blanchet@45700
  1447
blanchet@47933
  1448
datatype app_op_level =
blanchet@47933
  1449
  Min_App_Op |
blanchet@47933
  1450
  Sufficient_App_Op |
blanchet@47933
  1451
  Sufficient_App_Op_And_Predicator |
blanchet@47933
  1452
  Full_App_Op_And_Predicator
blanchet@47217
  1453
blanchet@48947
  1454
fun add_iterm_syms_to_sym_table ctxt app_op_level conj_fact =
blanchet@43429
  1455
  let
blanchet@47513
  1456
    val thy = Proof_Context.theory_of ctxt
blanchet@45643
  1457
    fun consider_var_ary const_T var_T max_ary =
blanchet@43905
  1458
      let
blanchet@43905
  1459
        fun iter ary T =
blanchet@48021
  1460
          if ary = max_ary orelse type_instance thy var_T T orelse
blanchet@48021
  1461
             type_instance thy T var_T then
blanchet@44051
  1462
            ary
blanchet@44051
  1463
          else
blanchet@44051
  1464
            iter (ary + 1) (range_type T)
blanchet@43905
  1465
      in iter 0 const_T end
blanchet@45262
  1466
    fun add_universal_var T (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@47933
  1467
      if (app_op_level = Sufficient_App_Op andalso can dest_funT T) orelse
blanchet@47933
  1468
         (app_op_level = Sufficient_App_Op_And_Predicator andalso
blanchet@47933
  1469
          (can dest_funT T orelse T = @{typ bool})) then
blanchet@44042
  1470
        let
blanchet@47933
  1471
          val bool_vars' =
blanchet@47933
  1472
            bool_vars orelse
blanchet@47933
  1473
            (app_op_level = Sufficient_App_Op_And_Predicator andalso
blanchet@47933
  1474
             body_type T = @{typ bool})
blanchet@45700
  1475
          fun repair_min_ary {pred_sym, min_ary, max_ary, types, in_conj} =
blanchet@44042
  1476
            {pred_sym = pred_sym andalso not bool_vars',
blanchet@45643
  1477
             min_ary = fold (fn T' => consider_var_ary T' T) types min_ary,
blanchet@45700
  1478
             max_ary = max_ary, types = types, in_conj = in_conj}
blanchet@44042
  1479
          val fun_var_Ts' =
blanchet@48021
  1480
            fun_var_Ts |> can dest_funT T ? insert_type thy I T
blanchet@44042
  1481
        in
blanchet@44042
  1482
          if bool_vars' = bool_vars andalso
blanchet@44042
  1483
             pointer_eq (fun_var_Ts', fun_var_Ts) then
blanchet@44042
  1484
            accum
blanchet@44008
  1485
          else
blanchet@45643
  1486
            ((bool_vars', fun_var_Ts'), Symtab.map (K repair_min_ary) sym_tab)
blanchet@44042
  1487
        end
blanchet@44042
  1488
      else
blanchet@44042
  1489
        accum
blanchet@48947
  1490
    fun add_iterm_syms top_level tm
blanchet@48947
  1491
                       (accum as ((bool_vars, fun_var_Ts), sym_tab)) =
blanchet@48947
  1492
      let val (head, args) = strip_iterm_comb tm in
blanchet@48947
  1493
        (case head of
blanchet@48947
  1494
           IConst ((s, _), T, _) =>
blanchet@48947
  1495
           if String.isPrefix bound_var_prefix s orelse
blanchet@48947
  1496
              String.isPrefix all_bound_var_prefix s then
blanchet@48947
  1497
             add_universal_var T accum
blanchet@48947
  1498
           else if String.isPrefix exist_bound_var_prefix s then
blanchet@48947
  1499
             accum
blanchet@48947
  1500
           else
blanchet@48947
  1501
             let val ary = length args in
blanchet@48947
  1502
               ((bool_vars, fun_var_Ts),
blanchet@48947
  1503
                case Symtab.lookup sym_tab s of
blanchet@48947
  1504
                  SOME {pred_sym, min_ary, max_ary, types, in_conj} =>
blanchet@48947
  1505
                  let
blanchet@48947
  1506
                    val pred_sym =
blanchet@48947
  1507
                      pred_sym andalso top_level andalso not bool_vars
blanchet@48947
  1508
                    val types' = types |> insert_type thy I T
blanchet@48947
  1509
                    val in_conj = in_conj orelse conj_fact
blanchet@48947
  1510
                    val min_ary =
blanchet@48947
  1511
                      if (app_op_level = Sufficient_App_Op orelse
blanchet@48947
  1512
                          app_op_level = Sufficient_App_Op_And_Predicator)
blanchet@48947
  1513
                         andalso not (pointer_eq (types', types)) then
blanchet@48947
  1514
                        fold (consider_var_ary T) fun_var_Ts min_ary
blanchet@48947
  1515
                      else
blanchet@48947
  1516
                        min_ary
blanchet@48947
  1517
                  in
blanchet@48947
  1518
                    Symtab.update (s, {pred_sym = pred_sym,
blanchet@48947
  1519
                                       min_ary = Int.min (ary, min_ary),
blanchet@48947
  1520
                                       max_ary = Int.max (ary, max_ary),
blanchet@48947
  1521
                                       types = types', in_conj = in_conj})
blanchet@48947
  1522
                                  sym_tab
blanchet@48947
  1523
                  end
blanchet@48947
  1524
                | NONE =>
blanchet@48947
  1525
                  let
blanchet@48947
  1526
                    val pred_sym = top_level andalso not bool_vars
blanchet@48947
  1527
                    val ary =
blanchet@48947
  1528
                      case unprefix_and_unascii const_prefix s of
blanchet@48947
  1529
                        SOME s =>
blanchet@48947
  1530
                        (if String.isSubstring uncurried_alias_sep s then
blanchet@48947
  1531
                           ary
blanchet@48947
  1532
                         else case try (robust_const_ary thy
blanchet@48947
  1533
                                        o invert_const o hd
blanchet@48947
  1534
                                        o unmangled_const_name) s of
blanchet@48947
  1535
                           SOME ary0 => Int.min (ary0, ary)
blanchet@48947
  1536
                         | NONE => ary)
blanchet@48947
  1537
                      | NONE => ary
blanchet@48947
  1538
                    val min_ary =
blanchet@48947
  1539
                      case app_op_level of
blanchet@48947
  1540
                        Min_App_Op => ary
blanchet@48947
  1541
                      | Full_App_Op_And_Predicator => 0
blanchet@48947
  1542
                      | _ => fold (consider_var_ary T) fun_var_Ts ary
blanchet@48947
  1543
                  in
blanchet@48947
  1544
                    Symtab.update_new (s,
blanchet@48947
  1545
                        {pred_sym = pred_sym, min_ary = min_ary,
blanchet@48947
  1546
                         max_ary = ary, types = [T], in_conj = conj_fact})
blanchet@48947
  1547
                        sym_tab
blanchet@48947
  1548
                  end)
blanchet@48947
  1549
             end
blanchet@48947
  1550
         | IVar (_, T) => add_universal_var T accum
blanchet@48947
  1551
         | IAbs ((_, T), tm) =>
blanchet@48947
  1552
           accum |> add_universal_var T |> add_iterm_syms false tm
blanchet@48947
  1553
         | _ => accum)
blanchet@48947
  1554
        |> fold (add_iterm_syms false) args
blanchet@48947
  1555
      end
blanchet@48947
  1556
  in add_iterm_syms end
blanchet@48947
  1557
blanchet@48947
  1558
fun sym_table_for_facts ctxt type_enc app_op_level conjs facts =
blanchet@48947
  1559
  let
blanchet@48947
  1560
    fun add_iterm_syms conj_fact =
blanchet@48947
  1561
      add_iterm_syms_to_sym_table ctxt app_op_level conj_fact true
blanchet@45700
  1562
    fun add_fact_syms conj_fact =
blanchet@48996
  1563
      K (add_iterm_syms conj_fact) |> formula_fold NONE |> ifact_lift
blanchet@45700
  1564
  in
blanchet@45700
  1565
    ((false, []), Symtab.empty)
blanchet@45700
  1566
    |> fold (add_fact_syms true) conjs
blanchet@45700
  1567
    |> fold (add_fact_syms false) facts
blanchet@48947
  1568
    ||> fold Symtab.update (default_sym_tab_entries type_enc)
blanchet@45700
  1569
  end
blanchet@38506
  1570
blanchet@45643
  1571
fun min_ary_of sym_tab s =
blanchet@43429
  1572
  case Symtab.lookup sym_tab s of
blanchet@43445
  1573
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@43429
  1574
  | NONE =>
blanchet@46382
  1575
    case unprefix_and_unascii const_prefix s of
blanchet@43418
  1576
      SOME s =>
blanchet@47220
  1577
      let val s = s |> unmangled_const_name |> hd |> invert_const in
blanchet@43807
  1578
        if s = predicator_name then 1
blanchet@43807
  1579
        else if s = app_op_name then 2
blanchet@45255
  1580
        else if s = type_guard_name then 1
blanchet@43428
  1581
        else 0
blanchet@43418
  1582
      end
blanchet@38506
  1583
    | NONE => 0
blanchet@38506
  1584
blanchet@38506
  1585
(* True if the constant ever appears outside of the top-level position in
blanchet@38506
  1586
   literals, or if it appears with different arities (e.g., because of different
blanchet@38506
  1587
   type instantiations). If false, the constant always receives all of its
blanchet@38506
  1588
   arguments and is used as a predicate. *)
blanchet@43429
  1589
fun is_pred_sym sym_tab s =
blanchet@43429
  1590
  case Symtab.lookup sym_tab s of
blanchet@43445
  1591
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@43445
  1592
    pred_sym andalso min_ary = max_ary
blanchet@43429
  1593
  | NONE => false
blanchet@38506
  1594
blanchet@48961
  1595
val fTrue_iconst =
blanchet@48961
  1596
  IConst ((const_prefix ^ "fTrue", @{const_name ATP.fTrue}), @{typ bool}, [])
blanchet@48961
  1597
val predicator_iconst =
nik@45350
  1598
  IConst (`(make_fixed_const NONE) predicator_name, @{typ "bool => bool"}, [])
blanchet@45644
  1599
blanchet@48961
  1600
fun predicatify aggressive tm =
blanchet@48961
  1601
  if aggressive then
blanchet@48961
  1602
    IApp (IApp (IConst (`I tptp_equal, @{typ "bool => bool => bool"}, []), tm),
blanchet@48961
  1603
          fTrue_iconst)
blanchet@48961
  1604
  else
blanchet@48961
  1605
    IApp (predicator_iconst, tm)
blanchet@48961
  1606
blanchet@48961
  1607
val app_op = `(make_fixed_const NONE) app_op_name
blanchet@48961
  1608
blanchet@45644
  1609
fun list_app head args = fold (curry (IApp o swap)) args head
blanchet@38506
  1610
blanchet@48638
  1611
fun mk_app_op type_enc head arg =
blanchet@43415
  1612
  let
blanchet@47220
  1613
    val head_T = ityp_of head
blanchet@47220
  1614
    val (arg_T, res_T) = dest_funT head_T
blanchet@47220
  1615
    val app =
blanchet@47220
  1616
      IConst (app_op, head_T --> head_T, [arg_T, res_T])
blanchet@48638
  1617
      |> mangle_type_args_in_iterm type_enc
blanchet@47220
  1618
  in list_app app [head, arg] end
blanchet@47220
  1619
blanchet@49103
  1620
fun firstorderize_fact thy constrs type_enc sym_tab uncurried_aliases
blanchet@48961
  1621
                       aggressive =
blanchet@47220
  1622
  let
blanchet@48638
  1623
    fun do_app arg head = mk_app_op type_enc head arg
blanchet@45644
  1624
    fun list_app_ops head args = fold do_app args head
blanchet@45644
  1625
    fun introduce_app_ops tm =
blanchet@47220
  1626
      let val (head, args) = tm |> strip_iterm_comb ||> map introduce_app_ops in
blanchet@47220
  1627
        case head of
blanchet@47220
  1628
          IConst (name as (s, _), T, T_args) =>
blanchet@47237
  1629
          if uncurried_aliases andalso String.isPrefix const_prefix s then
blanchet@47220
  1630
            let
blanchet@47220
  1631
              val ary = length args
blanchet@47510
  1632
              val name =
blanchet@47510
  1633
                name |> ary > min_ary_of sym_tab s ? aliased_uncurried ary
blanchet@47220
  1634
            in list_app (IConst (name, T, T_args)) args end
blanchet@47220
  1635
          else
blanchet@47220
  1636
            args |> chop (min_ary_of sym_tab s)
blanchet@47220
  1637
                 |>> list_app head |-> list_app_ops
blanchet@47220
  1638
        | _ => list_app_ops head args
blanchet@47220
  1639
      end
blanchet@45644
  1640
    fun introduce_predicators tm =
blanchet@45644
  1641
      case strip_iterm_comb tm of
blanchet@45644
  1642
        (IConst ((s, _), _, _), _) =>
blanchet@48961
  1643
        if is_pred_sym sym_tab s then tm else predicatify aggressive tm
blanchet@48961
  1644
      | _ => predicatify aggressive tm
blanchet@45644
  1645
    val do_iterm =
blanchet@45644
  1646
      not (is_type_enc_higher_order type_enc)
blanchet@45644
  1647
      ? (introduce_app_ops #> introduce_predicators)
blanchet@49103
  1648
      #> filter_type_args_in_iterm thy constrs type_enc
blanchet@45644
  1649
  in update_iformula (formula_map do_iterm) end
blanchet@43444
  1650
blanchet@43444
  1651
(** Helper facts **)
blanchet@43444
  1652
blanchet@45307
  1653
val not_ffalse = @{lemma "~ fFalse" by (unfold fFalse_def) fast}
blanchet@45307
  1654
val ftrue = @{lemma "fTrue" by (unfold fTrue_def) fast}
blanchet@45307
  1655
blanchet@44035
  1656
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@48961
  1657
val base_helper_table =
blanchet@48961
  1658
  [(("COMBI", false), [(Def, @{thm Meson.COMBI_def})]),
blanchet@48961
  1659
   (("COMBK", false), [(Def, @{thm Meson.COMBK_def})]),
blanchet@48961
  1660
   (("COMBB", false), [(Def, @{thm Meson.COMBB_def})]),
blanchet@48961
  1661
   (("COMBC", false), [(Def, @{thm Meson.COMBC_def})]),
blanchet@48961
  1662
   (("COMBS", false), [(Def, @{thm Meson.COMBS_def})]),
blanchet@48961
  1663
   ((predicator_name, false), [(General, not_ffalse), (General, ftrue)]),
blanchet@48961
  1664
   (("fFalse", false), [(General, not_ffalse)]),
blanchet@48961
  1665
   (("fFalse", true), [(General, @{thm True_or_False})]),
blanchet@48961
  1666
   (("fTrue", false), [(General, ftrue)]),
blanchet@48961
  1667
   (("fTrue", true), [(General, @{thm True_or_False})]),
blanchet@48961
  1668
   (("If", true),
blanchet@48961
  1669
    [(Def, @{thm if_True}), (Def, @{thm if_False}),
blanchet@48961
  1670
     (General, @{thm True_or_False})])]
blanchet@48961
  1671
blanchet@43926
  1672
val helper_table =
blanchet@48961
  1673
  base_helper_table @
blanchet@48961
  1674
  [(("fNot", false),
blanchet@44035
  1675
    @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@48961
  1676
           fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]}
blanchet@48961
  1677
    |> map (pair Def)),
blanchet@44035
  1678
   (("fconj", false),
blanchet@44035
  1679
    @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@48961
  1680
        by (unfold fconj_def) fast+}
blanchet@48961
  1681
    |> map (pair General)),
blanchet@44035
  1682
   (("fdisj", false),
blanchet@44035
  1683
    @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@48961
  1684
        by (unfold fdisj_def) fast+}
blanchet@48961
  1685
    |> map (pair General)),
blanchet@44035
  1686
   (("fimplies", false),
blanchet@44051
  1687
    @{lemma "P | fimplies P Q" "~ Q | fimplies P Q" "~ fimplies P Q | ~ P | Q"
blanchet@48961
  1688
        by (unfold fimplies_def) fast+}
blanchet@48961
  1689
    |> map (pair General)),
nik@44537
  1690
   (("fequal", true),
nik@44537
  1691
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
nik@44537
  1692
       However, this is done so for backward compatibility: Including the
nik@44537
  1693
       equality helpers by default in Metis breaks a few existing proofs. *)
nik@44537
  1694
    @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@48961
  1695
           fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]}
blanchet@48961
  1696
    |> map (pair General)),
blanchet@44874
  1697
   (* Partial characterization of "fAll" and "fEx". A complete characterization
blanchet@44874
  1698
      would require the axiom of choice for replay with Metis. *)
blanchet@48961
  1699
   (("fAll", false),
blanchet@48961
  1700
    [(General, @{lemma "~ fAll P | P x" by (auto simp: fAll_def)})]),
blanchet@48961
  1701
   (("fEx", false),
blanchet@48961
  1702
    [(General, @{lemma "~ P x | fEx P" by (auto simp: fEx_def)})])]
blanchet@48961
  1703
  |> map (apsnd (map (apsnd zero_var_indexes)))
blanchet@48961
  1704
blanchet@48961
  1705
val aggressive_helper_table =
blanchet@48961
  1706
  base_helper_table @
blanchet@48961
  1707
  [((predicator_name, true),
blanchet@48961
  1708
    @{thms True_or_False fTrue_ne_fFalse} |> map (pair General)),
blanchet@48961
  1709
   ((app_op_name, true),
blanchet@48961
  1710
    [(General, @{lemma "EX x. ~ f x = g x | f = g" by blast})]),
blanchet@48961
  1711
   (("fconj", false),
blanchet@48961
  1712
    @{thms fconj_table fconj_laws fdisj_laws} |> map (pair Def)),
blanchet@48961
  1713
   (("fdisj", false),
blanchet@48961
  1714
    @{thms fdisj_table fconj_laws fdisj_laws} |> map (pair Def)),
blanchet@48961
  1715
   (("fimplies", false),
blanchet@48961
  1716
    @{thms fimplies_table fconj_laws fdisj_laws fimplies_laws}
blanchet@48961
  1717
    |> map (pair Def)),
blanchet@48961
  1718
   (("fequal", false),
blanchet@48961
  1719
    (@{thms fequal_table} |> map (pair Def)) @
blanchet@48961
  1720
    (@{thms fequal_laws} |> map (pair General))),
blanchet@48961
  1721
   (("fAll", false),
blanchet@48961
  1722
    @{thms fAll_table fComp_law fAll_law fEx_law} |> map (pair Def)),
blanchet@48961
  1723
   (("fEx", false),
blanchet@48961
  1724
    @{thms fEx_table fComp_law fAll_law fEx_law} |> map (pair Def))]
blanchet@48961
  1725
  |> map (apsnd (map (apsnd zero_var_indexes)))
blanchet@43926
  1726
blanchet@46791
  1727
fun bound_tvars type_enc sorts Ts =
blanchet@49148
  1728
  case filter is_TVar Ts of
blanchet@49148
  1729
    [] => I
blanchet@49148
  1730
  | Ts =>
blanchet@49148
  1731
    (sorts ? mk_ahorn (formulas_for_types type_enc add_sorts_on_tvar Ts))
blanchet@49148
  1732
    #> (if is_type_enc_native type_enc then
blanchet@49148
  1733
          mk_atyquant AForall
blanchet@49148
  1734
                      (map (fn TVar (x, _) => AType (tvar_name x, [])) Ts)
blanchet@49148
  1735
        else
blanchet@49148
  1736
          mk_aquant AForall (map (fn TVar (x, _) => (tvar_name x, NONE)) Ts))
blanchet@45263
  1737
blanchet@47220
  1738
fun eq_formula type_enc atomic_Ts bounds pred_sym tm1 tm2 =
blanchet@45263
  1739
  (if pred_sym then AConn (AIff, [AAtom tm1, AAtom tm2])
blanchet@49147
  1740
   else AAtom (ATerm ((`I tptp_equal, []), [tm1, tm2])))
blanchet@47220
  1741
  |> mk_aquant AForall bounds
blanchet@46248
  1742
  |> close_formula_universally
blanchet@46791
  1743
  |> bound_tvars type_enc true atomic_Ts
blanchet@45263
  1744
blanchet@47234
  1745
val helper_rank = default_rank
blanchet@47234
  1746
val min_rank = 9 * helper_rank div 10
blanchet@47234
  1747
val max_rank = 4 * min_rank
blanchet@47234
  1748
blanchet@47234
  1749
fun rank_of_fact_num n j = min_rank + (max_rank - min_rank) * j div n
blanchet@47234
  1750
nik@45350
  1751
val type_tag = `(make_fixed_const NONE) type_tag_name
blanchet@43971
  1752
blanchet@48961
  1753
fun could_specialize_helpers type_enc =
blanchet@49146
  1754
  not (is_type_enc_polymorphic type_enc) andalso
blanchet@48961
  1755
  level_of_type_enc type_enc <> No_Types
blanchet@44493
  1756
fun should_specialize_helper type_enc t =
blanchet@48961
  1757
  could_specialize_helpers type_enc andalso
blanchet@44495
  1758
  not (null (Term.hidden_polymorphism t))
blanchet@44000
  1759
blanchet@48961
  1760
fun add_helper_facts_for_sym ctxt format type_enc aggressive
blanchet@48961
  1761
                             (s, {types, ...} : sym_info) =
blanchet@46382
  1762
  case unprefix_and_unascii const_prefix s of
blanchet@43444
  1763
    SOME mangled_s =>
blanchet@43444
  1764
    let
blanchet@43444
  1765
      val thy = Proof_Context.theory_of ctxt
blanchet@47220
  1766
      val unmangled_s = mangled_s |> unmangled_const_name |> hd
blanchet@49104
  1767
      fun dub needs_sound j k =
blanchet@48961
  1768
        ascii_of unmangled_s ^ "_" ^ string_of_int j ^ "_" ^ string_of_int k ^
blanchet@47167
  1769
        (if mangled_s = unmangled_s then "" else "_" ^ ascii_of mangled_s) ^
blanchet@49104
  1770
        (if needs_sound then typed_helper_suffix else untyped_helper_suffix)
blanchet@48947
  1771
      fun specialize_helper t T =
blanchet@48947
  1772
        if unmangled_s = app_op_name then
blanchet@48947
  1773
          let
blanchet@48947
  1774
            val tyenv =
blanchet@48947
  1775
              Sign.typ_match thy (alpha_to_beta, domain_type T) Vartab.empty
blanchet@48947
  1776
          in monomorphic_term tyenv t end
blanchet@48947
  1777
        else
blanchet@48947
  1778
          specialize_type thy (invert_const unmangled_s, T) t
blanchet@49104
  1779
      fun dub_and_inst needs_sound ((status, t), j) =
blanchet@48947
  1780
        (if should_specialize_helper type_enc t then
blanchet@48961
  1781
           map_filter (try (specialize_helper t)) types
blanchet@48947
  1782
         else
blanchet@48947
  1783
           [t])
blanchet@47167
  1784
        |> tag_list 1
blanchet@49104
  1785
        |> map (fn (k, t) => ((dub needs_sound j k, (Global, status)), t))
blanchet@44731
  1786
      val make_facts = map_filter (make_fact ctxt format type_enc false)
blanchet@49104
  1787
      val sound = is_type_enc_sound type_enc
blanchet@48961
  1788
      val could_specialize = could_specialize_helpers type_enc
blanchet@43444
  1789
    in
blanchet@49104
  1790
      fold (fn ((helper_s, needs_sound), ths) =>
blanchet@49104
  1791
               if (needs_sound andalso not sound) orelse
blanchet@48961
  1792
                  (helper_s <> unmangled_s andalso
blanchet@48961
  1793
                   (not aggressive orelse could_specialize)) then
blanchet@48681
  1794
                 I
blanchet@48681
  1795
               else
blanchet@48681
  1796
                 ths ~~ (1 upto length ths)
blanchet@49104
  1797
                 |> maps (dub_and_inst needs_sound o apfst (apsnd prop_of))
blanchet@48681
  1798
                 |> make_facts
blanchet@48681
  1799
                 |> union (op = o pairself #iformula))
blanchet@48961
  1800
           (if aggressive then aggressive_helper_table else helper_table)
blanchet@43444
  1801
    end
blanchet@48681
  1802
  | NONE => I
blanchet@48961
  1803
fun helper_facts_for_sym_table ctxt format type_enc aggressive sym_tab =
blanchet@48961
  1804
  Symtab.fold_rev (add_helper_facts_for_sym ctxt format type_enc aggressive)
blanchet@48961
  1805
                  sym_tab []
blanchet@43444
  1806
blanchet@43926
  1807
(***************************************************************)
blanchet@43926
  1808
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@43926
  1809
(***************************************************************)
blanchet@43926
  1810
blanchet@43926
  1811
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@43926
  1812
blanchet@43926
  1813
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@43926
  1814
blanchet@43926
  1815
(* Remove this trivial type class (FIXME: similar code elsewhere) *)
blanchet@43926
  1816
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
blanchet@43926
  1817
blanchet@43934
  1818
fun classes_of_terms get_Ts =
blanchet@43962
  1819
  map (map snd o get_Ts)
blanchet@43934
  1820
  #> List.foldl add_classes Symtab.empty
blanchet@43934
  1821
  #> delete_type #> Symtab.keys
blanchet@43926
  1822
wenzelm@45004
  1823
val tfree_classes_of_terms = classes_of_terms Misc_Legacy.term_tfrees
wenzelm@45004
  1824
val tvar_classes_of_terms = classes_of_terms Misc_Legacy.term_tvars
blanchet@43926
  1825
blanchet@44489
  1826
fun fold_type_constrs f (Type (s, Ts)) x =
blanchet@44489
  1827
    fold (fold_type_constrs f) Ts (f (s, x))
blanchet@44030
  1828
  | fold_type_constrs _ _ x = x
blanchet@43926
  1829
blanchet@44778
  1830
(* Type constructors used to instantiate overloaded constants are the only ones
blanchet@44778
  1831
   needed. *)
blanchet@44030
  1832
fun add_type_constrs_in_term thy =
blanchet@43926
  1833
  let
blanchet@44029
  1834
    fun add (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@44022
  1835
      | add (t $ u) = add t #> add u
blanchet@45602
  1836
      | add (Const x) =
blanchet@45602
  1837
        x |> robust_const_typargs thy |> fold (fold_type_constrs set_insert)
blanchet@44022
  1838
      | add (Abs (_, _, u)) = add u
blanchet@44022
  1839
      | add _ = I
blanchet@44022
  1840
  in add end
blanchet@43926
  1841
blanchet@44030
  1842
fun type_constrs_of_terms thy ts =
blanchet@44030
  1843
  Symtab.keys (fold (add_type_constrs_in_term thy) ts Symtab.empty)
blanchet@43926
  1844
blanchet@46382
  1845
fun extract_lambda_def (Const (@{const_name HOL.eq}, _) $ t $ u) =
blanchet@46382
  1846
    let val (head, args) = strip_comb t in
blanchet@46382
  1847
      (head |> dest_Const |> fst,
blanchet@46382
  1848
       fold_rev (fn t as Var ((s, _), T) =>
blanchet@46382
  1849
                    (fn u => Abs (s, T, abstract_over (t, u)))
blanchet@48947
  1850
                  | _ => raise Fail "expected \"Var\"") args u)
blanchet@46382
  1851
    end
blanchet@46382
  1852
  | extract_lambda_def _ = raise Fail "malformed lifted lambda"
blanchet@46379
  1853
blanchet@46385
  1854
fun trans_lams_from_string ctxt type_enc lam_trans =
blanchet@46385
  1855
  if lam_trans = no_lamsN then
blanchet@46385
  1856
    rpair []
blanchet@46385
  1857
  else if lam_trans = hide_lamsN then
blanchet@46385
  1858
    lift_lams ctxt type_enc ##> K []
blanchet@47193
  1859
  else if lam_trans = liftingN orelse lam_trans = lam_liftingN then
blanchet@46385
  1860
    lift_lams ctxt type_enc
blanchet@47193
  1861
  else if lam_trans = combsN then
blanchet@46385
  1862
    map (introduce_combinators ctxt) #> rpair []
blanchet@47193
  1863
  else if lam_trans = combs_and_liftingN then
blanchet@47193
  1864
    lift_lams_part_1 ctxt type_enc
blanchet@47193
  1865
    ##> maps (fn t => [t, introduce_combinators ctxt (intentionalize_def t)])
blanchet@47689
  1866
    #> lift_lams_part_2 ctxt
blanchet@47196
  1867
  else if lam_trans = combs_or_liftingN then
blanchet@46425
  1868
    lift_lams_part_1 ctxt type_enc
blanchet@47196
  1869
    ##> map (fn t => case head_of (strip_qnt_body @{const_name All} t) of
blanchet@47196
  1870
                       @{term "op =::bool => bool => bool"} => t
blanchet@47196
  1871
                     | _ => introduce_combinators ctxt (intentionalize_def t))
blanchet@47689
  1872
    #> lift_lams_part_2 ctxt
blanchet@46385
  1873
  else if lam_trans = keep_lamsN then
blanchet@46385
  1874
    map (Envir.eta_contract) #> rpair []
blanchet@46385
  1875
  else
blanchet@46390
  1876
    error ("Unknown lambda translation scheme: " ^ quote lam_trans ^ ".")
blanchet@46385
  1877
blanchet@48996
  1878
val pull_and_reorder_definitions =
blanchet@48990
  1879
  let
blanchet@48990
  1880
    fun add_consts (IApp (t, u)) = fold add_consts [t, u]
blanchet@48990
  1881
      | add_consts (IAbs (_, t)) = add_consts t
blanchet@48990
  1882
      | add_consts (IConst (name, _, _)) = insert (op =) name
blanchet@48990
  1883
      | add_consts (IVar _) = I
blanchet@48996
  1884
    fun consts_of_hs l_or_r ({iformula, ...} : ifact) =
blanchet@48990
  1885
      case iformula of
blanchet@48990
  1886
        AAtom (IApp (IApp (IConst _, t), u)) => add_consts (l_or_r (t, u)) []
blanchet@48990
  1887
      | _ => []
blanchet@48990
  1888
    (* Quadratic, but usually OK. *)
blanchet@48996
  1889
    fun reorder [] [] = []
blanchet@48996
  1890
      | reorder (fact :: skipped) [] =
blanchet@48996
  1891
        fact :: reorder [] skipped (* break cycle *)
blanchet@48996
  1892
      | reorder skipped (fact :: facts) =
blanchet@48990
  1893
        let val rhs_consts = consts_of_hs snd fact in
blanchet@49111
  1894
          if exists (exists (exists (member (op =) rhs_consts)
blanchet@49111
  1895
                     o consts_of_hs fst)) [skipped, facts] then
blanchet@48996
  1896
            reorder (fact :: skipped) facts
blanchet@48990
  1897
          else
blanchet@48996
  1898
            fact :: reorder [] (facts @ skipped)
blanchet@48990
  1899
        end
blanchet@48996
  1900
  in List.partition (curry (op =) Definition o #role) #>> reorder [] #> op @ end
blanchet@48990
  1901
blanchet@48990
  1902
fun translate_formulas ctxt prem_role format type_enc lam_trans presimp hyp_ts
blanchet@46385
  1903
                       concl_t facts =
blanchet@43444
  1904
  let
blanchet@43444
  1905
    val thy = Proof_Context.theory_of ctxt
blanchet@46385
  1906
    val trans_lams = trans_lams_from_string ctxt type_enc lam_trans
blanchet@44732
  1907
    val fact_ts = facts |> map snd
blanchet@43444
  1908
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@43444
  1909
       boost an ATP's performance (for some reason). *)
blanchet@44033
  1910
    val hyp_ts =
blanchet@44033
  1911
      hyp_ts
blanchet@44033
  1912
      |> map (fn t => if member (op aconv) fact_ts t then @{prop True} else t)
blanchet@44735
  1913
    val facts = facts |> map (apsnd (pair Axiom))
blanchet@44735
  1914
    val conjs =
blanchet@48990
  1915
      map (pair prem_role) hyp_ts @ [(Conjecture, s_not_prop concl_t)]
blanchet@46039
  1916
      |> map (apsnd freeze_term)
blanchet@47168
  1917
      |> map2 (pair o rpair (Local, General) o string_of_int)
blanchet@47168
  1918
              (0 upto length hyp_ts)
blanchet@46425
  1919
    val ((conjs, facts), lam_facts) =
blanchet@46382
  1920
      (conjs, facts)
blanchet@48639
  1921
      |> presimp ? pairself (map (apsnd (apsnd (presimp_prop ctxt type_enc))))
blanchet@46385
  1922
      |> (if lam_trans = no_lamsN then
blanchet@46382
  1923
            rpair []
blanchet@46382
  1924
          else
blanchet@46382
  1925
            op @
blanchet@46385
  1926
            #> preprocess_abstractions_in_terms trans_lams
blanchet@46382
  1927
            #>> chop (length conjs))
blanchet@48996
  1928
    val conjs =
blanchet@48996
  1929
      conjs |> make_conjecture ctxt format type_enc
blanchet@48996
  1930
            |> pull_and_reorder_definitions
blanchet@48996
  1931
    val facts =
blanchet@48996
  1932
      facts |> map_filter (fn (name, (_, t)) =>
blanchet@48996
  1933
                              make_fact ctxt format type_enc true (name, t))
blanchet@48996
  1934
            |> pull_and_reorder_definitions
blanchet@48996
  1935
    val fact_names =
blanchet@48996
  1936
      facts |> map (fn {name, stature, ...} : ifact => (name, stature))
blanchet@47203
  1937
    val lifted = lam_facts |> map (extract_lambda_def o snd o snd)
blanchet@46425
  1938
    val lam_facts =
blanchet@46425
  1939
      lam_facts |> map_filter (make_fact ctxt format type_enc true o apsnd snd)
blanchet@44732
  1940
    val all_ts = concl_t :: hyp_ts @ fact_ts
blanchet@43444
  1941
    val subs = tfree_classes_of_terms all_ts
blanchet@43444
  1942
    val supers = tvar_classes_of_terms all_ts
blanchet@44030
  1943
    val tycons = type_constrs_of_terms thy all_ts
blanchet@44732
  1944
    val (supers, arity_clauses) =
blanchet@44493
  1945
      if level_of_type_enc type_enc = No_Types then ([], [])
blanchet@43444
  1946
      else make_arity_clauses thy tycons supers
blanchet@44732
  1947
    val class_rel_clauses = make_class_rel_clauses thy subs supers
blanchet@43444
  1948
  in
blanchet@46379
  1949
    (fact_names |> map single, union (op =) subs supers, conjs,
blanchet@46425
  1950
     facts @ lam_facts, class_rel_clauses, arity_clauses, lifted)
blanchet@43444
  1951
  end
blanchet@43444
  1952
nik@45350
  1953
val type_guard = `(make_fixed_const NONE) type_guard_name
blanchet@43971
  1954
blanchet@48638
  1955
fun type_guard_iterm type_enc T tm =
blanchet@45255
  1956
  IApp (IConst (type_guard, T --> @{typ bool}, [T])
blanchet@48638
  1957
        |> mangle_type_args_in_iterm type_enc, tm)
blanchet@43444
  1958
blanchet@44282
  1959
fun is_var_positively_naked_in_term _ (SOME false) _ accum = accum
blanchet@49147
  1960
  | is_var_positively_naked_in_term name _ (ATerm (((s, _), _), tms)) accum =
blanchet@49147
  1961
    accum orelse
blanchet@49147
  1962
    (is_tptp_equal s andalso member (op =) tms (ATerm ((name, []), [])))
blanchet@44558
  1963
  | is_var_positively_naked_in_term _ _ _ _ = true
blanchet@45262
  1964
blanchet@49110
  1965
fun is_var_positively_naked_or_undercover_in_term thy name pos tm accum =
blanchet@45673
  1966
  is_var_positively_naked_in_term name pos tm accum orelse
blanchet@45673
  1967
  let
blanchet@49147
  1968
    val var = ATerm ((name, []), [])
blanchet@49110
  1969
    fun is_undercover (ATerm (_, [])) = false
blanchet@49147
  1970
      | is_undercover (ATerm (((s, _), _), tms)) =
blanchet@46819
  1971
        let
blanchet@46819
  1972
          val ary = length tms
blanchet@49095
  1973
          val cover = type_arg_cover thy s ary
blanchet@46819
  1974
        in
blanchet@49102
  1975
          exists (fn (j, tm) => tm = var andalso member (op =) cover j)
blanchet@49102
  1976
                 (0 upto ary - 1 ~~ tms) orelse
blanchet@49110
  1977
          exists is_undercover tms
blanchet@46819
  1978
        end
blanchet@49110
  1979
      | is_undercover _ = true
blanchet@49110
  1980
  in is_undercover tm end
blanchet@45673
  1981
blanchet@49102
  1982
fun should_guard_var_in_formula thy level pos phi (SOME true) name =
blanchet@45673
  1983
    (case granularity_of_type_level level of
blanchet@45673
  1984
       All_Vars => true
blanchet@45673
  1985
     | Positively_Naked_Vars =>
blanchet@45673
  1986
       formula_fold pos (is_var_positively_naked_in_term name) phi false
blanchet@49110
  1987
     | Undercover_Vars =>
blanchet@49110
  1988
       formula_fold pos (is_var_positively_naked_or_undercover_in_term thy name)
blanchet@49110
  1989
                    phi false)
blanchet@49102
  1990
  | should_guard_var_in_formula _ _ _ _ _ _ = true
blanchet@46819
  1991
blanchet@49102
  1992
fun always_guard_var_in_formula _ _ _ _ _ _ = true
blanchet@43705
  1993
blanchet@45264
  1994
fun should_generate_tag_bound_decl _ _ _ (SOME true) _ = false
blanchet@45639
  1995
  | should_generate_tag_bound_decl ctxt mono (Tags (_, level)) _ T =
blanchet@45673
  1996
    granularity_of_type_level level <> All_Vars andalso
blanchet@45650
  1997
    should_encode_type ctxt mono level T
blanchet@45264
  1998
  | should_generate_tag_bound_decl _ _ _ _ _ = false
blanchet@45263
  1999
blanchet@48638
  2000
fun mk_aterm type_enc name T_args args =
blanchet@49148
  2001
  let val (ty_args, tm_args) = process_type_args type_enc T_args in
blanchet@49148
  2002
    ATerm ((name, ty_args), tm_args @ args)
blanchet@49148
  2003
  end
blanchet@43835
  2004
blanchet@48638
  2005
fun do_bound_type ctxt mono type_enc =
blanchet@47220
  2006
  case type_enc of
blanchet@48637
  2007
    Native (_, _, level) =>
blanchet@48638
  2008
    fused_type ctxt mono level 0 #> ho_type_from_typ type_enc false 0 #> SOME
blanchet@47220
  2009
  | _ => K NONE
blanchet@47220
  2010
blanchet@48638
  2011
fun tag_with_type ctxt mono type_enc pos T tm =
blanchet@44730
  2012
  IConst (type_tag, T --> T, [T])
blanchet@48638
  2013
  |> mangle_type_args_in_iterm type_enc
blanchet@48638
  2014
  |> ho_term_from_iterm ctxt mono type_enc pos
blanchet@49147
  2015
  |> (fn ATerm ((s, tys), tms) => ATerm ((s, tys), tms @ [tm])
blanchet@44558
  2016
       | _ => raise Fail "unexpected lambda-abstraction")
blanchet@48638
  2017
and ho_term_from_iterm ctxt mono type_enc pos =
blanchet@43444
  2018
  let
blanchet@46820
  2019
    fun term site u =
blanchet@43803
  2020
      let
blanchet@44730
  2021
        val (head, args) = strip_iterm_comb u
nik@44536
  2022
        val pos =
blanchet@46820
  2023
          case site of
nik@44536
  2024
            Top_Level pos => pos
nik@44536
  2025
          | Eq_Arg pos => pos
blanchet@45676
  2026
          | _ => NONE
nik@44536
  2027
        val t =
blanchet@43803
  2028
          case head of
blanchet@44730
  2029
            IConst (name as (s, _), _, T_args) =>
blanchet@48024
  2030
            let
blanchet@48024
  2031
              val arg_site = if is_tptp_equal s then Eq_Arg pos else Elsewhere
blanchet@48638
  2032
            in map (term arg_site) args |> mk_aterm type_enc name T_args end
blanchet@44730
  2033
          | IVar (name, _) =>
blanchet@48638
  2034
            map (term Elsewhere) args |> mk_aterm type_enc name []
blanchet@44730
  2035
          | IAbs ((name, T), tm) =>
blanchet@47689
  2036
            if is_type_enc_higher_order type_enc then
blanchet@49148
  2037
              AAbs (((name, ho_type_from_typ type_enc true (* FIXME? why "true"? *) 0 T),
blanchet@48926
  2038
                     term Elsewhere tm), map (term Elsewhere) args)
blanchet@47689
  2039
            else
blanchet@47689
  2040
              raise Fail "unexpected lambda-abstraction"
blanchet@44730
  2041
          | IApp _ => raise Fail "impossible \"IApp\""
blanchet@44730
  2042
        val T = ityp_of u
blanchet@43803
  2043
      in
blanchet@46820
  2044
        if should_tag_with_type ctxt mono type_enc site u T then
blanchet@48638
  2045
          tag_with_type ctxt mono type_enc pos T t
blanchet@46818
  2046
        else
blanchet@46818
  2047
          t
blanchet@43803
  2048
      end
blanchet@48926
  2049
  in term (Top_Level pos) end
blanchet@49102
  2050
and formula_from_iformula ctxt mono type_enc should_guard_var =
blanchet@43700
  2051
  let
blanchet@45673
  2052
    val thy = Proof_Context.theory_of ctxt
blanchet@45673
  2053
    val level = level_of_type_enc type_enc
blanchet@48638
  2054
    val do_term = ho_term_from_iterm ctxt mono type_enc
blanchet@43747
  2055
    fun do_out_of_bound_type pos phi universal (name, T) =
blanchet@45258
  2056
      if should_guard_type ctxt mono type_enc
blanchet@49102
  2057
             (fn () => should_guard_var thy level pos phi universal name) T then
blanchet@44730
  2058
        IVar (name, T)
blanchet@48638
  2059
        |> type_guard_iterm type_enc T
blanchet@44232
  2060
        |> do_term pos |> AAtom |> SOME
blanchet@45264
  2061
      else if should_generate_tag_bound_decl ctxt mono type_enc universal T then
blanchet@45264
  2062
        let
blanchet@49147
  2063
          val var = ATerm ((name, []), [])
blanchet@48638
  2064
          val tagged_var = tag_with_type ctxt mono type_enc pos T var
blanchet@49147
  2065
        in SOME (AAtom (ATerm ((`I tptp_equal, []), [tagged_var, var]))) end
blanchet@43444
  2066
      else
blanchet@43444
  2067
        NONE
blanchet@49148
  2068
    fun do_formula pos (ATyQuant (q, xs, phi)) =
blanchet@49148
  2069
        ATyQuant (q, map (ho_type_from_typ type_enc false 0) xs,
blanchet@49148
  2070
                  do_formula pos phi)
blanchet@49148
  2071
      | do_formula pos (AQuant (q, xs, phi)) =
blanchet@43747
  2072
        let
blanchet@43747
  2073
          val phi = phi |> do_formula pos
blanchet@43747
  2074
          val universal = Option.map (q = AExists ? not) pos
blanchet@48638
  2075
          val do_bound_type = do_bound_type ctxt mono type_enc
blanchet@43747
  2076
        in
blanchet@43705
  2077
          AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@43705
  2078
                                        | SOME T => do_bound_type T)),
blanchet@43705
  2079
                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@43705
  2080
                      (map_filter
blanchet@43705
  2081
                           (fn (_, NONE) => NONE
blanchet@43705
  2082
                             | (s, SOME T) =>
blanchet@43747
  2083
                               do_out_of_bound_type pos phi universal (s, T))
blanchet@43747
  2084
                           xs)
blanchet@43705
  2085
                      phi)
blanchet@43705
  2086
        end
blanchet@43747
  2087
      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
blanchet@44232
  2088
      | do_formula pos (AAtom tm) = AAtom (do_term pos tm)
blanchet@44364
  2089
  in do_formula end
blanchet@43444
  2090
blanchet@43444
  2091
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@43444
  2092
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@43444
  2093
   the remote provers might care. *)
blanchet@49102
  2094
fun formula_line_for_fact ctxt prefix encode freshen pos mono type_enc rank
blanchet@49102
  2095
                          (j, {name, stature, role, iformula, atomic_types}) =
blanchet@48990
  2096
  (prefix ^ (if freshen then string_of_int j ^ "_" else "") ^ encode name, role,
blanchet@44730
  2097
   iformula
blanchet@49102
  2098
   |> formula_from_iformula ctxt mono type_enc should_guard_var_in_formula
blanchet@49102
  2099
                            (if pos then SOME true else NONE)
blanchet@46248
  2100
   |> close_formula_universally
blanchet@46791
  2101
   |> bound_tvars type_enc true atomic_types,
blanchet@44364
  2102
   NONE,
blanchet@47234
  2103
   let val rank = rank j in
blanchet@47234
  2104
     case snd stature of
blanchet@47909
  2105
       Intro => isabelle_info introN rank
blanchet@48019
  2106
     | Inductive => isabelle_info inductiveN rank
blanchet@47909
  2107
     | Elim => isabelle_info elimN rank
blanchet@47909
  2108
     | Simp => isabelle_info simpN rank
blanchet@48019
  2109
     | Def => isabelle_info defN rank
blanchet@47909
  2110
     | _ => isabelle_info "" rank
blanchet@47234
  2111
   end)
blanchet@44364
  2112
  |> Formula
blanchet@43444
  2113
blanchet@47909
  2114
fun formula_line_for_class_rel_clause type_enc
blanchet@45457
  2115
        ({name, subclass, superclass, ...} : class_rel_clause) =
blanchet@49148
  2116
  Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@49148
  2117
           AConn (AImplies,
blanchet@49148
  2118
                  [type_class_atom type_enc (subclass, tvar_a),
blanchet@49148
  2119
                   type_class_atom type_enc (superclass, tvar_a)])
blanchet@49148
  2120
           |> bound_tvars type_enc false [tvar_a],
blanchet@49148
  2121
           NONE, isabelle_info inductiveN helper_rank)
blanchet@49148
  2122
blanchet@49148
  2123
fun formula_line_for_arity_clause type_enc
blanchet@49148
  2124
        ({name, prems, concl} : arity_clause) =
blanchet@49148
  2125
  let
blanchet@49148
  2126
    val atomic_Ts = fold (fold_atyps (insert (op =)) o snd) (concl :: prems) []
blanchet@49148
  2127
  in
blanchet@49148
  2128
    Formula (arity_clause_prefix ^ name, Axiom,
blanchet@49148
  2129
             mk_ahorn (map (type_class_atom type_enc) prems)
blanchet@49148
  2130
                      (type_class_atom type_enc concl)
blanchet@49148
  2131
             |> bound_tvars type_enc true atomic_Ts,
blanchet@48019
  2132
             NONE, isabelle_info inductiveN helper_rank)
blanchet@43444
  2133
  end
blanchet@43444
  2134
blanchet@49102
  2135
fun formula_line_for_conjecture ctxt mono type_enc
blanchet@48996
  2136
        ({name, role, iformula, atomic_types, ...} : ifact) =
blanchet@48990
  2137
  Formula (conjecture_prefix ^ name, role,
blanchet@46187
  2138
           iformula
blanchet@49102
  2139
           |> formula_from_iformula ctxt mono type_enc
blanchet@46187
  2140
                  should_guard_var_in_formula (SOME false)
blanchet@46248
  2141
           |> close_formula_universally
blanchet@47234
  2142
           |> bound_tvars type_enc true atomic_types, NONE, [])
blanchet@43444
  2143
blanchet@48996
  2144
fun formula_lines_for_free_types type_enc (facts : ifact list) =
blanchet@49148
  2145
  let
blanchet@49148
  2146
    fun line j phi =
blanchet@49148
  2147
      Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis, phi, NONE, [])
blanchet@49148
  2148
    val phis =
blanchet@49148
  2149
      fold (union (op =)) (map #atomic_types facts) []
blanchet@49148
  2150
      |> formulas_for_types type_enc add_sorts_on_tfree
blanchet@49148
  2151
  in map2 line (0 upto length phis - 1) phis end
blanchet@43444
  2152
blanchet@43444
  2153
(** Symbol declarations **)
blanchet@43415
  2154
blanchet@49146
  2155
fun decl_line_for_class order phantoms s =
blanchet@45459
  2156
  let val name as (s, _) = `make_type_class s in
blanchet@45480
  2157
    Decl (sym_decl_prefix ^ s, name,
blanchet@46650
  2158
          if order = First_Order then
blanchet@49148
  2159
            APi ([tvar_a_name],
blanchet@49148
  2160
                 if phantoms = Without_Phantom_Type_Vars then
blanchet@49148
  2161
                   AFun (a_itself_atype, bool_atype)
blanchet@49148
  2162
                 else
blanchet@49148
  2163
                   bool_atype)
blanchet@45480
  2164
          else
blanchet@45618
  2165
            AFun (atype_of_types, bool_atype))
blanchet@45459
  2166
  end
blanchet@45459
  2167
blanchet@45459
  2168
fun decl_lines_for_classes type_enc classes =
blanchet@45459
  2169
  case type_enc of
blanchet@49146
  2170
    Native (order, Raw_Polymorphic phantoms, _) =>
blanchet@49146
  2171
    map (decl_line_for_class order phantoms) classes
blanchet@45459
  2172
  | _ => []
blanchet@45459
  2173
blanchet@48638
  2174
fun sym_decl_table_for_facts thy type_enc sym_tab (conjs, facts, extra_tms) =
blanchet@43445
  2175
  let
blanchet@45700
  2176
    fun add_iterm_syms tm =
blanchet@44730
  2177
      let val (head, args) = strip_iterm_comb tm in
blanchet@43445
  2178
        (case head of
blanchet@44730
  2179
           IConst ((s, s'), T, T_args) =>
blanchet@45458
  2180
           let
blanchet@45700
  2181
             val (pred_sym, in_conj) =
blanchet@45700
  2182
               case Symtab.lookup sym_tab s of
blanchet@45724
  2183
                 SOME ({pred_sym, in_conj, ...} : sym_info) =>
blanchet@45724
  2184
                 (pred_sym, in_conj)
blanchet@45700
  2185
               | NONE => (false, false)
blanchet@45458
  2186
             val decl_sym =
blanchet@45458
  2187
               (case type_enc of
blanchet@45458
  2188
                  Guards _ => not pred_sym
blanchet@45458
  2189
                | _ => true) andalso
blanchet@45458
  2190
               is_tptp_user_symbol s
blanchet@45458
  2191
           in
blanchet@45458
  2192
             if decl_sym then
blanchet@43447
  2193
               Symtab.map_default (s, [])
blanchet@48021
  2194
                   (insert_type thy #3 (s', T_args, T, pred_sym, length args,
blanchet@48021
  2195
                                        in_conj))
blanchet@43445
  2196
             else
blanchet@43445
  2197
               I
blanchet@43445
  2198
           end
blanchet@45700
  2199
         | IAbs (_, tm) => add_iterm_syms tm
blanchet@43445
  2200
         | _ => I)
blanchet@45700
  2201
        #> fold add_iterm_syms args
blanchet@43445
  2202
      end
blanchet@48996
  2203
    val add_fact_syms = K add_iterm_syms |> formula_fold NONE |> ifact_lift
blanchet@49148
  2204
    fun add_formula_var_types (ATyQuant (_, _, phi)) = add_formula_var_types phi
blanchet@49148
  2205
      | add_formula_var_types (AQuant (_, xs, phi)) =
blanchet@48021
  2206
        fold (fn (_, SOME T) => insert_type thy I T | _ => I) xs
blanchet@44837
  2207
        #> add_formula_var_types phi
blanchet@44837
  2208
      | add_formula_var_types (AConn (_, phis)) =
blanchet@44837
  2209
        fold add_formula_var_types phis
blanchet@44837
  2210
      | add_formula_var_types _ = I
blanchet@44837
  2211
    fun var_types () =
blanchet@49146
  2212
      if is_type_enc_polymorphic type_enc then [tvar_a]
blanchet@48996
  2213
      else fold (ifact_lift add_formula_var_types) (conjs @ facts) []
blanchet@44837
  2214
    fun add_undefined_const T =
blanchet@44855
  2215
      let
blanchet@44855
  2216
        val (s, s') =
blanchet@45480
  2217
          `(make_fixed_const NONE) @{const_name undefined}
blanchet@46816
  2218
          |> (case type_arg_policy [] type_enc @{const_name undefined} of
blanchet@48638
  2219
                Mangled_Type_Args => mangled_const_name type_enc [T]
blanchet@44872
  2220
              | _ => I)
blanchet@44855
  2221
      in
blanchet@44855
  2222
        Symtab.map_default (s, [])
blanchet@48021
  2223
                           (insert_type thy #3 (s', [T], T, false, 0, false))
blanchet@44855
  2224
      end
blanchet@45480
  2225
    fun add_TYPE_const () =
blanchet@45480
  2226
      let val (s, s') = TYPE_name in
blanchet@45480
  2227
        Symtab.map_default (s, [])
blanchet@48021
  2228
            (insert_type thy #3
blanchet@45480
  2229
                         (s', [tvar_a], @{typ "'a itself"}, false, 0, false))
blanchet@45480
  2230
      end
blanchet@43568
  2231
  in
blanchet@43568
  2232
    Symtab.empty
blanchet@49104
  2233
    |> is_type_enc_sound type_enc
blanchet@45700
  2234
       ? (fold (fold add_fact_syms) [conjs, facts]
blanchet@47220
  2235
          #> fold add_iterm_syms extra_tms
blanchet@44856
  2236
          #> (case type_enc of
blanchet@49146
  2237
                Native (First_Order, Raw_Polymorphic phantoms, _) =>
blanchet@49146
  2238
                phantoms = Without_Phantom_Type_Vars ? add_TYPE_const ()
blanchet@48637
  2239
              | Native _ => I
blanchet@44856
  2240
              | _ => fold add_undefined_const (var_types ())))
blanchet@43568
  2241
  end
blanchet@43445
  2242
blanchet@45258
  2243
(* We add "bool" in case the helper "True_or_False" is included later. *)
blanchet@49120
  2244
fun default_mono level aggressive =
blanchet@45258
  2245
  {maybe_finite_Ts = [@{typ bool}],
blanchet@45492
  2246
   surely_infinite_Ts =
blanchet@45492
  2247
     case level of
blanchet@49107
  2248
       Nonmono_Types (Strict, _) => []
blanchet@45492
  2249
     | _ => known_infinite_types,
blanchet@49120
  2250
   maybe_nonmono_Ts = [if aggressive then tvar_a else @{typ bool}]}
blanchet@45258
  2251
blanchet@43555
  2252
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@43555
  2253
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@45258
  2254
fun add_iterm_mononotonicity_info _ _ (SOME false) _ mono = mono
blanchet@45258
  2255
  | add_iterm_mononotonicity_info ctxt level _
blanchet@45258
  2256
        (IApp (IApp (IConst ((s, _), Type (_, [T, _]), _), tm1), tm2))
blanchet@49118
  2257
        (mono as {maybe_finite_Ts, surely_infinite_Ts, maybe_nonmono_Ts}) =
blanchet@48021
  2258
    let val thy = Proof_Context.theory_of ctxt in
blanchet@48021
  2259
      if is_tptp_equal s andalso exists is_maybe_universal_var [tm1, tm2] then
blanchet@48021
  2260
        case level of
blanchet@49107
  2261
          Nonmono_Types (strictness, _) =>
blanchet@48021
  2262
          if exists (type_instance thy T) surely_infinite_Ts orelse
blanchet@48021
  2263
             member (type_equiv thy) maybe_finite_Ts T then
blanchet@48021
  2264
            mono
blanchet@48021
  2265
          else if is_type_kind_of_surely_infinite ctxt strictness
blanchet@48021
  2266
                                                  surely_infinite_Ts T then
blanchet@48021
  2267
            {maybe_finite_Ts = maybe_finite_Ts,
blanchet@48021
  2268
             surely_infinite_Ts = surely_infinite_Ts |> insert_type thy I T,
blanchet@48021
  2269
             maybe_nonmono_Ts = maybe_nonmono_Ts}
blanchet@48021
  2270
          else
blanchet@48021
  2271
            {maybe_finite_Ts = maybe_finite_Ts |> insert (type_equiv thy) T,
blanchet@48021
  2272
             surely_infinite_Ts = surely_infinite_Ts,
blanchet@48021
  2273
             maybe_nonmono_Ts = maybe_nonmono_Ts |> insert_type thy I T}
blanchet@48021
  2274
        | _ => mono
blanchet@48021
  2275
      else
blanchet@48021
  2276
        mono
blanchet@48021
  2277
    end
blanchet@45258
  2278
  | add_iterm_mononotonicity_info _ _ _ _ mono = mono
blanchet@48996
  2279
fun add_fact_mononotonicity_info ctxt level ({role, iformula, ...} : ifact) =
blanchet@48990
  2280
  formula_fold (SOME (role <> Conjecture))
blanchet@45258
  2281
               (add_iterm_mononotonicity_info ctxt level) iformula
blanchet@49120
  2282
fun mononotonicity_info_for_facts ctxt type_enc aggressive facts =
blanchet@44493
  2283
  let val level = level_of_type_enc type_enc in
blanchet@49120
  2284
    default_mono level aggressive
blanchet@45258
  2285
    |> is_type_level_monotonicity_based level
blanchet@45258
  2286
       ? fold (add_fact_mononotonicity_info ctxt level) facts
blanchet@43700
  2287
  end
blanchet@43547
  2288
blanchet@45356
  2289
fun add_iformula_monotonic_types ctxt mono type_enc =
blanchet@45356
  2290
  let
blanchet@48021
  2291
    val thy = Proof_Context.theory_of ctxt
blanchet@45356
  2292
    val level = level_of_type_enc type_enc
blanchet@45356
  2293
    val should_encode = should_encode_type ctxt mono level
blanchet@48021
  2294
    fun add_type T = not (should_encode T) ? insert_type thy I T
blanchet@45361
  2295
    fun add_args (IApp (tm1, tm2)) = add_args tm1 #> add_term tm2
blanchet@45361
  2296
      | add_args _ = I
blanchet@45361
  2297
    and add_term tm = add_type (ityp_of tm) #> add_args tm
blanchet@45356
  2298
  in formula_fold NONE (K add_term) end
blanchet@45356
  2299
fun add_fact_monotonic_types ctxt mono type_enc =
blanchet@48996
  2300
  add_iformula_monotonic_types ctxt mono type_enc |> ifact_lift
blanchet@45356
  2301
fun monotonic_types_for_facts ctxt mono type_enc facts =
blanchet@45673
  2302
  let val level = level_of_type_enc type_enc in
blanchet@49146
  2303
    [] |> (is_type_enc_polymorphic type_enc andalso
blanchet@45673
  2304
           is_type_level_monotonicity_based level andalso
blanchet@49110
  2305
           granularity_of_type_level level <> Undercover_Vars)
blanchet@45673
  2306
          ? fold (add_fact_monotonic_types ctxt mono type_enc) facts
blanchet@45673
  2307
  end
blanchet@45356
  2308
blanchet@48638
  2309
fun formula_line_for_guards_mono_type ctxt mono type_enc T =
blanchet@45255
  2310
  Formula (guards_sym_formula_prefix ^
blanchet@48638
  2311
           ascii_of (mangled_type type_enc T),
blanchet@45255
  2312
           Axiom,
blanchet@45255
  2313
           IConst (`make_bound_var "X", T, [])
blanchet@48638
  2314
           |> type_guard_iterm type_enc T
blanchet@45255
  2315
           |> AAtom
blanchet@49102
  2316
           |> formula_from_iformula ctxt mono type_enc
blanchet@46819
  2317
                                    always_guard_var_in_formula (SOME true)
blanchet@46248
  2318
           |> close_formula_universally
blanchet@46791
  2319
           |> bound_tvars type_enc true (atomic_types_of T),
blanchet@48019
  2320
           NONE, isabelle_info inductiveN helper_rank)
blanchet@45255
  2321
blanchet@48638
  2322
fun formula_line_for_tags_mono_type ctxt mono type_enc T =
blanchet@49147
  2323
  let val x_var = ATerm ((`make_bound_var "X", []), []) in
blanchet@45255
  2324
    Formula (tags_sym_formula_prefix ^
blanchet@48638
  2325
             ascii_of (mangled_type type_enc T),
blanchet@45255
  2326
             Axiom,
blanchet@47220
  2327
             eq_formula type_enc (atomic_types_of T) [] false
blanchet@48638
  2328
                  (tag_with_type ctxt mono type_enc NONE T x_var) x_var,
blanchet@48019
  2329
             NONE, isabelle_info defN helper_rank)
blanchet@45255
  2330
  end
blanchet@45255
  2331
blanchet@48638
  2332
fun problem_lines_for_mono_types ctxt mono type_enc Ts =
blanchet@45255
  2333
  case type_enc of
blanchet@48637
  2334
    Native _ => []
blanchet@48638
  2335
  | Guards _ => map (formula_line_for_guards_mono_type ctxt mono type_enc) Ts
blanchet@48638
  2336
  | Tags _ => map (formula_line_for_tags_mono_type ctxt mono type_enc) Ts
blanchet@45255
  2337
blanchet@48638
  2338
fun decl_line_for_sym ctxt mono type_enc s
blanchet@43835
  2339
                      (s', T_args, T, pred_sym, ary, _) =
blanchet@43835
  2340
  let
blanchet@45458
  2341
    val thy = Proof_Context.theory_of ctxt
blanchet@45458
  2342
    val (T, T_args) =
blanchet@45458
  2343
      if null T_args then
blanchet@45458
  2344
        (T, [])
blanchet@46382
  2345
      else case unprefix_and_unascii const_prefix s of
blanchet@45458
  2346
        SOME s' =>
blanchet@45458
  2347
        let
blanchet@45458
  2348
          val s' = s' |> invert_const
blanchet@45458
  2349
          val T = s' |> robust_const_type thy
blanchet@45458
  2350
        in (T, robust_const_typargs thy (s', T)) end
blanchet@46380
  2351
      | NONE => raise Fail "unexpected type arguments"
blanchet@43835
  2352
  in
blanchet@43839
  2353
    Decl (sym_decl_prefix ^ s, (s, s'),
blanchet@45458
  2354
          T |> fused_type ctxt mono (level_of_type_enc type_enc) ary
blanchet@48638
  2355
            |> ho_type_from_typ type_enc pred_sym ary
blanchet@45458
  2356
            |> not (null T_args)
blanchet@49148
  2357
               ? curry APi (map (tvar_name o fst o dest_TVar) T_args))
blanchet@43835
  2358
  end
blanchet@43450
  2359
blanchet@48990
  2360
fun honor_conj_sym_role in_conj =
blanchet@48927
  2361
  if in_conj then (Hypothesis, I) else (Axiom, I)
blanchet@47220
  2362
blanchet@48927
  2363
fun formula_line_for_guards_sym_decl ctxt mono type_enc n s j
blanchet@48638
  2364
                                     (s', T_args, T, _, ary, in_conj) =
blanchet@43450
  2365
  let
blanchet@45673
  2366
    val thy = Proof_Context.theory_of ctxt
blanchet@48990
  2367
    val (role, maybe_negate) = honor_conj_sym_role in_conj
blanchet@43618
  2368
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@45676
  2369
    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  2370
    val bounds =
blanchet@44730
  2371
      bound_names ~~ arg_Ts |> map (fn (name, T) => IConst (name, T, []))
blanchet@43450
  2372
    val bound_Ts =
blanchet@45673
  2373
      if exists (curry (op =) dummyT) T_args then
blanchet@49095
  2374
        let val cover = type_arg_cover thy s ary in
blanchet@49095
  2375
          map2 (fn j => if member (op =) cover j then SOME else K NONE)
blanchet@49095
  2376
               (0 upto ary - 1) arg_Ts
blanchet@49095
  2377
        end
blanchet@45673
  2378
      else
blanchet@45676
  2379
        replicate ary NONE
blanchet@43450
  2380
  in
blanchet@44860
  2381
    Formula (guards_sym_formula_prefix ^ s ^
blanchet@48990
  2382
             (if n > 1 then "_" ^ string_of_int j else ""), role,
blanchet@44730
  2383
             IConst ((s, s'), T, T_args)
blanchet@44730
  2384
             |> fold (curry (IApp o swap)) bounds
blanchet@48638
  2385
             |> type_guard_iterm type_enc res_T
blanchet@43804
  2386
             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@49102
  2387
             |> formula_from_iformula ctxt mono type_enc
blanchet@46819
  2388
                                      always_guard_var_in_formula (SOME true)
blanchet@46248
  2389
             |> close_formula_universally
blanchet@46791
  2390
             |> bound_tvars type_enc (n > 1) (atomic_types_of T)
blanchet@43580
  2391
             |> maybe_negate,
blanchet@48019
  2392
             NONE, isabelle_info inductiveN helper_rank)
blanchet@43450
  2393
  end
blanchet@43450
  2394
blanchet@48927
  2395
fun formula_lines_for_tags_sym_decl ctxt mono type_enc n s
blanchet@45673
  2396
        (j, (s', T_args, T, pred_sym, ary, in_conj)) =
blanchet@43700
  2397
  let
blanchet@45676
  2398
    val thy = Proof_Context.theory_of ctxt
blanchet@45676
  2399
    val level = level_of_type_enc type_enc
blanchet@45676
  2400
    val grain = granularity_of_type_level level
blanchet@43700
  2401
    val ident_base =
blanchet@45255
  2402
      tags_sym_formula_prefix ^ s ^
blanchet@43966
  2403
      (if n > 1 then "_" ^ string_of_int j else "")
blanchet@48990
  2404
    val (role, maybe_negate) = honor_conj_sym_role in_conj
blanchet@43700
  2405
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@45676
  2406
    val bound_names = 1 upto ary |> map (`I o make_bound_var o string_of_int)
blanchet@49147
  2407
    val bounds = bound_names |> map (fn name => ATerm ((name, []), []))
blanchet@48638
  2408
    val cst = mk_aterm type_enc (s, s') T_args
blanchet@47220
  2409
    val eq = maybe_negate oo eq_formula type_enc (atomic_types_of T) [] pred_sym
blanchet@45676
  2410
    val should_encode = should_encode_type ctxt mono level
blanchet@48638
  2411
    val tag_with = tag_with_type ctxt mono type_enc NONE
blanchet@43700
  2412
    val add_formula_for_res =
blanchet@43700
  2413
      if should_encode res_T then
blanchet@45676
  2414
        let
blanchet@45676
  2415
          val tagged_bounds =
blanchet@49110
  2416
            if grain = Undercover_Vars then
blanchet@49095
  2417
              let val cover = type_arg_cover thy s ary in
blanchet@49095
  2418
                map2 (fn (j, arg_T) => member (op =) cover j ? tag_with arg_T)
blanchet@45676
  2419
                     (0 upto ary - 1 ~~ arg_Ts) bounds
blanchet@45676
  2420
              end
blanchet@45676
  2421
            else
blanchet@45676
  2422
              bounds
blanchet@45676
  2423
        in
blanchet@48990
  2424
          cons (Formula (ident_base ^ "_res", role,
blanchet@45676
  2425
                         eq (tag_with res_T (cst bounds)) (cst tagged_bounds),
blanchet@48019
  2426
                         NONE, isabelle_info defN helper_rank))
blanchet@45676
  2427
        end
blanchet@43700
  2428
      else
blanchet@43700
  2429
        I
blanchet@47917
  2430
  in [] |> not pred_sym ? add_formula_for_res end
blanchet@43700
  2431
blanchet@43707
  2432
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@43707
  2433
blanchet@48021
  2434
fun rationalize_decls thy (decls as decl :: (decls' as _ :: _)) =
blanchet@46651
  2435
    let
blanchet@46651
  2436
      val T = result_type_of_decl decl
blanchet@46651
  2437
              |> map_type_tvar (fn (z, _) => TVar (z, HOLogic.typeS))
blanchet@46651
  2438
    in
blanchet@48021
  2439
      if forall (type_generalization thy T o result_type_of_decl) decls' then
blanchet@46651
  2440
        [decl]
blanchet@46651
  2441
      else
blanchet@46651
  2442
        decls
blanchet@46651
  2443
    end
blanchet@46651
  2444
  | rationalize_decls _ decls = decls
blanchet@46651
  2445
blanchet@48927
  2446
fun problem_lines_for_sym_decls ctxt mono type_enc (s, decls) =
blanchet@44493
  2447
  case type_enc of
blanchet@48638
  2448
    Native _ => [decl_line_for_sym ctxt mono type_enc s (hd decls)]
blanchet@45639
  2449
  | Guards (_, level) =>
blanchet@43839
  2450
    let
blanchet@48021
  2451
      val thy = Proof_Context.theory_of ctxt
blanchet@48021
  2452
      val decls = decls |> rationalize_decls thy
blanchet@43839
  2453
      val n = length decls
blanchet@43839
  2454
      val decls =
blanchet@45258
  2455
        decls |> filter (should_encode_type ctxt mono level
blanchet@44264
  2456
                         o result_type_of_decl)
blanchet@43839
  2457
    in
blanchet@43839
  2458
      (0 upto length decls - 1, decls)
blanchet@48927
  2459
      |-> map2 (formula_line_for_guards_sym_decl ctxt mono type_enc n s)
blanchet@43839
  2460
    end
blanchet@45639
  2461
  | Tags (_, level) =>
blanchet@45673
  2462
    if granularity_of_type_level level = All_Vars then
blanchet@45639
  2463
      []
blanchet@45639
  2464
    else
blanchet@45639
  2465
      let val n = length decls in
blanchet@45639
  2466
        (0 upto n - 1 ~~ decls)
blanchet@48927
  2467
        |> maps (formula_lines_for_tags_sym_decl ctxt mono type_enc n s)
blanchet@45639
  2468
      end
blanchet@43450
  2469
blanchet@48927
  2470
fun problem_lines_for_sym_decl_table ctxt mono type_enc mono_Ts sym_decl_tab =
blanchet@45255
  2471
  let
blanchet@45255
  2472
    val syms = sym_decl_tab |> Symtab.dest |> sort_wrt fst
blanchet@48638
  2473
    val mono_lines = problem_lines_for_mono_types ctxt mono type_enc mono_Ts
blanchet@45255
  2474
    val decl_lines =
blanchet@48927
  2475
      fold_rev (append o problem_lines_for_sym_decls ctxt mono type_enc) syms []
blanchet@45255
  2476
  in mono_lines @ decl_lines end
blanchet@43414
  2477
blanchet@47220
  2478
fun pair_append (xs1, xs2) (ys1, ys2) = (xs1 @ ys1, xs2 @ ys2)
blanchet@47220
  2479
blanchet@49103
  2480
fun do_uncurried_alias_lines_for_sym ctxt constrs mono type_enc sym_tab0 sym_tab
blanchet@49103
  2481
                                     base_s0 types in_conj =
blanchet@47220
  2482
  let
blanchet@47220
  2483
    fun do_alias ary =
blanchet@47220
  2484
      let
blanchet@47220
  2485
        val thy = Proof_Context.theory_of ctxt
blanchet@48990
  2486
        val (role, maybe_negate) = honor_conj_sym_role in_conj
blanchet@48638
  2487
        val base_name = base_s0 |> `(make_fixed_const (SOME type_enc))
blanchet@47220
  2488
        val T = case types of [T] => T | _ => robust_const_type thy base_s0
blanchet@47220
  2489
        val T_args = robust_const_typargs thy (base_s0, T)
blanchet@47220
  2490
        val (base_name as (base_s, _), T_args) =
blanchet@48638
  2491
          mangle_type_args_in_const type_enc base_name T_args
blanchet@47230
  2492
        val base_ary = min_ary_of sym_tab0 base_s
blanchet@47220
  2493
        fun do_const name = IConst (name, T, T_args)
blanchet@49103
  2494
        val filter_ty_args = filter_type_args_in_iterm thy constrs type_enc
blanchet@48638
  2495
        val ho_term_of = ho_term_from_iterm ctxt mono type_enc (SOME true)
blanchet@47220
  2496
        val name1 as (s1, _) =
blanchet@47237
  2497
          base_name |> ary - 1 > base_ary ? aliased_uncurried (ary - 1)
blanchet@47237
  2498
        val name2 as (s2, _) = base_name |> aliased_uncurried ary
blanchet@47220
  2499
        val (arg_Ts, _) = chop_fun ary T
blanchet@47220
  2500
        val bound_names =
blanchet@47220
  2501
          1 upto ary |> map (`I o make_bound_var o string_of_int)
blanchet@47220
  2502
        val bounds = bound_names ~~ arg_Ts
blanchet@47220
  2503
        val (first_bounds, last_bound) =
blanchet@47220
  2504
          bounds |> map (fn (name, T) => IConst (name, T, [])) |> split_last
blanchet@47220
  2505
        val tm1 =
blanchet@48638
  2506
          mk_app_op type_enc (list_app (do_const name1) first_bounds) last_bound
blanchet@47265
  2507
          |> filter_ty_args
blanchet@47265
  2508
        val tm2 =
blanchet@47265
  2509
          list_app (do_const name2) (first_bounds @ [last_bound])
blanchet@47265
  2510
          |> filter_ty_args
blanchet@48638
  2511
        val do_bound_type = do_bound_type ctxt mono type_enc
blanchet@47220
  2512
        val eq =
blanchet@47220
  2513
          eq_formula type_enc (atomic_types_of T)
blanchet@47220
  2514
                     (map (apsnd do_bound_type) bounds) false
blanchet@47265
  2515
                     (ho_term_of tm1) (ho_term_of tm2)
blanchet@47220
  2516
      in
blanchet@47220
  2517
        ([tm1, tm2],
blanchet@48990
  2518
         [Formula (uncurried_alias_eq_prefix ^ s2, role, eq |> maybe_negate,
blanchet@48019
  2519
                   NONE, isabelle_info defN helper_rank)])
blanchet@47220
  2520
        |> (if ary - 1 = base_ary orelse Symtab.defined sym_tab s1 then I
blanchet@47220
  2521
            else pair_append (do_alias (ary - 1)))
blanchet@47220
  2522
      end
blanchet@47220
  2523
  in do_alias end
blanchet@49103
  2524
fun uncurried_alias_lines_for_sym ctxt constrs mono type_enc sym_tab0
blanchet@48927
  2525
        sym_tab (s, {min_ary, types, in_conj, ...} : sym_info) =
blanchet@47220
  2526
  case unprefix_and_unascii const_prefix s of
blanchet@47220
  2527
    SOME mangled_s =>
blanchet@47237
  2528
    if String.isSubstring uncurried_alias_sep mangled_s then
blanchet@47220
  2529
      let
blanchet@47220
  2530
        val base_s0 = mangled_s |> unmangled_const_name |> hd |> invert_const
blanchet@47220
  2531
      in
blanchet@49103
  2532
        do_uncurried_alias_lines_for_sym ctxt constrs mono type_enc sym_tab0
blanchet@49103
  2533
                                         sym_tab base_s0 types in_conj min_ary
blanchet@47220
  2534
      end
blanchet@47220
  2535
    else
blanchet@47220
  2536
      ([], [])
blanchet@47220
  2537
  | NONE => ([], [])
blanchet@49103
  2538
fun uncurried_alias_lines_for_sym_table ctxt constrs mono type_enc
blanchet@48927
  2539
                                        uncurried_aliases sym_tab0 sym_tab =
blanchet@47220
  2540
  ([], [])
blanchet@47237
  2541
  |> uncurried_aliases
blanchet@47230
  2542
     ? Symtab.fold_rev
blanchet@47230
  2543
           (pair_append
blanchet@49103
  2544
            o uncurried_alias_lines_for_sym ctxt constrs mono type_enc sym_tab0
blanchet@49103
  2545
                                            sym_tab) sym_tab
blanchet@47220
  2546
blanchet@43839
  2547
val implicit_declsN = "Should-be-implicit typings"
blanchet@43839
  2548
val explicit_declsN = "Explicit typings"
blanchet@47237
  2549
val uncurried_alias_eqsN = "Uncurried aliases"
blanchet@41405
  2550
val factsN = "Relevant facts"
blanchet@41405
  2551
val class_relsN = "Class relationships"
blanchet@43414
  2552
val aritiesN = "Arities"
blanchet@41405
  2553
val helpersN = "Helper facts"
blanchet@41405
  2554
val conjsN = "Conjectures"
blanchet@41561
  2555
val free_typesN = "Type variables"
blanchet@41405
  2556
blanchet@46698
  2557
(* TFF allows implicit declarations of types, function symbols, and predicate
blanchet@46698
  2558
   symbols (with "$i" as the type of individuals), but some provers (e.g.,
blanchet@46698
  2559
   SNARK) require explicit declarations. The situation is similar for THF. *)
blanchet@46698
  2560
blanchet@46746
  2561
fun default_type type_enc pred_sym s =
blanchet@46698
  2562
  let
blanchet@46698
  2563
    val ind =
blanchet@46746
  2564
      case type_enc of
blanchet@48637
  2565
        Native _ =>
blanchet@48016
  2566
        if String.isPrefix type_const_prefix s orelse
blanchet@48016
  2567
           String.isPrefix tfree_prefix s then
blanchet@48016
  2568
          atype_of_types
blanchet@48016
  2569
        else
blanchet@48016
  2570
          individual_atype
blanchet@46746
  2571
      | _ => individual_atype
blanchet@49148
  2572
    fun typ 0 0 = if pred_sym then bool_atype else ind
blanchet@49148
  2573
      | typ 0 tm_ary = AFun (ind, typ 0 (tm_ary - 1))
blanchet@49148
  2574
      | typ ty_ary tm_ary = APi (replicate ty_ary tvar_a_name, typ 0 tm_ary)
blanchet@46698
  2575
  in typ end
blanchet@46698
  2576
blanchet@46698
  2577
fun nary_type_constr_type n =
blanchet@46698
  2578
  funpow n (curry AFun atype_of_types) atype_of_types
blanchet@46698
  2579
blanchet@46746
  2580
fun undeclared_syms_in_problem type_enc problem =
blanchet@46698
  2581
  let
blanchet@47220
  2582
    fun do_sym (name as (s, _)) ty =
blanchet@48021
  2583
      if is_tptp_user_symbol s then
blanchet@48021
  2584
        Symtab.default (s, (name, ty))
blanchet@47220
  2585
      else
blanchet@47220
  2586
        I
blanchet@47220
  2587
    fun do_type (AType (name, tys)) =
blanchet@47220
  2588
        do_sym name (fn () => nary_type_constr_type (length tys))
blanchet@46698
  2589
        #> fold do_type tys
blanchet@46698
  2590
      | do_type (AFun (ty1, ty2)) = do_type ty1 #> do_type ty2
blanchet@49148
  2591
      | do_type (APi (_, ty)) = do_type ty
blanchet@49147
  2592
    fun do_term pred_sym (ATerm ((name as (s, _), tys), tms)) =
blanchet@49148
  2593
        do_sym name
blanchet@49148
  2594
            (fn _ => default_type type_enc pred_sym s (length tys) (length tms))
blanchet@49147
  2595
        #> fold do_type tys #> fold (do_term false) tms
blanchet@48926
  2596
      | do_term _ (AAbs (((_, ty), tm), args)) =
blanchet@48926
  2597
        do_type ty #> do_term false tm #> fold (do_term false) args
blanchet@49148
  2598
    fun do_formula (ATyQuant (_, _, phi)) = do_formula phi
blanchet@49148
  2599
      | do_formula (AQuant (_, xs, phi)) =
blanchet@46698
  2600
        fold do_type (map_filter snd xs) #> do_formula phi
blanchet@46698
  2601
      | do_formula (AConn (_, phis)) = fold do_formula phis
blanchet@46698
  2602
      | do_formula (AAtom tm) = do_term true tm
blanchet@46698
  2603
    fun do_problem_line (Decl (_, _, ty)) = do_type ty
blanchet@46698
  2604
      | do_problem_line (Formula (_, _, phi, _, _)) = do_formula phi
blanchet@46698
  2605
  in
blanchet@48021
  2606
    Symtab.empty
blanchet@48021
  2607
    |> fold (fn (s, _) => Symtab.default (s, (("", ""), K tvar_a_atype)))
blanchet@48021
  2608
            (declared_syms_in_problem problem)
blanchet@48021
  2609
    |> fold (fold do_problem_line o snd) problem
blanchet@46698
  2610
  end
blanchet@46698
  2611
blanchet@46746
  2612
fun declare_undeclared_syms_in_atp_problem type_enc problem =
blanchet@46698
  2613
  let
blanchet@46698
  2614
    val decls =
blanchet@48021
  2615
      Symtab.fold (fn (_, (("", ""), _)) => I (* already declared *)
blanchet@48021
  2616
                    | (s, (sym, ty)) =>
blanchet@48021
  2617
                      cons (Decl (type_decl_prefix ^ s, sym, ty ())))
blanchet@48021
  2618
                  (undeclared_syms_in_problem type_enc problem) []
blanchet@46698
  2619
  in (implicit_declsN, decls) :: problem end
blanchet@46698
  2620
blanchet@46816
  2621
fun exists_subdtype P =
blanchet@46816
  2622
  let
blanchet@46816
  2623
    fun ex U = P U orelse
blanchet@46816
  2624
      (case U of Datatype.DtType (_, Us) => exists ex Us | _ => false)
blanchet@46816
  2625
  in ex end
blanchet@46816
  2626
blanchet@49103
  2627
val is_poly_constr =
blanchet@49103
  2628
  exists_subdtype (fn Datatype.DtTFree _ => true | _ => false)
blanchet@46816
  2629
blanchet@46818
  2630
fun all_constrs_of_polymorphic_datatypes thy =
blanchet@49103
  2631
  Symtab.fold (snd #> #descr #> maps (#3 o snd)
blanchet@49103
  2632
               #> (fn cs => exists (exists is_poly_constr o snd) cs
blanchet@49103
  2633
                            ? append (map fst cs)))
blanchet@49103
  2634
               (Datatype.get_all thy) []
blanchet@46816
  2635
blanchet@47933
  2636
val app_op_and_predicator_threshold = 50
blanchet@44100
  2637
blanchet@48990
  2638
fun prepare_atp_problem ctxt format prem_role type_enc mode lam_trans
blanchet@48927
  2639
                        uncurried_aliases readable_names preproc hyp_ts concl_t
blanchet@48927
  2640
                        facts =
blanchet@38506
  2641
  let
blanchet@45645
  2642
    val thy = Proof_Context.theory_of ctxt
blanchet@45275
  2643
    val type_enc = type_enc |> adjust_type_enc format
blanchet@47217
  2644
    (* Forcing explicit applications is expensive for polymorphic encodings,
blanchet@47217
  2645
       because it takes only one existential variable ranging over "'a => 'b" to
blanchet@47217
  2646
       ruin everything. Hence we do it only if there are few facts (which is
blanchet@47217
  2647
       normally the case for "metis" and the minimizer). *)
blanchet@47220
  2648
    val app_op_level =
blanchet@48961
  2649
      if mode = Sledgehammer_Aggressive then
blanchet@48961
  2650
        Full_App_Op_And_Predicator
blanchet@48961
  2651
      else if length facts + length hyp_ts
blanchet@48961
  2652
              > app_op_and_predicator_threshold then
blanchet@49146
  2653
        if is_type_enc_polymorphic type_enc then Min_App_Op
blanchet@48926
  2654
        else Sufficient_App_Op
blanchet@47198
  2655
      else
blanchet@47933
  2656
        Sufficient_App_Op_And_Predicator
blanchet@48961
  2657
    val exporter = (mode = Exporter)
blanchet@48961
  2658
    val aggressive = (mode = Sledgehammer_Aggressive)
blanchet@46385
  2659
    val lam_trans =
blanchet@46391
  2660
      if lam_trans = keep_lamsN andalso
blanchet@46391
  2661
         not (is_type_enc_higher_order type_enc) then
blanchet@49111
  2662
        liftingN
blanchet@44959
  2663
      else
blanchet@46385
  2664
        lam_trans
blanchet@46379
  2665
    val (fact_names, classes, conjs, facts, class_rel_clauses, arity_clauses,
blanchet@46379
  2666
         lifted) =
blanchet@48990
  2667
      translate_formulas ctxt prem_role format type_enc lam_trans preproc hyp_ts
blanchet@46385
  2668
                         concl_t facts
blanchet@48947
  2669
    val (_, sym_tab0) =
blanchet@48947
  2670
      sym_table_for_facts ctxt type_enc app_op_level conjs facts
blanchet@49120
  2671
    val mono =
blanchet@49120
  2672
      conjs @ facts |> mononotonicity_info_for_facts ctxt type_enc aggressive
blanchet@49103
  2673
    val constrs = all_constrs_of_polymorphic_datatypes thy
blanchet@47228
  2674
    fun firstorderize in_helper =
blanchet@49103
  2675
      firstorderize_fact thy constrs type_enc sym_tab0
blanchet@48961
  2676
          (uncurried_aliases andalso not in_helper) aggressive
blanchet@47228
  2677
    val (conjs, facts) = (conjs, facts) |> pairself (map (firstorderize false))
blanchet@48947
  2678
    val (ho_stuff, sym_tab) =
blanchet@48947
  2679
      sym_table_for_facts ctxt type_enc Min_App_Op conjs facts
blanchet@48947
  2680
    val (uncurried_alias_eq_tms, uncurried_alias_eq_lines) =
blanchet@49103
  2681
      uncurried_alias_lines_for_sym_table ctxt constrs mono type_enc
blanchet@48947
  2682
                                          uncurried_aliases sym_tab0 sym_tab
blanchet@48947
  2683
    val (_, sym_tab) =
blanchet@48947
  2684
      (ho_stuff, sym_tab)
blanchet@48947
  2685
      |> fold (add_iterm_syms_to_sym_table ctxt Min_App_Op false false)
blanchet@48947
  2686
              uncurried_alias_eq_tms
blanchet@43444
  2687
    val helpers =
blanchet@48961
  2688
      sym_tab |> helper_facts_for_sym_table ctxt format type_enc aggressive
blanchet@47228
  2689
              |> map (firstorderize true)
blanchet@45356
  2690
    val mono_Ts =
blanchet@46808
  2691
      helpers @ conjs @ facts |> monotonic_types_for_facts ctxt mono type_enc
blanchet@45459
  2692
    val class_decl_lines = decl_lines_for_classes type_enc classes
blanchet@43550
  2693
    val sym_decl_lines =
blanchet@47237
  2694
      (conjs, helpers @ facts, uncurried_alias_eq_tms)
blanchet@48638
  2695
      |> sym_decl_table_for_facts thy type_enc sym_tab
blanchet@48927
  2696
      |> problem_lines_for_sym_decl_table ctxt mono type_enc mono_Ts
blanchet@47234
  2697
    val num_facts = length facts
blanchet@47234
  2698
    val fact_lines =
blanchet@49102
  2699
      map (formula_line_for_fact ctxt fact_prefix ascii_of (not exporter)
blanchet@49102
  2700
               (not exporter) mono type_enc (rank_of_fact_num num_facts))
blanchet@47234
  2701
          (0 upto num_facts - 1 ~~ facts)
blanchet@49146
  2702
    val class_rel_lines =
blanchet@49146
  2703
      map (formula_line_for_class_rel_clause type_enc) class_rel_clauses
blanchet@43750
  2704
    val helper_lines =
blanchet@43797
  2705
      0 upto length helpers - 1 ~~ helpers
blanchet@49102
  2706
      |> map (formula_line_for_fact ctxt helper_prefix I false true mono
blanchet@49102
  2707
                                    type_enc (K default_rank))
blanchet@49020
  2708
    (* Reordering these might confuse the proof reconstruction code. *)
blanchet@38506
  2709
    val problem =
blanchet@45459
  2710
      [(explicit_declsN, class_decl_lines @ sym_decl_lines),
blanchet@47237
  2711
       (uncurried_alias_eqsN, uncurried_alias_eq_lines),
blanchet@47234
  2712
       (factsN, fact_lines),
blanchet@49146
  2713
       (class_relsN, class_rel_lines),
blanchet@47909
  2714
       (aritiesN, map (formula_line_for_arity_clause type_enc) arity_clauses),
blanchet@43750
  2715
       (helpersN, helper_lines),
blanchet@47514
  2716
       (free_typesN, formula_lines_for_free_types type_enc (facts @ conjs)),
blanchet@49102
  2717
       (conjsN, map (formula_line_for_conjecture ctxt mono type_enc) conjs)]
blanchet@43414
  2718
    val problem =
blanchet@43432
  2719
      problem
blanchet@43933
  2720
      |> (case format of
blanchet@43933
  2721
            CNF => ensure_cnf_problem
blanchet@43933
  2722
          | CNF_UEQ => filter_cnf_ueq_problem
blanchet@45453
  2723
          | FOF => I
blanchet@45618
  2724
          | TFF (_, TPTP_Implicit) => I
blanchet@49019
  2725
          | THF (_, TPTP_Implicit, _, _) => I
blanchet@46746
  2726
          | _ => declare_undeclared_syms_in_atp_problem type_enc)
blanchet@46810
  2727
    val (problem, pool) = problem |> nice_atp_problem readable_names format
blanchet@45643
  2728
    fun add_sym_ary (s, {min_ary, ...} : sym_info) =
blanchet@45644
  2729
      min_ary > 0 ? Symtab.insert (op =) (s, min_ary)
blanchet@38506
  2730
  in
blanchet@49111
  2731
    (problem, pool |> Option.map snd |> the_default Symtab.empty,
blanchet@49111
  2732
     fact_names |> Vector.fromList, lifted,
blanchet@45643
  2733
     Symtab.empty |> Symtab.fold add_sym_ary sym_tab)
blanchet@38506
  2734
  end
blanchet@38506
  2735
blanchet@41561
  2736
(* FUDGE *)
blanchet@41561
  2737
val conj_weight = 0.0
blanchet@42641
  2738
val hyp_weight = 0.1
blanchet@42641
  2739
val fact_min_weight = 0.2
blanchet@41561
  2740
val fact_max_weight = 1.0
blanchet@43479
  2741
val type_info_default_weight = 0.8
blanchet@41561
  2742
blanchet@47270
  2743
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@47901
  2744
fun atp_problem_selection_weights problem =
blanchet@41561
  2745
  let
blanchet@49147
  2746
    fun add_term_weights weight (ATerm ((s, _), tms)) =
blanchet@47270
  2747
        is_tptp_user_symbol s ? Symtab.default (s, weight)
blanchet@47270
  2748
        #> fold (add_term_weights weight) tms
blanchet@48926
  2749
      | add_term_weights weight (AAbs ((_, tm), args)) =
blanchet@48926
  2750
        add_term_weights weight tm #> fold (add_term_weights weight) args
blanchet@47270
  2751
    fun add_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@47270
  2752
        formula_fold NONE (K (add_term_weights weight)) phi
blanchet@47270
  2753
      | add_line_weights _ _ = I
blanchet@47270
  2754
    fun add_conjectures_weights [] = I
blanchet@47270
  2755
      | add_conjectures_weights conjs =
blanchet@47270
  2756
        let val (hyps, conj) = split_last conjs in
blanchet@47270
  2757
          add_line_weights conj_weight conj
blanchet@47270
  2758
          #> fold (add_line_weights hyp_weight) hyps
blanchet@47270
  2759
        end
blanchet@47270
  2760
    fun add_facts_weights facts =
blanchet@47270
  2761
      let
blanchet@47270
  2762
        val num_facts = length facts
blanchet@47270
  2763
        fun weight_of j =
blanchet@47270
  2764
          fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@47270
  2765
                            / Real.fromInt num_facts
blanchet@47270
  2766
      in
blanchet@47270
  2767
        map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@47270
  2768
        |> fold (uncurry add_line_weights)
blanchet@47270
  2769
      end
blanchet@47270
  2770
    val get = these o AList.lookup (op =) problem
blanchet@41561
  2771
  in
blanchet@43479
  2772
    Symtab.empty
blanchet@43479
  2773
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@43479
  2774
    |> add_facts_weights (get factsN)
blanchet@47270
  2775
    |> fold (fold (add_line_weights type_info_default_weight) o get)
blanchet@43839
  2776
            [explicit_declsN, class_relsN, aritiesN]
blanchet@43479
  2777
    |> Symtab.dest
blanchet@43479
  2778
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@43479
  2779
  end
blanchet@41561
  2780
blanchet@47933
  2781
(* Ugly hack: may make innocent victims (collateral damage) *)
blanchet@47933
  2782
fun may_be_app s args = String.isPrefix app_op_name s andalso length args = 2
blanchet@47933
  2783
fun may_be_predicator s =
blanchet@47933
  2784
  member (op =) [predicator_name, prefixed_predicator_name] s
blanchet@47933
  2785
blanchet@49147
  2786
fun strip_predicator (tm as ATerm ((s, _), [tm'])) =
blanchet@47933
  2787
    if may_be_predicator s then tm' else tm
blanchet@47933
  2788
  | strip_predicator tm = tm
blanchet@47933
  2789
blanchet@49147
  2790
fun make_head_roll (ATerm ((s, _), tms)) =
blanchet@47933
  2791
    if may_be_app s tms then make_head_roll (hd tms) ||> append (tl tms)
blanchet@47933
  2792
    else (s, tms)
blanchet@47903
  2793
  | make_head_roll _ = ("", [])
blanchet@47271
  2794
blanchet@49148
  2795
fun strip_up_to_predicator (ATyQuant (_, _, phi)) = strip_up_to_predicator phi
blanchet@49148
  2796
  | strip_up_to_predicator (AQuant (_, _, phi)) = strip_up_to_predicator phi
blanchet@47933
  2797
  | strip_up_to_predicator (AConn (_, phis)) = maps strip_up_to_predicator phis
blanchet@47933
  2798
  | strip_up_to_predicator (AAtom tm) = [strip_predicator tm]
blanchet@47933
  2799
blanchet@49148
  2800
fun strip_ahorn_etc (ATyQuant (_, _, phi)) = strip_ahorn_etc phi
blanchet@49148
  2801
  | strip_ahorn_etc (AQuant (_, _, phi)) = strip_ahorn_etc phi
blanchet@47933
  2802
  | strip_ahorn_etc (AConn (AImplies, [phi1, phi2])) =
blanchet@47933
  2803
    strip_ahorn_etc phi2 |>> append (strip_up_to_predicator phi1)
blanchet@47933
  2804
  | strip_ahorn_etc phi = ([], hd (strip_up_to_predicator phi))
blanchet@47933
  2805
blanchet@49148
  2806
fun strip_iff_etc (ATyQuant (_, _, phi)) = strip_iff_etc phi
blanchet@49148
  2807
  | strip_iff_etc (AQuant (_, _, phi)) = strip_iff_etc phi
blanchet@47933
  2808
  | strip_iff_etc (AConn (AIff, [phi1, phi2])) =
blanchet@47933
  2809
    pairself strip_up_to_predicator (phi1, phi2)
blanchet@47933
  2810
  | strip_iff_etc _ = ([], [])
blanchet@47933
  2811
blanchet@47901
  2812
val max_term_order_weight = 2147483647
blanchet@47278
  2813
blanchet@47909
  2814
fun atp_problem_term_order_info problem =
blanchet@47270
  2815
  let
blanchet@47909
  2816
    fun add_edge s s' =
blanchet@47909
  2817
      Graph.default_node (s, ())
blanchet@47909
  2818
      #> Graph.default_node (s', ())
blanchet@47909
  2819
      #> Graph.add_edge_acyclic (s, s')
blanchet@49147
  2820
    fun add_term_deps head (ATerm ((s, _), args)) =
blanchet@47933
  2821
        if is_tptp_user_symbol head then
blanchet@47933
  2822
          (if is_tptp_user_symbol s then perhaps (try (add_edge s head)) else I)
blanchet@47933
  2823
          #> fold (add_term_deps head) args
blanchet@47933
  2824
        else
blanchet@47933
  2825
          I
blanchet@48926
  2826
      | add_term_deps head (AAbs ((_, tm), args)) =
blanchet@48926
  2827
        add_term_deps head tm #> fold (add_term_deps head) args
blanchet@47933
  2828
    fun add_intro_deps pred (Formula (_, role, phi, _, info)) =
blanchet@47933
  2829
        if pred (role, info) then
blanchet@47933
  2830
          let val (hyps, concl) = strip_ahorn_etc phi in
blanchet@47933
  2831
            case make_head_roll concl of
blanchet@47933
  2832
              (head, args as _ :: _) => fold (add_term_deps head) (hyps @ args)
blanchet@47933
  2833
            | _ => I
blanchet@47933
  2834
          end
blanchet@47933
  2835
        else
blanchet@47933
  2836
          I
blanchet@47933
  2837
      | add_intro_deps _ _ = I
blanchet@49147
  2838
    fun add_atom_eq_deps (SOME true) (ATerm ((s, _), [lhs as _, rhs])) =
blanchet@47271
  2839
        if is_tptp_equal s then
blanchet@47909
  2840
          case make_head_roll lhs of
blanchet@47933
  2841
            (head, args as _ :: _) => fold (add_term_deps head) (rhs :: args)
blanchet@47909
  2842
          | _ => I
blanchet@47271
  2843
        else
blanchet@47271
  2844
          I
blanchet@47933
  2845
      | add_atom_eq_deps _ _ = I
blanchet@47933
  2846
    fun add_eq_deps pred (Formula (_, role, phi, _, info)) =
blanchet@47910
  2847
        if pred (role, info) then
blanchet@47933
  2848
          case strip_iff_etc phi of
blanchet@47933
  2849
            ([lhs], rhs) =>
blanchet@47933
  2850
            (case make_head_roll lhs of
blanchet@47933
  2851
               (head, args as _ :: _) => fold (add_term_deps head) (rhs @ args)
blanchet@47933
  2852
             | _ => I)
blanchet@47933
  2853
          | _ => formula_fold (SOME (role <> Conjecture)) add_atom_eq_deps phi
blanchet@47270
  2854
        else
blanchet@47270
  2855
          I
blanchet@47933
  2856
      | add_eq_deps _ _ = I
blanchet@48986
  2857
    fun has_status status (_, info) = extract_isabelle_status info = SOME status
blanchet@47910
  2858
    fun is_conj (role, _) = (role = Conjecture orelse role = Hypothesis)
blanchet@47270
  2859
    val graph =
blanchet@47910
  2860
      Graph.empty
blanchet@48019
  2861
      |> fold (fold (add_eq_deps (has_status defN)) o snd) problem
blanchet@47933
  2862
      |> fold (fold (add_eq_deps (has_status simpN orf is_conj)) o snd) problem
blanchet@48019
  2863
      |> fold (fold (add_intro_deps (has_status inductiveN)) o snd) problem
blanchet@47933
  2864
      |> fold (fold (add_intro_deps (has_status introN)) o snd) problem
blanchet@47901
  2865
    fun next_weight w = if w + w <= max_term_order_weight then w + w else w + 1
blanchet@47270
  2866
    fun add_weights _ [] = I
blanchet@47270
  2867
      | add_weights weight syms =
blanchet@47270
  2868
        fold (AList.update (op =) o rpair weight) syms
blanchet@47270
  2869
        #> add_weights (next_weight weight)
blanchet@47270
  2870
               (fold (union (op =) o Graph.immediate_succs graph) syms [])
blanchet@47270
  2871
  in
blanchet@47909
  2872
    (* Sorting is not just for aesthetics: It specifies the precedence order
blanchet@47909
  2873
       for the term ordering (KBO or LPO), from smaller to larger values. *)
blanchet@47274
  2874
    [] |> add_weights 1 (Graph.minimals graph) |> sort (int_ord o pairself snd)
blanchet@47270
  2875
  end
blanchet@47270
  2876
blanchet@38506
  2877
end;