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