src/HOL/Tools/Sledgehammer/sledgehammer_filter.ML
author blanchet
Mon Jul 09 23:23:12 2012 +0200 (2012-07-09 ago)
changeset 48219 49930a9ec27c
parent 47976 6b13451135a9
child 48227 3a7ac7439ccf
permissions -rw-r--r--
tuning
blanchet@38988
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_filter.ML
blanchet@38027
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@39958
     4
blanchet@39958
     5
Sledgehammer's relevance filter.
wenzelm@33309
     6
*)
paulson@15452
     7
blanchet@38988
     8
signature SLEDGEHAMMER_FILTER =
wenzelm@16802
     9
sig
blanchet@46388
    10
  type status = ATP_Problem_Generate.status
blanchet@46340
    11
  type stature = ATP_Problem_Generate.stature
blanchet@38752
    12
blanchet@40070
    13
  type relevance_fudge =
blanchet@42738
    14
    {local_const_multiplier : real,
blanchet@41159
    15
     worse_irrel_freq : real,
blanchet@40070
    16
     higher_order_irrel_weight : real,
blanchet@40070
    17
     abs_rel_weight : real,
blanchet@40070
    18
     abs_irrel_weight : real,
blanchet@40070
    19
     skolem_irrel_weight : real,
blanchet@40070
    20
     theory_const_rel_weight : real,
blanchet@40070
    21
     theory_const_irrel_weight : real,
blanchet@42735
    22
     chained_const_irrel_weight : real,
blanchet@40070
    23
     intro_bonus : real,
blanchet@40070
    24
     elim_bonus : real,
blanchet@40070
    25
     simp_bonus : real,
blanchet@40070
    26
     local_bonus : real,
blanchet@40070
    27
     assum_bonus : real,
blanchet@40070
    28
     chained_bonus : real,
blanchet@40070
    29
     max_imperfect : real,
blanchet@40070
    30
     max_imperfect_exp : real,
blanchet@40070
    31
     threshold_divisor : real,
blanchet@40070
    32
     ridiculous_threshold : real}
blanchet@40070
    33
blanchet@35966
    34
  type relevance_override =
blanchet@40070
    35
    {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
    36
     del : (Facts.ref * Attrib.src list) list,
blanchet@40070
    37
     only : bool}
blanchet@35966
    38
blanchet@42646
    39
  val trace : bool Config.T
blanchet@42728
    40
  val ignore_no_atp : bool Config.T
blanchet@42728
    41
  val instantiate_inducts : bool Config.T
blanchet@48219
    42
  val pseudo_abs_name : string
blanchet@48219
    43
  val pseudo_skolem_prefix : string
blanchet@44462
    44
  val no_relevance_override : relevance_override
blanchet@43351
    45
  val const_names_in_fact :
blanchet@43351
    46
    theory -> (string * typ -> term list -> bool * term list) -> term
blanchet@43351
    47
    -> string list
blanchet@46388
    48
  val clasimpset_rule_table_of : Proof.context -> status Termtab.table
blanchet@40205
    49
  val fact_from_ref :
blanchet@46388
    50
    Proof.context -> unit Symtab.table -> thm list -> status Termtab.table
blanchet@46340
    51
    -> Facts.ref * Attrib.src list -> ((string * stature) * thm) list
blanchet@41767
    52
  val all_facts :
blanchet@46734
    53
    Proof.context -> bool -> 'a Symtab.table -> bool -> thm list
blanchet@47774
    54
    -> thm list -> status Termtab.table
blanchet@47774
    55
    -> (((unit -> string) * stature) * thm) list
blanchet@43351
    56
  val nearly_all_facts :
nik@44585
    57
    Proof.context -> bool -> relevance_override -> thm list -> term list -> term
blanchet@46340
    58
    -> (((unit -> string) * stature) * thm) list
blanchet@37347
    59
  val relevant_facts :
blanchet@44625
    60
    Proof.context -> real * real -> int
blanchet@41336
    61
    -> (string * typ -> term list -> bool * term list) -> relevance_fudge
blanchet@41066
    62
    -> relevance_override -> thm list -> term list -> term
blanchet@46340
    63
    -> (((unit -> string) * stature) * thm) list
blanchet@46340
    64
    -> ((string * stature) * thm) list
paulson@15347
    65
end;
paulson@15347
    66
blanchet@38988
    67
structure Sledgehammer_Filter : SLEDGEHAMMER_FILTER =
paulson@15347
    68
struct
paulson@15347
    69
blanchet@46320
    70
open ATP_Problem_Generate
blanchet@44934
    71
open Metis_Tactic
blanchet@38652
    72
open Sledgehammer_Util
blanchet@38652
    73
blanchet@42646
    74
val trace =
blanchet@42646
    75
  Attrib.setup_config_bool @{binding sledgehammer_filter_trace} (K false)
blanchet@42646
    76
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
blanchet@35826
    77
blanchet@41273
    78
(* experimental features *)
blanchet@42728
    79
val ignore_no_atp =
blanchet@42728
    80
  Attrib.setup_config_bool @{binding sledgehammer_ignore_no_atp} (K false)
blanchet@42728
    81
val instantiate_inducts =
blanchet@42728
    82
  Attrib.setup_config_bool @{binding sledgehammer_instantiate_inducts} (K false)
blanchet@38827
    83
blanchet@40070
    84
type relevance_fudge =
blanchet@42738
    85
  {local_const_multiplier : real,
blanchet@41159
    86
   worse_irrel_freq : real,
blanchet@40070
    87
   higher_order_irrel_weight : real,
blanchet@40070
    88
   abs_rel_weight : real,
blanchet@40070
    89
   abs_irrel_weight : real,
blanchet@40070
    90
   skolem_irrel_weight : real,
blanchet@40070
    91
   theory_const_rel_weight : real,
blanchet@40070
    92
   theory_const_irrel_weight : real,
blanchet@42735
    93
   chained_const_irrel_weight : real,
blanchet@40070
    94
   intro_bonus : real,
blanchet@40070
    95
   elim_bonus : real,
blanchet@40070
    96
   simp_bonus : real,
blanchet@40070
    97
   local_bonus : real,
blanchet@40070
    98
   assum_bonus : real,
blanchet@40070
    99
   chained_bonus : real,
blanchet@40070
   100
   max_imperfect : real,
blanchet@40070
   101
   max_imperfect_exp : real,
blanchet@40070
   102
   threshold_divisor : real,
blanchet@40070
   103
   ridiculous_threshold : real}
blanchet@40070
   104
blanchet@35966
   105
type relevance_override =
blanchet@40070
   106
  {add : (Facts.ref * Attrib.src list) list,
blanchet@40070
   107
   del : (Facts.ref * Attrib.src list) list,
blanchet@40070
   108
   only : bool}
paulson@21070
   109
blanchet@44462
   110
val no_relevance_override = {add = [], del = [], only = false}
blanchet@44462
   111
blanchet@37616
   112
val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
blanchet@48219
   113
val pseudo_abs_name = sledgehammer_prefix ^ "abs"
blanchet@48219
   114
val pseudo_skolem_prefix = sledgehammer_prefix ^ "sko"
blanchet@38992
   115
val theory_const_suffix = Long_Name.separator ^ " 1"
blanchet@37616
   116
blanchet@46438
   117
(* unfolding these can yield really huge terms *)
blanchet@47148
   118
val risky_defs = @{thms Bit0_def Bit1_def}
blanchet@47148
   119
blanchet@47148
   120
fun is_rec_eq lhs = Term.exists_subterm (curry (op =) (head_of lhs))
blanchet@47148
   121
fun is_rec_def (@{const Trueprop} $ t) = is_rec_def t
blanchet@47148
   122
  | is_rec_def (@{const ==>} $ _ $ t2) = is_rec_def t2
blanchet@47148
   123
  | is_rec_def (Const (@{const_name "=="}, _) $ t1 $ t2) = is_rec_eq t1 t2
blanchet@47148
   124
  | is_rec_def (Const (@{const_name HOL.eq}, _) $ t1 $ t2) = is_rec_eq t1 t2
blanchet@47148
   125
  | is_rec_def _ = false
blanchet@46438
   126
blanchet@46388
   127
fun clasimpset_rule_table_of ctxt =
blanchet@46388
   128
  let
blanchet@46388
   129
    val thy = Proof_Context.theory_of ctxt
blanchet@46388
   130
    val atomize = HOLogic.mk_Trueprop o Object_Logic.atomize_term thy
blanchet@46734
   131
    fun add stature normalizers get_th =
blanchet@46734
   132
      fold (fn rule =>
blanchet@46734
   133
               let
blanchet@46734
   134
                 val th = rule |> get_th
blanchet@46734
   135
                 val t =
blanchet@46734
   136
                   th |> Thm.maxidx_of th > 0 ? zero_var_indexes |> prop_of
blanchet@46734
   137
               in
blanchet@46734
   138
                 fold (fn normalize => Termtab.update (normalize t, stature))
blanchet@46734
   139
                      (I :: normalizers)
blanchet@46734
   140
               end)
blanchet@47073
   141
    val {safeIs, (* safeEs, *) hazIs, (* hazEs, *) ...} =
blanchet@46388
   142
      ctxt |> claset_of |> Classical.rep_cs
blanchet@46388
   143
    val intros = Item_Net.content safeIs @ Item_Net.content hazIs
blanchet@47073
   144
(* Add once it is used:
blanchet@46388
   145
    val elims =
blanchet@46388
   146
      Item_Net.content safeEs @ Item_Net.content hazEs
blanchet@46388
   147
      |> map Classical.classical_rule
blanchet@46734
   148
*)
blanchet@46388
   149
    val simps = ctxt |> simpset_of |> dest_ss |> #simps
blanchet@47073
   150
    val specs = ctxt |> Spec_Rules.get
blanchet@47148
   151
    val (rec_defs, nonrec_defs) =
blanchet@47073
   152
      specs |> filter (curry (op =) Spec_Rules.Equational o fst)
blanchet@47073
   153
            |> maps (snd o snd)
blanchet@47148
   154
            |> filter_out (member Thm.eq_thm_prop risky_defs)
blanchet@47148
   155
            |> List.partition (is_rec_def o prop_of)
blanchet@47073
   156
    val spec_intros =
blanchet@47073
   157
      specs |> filter (member (op =) [Spec_Rules.Inductive,
blanchet@47073
   158
                                      Spec_Rules.Co_Inductive] o fst)
blanchet@47073
   159
            |> maps (snd o snd)
blanchet@46388
   160
  in
blanchet@46734
   161
    Termtab.empty |> add Simp [atomize] snd simps
blanchet@47148
   162
                  |> add Simp [] I rec_defs
blanchet@47148
   163
                  |> add Def [] I nonrec_defs
blanchet@47073
   164
(* Add once it is used:
blanchet@46734
   165
                  |> add Elim [] I elims
blanchet@47073
   166
*)
blanchet@46734
   167
                  |> add Intro [] I intros
blanchet@47148
   168
                  |> add Inductive [] I spec_intros
blanchet@46388
   169
  end
blanchet@46388
   170
blanchet@40227
   171
fun needs_quoting reserved s =
blanchet@40375
   172
  Symtab.defined reserved s orelse
wenzelm@42290
   173
  exists (not o Lexicon.is_identifier) (Long_Name.explode s)
blanchet@40227
   174
blanchet@40375
   175
fun make_name reserved multi j name =
blanchet@40227
   176
  (name |> needs_quoting reserved name ? quote) ^
wenzelm@41491
   177
  (if multi then "(" ^ string_of_int j ^ ")" else "")
blanchet@38744
   178
blanchet@40375
   179
fun explode_interval _ (Facts.FromTo (i, j)) = i upto j
blanchet@40375
   180
  | explode_interval max (Facts.From i) = i upto i + max - 1
blanchet@40375
   181
  | explode_interval _ (Facts.Single i) = [i]
blanchet@40375
   182
blanchet@41279
   183
val backquote =
blanchet@41279
   184
  raw_explode #> map (fn "`" => "\\`" | s => s) #> implode #> enclose "`" "`"
blanchet@46388
   185
blanchet@46388
   186
fun is_assum assms th = exists (fn ct => prop_of th aconv term_of ct) assms
blanchet@46388
   187
fun is_chained chained_ths = member Thm.eq_thm_prop chained_ths
blanchet@46388
   188
blanchet@46388
   189
fun scope_of_thm global assms chained_ths th =
blanchet@46388
   190
  if is_chained chained_ths th then Chained
blanchet@46388
   191
  else if global then Global
blanchet@46388
   192
  else if is_assum assms th then Assum
blanchet@46388
   193
  else Local
blanchet@46388
   194
blanchet@47904
   195
val may_be_induction =
blanchet@47904
   196
  exists_subterm (fn Var (_, Type (@{type_name fun}, [_, T])) =>
blanchet@47904
   197
                     body_type T = @{typ bool}
blanchet@47904
   198
                   | _ => false)
blanchet@47904
   199
blanchet@46388
   200
fun status_of_thm css_table name th =
blanchet@46388
   201
  (* FIXME: use structured name *)
blanchet@47904
   202
  if (String.isSubstring ".induct" name orelse
blanchet@47904
   203
      String.isSubstring ".inducts" name) andalso
blanchet@47904
   204
     may_be_induction (prop_of th) then
blanchet@47148
   205
    Induction
blanchet@46388
   206
  else case Termtab.lookup css_table (prop_of th) of
blanchet@46388
   207
    SOME status => status
blanchet@46388
   208
  | NONE => General
blanchet@46388
   209
blanchet@46388
   210
fun stature_of_thm global assms chained_ths css_table name th =
blanchet@46388
   211
  (scope_of_thm global assms chained_ths th, status_of_thm css_table name th)
blanchet@46388
   212
blanchet@46388
   213
fun fact_from_ref ctxt reserved chained_ths css_table (xthm as (xref, args)) =
blanchet@38744
   214
  let
blanchet@38996
   215
    val ths = Attrib.eval_thms ctxt [xthm]
blanchet@38996
   216
    val bracket =
blanchet@41999
   217
      map (enclose "[" "]" o Pretty.str_of o Args.pretty_src ctxt) args
blanchet@41999
   218
      |> implode
blanchet@40375
   219
    fun nth_name j =
blanchet@38996
   220
      case xref of
blanchet@41279
   221
        Facts.Fact s => backquote s ^ bracket
blanchet@38996
   222
      | Facts.Named (("", _), _) => "[" ^ bracket ^ "]"
blanchet@40375
   223
      | Facts.Named ((name, _), NONE) =>
blanchet@40375
   224
        make_name reserved (length ths > 1) (j + 1) name ^ bracket
blanchet@40375
   225
      | Facts.Named ((name, _), SOME intervals) =>
blanchet@40375
   226
        make_name reserved true
blanchet@40375
   227
                 (nth (maps (explode_interval (length ths)) intervals) j) name ^
blanchet@40375
   228
        bracket
blanchet@38744
   229
  in
blanchet@40375
   230
    (ths, (0, []))
blanchet@38752
   231
    |-> fold (fn th => fn (j, rest) =>
blanchet@46388
   232
                 let val name = nth_name j in
blanchet@46388
   233
                   (j + 1, ((name, stature_of_thm false [] chained_ths
blanchet@46388
   234
                                             css_table name th), th) :: rest)
blanchet@46388
   235
                 end)
blanchet@38744
   236
    |> snd
blanchet@38699
   237
  end
blanchet@37616
   238
blanchet@45034
   239
(* This is a terrible hack. Free variables are sometimes coded as "M__" when
blanchet@45034
   240
   they are displayed as "M" and we want to avoid clashes with these. But
blanchet@45034
   241
   sometimes it's even worse: "Ma__" encodes "M". So we simply reserve all
blanchet@45034
   242
   prefixes of all free variables. In the worse case scenario, where the fact
blanchet@45034
   243
   won't be resolved correctly, the user can fix it manually, e.g., by naming
blanchet@45034
   244
   the fact in question. Ideally we would need nothing of it, but backticks
blanchet@45034
   245
   simply don't work with schematic variables. *)
blanchet@41199
   246
fun all_prefixes_of s =
blanchet@41199
   247
  map (fn i => String.extract (s, 0, SOME i)) (1 upto size s - 1)
blanchet@41199
   248
fun close_form t =
blanchet@41199
   249
  (t, [] |> Term.add_free_names t |> maps all_prefixes_of)
blanchet@41199
   250
  |> fold (fn ((s, i), T) => fn (t', taken) =>
wenzelm@43324
   251
              let val s' = singleton (Name.variant_list taken) s in
blanchet@41199
   252
                ((if fastype_of t' = HOLogic.boolT then HOLogic.all_const
wenzelm@46217
   253
                  else Logic.all_const) T
blanchet@41199
   254
                 $ Abs (s', T, abstract_over (Var ((s, i), T), t')),
blanchet@41199
   255
                 s' :: taken)
blanchet@41199
   256
              end)
blanchet@41199
   257
          (Term.add_vars t [] |> sort_wrt (fst o fst))
blanchet@41199
   258
  |> fst
blanchet@41199
   259
blanchet@41199
   260
fun string_for_term ctxt t =
blanchet@41199
   261
  Print_Mode.setmp (filter (curry (op =) Symbol.xsymbolsN)
blanchet@41199
   262
                   (print_mode_value ())) (Syntax.string_of_term ctxt) t
blanchet@41199
   263
  |> String.translate (fn c => if Char.isPrint c then str c else "")
blanchet@41199
   264
  |> simplify_spaces
blanchet@41199
   265
blanchet@41199
   266
(** Structural induction rules **)
blanchet@41199
   267
blanchet@41200
   268
fun struct_induct_rule_on th =
blanchet@41199
   269
  case Logic.strip_horn (prop_of th) of
blanchet@41199
   270
    (prems, @{const Trueprop}
blanchet@41199
   271
            $ ((p as Var ((p_name, 0), _)) $ (a as Var (_, ind_T)))) =>
blanchet@41199
   272
    if not (is_TVar ind_T) andalso length prems > 1 andalso
blanchet@41199
   273
       exists (exists_subterm (curry (op aconv) p)) prems andalso
blanchet@41199
   274
       not (exists (exists_subterm (curry (op aconv) a)) prems) then
blanchet@41199
   275
      SOME (p_name, ind_T)
blanchet@41199
   276
    else
blanchet@41199
   277
      NONE
blanchet@41199
   278
  | _ => NONE
blanchet@41199
   279
blanchet@46340
   280
fun instantiate_induct_rule ctxt concl_prop p_name ((name, stature), th) ind_x =
blanchet@41199
   281
  let
blanchet@41199
   282
    fun varify_noninducts (t as Free (s, T)) =
blanchet@41199
   283
        if (s, T) = ind_x orelse can dest_funT T then t else Var ((s, 0), T)
blanchet@41199
   284
      | varify_noninducts t = t
blanchet@41199
   285
    val p_inst =
blanchet@41199
   286
      concl_prop |> map_aterms varify_noninducts |> close_form
blanchet@41199
   287
                 |> lambda (Free ind_x)
blanchet@41199
   288
                 |> string_for_term ctxt
blanchet@41199
   289
  in
blanchet@46340
   290
    ((fn () => name () ^ "[where " ^ p_name ^ " = " ^ quote p_inst ^ "]",
blanchet@46340
   291
      stature), th |> read_instantiate ctxt [((p_name, 0), p_inst)])
blanchet@41199
   292
  end
blanchet@41199
   293
blanchet@41199
   294
fun type_match thy (T1, T2) =
blanchet@41199
   295
  (Sign.typ_match thy (T2, T1) Vartab.empty; true)
blanchet@41199
   296
  handle Type.TYPE_MATCH => false
blanchet@41199
   297
blanchet@43245
   298
fun instantiate_if_induct_rule ctxt stmt stmt_xs (ax as (_, th)) =
blanchet@41200
   299
  case struct_induct_rule_on th of
blanchet@41199
   300
    SOME (p_name, ind_T) =>
wenzelm@42361
   301
    let val thy = Proof_Context.theory_of ctxt in
blanchet@41199
   302
      stmt_xs |> filter (fn (_, T) => type_match thy (T, ind_T))
blanchet@41199
   303
              |> map_filter (try (instantiate_induct_rule ctxt stmt p_name ax))
blanchet@41199
   304
    end
blanchet@41199
   305
  | NONE => [ax]
blanchet@41199
   306
wenzelm@28477
   307
(***************************************************************)
wenzelm@28477
   308
(* Relevance Filtering                                         *)
wenzelm@28477
   309
(***************************************************************)
mengj@19194
   310
paulson@24287
   311
(*** constants with types ***)
paulson@24287
   312
blanchet@46073
   313
fun order_of_type (Type (@{type_name fun}, [T1, T2])) =
blanchet@38939
   314
    Int.max (order_of_type T1 + 1, order_of_type T2)
blanchet@38939
   315
  | order_of_type (Type (_, Ts)) = fold (Integer.max o order_of_type) Ts 0
blanchet@38939
   316
  | order_of_type _ = 0
blanchet@38939
   317
blanchet@38823
   318
(* An abstraction of Isabelle types and first-order terms *)
blanchet@38823
   319
datatype pattern = PVar | PApp of string * pattern list
blanchet@38939
   320
datatype ptype = PType of int * pattern list
blanchet@38744
   321
blanchet@38823
   322
fun string_for_pattern PVar = "_"
blanchet@38823
   323
  | string_for_pattern (PApp (s, ps)) =
blanchet@38823
   324
    if null ps then s else s ^ string_for_patterns ps
blanchet@38823
   325
and string_for_patterns ps = "(" ^ commas (map string_for_pattern ps) ^ ")"
blanchet@38939
   326
fun string_for_ptype (PType (_, ps)) = string_for_patterns ps
paulson@24287
   327
paulson@24287
   328
(*Is the second type an instance of the first one?*)
blanchet@38824
   329
fun match_pattern (PVar, _) = true
blanchet@38824
   330
  | match_pattern (PApp _, PVar) = false
blanchet@38824
   331
  | match_pattern (PApp (s, ps), PApp (t, qs)) =
blanchet@38824
   332
    s = t andalso match_patterns (ps, qs)
blanchet@38824
   333
and match_patterns (_, []) = true
blanchet@38824
   334
  | match_patterns ([], _) = false
blanchet@38824
   335
  | match_patterns (p :: ps, q :: qs) =
blanchet@38824
   336
    match_pattern (p, q) andalso match_patterns (ps, qs)
blanchet@38939
   337
fun match_ptype (PType (_, ps), PType (_, qs)) = match_patterns (ps, qs)
paulson@24287
   338
blanchet@38823
   339
(* Is there a unifiable constant? *)
blanchet@38827
   340
fun pconst_mem f consts (s, ps) =
blanchet@38939
   341
  exists (curry (match_ptype o f) ps)
blanchet@38827
   342
         (map snd (filter (curry (op =) s o fst) consts))
blanchet@38827
   343
fun pconst_hyper_mem f const_tab (s, ps) =
blanchet@38939
   344
  exists (curry (match_ptype o f) ps) (these (Symtab.lookup const_tab s))
blanchet@37505
   345
blanchet@38939
   346
fun pattern_for_type (Type (s, Ts)) = PApp (s, map pattern_for_type Ts)
blanchet@38939
   347
  | pattern_for_type (TFree (s, _)) = PApp (s, [])
blanchet@38939
   348
  | pattern_for_type (TVar _) = PVar
blanchet@38827
   349
blanchet@38744
   350
(* Pairs a constant with the list of its type instantiations. *)
blanchet@41204
   351
fun ptype thy const x =
blanchet@38939
   352
  (if const then map pattern_for_type (these (try (Sign.const_typargs thy) x))
blanchet@41204
   353
   else [])
blanchet@41204
   354
fun rich_ptype thy const (s, T) =
blanchet@41204
   355
  PType (order_of_type T, ptype thy const (s, T))
blanchet@41204
   356
fun rich_pconst thy const (s, T) = (s, rich_ptype thy const (s, T))
paulson@24287
   357
blanchet@38939
   358
fun string_for_hyper_pconst (s, ps) =
blanchet@38939
   359
  s ^ "{" ^ commas (map string_for_ptype ps) ^ "}"
paulson@24287
   360
blanchet@38823
   361
(* Add a pconstant to the table, but a [] entry means a standard
blanchet@38819
   362
   connective, which we ignore.*)
blanchet@41066
   363
fun add_pconst_to_table also_skolem (s, p) =
blanchet@48219
   364
  if (not also_skolem andalso String.isPrefix pseudo_skolem_prefix s) then I
blanchet@41066
   365
  else Symtab.map_default (s, [p]) (insert (op =) p)
blanchet@38819
   366
blanchet@47933
   367
(* Set constants tend to pull in too many irrelevant facts. We limit the damage
blanchet@47933
   368
   by treating them more or less as if they were built-in but add their
blanchet@47933
   369
   axiomatization at the end. *)
blanchet@47933
   370
val set_consts = [@{const_name Collect}, @{const_name Set.member}]
blanchet@47939
   371
val set_thms = @{thms Collect_mem_eq mem_Collect_eq Collect_cong}
blanchet@47933
   372
blanchet@42732
   373
fun add_pconsts_in_term thy is_built_in_const also_skolems pos =
blanchet@37505
   374
  let
blanchet@38819
   375
    val flip = Option.map not
blanchet@38587
   376
    (* We include free variables, as well as constants, to handle locales. For
blanchet@41205
   377
       each quantifiers that must necessarily be skolemized by the automatic
blanchet@41205
   378
       prover, we introduce a fresh constant to simulate the effect of
blanchet@41205
   379
       Skolemization. *)
blanchet@47933
   380
    fun do_const const ext_arg (x as (s, _)) ts =
blanchet@41336
   381
      let val (built_in, ts) = is_built_in_const x ts in
blanchet@47933
   382
        if member (op =) set_consts s then
blanchet@47933
   383
          fold (do_term ext_arg) ts
blanchet@47933
   384
        else
blanchet@47933
   385
          (not built_in
blanchet@47933
   386
           ? add_pconst_to_table also_skolems (rich_pconst thy const x))
blanchet@47933
   387
          #> fold (do_term false) ts
blanchet@41336
   388
      end
blanchet@42741
   389
    and do_term ext_arg t =
blanchet@38827
   390
      case strip_comb t of
blanchet@47933
   391
        (Const x, ts) => do_const true ext_arg x ts
blanchet@47933
   392
      | (Free x, ts) => do_const false ext_arg x ts
blanchet@38939
   393
      | (Abs (_, T, t'), ts) =>
blanchet@42741
   394
        ((null ts andalso not ext_arg)
blanchet@42741
   395
         (* Since lambdas on the right-hand side of equalities are usually
blanchet@47953
   396
            extensionalized later by "abs_extensionalize_term", we don't
blanchet@47953
   397
            penalize them here. *)
blanchet@48219
   398
         ? add_pconst_to_table true (pseudo_abs_name,
blanchet@48219
   399
                                     PType (order_of_type T + 1, [])))
blanchet@42735
   400
        #> fold (do_term false) (t' :: ts)
blanchet@42735
   401
      | (_, ts) => fold (do_term false) ts
blanchet@38939
   402
    fun do_quantifier will_surely_be_skolemized abs_T body_t =
blanchet@37537
   403
      do_formula pos body_t
blanchet@38747
   404
      #> (if also_skolems andalso will_surely_be_skolemized then
blanchet@48219
   405
            add_pconst_to_table true (pseudo_skolem_prefix ^ serial_string (),
blanchet@48219
   406
                                      PType (order_of_type abs_T, []))
blanchet@38587
   407
          else
blanchet@38587
   408
            I)
blanchet@42741
   409
    and do_term_or_formula ext_arg T =
blanchet@42741
   410
      if T = HOLogic.boolT then do_formula NONE else do_term ext_arg
blanchet@37537
   411
    and do_formula pos t =
blanchet@37537
   412
      case t of
blanchet@38939
   413
        Const (@{const_name all}, _) $ Abs (_, T, t') =>
blanchet@38939
   414
        do_quantifier (pos = SOME false) T t'
blanchet@37537
   415
      | @{const "==>"} $ t1 $ t2 =>
blanchet@37537
   416
        do_formula (flip pos) t1 #> do_formula pos t2
blanchet@37537
   417
      | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@42741
   418
        do_term_or_formula false T t1 #> do_term_or_formula true T t2
blanchet@37537
   419
      | @{const Trueprop} $ t1 => do_formula pos t1
blanchet@41140
   420
      | @{const False} => I
blanchet@41140
   421
      | @{const True} => I
blanchet@37537
   422
      | @{const Not} $ t1 => do_formula (flip pos) t1
blanchet@38939
   423
      | Const (@{const_name All}, _) $ Abs (_, T, t') =>
blanchet@38939
   424
        do_quantifier (pos = SOME false) T t'
blanchet@38939
   425
      | Const (@{const_name Ex}, _) $ Abs (_, T, t') =>
blanchet@38939
   426
        do_quantifier (pos = SOME true) T t'
haftmann@38795
   427
      | @{const HOL.conj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38795
   428
      | @{const HOL.disj} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
haftmann@38786
   429
      | @{const HOL.implies} $ t1 $ t2 =>
blanchet@37537
   430
        do_formula (flip pos) t1 #> do_formula pos t2
haftmann@38864
   431
      | Const (@{const_name HOL.eq}, Type (_, [T, _])) $ t1 $ t2 =>
blanchet@42741
   432
        do_term_or_formula false T t1 #> do_term_or_formula true T t2
blanchet@38587
   433
      | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
blanchet@38587
   434
        $ t1 $ t2 $ t3 =>
blanchet@42735
   435
        do_formula NONE t1 #> fold (do_term_or_formula false T) [t2, t3]
blanchet@38939
   436
      | Const (@{const_name Ex1}, _) $ Abs (_, T, t') =>
blanchet@38939
   437
        do_quantifier (is_some pos) T t'
blanchet@38939
   438
      | Const (@{const_name Ball}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   439
        do_quantifier (pos = SOME false) T
blanchet@38939
   440
                      (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@38939
   441
      | Const (@{const_name Bex}, _) $ t1 $ Abs (_, T, t') =>
blanchet@38939
   442
        do_quantifier (pos = SOME true) T
blanchet@38939
   443
                      (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, t'))
blanchet@37537
   444
      | (t0 as Const (_, @{typ bool})) $ t1 =>
blanchet@42735
   445
        do_term false t0 #> do_formula pos t1  (* theory constant *)
blanchet@42735
   446
      | _ => do_term false t
blanchet@42732
   447
  in do_formula pos end
paulson@24287
   448
paulson@24287
   449
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   450
  takes the given theory into account.*)
blanchet@41200
   451
fun theory_constify ({theory_const_rel_weight, theory_const_irrel_weight, ...}
blanchet@41200
   452
                     : relevance_fudge) thy_name t =
blanchet@40070
   453
  if exists (curry (op <) 0.0) [theory_const_rel_weight,
blanchet@40070
   454
                                theory_const_irrel_weight] then
blanchet@41200
   455
    Const (thy_name ^ theory_const_suffix, @{typ bool}) $ t
blanchet@37505
   456
  else
blanchet@41200
   457
    t
blanchet@41200
   458
blanchet@41200
   459
fun theory_const_prop_of fudge th =
blanchet@41200
   460
  theory_constify fudge (Context.theory_name (theory_of_thm th)) (prop_of th)
blanchet@37505
   461
paulson@24287
   462
(**** Constant / Type Frequencies ****)
paulson@24287
   463
blanchet@38743
   464
(* A two-dimensional symbol table counts frequencies of constants. It's keyed
blanchet@38743
   465
   first by constant name and second by its list of type instantiations. For the
blanchet@38823
   466
   latter, we need a linear ordering on "pattern list". *)
paulson@24287
   467
blanchet@38823
   468
fun pattern_ord p =
blanchet@38743
   469
  case p of
blanchet@38744
   470
    (PVar, PVar) => EQUAL
blanchet@38823
   471
  | (PVar, PApp _) => LESS
blanchet@38823
   472
  | (PApp _, PVar) => GREATER
blanchet@38823
   473
  | (PApp q1, PApp q2) =>
blanchet@38823
   474
    prod_ord fast_string_ord (dict_ord pattern_ord) (q1, q2)
blanchet@38939
   475
fun ptype_ord (PType p, PType q) =
blanchet@38939
   476
  prod_ord (dict_ord pattern_ord) int_ord (swap p, swap q)
paulson@24287
   477
blanchet@38939
   478
structure PType_Tab = Table(type key = ptype val ord = ptype_ord)
paulson@24287
   479
blanchet@40204
   480
fun count_fact_consts thy fudge =
blanchet@37503
   481
  let
blanchet@38827
   482
    fun do_const const (s, T) ts =
blanchet@38827
   483
      (* Two-dimensional table update. Constant maps to types maps to count. *)
blanchet@41204
   484
      PType_Tab.map_default (rich_ptype thy const (s, T), 0) (Integer.add 1)
blanchet@38939
   485
      |> Symtab.map_default (s, PType_Tab.empty)
blanchet@38827
   486
      #> fold do_term ts
blanchet@38827
   487
    and do_term t =
blanchet@38827
   488
      case strip_comb t of
blanchet@38827
   489
        (Const x, ts) => do_const true x ts
blanchet@38827
   490
      | (Free x, ts) => do_const false x ts
blanchet@38827
   491
      | (Abs (_, _, t'), ts) => fold do_term (t' :: ts)
blanchet@38827
   492
      | (_, ts) => fold do_term ts
blanchet@40070
   493
  in do_term o theory_const_prop_of fudge o snd end
paulson@24287
   494
paulson@24287
   495
paulson@24287
   496
(**** Actual Filtering Code ****)
paulson@24287
   497
blanchet@39367
   498
fun pow_int _ 0 = 1.0
blanchet@38939
   499
  | pow_int x 1 = x
blanchet@38939
   500
  | pow_int x n = if n > 0 then x * pow_int x (n - 1) else pow_int x (n + 1) / x
blanchet@38939
   501
paulson@24287
   502
(*The frequency of a constant is the sum of those of all instances of its type.*)
blanchet@38824
   503
fun pconst_freq match const_tab (c, ps) =
blanchet@38939
   504
  PType_Tab.fold (fn (qs, m) => match (ps, qs) ? Integer.add m)
blanchet@38939
   505
                 (the (Symtab.lookup const_tab c)) 0
blanchet@38686
   506
paulson@24287
   507
blanchet@38085
   508
(* A surprising number of theorems contain only a few significant constants.
blanchet@38085
   509
   These include all induction rules, and other general theorems. *)
blanchet@37503
   510
blanchet@37503
   511
(* "log" seems best in practice. A constant function of one ignores the constant
blanchet@38938
   512
   frequencies. Rare constants give more points if they are relevant than less
blanchet@38938
   513
   rare ones. *)
blanchet@39367
   514
fun rel_weight_for _ freq = 1.0 + 2.0 / Math.ln (Real.fromInt freq + 1.0)
blanchet@38938
   515
blanchet@38938
   516
(* Irrelevant constants are treated differently. We associate lower penalties to
blanchet@38938
   517
   very rare constants and very common ones -- the former because they can't
blanchet@38938
   518
   lead to the inclusion of too many new facts, and the latter because they are
blanchet@38938
   519
   so common as to be of little interest. *)
blanchet@40070
   520
fun irrel_weight_for ({worse_irrel_freq, higher_order_irrel_weight, ...}
blanchet@40070
   521
                      : relevance_fudge) order freq =
blanchet@40070
   522
  let val (k, x) = worse_irrel_freq |> `Real.ceil in
blanchet@38939
   523
    (if freq < k then Math.ln (Real.fromInt (freq + 1)) / Math.ln x
blanchet@38939
   524
     else rel_weight_for order freq / rel_weight_for order k)
blanchet@40070
   525
    * pow_int higher_order_irrel_weight (order - 1)
blanchet@38938
   526
  end
blanchet@37503
   527
blanchet@41790
   528
fun multiplier_for_const_name local_const_multiplier s =
blanchet@41790
   529
  if String.isSubstring "." s then 1.0 else local_const_multiplier
blanchet@38821
   530
blanchet@41790
   531
(* Computes a constant's weight, as determined by its frequency. *)
blanchet@41790
   532
fun generic_pconst_weight local_const_multiplier abs_weight skolem_weight
blanchet@42735
   533
                          theory_const_weight chained_const_weight weight_for f
blanchet@42735
   534
                          const_tab chained_const_tab (c as (s, PType (m, _))) =
blanchet@48219
   535
  if s = pseudo_abs_name then
blanchet@41790
   536
    abs_weight
blanchet@48219
   537
  else if String.isPrefix pseudo_skolem_prefix s then
blanchet@41790
   538
    skolem_weight
blanchet@41790
   539
  else if String.isSuffix theory_const_suffix s then
blanchet@41790
   540
    theory_const_weight
blanchet@41790
   541
  else
blanchet@41790
   542
    multiplier_for_const_name local_const_multiplier s
blanchet@41790
   543
    * weight_for m (pconst_freq (match_ptype o f) const_tab c)
blanchet@42735
   544
    |> (if chained_const_weight < 1.0 andalso
blanchet@42735
   545
           pconst_hyper_mem I chained_const_tab c then
blanchet@42735
   546
          curry (op *) chained_const_weight
blanchet@42735
   547
        else
blanchet@42735
   548
          I)
blanchet@41790
   549
blanchet@41790
   550
fun rel_pconst_weight ({local_const_multiplier, abs_rel_weight,
blanchet@41790
   551
                        theory_const_rel_weight, ...} : relevance_fudge)
blanchet@41790
   552
                      const_tab =
blanchet@41790
   553
  generic_pconst_weight local_const_multiplier abs_rel_weight 0.0
blanchet@42735
   554
                        theory_const_rel_weight 0.0 rel_weight_for I const_tab
blanchet@42735
   555
                        Symtab.empty
blanchet@42735
   556
blanchet@41790
   557
fun irrel_pconst_weight (fudge as {local_const_multiplier, abs_irrel_weight,
blanchet@41790
   558
                                   skolem_irrel_weight,
blanchet@42735
   559
                                   theory_const_irrel_weight,
blanchet@42735
   560
                                   chained_const_irrel_weight, ...})
blanchet@42735
   561
                        const_tab chained_const_tab =
blanchet@41790
   562
  generic_pconst_weight local_const_multiplier abs_irrel_weight
blanchet@41790
   563
                        skolem_irrel_weight theory_const_irrel_weight
blanchet@42735
   564
                        chained_const_irrel_weight (irrel_weight_for fudge) swap
blanchet@42735
   565
                        const_tab chained_const_tab
paulson@24287
   566
blanchet@46340
   567
fun stature_bonus ({intro_bonus, ...} : relevance_fudge) (_, Intro) =
blanchet@46340
   568
    intro_bonus
blanchet@46340
   569
  | stature_bonus {elim_bonus, ...} (_, Elim) = elim_bonus
blanchet@46340
   570
  | stature_bonus {simp_bonus, ...} (_, Simp) = simp_bonus
blanchet@46340
   571
  | stature_bonus {local_bonus, ...} (Local, _) = local_bonus
blanchet@46340
   572
  | stature_bonus {assum_bonus, ...} (Assum, _) = assum_bonus
blanchet@46340
   573
  | stature_bonus {chained_bonus, ...} (Chained, _) = chained_bonus
blanchet@46340
   574
  | stature_bonus _ _ = 0.0
blanchet@38751
   575
blanchet@40418
   576
fun is_odd_const_name s =
blanchet@48219
   577
  s = pseudo_abs_name orelse String.isPrefix pseudo_skolem_prefix s orelse
blanchet@40418
   578
  String.isSuffix theory_const_suffix s
blanchet@40418
   579
blanchet@46340
   580
fun fact_weight fudge stature const_tab relevant_consts chained_consts
blanchet@46340
   581
                fact_consts =
blanchet@40204
   582
  case fact_consts |> List.partition (pconst_hyper_mem I relevant_consts)
blanchet@40204
   583
                   ||> filter_out (pconst_hyper_mem swap relevant_consts) of
blanchet@38827
   584
    ([], _) => 0.0
blanchet@38744
   585
  | (rel, irrel) =>
blanchet@40418
   586
    if forall (forall (is_odd_const_name o fst)) [rel, irrel] then
blanchet@40371
   587
      0.0
blanchet@40371
   588
    else
blanchet@40371
   589
      let
blanchet@42735
   590
        val irrel = irrel |> filter_out (pconst_mem swap rel)
blanchet@40371
   591
        val rel_weight =
blanchet@40371
   592
          0.0 |> fold (curry (op +) o rel_pconst_weight fudge const_tab) rel
blanchet@40371
   593
        val irrel_weight =
blanchet@46340
   594
          ~ (stature_bonus fudge stature)
blanchet@42735
   595
          |> fold (curry (op +)
blanchet@42735
   596
                   o irrel_pconst_weight fudge const_tab chained_consts) irrel
blanchet@40371
   597
        val res = rel_weight / (rel_weight + irrel_weight)
blanchet@40371
   598
      in if Real.isFinite res then res else 0.0 end
blanchet@38747
   599
blanchet@40369
   600
fun pconsts_in_fact thy is_built_in_const t =
blanchet@38825
   601
  Symtab.fold (fn (s, pss) => fold (cons o pair s) pss)
blanchet@42732
   602
              (Symtab.empty |> add_pconsts_in_term thy is_built_in_const true
blanchet@42732
   603
                                                   (SOME true) t) []
blanchet@42729
   604
blanchet@40369
   605
fun pair_consts_fact thy is_built_in_const fudge fact =
blanchet@40204
   606
  case fact |> snd |> theory_const_prop_of fudge
blanchet@40369
   607
            |> pconsts_in_fact thy is_built_in_const of
blanchet@38827
   608
    [] => NONE
blanchet@40204
   609
  | consts => SOME ((fact, consts), NONE)
paulson@24287
   610
blanchet@41768
   611
val const_names_in_fact = map fst ooo pconsts_in_fact
blanchet@41768
   612
blanchet@38699
   613
type annotated_thm =
blanchet@46340
   614
  (((unit -> string) * stature) * thm) * (string * ptype) list
blanchet@37505
   615
blanchet@42646
   616
fun take_most_relevant ctxt max_relevant remaining_max
blanchet@42728
   617
        ({max_imperfect, max_imperfect_exp, ...} : relevance_fudge)
blanchet@40070
   618
        (candidates : (annotated_thm * real) list) =
blanchet@38744
   619
  let
blanchet@38747
   620
    val max_imperfect =
blanchet@40070
   621
      Real.ceil (Math.pow (max_imperfect,
blanchet@38904
   622
                    Math.pow (Real.fromInt remaining_max
blanchet@40070
   623
                              / Real.fromInt max_relevant, max_imperfect_exp)))
blanchet@38747
   624
    val (perfect, imperfect) =
blanchet@38889
   625
      candidates |> sort (Real.compare o swap o pairself snd)
blanchet@38889
   626
                 |> take_prefix (fn (_, w) => w > 0.99999)
blanchet@38747
   627
    val ((accepts, more_rejects), rejects) =
blanchet@38747
   628
      chop max_imperfect imperfect |>> append perfect |>> chop remaining_max
blanchet@38744
   629
  in
blanchet@42646
   630
    trace_msg ctxt (fn () =>
wenzelm@41491
   631
        "Actually passed (" ^ string_of_int (length accepts) ^ " of " ^
wenzelm@41491
   632
        string_of_int (length candidates) ^ "): " ^
blanchet@38889
   633
        (accepts |> map (fn ((((name, _), _), _), weight) =>
blanchet@38752
   634
                            name () ^ " [" ^ Real.toString weight ^ "]")
blanchet@38745
   635
                 |> commas));
blanchet@38747
   636
    (accepts, more_rejects @ rejects)
blanchet@38744
   637
  end
paulson@24287
   638
blanchet@46340
   639
fun if_empty_replace_with_scope thy is_built_in_const facts sc tab =
blanchet@38819
   640
  if Symtab.is_empty tab then
blanchet@42732
   641
    Symtab.empty
blanchet@42732
   642
    |> fold (add_pconsts_in_term thy is_built_in_const false (SOME false))
blanchet@46340
   643
            (map_filter (fn ((_, (sc', _)), th) =>
blanchet@46340
   644
                            if sc' = sc then SOME (prop_of th) else NONE) facts)
blanchet@38819
   645
  else
blanchet@38819
   646
    tab
blanchet@38819
   647
blanchet@42702
   648
fun consider_arities is_built_in_const th =
blanchet@41158
   649
  let
blanchet@41158
   650
    fun aux _ _ NONE = NONE
blanchet@41158
   651
      | aux t args (SOME tab) =
blanchet@41158
   652
        case t of
blanchet@41158
   653
          t1 $ t2 => SOME tab |> aux t1 (t2 :: args) |> aux t2 []
blanchet@41158
   654
        | Const (x as (s, _)) =>
blanchet@41336
   655
          (if is_built_in_const x args |> fst then
blanchet@41158
   656
             SOME tab
blanchet@41158
   657
           else case Symtab.lookup tab s of
blanchet@41158
   658
             NONE => SOME (Symtab.update (s, length args) tab)
blanchet@41158
   659
           | SOME n => if n = length args then SOME tab else NONE)
blanchet@41158
   660
        | _ => SOME tab
blanchet@41158
   661
  in aux (prop_of th) [] end
blanchet@41158
   662
blanchet@44785
   663
(* FIXME: This is currently only useful for polymorphic type encodings. *)
blanchet@42702
   664
fun could_benefit_from_ext is_built_in_const facts =
blanchet@42702
   665
  fold (consider_arities is_built_in_const o snd) facts (SOME Symtab.empty)
blanchet@41158
   666
  |> is_none
blanchet@41158
   667
blanchet@43492
   668
(* High enough so that it isn't wrongly considered as very relevant (e.g., for E
blanchet@43492
   669
   weights), but low enough so that it is unlikely to be truncated away if few
blanchet@43492
   670
   facts are included. *)
blanchet@43492
   671
val special_fact_index = 75
blanchet@43492
   672
blanchet@44625
   673
fun relevance_filter ctxt threshold0 decay max_relevant is_built_in_const
blanchet@40070
   674
        (fudge as {threshold_divisor, ridiculous_threshold, ...})
blanchet@42732
   675
        ({add, del, ...} : relevance_override) facts chained_ts hyp_ts concl_t =
blanchet@38739
   676
  let
wenzelm@42361
   677
    val thy = Proof_Context.theory_of ctxt
blanchet@40204
   678
    val const_tab = fold (count_fact_consts thy fudge) facts Symtab.empty
blanchet@42732
   679
    val add_pconsts = add_pconsts_in_term thy is_built_in_const false o SOME
blanchet@42732
   680
    val chained_const_tab = Symtab.empty |> fold (add_pconsts true) chained_ts
blanchet@38819
   681
    val goal_const_tab =
blanchet@42732
   682
      Symtab.empty |> fold (add_pconsts true) hyp_ts
blanchet@42732
   683
                   |> add_pconsts false concl_t
blanchet@42732
   684
      |> (fn tab => if Symtab.is_empty tab then chained_const_tab else tab)
blanchet@46340
   685
      |> fold (if_empty_replace_with_scope thy is_built_in_const facts)
blanchet@38993
   686
              [Chained, Assum, Local]
blanchet@39012
   687
    val add_ths = Attrib.eval_thms ctxt add
blanchet@39012
   688
    val del_ths = Attrib.eval_thms ctxt del
blanchet@42957
   689
    val facts = facts |> filter_out (member Thm.eq_thm_prop del_ths o snd)
blanchet@38747
   690
    fun iter j remaining_max threshold rel_const_tab hopeless hopeful =
blanchet@38739
   691
      let
blanchet@40191
   692
        fun relevant [] _ [] =
blanchet@38747
   693
            (* Nothing has been added this iteration. *)
blanchet@40070
   694
            if j = 0 andalso threshold >= ridiculous_threshold then
blanchet@38747
   695
              (* First iteration? Try again. *)
blanchet@40070
   696
              iter 0 max_relevant (threshold / threshold_divisor) rel_const_tab
blanchet@38747
   697
                   hopeless hopeful
blanchet@38744
   698
            else
blanchet@40191
   699
              []
blanchet@38889
   700
          | relevant candidates rejects [] =
blanchet@38739
   701
            let
blanchet@38747
   702
              val (accepts, more_rejects) =
blanchet@42646
   703
                take_most_relevant ctxt max_relevant remaining_max fudge
blanchet@42646
   704
                                   candidates
blanchet@38739
   705
              val rel_const_tab' =
blanchet@38745
   706
                rel_const_tab
blanchet@41066
   707
                |> fold (add_pconst_to_table false) (maps (snd o fst) accepts)
blanchet@38744
   708
              fun is_dirty (c, _) =
blanchet@38744
   709
                Symtab.lookup rel_const_tab' c <> Symtab.lookup rel_const_tab c
blanchet@38745
   710
              val (hopeful_rejects, hopeless_rejects) =
blanchet@38745
   711
                 (rejects @ hopeless, ([], []))
blanchet@38745
   712
                 |-> fold (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   713
                              if exists is_dirty consts then
blanchet@38745
   714
                                apfst (cons (ax, NONE))
blanchet@38745
   715
                              else
blanchet@38745
   716
                                apsnd (cons (ax, old_weight)))
blanchet@38745
   717
                 |>> append (more_rejects
blanchet@38745
   718
                             |> map (fn (ax as (_, consts), old_weight) =>
blanchet@38745
   719
                                        (ax, if exists is_dirty consts then NONE
blanchet@38745
   720
                                             else SOME old_weight)))
blanchet@38747
   721
              val threshold =
blanchet@38822
   722
                1.0 - (1.0 - threshold)
blanchet@38822
   723
                      * Math.pow (decay, Real.fromInt (length accepts))
blanchet@38747
   724
              val remaining_max = remaining_max - length accepts
blanchet@38739
   725
            in
blanchet@42646
   726
              trace_msg ctxt (fn () => "New or updated constants: " ^
blanchet@38744
   727
                  commas (rel_const_tab' |> Symtab.dest
blanchet@38822
   728
                          |> subtract (op =) (rel_const_tab |> Symtab.dest)
blanchet@38827
   729
                          |> map string_for_hyper_pconst));
blanchet@38745
   730
              map (fst o fst) accepts @
blanchet@38747
   731
              (if remaining_max = 0 then
blanchet@40191
   732
                 []
blanchet@38745
   733
               else
blanchet@38747
   734
                 iter (j + 1) remaining_max threshold rel_const_tab'
blanchet@38747
   735
                      hopeless_rejects hopeful_rejects)
blanchet@38739
   736
            end
blanchet@38889
   737
          | relevant candidates rejects
blanchet@46340
   738
                     (((ax as (((_, stature), _), fact_consts)), cached_weight)
blanchet@38747
   739
                      :: hopeful) =
blanchet@38739
   740
            let
blanchet@38739
   741
              val weight =
blanchet@38739
   742
                case cached_weight of
blanchet@38739
   743
                  SOME w => w
blanchet@46340
   744
                | NONE => fact_weight fudge stature const_tab rel_const_tab
blanchet@42732
   745
                                      chained_const_tab fact_consts
blanchet@38739
   746
            in
blanchet@38741
   747
              if weight >= threshold then
blanchet@38889
   748
                relevant ((ax, weight) :: candidates) rejects hopeful
blanchet@38739
   749
              else
blanchet@38889
   750
                relevant candidates ((ax, weight) :: rejects) hopeful
blanchet@38739
   751
            end
blanchet@38739
   752
        in
blanchet@42646
   753
          trace_msg ctxt (fn () =>
blanchet@38744
   754
              "ITERATION " ^ string_of_int j ^ ": current threshold: " ^
blanchet@38744
   755
              Real.toString threshold ^ ", constants: " ^
blanchet@38744
   756
              commas (rel_const_tab |> Symtab.dest
blanchet@38744
   757
                      |> filter (curry (op <>) [] o snd)
blanchet@38827
   758
                      |> map string_for_hyper_pconst));
blanchet@38889
   759
          relevant [] [] hopeful
blanchet@38739
   760
        end
blanchet@42826
   761
    fun prepend_facts ths accepts =
blanchet@42957
   762
      ((facts |> filter (member Thm.eq_thm_prop ths o snd)) @
blanchet@42957
   763
       (accepts |> filter_out (member Thm.eq_thm_prop ths o snd)))
blanchet@40408
   764
      |> take max_relevant
blanchet@47933
   765
    fun uses_const s t =
blanchet@47933
   766
      fold_aterms (curry (fn (Const (s', _), false) => s' = s | (_, b) => b)) t
blanchet@47933
   767
                  false
blanchet@47933
   768
    fun uses_const_anywhere accepts s =
blanchet@47933
   769
      exists (uses_const s o prop_of o snd) accepts orelse
blanchet@47933
   770
      exists (uses_const s) (concl_t :: hyp_ts)
blanchet@47933
   771
    fun add_set_const_thms accepts =
blanchet@47933
   772
      exists (uses_const_anywhere accepts) set_consts ? append set_thms
blanchet@43492
   773
    fun insert_into_facts accepts [] = accepts
blanchet@43492
   774
      | insert_into_facts accepts ths =
blanchet@43492
   775
        let
blanchet@43492
   776
          val add = facts |> filter (member Thm.eq_thm_prop ths o snd)
blanchet@43492
   777
          val (bef, after) =
blanchet@43492
   778
            accepts |> filter_out (member Thm.eq_thm_prop ths o snd)
blanchet@43492
   779
                    |> take (max_relevant - length add)
blanchet@43492
   780
                    |> chop special_fact_index
blanchet@43492
   781
        in bef @ add @ after end
blanchet@43492
   782
    fun insert_special_facts accepts =
blanchet@47939
   783
       (* FIXME: get rid of "ext" here once it is treated as a helper *)
blanchet@43066
   784
       [] |> could_benefit_from_ext is_built_in_const accepts ? cons @{thm ext}
blanchet@47933
   785
          |> add_set_const_thms accepts
blanchet@43492
   786
          |> insert_into_facts accepts
blanchet@38739
   787
  in
blanchet@40369
   788
    facts |> map_filter (pair_consts_fact thy is_built_in_const fudge)
blanchet@40204
   789
          |> iter 0 max_relevant threshold0 goal_const_tab []
blanchet@42826
   790
          |> not (null add_ths) ? prepend_facts add_ths
blanchet@43492
   791
          |> insert_special_facts
blanchet@42646
   792
          |> tap (fn accepts => trace_msg ctxt (fn () =>
wenzelm@41491
   793
                      "Total relevant: " ^ string_of_int (length accepts)))
blanchet@38739
   794
  end
paulson@24287
   795
blanchet@38744
   796
paulson@24287
   797
(***************************************************************)
mengj@19768
   798
(* Retrieving and filtering lemmas                             *)
mengj@19768
   799
(***************************************************************)
mengj@19768
   800
paulson@33022
   801
(*** retrieve lemmas and filter them ***)
mengj@19768
   802
paulson@20757
   803
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   804
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   805
fun is_package_def a =
blanchet@40205
   806
  let val names = Long_Name.explode a in
blanchet@40205
   807
    (length names > 2 andalso not (hd names = "local") andalso
blanchet@40205
   808
     String.isSuffix "_def" a) orelse String.isSuffix "_defs" a
blanchet@40205
   809
  end
paulson@20757
   810
blanchet@43245
   811
fun uniquify xs =
blanchet@43245
   812
  Termtab.fold (cons o snd)
blanchet@43245
   813
               (fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty) []
mengj@19768
   814
blanchet@37626
   815
(* FIXME: put other record thms here, or declare as "no_atp" *)
nik@44585
   816
fun multi_base_blacklist ctxt ho_atp =
blanchet@41199
   817
  ["defs", "select_defs", "update_defs", "split", "splits", "split_asm",
blanchet@41199
   818
   "cases", "ext_cases", "eq.simps", "eq.refl", "nchotomy", "case_cong",
blanchet@41199
   819
   "weak_case_cong"]
nik@44585
   820
  |> not (ho_atp orelse (Config.get ctxt instantiate_inducts)) ?
nik@44585
   821
        append ["induct", "inducts"]
blanchet@38682
   822
  |> map (prefix ".")
blanchet@37626
   823
nik@44585
   824
val max_lambda_nesting = 3 (*only applies if not ho_atp*)
blanchet@37626
   825
blanchet@37626
   826
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37626
   827
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37626
   828
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37626
   829
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37626
   830
  | term_has_too_many_lambdas _ _ = false
blanchet@37626
   831
blanchet@37626
   832
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37626
   833
   quantifiers. *)
nik@44585
   834
fun formula_has_too_many_lambdas true _ _ = false (*i.e. ho_atp*)
nik@44585
   835
  | formula_has_too_many_lambdas _ Ts (Abs (_, T, t)) =
nik@44585
   836
      formula_has_too_many_lambdas false (T :: Ts) t
nik@44585
   837
  | formula_has_too_many_lambdas _ Ts t =
blanchet@41273
   838
    if member (op =) [HOLogic.boolT, propT] (fastype_of1 (Ts, t)) then
nik@44585
   839
      exists (formula_has_too_many_lambdas false Ts) (#2 (strip_comb t))
blanchet@37626
   840
    else
blanchet@37626
   841
      term_has_too_many_lambdas max_lambda_nesting t
blanchet@37626
   842
blanchet@38692
   843
(* The max apply depth of any "metis" call in "Metis_Examples" (on 2007-10-31)
blanchet@37626
   844
   was 11. *)
blanchet@37626
   845
val max_apply_depth = 15
blanchet@37626
   846
blanchet@37626
   847
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37626
   848
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37626
   849
  | apply_depth _ = 0
blanchet@37626
   850
nik@44585
   851
fun is_formula_too_complex ho_atp t =
nik@44585
   852
  apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas ho_atp [] t
blanchet@37626
   853
blanchet@39946
   854
(* FIXME: Extend to "Meson" and "Metis" *)
blanchet@37543
   855
val exists_sledgehammer_const =
blanchet@37626
   856
  exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
blanchet@37626
   857
blanchet@38904
   858
(* FIXME: make more reliable *)
blanchet@38904
   859
val exists_low_level_class_const =
blanchet@38904
   860
  exists_Const (fn (s, _) =>
blanchet@47976
   861
     s = @{const_name equal_class.equal} orelse
blanchet@38904
   862
     String.isSubstring (Long_Name.separator ^ "class" ^ Long_Name.separator) s)
blanchet@38904
   863
blanchet@38821
   864
fun is_metastrange_theorem th =
blanchet@37626
   865
  case head_of (concl_of th) of
blanchet@43576
   866
    Const (s, _) => (s <> @{const_name Trueprop} andalso
blanchet@43576
   867
                     s <> @{const_name "=="})
blanchet@43576
   868
  | _ => false
blanchet@37626
   869
blanchet@38821
   870
fun is_that_fact th =
blanchet@38821
   871
  String.isSuffix (Long_Name.separator ^ Obtain.thatN) (Thm.get_name_hint th)
blanchet@38821
   872
  andalso exists_subterm (fn Free (s, _) => s = Name.skolem Auto_Bind.thesisN
blanchet@38821
   873
                           | _ => false) (prop_of th)
blanchet@38821
   874
blanchet@38085
   875
(**** Predicates to detect unwanted facts (prolific or likely to cause
blanchet@37347
   876
      unsoundness) ****)
paulson@21470
   877
nik@44585
   878
fun is_theorem_bad_for_atps ho_atp exporter thm =
blanchet@43576
   879
  is_metastrange_theorem thm orelse
blanchet@43576
   880
  (not exporter andalso
blanchet@43576
   881
   let val t = prop_of thm in
nik@44585
   882
     is_formula_too_complex ho_atp t orelse exists_type type_has_top_sort t orelse
blanchet@43576
   883
     exists_sledgehammer_const t orelse exists_low_level_class_const t orelse
blanchet@43576
   884
     is_that_fact thm
blanchet@43576
   885
   end)
blanchet@38627
   886
blanchet@46734
   887
fun all_facts ctxt ho_atp reserved exporter add_ths chained_ths css_table =
blanchet@38627
   888
  let
wenzelm@42361
   889
    val thy = Proof_Context.theory_of ctxt
wenzelm@39557
   890
    val global_facts = Global_Theory.facts_of thy
wenzelm@42361
   891
    val local_facts = Proof_Context.facts_of ctxt
blanchet@38644
   892
    val named_locals = local_facts |> Facts.dest_static []
blanchet@38993
   893
    val assms = Assumption.all_assms_of ctxt
blanchet@38738
   894
    fun is_good_unnamed_local th =
blanchet@38820
   895
      not (Thm.has_name_hint th) andalso
blanchet@42957
   896
      forall (fn (_, ths) => not (member Thm.eq_thm_prop ths th)) named_locals
blanchet@38644
   897
    val unnamed_locals =
blanchet@42957
   898
      union Thm.eq_thm_prop (Facts.props local_facts) chained_ths
blanchet@38820
   899
      |> filter is_good_unnamed_local |> map (pair "" o single)
blanchet@38627
   900
    val full_space =
blanchet@38738
   901
      Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts)
blanchet@38752
   902
    fun add_facts global foldx facts =
blanchet@38699
   903
      foldx (fn (name0, ths) =>
blanchet@43576
   904
        if not exporter andalso name0 <> "" andalso
blanchet@42957
   905
           forall (not o member Thm.eq_thm_prop add_ths) ths andalso
blanchet@38699
   906
           (Facts.is_concealed facts name0 orelse
blanchet@42728
   907
            (not (Config.get ctxt ignore_no_atp) andalso
blanchet@42728
   908
             is_package_def name0) orelse
blanchet@42728
   909
            exists (fn s => String.isSuffix s name0)
wenzelm@46976
   910
                   (multi_base_blacklist ctxt ho_atp)) then
blanchet@38627
   911
          I
blanchet@38627
   912
        else
blanchet@38627
   913
          let
blanchet@38699
   914
            val multi = length ths > 1
blanchet@41279
   915
            val backquote_thm =
blanchet@41279
   916
              backquote o string_for_term ctxt o close_form o prop_of
blanchet@38699
   917
            fun check_thms a =
wenzelm@42361
   918
              case try (Proof_Context.get_thms ctxt) a of
blanchet@38699
   919
                NONE => false
blanchet@42957
   920
              | SOME ths' => eq_list Thm.eq_thm_prop (ths, ths')
blanchet@38627
   921
          in
blanchet@38699
   922
            pair 1
blanchet@43245
   923
            #> fold (fn th => fn (j, (multis, unis)) =>
blanchet@42641
   924
                        (j + 1,
blanchet@43576
   925
                         if not (member Thm.eq_thm_prop add_ths th) andalso
nik@44585
   926
                            is_theorem_bad_for_atps ho_atp exporter th then
blanchet@43245
   927
                           (multis, unis)
blanchet@42641
   928
                         else
blanchet@43245
   929
                           let
blanchet@43245
   930
                             val new =
blanchet@43245
   931
                               (((fn () =>
blanchet@42641
   932
                                 if name0 = "" then
blanchet@42641
   933
                                   th |> backquote_thm
blanchet@42641
   934
                                 else
blanchet@42641
   935
                                   [Facts.extern ctxt facts name0,
blanchet@42641
   936
                                    Name_Space.extern ctxt full_space name0,
blanchet@42641
   937
                                    name0]
blanchet@42641
   938
                                   |> find_first check_thms
blanchet@42641
   939
                                   |> (fn SOME name =>
blanchet@42641
   940
                                          make_name reserved multi j name
blanchet@42641
   941
                                        | NONE => "")),
blanchet@46388
   942
                                stature_of_thm global assms chained_ths
blanchet@46388
   943
                                               css_table name0 th), th)
blanchet@43245
   944
                           in
blanchet@43245
   945
                             if multi then (new :: multis, unis)
blanchet@43245
   946
                             else (multis, new :: unis)
blanchet@43245
   947
                           end)) ths
blanchet@38699
   948
            #> snd
blanchet@38627
   949
          end)
blanchet@38644
   950
  in
blanchet@43245
   951
    (* The single-name theorems go after the multiple-name ones, so that single
blanchet@43245
   952
       names are preferred when both are available. *)
blanchet@43245
   953
    ([], []) |> add_facts false fold local_facts (unnamed_locals @ named_locals)
blanchet@43245
   954
             |> add_facts true Facts.fold_static global_facts global_facts
blanchet@43245
   955
             |> op @
blanchet@38644
   956
  end
blanchet@38627
   957
blanchet@41199
   958
fun external_frees t =
blanchet@41199
   959
  [] |> Term.add_frees t |> filter_out (can Name.dest_internal o fst)
blanchet@41199
   960
nik@44585
   961
fun nearly_all_facts ctxt ho_atp ({add, only, ...} : relevance_override)
nik@44585
   962
                     chained_ths hyp_ts concl_t =
blanchet@46734
   963
  if only andalso null add then
blanchet@46734
   964
    []
blanchet@46734
   965
  else
blanchet@46734
   966
    let
blanchet@46734
   967
      val thy = Proof_Context.theory_of ctxt
blanchet@46734
   968
      val reserved = reserved_isar_keyword_table ()
blanchet@46734
   969
      val add_ths = Attrib.eval_thms ctxt add
blanchet@46734
   970
      val ind_stmt =
blanchet@46734
   971
        (hyp_ts |> filter_out (null o external_frees), concl_t)
blanchet@46734
   972
        |> Logic.list_implies |> Object_Logic.atomize_term thy
blanchet@46734
   973
      val ind_stmt_xs = external_frees ind_stmt
blanchet@46734
   974
      val css_table = clasimpset_rule_table_of ctxt
blanchet@46734
   975
    in
blanchet@46734
   976
      (if only then
blanchet@46734
   977
         maps (map (fn ((name, stature), th) => ((K name, stature), th))
blanchet@46734
   978
               o fact_from_ref ctxt reserved chained_ths css_table) add
blanchet@46734
   979
       else
blanchet@46734
   980
         all_facts ctxt ho_atp reserved false add_ths chained_ths css_table)
blanchet@46734
   981
      |> Config.get ctxt instantiate_inducts
blanchet@46734
   982
         ? maps (instantiate_if_induct_rule ctxt ind_stmt ind_stmt_xs)
blanchet@46734
   983
      |> (not (Config.get ctxt ignore_no_atp) andalso not only)
blanchet@46734
   984
         ? filter_out (No_ATPs.member ctxt o snd)
blanchet@46734
   985
      |> uniquify
blanchet@46734
   986
    end
blanchet@43351
   987
blanchet@44625
   988
fun relevant_facts ctxt (threshold0, threshold1) max_relevant is_built_in_const
blanchet@44625
   989
                   fudge (override as {only, ...}) chained_ths hyp_ts concl_t
blanchet@44625
   990
                   facts =
blanchet@37538
   991
  let
wenzelm@42361
   992
    val thy = Proof_Context.theory_of ctxt
blanchet@38822
   993
    val decay = Math.pow ((1.0 - threshold1) / (1.0 - threshold0),
blanchet@38822
   994
                          1.0 / Real.fromInt (max_relevant + 1))
blanchet@37538
   995
  in
blanchet@42646
   996
    trace_msg ctxt (fn () => "Considering " ^ string_of_int (length facts) ^
blanchet@42646
   997
                             " facts");
blanchet@39366
   998
    (if only orelse threshold1 < 0.0 then
blanchet@40204
   999
       facts
blanchet@39366
  1000
     else if threshold0 > 1.0 orelse threshold0 > threshold1 orelse
blanchet@39366
  1001
             max_relevant = 0 then
blanchet@38739
  1002
       []
blanchet@38739
  1003
     else
blanchet@44625
  1004
       relevance_filter ctxt threshold0 decay max_relevant is_built_in_const
blanchet@44625
  1005
           fudge override facts (chained_ths |> map prop_of) hyp_ts
blanchet@44625
  1006
           (concl_t |> theory_constify fudge (Context.theory_name thy)))
blanchet@38822
  1007
    |> map (apfst (apfst (fn f => f ())))
blanchet@37538
  1008
  end
immler@30536
  1009
paulson@15347
  1010
end;