src/HOL/Tools/ATP/atp_translate.ML
author blanchet
Tue, 31 May 2011 16:38:36 +0200
changeset 43933 93ec303e1917
parent 43927 4dce7f2bb59f
child 43934 40e50afbc203
permissions -rw-r--r--
more work on new metis that exploits the powerful new type encodings
blanchet@40358
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_atp_translate.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@39734
     6
Translation of HOL to FOL for Sledgehammer.
blanchet@38506
     7
*)
blanchet@38506
     8
blanchet@43926
     9
signature ATP_TRANSLATE =
blanchet@38506
    10
sig
blanchet@43088
    11
  type 'a fo_term = 'a ATP_Problem.fo_term
blanchet@43780
    12
  type format = ATP_Problem.format
blanchet@43580
    13
  type formula_kind = ATP_Problem.formula_kind
blanchet@38506
    14
  type 'a problem = 'a ATP_Problem.problem
blanchet@43926
    15
blanchet@43926
    16
  type name = string * string
blanchet@43926
    17
blanchet@43926
    18
  datatype type_literal =
blanchet@43926
    19
    TyLitVar of name * name |
blanchet@43926
    20
    TyLitFree of name * name
blanchet@43926
    21
blanchet@43926
    22
  datatype arity_literal =
blanchet@43926
    23
    TConsLit of name * name * name list |
blanchet@43926
    24
    TVarLit of name * name
blanchet@43926
    25
blanchet@43927
    26
  type arity_clause =
blanchet@43927
    27
    {name: string,
blanchet@43927
    28
     prem_lits: arity_literal list,
blanchet@43927
    29
     concl_lits: arity_literal}
blanchet@43926
    30
blanchet@43927
    31
  type class_rel_clause =
blanchet@43927
    32
    {name: string,
blanchet@43927
    33
     subclass: name,
blanchet@43927
    34
     superclass: name}
blanchet@43926
    35
blanchet@43926
    36
  datatype combterm =
blanchet@43926
    37
    CombConst of name * typ * typ list |
blanchet@43926
    38
    CombVar of name * typ |
blanchet@43926
    39
    CombApp of combterm * combterm
blanchet@43926
    40
blanchet@43926
    41
  datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@43484
    42
blanchet@43484
    43
  datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@43484
    44
  datatype type_level =
blanchet@43484
    45
    All_Types | Nonmonotonic_Types | Finite_Types | Const_Arg_Types | No_Types
blanchet@43708
    46
  datatype type_heaviness = Heavy | Light
blanchet@43484
    47
blanchet@43484
    48
  datatype type_system =
blanchet@43587
    49
    Simple_Types of type_level |
blanchet@43708
    50
    Preds of polymorphism * type_level * type_heaviness |
blanchet@43708
    51
    Tags of polymorphism * type_level * type_heaviness
blanchet@43484
    52
blanchet@40358
    53
  type translated_formula
blanchet@38506
    54
blanchet@43926
    55
  val type_tag_name : string
blanchet@43926
    56
  val bound_var_prefix : string
blanchet@43926
    57
  val schematic_var_prefix: string
blanchet@43926
    58
  val fixed_var_prefix: string
blanchet@43926
    59
  val tvar_prefix: string
blanchet@43926
    60
  val tfree_prefix: string
blanchet@43926
    61
  val const_prefix: string
blanchet@43926
    62
  val type_const_prefix: string
blanchet@43926
    63
  val class_prefix: string
blanchet@43926
    64
  val skolem_const_prefix : string
blanchet@43926
    65
  val old_skolem_const_prefix : string
blanchet@43926
    66
  val new_skolem_const_prefix : string
blanchet@40445
    67
  val fact_prefix : string
blanchet@38506
    68
  val conjecture_prefix : string
blanchet@43750
    69
  val helper_prefix : string
blanchet@43750
    70
  val typed_helper_suffix : string
blanchet@43807
    71
  val predicator_name : string
blanchet@43807
    72
  val app_op_name : string
blanchet@43807
    73
  val type_pred_name : string
blanchet@43803
    74
  val simple_type_prefix : string
blanchet@43926
    75
  val ascii_of: string -> string
blanchet@43926
    76
  val unascii_of: string -> string
blanchet@43926
    77
  val strip_prefix_and_unascii : string -> string -> string option
blanchet@43926
    78
  val proxify_const : string -> (int * (string * string)) option
blanchet@43926
    79
  val invert_const: string -> string
blanchet@43926
    80
  val unproxify_const: string -> string
blanchet@43926
    81
  val make_bound_var : string -> string
blanchet@43926
    82
  val make_schematic_var : string * int -> string
blanchet@43926
    83
  val make_fixed_var : string -> string
blanchet@43926
    84
  val make_schematic_type_var : string * int -> string
blanchet@43926
    85
  val make_fixed_type_var : string -> string
blanchet@43926
    86
  val make_fixed_const : string -> string
blanchet@43926
    87
  val make_fixed_type_const : string -> string
blanchet@43926
    88
  val make_type_class : string -> string
blanchet@43926
    89
  val make_arity_clauses :
blanchet@43926
    90
    theory -> string list -> class list -> class list * arity_clause list
blanchet@43926
    91
  val make_class_rel_clauses :
blanchet@43926
    92
    theory -> class list -> class list -> class_rel_clause list
blanchet@43926
    93
  val combtyp_of : combterm -> typ
blanchet@43926
    94
  val strip_combterm_comb : combterm -> combterm * combterm list
blanchet@43926
    95
  val atyps_of : typ -> typ list
blanchet@43926
    96
  val combterm_from_term :
blanchet@43926
    97
    theory -> (string * typ) list -> term -> combterm * typ list
blanchet@43926
    98
  val is_locality_global : locality -> bool
blanchet@43484
    99
  val type_sys_from_string : string -> type_system
blanchet@43484
   100
  val polymorphism_of_type_sys : type_system -> polymorphism
blanchet@43484
   101
  val level_of_type_sys : type_system -> type_level
blanchet@43484
   102
  val is_type_sys_virtually_sound : type_system -> bool
blanchet@43484
   103
  val is_type_sys_fairly_sound : type_system -> bool
blanchet@43926
   104
  val raw_type_literals_for_types : typ list -> type_literal list
blanchet@43413
   105
  val unmangled_const : string -> string * string fo_term list
blanchet@41336
   106
  val translate_atp_fact :
blanchet@43835
   107
    Proof.context -> format -> type_system -> bool -> (string * locality) * thm
blanchet@43511
   108
    -> translated_formula option * ((string * locality) * thm)
blanchet@43926
   109
  val helper_table : (string * (bool * thm list)) list
blanchet@43926
   110
  val tfree_classes_of_terms : term list -> string list
blanchet@43926
   111
  val tvar_classes_of_terms : term list -> string list
blanchet@43926
   112
  val type_consts_of_terms : theory -> term list -> string list
blanchet@40240
   113
  val prepare_atp_problem :
blanchet@43780
   114
    Proof.context -> format -> formula_kind -> formula_kind -> type_system
blanchet@43933
   115
    -> bool option -> bool -> term list -> term
blanchet@41339
   116
    -> (translated_formula option * ((string * 'a) * thm)) list
blanchet@43412
   117
    -> string problem * string Symtab.table * int * int
blanchet@43750
   118
       * (string * 'a) list vector * int list * int Symtab.table
blanchet@41561
   119
  val atp_problem_weights : string problem -> (string * real) list
blanchet@38506
   120
end;
blanchet@38506
   121
blanchet@43926
   122
structure ATP_Translate : ATP_TRANSLATE =
blanchet@38506
   123
struct
blanchet@38506
   124
blanchet@43926
   125
open ATP_Util
blanchet@38506
   126
open ATP_Problem
blanchet@43926
   127
blanchet@43926
   128
type name = string * string
blanchet@43926
   129
blanchet@43926
   130
(* FIXME: avoid *)
blanchet@43926
   131
fun union_all xss = fold (union (op =)) xss []
blanchet@43511
   132
blanchet@43511
   133
(* experimental *)
blanchet@43511
   134
val generate_useful_info = false
blanchet@38506
   135
blanchet@43748
   136
fun useful_isabelle_info s =
blanchet@43748
   137
  if generate_useful_info then
blanchet@43748
   138
    SOME (ATerm ("[]", [ATerm ("isabelle_" ^ s, [])]))
blanchet@43748
   139
  else
blanchet@43748
   140
    NONE
blanchet@43748
   141
blanchet@43748
   142
val intro_info = useful_isabelle_info "intro"
blanchet@43748
   143
val elim_info = useful_isabelle_info "elim"
blanchet@43748
   144
val simp_info = useful_isabelle_info "simp"
blanchet@43748
   145
blanchet@43926
   146
val type_tag_name = "ti"
blanchet@43926
   147
blanchet@43926
   148
val bound_var_prefix = "B_"
blanchet@43926
   149
val schematic_var_prefix = "V_"
blanchet@43926
   150
val fixed_var_prefix = "v_"
blanchet@43926
   151
blanchet@43926
   152
val tvar_prefix = "T_"
blanchet@43926
   153
val tfree_prefix = "t_"
blanchet@43926
   154
blanchet@43926
   155
val const_prefix = "c_"
blanchet@43926
   156
val type_const_prefix = "tc_"
blanchet@43926
   157
val class_prefix = "cl_"
blanchet@43926
   158
blanchet@43926
   159
val skolem_const_prefix = "Sledgehammer" ^ Long_Name.separator ^ "Sko"
blanchet@43926
   160
val old_skolem_const_prefix = skolem_const_prefix ^ "o"
blanchet@43926
   161
val new_skolem_const_prefix = skolem_const_prefix ^ "n"
blanchet@43926
   162
blanchet@43839
   163
val type_decl_prefix = "ty_"
blanchet@43839
   164
val sym_decl_prefix = "sy_"
blanchet@43839
   165
val sym_formula_prefix = "sym_"
blanchet@40445
   166
val fact_prefix = "fact_"
blanchet@38506
   167
val conjecture_prefix = "conj_"
blanchet@38506
   168
val helper_prefix = "help_"
blanchet@43414
   169
val class_rel_clause_prefix = "crel_";
blanchet@38506
   170
val arity_clause_prefix = "arity_"
blanchet@43926
   171
val tfree_clause_prefix = "tfree_"
blanchet@38506
   172
blanchet@43750
   173
val typed_helper_suffix = "_T"
blanchet@43750
   174
val untyped_helper_suffix = "_U"
blanchet@43750
   175
blanchet@43807
   176
val predicator_name = "hBOOL"
blanchet@43807
   177
val app_op_name = "hAPP"
blanchet@43807
   178
val type_pred_name = "is"
blanchet@43803
   179
val simple_type_prefix = "ty_"
blanchet@43402
   180
blanchet@38506
   181
(* Freshness almost guaranteed! *)
blanchet@38506
   182
val sledgehammer_weak_prefix = "Sledgehammer:"
blanchet@38506
   183
blanchet@43926
   184
(*Escaping of special characters.
blanchet@43926
   185
  Alphanumeric characters are left unchanged.
blanchet@43926
   186
  The character _ goes to __
blanchet@43926
   187
  Characters in the range ASCII space to / go to _A to _P, respectively.
blanchet@43926
   188
  Other characters go to _nnn where nnn is the decimal ASCII code.*)
blanchet@43926
   189
val upper_a_minus_space = Char.ord #"A" - Char.ord #" ";
blanchet@43926
   190
blanchet@43926
   191
fun stringN_of_int 0 _ = ""
blanchet@43926
   192
  | stringN_of_int k n =
blanchet@43926
   193
    stringN_of_int (k - 1) (n div 10) ^ string_of_int (n mod 10)
blanchet@43926
   194
blanchet@43926
   195
fun ascii_of_char c =
blanchet@43926
   196
  if Char.isAlphaNum c then
blanchet@43926
   197
    String.str c
blanchet@43926
   198
  else if c = #"_" then
blanchet@43926
   199
    "__"
blanchet@43926
   200
  else if #" " <= c andalso c <= #"/" then
blanchet@43926
   201
    "_" ^ String.str (Char.chr (Char.ord c + upper_a_minus_space))
blanchet@43926
   202
  else
blanchet@43926
   203
    (* fixed width, in case more digits follow *)
blanchet@43926
   204
    "_" ^ stringN_of_int 3 (Char.ord c)
blanchet@43926
   205
blanchet@43926
   206
val ascii_of = String.translate ascii_of_char
blanchet@43926
   207
blanchet@43926
   208
(** Remove ASCII armoring from names in proof files **)
blanchet@43926
   209
blanchet@43926
   210
(* We don't raise error exceptions because this code can run inside a worker
blanchet@43926
   211
   thread. Also, the errors are impossible. *)
blanchet@43926
   212
val unascii_of =
blanchet@43926
   213
  let
blanchet@43926
   214
    fun un rcs [] = String.implode(rev rcs)
blanchet@43926
   215
      | un rcs [#"_"] = un (#"_" :: rcs) [] (* ERROR *)
blanchet@43926
   216
        (* Three types of _ escapes: __, _A to _P, _nnn *)
blanchet@43926
   217
      | un rcs (#"_" :: #"_" :: cs) = un (#"_"::rcs) cs
blanchet@43926
   218
      | un rcs (#"_" :: c :: cs) =
blanchet@43926
   219
        if #"A" <= c andalso c<= #"P" then
blanchet@43926
   220
          (* translation of #" " to #"/" *)
blanchet@43926
   221
          un (Char.chr (Char.ord c - upper_a_minus_space) :: rcs) cs
blanchet@43926
   222
        else
blanchet@43926
   223
          let val digits = List.take (c::cs, 3) handle Subscript => [] in
blanchet@43926
   224
            case Int.fromString (String.implode digits) of
blanchet@43926
   225
              SOME n => un (Char.chr n :: rcs) (List.drop (cs, 2))
blanchet@43926
   226
            | NONE => un (c:: #"_"::rcs) cs (* ERROR *)
blanchet@43926
   227
          end
blanchet@43926
   228
      | un rcs (c :: cs) = un (c :: rcs) cs
blanchet@43926
   229
  in un [] o String.explode end
blanchet@43926
   230
blanchet@43926
   231
(* If string s has the prefix s1, return the result of deleting it,
blanchet@43926
   232
   un-ASCII'd. *)
blanchet@43926
   233
fun strip_prefix_and_unascii s1 s =
blanchet@43926
   234
  if String.isPrefix s1 s then
blanchet@43926
   235
    SOME (unascii_of (String.extract (s, size s1, NONE)))
blanchet@43926
   236
  else
blanchet@43926
   237
    NONE
blanchet@43926
   238
blanchet@43926
   239
val proxies =
blanchet@43926
   240
  [("c_False",
blanchet@43926
   241
    (@{const_name False}, (0, ("fFalse", @{const_name ATP.fFalse})))),
blanchet@43926
   242
   ("c_True", (@{const_name True}, (0, ("fTrue", @{const_name ATP.fTrue})))),
blanchet@43926
   243
   ("c_Not", (@{const_name Not}, (1, ("fNot", @{const_name ATP.fNot})))),
blanchet@43926
   244
   ("c_conj", (@{const_name conj}, (2, ("fconj", @{const_name ATP.fconj})))),
blanchet@43926
   245
   ("c_disj", (@{const_name disj}, (2, ("fdisj", @{const_name ATP.fdisj})))),
blanchet@43926
   246
   ("c_implies",
blanchet@43926
   247
    (@{const_name implies}, (2, ("fimplies", @{const_name ATP.fimplies})))),
blanchet@43926
   248
   ("equal",
blanchet@43926
   249
    (@{const_name HOL.eq}, (2, ("fequal", @{const_name ATP.fequal}))))]
blanchet@43926
   250
blanchet@43926
   251
val proxify_const = AList.lookup (op =) proxies #> Option.map snd
blanchet@43926
   252
blanchet@43926
   253
(* Readable names for the more common symbolic functions. Do not mess with the
blanchet@43926
   254
   table unless you know what you are doing. *)
blanchet@43926
   255
val const_trans_table =
blanchet@43926
   256
  [(@{type_name Product_Type.prod}, "prod"),
blanchet@43926
   257
   (@{type_name Sum_Type.sum}, "sum"),
blanchet@43926
   258
   (@{const_name False}, "False"),
blanchet@43926
   259
   (@{const_name True}, "True"),
blanchet@43926
   260
   (@{const_name Not}, "Not"),
blanchet@43926
   261
   (@{const_name conj}, "conj"),
blanchet@43926
   262
   (@{const_name disj}, "disj"),
blanchet@43926
   263
   (@{const_name implies}, "implies"),
blanchet@43926
   264
   (@{const_name HOL.eq}, "equal"),
blanchet@43926
   265
   (@{const_name If}, "If"),
blanchet@43926
   266
   (@{const_name Set.member}, "member"),
blanchet@43926
   267
   (@{const_name Meson.COMBI}, "COMBI"),
blanchet@43926
   268
   (@{const_name Meson.COMBK}, "COMBK"),
blanchet@43926
   269
   (@{const_name Meson.COMBB}, "COMBB"),
blanchet@43926
   270
   (@{const_name Meson.COMBC}, "COMBC"),
blanchet@43926
   271
   (@{const_name Meson.COMBS}, "COMBS")]
blanchet@43926
   272
  |> Symtab.make
blanchet@43926
   273
  |> fold (Symtab.update o swap o snd o snd o snd) proxies
blanchet@43926
   274
blanchet@43926
   275
(* Invert the table of translations between Isabelle and ATPs. *)
blanchet@43926
   276
val const_trans_table_inv =
blanchet@43926
   277
  const_trans_table |> Symtab.dest |> map swap |> Symtab.make
blanchet@43926
   278
val const_trans_table_unprox =
blanchet@43926
   279
  Symtab.empty
blanchet@43926
   280
  |> fold (fn (_, (isa, (_, (_, metis)))) => Symtab.update (metis, isa)) proxies
blanchet@43926
   281
blanchet@43926
   282
val invert_const = perhaps (Symtab.lookup const_trans_table_inv)
blanchet@43926
   283
val unproxify_const = perhaps (Symtab.lookup const_trans_table_unprox)
blanchet@43926
   284
blanchet@43926
   285
fun lookup_const c =
blanchet@43926
   286
  case Symtab.lookup const_trans_table c of
blanchet@43926
   287
    SOME c' => c'
blanchet@43926
   288
  | NONE => ascii_of c
blanchet@43926
   289
blanchet@43926
   290
(*Remove the initial ' character from a type variable, if it is present*)
blanchet@43926
   291
fun trim_type_var s =
blanchet@43926
   292
  if s <> "" andalso String.sub(s,0) = #"'" then String.extract(s,1,NONE)
blanchet@43926
   293
  else raise Fail ("trim_type: Malformed type variable encountered: " ^ s)
blanchet@43926
   294
blanchet@43926
   295
fun ascii_of_indexname (v,0) = ascii_of v
blanchet@43926
   296
  | ascii_of_indexname (v,i) = ascii_of v ^ "_" ^ string_of_int i
blanchet@43926
   297
blanchet@43926
   298
fun make_bound_var x = bound_var_prefix ^ ascii_of x
blanchet@43926
   299
fun make_schematic_var v = schematic_var_prefix ^ ascii_of_indexname v
blanchet@43926
   300
fun make_fixed_var x = fixed_var_prefix ^ ascii_of x
blanchet@43926
   301
blanchet@43926
   302
fun make_schematic_type_var (x,i) =
blanchet@43926
   303
      tvar_prefix ^ (ascii_of_indexname (trim_type_var x, i))
blanchet@43926
   304
fun make_fixed_type_var x = tfree_prefix ^ (ascii_of (trim_type_var x))
blanchet@43926
   305
blanchet@43926
   306
(* HOL.eq MUST BE "equal" because it's built into ATPs. *)
blanchet@43926
   307
fun make_fixed_const @{const_name HOL.eq} = "equal"
blanchet@43926
   308
  | make_fixed_const c = const_prefix ^ lookup_const c
blanchet@43926
   309
blanchet@43926
   310
fun make_fixed_type_const c = type_const_prefix ^ lookup_const c
blanchet@43926
   311
blanchet@43926
   312
fun make_type_class clas = class_prefix ^ ascii_of clas
blanchet@43926
   313
blanchet@43926
   314
(** Definitions and functions for FOL clauses and formulas for TPTP **)
blanchet@43926
   315
blanchet@43926
   316
(* The first component is the type class; the second is a "TVar" or "TFree". *)
blanchet@43926
   317
datatype type_literal =
blanchet@43926
   318
  TyLitVar of name * name |
blanchet@43926
   319
  TyLitFree of name * name
blanchet@43926
   320
blanchet@43926
   321
blanchet@43926
   322
(** Isabelle arities **)
blanchet@43926
   323
blanchet@43926
   324
datatype arity_literal =
blanchet@43926
   325
  TConsLit of name * name * name list |
blanchet@43926
   326
  TVarLit of name * name
blanchet@43926
   327
blanchet@43926
   328
fun gen_TVars 0 = []
blanchet@43926
   329
  | gen_TVars n = ("T_" ^ string_of_int n) :: gen_TVars (n-1);
blanchet@43926
   330
blanchet@43926
   331
fun pack_sort (_,[])  = []
blanchet@43926
   332
  | pack_sort (tvar, "HOL.type" :: srt) =
blanchet@43926
   333
    pack_sort (tvar, srt) (* IGNORE sort "type" *)
blanchet@43926
   334
  | pack_sort (tvar, cls :: srt) =
blanchet@43926
   335
    (`make_type_class cls, `I tvar) :: pack_sort (tvar, srt)
blanchet@43926
   336
blanchet@43927
   337
type arity_clause =
blanchet@43927
   338
  {name: string,
blanchet@43927
   339
   prem_lits: arity_literal list,
blanchet@43927
   340
   concl_lits: arity_literal}
blanchet@43926
   341
blanchet@43926
   342
(* Arity of type constructor "tcon :: (arg1, ..., argN) res" *)
blanchet@43926
   343
fun make_axiom_arity_clause (tcons, name, (cls, args)) =
blanchet@43926
   344
  let
blanchet@43926
   345
    val tvars = gen_TVars (length args)
blanchet@43926
   346
    val tvars_srts = ListPair.zip (tvars, args)
blanchet@43926
   347
  in
blanchet@43927
   348
    {name = name,
blanchet@43927
   349
     prem_lits = map TVarLit (union_all (map pack_sort tvars_srts)),
blanchet@43927
   350
     concl_lits = TConsLit (`make_type_class cls,
blanchet@43927
   351
                            `make_fixed_type_const tcons,
blanchet@43927
   352
                            tvars ~~ tvars)}
blanchet@43926
   353
  end
blanchet@43926
   354
blanchet@43926
   355
fun arity_clause _ _ (_, []) = []
blanchet@43926
   356
  | arity_clause seen n (tcons, ("HOL.type",_)::ars) =  (*ignore*)
blanchet@43926
   357
      arity_clause seen n (tcons,ars)
blanchet@43926
   358
  | arity_clause seen n (tcons, (ar as (class,_)) :: ars) =
blanchet@43926
   359
      if member (op =) seen class then (*multiple arities for the same tycon, class pair*)
blanchet@43926
   360
          make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class ^ "_" ^ string_of_int n, ar) ::
blanchet@43926
   361
          arity_clause seen (n+1) (tcons,ars)
blanchet@43926
   362
      else
blanchet@43926
   363
          make_axiom_arity_clause (tcons, lookup_const tcons ^ "_" ^ class, ar) ::
blanchet@43926
   364
          arity_clause (class::seen) n (tcons,ars)
blanchet@43926
   365
blanchet@43926
   366
fun multi_arity_clause [] = []
blanchet@43926
   367
  | multi_arity_clause ((tcons, ars) :: tc_arlists) =
blanchet@43926
   368
      arity_clause [] 1 (tcons, ars) @ multi_arity_clause tc_arlists
blanchet@43926
   369
blanchet@43926
   370
(*Generate all pairs (tycon,class,sorts) such that tycon belongs to class in theory thy
blanchet@43926
   371
  provided its arguments have the corresponding sorts.*)
blanchet@43926
   372
fun type_class_pairs thy tycons classes =
blanchet@43926
   373
  let val alg = Sign.classes_of thy
blanchet@43926
   374
      fun domain_sorts tycon = Sorts.mg_domain alg tycon o single
blanchet@43926
   375
      fun add_class tycon class =
blanchet@43926
   376
        cons (class, domain_sorts tycon class)
blanchet@43926
   377
        handle Sorts.CLASS_ERROR _ => I
blanchet@43926
   378
      fun try_classes tycon = (tycon, fold (add_class tycon) classes [])
blanchet@43926
   379
  in  map try_classes tycons  end;
blanchet@43926
   380
blanchet@43926
   381
(*Proving one (tycon, class) membership may require proving others, so iterate.*)
blanchet@43926
   382
fun iter_type_class_pairs _ _ [] = ([], [])
blanchet@43926
   383
  | iter_type_class_pairs thy tycons classes =
blanchet@43926
   384
      let val cpairs = type_class_pairs thy tycons classes
blanchet@43926
   385
          val newclasses = union_all (union_all (union_all (map (map #2 o #2) cpairs)))
blanchet@43926
   386
            |> subtract (op =) classes |> subtract (op =) HOLogic.typeS
blanchet@43926
   387
          val (classes', cpairs') = iter_type_class_pairs thy tycons newclasses
blanchet@43926
   388
      in (union (op =) classes' classes, union (op =) cpairs' cpairs) end;
blanchet@43926
   389
blanchet@43926
   390
fun make_arity_clauses thy tycons =
blanchet@43926
   391
  iter_type_class_pairs thy tycons ##> multi_arity_clause
blanchet@43926
   392
blanchet@43926
   393
blanchet@43926
   394
(** Isabelle class relations **)
blanchet@43926
   395
blanchet@43927
   396
type class_rel_clause =
blanchet@43927
   397
  {name: string,
blanchet@43927
   398
   subclass: name,
blanchet@43927
   399
   superclass: name}
blanchet@43926
   400
blanchet@43926
   401
(*Generate all pairs (sub,super) such that sub is a proper subclass of super in theory thy.*)
blanchet@43926
   402
fun class_pairs _ [] _ = []
blanchet@43926
   403
  | class_pairs thy subs supers =
blanchet@43926
   404
      let
blanchet@43926
   405
        val class_less = Sorts.class_less (Sign.classes_of thy)
blanchet@43926
   406
        fun add_super sub super = class_less (sub, super) ? cons (sub, super)
blanchet@43926
   407
        fun add_supers sub = fold (add_super sub) supers
blanchet@43926
   408
      in fold add_supers subs [] end
blanchet@43926
   409
blanchet@43926
   410
fun make_class_rel_clause (sub,super) =
blanchet@43927
   411
  {name = sub ^ "_" ^ super,
blanchet@43927
   412
   subclass = `make_type_class sub,
blanchet@43927
   413
   superclass = `make_type_class super}
blanchet@43926
   414
blanchet@43926
   415
fun make_class_rel_clauses thy subs supers =
blanchet@43926
   416
  map make_class_rel_clause (class_pairs thy subs supers);
blanchet@43926
   417
blanchet@43926
   418
datatype combterm =
blanchet@43926
   419
  CombConst of name * typ * typ list |
blanchet@43926
   420
  CombVar of name * typ |
blanchet@43926
   421
  CombApp of combterm * combterm
blanchet@43926
   422
blanchet@43926
   423
fun combtyp_of (CombConst (_, T, _)) = T
blanchet@43926
   424
  | combtyp_of (CombVar (_, T)) = T
blanchet@43926
   425
  | combtyp_of (CombApp (t1, _)) = snd (dest_funT (combtyp_of t1))
blanchet@43926
   426
blanchet@43926
   427
(*gets the head of a combinator application, along with the list of arguments*)
blanchet@43926
   428
fun strip_combterm_comb u =
blanchet@43926
   429
    let fun stripc (CombApp(t,u), ts) = stripc (t, u::ts)
blanchet@43926
   430
        |   stripc  x =  x
blanchet@43926
   431
    in stripc(u,[]) end
blanchet@43926
   432
blanchet@43926
   433
fun atyps_of T = fold_atyps (insert (op =)) T []
blanchet@43926
   434
blanchet@43926
   435
fun new_skolem_const_name s num_T_args =
blanchet@43926
   436
  [new_skolem_const_prefix, s, string_of_int num_T_args]
blanchet@43926
   437
  |> space_implode Long_Name.separator
blanchet@43926
   438
blanchet@43926
   439
(* Converts a term (with combinators) into a combterm. Also accumulates sort
blanchet@43926
   440
   infomation. *)
blanchet@43926
   441
fun combterm_from_term thy bs (P $ Q) =
blanchet@43926
   442
    let
blanchet@43926
   443
      val (P', P_atomics_Ts) = combterm_from_term thy bs P
blanchet@43926
   444
      val (Q', Q_atomics_Ts) = combterm_from_term thy bs Q
blanchet@43926
   445
    in (CombApp (P', Q'), union (op =) P_atomics_Ts Q_atomics_Ts) end
blanchet@43926
   446
  | combterm_from_term thy _ (Const (c, T)) =
blanchet@43926
   447
    let
blanchet@43926
   448
      val tvar_list =
blanchet@43926
   449
        (if String.isPrefix old_skolem_const_prefix c then
blanchet@43926
   450
           [] |> Term.add_tvarsT T |> map TVar
blanchet@43926
   451
         else
blanchet@43926
   452
           (c, T) |> Sign.const_typargs thy)
blanchet@43926
   453
      val c' = CombConst (`make_fixed_const c, T, tvar_list)
blanchet@43926
   454
    in (c', atyps_of T) end
blanchet@43926
   455
  | combterm_from_term _ _ (Free (v, T)) =
blanchet@43926
   456
    (CombConst (`make_fixed_var v, T, []), atyps_of T)
blanchet@43926
   457
  | combterm_from_term _ _ (Var (v as (s, _), T)) =
blanchet@43926
   458
    (if String.isPrefix Meson_Clausify.new_skolem_var_prefix s then
blanchet@43926
   459
       let
blanchet@43926
   460
         val Ts = T |> strip_type |> swap |> op ::
blanchet@43926
   461
         val s' = new_skolem_const_name s (length Ts)
blanchet@43926
   462
       in CombConst (`make_fixed_const s', T, Ts) end
blanchet@43926
   463
     else
blanchet@43926
   464
       CombVar ((make_schematic_var v, s), T), atyps_of T)
blanchet@43926
   465
  | combterm_from_term _ bs (Bound j) =
blanchet@43926
   466
    nth bs j
blanchet@43926
   467
    |> (fn (s, T) => (CombConst (`make_bound_var s, T, []), atyps_of T))
blanchet@43926
   468
  | combterm_from_term _ _ (Abs _) = raise Fail "HOL clause: Abs"
blanchet@43926
   469
blanchet@43926
   470
datatype locality = General | Intro | Elim | Simp | Local | Assum | Chained
blanchet@43926
   471
blanchet@43926
   472
(* (quasi-)underapproximation of the truth *)
blanchet@43926
   473
fun is_locality_global Local = false
blanchet@43926
   474
  | is_locality_global Assum = false
blanchet@43926
   475
  | is_locality_global Chained = false
blanchet@43926
   476
  | is_locality_global _ = true
blanchet@43926
   477
blanchet@43484
   478
datatype polymorphism = Polymorphic | Monomorphic | Mangled_Monomorphic
blanchet@43484
   479
datatype type_level =
blanchet@43484
   480
  All_Types | Nonmonotonic_Types | Finite_Types | Const_Arg_Types | No_Types
blanchet@43708
   481
datatype type_heaviness = Heavy | Light
blanchet@43484
   482
blanchet@43484
   483
datatype type_system =
blanchet@43587
   484
  Simple_Types of type_level |
blanchet@43708
   485
  Preds of polymorphism * type_level * type_heaviness |
blanchet@43708
   486
  Tags of polymorphism * type_level * type_heaviness
blanchet@43484
   487
blanchet@43559
   488
fun try_unsuffixes ss s =
blanchet@43559
   489
  fold (fn s' => fn NONE => try (unsuffix s') s | some => some) ss NONE
blanchet@43559
   490
blanchet@43484
   491
fun type_sys_from_string s =
blanchet@43587
   492
  (case try (unprefix "poly_") s of
blanchet@43587
   493
     SOME s => (SOME Polymorphic, s)
blanchet@43484
   494
   | NONE =>
blanchet@43484
   495
     case try (unprefix "mono_") s of
blanchet@43587
   496
       SOME s => (SOME Monomorphic, s)
blanchet@43587
   497
     | NONE =>
blanchet@43587
   498
       case try (unprefix "mangled_") s of
blanchet@43587
   499
         SOME s => (SOME Mangled_Monomorphic, s)
blanchet@43587
   500
       | NONE => (NONE, s))
blanchet@43484
   501
  ||> (fn s =>
blanchet@43559
   502
          (* "_query" and "_bang" are for the ASCII-challenged Mirabelle. *)
blanchet@43559
   503
          case try_unsuffixes ["?", "_query"] s of
blanchet@43484
   504
            SOME s => (Nonmonotonic_Types, s)
blanchet@43484
   505
          | NONE =>
blanchet@43559
   506
            case try_unsuffixes ["!", "_bang"] s of
blanchet@43484
   507
              SOME s => (Finite_Types, s)
blanchet@43484
   508
            | NONE => (All_Types, s))
blanchet@43699
   509
  ||> apsnd (fn s =>
blanchet@43708
   510
                case try (unsuffix "_heavy") s of
blanchet@43723
   511
                  SOME s => (Heavy, s)
blanchet@43723
   512
                | NONE => (Light, s))
blanchet@43708
   513
  |> (fn (poly, (level, (heaviness, core))) =>
blanchet@43708
   514
         case (core, (poly, level, heaviness)) of
blanchet@43724
   515
           ("simple", (NONE, _, Light)) => Simple_Types level
blanchet@43723
   516
         | ("preds", (SOME poly, _, _)) => Preds (poly, level, heaviness)
blanchet@43720
   517
         | ("tags", (SOME Polymorphic, All_Types, _)) =>
blanchet@43723
   518
           Tags (Polymorphic, All_Types, heaviness)
blanchet@43755
   519
         | ("tags", (SOME Polymorphic, _, _)) =>
blanchet@43755
   520
           (* The actual light encoding is very unsound. *)
blanchet@43755
   521
           Tags (Polymorphic, level, Heavy)
blanchet@43723
   522
         | ("tags", (SOME poly, _, _)) => Tags (poly, level, heaviness)
blanchet@43723
   523
         | ("args", (SOME poly, All_Types (* naja *), Light)) =>
blanchet@43708
   524
           Preds (poly, Const_Arg_Types, Light)
blanchet@43723
   525
         | ("erased", (NONE, All_Types (* naja *), Light)) =>
blanchet@43708
   526
           Preds (Polymorphic, No_Types, Light)
blanchet@43618
   527
         | _ => raise Same.SAME)
blanchet@43618
   528
  handle Same.SAME => error ("Unknown type system: " ^ quote s ^ ".")
blanchet@43484
   529
blanchet@43587
   530
fun polymorphism_of_type_sys (Simple_Types _) = Mangled_Monomorphic
blanchet@43699
   531
  | polymorphism_of_type_sys (Preds (poly, _, _)) = poly
blanchet@43699
   532
  | polymorphism_of_type_sys (Tags (poly, _, _)) = poly
blanchet@43484
   533
blanchet@43587
   534
fun level_of_type_sys (Simple_Types level) = level
blanchet@43699
   535
  | level_of_type_sys (Preds (_, level, _)) = level
blanchet@43699
   536
  | level_of_type_sys (Tags (_, level, _)) = level
blanchet@43699
   537
blanchet@43708
   538
fun heaviness_of_type_sys (Simple_Types _) = Heavy
blanchet@43708
   539
  | heaviness_of_type_sys (Preds (_, _, heaviness)) = heaviness
blanchet@43708
   540
  | heaviness_of_type_sys (Tags (_, _, heaviness)) = heaviness
blanchet@43702
   541
blanchet@43557
   542
fun is_type_level_virtually_sound level =
blanchet@43557
   543
  level = All_Types orelse level = Nonmonotonic_Types
blanchet@43484
   544
val is_type_sys_virtually_sound =
blanchet@43484
   545
  is_type_level_virtually_sound o level_of_type_sys
blanchet@43484
   546
blanchet@43484
   547
fun is_type_level_fairly_sound level =
blanchet@43484
   548
  is_type_level_virtually_sound level orelse level = Finite_Types
blanchet@43484
   549
val is_type_sys_fairly_sound = is_type_level_fairly_sound o level_of_type_sys
blanchet@43484
   550
blanchet@43835
   551
fun is_setting_higher_order THF (Simple_Types _) = true
blanchet@43835
   552
  | is_setting_higher_order _ _ = false
blanchet@43835
   553
blanchet@40358
   554
type translated_formula =
blanchet@38991
   555
  {name: string,
blanchet@43511
   556
   locality: locality,
blanchet@43396
   557
   kind: formula_kind,
blanchet@43433
   558
   combformula: (name, typ, combterm) formula,
blanchet@43433
   559
   atomic_types: typ list}
blanchet@38506
   560
blanchet@43511
   561
fun update_combformula f ({name, locality, kind, combformula, atomic_types}
blanchet@43511
   562
                          : translated_formula) =
blanchet@43511
   563
  {name = name, locality = locality, kind = kind, combformula = f combformula,
blanchet@43433
   564
   atomic_types = atomic_types} : translated_formula
blanchet@43413
   565
blanchet@43429
   566
fun fact_lift f ({combformula, ...} : translated_formula) = f combformula
blanchet@43429
   567
blanchet@43905
   568
val type_instance = Sign.typ_instance o Proof_Context.theory_of
blanchet@43905
   569
blanchet@43905
   570
fun insert_type ctxt get_T x xs =
blanchet@43905
   571
  let val T = get_T x in
blanchet@43905
   572
    if exists (curry (type_instance ctxt) T o get_T) xs then xs
blanchet@43905
   573
    else x :: filter_out (curry (type_instance ctxt o swap) T o get_T) xs
blanchet@43905
   574
  end
blanchet@43547
   575
blanchet@43618
   576
(* The Booleans indicate whether all type arguments should be kept. *)
blanchet@43618
   577
datatype type_arg_policy =
blanchet@43618
   578
  Explicit_Type_Args of bool |
blanchet@43618
   579
  Mangled_Type_Args of bool |
blanchet@43618
   580
  No_Type_Args
blanchet@41384
   581
blanchet@43707
   582
fun should_drop_arg_type_args (Simple_Types _) =
blanchet@43707
   583
    false (* since TFF doesn't support overloading *)
blanchet@43707
   584
  | should_drop_arg_type_args type_sys =
blanchet@43707
   585
    level_of_type_sys type_sys = All_Types andalso
blanchet@43708
   586
    heaviness_of_type_sys type_sys = Heavy
blanchet@43702
   587
blanchet@43460
   588
fun general_type_arg_policy type_sys =
blanchet@43460
   589
  if level_of_type_sys type_sys = No_Types then
blanchet@43460
   590
    No_Type_Args
blanchet@43460
   591
  else if polymorphism_of_type_sys type_sys = Mangled_Monomorphic then
blanchet@43702
   592
    Mangled_Type_Args (should_drop_arg_type_args type_sys)
blanchet@43460
   593
  else
blanchet@43702
   594
    Explicit_Type_Args (should_drop_arg_type_args type_sys)
blanchet@43434
   595
blanchet@43792
   596
fun type_arg_policy type_sys s =
blanchet@43792
   597
  if s = @{const_name HOL.eq} orelse
blanchet@43807
   598
     (s = app_op_name andalso level_of_type_sys type_sys = Const_Arg_Types) then
blanchet@43792
   599
    No_Type_Args
blanchet@43792
   600
  else
blanchet@43792
   601
    general_type_arg_policy type_sys
blanchet@43088
   602
blanchet@43926
   603
(*Make literals for sorted type variables*)
blanchet@43926
   604
fun sorts_on_typs_aux (_, [])   = []
blanchet@43926
   605
  | sorts_on_typs_aux ((x,i),  s::ss) =
blanchet@43926
   606
      let val sorts = sorts_on_typs_aux ((x,i), ss)
blanchet@43926
   607
      in
blanchet@43926
   608
          if s = the_single @{sort HOL.type} then sorts
blanchet@43926
   609
          else if i = ~1 then TyLitFree (`make_type_class s, `make_fixed_type_var x) :: sorts
blanchet@43926
   610
          else TyLitVar (`make_type_class s, (make_schematic_type_var (x,i), x)) :: sorts
blanchet@43926
   611
      end;
blanchet@43926
   612
blanchet@43926
   613
fun sorts_on_typs (TFree (a, s)) = sorts_on_typs_aux ((a, ~1), s)
blanchet@43926
   614
  | sorts_on_typs (TVar (v, s)) = sorts_on_typs_aux (v, s)
blanchet@43926
   615
  | sorts_on_typs _ = raise Fail "expected \"TVar\" or \"TFree\""
blanchet@43926
   616
blanchet@43926
   617
(*Given a list of sorted type variables, return a list of type literals.*)
blanchet@43926
   618
val raw_type_literals_for_types = union_all o map sorts_on_typs
blanchet@43926
   619
blanchet@43926
   620
fun type_literals_for_types format type_sys kind Ts =
blanchet@43797
   621
  if level_of_type_sys type_sys = No_Types orelse format = CNF_UEQ then
blanchet@43224
   622
    []
blanchet@43224
   623
  else
blanchet@43926
   624
    Ts |> raw_type_literals_for_types
blanchet@43224
   625
       |> filter (fn TyLitVar _ => kind <> Conjecture
blanchet@43224
   626
                   | TyLitFree _ => kind = Conjecture)
blanchet@41385
   627
blanchet@43405
   628
fun mk_aconns c phis =
blanchet@43405
   629
  let val (phis', phi') = split_last phis in
blanchet@43405
   630
    fold_rev (mk_aconn c) phis' phi'
blanchet@43405
   631
  end
blanchet@38506
   632
fun mk_ahorn [] phi = phi
blanchet@43405
   633
  | mk_ahorn phis psi = AConn (AImplies, [mk_aconns AAnd phis, psi])
blanchet@43393
   634
fun mk_aquant _ [] phi = phi
blanchet@43393
   635
  | mk_aquant q xs (phi as AQuant (q', xs', phi')) =
blanchet@43393
   636
    if q = q' then AQuant (q, xs @ xs', phi') else AQuant (q, xs, phi)
blanchet@43393
   637
  | mk_aquant q xs phi = AQuant (q, xs, phi)
blanchet@38506
   638
blanchet@43393
   639
fun close_universally atom_vars phi =
blanchet@41393
   640
  let
blanchet@41393
   641
    fun formula_vars bounds (AQuant (_, xs, phi)) =
blanchet@43397
   642
        formula_vars (map fst xs @ bounds) phi
blanchet@41393
   643
      | formula_vars bounds (AConn (_, phis)) = fold (formula_vars bounds) phis
blanchet@43393
   644
      | formula_vars bounds (AAtom tm) =
blanchet@43397
   645
        union (op =) (atom_vars tm []
blanchet@43397
   646
                      |> filter_out (member (op =) bounds o fst))
blanchet@43393
   647
  in mk_aquant AForall (formula_vars [] phi []) phi end
blanchet@43393
   648
blanchet@43402
   649
fun combterm_vars (CombApp (tm1, tm2)) = fold combterm_vars [tm1, tm2]
blanchet@43393
   650
  | combterm_vars (CombConst _) = I
blanchet@43445
   651
  | combterm_vars (CombVar (name, T)) = insert (op =) (name, SOME T)
blanchet@43545
   652
fun close_combformula_universally phi = close_universally combterm_vars phi
blanchet@43393
   653
blanchet@43393
   654
fun term_vars (ATerm (name as (s, _), tms)) =
blanchet@43839
   655
  is_tptp_variable s ? insert (op =) (name, NONE) #> fold term_vars tms
blanchet@43545
   656
fun close_formula_universally phi = close_universally term_vars phi
blanchet@41393
   657
blanchet@43835
   658
val homo_infinite_type_name = @{type_name ind} (* any infinite type *)
blanchet@43835
   659
val homo_infinite_type = Type (homo_infinite_type_name, [])
blanchet@43835
   660
blanchet@43835
   661
fun fo_term_from_typ higher_order =
blanchet@43835
   662
  let
blanchet@43835
   663
    fun term (Type (s, Ts)) =
blanchet@43835
   664
      ATerm (case (higher_order, s) of
blanchet@43835
   665
               (true, @{type_name bool}) => `I tptp_bool_type
blanchet@43835
   666
             | (true, @{type_name fun}) => `I tptp_fun_type
blanchet@43835
   667
             | _ => if s = homo_infinite_type_name then `I tptp_individual_type
blanchet@43835
   668
                    else `make_fixed_type_const s,
blanchet@43835
   669
             map term Ts)
blanchet@43835
   670
    | term (TFree (s, _)) = ATerm (`make_fixed_type_var s, [])
blanchet@43835
   671
    | term (TVar ((x as (s, _)), _)) =
blanchet@43835
   672
      ATerm ((make_schematic_type_var x, s), [])
blanchet@43835
   673
  in term end
blanchet@43433
   674
blanchet@43433
   675
(* This shouldn't clash with anything else. *)
blanchet@43413
   676
val mangled_type_sep = "\000"
blanchet@43413
   677
blanchet@43433
   678
fun generic_mangled_type_name f (ATerm (name, [])) = f name
blanchet@43433
   679
  | generic_mangled_type_name f (ATerm (name, tys)) =
blanchet@43626
   680
    f name ^ "(" ^ space_implode "," (map (generic_mangled_type_name f) tys)
blanchet@43626
   681
    ^ ")"
blanchet@43413
   682
blanchet@43839
   683
val bool_atype = AType (`I tptp_bool_type)
blanchet@43839
   684
blanchet@43926
   685
fun make_simple_type s =
blanchet@43926
   686
  if s = tptp_bool_type orelse s = tptp_fun_type orelse
blanchet@43926
   687
     s = tptp_individual_type then
blanchet@43926
   688
    s
blanchet@43926
   689
  else
blanchet@43926
   690
    simple_type_prefix ^ ascii_of s
blanchet@43926
   691
blanchet@43835
   692
fun ho_type_from_fo_term higher_order pred_sym ary =
blanchet@43804
   693
  let
blanchet@43804
   694
    fun to_atype ty =
blanchet@43804
   695
      AType ((make_simple_type (generic_mangled_type_name fst ty),
blanchet@43804
   696
              generic_mangled_type_name snd ty))
blanchet@43804
   697
    fun to_afun f1 f2 tys = AFun (f1 (hd tys), f2 (nth tys 1))
blanchet@43839
   698
    fun to_fo 0 ty = if pred_sym then bool_atype else to_atype ty
blanchet@43835
   699
      | to_fo ary (ATerm (_, tys)) = to_afun to_atype (to_fo (ary - 1)) tys
blanchet@43835
   700
    fun to_ho (ty as ATerm ((s, _), tys)) =
blanchet@43835
   701
      if s = tptp_fun_type then to_afun to_ho to_ho tys else to_atype ty
blanchet@43835
   702
  in if higher_order then to_ho else to_fo ary end
blanchet@43804
   703
blanchet@43835
   704
fun mangled_type higher_order pred_sym ary =
blanchet@43835
   705
  ho_type_from_fo_term higher_order pred_sym ary o fo_term_from_typ higher_order
blanchet@43804
   706
blanchet@43835
   707
fun mangled_const_name T_args (s, s') =
blanchet@43804
   708
  let
blanchet@43835
   709
    val ty_args = map (fo_term_from_typ false) T_args
blanchet@43804
   710
    fun type_suffix f g =
blanchet@43804
   711
      fold_rev (curry (op ^) o g o prefix mangled_type_sep
blanchet@43804
   712
                o generic_mangled_type_name f) ty_args ""
blanchet@43804
   713
  in (s ^ type_suffix fst ascii_of, s' ^ type_suffix snd I) end
blanchet@43413
   714
blanchet@43413
   715
val parse_mangled_ident =
blanchet@43413
   716
  Scan.many1 (not o member (op =) ["(", ")", ","]) >> implode
blanchet@43413
   717
blanchet@43413
   718
fun parse_mangled_type x =
blanchet@43413
   719
  (parse_mangled_ident
blanchet@43413
   720
   -- Scan.optional ($$ "(" |-- Scan.optional parse_mangled_types [] --| $$ ")")
blanchet@43413
   721
                    [] >> ATerm) x
blanchet@43413
   722
and parse_mangled_types x =
blanchet@43413
   723
  (parse_mangled_type ::: Scan.repeat ($$ "," |-- parse_mangled_type)) x
blanchet@43413
   724
blanchet@43413
   725
fun unmangled_type s =
blanchet@43413
   726
  s |> suffix ")" |> raw_explode
blanchet@43413
   727
    |> Scan.finite Symbol.stopper
blanchet@43413
   728
           (Scan.error (!! (fn _ => raise Fail ("unrecognized mangled type " ^
blanchet@43413
   729
                                                quote s)) parse_mangled_type))
blanchet@43413
   730
    |> fst
blanchet@43413
   731
blanchet@43432
   732
val unmangled_const_name = space_explode mangled_type_sep #> hd
blanchet@43413
   733
fun unmangled_const s =
blanchet@43413
   734
  let val ss = space_explode mangled_type_sep s in
blanchet@43413
   735
    (hd ss, map unmangled_type (tl ss))
blanchet@43413
   736
  end
blanchet@43413
   737
blanchet@43858
   738
fun introduce_proxies format type_sys =
blanchet@43439
   739
  let
blanchet@43858
   740
    fun intro top_level (CombApp (tm1, tm2)) =
blanchet@43858
   741
        CombApp (intro top_level tm1, intro false tm2)
blanchet@43858
   742
      | intro top_level (CombConst (name as (s, _), T, T_args)) =
blanchet@43441
   743
        (case proxify_const s of
blanchet@43858
   744
           SOME (_, proxy_base) =>
blanchet@43841
   745
           if top_level orelse is_setting_higher_order format type_sys then
blanchet@43841
   746
             case (top_level, s) of
blanchet@43841
   747
               (_, "c_False") => (`I tptp_false, [])
blanchet@43841
   748
             | (_, "c_True") => (`I tptp_true, [])
blanchet@43841
   749
             | (false, "c_Not") => (`I tptp_not, [])
blanchet@43841
   750
             | (false, "c_conj") => (`I tptp_and, [])
blanchet@43841
   751
             | (false, "c_disj") => (`I tptp_or, [])
blanchet@43841
   752
             | (false, "c_implies") => (`I tptp_implies, [])
blanchet@43841
   753
             | (false, s) =>
blanchet@43858
   754
               if is_tptp_equal s then (`I tptp_equal, [])
blanchet@43858
   755
               else (proxy_base |>> prefix const_prefix, T_args)
blanchet@43841
   756
             | _ => (name, [])
blanchet@43440
   757
           else
blanchet@43445
   758
             (proxy_base |>> prefix const_prefix, T_args)
blanchet@43445
   759
          | NONE => (name, T_args))
blanchet@43445
   760
        |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43858
   761
      | intro _ tm = tm
blanchet@43858
   762
  in intro true end
blanchet@43439
   763
blanchet@43835
   764
fun combformula_from_prop thy format type_sys eq_as_iff =
blanchet@38506
   765
  let
blanchet@43439
   766
    fun do_term bs t atomic_types =
blanchet@41388
   767
      combterm_from_term thy bs (Envir.eta_contract t)
blanchet@43835
   768
      |>> (introduce_proxies format type_sys #> AAtom)
blanchet@43439
   769
      ||> union (op =) atomic_types
blanchet@38506
   770
    fun do_quant bs q s T t' =
blanchet@38743
   771
      let val s = Name.variant (map fst bs) s in
blanchet@38743
   772
        do_formula ((s, T) :: bs) t'
blanchet@43433
   773
        #>> mk_aquant q [(`make_bound_var s, SOME T)]
blanchet@38743
   774
      end
blanchet@38506
   775
    and do_conn bs c t1 t2 =
blanchet@38506
   776
      do_formula bs t1 ##>> do_formula bs t2
blanchet@43402
   777
      #>> uncurry (mk_aconn c)
blanchet@38506
   778
    and do_formula bs t =
blanchet@38506
   779
      case t of
blanchet@43402
   780
        @{const Not} $ t1 => do_formula bs t1 #>> mk_anot
blanchet@38506
   781
      | Const (@{const_name All}, _) $ Abs (s, T, t') =>
blanchet@38506
   782
        do_quant bs AForall s T t'
blanchet@38506
   783
      | Const (@{const_name Ex}, _) $ Abs (s, T, t') =>
blanchet@38506
   784
        do_quant bs AExists s T t'
haftmann@39028
   785
      | @{const HOL.conj} $ t1 $ t2 => do_conn bs AAnd t1 t2
haftmann@39028
   786
      | @{const HOL.disj} $ t1 $ t2 => do_conn bs AOr t1 t2
haftmann@39019
   787
      | @{const HOL.implies} $ t1 $ t2 => do_conn bs AImplies t1 t2
haftmann@39093
   788
      | Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])) $ t1 $ t2 =>
blanchet@41388
   789
        if eq_as_iff then do_conn bs AIff t1 t2 else do_term bs t
blanchet@41388
   790
      | _ => do_term bs t
blanchet@38506
   791
  in do_formula [] end
blanchet@38506
   792
blanchet@43615
   793
fun presimplify_term ctxt =
blanchet@43615
   794
  Skip_Proof.make_thm (Proof_Context.theory_of ctxt)
blanchet@43615
   795
  #> Meson.presimplify ctxt
blanchet@43615
   796
  #> prop_of
blanchet@38506
   797
wenzelm@41739
   798
fun concealed_bound_name j = sledgehammer_weak_prefix ^ string_of_int j
blanchet@38506
   799
fun conceal_bounds Ts t =
blanchet@38506
   800
  subst_bounds (map (Free o apfst concealed_bound_name)
blanchet@38506
   801
                    (0 upto length Ts - 1 ~~ Ts), t)
blanchet@38506
   802
fun reveal_bounds Ts =
blanchet@38506
   803
  subst_atomic (map (fn (j, T) => (Free (concealed_bound_name j, T), Bound j))
blanchet@38506
   804
                    (0 upto length Ts - 1 ~~ Ts))
blanchet@38506
   805
blanchet@43612
   806
fun extensionalize_term ctxt t =
blanchet@43612
   807
  let val thy = Proof_Context.theory_of ctxt in
blanchet@43612
   808
    t |> cterm_of thy |> Meson.extensionalize_conv ctxt
blanchet@43612
   809
      |> prop_of |> Logic.dest_equals |> snd
blanchet@43612
   810
  end
blanchet@38831
   811
blanchet@38506
   812
fun introduce_combinators_in_term ctxt kind t =
wenzelm@43232
   813
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38716
   814
    if Meson.is_fol_term thy t then
blanchet@38716
   815
      t
blanchet@38716
   816
    else
blanchet@38716
   817
      let
blanchet@38716
   818
        fun aux Ts t =
blanchet@38716
   819
          case t of
blanchet@38716
   820
            @{const Not} $ t1 => @{const Not} $ aux Ts t1
blanchet@38716
   821
          | (t0 as Const (@{const_name All}, _)) $ Abs (s, T, t') =>
blanchet@38716
   822
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   823
          | (t0 as Const (@{const_name All}, _)) $ t1 =>
blanchet@38890
   824
            aux Ts (t0 $ eta_expand Ts t1 1)
blanchet@38716
   825
          | (t0 as Const (@{const_name Ex}, _)) $ Abs (s, T, t') =>
blanchet@38716
   826
            t0 $ Abs (s, T, aux (T :: Ts) t')
blanchet@38890
   827
          | (t0 as Const (@{const_name Ex}, _)) $ t1 =>
blanchet@38890
   828
            aux Ts (t0 $ eta_expand Ts t1 1)
haftmann@39028
   829
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39028
   830
          | (t0 as @{const HOL.disj}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39019
   831
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => t0 $ aux Ts t1 $ aux Ts t2
haftmann@39093
   832
          | (t0 as Const (@{const_name HOL.eq}, Type (_, [@{typ bool}, _])))
blanchet@38716
   833
              $ t1 $ t2 =>
blanchet@38716
   834
            t0 $ aux Ts t1 $ aux Ts t2
blanchet@38716
   835
          | _ => if not (exists_subterm (fn Abs _ => true | _ => false) t) then
blanchet@38716
   836
                   t
blanchet@38716
   837
                 else
blanchet@38716
   838
                   t |> conceal_bounds Ts
blanchet@38716
   839
                     |> Envir.eta_contract
blanchet@38716
   840
                     |> cterm_of thy
blanchet@40071
   841
                     |> Meson_Clausify.introduce_combinators_in_cterm
blanchet@38716
   842
                     |> prop_of |> Logic.dest_equals |> snd
blanchet@38716
   843
                     |> reveal_bounds Ts
blanchet@39616
   844
        val (t, ctxt') = Variable.import_terms true [t] ctxt |>> the_single
blanchet@38716
   845
      in t |> aux [] |> singleton (Variable.export_terms ctxt' ctxt) end
blanchet@38716
   846
      handle THM _ =>
blanchet@38716
   847
             (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@38836
   848
             if kind = Conjecture then HOLogic.false_const
blanchet@38836
   849
             else HOLogic.true_const
blanchet@38716
   850
  end
blanchet@38506
   851
blanchet@38506
   852
(* Metis's use of "resolve_tac" freezes the schematic variables. We simulate the
blanchet@43224
   853
   same in Sledgehammer to prevent the discovery of unreplayable proofs. *)
blanchet@38506
   854
fun freeze_term t =
blanchet@38506
   855
  let
blanchet@38506
   856
    fun aux (t $ u) = aux t $ aux u
blanchet@38506
   857
      | aux (Abs (s, T, t)) = Abs (s, T, aux t)
blanchet@38506
   858
      | aux (Var ((s, i), T)) =
blanchet@38506
   859
        Free (sledgehammer_weak_prefix ^ s ^ "_" ^ string_of_int i, T)
blanchet@38506
   860
      | aux t = t
blanchet@38506
   861
  in t |> exists_subterm is_Var t ? aux end
blanchet@38506
   862
blanchet@40445
   863
(* making fact and conjecture formulas *)
blanchet@43835
   864
fun make_formula ctxt format type_sys eq_as_iff presimp name loc kind t =
blanchet@38506
   865
  let
wenzelm@43232
   866
    val thy = Proof_Context.theory_of ctxt
blanchet@38831
   867
    val t = t |> Envir.beta_eta_contract
blanchet@43785
   868
              |> transform_elim_prop
blanchet@41459
   869
              |> Object_Logic.atomize_term thy
blanchet@43434
   870
    val need_trueprop = (fastype_of t = @{typ bool})
blanchet@38890
   871
    val t = t |> need_trueprop ? HOLogic.mk_Trueprop
blanchet@43607
   872
              |> Raw_Simplifier.rewrite_term thy
blanchet@43607
   873
                     (Meson.unfold_set_const_simps ctxt) []
blanchet@43612
   874
              |> extensionalize_term ctxt
blanchet@43615
   875
              |> presimp ? presimplify_term ctxt
blanchet@38506
   876
              |> perhaps (try (HOLogic.dest_Trueprop))
blanchet@38506
   877
              |> introduce_combinators_in_term ctxt kind
blanchet@38836
   878
              |> kind <> Axiom ? freeze_term
blanchet@43803
   879
    val (combformula, atomic_types) =
blanchet@43835
   880
      combformula_from_prop thy format type_sys eq_as_iff t []
blanchet@38506
   881
  in
blanchet@43511
   882
    {name = name, locality = loc, kind = kind, combformula = combformula,
blanchet@43433
   883
     atomic_types = atomic_types}
blanchet@38506
   884
  end
blanchet@38506
   885
blanchet@43835
   886
fun make_fact ctxt format type_sys keep_trivial eq_as_iff presimp
blanchet@43835
   887
              ((name, loc), t) =
blanchet@43803
   888
  case (keep_trivial,
blanchet@43835
   889
        make_formula ctxt format type_sys eq_as_iff presimp name loc Axiom t) of
blanchet@43842
   890
    (false, formula as {combformula = AAtom (CombConst ((s, _), _, _)), ...}) =>
blanchet@43842
   891
    if s = tptp_true then NONE else SOME formula
blanchet@42861
   892
  | (_, formula) => SOME formula
blanchet@43432
   893
blanchet@43835
   894
fun make_conjecture ctxt format prem_kind type_sys ts =
blanchet@38836
   895
  let val last = length ts - 1 in
blanchet@43580
   896
    map2 (fn j => fn t =>
blanchet@43580
   897
             let
blanchet@43580
   898
               val (kind, maybe_negate) =
blanchet@43580
   899
                 if j = last then
blanchet@43580
   900
                   (Conjecture, I)
blanchet@43580
   901
                 else
blanchet@43580
   902
                   (prem_kind,
blanchet@43580
   903
                    if prem_kind = Conjecture then update_combformula mk_anot
blanchet@43580
   904
                    else I)
blanchet@43580
   905
              in
blanchet@43835
   906
                t |> make_formula ctxt format type_sys true true
blanchet@43835
   907
                                  (string_of_int j) General kind
blanchet@43803
   908
                  |> maybe_negate
blanchet@43580
   909
              end)
blanchet@38836
   910
         (0 upto last) ts
blanchet@38836
   911
  end
blanchet@38506
   912
blanchet@43552
   913
(** Finite and infinite type inference **)
blanchet@43552
   914
blanchet@43755
   915
fun deep_freeze_atyp (TVar (_, S)) = TFree ("v", S)
blanchet@43755
   916
  | deep_freeze_atyp T = T
blanchet@43755
   917
val deep_freeze_type = map_atyps deep_freeze_atyp
blanchet@43755
   918
blanchet@43552
   919
(* Finite types such as "unit", "bool", "bool * bool", and "bool => bool" are
blanchet@43552
   920
   dangerous because their "exhaust" properties can easily lead to unsound ATP
blanchet@43552
   921
   proofs. On the other hand, all HOL infinite types can be given the same
blanchet@43552
   922
   models in first-order logic (via Löwenheim-Skolem). *)
blanchet@43552
   923
blanchet@43755
   924
fun should_encode_type ctxt (nonmono_Ts as _ :: _) _ T =
blanchet@43755
   925
    exists (curry (type_instance ctxt) (deep_freeze_type T)) nonmono_Ts
blanchet@43707
   926
  | should_encode_type _ _ All_Types _ = true
blanchet@43552
   927
  | should_encode_type ctxt _ Finite_Types T = is_type_surely_finite ctxt T
blanchet@43552
   928
  | should_encode_type _ _ _ _ = false
blanchet@43552
   929
blanchet@43708
   930
fun should_predicate_on_type ctxt nonmono_Ts (Preds (_, level, heaviness))
blanchet@43705
   931
                             should_predicate_on_var T =
blanchet@43747
   932
    (heaviness = Heavy orelse should_predicate_on_var ()) andalso
blanchet@43747
   933
    should_encode_type ctxt nonmono_Ts level T
blanchet@43705
   934
  | should_predicate_on_type _ _ _ _ _ = false
blanchet@43552
   935
blanchet@43707
   936
fun is_var_or_bound_var (CombConst ((s, _), _, _)) =
blanchet@43707
   937
    String.isPrefix bound_var_prefix s
blanchet@43707
   938
  | is_var_or_bound_var (CombVar _) = true
blanchet@43707
   939
  | is_var_or_bound_var _ = false
blanchet@43707
   940
blanchet@43700
   941
datatype tag_site = Top_Level | Eq_Arg | Elsewhere
blanchet@43700
   942
blanchet@43700
   943
fun should_tag_with_type _ _ _ Top_Level _ _ = false
blanchet@43708
   944
  | should_tag_with_type ctxt nonmono_Ts (Tags (_, level, heaviness)) site u T =
blanchet@43708
   945
    (case heaviness of
blanchet@43708
   946
       Heavy => should_encode_type ctxt nonmono_Ts level T
blanchet@43708
   947
     | Light =>
blanchet@43707
   948
       case (site, is_var_or_bound_var u) of
blanchet@43707
   949
         (Eq_Arg, true) => should_encode_type ctxt nonmono_Ts level T
blanchet@43700
   950
       | _ => false)
blanchet@43700
   951
  | should_tag_with_type _ _ _ _ _ _ = false
blanchet@43552
   952
blanchet@43835
   953
fun homogenized_type ctxt nonmono_Ts level =
blanchet@43835
   954
  let
blanchet@43835
   955
    val should_encode = should_encode_type ctxt nonmono_Ts level
blanchet@43835
   956
    fun homo 0 T = if should_encode T then T else homo_infinite_type
blanchet@43835
   957
      | homo ary (Type (@{type_name fun}, [T1, T2])) =
blanchet@43835
   958
        homo 0 T1 --> homo (ary - 1) T2
blanchet@43835
   959
      | homo _ _ = raise Fail "expected function type"
blanchet@43835
   960
  in homo end
blanchet@43552
   961
blanchet@43444
   962
(** "hBOOL" and "hAPP" **)
blanchet@41561
   963
blanchet@43445
   964
type sym_info =
blanchet@43905
   965
  {pred_sym : bool, min_ary : int, max_ary : int, types : typ list}
blanchet@43434
   966
blanchet@43905
   967
fun add_combterm_syms_to_table ctxt explicit_apply =
blanchet@43429
   968
  let
blanchet@43905
   969
    fun consider_var_arity const_T var_T max_ary =
blanchet@43905
   970
      let
blanchet@43905
   971
        fun iter ary T =
blanchet@43905
   972
          if ary = max_ary orelse type_instance ctxt (var_T, T) then ary
blanchet@43905
   973
          else iter (ary + 1) (range_type T)
blanchet@43905
   974
      in iter 0 const_T end
blanchet@43905
   975
    fun add top_level tm (accum as (ho_var_Ts, sym_tab)) =
blanchet@43429
   976
      let val (head, args) = strip_combterm_comb tm in
blanchet@43429
   977
        (case head of
blanchet@43434
   978
           CombConst ((s, _), T, _) =>
blanchet@43429
   979
           if String.isPrefix bound_var_prefix s then
blanchet@43905
   980
             if explicit_apply = NONE andalso can dest_funT T then
blanchet@43905
   981
               let
blanchet@43905
   982
                 fun repair_min_arity {pred_sym, min_ary, max_ary, types} =
blanchet@43905
   983
                   {pred_sym = pred_sym,
blanchet@43905
   984
                    min_ary =
blanchet@43905
   985
                      fold (fn T' => consider_var_arity T' T) types min_ary,
blanchet@43905
   986
                    max_ary = max_ary, types = types}
blanchet@43905
   987
                 val ho_var_Ts' = ho_var_Ts |> insert_type ctxt I T
blanchet@43905
   988
               in
blanchet@43905
   989
                 if pointer_eq (ho_var_Ts', ho_var_Ts) then accum
blanchet@43905
   990
                 else (ho_var_Ts', Symtab.map (K repair_min_arity) sym_tab)
blanchet@43905
   991
               end
blanchet@43905
   992
             else
blanchet@43905
   993
               accum
blanchet@43429
   994
           else
blanchet@43905
   995
             let
blanchet@43905
   996
               val ary = length args
blanchet@43905
   997
             in
blanchet@43905
   998
               (ho_var_Ts,
blanchet@43905
   999
                case Symtab.lookup sym_tab s of
blanchet@43905
  1000
                  SOME {pred_sym, min_ary, max_ary, types} =>
blanchet@43905
  1001
                  let
blanchet@43905
  1002
                    val types' = types |> insert_type ctxt I T
blanchet@43905
  1003
                    val min_ary =
blanchet@43905
  1004
                      if is_some explicit_apply orelse
blanchet@43905
  1005
                         pointer_eq (types', types) then
blanchet@43905
  1006
                        min_ary
blanchet@43905
  1007
                      else
blanchet@43905
  1008
                        fold (consider_var_arity T) ho_var_Ts min_ary
blanchet@43905
  1009
                  in
blanchet@43905
  1010
                    Symtab.update (s, {pred_sym = pred_sym andalso top_level,
blanchet@43905
  1011
                                       min_ary = Int.min (ary, min_ary),
blanchet@43905
  1012
                                       max_ary = Int.max (ary, max_ary),
blanchet@43905
  1013
                                       types = types'})
blanchet@43905
  1014
                                  sym_tab
blanchet@43905
  1015
                  end
blanchet@43905
  1016
                | NONE =>
blanchet@43905
  1017
                  let
blanchet@43905
  1018
                    val min_ary =
blanchet@43905
  1019
                      case explicit_apply of
blanchet@43905
  1020
                        SOME true => 0
blanchet@43905
  1021
                      | SOME false => ary
blanchet@43905
  1022
                      | NONE => fold (consider_var_arity T) ho_var_Ts ary
blanchet@43905
  1023
                  in
blanchet@43905
  1024
                    Symtab.update_new (s, {pred_sym = top_level,
blanchet@43905
  1025
                                           min_ary = min_ary, max_ary = ary,
blanchet@43905
  1026
                                           types = [T]})
blanchet@43905
  1027
                                      sym_tab
blanchet@43905
  1028
                  end)
blanchet@43905
  1029
             end
blanchet@43905
  1030
         | _ => accum)
blanchet@43905
  1031
        |> fold (add false) args
blanchet@43429
  1032
      end
blanchet@43905
  1033
  in add true end
blanchet@43905
  1034
fun add_fact_syms_to_table ctxt explicit_apply =
blanchet@43905
  1035
  fact_lift (formula_fold NONE
blanchet@43905
  1036
                          (K (add_combterm_syms_to_table ctxt explicit_apply)))
blanchet@38506
  1037
blanchet@43546
  1038
val default_sym_table_entries : (string * sym_info) list =
blanchet@43905
  1039
  [(tptp_equal, {pred_sym = true, min_ary = 2, max_ary = 2, types = []}),
blanchet@43905
  1040
   (tptp_old_equal, {pred_sym = true, min_ary = 2, max_ary = 2, types = []}),
blanchet@43807
  1041
   (make_fixed_const predicator_name,
blanchet@43905
  1042
    {pred_sym = true, min_ary = 1, max_ary = 1, types = []})] @
blanchet@43439
  1043
  ([tptp_false, tptp_true]
blanchet@43905
  1044
   |> map (rpair {pred_sym = true, min_ary = 0, max_ary = 0, types = []}))
blanchet@41388
  1045
blanchet@43905
  1046
fun sym_table_for_facts ctxt explicit_apply facts =
blanchet@43905
  1047
  Symtab.empty
blanchet@43905
  1048
  |> fold Symtab.default default_sym_table_entries
blanchet@43905
  1049
  |> pair [] |> fold (add_fact_syms_to_table ctxt explicit_apply) facts |> snd
blanchet@38506
  1050
blanchet@43429
  1051
fun min_arity_of sym_tab s =
blanchet@43429
  1052
  case Symtab.lookup sym_tab s of
blanchet@43445
  1053
    SOME ({min_ary, ...} : sym_info) => min_ary
blanchet@43429
  1054
  | NONE =>
blanchet@43429
  1055
    case strip_prefix_and_unascii const_prefix s of
blanchet@43418
  1056
      SOME s =>
blanchet@43441
  1057
      let val s = s |> unmangled_const_name |> invert_const in
blanchet@43807
  1058
        if s = predicator_name then 1
blanchet@43807
  1059
        else if s = app_op_name then 2
blanchet@43807
  1060
        else if s = type_pred_name then 1
blanchet@43428
  1061
        else 0
blanchet@43418
  1062
      end
blanchet@38506
  1063
    | NONE => 0
blanchet@38506
  1064
blanchet@38506
  1065
(* True if the constant ever appears outside of the top-level position in
blanchet@38506
  1066
   literals, or if it appears with different arities (e.g., because of different
blanchet@38506
  1067
   type instantiations). If false, the constant always receives all of its
blanchet@38506
  1068
   arguments and is used as a predicate. *)
blanchet@43429
  1069
fun is_pred_sym sym_tab s =
blanchet@43429
  1070
  case Symtab.lookup sym_tab s of
blanchet@43445
  1071
    SOME ({pred_sym, min_ary, max_ary, ...} : sym_info) =>
blanchet@43445
  1072
    pred_sym andalso min_ary = max_ary
blanchet@43429
  1073
  | NONE => false
blanchet@38506
  1074
blanchet@43439
  1075
val predicator_combconst =
blanchet@43807
  1076
  CombConst (`make_fixed_const predicator_name, @{typ "bool => bool"}, [])
blanchet@43439
  1077
fun predicator tm = CombApp (predicator_combconst, tm)
blanchet@38506
  1078
blanchet@43439
  1079
fun introduce_predicators_in_combterm sym_tab tm =
blanchet@43413
  1080
  case strip_combterm_comb tm of
blanchet@43413
  1081
    (CombConst ((s, _), _, _), _) =>
blanchet@43439
  1082
    if is_pred_sym sym_tab s then tm else predicator tm
blanchet@43439
  1083
  | _ => predicator tm
blanchet@38506
  1084
blanchet@43415
  1085
fun list_app head args = fold (curry (CombApp o swap)) args head
blanchet@38506
  1086
blanchet@43415
  1087
fun explicit_app arg head =
blanchet@43415
  1088
  let
blanchet@43433
  1089
    val head_T = combtyp_of head
blanchet@43563
  1090
    val (arg_T, res_T) = dest_funT head_T
blanchet@43415
  1091
    val explicit_app =
blanchet@43807
  1092
      CombConst (`make_fixed_const app_op_name, head_T --> head_T,
blanchet@43563
  1093
                 [arg_T, res_T])
blanchet@43415
  1094
  in list_app explicit_app [head, arg] end
blanchet@43415
  1095
fun list_explicit_app head args = fold explicit_app args head
blanchet@43415
  1096
blanchet@43436
  1097
fun introduce_explicit_apps_in_combterm sym_tab =
blanchet@43415
  1098
  let
blanchet@43415
  1099
    fun aux tm =
blanchet@43415
  1100
      case strip_combterm_comb tm of
blanchet@43415
  1101
        (head as CombConst ((s, _), _, _), args) =>
blanchet@43415
  1102
        args |> map aux
blanchet@43428
  1103
             |> chop (min_arity_of sym_tab s)
blanchet@43415
  1104
             |>> list_app head
blanchet@43415
  1105
             |-> list_explicit_app
blanchet@43415
  1106
      | (head, args) => list_explicit_app head (map aux args)
blanchet@43415
  1107
  in aux end
blanchet@43415
  1108
blanchet@43618
  1109
fun chop_fun 0 T = ([], T)
blanchet@43618
  1110
  | chop_fun n (Type (@{type_name fun}, [dom_T, ran_T])) =
blanchet@43618
  1111
    chop_fun (n - 1) ran_T |>> cons dom_T
blanchet@43618
  1112
  | chop_fun _ _ = raise Fail "unexpected non-function"
blanchet@43618
  1113
blanchet@43651
  1114
fun filter_type_args _ _ _ [] = []
blanchet@43651
  1115
  | filter_type_args thy s arity T_args =
blanchet@43705
  1116
    let
blanchet@43705
  1117
      (* will throw "TYPE" for pseudo-constants *)
blanchet@43807
  1118
      val U = if s = app_op_name then
blanchet@43705
  1119
                @{typ "('a => 'b) => 'a => 'b"} |> Logic.varifyT_global
blanchet@43705
  1120
              else
blanchet@43705
  1121
                s |> Sign.the_const_type thy
blanchet@43705
  1122
    in
blanchet@43652
  1123
      case Term.add_tvarsT (U |> chop_fun arity |> snd) [] of
blanchet@43652
  1124
        [] => []
blanchet@43652
  1125
      | res_U_vars =>
blanchet@43652
  1126
        let val U_args = (s, U) |> Sign.const_typargs thy in
blanchet@43652
  1127
          U_args ~~ T_args
blanchet@43652
  1128
          |> map_filter (fn (U, T) =>
blanchet@43652
  1129
                            if member (op =) res_U_vars (dest_TVar U) then
blanchet@43652
  1130
                              SOME T
blanchet@43652
  1131
                            else
blanchet@43652
  1132
                              NONE)
blanchet@43652
  1133
        end
blanchet@43651
  1134
    end
blanchet@43651
  1135
    handle TYPE _ => T_args
blanchet@43618
  1136
blanchet@43835
  1137
fun enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys =
blanchet@43618
  1138
  let
blanchet@43618
  1139
    val thy = Proof_Context.theory_of ctxt
blanchet@43618
  1140
    fun aux arity (CombApp (tm1, tm2)) =
blanchet@43618
  1141
        CombApp (aux (arity + 1) tm1, aux 0 tm2)
blanchet@43618
  1142
      | aux arity (CombConst (name as (s, _), T, T_args)) =
blanchet@43571
  1143
        let
blanchet@43571
  1144
          val level = level_of_type_sys type_sys
blanchet@43571
  1145
          val (T, T_args) =
blanchet@43571
  1146
            (* Aggressively merge most "hAPPs" if the type system is unsound
blanchet@43571
  1147
               anyway, by distinguishing overloads only on the homogenized
blanchet@43708
  1148
               result type. Don't do it for lightweight type systems, though,
blanchet@43708
  1149
               since it leads to too many unsound proofs. *)
blanchet@43807
  1150
            if s = const_prefix ^ app_op_name andalso
blanchet@43591
  1151
               length T_args = 2 andalso
blanchet@43707
  1152
               not (is_type_sys_virtually_sound type_sys) andalso
blanchet@43708
  1153
               heaviness_of_type_sys type_sys = Heavy then
blanchet@43835
  1154
              T_args |> map (homogenized_type ctxt nonmono_Ts level 0)
blanchet@43571
  1155
                     |> (fn Ts => let val T = hd Ts --> nth Ts 1 in
blanchet@43702
  1156
                                    (T --> T, tl Ts)
blanchet@43571
  1157
                                  end)
blanchet@43571
  1158
            else
blanchet@43571
  1159
              (T, T_args)
blanchet@43571
  1160
        in
blanchet@43571
  1161
          (case strip_prefix_and_unascii const_prefix s of
blanchet@43571
  1162
             NONE => (name, T_args)
blanchet@43571
  1163
           | SOME s'' =>
blanchet@43618
  1164
             let
blanchet@43618
  1165
               val s'' = invert_const s''
blanchet@43702
  1166
               fun filtered_T_args false = T_args
blanchet@43702
  1167
                 | filtered_T_args true = filter_type_args thy s'' arity T_args
blanchet@43618
  1168
             in
blanchet@43571
  1169
               case type_arg_policy type_sys s'' of
blanchet@43702
  1170
                 Explicit_Type_Args drop_args =>
blanchet@43702
  1171
                 (name, filtered_T_args drop_args)
blanchet@43702
  1172
               | Mangled_Type_Args drop_args =>
blanchet@43835
  1173
                 (mangled_const_name (filtered_T_args drop_args) name, [])
blanchet@43618
  1174
               | No_Type_Args => (name, [])
blanchet@43571
  1175
             end)
blanchet@43571
  1176
          |> (fn (name, T_args) => CombConst (name, T, T_args))
blanchet@43571
  1177
        end
blanchet@43618
  1178
      | aux _ tm = tm
blanchet@43618
  1179
  in aux 0 end
blanchet@43444
  1180
blanchet@43803
  1181
fun repair_combterm ctxt format nonmono_Ts type_sys sym_tab =
blanchet@43835
  1182
  not (is_setting_higher_order format type_sys)
blanchet@43835
  1183
  ? (introduce_explicit_apps_in_combterm sym_tab
blanchet@43835
  1184
     #> introduce_predicators_in_combterm sym_tab)
blanchet@43835
  1185
  #> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys
blanchet@43803
  1186
fun repair_fact ctxt format nonmono_Ts type_sys sym_tab =
blanchet@43571
  1187
  update_combformula (formula_map
blanchet@43803
  1188
      (repair_combterm ctxt format nonmono_Ts type_sys sym_tab))
blanchet@43444
  1189
blanchet@43444
  1190
(** Helper facts **)
blanchet@43444
  1191
blanchet@43926
  1192
(* The Boolean indicates that a fairly sound type encoding is needed. *)
blanchet@43926
  1193
val helper_table =
blanchet@43926
  1194
  [("COMBI", (false, @{thms Meson.COMBI_def})),
blanchet@43926
  1195
   ("COMBK", (false, @{thms Meson.COMBK_def})),
blanchet@43926
  1196
   ("COMBB", (false, @{thms Meson.COMBB_def})),
blanchet@43926
  1197
   ("COMBC", (false, @{thms Meson.COMBC_def})),
blanchet@43926
  1198
   ("COMBS", (false, @{thms Meson.COMBS_def})),
blanchet@43926
  1199
   ("fequal",
blanchet@43926
  1200
    (* This is a lie: Higher-order equality doesn't need a sound type encoding.
blanchet@43926
  1201
       However, this is done so for backward compatibility: Including the
blanchet@43926
  1202
       equality helpers by default in Metis breaks a few existing proofs. *)
blanchet@43926
  1203
    (true, @{thms fequal_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@43926
  1204
                  fequal_def [THEN Meson.iff_to_disjD, THEN conjunct2]})),
blanchet@43926
  1205
   ("fFalse", (true, @{thms True_or_False})),
blanchet@43926
  1206
   ("fFalse", (false, [@{lemma "~ fFalse" by (unfold fFalse_def) fast}])),
blanchet@43926
  1207
   ("fTrue", (true, @{thms True_or_False})),
blanchet@43926
  1208
   ("fTrue", (false, [@{lemma "fTrue" by (unfold fTrue_def) fast}])),
blanchet@43926
  1209
   ("fNot",
blanchet@43926
  1210
    (false, @{thms fNot_def [THEN Meson.iff_to_disjD, THEN conjunct1]
blanchet@43926
  1211
                   fNot_def [THEN Meson.iff_to_disjD, THEN conjunct2]})),
blanchet@43926
  1212
   ("fconj",
blanchet@43926
  1213
    (false,
blanchet@43926
  1214
     @{lemma "~ P | ~ Q | fconj P Q" "~ fconj P Q | P" "~ fconj P Q | Q"
blanchet@43926
  1215
         by (unfold fconj_def) fast+})),
blanchet@43926
  1216
   ("fdisj",
blanchet@43926
  1217
    (false,
blanchet@43926
  1218
     @{lemma "~ P | fdisj P Q" "~ Q | fdisj P Q" "~ fdisj P Q | P | Q"
blanchet@43926
  1219
         by (unfold fdisj_def) fast+})),
blanchet@43926
  1220
   ("fimplies",
blanchet@43926
  1221
    (false, @{lemma "P | fimplies P Q" "~ Q | fimplies P Q"
blanchet@43926
  1222
                    "~ fimplies P Q | ~ P | Q"
blanchet@43926
  1223
                by (unfold fimplies_def) fast+})),
blanchet@43926
  1224
   ("If", (true, @{thms if_True if_False True_or_False}))]
blanchet@43926
  1225
blanchet@43444
  1226
fun ti_ti_helper_fact () =
blanchet@43444
  1227
  let
blanchet@43444
  1228
    fun var s = ATerm (`I s, [])
blanchet@43460
  1229
    fun tag tm = ATerm (`make_fixed_const type_tag_name, [var "X", tm])
blanchet@43444
  1230
  in
blanchet@43483
  1231
    Formula (helper_prefix ^ "ti_ti", Axiom,
blanchet@43841
  1232
             AAtom (ATerm (`I tptp_equal, [tag (tag (var "Y")), tag (var "Y")]))
blanchet@43748
  1233
             |> close_formula_universally, simp_info, NONE)
blanchet@43444
  1234
  end
blanchet@43444
  1235
blanchet@43905
  1236
fun helper_facts_for_sym ctxt format type_sys (s, {types, ...} : sym_info) =
blanchet@43444
  1237
  case strip_prefix_and_unascii const_prefix s of
blanchet@43444
  1238
    SOME mangled_s =>
blanchet@43444
  1239
    let
blanchet@43444
  1240
      val thy = Proof_Context.theory_of ctxt
blanchet@43444
  1241
      val unmangled_s = mangled_s |> unmangled_const_name
blanchet@43764
  1242
      fun dub_and_inst c needs_fairly_sound (th, j) =
blanchet@43750
  1243
        ((c ^ "_" ^ string_of_int j ^
blanchet@43764
  1244
          (if needs_fairly_sound then typed_helper_suffix
blanchet@43750
  1245
           else untyped_helper_suffix),
blanchet@43750
  1246
          General),
blanchet@43444
  1247
         let val t = th |> prop_of in
blanchet@43618
  1248
           t |> ((case general_type_arg_policy type_sys of
blanchet@43618
  1249
                    Mangled_Type_Args _ => true
blanchet@43618
  1250
                  | _ => false) andalso
blanchet@43444
  1251
                 not (null (Term.hidden_polymorphism t)))
blanchet@43905
  1252
                ? (case types of
blanchet@43905
  1253
                     [T] => specialize_type thy (invert_const unmangled_s, T)
blanchet@43905
  1254
                   | _ => I)
blanchet@43444
  1255
         end)
blanchet@43444
  1256
      fun make_facts eq_as_iff =
blanchet@43835
  1257
        map_filter (make_fact ctxt format type_sys false eq_as_iff false)
blanchet@43764
  1258
      val fairly_sound = is_type_sys_fairly_sound type_sys
blanchet@43444
  1259
    in
blanchet@43926
  1260
      helper_table
blanchet@43765
  1261
      |> maps (fn (metis_s, (needs_fairly_sound, ths)) =>
blanchet@43444
  1262
                  if metis_s <> unmangled_s orelse
blanchet@43765
  1263
                     (needs_fairly_sound andalso not fairly_sound) then
blanchet@43444
  1264
                    []
blanchet@43444
  1265
                  else
blanchet@43444
  1266
                    ths ~~ (1 upto length ths)
blanchet@43764
  1267
                    |> map (dub_and_inst mangled_s needs_fairly_sound)
blanchet@43764
  1268
                    |> make_facts (not needs_fairly_sound))
blanchet@43444
  1269
    end
blanchet@43444
  1270
  | NONE => []
blanchet@43803
  1271
fun helper_facts_for_sym_table ctxt format type_sys sym_tab =
blanchet@43803
  1272
  Symtab.fold_rev (append o helper_facts_for_sym ctxt format type_sys) sym_tab
blanchet@43803
  1273
                  []
blanchet@43444
  1274
blanchet@43835
  1275
fun translate_atp_fact ctxt format type_sys keep_trivial =
blanchet@43835
  1276
  `(make_fact ctxt format type_sys keep_trivial true true o apsnd prop_of)
blanchet@43444
  1277
blanchet@43926
  1278
(***************************************************************)
blanchet@43926
  1279
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
blanchet@43926
  1280
(***************************************************************)
blanchet@43926
  1281
blanchet@43926
  1282
fun set_insert (x, s) = Symtab.update (x, ()) s
blanchet@43926
  1283
blanchet@43926
  1284
fun add_classes (sorts, cset) = List.foldl set_insert cset (flat sorts)
blanchet@43926
  1285
blanchet@43926
  1286
(* Remove this trivial type class (FIXME: similar code elsewhere) *)
blanchet@43926
  1287
fun delete_type cset = Symtab.delete_safe (the_single @{sort HOL.type}) cset
blanchet@43926
  1288
blanchet@43926
  1289
fun tfree_classes_of_terms ts =
blanchet@43926
  1290
  let val sorts_list = map (map #2 o OldTerm.term_tfrees) ts
blanchet@43926
  1291
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
blanchet@43926
  1292
blanchet@43926
  1293
fun tvar_classes_of_terms ts =
blanchet@43926
  1294
  let val sorts_list = map (map #2 o OldTerm.term_tvars) ts
blanchet@43926
  1295
  in  Symtab.keys (delete_type (List.foldl add_classes Symtab.empty sorts_list))  end;
blanchet@43926
  1296
blanchet@43926
  1297
(*fold type constructors*)
blanchet@43926
  1298
fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
blanchet@43926
  1299
  | fold_type_consts _ _ x = x;
blanchet@43926
  1300
blanchet@43926
  1301
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
blanchet@43926
  1302
fun add_type_consts_in_term thy =
blanchet@43926
  1303
  let
blanchet@43926
  1304
    fun aux (Const (@{const_name Meson.skolem}, _) $ _) = I
blanchet@43926
  1305
      | aux (t $ u) = aux t #> aux u
blanchet@43926
  1306
      | aux (Const x) =
blanchet@43926
  1307
        fold (fold_type_consts set_insert) (Sign.const_typargs thy x)
blanchet@43926
  1308
      | aux (Abs (_, _, u)) = aux u
blanchet@43926
  1309
      | aux _ = I
blanchet@43926
  1310
  in aux end
blanchet@43926
  1311
blanchet@43926
  1312
fun type_consts_of_terms thy ts =
blanchet@43926
  1313
  Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
blanchet@43926
  1314
blanchet@43926
  1315
blanchet@43803
  1316
fun translate_formulas ctxt format prem_kind type_sys hyp_ts concl_t
blanchet@43803
  1317
                       rich_facts =
blanchet@43444
  1318
  let
blanchet@43444
  1319
    val thy = Proof_Context.theory_of ctxt
blanchet@43444
  1320
    val fact_ts = map (prop_of o snd o snd) rich_facts
blanchet@43444
  1321
    val (facts, fact_names) =
blanchet@43444
  1322
      rich_facts
blanchet@43444
  1323
      |> map_filter (fn (NONE, _) => NONE
blanchet@43444
  1324
                      | (SOME fact, (name, _)) => SOME (fact, name))
blanchet@43444
  1325
      |> ListPair.unzip
blanchet@43444
  1326
    (* Remove existing facts from the conjecture, as this can dramatically
blanchet@43444
  1327
       boost an ATP's performance (for some reason). *)
blanchet@43444
  1328
    val hyp_ts = hyp_ts |> filter_out (member (op aconv) fact_ts)
blanchet@43444
  1329
    val goal_t = Logic.list_implies (hyp_ts, concl_t)
blanchet@43444
  1330
    val all_ts = goal_t :: fact_ts
blanchet@43444
  1331
    val subs = tfree_classes_of_terms all_ts
blanchet@43444
  1332
    val supers = tvar_classes_of_terms all_ts
blanchet@43444
  1333
    val tycons = type_consts_of_terms thy all_ts
blanchet@43835
  1334
    val conjs =
blanchet@43835
  1335
      hyp_ts @ [concl_t] |> make_conjecture ctxt format prem_kind type_sys
blanchet@43444
  1336
    val (supers', arity_clauses) =
blanchet@43460
  1337
      if level_of_type_sys type_sys = No_Types then ([], [])
blanchet@43444
  1338
      else make_arity_clauses thy tycons supers
blanchet@43444
  1339
    val class_rel_clauses = make_class_rel_clauses thy subs supers'
blanchet@43444
  1340
  in
blanchet@43444
  1341
    (fact_names |> map single, (conjs, facts, class_rel_clauses, arity_clauses))
blanchet@43444
  1342
  end
blanchet@43444
  1343
blanchet@43444
  1344
fun fo_literal_from_type_literal (TyLitVar (class, name)) =
blanchet@43444
  1345
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
  1346
  | fo_literal_from_type_literal (TyLitFree (class, name)) =
blanchet@43444
  1347
    (true, ATerm (class, [ATerm (name, [])]))
blanchet@43444
  1348
blanchet@43444
  1349
fun formula_from_fo_literal (pos, t) = AAtom t |> not pos ? mk_anot
blanchet@43444
  1350
blanchet@43835
  1351
fun type_pred_combterm ctxt nonmono_Ts type_sys T tm =
blanchet@43807
  1352
  CombApp (CombConst (`make_fixed_const type_pred_name, T --> @{typ bool}, [T])
blanchet@43835
  1353
           |> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys,
blanchet@43444
  1354
           tm)
blanchet@43444
  1355
blanchet@43747
  1356
fun var_occurs_positively_naked_in_term _ (SOME false) _ accum = accum
blanchet@43747
  1357
  | var_occurs_positively_naked_in_term name _ (ATerm ((s, _), tms)) accum =
blanchet@43841
  1358
    accum orelse (is_tptp_equal s andalso member (op =) tms (ATerm (name, [])))
blanchet@43747
  1359
fun is_var_nonmonotonic_in_formula _ _ (SOME false) _ = false
blanchet@43747
  1360
  | is_var_nonmonotonic_in_formula pos phi _ name =
blanchet@43747
  1361
    formula_fold pos (var_occurs_positively_naked_in_term name) phi false
blanchet@43705
  1362
blanchet@43835
  1363
fun mk_const_aterm x T_args args =
blanchet@43835
  1364
  ATerm (x, map (fo_term_from_typ false) T_args @ args)
blanchet@43835
  1365
blanchet@43803
  1366
fun tag_with_type ctxt format nonmono_Ts type_sys T tm =
blanchet@43700
  1367
  CombConst (`make_fixed_const type_tag_name, T --> T, [T])
blanchet@43835
  1368
  |> enforce_type_arg_policy_in_combterm ctxt nonmono_Ts type_sys
blanchet@43803
  1369
  |> term_from_combterm ctxt format nonmono_Ts type_sys Top_Level
blanchet@43700
  1370
  |> (fn ATerm (s, tms) => ATerm (s, tms @ [tm]))
blanchet@43803
  1371
and term_from_combterm ctxt format nonmono_Ts type_sys =
blanchet@43444
  1372
  let
blanchet@43803
  1373
    fun aux site u =
blanchet@43803
  1374
      let
blanchet@43803
  1375
        val (head, args) = strip_combterm_comb u
blanchet@43803
  1376
        val (x as (s, _), T_args) =
blanchet@43803
  1377
          case head of
blanchet@43803
  1378
            CombConst (name, _, T_args) => (name, T_args)
blanchet@43803
  1379
          | CombVar (name, _) => (name, [])
blanchet@43803
  1380
          | CombApp _ => raise Fail "impossible \"CombApp\""
blanchet@43841
  1381
        val arg_site = if site = Top_Level andalso is_tptp_equal s then Eq_Arg
blanchet@43803
  1382
                       else Elsewhere
blanchet@43835
  1383
        val t = mk_const_aterm x T_args (map (aux arg_site) args)
blanchet@43803
  1384
        val T = combtyp_of u
blanchet@43803
  1385
      in
blanchet@43803
  1386
        t |> (if should_tag_with_type ctxt nonmono_Ts type_sys site u T then
blanchet@43803
  1387
                tag_with_type ctxt format nonmono_Ts type_sys T
blanchet@43803
  1388
              else
blanchet@43803
  1389
                I)
blanchet@43803
  1390
      end
blanchet@43803
  1391
  in aux end
blanchet@43803
  1392
and formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43803
  1393
                             should_predicate_on_var =
blanchet@43700
  1394
  let
blanchet@43835
  1395
    val higher_order = is_setting_higher_order format type_sys
blanchet@43803
  1396
    val do_term = term_from_combterm ctxt format nonmono_Ts type_sys Top_Level
blanchet@43444
  1397
    val do_bound_type =
blanchet@43552
  1398
      case type_sys of
blanchet@43587
  1399
        Simple_Types level =>
blanchet@43835
  1400
        homogenized_type ctxt nonmono_Ts level 0
blanchet@43835
  1401
        #> mangled_type higher_order false 0 #> SOME
blanchet@43552
  1402
      | _ => K NONE
blanchet@43747
  1403
    fun do_out_of_bound_type pos phi universal (name, T) =
blanchet@43705
  1404
      if should_predicate_on_type ctxt nonmono_Ts type_sys
blanchet@43747
  1405
             (fn () => should_predicate_on_var pos phi universal name) T then
blanchet@43705
  1406
        CombVar (name, T)
blanchet@43835
  1407
        |> type_pred_combterm ctxt nonmono_Ts type_sys T
blanchet@43747
  1408
        |> do_term |> AAtom |> SOME
blanchet@43444
  1409
      else
blanchet@43444
  1410
        NONE
blanchet@43747
  1411
    fun do_formula pos (AQuant (q, xs, phi)) =
blanchet@43747
  1412
        let
blanchet@43747
  1413
          val phi = phi |> do_formula pos
blanchet@43747
  1414
          val universal = Option.map (q = AExists ? not) pos
blanchet@43747
  1415
        in
blanchet@43705
  1416
          AQuant (q, xs |> map (apsnd (fn NONE => NONE
blanchet@43705
  1417
                                        | SOME T => do_bound_type T)),
blanchet@43705
  1418
                  (if q = AForall then mk_ahorn else fold_rev (mk_aconn AAnd))
blanchet@43705
  1419
                      (map_filter
blanchet@43705
  1420
                           (fn (_, NONE) => NONE
blanchet@43705
  1421
                             | (s, SOME T) =>
blanchet@43747
  1422
                               do_out_of_bound_type pos phi universal (s, T))
blanchet@43747
  1423
                           xs)
blanchet@43705
  1424
                      phi)
blanchet@43705
  1425
        end
blanchet@43747
  1426
      | do_formula pos (AConn conn) = aconn_map pos do_formula conn
blanchet@43747
  1427
      | do_formula _ (AAtom tm) = AAtom (do_term tm)
blanchet@43747
  1428
  in do_formula o SOME end
blanchet@43444
  1429
blanchet@43797
  1430
fun bound_atomic_types format type_sys Ts =
blanchet@43592
  1431
  mk_ahorn (map (formula_from_fo_literal o fo_literal_from_type_literal)
blanchet@43926
  1432
                (type_literals_for_types format type_sys Axiom Ts))
blanchet@43592
  1433
blanchet@43797
  1434
fun formula_for_fact ctxt format nonmono_Ts type_sys
blanchet@43444
  1435
                     ({combformula, atomic_types, ...} : translated_formula) =
blanchet@43592
  1436
  combformula
blanchet@43592
  1437
  |> close_combformula_universally
blanchet@43803
  1438
  |> formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43747
  1439
                              is_var_nonmonotonic_in_formula true
blanchet@43797
  1440
  |> bound_atomic_types format type_sys atomic_types
blanchet@43444
  1441
  |> close_formula_universally
blanchet@43444
  1442
blanchet@43444
  1443
(* Each fact is given a unique fact number to avoid name clashes (e.g., because
blanchet@43444
  1444
   of monomorphization). The TPTP explicitly forbids name clashes, and some of
blanchet@43444
  1445
   the remote provers might care. *)
blanchet@43797
  1446
fun formula_line_for_fact ctxt format prefix nonmono_Ts type_sys
blanchet@43511
  1447
                          (j, formula as {name, locality, kind, ...}) =
blanchet@43550
  1448
  Formula (prefix ^ (if polymorphism_of_type_sys type_sys = Polymorphic then ""
blanchet@43550
  1449
                     else string_of_int j ^ "_") ^
blanchet@43518
  1450
           ascii_of name,
blanchet@43797
  1451
           kind, formula_for_fact ctxt format nonmono_Ts type_sys formula, NONE,
blanchet@43748
  1452
           case locality of
blanchet@43748
  1453
             Intro => intro_info
blanchet@43748
  1454
           | Elim => elim_info
blanchet@43748
  1455
           | Simp => simp_info
blanchet@43748
  1456
           | _ => NONE)
blanchet@43444
  1457
blanchet@43927
  1458
fun formula_line_for_class_rel_clause ({name, subclass, superclass, ...}
blanchet@43927
  1459
                                       : class_rel_clause) =
blanchet@43444
  1460
  let val ty_arg = ATerm (`I "T", []) in
blanchet@43448
  1461
    Formula (class_rel_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
  1462
             AConn (AImplies, [AAtom (ATerm (subclass, [ty_arg])),
blanchet@43444
  1463
                               AAtom (ATerm (superclass, [ty_arg]))])
blanchet@43748
  1464
             |> close_formula_universally, intro_info, NONE)
blanchet@43444
  1465
  end
blanchet@43444
  1466
blanchet@43444
  1467
fun fo_literal_from_arity_literal (TConsLit (c, t, args)) =
blanchet@43444
  1468
    (true, ATerm (c, [ATerm (t, map (fn arg => ATerm (arg, [])) args)]))
blanchet@43444
  1469
  | fo_literal_from_arity_literal (TVarLit (c, sort)) =
blanchet@43444
  1470
    (false, ATerm (c, [ATerm (sort, [])]))
blanchet@43444
  1471
blanchet@43927
  1472
fun formula_line_for_arity_clause ({name, prem_lits, concl_lits, ...}
blanchet@43927
  1473
                                   : arity_clause) =
blanchet@43448
  1474
  Formula (arity_clause_prefix ^ ascii_of name, Axiom,
blanchet@43444
  1475
           mk_ahorn (map (formula_from_fo_literal o apfst not
blanchet@43766
  1476
                          o fo_literal_from_arity_literal) prem_lits)
blanchet@43444
  1477
                    (formula_from_fo_literal
blanchet@43766
  1478
                         (fo_literal_from_arity_literal concl_lits))
blanchet@43748
  1479
           |> close_formula_universally, intro_info, NONE)
blanchet@43444
  1480
blanchet@43803
  1481
fun formula_line_for_conjecture ctxt format nonmono_Ts type_sys
blanchet@43444
  1482
        ({name, kind, combformula, ...} : translated_formula) =
blanchet@43448
  1483
  Formula (conjecture_prefix ^ name, kind,
blanchet@43803
  1484
           formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43780
  1485
               is_var_nonmonotonic_in_formula false
blanchet@43780
  1486
               (close_combformula_universally combformula)
blanchet@43444
  1487
           |> close_formula_universally, NONE, NONE)
blanchet@43444
  1488
blanchet@43797
  1489
fun free_type_literals format type_sys
blanchet@43797
  1490
                       ({atomic_types, ...} : translated_formula) =
blanchet@43926
  1491
  atomic_types |> type_literals_for_types format type_sys Conjecture
blanchet@43444
  1492
               |> map fo_literal_from_type_literal
blanchet@43444
  1493
blanchet@43444
  1494
fun formula_line_for_free_type j lit =
blanchet@43926
  1495
  Formula (tfree_clause_prefix ^ string_of_int j, Hypothesis,
blanchet@43444
  1496
           formula_from_fo_literal lit, NONE, NONE)
blanchet@43797
  1497
fun formula_lines_for_free_types format type_sys facts =
blanchet@43444
  1498
  let
blanchet@43797
  1499
    val litss = map (free_type_literals format type_sys) facts
blanchet@43444
  1500
    val lits = fold (union (op =)) litss []
blanchet@43444
  1501
  in map2 formula_line_for_free_type (0 upto length lits - 1) lits end
blanchet@43444
  1502
blanchet@43444
  1503
(** Symbol declarations **)
blanchet@43415
  1504
blanchet@43445
  1505
fun should_declare_sym type_sys pred_sym s =
blanchet@43839
  1506
  is_tptp_user_symbol s andalso not (String.isPrefix bound_var_prefix s) andalso
blanchet@43765
  1507
  (case type_sys of
blanchet@43765
  1508
     Simple_Types _ => true
blanchet@43765
  1509
   | Tags (_, _, Light) => true
blanchet@43765
  1510
   | _ => not pred_sym)
blanchet@43413
  1511
blanchet@43755
  1512
fun sym_decl_table_for_facts ctxt type_sys repaired_sym_tab (conjs, facts) =
blanchet@43445
  1513
  let
blanchet@43568
  1514
    fun add_combterm in_conj tm =
blanchet@43445
  1515
      let val (head, args) = strip_combterm_comb tm in
blanchet@43445
  1516
        (case head of
blanchet@43445
  1517
           CombConst ((s, s'), T, T_args) =>
blanchet@43445
  1518
           let val pred_sym = is_pred_sym repaired_sym_tab s in
blanchet@43445
  1519
             if should_declare_sym type_sys pred_sym s then
blanchet@43447
  1520
               Symtab.map_default (s, [])
blanchet@43755
  1521
                   (insert_type ctxt #3 (s', T_args, T, pred_sym, length args,
blanchet@43755
  1522
                                         in_conj))
blanchet@43445
  1523
             else
blanchet@43445
  1524
               I
blanchet@43445
  1525
           end
blanchet@43445
  1526
         | _ => I)
blanchet@43568
  1527
        #> fold (add_combterm in_conj) args
blanchet@43445
  1528
      end
blanchet@43568
  1529
    fun add_fact in_conj =
blanchet@43705
  1530
      fact_lift (formula_fold NONE (K (add_combterm in_conj)))
blanchet@43568
  1531
  in
blanchet@43568
  1532
    Symtab.empty
blanchet@43568
  1533
    |> is_type_sys_fairly_sound type_sys
blanchet@43568
  1534
       ? (fold (add_fact true) conjs #> fold (add_fact false) facts)
blanchet@43568
  1535
  end
blanchet@43445
  1536
blanchet@43755
  1537
(* These types witness that the type classes they belong to allow infinite
blanchet@43755
  1538
   models and hence that any types with these type classes is monotonic. *)
blanchet@43926
  1539
val known_infinite_types =
blanchet@43926
  1540
  [@{typ nat}, Type ("Int.int", []), @{typ "nat => bool"}]
blanchet@43755
  1541
blanchet@43555
  1542
(* This inference is described in section 2.3 of Claessen et al.'s "Sorting it
blanchet@43555
  1543
   out with monotonicity" paper presented at CADE 2011. *)
blanchet@43755
  1544
fun add_combterm_nonmonotonic_types _ _ (SOME false) _ = I
blanchet@43700
  1545
  | add_combterm_nonmonotonic_types ctxt level _
blanchet@43841
  1546
        (CombApp (CombApp (CombConst ((s, _), Type (_, [T, _]), _), tm1), tm2)) =
blanchet@43841
  1547
    (is_tptp_equal s andalso exists is_var_or_bound_var [tm1, tm2] andalso
blanchet@43700
  1548
     (case level of
blanchet@43755
  1549
        Nonmonotonic_Types =>
blanchet@43755
  1550
        not (is_type_surely_infinite ctxt known_infinite_types T)
blanchet@43700
  1551
      | Finite_Types => is_type_surely_finite ctxt T
blanchet@43755
  1552
      | _ => true)) ? insert_type ctxt I (deep_freeze_type T)
blanchet@43700
  1553
  | add_combterm_nonmonotonic_types _ _ _ _ = I
blanchet@43700
  1554
fun add_fact_nonmonotonic_types ctxt level ({kind, combformula, ...}
blanchet@43700
  1555
                                            : translated_formula) =
blanchet@43705
  1556
  formula_fold (SOME (kind <> Conjecture))
blanchet@43700
  1557
               (add_combterm_nonmonotonic_types ctxt level) combformula
blanchet@43755
  1558
fun nonmonotonic_types_for_facts ctxt type_sys facts =
blanchet@43700
  1559
  let val level = level_of_type_sys type_sys in
blanchet@43755
  1560
    if level = Nonmonotonic_Types orelse level = Finite_Types then
blanchet@43755
  1561
      [] |> fold (add_fact_nonmonotonic_types ctxt level) facts
blanchet@43755
  1562
         (* We must add "bool" in case the helper "True_or_False" is added
blanchet@43755
  1563
            later. In addition, several places in the code rely on the list of
blanchet@43755
  1564
            nonmonotonic types not being empty. *)
blanchet@43755
  1565
         |> insert_type ctxt I @{typ bool}
blanchet@43755
  1566
    else
blanchet@43755
  1567
      []
blanchet@43700
  1568
  end
blanchet@43547
  1569
blanchet@43835
  1570
fun decl_line_for_sym ctxt format nonmono_Ts type_sys s
blanchet@43835
  1571
                      (s', T_args, T, pred_sym, ary, _) =
blanchet@43835
  1572
  let
blanchet@43835
  1573
    val (higher_order, T_arg_Ts, level) =
blanchet@43835
  1574
      case type_sys of
blanchet@43835
  1575
        Simple_Types level => (format = THF, [], level)
blanchet@43835
  1576
      | _ => (false, replicate (length T_args) homo_infinite_type, No_Types)
blanchet@43835
  1577
  in
blanchet@43839
  1578
    Decl (sym_decl_prefix ^ s, (s, s'),
blanchet@43835
  1579
          (T_arg_Ts ---> (T |> homogenized_type ctxt nonmono_Ts level ary))
blanchet@43835
  1580
          |> mangled_type higher_order pred_sym (length T_arg_Ts + ary))
blanchet@43835
  1581
  end
blanchet@43450
  1582
blanchet@43463
  1583
fun is_polymorphic_type T = fold_atyps (fn TVar _ => K true | _ => I) T false
blanchet@43463
  1584
blanchet@43797
  1585
fun formula_line_for_pred_sym_decl ctxt format conj_sym_kind nonmono_Ts type_sys
blanchet@43797
  1586
                                   n s j (s', T_args, T, _, ary, in_conj) =
blanchet@43450
  1587
  let
blanchet@43580
  1588
    val (kind, maybe_negate) =
blanchet@43580
  1589
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@43580
  1590
      else (Axiom, I)
blanchet@43618
  1591
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43450
  1592
    val bound_names =
blanchet@43450
  1593
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  1594
    val bounds =
blanchet@43450
  1595
      bound_names ~~ arg_Ts |> map (fn (name, T) => CombConst (name, T, []))
blanchet@43450
  1596
    val bound_Ts =
blanchet@43463
  1597
      arg_Ts |> map (fn T => if n > 1 orelse is_polymorphic_type T then SOME T
blanchet@43463
  1598
                             else NONE)
blanchet@43450
  1599
  in
blanchet@43839
  1600
    Formula (sym_formula_prefix ^ s ^
blanchet@43580
  1601
             (if n > 1 then "_" ^ string_of_int j else ""), kind,
blanchet@43450
  1602
             CombConst ((s, s'), T, T_args)
blanchet@43700
  1603
             |> fold (curry (CombApp o swap)) bounds
blanchet@43835
  1604
             |> type_pred_combterm ctxt nonmono_Ts type_sys res_T
blanchet@43804
  1605
             |> AAtom |> mk_aquant AForall (bound_names ~~ bound_Ts)
blanchet@43803
  1606
             |> formula_from_combformula ctxt format nonmono_Ts type_sys
blanchet@43747
  1607
                                         (K (K (K (K true)))) true
blanchet@43797
  1608
             |> n > 1 ? bound_atomic_types format type_sys (atyps_of T)
blanchet@43580
  1609
             |> close_formula_universally
blanchet@43580
  1610
             |> maybe_negate,
blanchet@43748
  1611
             intro_info, NONE)
blanchet@43450
  1612
  end
blanchet@43450
  1613
blanchet@43797
  1614
fun formula_lines_for_tag_sym_decl ctxt format conj_sym_kind nonmono_Ts type_sys
blanchet@43797
  1615
        n s (j, (s', T_args, T, pred_sym, ary, in_conj)) =
blanchet@43700
  1616
  let
blanchet@43700
  1617
    val ident_base =
blanchet@43839
  1618
      sym_formula_prefix ^ s ^ (if n > 1 then "_" ^ string_of_int j else "")
blanchet@43721
  1619
    val (kind, maybe_negate) =
blanchet@43721
  1620
      if in_conj then (conj_sym_kind, conj_sym_kind = Conjecture ? mk_anot)
blanchet@43721
  1621
      else (Axiom, I)
blanchet@43700
  1622
    val (arg_Ts, res_T) = chop_fun ary T
blanchet@43700
  1623
    val bound_names =
blanchet@43700
  1624
      1 upto length arg_Ts |> map (`I o make_bound_var o string_of_int)
blanchet@43700
  1625
    val bounds = bound_names |> map (fn name => ATerm (name, []))
blanchet@43835
  1626
    val cst = mk_const_aterm (s, s') T_args
blanchet@43701
  1627
    val atomic_Ts = atyps_of T
blanchet@43705
  1628
    fun eq tms =
blanchet@43705
  1629
      (if pred_sym then AConn (AIff, map AAtom tms)
blanchet@43841
  1630
       else AAtom (ATerm (`I tptp_equal, tms)))
blanchet@43797
  1631
      |> bound_atomic_types format type_sys atomic_Ts
blanchet@43701
  1632
      |> close_formula_universally
blanchet@43721
  1633
      |> maybe_negate
blanchet@43707
  1634
    val should_encode = should_encode_type ctxt nonmono_Ts All_Types
blanchet@43803
  1635
    val tag_with = tag_with_type ctxt format nonmono_Ts type_sys
blanchet@43700
  1636
    val add_formula_for_res =
blanchet@43700
  1637
      if should_encode res_T then
blanchet@43721
  1638
        cons (Formula (ident_base ^ "_res", kind,
blanchet@43835
  1639
                       eq [tag_with res_T (cst bounds), cst bounds],
blanchet@43748
  1640
                       simp_info, NONE))
blanchet@43700
  1641
      else
blanchet@43700
  1642
        I
blanchet@43700
  1643
    fun add_formula_for_arg k =
blanchet@43700
  1644
      let val arg_T = nth arg_Ts k in
blanchet@43700
  1645
        if should_encode arg_T then
blanchet@43700
  1646
          case chop k bounds of
blanchet@43700
  1647
            (bounds1, bound :: bounds2) =>
blanchet@43721
  1648
            cons (Formula (ident_base ^ "_arg" ^ string_of_int (k + 1), kind,
blanchet@43835
  1649
                           eq [cst (bounds1 @ tag_with arg_T bound :: bounds2),
blanchet@43835
  1650
                               cst bounds],
blanchet@43748
  1651
                           simp_info, NONE))
blanchet@43700
  1652
          | _ => raise Fail "expected nonempty tail"
blanchet@43700
  1653
        else
blanchet@43700
  1654
          I
blanchet@43700
  1655
      end
blanchet@43700
  1656
  in
blanchet@43705
  1657
    [] |> not pred_sym ? add_formula_for_res
blanchet@43700
  1658
       |> fold add_formula_for_arg (ary - 1 downto 0)
blanchet@43700
  1659
  end
blanchet@43700
  1660
blanchet@43707
  1661
fun result_type_of_decl (_, _, T, _, ary, _) = chop_fun ary T |> snd
blanchet@43707
  1662
blanchet@43797
  1663
fun problem_lines_for_sym_decls ctxt format conj_sym_kind nonmono_Ts type_sys
blanchet@43580
  1664
                                (s, decls) =
blanchet@43839
  1665
  case type_sys of
blanchet@43839
  1666
    Simple_Types _ =>
blanchet@43839
  1667
    decls |> map (decl_line_for_sym ctxt format nonmono_Ts type_sys s)
blanchet@43839
  1668
  | Preds _ =>
blanchet@43839
  1669
    let
blanchet@43839
  1670
      val decls =
blanchet@43839
  1671
        case decls of
blanchet@43839
  1672
          decl :: (decls' as _ :: _) =>
blanchet@43839
  1673
          let val T = result_type_of_decl decl in
blanchet@43839
  1674
            if forall (curry (type_instance ctxt o swap) T
blanchet@43839
  1675
                       o result_type_of_decl) decls' then
blanchet@43839
  1676
              [decl]
blanchet@43839
  1677
            else
blanchet@43839
  1678
              decls
blanchet@43839
  1679
          end
blanchet@43839
  1680
        | _ => decls
blanchet@43839
  1681
      val n = length decls
blanchet@43839
  1682
      val decls =
blanchet@43839
  1683
        decls
blanchet@43839
  1684
        |> filter (should_predicate_on_type ctxt nonmono_Ts type_sys (K true)
blanchet@43839
  1685
                   o result_type_of_decl)
blanchet@43839
  1686
    in
blanchet@43839
  1687
      (0 upto length decls - 1, decls)
blanchet@43839
  1688
      |-> map2 (formula_line_for_pred_sym_decl ctxt format conj_sym_kind
blanchet@43839
  1689
                                               nonmono_Ts type_sys n s)
blanchet@43839
  1690
    end
blanchet@43839
  1691
  | Tags (_, _, heaviness) =>
blanchet@43839
  1692
    (case heaviness of
blanchet@43839
  1693
       Heavy => []
blanchet@43839
  1694
     | Light =>
blanchet@43839
  1695
       let val n = length decls in
blanchet@43839
  1696
         (0 upto n - 1 ~~ decls)
blanchet@43839
  1697
         |> maps (formula_lines_for_tag_sym_decl ctxt format conj_sym_kind
blanchet@43839
  1698
                                                 nonmono_Ts type_sys n s)
blanchet@43839
  1699
       end)
blanchet@43450
  1700
blanchet@43797
  1701
fun problem_lines_for_sym_decl_table ctxt format conj_sym_kind nonmono_Ts
blanchet@43797
  1702
                                     type_sys sym_decl_tab =
blanchet@43839
  1703
  sym_decl_tab
blanchet@43839
  1704
  |> Symtab.dest
blanchet@43839
  1705
  |> sort_wrt fst
blanchet@43839
  1706
  |> rpair []
blanchet@43839
  1707
  |-> fold_rev (append o problem_lines_for_sym_decls ctxt format conj_sym_kind
blanchet@43839
  1708
                                                     nonmono_Ts type_sys)
blanchet@43414
  1709
blanchet@43708
  1710
fun should_add_ti_ti_helper (Tags (Polymorphic, level, Heavy)) =
blanchet@43702
  1711
    level = Nonmonotonic_Types orelse level = Finite_Types
blanchet@43702
  1712
  | should_add_ti_ti_helper _ = false
blanchet@43702
  1713
blanchet@43780
  1714
fun offset_of_heading_in_problem _ [] j = j
blanchet@43780
  1715
  | offset_of_heading_in_problem needle ((heading, lines) :: problem) j =
blanchet@43780
  1716
    if heading = needle then j
blanchet@43780
  1717
    else offset_of_heading_in_problem needle problem (j + length lines)
blanchet@43780
  1718
blanchet@43839
  1719
val implicit_declsN = "Should-be-implicit typings"
blanchet@43839
  1720
val explicit_declsN = "Explicit typings"
blanchet@41405
  1721
val factsN = "Relevant facts"
blanchet@41405
  1722
val class_relsN = "Class relationships"
blanchet@43414
  1723
val aritiesN = "Arities"
blanchet@41405
  1724
val helpersN = "Helper facts"
blanchet@41405
  1725
val conjsN = "Conjectures"
blanchet@41561
  1726
val free_typesN = "Type variables"
blanchet@41405
  1727
blanchet@43780
  1728
fun prepare_atp_problem ctxt format conj_sym_kind prem_kind type_sys
blanchet@43933
  1729
                        explicit_apply readable_names hyp_ts concl_t facts =
blanchet@38506
  1730
  let
blanchet@41561
  1731
    val (fact_names, (conjs, facts, class_rel_clauses, arity_clauses)) =
blanchet@43803
  1732
      translate_formulas ctxt format prem_kind type_sys hyp_ts concl_t facts
blanchet@43905
  1733
    val sym_tab = conjs @ facts |> sym_table_for_facts ctxt explicit_apply
blanchet@43755
  1734
    val nonmono_Ts = conjs @ facts |> nonmonotonic_types_for_facts ctxt type_sys
blanchet@43803
  1735
    val repair = repair_fact ctxt format nonmono_Ts type_sys sym_tab
blanchet@43552
  1736
    val (conjs, facts) = (conjs, facts) |> pairself (map repair)
blanchet@43905
  1737
    val repaired_sym_tab =
blanchet@43905
  1738
      conjs @ facts |> sym_table_for_facts ctxt (SOME false)
blanchet@43444
  1739
    val helpers =
blanchet@43803
  1740
      repaired_sym_tab |> helper_facts_for_sym_table ctxt format type_sys
blanchet@43803
  1741
                       |> map repair
blanchet@43765
  1742
    val lavish_nonmono_Ts =
blanchet@43765
  1743
      if null nonmono_Ts orelse
blanchet@43765
  1744
         polymorphism_of_type_sys type_sys <> Polymorphic then
blanchet@43765
  1745
        nonmono_Ts
blanchet@43765
  1746
      else
blanchet@43765
  1747
        [TVar (("'a", 0), HOLogic.typeS)]
blanchet@43550
  1748
    val sym_decl_lines =
blanchet@43596
  1749
      (conjs, helpers @ facts)
blanchet@43755
  1750
      |> sym_decl_table_for_facts ctxt type_sys repaired_sym_tab
blanchet@43797
  1751
      |> problem_lines_for_sym_decl_table ctxt format conj_sym_kind
blanchet@43797
  1752
                                          lavish_nonmono_Ts type_sys
blanchet@43750
  1753
    val helper_lines =
blanchet@43797
  1754
      0 upto length helpers - 1 ~~ helpers
blanchet@43797
  1755
      |> map (formula_line_for_fact ctxt format helper_prefix lavish_nonmono_Ts
blanchet@43797
  1756
                                    type_sys)
blanchet@43797
  1757
      |> (if should_add_ti_ti_helper type_sys then cons (ti_ti_helper_fact ())
blanchet@43797
  1758
          else I)
blanchet@43393
  1759
    (* Reordering these might confuse the proof reconstruction code or the SPASS
blanchet@43880
  1760
       FLOTTER hack. *)
blanchet@38506
  1761
    val problem =
blanchet@43839
  1762
      [(explicit_declsN, sym_decl_lines),
blanchet@43797
  1763
       (factsN,
blanchet@43797
  1764
        map (formula_line_for_fact ctxt format fact_prefix nonmono_Ts type_sys)
blanchet@43797
  1765
            (0 upto length facts - 1 ~~ facts)),
blanchet@43416
  1766
       (class_relsN, map formula_line_for_class_rel_clause class_rel_clauses),
blanchet@43416
  1767
       (aritiesN, map formula_line_for_arity_clause arity_clauses),
blanchet@43750
  1768
       (helpersN, helper_lines),
blanchet@43803
  1769
       (conjsN,
blanchet@43803
  1770
        map (formula_line_for_conjecture ctxt format nonmono_Ts type_sys)
blanchet@43803
  1771
            conjs),
blanchet@43797
  1772
       (free_typesN,
blanchet@43797
  1773
        formula_lines_for_free_types format type_sys (facts @ conjs))]
blanchet@43414
  1774
    val problem =
blanchet@43432
  1775
      problem
blanchet@43933
  1776
      |> (case format of
blanchet@43933
  1777
            CNF => ensure_cnf_problem
blanchet@43933
  1778
          | CNF_UEQ => filter_cnf_ueq_problem
blanchet@43933
  1779
          | _ => I)
blanchet@43839
  1780
      |> (if is_format_typed format then
blanchet@43839
  1781
            declare_undeclared_syms_in_atp_problem type_decl_prefix
blanchet@43839
  1782
                                                   implicit_declsN
blanchet@43839
  1783
          else
blanchet@43839
  1784
            I)
blanchet@43933
  1785
    val (problem, pool) = problem |> nice_atp_problem readable_names
blanchet@43750
  1786
    val helpers_offset = offset_of_heading_in_problem helpersN problem 0
blanchet@43750
  1787
    val typed_helpers =
blanchet@43750
  1788
      map_filter (fn (j, {name, ...}) =>
blanchet@43750
  1789
                     if String.isSuffix typed_helper_suffix name then SOME j
blanchet@43750
  1790
                     else NONE)
blanchet@43750
  1791
                 ((helpers_offset + 1 upto helpers_offset + length helpers)
blanchet@43750
  1792
                  ~~ helpers)
blanchet@43649
  1793
    fun add_sym_arity (s, {min_ary, ...} : sym_info) =
blanchet@43620
  1794
      if min_ary > 0 then
blanchet@43620
  1795
        case strip_prefix_and_unascii const_prefix s of
blanchet@43620
  1796
          SOME s => Symtab.insert (op =) (s, min_ary)
blanchet@43620
  1797
        | NONE => I
blanchet@43620
  1798
      else
blanchet@43620
  1799
        I
blanchet@38506
  1800
  in
blanchet@38506
  1801
    (problem,
blanchet@38506
  1802
     case pool of SOME the_pool => snd the_pool | NONE => Symtab.empty,
blanchet@43456
  1803
     offset_of_heading_in_problem conjsN problem 0,
blanchet@43412
  1804
     offset_of_heading_in_problem factsN problem 0,
blanchet@43620
  1805
     fact_names |> Vector.fromList,
blanchet@43750
  1806
     typed_helpers,
blanchet@43620
  1807
     Symtab.empty |> Symtab.fold add_sym_arity sym_tab)
blanchet@38506
  1808
  end
blanchet@38506
  1809
blanchet@41561
  1810
(* FUDGE *)
blanchet@41561
  1811
val conj_weight = 0.0
blanchet@42641
  1812
val hyp_weight = 0.1
blanchet@42641
  1813
val fact_min_weight = 0.2
blanchet@41561
  1814
val fact_max_weight = 1.0
blanchet@43479
  1815
val type_info_default_weight = 0.8
blanchet@41561
  1816
blanchet@41561
  1817
fun add_term_weights weight (ATerm (s, tms)) =
blanchet@43839
  1818
  is_tptp_user_symbol s ? Symtab.default (s, weight)
blanchet@41561
  1819
  #> fold (add_term_weights weight) tms
blanchet@43448
  1820
fun add_problem_line_weights weight (Formula (_, _, phi, _, _)) =
blanchet@43705
  1821
    formula_fold NONE (K (add_term_weights weight)) phi
blanchet@43399
  1822
  | add_problem_line_weights _ _ = I
blanchet@41561
  1823
blanchet@41561
  1824
fun add_conjectures_weights [] = I
blanchet@41561
  1825
  | add_conjectures_weights conjs =
blanchet@41561
  1826
    let val (hyps, conj) = split_last conjs in
blanchet@41561
  1827
      add_problem_line_weights conj_weight conj
blanchet@41561
  1828
      #> fold (add_problem_line_weights hyp_weight) hyps
blanchet@41561
  1829
    end
blanchet@41561
  1830
blanchet@41561
  1831
fun add_facts_weights facts =
blanchet@41561
  1832
  let
blanchet@41561
  1833
    val num_facts = length facts
blanchet@41561
  1834
    fun weight_of j =
blanchet@41561
  1835
      fact_min_weight + (fact_max_weight - fact_min_weight) * Real.fromInt j
blanchet@41561
  1836
                        / Real.fromInt num_facts
blanchet@41561
  1837
  in
blanchet@41561
  1838
    map weight_of (0 upto num_facts - 1) ~~ facts
blanchet@41561
  1839
    |> fold (uncurry add_problem_line_weights)
blanchet@41561
  1840
  end
blanchet@41561
  1841
blanchet@41561
  1842
(* Weights are from 0.0 (most important) to 1.0 (least important). *)
blanchet@41561
  1843
fun atp_problem_weights problem =
blanchet@43479
  1844
  let val get = these o AList.lookup (op =) problem in
blanchet@43479
  1845
    Symtab.empty
blanchet@43479
  1846
    |> add_conjectures_weights (get free_typesN @ get conjsN)
blanchet@43479
  1847
    |> add_facts_weights (get factsN)
blanchet@43479
  1848
    |> fold (fold (add_problem_line_weights type_info_default_weight) o get)
blanchet@43839
  1849
            [explicit_declsN, class_relsN, aritiesN]
blanchet@43479
  1850
    |> Symtab.dest
blanchet@43479
  1851
    |> sort (prod_ord Real.compare string_ord o pairself swap)
blanchet@43479
  1852
  end
blanchet@41561
  1853
blanchet@38506
  1854
end;