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