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