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