src/Pure/Tools/find_theorems.ML
author krauss
Fri Feb 25 16:57:43 2011 +0100 (2011-02-25)
changeset 41844 b933142e02d0
parent 41841 c27b0b37041a
child 41845 6611b9cef38b
permissions -rw-r--r--
generalize find_theorems filters to work on raw propositions, too
     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 |
    15     External of Facts.ref * term
    16 
    17   val tac_limit: int Unsynchronized.ref
    18   val limit: int Unsynchronized.ref
    19   val find_theorems: Proof.context -> thm option -> int option -> bool ->
    20     (bool * string criterion) list -> int option * (Facts.ref * thm) list
    21   val filter_theorems: Proof.context -> theorem list -> thm option ->
    22     int option -> bool -> (bool * string criterion) list ->
    23     int option * theorem list
    24 
    25   val pretty_thm: Proof.context -> Facts.ref * thm -> Pretty.T
    26 end;
    27 
    28 structure Find_Theorems: FIND_THEOREMS =
    29 struct
    30 
    31 (** search criteria **)
    32 
    33 datatype 'term criterion =
    34   Name of string | Intro | IntroIff | Elim | Dest | Solves | Simp of 'term |
    35   Pattern of 'term;
    36 
    37 fun apply_dummies tm =
    38   let
    39     val (xs, _) = Term.strip_abs tm;
    40     val tm' = Term.betapplys (tm, map (Term.dummy_pattern o #2) xs);
    41   in #1 (Term.replace_dummy_patterns tm' 1) end;
    42 
    43 fun parse_pattern ctxt nm =
    44   let
    45     val consts = ProofContext.consts_of ctxt;
    46     val nm' =
    47       (case Syntax.parse_term ctxt nm of
    48         Const (c, _) => c
    49       | _ => Consts.intern consts nm);
    50   in
    51     (case try (Consts.the_abbreviation consts) nm' of
    52       SOME (_, rhs) => apply_dummies (ProofContext.expand_abbrevs ctxt rhs)
    53     | NONE => ProofContext.read_term_pattern ctxt nm)
    54   end;
    55 
    56 fun read_criterion _ (Name name) = Name name
    57   | read_criterion _ Intro = Intro
    58   | read_criterion _ IntroIff = IntroIff
    59   | read_criterion _ Elim = Elim
    60   | read_criterion _ Dest = Dest
    61   | read_criterion _ Solves = Solves
    62   | read_criterion ctxt (Simp str) = Simp (ProofContext.read_term_pattern ctxt str)
    63   | read_criterion ctxt (Pattern str) = Pattern (parse_pattern ctxt str);
    64 
    65 fun pretty_criterion ctxt (b, c) =
    66   let
    67     fun prfx s = if b then s else "-" ^ s;
    68   in
    69     (case c of
    70       Name name => Pretty.str (prfx "name: " ^ quote name)
    71     | Intro => Pretty.str (prfx "intro")
    72     | IntroIff => Pretty.str (prfx "introiff")
    73     | Elim => Pretty.str (prfx "elim")
    74     | Dest => Pretty.str (prfx "dest")
    75     | Solves => Pretty.str (prfx "solves")
    76     | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
    77         Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
    78     | Pattern pat => Pretty.enclose (prfx " \"") "\""
    79         [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
    80   end;
    81 
    82 
    83 (** theorems, either internal or external (without proof) *)
    84 
    85 datatype theorem =
    86   Internal of Facts.ref * thm |
    87   External of Facts.ref * term;
    88 
    89 fun prop_of (Internal (_, thm)) = Thm.full_prop_of thm
    90   | prop_of (External (_, prop)) = prop;
    91 
    92 fun nprems_of (Internal (_, thm)) = Thm.nprems_of thm
    93   | nprems_of (External (_, prop)) = Logic.count_prems prop;
    94 
    95 fun major_prem_of (Internal (_, thm)) = Thm.major_prem_of thm
    96   | major_prem_of (External (_, prop)) =
    97       Logic.strip_assums_concl (hd (Logic.strip_imp_prems prop));
    98 
    99 fun fact_ref_of (Internal (fact_ref, _)) = fact_ref
   100   | fact_ref_of (External (fact_ref, _)) = fact_ref;
   101 
   102 (** search criterion filters **)
   103 
   104 (*generated filters are to be of the form
   105   input: theorem
   106   output: (p:int, s:int) option, where
   107     NONE indicates no match
   108     p is the primary sorting criterion
   109       (eg. number of assumptions in the theorem)
   110     s is the secondary sorting criterion
   111       (eg. size of the substitution for intro, elim and dest)
   112   when applying a set of filters to a thm, fold results in:
   113     (biggest p, sum of all s)
   114   currently p and s only matter for intro, elim, dest and simp filters,
   115   otherwise the default ordering is used.
   116 *)
   117 
   118 
   119 (* matching theorems *)
   120 
   121 fun is_nontrivial thy = Term.is_Const o Term.head_of o Object_Logic.drop_judgment thy;
   122 
   123 (*educated guesses on HOL*)  (* FIXME broken *)
   124 val boolT = Type ("bool", []);
   125 val iff_const = Const ("op =", boolT --> boolT --> boolT);
   126 
   127 (*extract terms from term_src, refine them to the parts that concern us,
   128   if po try match them against obj else vice versa.
   129   trivial matches are ignored.
   130   returns: smallest substitution size*)
   131 fun is_matching_thm doiff (extract_terms, refine_term) ctxt po obj term_src =
   132   let
   133     val thy = ProofContext.theory_of ctxt;
   134 
   135     fun check_match pat = Pattern.matches thy (if po then (pat, obj) else (obj, pat));
   136     fun matches pat =
   137       let
   138         val jpat = Object_Logic.drop_judgment thy pat;
   139         val c = Term.head_of jpat;
   140         val pats =
   141           if Term.is_Const c
   142           then
   143             if doiff andalso c = iff_const then
   144               (pat :: map (Object_Logic.ensure_propT thy) (snd (strip_comb jpat)))
   145                 |> filter (is_nontrivial thy)
   146             else [pat]
   147           else [];
   148       in filter check_match pats end;
   149 
   150     fun substsize pat =
   151       let val (_, subst) =
   152         Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
   153       in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
   154 
   155     fun bestmatch [] = NONE
   156       | bestmatch xs = SOME (foldl1 Int.min xs);
   157 
   158     val match_thm = matches o refine_term;
   159   in
   160     maps match_thm (extract_terms term_src)
   161     |> map substsize
   162     |> bestmatch
   163   end;
   164 
   165 
   166 (* filter_name *)
   167 
   168 fun filter_name str_pat theorem =
   169   if match_string str_pat (Facts.name_of_ref (fact_ref_of theorem))
   170   then SOME (0, 0) else NONE;
   171 
   172 
   173 (* filter intro/elim/dest/solves rules *)
   174 
   175 fun filter_dest ctxt goal theorem =
   176   let
   177     val extract_dest =
   178      (fn theorem => if nprems_of theorem = 0 then [] else [prop_of theorem],
   179       hd o Logic.strip_imp_prems);
   180     val prems = Logic.prems_of_goal goal 1;
   181 
   182     fun try_subst prem = is_matching_thm false extract_dest ctxt true prem theorem;
   183     val successful = prems |> map_filter try_subst;
   184   in
   185     (*if possible, keep best substitution (one with smallest size)*)
   186     (*dest rules always have assumptions, so a dest with one
   187       assumption is as good as an intro rule with none*)
   188     if not (null successful)
   189     then SOME (nprems_of theorem - 1, foldl1 Int.min successful) else NONE
   190   end;
   191 
   192 fun filter_intro doiff ctxt goal theorem =
   193   let
   194     val extract_intro = (single o prop_of, Logic.strip_imp_concl);
   195     val concl = Logic.concl_of_goal goal 1;
   196     val ss = is_matching_thm doiff extract_intro ctxt true concl theorem;
   197   in
   198     if is_some ss then SOME (nprems_of theorem, the ss) else NONE
   199   end;
   200 
   201 fun filter_elim ctxt goal theorem =
   202   if nprems_of theorem > 0 then
   203     let
   204       val rule = prop_of theorem;
   205       val prems = Logic.prems_of_goal goal 1;
   206       val goal_concl = Logic.concl_of_goal goal 1;
   207       val rule_mp = hd (Logic.strip_imp_prems rule);
   208       val rule_concl = Logic.strip_imp_concl rule;
   209       fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);
   210       val rule_tree = combine rule_mp rule_concl;
   211       fun goal_tree prem = combine prem goal_concl;
   212       fun try_subst prem =
   213         is_matching_thm false (single, I) ctxt true (goal_tree prem) rule_tree;
   214       val successful = prems |> map_filter try_subst;
   215     in
   216       (*elim rules always have assumptions, so an elim with one
   217         assumption is as good as an intro rule with none*)
   218       if is_nontrivial (ProofContext.theory_of ctxt) (major_prem_of theorem)
   219         andalso not (null successful)
   220       then SOME (nprems_of theorem - 1, foldl1 Int.min successful) else NONE
   221     end
   222   else NONE
   223 
   224 val tac_limit = Unsynchronized.ref 5;
   225 
   226 fun filter_solves ctxt goal =
   227   let
   228     fun etacn thm i = Seq.take (! tac_limit) o etac thm i;
   229     fun try_thm thm =
   230       if Thm.no_prems thm then rtac thm 1 goal
   231       else (etacn thm THEN_ALL_NEW (Goal.norm_hhf_tac THEN' Method.assm_tac ctxt)) 1 goal;
   232   in
   233     fn Internal (_, thm) =>
   234       if is_some (Seq.pull (try_thm thm))
   235       then SOME (Thm.nprems_of thm, 0) else NONE
   236      | External _ => NONE
   237   end;
   238 
   239 
   240 (* filter_simp *)
   241 
   242 fun filter_simp ctxt t (Internal (_, thm)) =
   243       let
   244         val mksimps = Simplifier.mksimps (simpset_of ctxt);
   245         val extract_simp =
   246           (map Thm.full_prop_of o mksimps, #1 o Logic.dest_equals o Logic.strip_imp_concl);
   247         val ss = is_matching_thm false extract_simp ctxt false t thm;
   248       in
   249         if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
   250       end
   251   | filter_simp _ _ (External _) = NONE;
   252 
   253 
   254 (* filter_pattern *)
   255 
   256 fun get_names t = Term.add_const_names t (Term.add_free_names t []);
   257 
   258 (*Including all constants and frees is only sound because
   259   matching uses higher-order patterns. If full matching
   260   were used, then constants that may be subject to
   261   beta-reduction after substitution of frees should
   262   not be included for LHS set because they could be
   263   thrown away by the substituted function.
   264   e.g. for (?F 1 2) do not include 1 or 2, if it were
   265        possible for ?F to be (% x y. 3)
   266   The largest possible set should always be included on
   267   the RHS.*)
   268 
   269 fun filter_pattern ctxt pat =
   270   let
   271     val pat_consts = get_names pat;
   272 
   273     fun check (theorem, NONE) = check (theorem, SOME (get_names (prop_of theorem)))
   274       | check (theorem, c as SOME thm_consts) =
   275          (if subset (op =) (pat_consts, thm_consts) andalso
   276             Pattern.matches_subterm (ProofContext.theory_of ctxt) (pat, prop_of theorem)
   277           then SOME (0, 0) else NONE, c);
   278   in check end;
   279 
   280 
   281 (* interpret criteria as filters *)
   282 
   283 local
   284 
   285 fun err_no_goal c =
   286   error ("Current goal required for " ^ c ^ " search criterion");
   287 
   288 val fix_goal = Thm.prop_of;
   289 
   290 fun filter_crit _ _ (Name name) = apfst (filter_name name)
   291   | filter_crit _ NONE Intro = err_no_goal "intro"
   292   | filter_crit _ NONE IntroIff = err_no_goal "introiff"
   293   | filter_crit _ NONE Elim = err_no_goal "elim"
   294   | filter_crit _ NONE Dest = err_no_goal "dest"
   295   | filter_crit _ NONE Solves = err_no_goal "solves"
   296   | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro false ctxt (fix_goal goal))
   297   | filter_crit ctxt (SOME goal) IntroIff = apfst (filter_intro true ctxt (fix_goal goal))
   298   | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (fix_goal goal))
   299   | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (fix_goal goal))
   300   | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
   301   | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
   302   | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
   303 
   304 fun opt_not x = if is_some x then NONE else SOME (0, 0);
   305 
   306 fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
   307   | opt_add _ _ = NONE;
   308 
   309 fun app_filters thm =
   310   let
   311     fun app (NONE, _, _) = NONE
   312       | app (SOME v, _, []) = SOME (v, thm)
   313       | app (r, consts, f :: fs) =
   314           let val (r', consts') = f (thm, consts)
   315           in app (opt_add r r', consts', fs) end;
   316   in app end;
   317 
   318 
   319 in
   320 
   321 fun filter_criterion ctxt opt_goal (b, c) =
   322   (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
   323 
   324 fun sorted_filter filters theorems =
   325   let
   326     fun eval_filters theorem = app_filters theorem (SOME (0, 0), NONE, filters);
   327 
   328     (*filters return: (number of assumptions, substitution size) option, so
   329       sort (desc. in both cases) according to number of assumptions first,
   330       then by the substitution size*)
   331     fun result_ord (((p0, s0), _), ((p1, s1), _)) =
   332       prod_ord int_ord int_ord ((p1, s1), (p0, s0));
   333   in map_filter eval_filters theorems |> sort result_ord |> map #2 end;
   334 
   335 fun lazy_filter filters =
   336   let
   337     fun lazy_match thms = Seq.make (fn () => first_match thms)
   338 
   339     and first_match [] = NONE
   340       | first_match (thm :: thms) =
   341           (case app_filters thm (SOME (0, 0), NONE, filters) of
   342             NONE => first_match thms
   343           | SOME (_, t) => SOME (t, lazy_match thms));
   344   in lazy_match end;
   345 
   346 end;
   347 
   348 
   349 (* removing duplicates, preferring nicer names, roughly n log n *)
   350 
   351 local
   352 
   353 val index_ord = option_ord (K EQUAL);
   354 val hidden_ord = bool_ord o pairself Name_Space.is_hidden;
   355 val qual_ord = int_ord o pairself (length o Long_Name.explode);
   356 val txt_ord = int_ord o pairself size;
   357 
   358 fun nicer_name (x, i) (y, j) =
   359   (case hidden_ord (x, y) of EQUAL =>
   360     (case index_ord (i, j) of EQUAL =>
   361       (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
   362     | ord => ord)
   363   | ord => ord) <> GREATER;
   364 
   365 fun rem_cdups nicer xs =
   366   let
   367     fun rem_c rev_seen [] = rev rev_seen
   368       | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
   369       | rem_c rev_seen ((x as (t, _)) :: (y as (t', _)) :: xs) =
   370           if (prop_of t) aconv (prop_of t')
   371           then rem_c rev_seen ((if nicer (fact_ref_of t) (fact_ref_of t') then x else y) :: xs)
   372           else rem_c (x :: rev_seen) (y :: xs)
   373   in rem_c [] xs end;
   374 
   375 in
   376 
   377 fun nicer_shortest ctxt =
   378   let
   379     (* FIXME global name space!? *)
   380     val space = Facts.space_of (Global_Theory.facts_of (ProofContext.theory_of ctxt));
   381 
   382     val shorten =
   383       Name_Space.extern_flags
   384         {long_names = false, short_names = false, unique_names = false} space;
   385 
   386     fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
   387           nicer_name (shorten x, i) (shorten y, j)
   388       | nicer (Facts.Fact _) (Facts.Named _) = true
   389       | nicer (Facts.Named _) (Facts.Fact _) = false;
   390   in nicer end;
   391 
   392 fun rem_thm_dups nicer xs =
   393   xs ~~ (1 upto length xs)
   394   |> sort (Term_Ord.fast_term_ord o pairself (prop_of o #1))
   395   |> rem_cdups nicer
   396   |> sort (int_ord o pairself #2)
   397   |> map #1;
   398 
   399 end;
   400 
   401 
   402 (* print_theorems *)
   403 
   404 fun all_facts_of ctxt =
   405   let
   406     fun visible_facts facts =
   407       Facts.dest_static [] facts
   408       |> filter_out (Facts.is_concealed facts o #1);
   409   in
   410     maps Facts.selections
   411      (visible_facts (Global_Theory.facts_of (ProofContext.theory_of ctxt)) @
   412 
   413 
   414       visible_facts (ProofContext.facts_of ctxt))
   415   end;
   416 
   417 val limit = Unsynchronized.ref 40;
   418 
   419 fun filter_theorems ctxt theorems opt_goal opt_limit rem_dups raw_criteria =
   420   let
   421     val assms =
   422       ProofContext.get_fact ctxt (Facts.named "local.assms")
   423         handle ERROR _ => [];
   424     val add_prems = Seq.hd o TRY (Method.insert_tac assms 1);
   425     val opt_goal' = Option.map add_prems opt_goal;
   426 
   427     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   428     val filters = map (filter_criterion ctxt opt_goal') criteria;
   429 
   430     fun find_all theorems =
   431       let
   432         val raw_matches = sorted_filter filters theorems;
   433 
   434         val matches =
   435           if rem_dups
   436           then rem_thm_dups (nicer_shortest ctxt) raw_matches
   437           else raw_matches;
   438 
   439         val len = length matches;
   440         val lim = the_default (! limit) opt_limit;
   441       in (SOME len, drop (Int.max (len - lim, 0)) matches) end;
   442 
   443     val find =
   444       if rem_dups orelse is_none opt_limit
   445       then find_all
   446       else pair NONE o Seq.list_of o Seq.take (the opt_limit) o lazy_filter filters;
   447 
   448   in find theorems end;
   449 
   450 fun find_theorems ctxt opt_goal opt_limit rem_dups raw_criteria =
   451   filter_theorems ctxt (map Internal (all_facts_of ctxt)) opt_goal opt_limit
   452      rem_dups raw_criteria
   453   |> apsnd (map (fn Internal f => f));
   454 
   455 fun pretty_thm ctxt (thmref, thm) = Pretty.block
   456   [Pretty.str (Facts.string_of_ref thmref), Pretty.str ":", Pretty.brk 1,
   457     Display.pretty_thm ctxt thm];
   458 
   459 fun print_theorems ctxt (foundo, thms) raw_criteria =
   460   let
   461     val start = start_timing ();
   462 
   463     val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   464     val returned = length thms;
   465 
   466     val tally_msg =
   467       (case foundo of
   468         NONE => "displaying " ^ string_of_int returned ^ " theorem(s)"
   469       | SOME found =>
   470           "found " ^ string_of_int found ^ " theorem(s)" ^
   471             (if returned < found
   472              then " (" ^ string_of_int returned ^ " displayed)"
   473              else ""));
   474 
   475     val end_msg = " in " ^ Time.toString (#cpu (end_timing start)) ^ " secs";
   476   in
   477     Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria) ::
   478     Pretty.str "" ::
   479     (if null thms then [Pretty.str ("nothing found" ^ end_msg)]
   480      else
   481       [Pretty.str (tally_msg ^ end_msg ^ ":"), Pretty.str ""] @
   482         map (pretty_thm ctxt) thms)
   483   end |> Pretty.chunks |> Pretty.writeln;
   484 
   485 
   486 
   487 (** command syntax **)
   488 
   489 local
   490 
   491 val criterion =
   492   Parse.reserved "name" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.xname) >> Name ||
   493   Parse.reserved "intro" >> K Intro ||
   494   Parse.reserved "introiff" >> K IntroIff ||
   495   Parse.reserved "elim" >> K Elim ||
   496   Parse.reserved "dest" >> K Dest ||
   497   Parse.reserved "solves" >> K Solves ||
   498   Parse.reserved "simp" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.term) >> Simp ||
   499   Parse.term >> Pattern;
   500 
   501 val options =
   502   Scan.optional
   503     (Parse.$$$ "(" |--
   504       Parse.!!! (Scan.option Parse.nat -- Scan.optional (Parse.reserved "with_dups" >> K false) true
   505         --| Parse.$$$ ")")) (NONE, true);
   506 in
   507 
   508 val _ =
   509   Outer_Syntax.improper_command "find_theorems" "print theorems meeting specified criteria"
   510     Keyword.diag
   511     (options -- Scan.repeat (((Scan.option Parse.minus >> is_none) -- criterion))
   512       >> (fn ((opt_lim, rem_dups), spec) =>
   513         Toplevel.no_timing o
   514         Toplevel.keep (fn state =>
   515           let
   516             val ctxt = Toplevel.context_of state;
   517             val opt_goal = try (Proof.simple_goal o Toplevel.proof_of) state |> Option.map #goal;
   518             val found = find_theorems ctxt opt_goal opt_lim rem_dups spec;
   519           in print_theorems ctxt found spec end)));
   520 
   521 end;
   522 
   523 end;