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