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