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