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