src/Pure/Tools/find_theorems.ML
 author wenzelm Thu Jul 18 22:32:00 2013 +0200 (2013-07-18) changeset 52703 d68fd63bf082 parent 52702 c503730efae5 child 52704 b824497c8e86 permissions -rw-r--r--
tuned messages -- avoid text folds stemming from Pretty.chunks;
```     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     fun etacn thm i =
```
```   317       Seq.take (Options.default_int @{option find_theorems_tac_limit}) o etac thm i;
```
```   318     fun try_thm thm =
```
```   319       if Thm.no_prems thm then rtac thm 1 goal
```
```   320       else (etacn thm THEN_ALL_NEW (Goal.norm_hhf_tac THEN' Method.assm_tac ctxt)) 1 goal;
```
```   321   in
```
```   322     fn Internal (_, thm) =>
```
```   323         if is_some (Seq.pull (try_thm thm))
```
```   324         then SOME (Thm.nprems_of thm, 0) else NONE
```
```   325      | External _ => NONE
```
```   326   end;
```
```   327
```
```   328
```
```   329 (* filter_simp *)
```
```   330
```
```   331 fun filter_simp ctxt t (Internal (_, thm)) =
```
```   332       let
```
```   333         val mksimps = Simplifier.mksimps ctxt;
```
```   334         val extract_simp =
```
```   335           (map Thm.full_prop_of o mksimps, #1 o Logic.dest_equals o Logic.strip_imp_concl);
```
```   336         val ss = is_matching_thm extract_simp ctxt false t thm;
```
```   337       in
```
```   338         if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
```
```   339       end
```
```   340   | filter_simp _ _ (External _) = NONE;
```
```   341
```
```   342
```
```   343 (* filter_pattern *)
```
```   344
```
```   345 fun get_names t = Term.add_const_names t (Term.add_free_names t []);
```
```   346
```
```   347 (*Including all constants and frees is only sound because
```
```   348   matching uses higher-order patterns. If full matching
```
```   349   were used, then constants that may be subject to
```
```   350   beta-reduction after substitution of frees should
```
```   351   not be included for LHS set because they could be
```
```   352   thrown away by the substituted function.
```
```   353   e.g. for (?F 1 2) do not include 1 or 2, if it were
```
```   354        possible for ?F to be (% x y. 3)
```
```   355   The largest possible set should always be included on
```
```   356   the RHS.*)
```
```   357
```
```   358 fun filter_pattern ctxt pat =
```
```   359   let
```
```   360     val pat_consts = get_names pat;
```
```   361
```
```   362     fun check (theorem, NONE) = check (theorem, SOME (get_names (prop_of theorem)))
```
```   363       | check (theorem, c as SOME thm_consts) =
```
```   364          (if subset (op =) (pat_consts, thm_consts) andalso
```
```   365             Pattern.matches_subterm (Proof_Context.theory_of ctxt) (pat, prop_of theorem)
```
```   366           then SOME (0, 0) else NONE, c);
```
```   367   in check end;
```
```   368
```
```   369
```
```   370 (* interpret criteria as filters *)
```
```   371
```
```   372 local
```
```   373
```
```   374 fun err_no_goal c =
```
```   375   error ("Current goal required for " ^ c ^ " search criterion");
```
```   376
```
```   377 val fix_goal = Thm.prop_of;
```
```   378
```
```   379 fun filter_crit _ _ (Name name) = apfst (filter_name name)
```
```   380   | filter_crit _ NONE Intro = err_no_goal "intro"
```
```   381   | filter_crit _ NONE Elim = err_no_goal "elim"
```
```   382   | filter_crit _ NONE Dest = err_no_goal "dest"
```
```   383   | filter_crit _ NONE Solves = err_no_goal "solves"
```
```   384   | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt (fix_goal goal))
```
```   385   | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (fix_goal goal))
```
```   386   | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (fix_goal goal))
```
```   387   | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
```
```   388   | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
```
```   389   | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
```
```   390
```
```   391 fun opt_not x = if is_some x then NONE else SOME (0, 0);
```
```   392
```
```   393 fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
```
```   394   | opt_add _ _ = NONE;
```
```   395
```
```   396 fun app_filters thm =
```
```   397   let
```
```   398     fun app (NONE, _, _) = NONE
```
```   399       | app (SOME v, _, []) = SOME (v, thm)
```
```   400       | app (r, consts, f :: fs) =
```
```   401           let val (r', consts') = f (thm, consts)
```
```   402           in app (opt_add r r', consts', fs) end;
```
```   403   in app end;
```
```   404
```
```   405 in
```
```   406
```
```   407 fun filter_criterion ctxt opt_goal (b, c) =
```
```   408   (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
```
```   409
```
```   410 fun sorted_filter filters theorems =
```
```   411   let
```
```   412     fun eval_filters theorem = app_filters theorem (SOME (0, 0), NONE, filters);
```
```   413
```
```   414     (*filters return: (number of assumptions, substitution size) option, so
```
```   415       sort (desc. in both cases) according to number of assumptions first,
```
```   416       then by the substitution size*)
```
```   417     fun result_ord (((p0, s0), _), ((p1, s1), _)) =
```
```   418       prod_ord int_ord int_ord ((p1, s1), (p0, s0));
```
```   419   in
```
```   420     grouped 100 Par_List.map eval_filters theorems
```
```   421     |> map_filter I |> sort result_ord |> map #2
```
```   422   end;
```
```   423
```
```   424 fun lazy_filter filters =
```
```   425   let
```
```   426     fun lazy_match thms = Seq.make (fn () => first_match thms)
```
```   427     and first_match [] = NONE
```
```   428       | first_match (thm :: thms) =
```
```   429           (case app_filters thm (SOME (0, 0), NONE, filters) of
```
```   430             NONE => first_match thms
```
```   431           | SOME (_, t) => SOME (t, lazy_match thms));
```
```   432   in lazy_match end;
```
```   433
```
```   434 end;
```
```   435
```
```   436
```
```   437 (* removing duplicates, preferring nicer names, roughly n log n *)
```
```   438
```
```   439 local
```
```   440
```
```   441 val index_ord = option_ord (K EQUAL);
```
```   442 val hidden_ord = bool_ord o pairself Name_Space.is_hidden;
```
```   443 val qual_ord = int_ord o pairself (length o Long_Name.explode);
```
```   444 val txt_ord = int_ord o pairself size;
```
```   445
```
```   446 fun nicer_name (x, i) (y, j) =
```
```   447   (case hidden_ord (x, y) of EQUAL =>
```
```   448     (case index_ord (i, j) of EQUAL =>
```
```   449       (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
```
```   450     | ord => ord)
```
```   451   | ord => ord) <> GREATER;
```
```   452
```
```   453 fun rem_cdups nicer xs =
```
```   454   let
```
```   455     fun rem_c rev_seen [] = rev rev_seen
```
```   456       | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
```
```   457       | rem_c rev_seen ((x as (t, _)) :: (y as (t', _)) :: xs) =
```
```   458           if (prop_of t) aconv (prop_of t')
```
```   459           then rem_c rev_seen ((if nicer (fact_ref_of t) (fact_ref_of t') then x else y) :: xs)
```
```   460           else rem_c (x :: rev_seen) (y :: xs)
```
```   461   in rem_c [] xs end;
```
```   462
```
```   463 in
```
```   464
```
```   465 fun nicer_shortest ctxt =
```
```   466   let
```
```   467     (* FIXME Why global name space!?? *)
```
```   468     val space = Facts.space_of (Global_Theory.facts_of (Proof_Context.theory_of ctxt));
```
```   469
```
```   470     val shorten =
```
```   471       Name_Space.extern
```
```   472         (ctxt
```
```   473           |> Config.put Name_Space.names_long false
```
```   474           |> Config.put Name_Space.names_short false
```
```   475           |> Config.put Name_Space.names_unique false) space;
```
```   476
```
```   477     fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
```
```   478           nicer_name (shorten x, i) (shorten y, j)
```
```   479       | nicer (Facts.Fact _) (Facts.Named _) = true
```
```   480       | nicer (Facts.Named _) (Facts.Fact _) = false;
```
```   481   in nicer end;
```
```   482
```
```   483 fun rem_thm_dups nicer xs =
```
```   484   xs ~~ (1 upto length xs)
```
```   485   |> sort (Term_Ord.fast_term_ord o pairself (prop_of o #1))
```
```   486   |> rem_cdups nicer
```
```   487   |> sort (int_ord o pairself #2)
```
```   488   |> map #1;
```
```   489
```
```   490 end;
```
```   491
```
```   492
```
```   493 (* print_theorems *)
```
```   494
```
```   495 fun all_facts_of ctxt =
```
```   496   let
```
```   497     fun visible_facts facts =
```
```   498       Facts.dest_static [] facts
```
```   499       |> filter_out (Facts.is_concealed facts o #1);
```
```   500   in
```
```   501     maps Facts.selections
```
```   502      (visible_facts (Global_Theory.facts_of (Proof_Context.theory_of ctxt)) @
```
```   503       visible_facts (Proof_Context.facts_of ctxt))
```
```   504   end;
```
```   505
```
```   506 fun filter_theorems ctxt theorems query =
```
```   507   let
```
```   508     val {goal = opt_goal, limit = opt_limit, rem_dups, criteria} = query;
```
```   509     val filters = map (filter_criterion ctxt opt_goal) criteria;
```
```   510
```
```   511     fun find_all theorems =
```
```   512       let
```
```   513         val raw_matches = sorted_filter filters theorems;
```
```   514
```
```   515         val matches =
```
```   516           if rem_dups
```
```   517           then rem_thm_dups (nicer_shortest ctxt) raw_matches
```
```   518           else raw_matches;
```
```   519
```
```   520         val len = length matches;
```
```   521         val lim = the_default (Options.default_int @{option find_theorems_limit}) opt_limit;
```
```   522       in (SOME len, drop (Int.max (len - lim, 0)) matches) end;
```
```   523
```
```   524     val find =
```
```   525       if rem_dups orelse is_none opt_limit
```
```   526       then find_all
```
```   527       else pair NONE o Seq.list_of o Seq.take (the opt_limit) o lazy_filter filters;
```
```   528
```
```   529   in find theorems end;
```
```   530
```
```   531 fun filter_theorems_cmd ctxt theorems raw_query =
```
```   532   filter_theorems ctxt theorems (map_criteria
```
```   533     (map (apsnd (read_criterion ctxt))) raw_query);
```
```   534
```
```   535 fun gen_find_theorems filter ctxt opt_goal opt_limit rem_dups raw_criteria =
```
```   536   let
```
```   537     val assms =
```
```   538       Proof_Context.get_fact ctxt (Facts.named "local.assms")
```
```   539         handle ERROR _ => [];
```
```   540     val add_prems = Seq.hd o TRY (Method.insert_tac assms 1);
```
```   541     val opt_goal' = Option.map add_prems opt_goal;
```
```   542   in
```
```   543     filter ctxt (map Internal (all_facts_of ctxt))
```
```   544       {goal = opt_goal', limit = opt_limit, rem_dups = rem_dups, criteria = raw_criteria}
```
```   545     |> apsnd (map (fn Internal f => f))
```
```   546   end;
```
```   547
```
```   548 val find_theorems = gen_find_theorems filter_theorems;
```
```   549 val find_theorems_cmd = gen_find_theorems filter_theorems_cmd;
```
```   550
```
```   551 fun pretty_ref ctxt thmref =
```
```   552   let
```
```   553     val (name, sel) =
```
```   554       (case thmref of
```
```   555         Facts.Named ((name, _), sel) => (name, sel)
```
```   556       | Facts.Fact _ => raise Fail "Illegal literal fact");
```
```   557   in
```
```   558     [Pretty.mark (Proof_Context.markup_fact ctxt name) (Pretty.str name),
```
```   559       Pretty.str (Facts.string_of_selection sel), Pretty.str ":", Pretty.brk 1]
```
```   560   end;
```
```   561
```
```   562 fun pretty_theorem ctxt (Internal (thmref, thm)) =
```
```   563       Pretty.block (pretty_ref ctxt thmref @ [Display.pretty_thm ctxt thm])
```
```   564   | pretty_theorem ctxt (External (thmref, prop)) =
```
```   565       Pretty.block (pretty_ref ctxt thmref @ [Syntax.unparse_term ctxt prop]);
```
```   566
```
```   567 fun pretty_thm ctxt (thmref, thm) = pretty_theorem ctxt (Internal (thmref, thm));
```
```   568
```
```   569 fun gen_print_theorems find ctxt opt_goal opt_limit rem_dups raw_criteria =
```
```   570   let
```
```   571     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
```
```   572     val (foundo, theorems) = find
```
```   573       {goal = opt_goal, limit = opt_limit, rem_dups = rem_dups, criteria = criteria};
```
```   574     val returned = length theorems;
```
```   575
```
```   576     val tally_msg =
```
```   577       (case foundo of
```
```   578         NONE => "displaying " ^ string_of_int returned ^ " theorem(s)"
```
```   579       | SOME found =>
```
```   580           "found " ^ string_of_int found ^ " theorem(s)" ^
```
```   581             (if returned < found
```
```   582              then " (" ^ string_of_int returned ^ " displayed)"
```
```   583              else ""));
```
```   584   in
```
```   585     Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria) ::
```
```   586     Pretty.str "" ::
```
```   587     (if null theorems then [Pretty.str "nothing found"]
```
```   588      else
```
```   589       [Pretty.str (tally_msg ^ ":"), Pretty.str ""] @
```
```   590         grouped 10 Par_List.map (pretty_theorem ctxt) theorems)
```
```   591   end |> Pretty.fbreaks |> curry Pretty.blk 0 |> Pretty.writeln;
```
```   592
```
```   593 fun print_theorems ctxt =
```
```   594   gen_print_theorems (filter_theorems ctxt (map Internal (all_facts_of ctxt))) ctxt;
```
```   595
```
```   596
```
```   597
```
```   598 (** command syntax **)
```
```   599
```
```   600 local
```
```   601
```
```   602 val criterion =
```
```   603   Parse.reserved "name" |-- Parse.!!! (Parse.\$\$\$ ":" |-- Parse.xname) >> Name ||
```
```   604   Parse.reserved "intro" >> K Intro ||
```
```   605   Parse.reserved "elim" >> K Elim ||
```
```   606   Parse.reserved "dest" >> K Dest ||
```
```   607   Parse.reserved "solves" >> K Solves ||
```
```   608   Parse.reserved "simp" |-- Parse.!!! (Parse.\$\$\$ ":" |-- Parse.term) >> Simp ||
```
```   609   Parse.term >> Pattern;
```
```   610
```
```   611 val options =
```
```   612   Scan.optional
```
```   613     (Parse.\$\$\$ "(" |--
```
```   614       Parse.!!! (Scan.option Parse.nat -- Scan.optional (Parse.reserved "with_dups" >> K false) true
```
```   615         --| Parse.\$\$\$ ")")) (NONE, true);
```
```   616 in
```
```   617
```
```   618 val query_parser = Scan.repeat (((Scan.option Parse.minus >> is_none) -- criterion));
```
```   619
```
```   620 val _ =
```
```   621   Outer_Syntax.improper_command @{command_spec "find_theorems"}
```
```   622     "find theorems meeting specified criteria"
```
```   623     (options -- query_parser
```
```   624       >> (fn ((opt_lim, rem_dups), spec) =>
```
```   625         Toplevel.keep (fn state =>
```
```   626           let
```
```   627             val ctxt = Toplevel.context_of state;
```
```   628             val thy' =
```
```   629               Proof_Context.theory_of ctxt
```
```   630               |> Theory.copy
```
```   631               |> Context_Position.set_visible_global (Context_Position.is_visible ctxt)
```
```   632               |> Theory.checkpoint;
```
```   633
```
```   634             val opt_goal = try (Proof.simple_goal o Toplevel.proof_of) state |> Option.map #goal;
```
```   635             val (ctxt', opt_goal') =
```
```   636               (case opt_goal of
```
```   637                 NONE => (ctxt, NONE)
```
```   638               | SOME th => (Proof_Context.transfer thy' ctxt, SOME (Thm.transfer thy' th)));
```
```   639           in print_theorems ctxt' opt_goal' opt_lim rem_dups spec end)));
```
```   640
```
```   641 end;
```
```   642
```
```   643 end;
```