src/Pure/Tools/find_theorems.ML
author krauss
Mon May 30 17:07:48 2011 +0200 (2011-05-30)
changeset 43067 76e1d25c6357
parent 42669 04dfffda5671
child 43068 ac769b5edd1d
permissions -rw-r--r--
separate query parsing from actual search
wenzelm@30143
     1
(*  Title:      Pure/Tools/find_theorems.ML
wenzelm@26283
     2
    Author:     Rafal Kolanski and Gerwin Klein, NICTA
wenzelm@16033
     3
wenzelm@16033
     4
Retrieve theorems from proof context.
wenzelm@16033
     5
*)
wenzelm@16033
     6
wenzelm@16033
     7
signature FIND_THEOREMS =
wenzelm@16033
     8
sig
wenzelm@16036
     9
  datatype 'term criterion =
Timothy@31042
    10
    Name of string | Intro | IntroIff | Elim | Dest | Solves | Simp of 'term |
kleing@29857
    11
    Pattern of 'term
krauss@41844
    12
krauss@41844
    13
  datatype theorem =
krauss@41845
    14
    Internal of Facts.ref * thm | External of Facts.ref * term
krauss@41844
    15
wenzelm@32738
    16
  val tac_limit: int Unsynchronized.ref
wenzelm@32738
    17
  val limit: int Unsynchronized.ref
krauss@43067
    18
krauss@43067
    19
  val read_criterion: Proof.context -> string criterion -> term criterion
krauss@43067
    20
Timothy@30785
    21
  val find_theorems: Proof.context -> thm option -> int option -> bool ->
krauss@43067
    22
    (bool * term criterion) list -> int option * (Facts.ref * thm) list
krauss@43067
    23
  val find_theorems_cmd: Proof.context -> thm option -> int option -> bool ->
Timothy@30785
    24
    (bool * string criterion) list -> int option * (Facts.ref * thm) list
krauss@41844
    25
  val filter_theorems: Proof.context -> theorem list -> thm option ->
krauss@43067
    26
    int option -> bool -> (bool * term criterion) list ->
krauss@43067
    27
    int option * theorem list
krauss@43067
    28
  val filter_theorems_cmd: Proof.context -> theorem list -> thm option ->
noschinl@41841
    29
    int option -> bool -> (bool * string criterion) list ->
krauss@41844
    30
    int option * theorem list
noschinl@41841
    31
krauss@41845
    32
  val pretty_theorem: Proof.context -> theorem -> Pretty.T
wenzelm@30186
    33
  val pretty_thm: Proof.context -> Facts.ref * thm -> Pretty.T
krauss@41845
    34
wenzelm@16033
    35
end;
wenzelm@16033
    36
wenzelm@33301
    37
structure Find_Theorems: FIND_THEOREMS =
wenzelm@16033
    38
struct
wenzelm@16033
    39
wenzelm@16033
    40
(** search criteria **)
wenzelm@16033
    41
wenzelm@16036
    42
datatype 'term criterion =
Timothy@31042
    43
  Name of string | Intro | IntroIff | Elim | Dest | Solves | Simp of 'term |
kleing@29857
    44
  Pattern of 'term;
wenzelm@16036
    45
kleing@33036
    46
fun apply_dummies tm =
wenzelm@33301
    47
  let
wenzelm@33301
    48
    val (xs, _) = Term.strip_abs tm;
wenzelm@33301
    49
    val tm' = Term.betapplys (tm, map (Term.dummy_pattern o #2) xs);
wenzelm@33301
    50
  in #1 (Term.replace_dummy_patterns tm' 1) end;
kleing@33036
    51
kleing@33036
    52
fun parse_pattern ctxt nm =
kleing@33036
    53
  let
wenzelm@42360
    54
    val consts = Proof_Context.consts_of ctxt;
wenzelm@33301
    55
    val nm' =
wenzelm@33301
    56
      (case Syntax.parse_term ctxt nm of
wenzelm@33301
    57
        Const (c, _) => c
wenzelm@33301
    58
      | _ => Consts.intern consts nm);
kleing@33036
    59
  in
wenzelm@33301
    60
    (case try (Consts.the_abbreviation consts) nm' of
wenzelm@42360
    61
      SOME (_, rhs) => apply_dummies (Proof_Context.expand_abbrevs ctxt rhs)
wenzelm@42360
    62
    | NONE => Proof_Context.read_term_pattern ctxt nm)
kleing@33036
    63
  end;
kleing@33036
    64
wenzelm@16036
    65
fun read_criterion _ (Name name) = Name name
wenzelm@16036
    66
  | read_criterion _ Intro = Intro
Timothy@31042
    67
  | read_criterion _ IntroIff = IntroIff
wenzelm@16036
    68
  | read_criterion _ Elim = Elim
wenzelm@16036
    69
  | read_criterion _ Dest = Dest
kleing@29857
    70
  | read_criterion _ Solves = Solves
wenzelm@42360
    71
  | read_criterion ctxt (Simp str) = Simp (Proof_Context.read_term_pattern ctxt str)
kleing@33036
    72
  | read_criterion ctxt (Pattern str) = Pattern (parse_pattern ctxt str);
wenzelm@16033
    73
wenzelm@16036
    74
fun pretty_criterion ctxt (b, c) =
wenzelm@16036
    75
  let
wenzelm@16036
    76
    fun prfx s = if b then s else "-" ^ s;
wenzelm@16036
    77
  in
wenzelm@16036
    78
    (case c of
wenzelm@16036
    79
      Name name => Pretty.str (prfx "name: " ^ quote name)
wenzelm@16036
    80
    | Intro => Pretty.str (prfx "intro")
Timothy@31042
    81
    | IntroIff => Pretty.str (prfx "introiff")
wenzelm@16036
    82
    | Elim => Pretty.str (prfx "elim")
wenzelm@16036
    83
    | Dest => Pretty.str (prfx "dest")
kleing@29857
    84
    | Solves => Pretty.str (prfx "solves")
kleing@16088
    85
    | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
wenzelm@24920
    86
        Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
wenzelm@16036
    87
    | Pattern pat => Pretty.enclose (prfx " \"") "\""
wenzelm@24920
    88
        [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
wenzelm@16036
    89
  end;
wenzelm@16033
    90
wenzelm@30142
    91
krauss@41845
    92
(** theorems, either internal or external (without proof) **)
krauss@41844
    93
krauss@41844
    94
datatype theorem =
krauss@41844
    95
  Internal of Facts.ref * thm |
krauss@41844
    96
  External of Facts.ref * term;
krauss@41844
    97
krauss@41844
    98
fun prop_of (Internal (_, thm)) = Thm.full_prop_of thm
krauss@41844
    99
  | prop_of (External (_, prop)) = prop;
krauss@41844
   100
krauss@41844
   101
fun nprems_of (Internal (_, thm)) = Thm.nprems_of thm
krauss@41844
   102
  | nprems_of (External (_, prop)) = Logic.count_prems prop;
krauss@41844
   103
krauss@41844
   104
fun major_prem_of (Internal (_, thm)) = Thm.major_prem_of thm
krauss@41844
   105
  | major_prem_of (External (_, prop)) =
krauss@41844
   106
      Logic.strip_assums_concl (hd (Logic.strip_imp_prems prop));
krauss@41844
   107
krauss@41844
   108
fun fact_ref_of (Internal (fact_ref, _)) = fact_ref
krauss@41844
   109
  | fact_ref_of (External (fact_ref, _)) = fact_ref;
wenzelm@30142
   110
wenzelm@16033
   111
(** search criterion filters **)
wenzelm@16033
   112
kleing@16895
   113
(*generated filters are to be of the form
krauss@41844
   114
  input: theorem
wenzelm@17106
   115
  output: (p:int, s:int) option, where
kleing@16895
   116
    NONE indicates no match
wenzelm@17106
   117
    p is the primary sorting criterion
kleing@16895
   118
      (eg. number of assumptions in the theorem)
kleing@16895
   119
    s is the secondary sorting criterion
kleing@16895
   120
      (eg. size of the substitution for intro, elim and dest)
kleing@16895
   121
  when applying a set of filters to a thm, fold results in:
kleing@16895
   122
    (biggest p, sum of all s)
wenzelm@17106
   123
  currently p and s only matter for intro, elim, dest and simp filters,
wenzelm@17106
   124
  otherwise the default ordering is used.
kleing@16895
   125
*)
kleing@16895
   126
kleing@16088
   127
kleing@16088
   128
(* matching theorems *)
wenzelm@17106
   129
wenzelm@35625
   130
fun is_nontrivial thy = Term.is_Const o Term.head_of o Object_Logic.drop_judgment thy;
kleing@16088
   131
wenzelm@32798
   132
(*educated guesses on HOL*)  (* FIXME broken *)
wenzelm@32798
   133
val boolT = Type ("bool", []);
wenzelm@32798
   134
val iff_const = Const ("op =", boolT --> boolT --> boolT);
Timothy@31042
   135
kleing@16964
   136
(*extract terms from term_src, refine them to the parts that concern us,
kleing@16964
   137
  if po try match them against obj else vice versa.
kleing@16964
   138
  trivial matches are ignored.
kleing@16964
   139
  returns: smallest substitution size*)
Timothy@31042
   140
fun is_matching_thm doiff (extract_terms, refine_term) ctxt po obj term_src =
kleing@16088
   141
  let
wenzelm@42360
   142
    val thy = Proof_Context.theory_of ctxt;
kleing@16088
   143
wenzelm@32798
   144
    fun check_match pat = Pattern.matches thy (if po then (pat, obj) else (obj, pat));
wenzelm@16486
   145
    fun matches pat =
Timothy@31042
   146
      let
wenzelm@35625
   147
        val jpat = Object_Logic.drop_judgment thy pat;
Timothy@31042
   148
        val c = Term.head_of jpat;
Timothy@31042
   149
        val pats =
Timothy@31042
   150
          if Term.is_Const c
wenzelm@32798
   151
          then
wenzelm@32798
   152
            if doiff andalso c = iff_const then
wenzelm@35625
   153
              (pat :: map (Object_Logic.ensure_propT thy) (snd (strip_comb jpat)))
wenzelm@32798
   154
                |> filter (is_nontrivial thy)
wenzelm@32798
   155
            else [pat]
Timothy@31042
   156
          else [];
wenzelm@32798
   157
      in filter check_match pats end;
kleing@16895
   158
kleing@16895
   159
    fun substsize pat =
wenzelm@18184
   160
      let val (_, subst) =
wenzelm@18184
   161
        Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
wenzelm@17205
   162
      in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
kleing@16088
   163
kleing@16895
   164
    fun bestmatch [] = NONE
wenzelm@33029
   165
      | bestmatch xs = SOME (foldl1 Int.min xs);
kleing@16895
   166
kleing@16964
   167
    val match_thm = matches o refine_term;
wenzelm@16486
   168
  in
wenzelm@32798
   169
    maps match_thm (extract_terms term_src)
Timothy@31042
   170
    |> map substsize
wenzelm@26283
   171
    |> bestmatch
kleing@16088
   172
  end;
kleing@16088
   173
kleing@16088
   174
wenzelm@16033
   175
(* filter_name *)
wenzelm@16033
   176
krauss@41844
   177
fun filter_name str_pat theorem =
krauss@41844
   178
  if match_string str_pat (Facts.name_of_ref (fact_ref_of theorem))
wenzelm@17205
   179
  then SOME (0, 0) else NONE;
wenzelm@16033
   180
wenzelm@30142
   181
kleing@29857
   182
(* filter intro/elim/dest/solves rules *)
wenzelm@16033
   183
krauss@41844
   184
fun filter_dest ctxt goal theorem =
wenzelm@16033
   185
  let
kleing@16964
   186
    val extract_dest =
krauss@41844
   187
     (fn theorem => if nprems_of theorem = 0 then [] else [prop_of theorem],
wenzelm@16033
   188
      hd o Logic.strip_imp_prems);
wenzelm@16033
   189
    val prems = Logic.prems_of_goal goal 1;
kleing@16895
   190
krauss@41844
   191
    fun try_subst prem = is_matching_thm false extract_dest ctxt true prem theorem;
wenzelm@19482
   192
    val successful = prems |> map_filter try_subst;
wenzelm@16033
   193
  in
kleing@16895
   194
    (*if possible, keep best substitution (one with smallest size)*)
wenzelm@17106
   195
    (*dest rules always have assumptions, so a dest with one
kleing@16895
   196
      assumption is as good as an intro rule with none*)
wenzelm@17205
   197
    if not (null successful)
krauss@41844
   198
    then SOME (nprems_of theorem - 1, foldl1 Int.min successful) else NONE
wenzelm@16033
   199
  end;
wenzelm@16033
   200
krauss@41844
   201
fun filter_intro doiff ctxt goal theorem =
wenzelm@16033
   202
  let
krauss@41844
   203
    val extract_intro = (single o prop_of, Logic.strip_imp_concl);
wenzelm@16036
   204
    val concl = Logic.concl_of_goal goal 1;
krauss@41844
   205
    val ss = is_matching_thm doiff extract_intro ctxt true concl theorem;
wenzelm@16033
   206
  in
krauss@41844
   207
    if is_some ss then SOME (nprems_of theorem, the ss) else NONE
wenzelm@16033
   208
  end;
wenzelm@16033
   209
krauss@41844
   210
fun filter_elim ctxt goal theorem =
krauss@41844
   211
  if nprems_of theorem > 0 then
kleing@16964
   212
    let
krauss@41844
   213
      val rule = prop_of theorem;
kleing@16964
   214
      val prems = Logic.prems_of_goal goal 1;
kleing@16964
   215
      val goal_concl = Logic.concl_of_goal goal 1;
wenzelm@26283
   216
      val rule_mp = hd (Logic.strip_imp_prems rule);
kleing@16964
   217
      val rule_concl = Logic.strip_imp_concl rule;
wenzelm@26283
   218
      fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);
kleing@16964
   219
      val rule_tree = combine rule_mp rule_concl;
wenzelm@26283
   220
      fun goal_tree prem = combine prem goal_concl;
wenzelm@17106
   221
      fun try_subst prem =
Timothy@31042
   222
        is_matching_thm false (single, I) ctxt true (goal_tree prem) rule_tree;
wenzelm@19482
   223
      val successful = prems |> map_filter try_subst;
kleing@16964
   224
    in
wenzelm@32798
   225
      (*elim rules always have assumptions, so an elim with one
wenzelm@32798
   226
        assumption is as good as an intro rule with none*)
wenzelm@42360
   227
      if is_nontrivial (Proof_Context.theory_of ctxt) (major_prem_of theorem)
wenzelm@17205
   228
        andalso not (null successful)
krauss@41844
   229
      then SOME (nprems_of theorem - 1, foldl1 Int.min successful) else NONE
kleing@16964
   230
    end
kleing@16964
   231
  else NONE
wenzelm@16036
   232
wenzelm@32738
   233
val tac_limit = Unsynchronized.ref 5;
kleing@29857
   234
wenzelm@30143
   235
fun filter_solves ctxt goal =
wenzelm@30143
   236
  let
wenzelm@30143
   237
    fun etacn thm i = Seq.take (! tac_limit) o etac thm i;
wenzelm@30143
   238
    fun try_thm thm =
wenzelm@30143
   239
      if Thm.no_prems thm then rtac thm 1 goal
wenzelm@30318
   240
      else (etacn thm THEN_ALL_NEW (Goal.norm_hhf_tac THEN' Method.assm_tac ctxt)) 1 goal;
kleing@29857
   241
  in
krauss@41844
   242
    fn Internal (_, thm) =>
wenzelm@32798
   243
      if is_some (Seq.pull (try_thm thm))
wenzelm@30143
   244
      then SOME (Thm.nprems_of thm, 0) else NONE
krauss@41844
   245
     | External _ => NONE
kleing@29857
   246
  end;
wenzelm@16033
   247
wenzelm@30142
   248
kleing@16074
   249
(* filter_simp *)
wenzelm@16033
   250
krauss@41844
   251
fun filter_simp ctxt t (Internal (_, thm)) =
krauss@41844
   252
      let
krauss@41844
   253
        val mksimps = Simplifier.mksimps (simpset_of ctxt);
krauss@41844
   254
        val extract_simp =
krauss@41844
   255
          (map Thm.full_prop_of o mksimps, #1 o Logic.dest_equals o Logic.strip_imp_concl);
krauss@41844
   256
        val ss = is_matching_thm false extract_simp ctxt false t thm;
krauss@41844
   257
      in
krauss@41844
   258
        if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
krauss@41844
   259
      end
krauss@41844
   260
  | filter_simp _ _ (External _) = NONE;
wenzelm@16033
   261
wenzelm@16033
   262
wenzelm@16033
   263
(* filter_pattern *)
wenzelm@16033
   264
wenzelm@32798
   265
fun get_names t = Term.add_const_names t (Term.add_free_names t []);
kleing@28900
   266
wenzelm@30143
   267
(*Including all constants and frees is only sound because
wenzelm@30143
   268
  matching uses higher-order patterns. If full matching
wenzelm@30143
   269
  were used, then constants that may be subject to
wenzelm@30143
   270
  beta-reduction after substitution of frees should
wenzelm@30143
   271
  not be included for LHS set because they could be
wenzelm@30143
   272
  thrown away by the substituted function.
wenzelm@30143
   273
  e.g. for (?F 1 2) do not include 1 or 2, if it were
wenzelm@30143
   274
       possible for ?F to be (% x y. 3)
wenzelm@30143
   275
  The largest possible set should always be included on
wenzelm@30143
   276
  the RHS.*)
wenzelm@30143
   277
wenzelm@30143
   278
fun filter_pattern ctxt pat =
wenzelm@30143
   279
  let
kleing@29857
   280
    val pat_consts = get_names pat;
kleing@28900
   281
krauss@41844
   282
    fun check (theorem, NONE) = check (theorem, SOME (get_names (prop_of theorem)))
krauss@41844
   283
      | check (theorem, c as SOME thm_consts) =
haftmann@33038
   284
         (if subset (op =) (pat_consts, thm_consts) andalso
wenzelm@42360
   285
            Pattern.matches_subterm (Proof_Context.theory_of ctxt) (pat, prop_of theorem)
wenzelm@32798
   286
          then SOME (0, 0) else NONE, c);
kleing@28900
   287
  in check end;
wenzelm@16033
   288
wenzelm@30142
   289
wenzelm@16033
   290
(* interpret criteria as filters *)
wenzelm@16033
   291
wenzelm@16036
   292
local
wenzelm@16036
   293
wenzelm@16036
   294
fun err_no_goal c =
wenzelm@16036
   295
  error ("Current goal required for " ^ c ^ " search criterion");
wenzelm@16036
   296
kleing@29857
   297
val fix_goal = Thm.prop_of;
kleing@29857
   298
kleing@28900
   299
fun filter_crit _ _ (Name name) = apfst (filter_name name)
wenzelm@16036
   300
  | filter_crit _ NONE Intro = err_no_goal "intro"
noschinl@41835
   301
  | filter_crit _ NONE IntroIff = err_no_goal "introiff"
wenzelm@16036
   302
  | filter_crit _ NONE Elim = err_no_goal "elim"
wenzelm@16036
   303
  | filter_crit _ NONE Dest = err_no_goal "dest"
kleing@29857
   304
  | filter_crit _ NONE Solves = err_no_goal "solves"
Timothy@31042
   305
  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro false ctxt (fix_goal goal))
Timothy@31042
   306
  | filter_crit ctxt (SOME goal) IntroIff = apfst (filter_intro true ctxt (fix_goal goal))
wenzelm@30143
   307
  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (fix_goal goal))
wenzelm@30143
   308
  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (fix_goal goal))
kleing@29857
   309
  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
kleing@28900
   310
  | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
kleing@16088
   311
  | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
wenzelm@16036
   312
wenzelm@19502
   313
fun opt_not x = if is_some x then NONE else SOME (0, 0);
kleing@16895
   314
wenzelm@17756
   315
fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
wenzelm@26283
   316
  | opt_add _ _ = NONE;
kleing@16895
   317
wenzelm@30143
   318
fun app_filters thm =
wenzelm@30143
   319
  let
kleing@28900
   320
    fun app (NONE, _, _) = NONE
wenzelm@32798
   321
      | app (SOME v, _, []) = SOME (v, thm)
wenzelm@30143
   322
      | app (r, consts, f :: fs) =
wenzelm@30143
   323
          let val (r', consts') = f (thm, consts)
wenzelm@30143
   324
          in app (opt_add r r', consts', fs) end;
kleing@28900
   325
  in app end;
kleing@28900
   326
wenzelm@31684
   327
wenzelm@16036
   328
in
wenzelm@16033
   329
wenzelm@16033
   330
fun filter_criterion ctxt opt_goal (b, c) =
kleing@28900
   331
  (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
kleing@16895
   332
krauss@41844
   333
fun sorted_filter filters theorems =
kleing@16895
   334
  let
krauss@41844
   335
    fun eval_filters theorem = app_filters theorem (SOME (0, 0), NONE, filters);
wenzelm@16033
   336
kleing@16895
   337
    (*filters return: (number of assumptions, substitution size) option, so
kleing@16964
   338
      sort (desc. in both cases) according to number of assumptions first,
kleing@16895
   339
      then by the substitution size*)
krauss@41844
   340
    fun result_ord (((p0, s0), _), ((p1, s1), _)) =
wenzelm@17205
   341
      prod_ord int_ord int_ord ((p1, s1), (p0, s0));
krauss@41844
   342
  in map_filter eval_filters theorems |> sort result_ord |> map #2 end;
wenzelm@16033
   343
wenzelm@30822
   344
fun lazy_filter filters =
wenzelm@30822
   345
  let
Timothy@30785
   346
    fun lazy_match thms = Seq.make (fn () => first_match thms)
Timothy@30785
   347
Timothy@30785
   348
    and first_match [] = NONE
wenzelm@30822
   349
      | first_match (thm :: thms) =
wenzelm@30822
   350
          (case app_filters thm (SOME (0, 0), NONE, filters) of
Timothy@30785
   351
            NONE => first_match thms
wenzelm@30822
   352
          | SOME (_, t) => SOME (t, lazy_match thms));
Timothy@30785
   353
  in lazy_match end;
wenzelm@30822
   354
wenzelm@16036
   355
end;
wenzelm@16036
   356
wenzelm@16033
   357
kleing@22414
   358
(* removing duplicates, preferring nicer names, roughly n log n *)
kleing@22340
   359
wenzelm@25226
   360
local
wenzelm@25226
   361
huffman@27486
   362
val index_ord = option_ord (K EQUAL);
wenzelm@33095
   363
val hidden_ord = bool_ord o pairself Name_Space.is_hidden;
wenzelm@30364
   364
val qual_ord = int_ord o pairself (length o Long_Name.explode);
wenzelm@25226
   365
val txt_ord = int_ord o pairself size;
wenzelm@25226
   366
huffman@27486
   367
fun nicer_name (x, i) (y, j) =
huffman@27486
   368
  (case hidden_ord (x, y) of EQUAL =>
huffman@27486
   369
    (case index_ord (i, j) of EQUAL =>
huffman@27486
   370
      (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
huffman@27486
   371
    | ord => ord)
wenzelm@25226
   372
  | ord => ord) <> GREATER;
wenzelm@25226
   373
Timothy@29848
   374
fun rem_cdups nicer xs =
wenzelm@26336
   375
  let
wenzelm@26336
   376
    fun rem_c rev_seen [] = rev rev_seen
wenzelm@26336
   377
      | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
krauss@41844
   378
      | rem_c rev_seen ((x as (t, _)) :: (y as (t', _)) :: xs) =
krauss@41844
   379
          if (prop_of t) aconv (prop_of t')
krauss@41844
   380
          then rem_c rev_seen ((if nicer (fact_ref_of t) (fact_ref_of t') then x else y) :: xs)
wenzelm@30822
   381
          else rem_c (x :: rev_seen) (y :: xs)
wenzelm@26336
   382
  in rem_c [] xs end;
wenzelm@25226
   383
wenzelm@26336
   384
in
wenzelm@25226
   385
wenzelm@30143
   386
fun nicer_shortest ctxt =
wenzelm@30143
   387
  let
wenzelm@30216
   388
    (* FIXME global name space!? *)
wenzelm@42360
   389
    val space = Facts.space_of (Global_Theory.facts_of (Proof_Context.theory_of ctxt));
Timothy@29848
   390
wenzelm@30216
   391
    val shorten =
wenzelm@42358
   392
      Name_Space.extern
wenzelm@42358
   393
        (ctxt
wenzelm@42669
   394
          |> Config.put Name_Space.names_long false
wenzelm@42669
   395
          |> Config.put Name_Space.names_short false
wenzelm@42669
   396
          |> Config.put Name_Space.names_unique false) space;
Timothy@29848
   397
Timothy@29848
   398
    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
Timothy@29848
   399
          nicer_name (shorten x, i) (shorten y, j)
Timothy@29848
   400
      | nicer (Facts.Fact _) (Facts.Named _) = true
Timothy@29848
   401
      | nicer (Facts.Named _) (Facts.Fact _) = false;
Timothy@29848
   402
  in nicer end;
Timothy@29848
   403
Timothy@29848
   404
fun rem_thm_dups nicer xs =
wenzelm@26336
   405
  xs ~~ (1 upto length xs)
krauss@41844
   406
  |> sort (Term_Ord.fast_term_ord o pairself (prop_of o #1))
Timothy@29848
   407
  |> rem_cdups nicer
wenzelm@26336
   408
  |> sort (int_ord o pairself #2)
wenzelm@26336
   409
  |> map #1;
kleing@22340
   410
wenzelm@26336
   411
end;
kleing@22340
   412
kleing@22340
   413
wenzelm@16033
   414
(* print_theorems *)
wenzelm@16033
   415
wenzelm@26283
   416
fun all_facts_of ctxt =
krauss@33381
   417
  let
wenzelm@33382
   418
    fun visible_facts facts =
wenzelm@33382
   419
      Facts.dest_static [] facts
wenzelm@33382
   420
      |> filter_out (Facts.is_concealed facts o #1);
krauss@33381
   421
  in
krauss@33381
   422
    maps Facts.selections
wenzelm@42360
   423
     (visible_facts (Global_Theory.facts_of (Proof_Context.theory_of ctxt)) @
krauss@41844
   424
krauss@41844
   425
wenzelm@42360
   426
      visible_facts (Proof_Context.facts_of ctxt))
krauss@33381
   427
  end;
wenzelm@17972
   428
wenzelm@32738
   429
val limit = Unsynchronized.ref 40;
wenzelm@25992
   430
krauss@43067
   431
fun filter_theorems ctxt theorems opt_goal opt_limit rem_dups criteria =
wenzelm@16033
   432
  let
wenzelm@30822
   433
    val assms =
wenzelm@42360
   434
      Proof_Context.get_fact ctxt (Facts.named "local.assms")
wenzelm@30822
   435
        handle ERROR _ => [];
wenzelm@30822
   436
    val add_prems = Seq.hd o TRY (Method.insert_tac assms 1);
kleing@29857
   437
    val opt_goal' = Option.map add_prems opt_goal;
kleing@29857
   438
kleing@29857
   439
    val filters = map (filter_criterion ctxt opt_goal') criteria;
wenzelm@16033
   440
krauss@41844
   441
    fun find_all theorems =
Timothy@30785
   442
      let
krauss@41844
   443
        val raw_matches = sorted_filter filters theorems;
Timothy@30785
   444
Timothy@30785
   445
        val matches =
Timothy@30785
   446
          if rem_dups
Timothy@30785
   447
          then rem_thm_dups (nicer_shortest ctxt) raw_matches
Timothy@30785
   448
          else raw_matches;
kleing@28900
   449
Timothy@30785
   450
        val len = length matches;
Timothy@30785
   451
        val lim = the_default (! limit) opt_limit;
haftmann@34088
   452
      in (SOME len, drop (Int.max (len - lim, 0)) matches) end;
Timothy@30785
   453
Timothy@30785
   454
    val find =
Timothy@30785
   455
      if rem_dups orelse is_none opt_limit
Timothy@30785
   456
      then find_all
wenzelm@30822
   457
      else pair NONE o Seq.list_of o Seq.take (the opt_limit) o lazy_filter filters;
Timothy@30785
   458
krauss@41844
   459
  in find theorems end;
kleing@29857
   460
krauss@43067
   461
fun filter_theorems_cmd ctxt theorems opt_goal opt_limit rem_dups raw_criteria =
krauss@43067
   462
  filter_theorems ctxt theorems opt_goal opt_limit rem_dups
krauss@43067
   463
    (map (apsnd (read_criterion ctxt)) raw_criteria);
krauss@43067
   464
krauss@43067
   465
fun gen_find_theorems filter ctxt opt_goal opt_limit rem_dups raw_criteria =
krauss@43067
   466
  filter ctxt (map Internal (all_facts_of ctxt)) opt_goal opt_limit
krauss@41844
   467
     rem_dups raw_criteria
krauss@41844
   468
  |> apsnd (map (fn Internal f => f));
wenzelm@30186
   469
krauss@43067
   470
val find_theorems = gen_find_theorems filter_theorems;
krauss@43067
   471
val find_theorems_cmd = gen_find_theorems filter_theorems_cmd;
krauss@43067
   472
krauss@41845
   473
fun pretty_theorem ctxt (Internal (thmref, thm)) = Pretty.block
krauss@41845
   474
      [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
krauss@41845
   475
        Display.pretty_thm ctxt thm]
krauss@41845
   476
  | pretty_theorem ctxt (External (thmref, prop)) = Pretty.block
krauss@41845
   477
      [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
krauss@41845
   478
        Syntax.unparse_term ctxt prop];
wenzelm@30186
   479
krauss@41845
   480
fun pretty_thm ctxt (thmref, thm) = pretty_theorem ctxt (Internal (thmref, thm));
krauss@41845
   481
krauss@41845
   482
fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria =
wenzelm@30143
   483
  let
wenzelm@42012
   484
    val start = Timing.start ();
kleing@29857
   485
kleing@29857
   486
    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
krauss@41845
   487
    val (foundo, theorems) = filter_theorems ctxt (map Internal (all_facts_of ctxt))
krauss@43067
   488
      opt_goal opt_limit rem_dups criteria;
krauss@41845
   489
    val returned = length theorems;
wenzelm@31684
   490
Timothy@30785
   491
    val tally_msg =
wenzelm@30822
   492
      (case foundo of
wenzelm@38335
   493
        NONE => "displaying " ^ string_of_int returned ^ " theorem(s)"
wenzelm@30822
   494
      | SOME found =>
wenzelm@38335
   495
          "found " ^ string_of_int found ^ " theorem(s)" ^
wenzelm@30822
   496
            (if returned < found
wenzelm@30822
   497
             then " (" ^ string_of_int returned ^ " displayed)"
wenzelm@30822
   498
             else ""));
wenzelm@16033
   499
wenzelm@42012
   500
    val end_msg = " in " ^ Time.toString (#cpu (Timing.result start)) ^ " secs";
wenzelm@16033
   501
  in
wenzelm@38335
   502
    Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria) ::
wenzelm@38335
   503
    Pretty.str "" ::
krauss@41845
   504
    (if null theorems then [Pretty.str ("nothing found" ^ end_msg)]
wenzelm@38335
   505
     else
wenzelm@38335
   506
      [Pretty.str (tally_msg ^ end_msg ^ ":"), Pretty.str ""] @
krauss@41845
   507
        map (pretty_theorem ctxt) theorems)
wenzelm@38335
   508
  end |> Pretty.chunks |> Pretty.writeln;
wenzelm@30142
   509
wenzelm@30142
   510
wenzelm@32798
   511
wenzelm@30142
   512
(** command syntax **)
wenzelm@30142
   513
wenzelm@30142
   514
local
wenzelm@30142
   515
wenzelm@30142
   516
val criterion =
wenzelm@36950
   517
  Parse.reserved "name" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.xname) >> Name ||
wenzelm@36950
   518
  Parse.reserved "intro" >> K Intro ||
wenzelm@36950
   519
  Parse.reserved "introiff" >> K IntroIff ||
wenzelm@36950
   520
  Parse.reserved "elim" >> K Elim ||
wenzelm@36950
   521
  Parse.reserved "dest" >> K Dest ||
wenzelm@36950
   522
  Parse.reserved "solves" >> K Solves ||
wenzelm@36950
   523
  Parse.reserved "simp" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.term) >> Simp ||
wenzelm@36950
   524
  Parse.term >> Pattern;
wenzelm@30142
   525
wenzelm@30142
   526
val options =
wenzelm@30142
   527
  Scan.optional
wenzelm@36950
   528
    (Parse.$$$ "(" |--
wenzelm@36950
   529
      Parse.!!! (Scan.option Parse.nat -- Scan.optional (Parse.reserved "with_dups" >> K false) true
wenzelm@36950
   530
        --| Parse.$$$ ")")) (NONE, true);
wenzelm@30142
   531
in
wenzelm@30142
   532
wenzelm@30142
   533
val _ =
wenzelm@36953
   534
  Outer_Syntax.improper_command "find_theorems" "print theorems meeting specified criteria"
wenzelm@36950
   535
    Keyword.diag
wenzelm@36950
   536
    (options -- Scan.repeat (((Scan.option Parse.minus >> is_none) -- criterion))
wenzelm@38334
   537
      >> (fn ((opt_lim, rem_dups), spec) =>
wenzelm@38334
   538
        Toplevel.no_timing o
wenzelm@38334
   539
        Toplevel.keep (fn state =>
wenzelm@38334
   540
          let
wenzelm@38334
   541
            val ctxt = Toplevel.context_of state;
wenzelm@38334
   542
            val opt_goal = try (Proof.simple_goal o Toplevel.proof_of) state |> Option.map #goal;
krauss@41845
   543
          in print_theorems ctxt opt_goal opt_lim rem_dups spec end)));
wenzelm@16033
   544
wenzelm@16033
   545
end;
wenzelm@30142
   546
wenzelm@30142
   547
end;