src/Pure/Tools/find_theorems.ML
 author wenzelm Sun Mar 01 16:22:37 2009 +0100 (2009-03-01) changeset 30188 82144a95f9ec parent 30186 1f836e949ac2 child 30216 0300b7420b07 permissions -rw-r--r--
avoid fragile parsing of end_timing result -- would have produced GC time on MosML, for example;
```     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 | Elim | Dest | Solves | Simp of 'term |
```
```    11     Pattern of 'term
```
```    12   val tac_limit: int ref
```
```    13   val limit: int ref
```
```    14   val find_theorems: Proof.context -> thm option -> bool ->
```
```    15     (bool * string criterion) list -> (Facts.ref * thm) list
```
```    16   val pretty_thm: Proof.context -> Facts.ref * thm -> Pretty.T
```
```    17   val print_theorems: Proof.context -> thm option -> int option -> bool ->
```
```    18     (bool * string criterion) list -> unit
```
```    19 end;
```
```    20
```
```    21 structure FindTheorems: FIND_THEOREMS =
```
```    22 struct
```
```    23
```
```    24 (** search criteria **)
```
```    25
```
```    26 datatype 'term criterion =
```
```    27   Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
```
```    28   Pattern of 'term;
```
```    29
```
```    30 fun read_criterion _ (Name name) = Name name
```
```    31   | read_criterion _ Intro = Intro
```
```    32   | read_criterion _ Elim = Elim
```
```    33   | read_criterion _ Dest = Dest
```
```    34   | read_criterion _ Solves = Solves
```
```    35   | read_criterion ctxt (Simp str) = Simp (ProofContext.read_term_pattern ctxt str)
```
```    36   | read_criterion ctxt (Pattern str) = Pattern (ProofContext.read_term_pattern ctxt str);
```
```    37
```
```    38 fun pretty_criterion ctxt (b, c) =
```
```    39   let
```
```    40     fun prfx s = if b then s else "-" ^ s;
```
```    41   in
```
```    42     (case c of
```
```    43       Name name => Pretty.str (prfx "name: " ^ quote name)
```
```    44     | Intro => Pretty.str (prfx "intro")
```
```    45     | Elim => Pretty.str (prfx "elim")
```
```    46     | Dest => Pretty.str (prfx "dest")
```
```    47     | Solves => Pretty.str (prfx "solves")
```
```    48     | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
```
```    49         Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
```
```    50     | Pattern pat => Pretty.enclose (prfx " \"") "\""
```
```    51         [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
```
```    52   end;
```
```    53
```
```    54
```
```    55
```
```    56 (** search criterion filters **)
```
```    57
```
```    58 (*generated filters are to be of the form
```
```    59   input: (Facts.ref * thm)
```
```    60   output: (p:int, s:int) option, where
```
```    61     NONE indicates no match
```
```    62     p is the primary sorting criterion
```
```    63       (eg. number of assumptions in the theorem)
```
```    64     s is the secondary sorting criterion
```
```    65       (eg. size of the substitution for intro, elim and dest)
```
```    66   when applying a set of filters to a thm, fold results in:
```
```    67     (biggest p, sum of all s)
```
```    68   currently p and s only matter for intro, elim, dest and simp filters,
```
```    69   otherwise the default ordering is used.
```
```    70 *)
```
```    71
```
```    72
```
```    73 (* matching theorems *)
```
```    74
```
```    75 fun is_nontrivial thy = Term.is_Const o Term.head_of o ObjectLogic.drop_judgment thy;
```
```    76
```
```    77 (*extract terms from term_src, refine them to the parts that concern us,
```
```    78   if po try match them against obj else vice versa.
```
```    79   trivial matches are ignored.
```
```    80   returns: smallest substitution size*)
```
```    81 fun is_matching_thm (extract_terms, refine_term) ctxt po obj term_src =
```
```    82   let
```
```    83     val thy = ProofContext.theory_of ctxt;
```
```    84
```
```    85     fun matches pat =
```
```    86       is_nontrivial thy pat andalso
```
```    87       Pattern.matches thy (if po then (pat, obj) else (obj, pat));
```
```    88
```
```    89     fun substsize pat =
```
```    90       let val (_, subst) =
```
```    91         Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
```
```    92       in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
```
```    93
```
```    94     fun bestmatch [] = NONE
```
```    95      |  bestmatch xs = SOME (foldr1 Int.min xs);
```
```    96
```
```    97     val match_thm = matches o refine_term;
```
```    98   in
```
```    99     map (substsize o refine_term) (filter match_thm (extract_terms term_src))
```
```   100     |> bestmatch
```
```   101   end;
```
```   102
```
```   103
```
```   104 (* filter_name *)
```
```   105
```
```   106 fun filter_name str_pat (thmref, _) =
```
```   107   if match_string str_pat (Facts.name_of_ref thmref)
```
```   108   then SOME (0, 0) else NONE;
```
```   109
```
```   110
```
```   111 (* filter intro/elim/dest/solves rules *)
```
```   112
```
```   113 fun filter_dest ctxt goal (_, thm) =
```
```   114   let
```
```   115     val extract_dest =
```
```   116      (fn thm => if Thm.no_prems thm then [] else [Thm.full_prop_of thm],
```
```   117       hd o Logic.strip_imp_prems);
```
```   118     val prems = Logic.prems_of_goal goal 1;
```
```   119
```
```   120     fun try_subst prem = is_matching_thm extract_dest ctxt true prem thm;
```
```   121     val successful = prems |> map_filter try_subst;
```
```   122   in
```
```   123     (*if possible, keep best substitution (one with smallest size)*)
```
```   124     (*dest rules always have assumptions, so a dest with one
```
```   125       assumption is as good as an intro rule with none*)
```
```   126     if not (null successful)
```
```   127     then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
```
```   128   end;
```
```   129
```
```   130 fun filter_intro ctxt goal (_, thm) =
```
```   131   let
```
```   132     val extract_intro = (single o Thm.full_prop_of, Logic.strip_imp_concl);
```
```   133     val concl = Logic.concl_of_goal goal 1;
```
```   134     val ss = is_matching_thm extract_intro ctxt true concl thm;
```
```   135   in
```
```   136     if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
```
```   137   end;
```
```   138
```
```   139 fun filter_elim ctxt goal (_, thm) =
```
```   140   if not (Thm.no_prems thm) then
```
```   141     let
```
```   142       val rule = Thm.full_prop_of thm;
```
```   143       val prems = Logic.prems_of_goal goal 1;
```
```   144       val goal_concl = Logic.concl_of_goal goal 1;
```
```   145       val rule_mp = hd (Logic.strip_imp_prems rule);
```
```   146       val rule_concl = Logic.strip_imp_concl rule;
```
```   147       fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) \$ (t1 \$ t2);
```
```   148       val rule_tree = combine rule_mp rule_concl;
```
```   149       fun goal_tree prem = combine prem goal_concl;
```
```   150       fun try_subst prem =
```
```   151         is_matching_thm (single, I) ctxt true (goal_tree prem) rule_tree;
```
```   152       val successful = prems |> map_filter try_subst;
```
```   153     in
```
```   154     (*elim rules always have assumptions, so an elim with one
```
```   155       assumption is as good as an intro rule with none*)
```
```   156       if is_nontrivial (ProofContext.theory_of ctxt) (Thm.major_prem_of thm)
```
```   157         andalso not (null successful)
```
```   158       then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
```
```   159     end
```
```   160   else NONE
```
```   161
```
```   162 val tac_limit = ref 5;
```
```   163
```
```   164 fun filter_solves ctxt goal =
```
```   165   let
```
```   166     val baregoal = Logic.get_goal (Thm.prop_of goal) 1;
```
```   167
```
```   168     fun etacn thm i = Seq.take (! tac_limit) o etac thm i;
```
```   169     fun try_thm thm =
```
```   170       if Thm.no_prems thm then rtac thm 1 goal
```
```   171       else (etacn thm THEN_ALL_NEW
```
```   172              (Goal.norm_hhf_tac THEN'
```
```   173                Method.assumption_tac ctxt)) 1 goal;
```
```   174   in
```
```   175     fn (_, thm) =>
```
```   176       if (is_some o Seq.pull o try_thm) thm
```
```   177       then SOME (Thm.nprems_of thm, 0) else NONE
```
```   178   end;
```
```   179
```
```   180
```
```   181 (* filter_simp *)
```
```   182
```
```   183 fun filter_simp ctxt t (_, thm) =
```
```   184   let
```
```   185     val (_, {mk_rews = {mk, ...}, ...}) =
```
```   186       Simplifier.rep_ss (Simplifier.local_simpset_of ctxt);
```
```   187     val extract_simp =
```
```   188       (map Thm.full_prop_of o mk, #1 o Logic.dest_equals o Logic.strip_imp_concl);
```
```   189     val ss = is_matching_thm extract_simp ctxt false t thm
```
```   190   in
```
```   191     if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
```
```   192   end;
```
```   193
```
```   194
```
```   195 (* filter_pattern *)
```
```   196
```
```   197 fun get_names t = (Term.add_const_names t []) union (Term.add_free_names t []);
```
```   198 fun get_thm_names (_, thm) = get_names (Thm.full_prop_of thm);
```
```   199
```
```   200 (*Including all constants and frees is only sound because
```
```   201   matching uses higher-order patterns. If full matching
```
```   202   were used, then constants that may be subject to
```
```   203   beta-reduction after substitution of frees should
```
```   204   not be included for LHS set because they could be
```
```   205   thrown away by the substituted function.
```
```   206   e.g. for (?F 1 2) do not include 1 or 2, if it were
```
```   207        possible for ?F to be (% x y. 3)
```
```   208   The largest possible set should always be included on
```
```   209   the RHS.*)
```
```   210
```
```   211 fun filter_pattern ctxt pat =
```
```   212   let
```
```   213     val pat_consts = get_names pat;
```
```   214
```
```   215     fun check (t, NONE) = check (t, SOME (get_thm_names t))
```
```   216       | check ((_, thm), c as SOME thm_consts) =
```
```   217           (if pat_consts subset_string thm_consts
```
```   218               andalso (Pattern.matches_subterm (ProofContext.theory_of ctxt)
```
```   219                                                (pat, Thm.full_prop_of thm))
```
```   220            then SOME (0, 0) else NONE, c);
```
```   221   in check end;
```
```   222
```
```   223
```
```   224 (* interpret criteria as filters *)
```
```   225
```
```   226 local
```
```   227
```
```   228 fun err_no_goal c =
```
```   229   error ("Current goal required for " ^ c ^ " search criterion");
```
```   230
```
```   231 val fix_goal = Thm.prop_of;
```
```   232 val fix_goalo = Option.map fix_goal;
```
```   233
```
```   234 fun filter_crit _ _ (Name name) = apfst (filter_name name)
```
```   235   | filter_crit _ NONE Intro = err_no_goal "intro"
```
```   236   | filter_crit _ NONE Elim = err_no_goal "elim"
```
```   237   | filter_crit _ NONE Dest = err_no_goal "dest"
```
```   238   | filter_crit _ NONE Solves = err_no_goal "solves"
```
```   239   | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt (fix_goal goal))
```
```   240   | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (fix_goal goal))
```
```   241   | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (fix_goal goal))
```
```   242   | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
```
```   243   | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
```
```   244   | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
```
```   245
```
```   246 fun opt_not x = if is_some x then NONE else SOME (0, 0);
```
```   247
```
```   248 fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
```
```   249   | opt_add _ _ = NONE;
```
```   250
```
```   251 fun app_filters thm =
```
```   252   let
```
```   253     fun app (NONE, _, _) = NONE
```
```   254       | app (SOME v, consts, []) = SOME (v, thm)
```
```   255       | app (r, consts, f :: fs) =
```
```   256           let val (r', consts') = f (thm, consts)
```
```   257           in app (opt_add r r', consts', fs) end;
```
```   258   in app end;
```
```   259
```
```   260 in
```
```   261
```
```   262 fun filter_criterion ctxt opt_goal (b, c) =
```
```   263   (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
```
```   264
```
```   265 fun all_filters filters thms =
```
```   266   let
```
```   267     fun eval_filters thm = app_filters thm (SOME (0, 0), NONE, filters);
```
```   268
```
```   269     (*filters return: (number of assumptions, substitution size) option, so
```
```   270       sort (desc. in both cases) according to number of assumptions first,
```
```   271       then by the substitution size*)
```
```   272     fun thm_ord (((p0, s0), _), ((p1, s1), _)) =
```
```   273       prod_ord int_ord int_ord ((p1, s1), (p0, s0));
```
```   274   in map_filter eval_filters thms |> sort thm_ord |> map #2 end;
```
```   275
```
```   276 end;
```
```   277
```
```   278
```
```   279 (* removing duplicates, preferring nicer names, roughly n log n *)
```
```   280
```
```   281 local
```
```   282
```
```   283 val index_ord = option_ord (K EQUAL);
```
```   284 val hidden_ord = bool_ord o pairself NameSpace.is_hidden;
```
```   285 val qual_ord = int_ord o pairself (length o NameSpace.explode);
```
```   286 val txt_ord = int_ord o pairself size;
```
```   287
```
```   288 fun nicer_name (x, i) (y, j) =
```
```   289   (case hidden_ord (x, y) of EQUAL =>
```
```   290     (case index_ord (i, j) of EQUAL =>
```
```   291       (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
```
```   292     | ord => ord)
```
```   293   | ord => ord) <> GREATER;
```
```   294
```
```   295 fun rem_cdups nicer xs =
```
```   296   let
```
```   297     fun rem_c rev_seen [] = rev rev_seen
```
```   298       | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
```
```   299       | rem_c rev_seen ((x as ((n, t), _)) :: (y as ((n', t'), _)) :: xs) =
```
```   300         if Thm.eq_thm_prop (t, t')
```
```   301         then rem_c rev_seen ((if nicer n n' then x else y) :: xs)
```
```   302         else rem_c (x :: rev_seen) (y :: xs)
```
```   303   in rem_c [] xs end;
```
```   304
```
```   305 in
```
```   306
```
```   307 fun nicer_shortest ctxt =
```
```   308   let
```
```   309     val ns = ProofContext.theory_of ctxt
```
```   310              |> PureThy.facts_of
```
```   311              |> Facts.space_of;
```
```   312
```
```   313     val len_sort = sort (int_ord o (pairself size));
```
```   314     fun shorten s = (case len_sort (NameSpace.get_accesses ns s) of
```
```   315                        [] => s
```
```   316                      | s'::_ => s');
```
```   317
```
```   318     fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
```
```   319           nicer_name (shorten x, i) (shorten y, j)
```
```   320       | nicer (Facts.Fact _) (Facts.Named _) = true
```
```   321       | nicer (Facts.Named _) (Facts.Fact _) = false;
```
```   322   in nicer end;
```
```   323
```
```   324 fun rem_thm_dups nicer xs =
```
```   325   xs ~~ (1 upto length xs)
```
```   326   |> sort (TermOrd.fast_term_ord o pairself (Thm.prop_of o #2 o #1))
```
```   327   |> rem_cdups nicer
```
```   328   |> sort (int_ord o pairself #2)
```
```   329   |> map #1;
```
```   330
```
```   331 end;
```
```   332
```
```   333
```
```   334 (* print_theorems *)
```
```   335
```
```   336 fun all_facts_of ctxt =
```
```   337   maps Facts.selections
```
```   338    (Facts.dest_static [] (PureThy.facts_of (ProofContext.theory_of ctxt)) @
```
```   339     Facts.dest_static [] (ProofContext.facts_of ctxt));
```
```   340
```
```   341 val limit = ref 40;
```
```   342
```
```   343 fun find_theorems ctxt opt_goal rem_dups raw_criteria =
```
```   344   let
```
```   345     val add_prems = Seq.hd o (TRY (Method.insert_tac (Assumption.prems_of ctxt) 1));
```
```   346     val opt_goal' = Option.map add_prems opt_goal;
```
```   347
```
```   348     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
```
```   349     val filters = map (filter_criterion ctxt opt_goal') criteria;
```
```   350
```
```   351     val raw_matches = all_filters filters (all_facts_of ctxt);
```
```   352
```
```   353     val matches =
```
```   354       if rem_dups
```
```   355       then rem_thm_dups (nicer_shortest ctxt) raw_matches
```
```   356       else raw_matches;
```
```   357   in matches end;
```
```   358
```
```   359
```
```   360 fun pretty_thm ctxt (thmref, thm) = Pretty.block
```
```   361   [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
```
```   362     ProofContext.pretty_thm ctxt thm];
```
```   363
```
```   364 fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria =
```
```   365   let
```
```   366     val start = start_timing ();
```
```   367
```
```   368     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
```
```   369     val matches = find_theorems ctxt opt_goal rem_dups raw_criteria;
```
```   370
```
```   371     val len = length matches;
```
```   372     val lim = the_default (! limit) opt_limit;
```
```   373     val thms = Library.drop (len - lim, matches);
```
```   374
```
```   375     val end_msg = " in " ^ Time.toString (#all (end_timing start)) ^ " secs";
```
```   376   in
```
```   377     Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria)
```
```   378         :: Pretty.str "" ::
```
```   379      (if null thms then [Pretty.str ("nothing found" ^ end_msg)]
```
```   380       else
```
```   381         [Pretty.str ("found " ^ string_of_int len ^ " theorems" ^
```
```   382           (if len <= lim then ""
```
```   383            else " (" ^ string_of_int lim ^ " displayed)")
```
```   384            ^ end_msg ^ ":"), Pretty.str ""] @
```
```   385         map (pretty_thm ctxt) thms)
```
```   386     |> Pretty.chunks |> Pretty.writeln
```
```   387   end;
```
```   388
```
```   389
```
```   390
```
```   391 (** command syntax **)
```
```   392
```
```   393 fun find_theorems_cmd ((opt_lim, rem_dups), spec) =
```
```   394   Toplevel.unknown_theory o Toplevel.keep (fn state =>
```
```   395   let
```
```   396     val proof_state = Toplevel.enter_proof_body state;
```
```   397     val ctxt = Proof.context_of proof_state;
```
```   398     val opt_goal = try Proof.get_goal proof_state |> Option.map (#2 o #2);
```
```   399   in print_theorems ctxt opt_goal opt_lim rem_dups spec end);
```
```   400
```
```   401 local
```
```   402
```
```   403 structure P = OuterParse and K = OuterKeyword;
```
```   404
```
```   405 val criterion =
```
```   406   P.reserved "name" |-- P.!!! (P.\$\$\$ ":" |-- P.xname) >> Name ||
```
```   407   P.reserved "intro" >> K Intro ||
```
```   408   P.reserved "elim" >> K Elim ||
```
```   409   P.reserved "dest" >> K Dest ||
```
```   410   P.reserved "solves" >> K Solves ||
```
```   411   P.reserved "simp" |-- P.!!! (P.\$\$\$ ":" |-- P.term) >> Simp ||
```
```   412   P.term >> Pattern;
```
```   413
```
```   414 val options =
```
```   415   Scan.optional
```
```   416     (P.\$\$\$ "(" |--
```
```   417       P.!!! (Scan.option P.nat -- Scan.optional (P.reserved "with_dups" >> K false) true
```
```   418         --| P.\$\$\$ ")")) (NONE, true);
```
```   419 in
```
```   420
```
```   421 val _ =
```
```   422   OuterSyntax.improper_command "find_theorems" "print theorems meeting specified criteria" K.diag
```
```   423     (options -- Scan.repeat (((Scan.option P.minus >> is_none) -- criterion))
```
```   424       >> (Toplevel.no_timing oo find_theorems_cmd));
```
```   425
```
```   426 end;
```
```   427
```
```   428 end;
```