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