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