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