moved find_theorems.ML and find_consts.ML to Pure/Tools, collecting main implementation in one place each;
authorwenzelm
Fri Feb 27 15:46:22 2009 +0100 (2009-02-27)
changeset 301428d6145694bb5
parent 30141 c59a1258559b
child 30143 98a986b02022
moved find_theorems.ML and find_consts.ML to Pure/Tools, collecting main implementation in one place each;
src/Pure/IsaMakefile
src/Pure/Isar/ROOT.ML
src/Pure/Isar/find_consts.ML
src/Pure/Isar/find_theorems.ML
src/Pure/Isar/isar_cmd.ML
src/Pure/Isar/isar_syn.ML
src/Pure/Tools/ROOT.ML
src/Pure/Tools/find_consts.ML
src/Pure/Tools/find_theorems.ML
     1.1 --- a/src/Pure/IsaMakefile	Fri Feb 27 12:28:28 2009 +0100
     1.2 +++ b/src/Pure/IsaMakefile	Fri Feb 27 15:46:22 2009 +0100
     1.3 @@ -59,18 +59,18 @@
     1.4    Isar/attrib.ML Isar/auto_bind.ML Isar/calculation.ML Isar/class.ML	\
     1.5    Isar/class_target.ML Isar/code.ML Isar/code_unit.ML			\
     1.6    Isar/constdefs.ML Isar/context_rules.ML Isar/element.ML		\
     1.7 -  Isar/expression.ML Isar/find_consts.ML Isar/find_theorems.ML		\
     1.8 -  Isar/isar.ML Isar/isar_cmd.ML Isar/isar_document.ML Isar/isar_syn.ML	\
     1.9 -  Isar/local_defs.ML Isar/local_syntax.ML Isar/local_theory.ML		\
    1.10 -  Isar/locale.ML Isar/method.ML Isar/net_rules.ML Isar/object_logic.ML	\
    1.11 -  Isar/obtain.ML Isar/outer_keyword.ML Isar/outer_lex.ML		\
    1.12 -  Isar/outer_parse.ML Isar/outer_syntax.ML Isar/overloading.ML		\
    1.13 -  Isar/proof.ML Isar/proof_context.ML Isar/proof_display.ML		\
    1.14 -  Isar/proof_node.ML Isar/rule_cases.ML Isar/rule_insts.ML		\
    1.15 -  Isar/session.ML Isar/skip_proof.ML Isar/spec_parse.ML			\
    1.16 -  Isar/specification.ML Isar/theory_target.ML Isar/toplevel.ML		\
    1.17 -  Isar/value_parse.ML ML/ml_antiquote.ML ML/ml_context.ML ML/ml_lex.ML	\
    1.18 -  ML/ml_parse.ML ML/ml_syntax.ML ML/ml_thms.ML Proof/extraction.ML	\
    1.19 +  Isar/expression.ML Isar/isar.ML Isar/isar_cmd.ML			\
    1.20 +  Isar/isar_document.ML Isar/isar_syn.ML Isar/local_defs.ML		\
    1.21 +  Isar/local_syntax.ML Isar/local_theory.ML Isar/locale.ML		\
    1.22 +  Isar/method.ML Isar/net_rules.ML Isar/object_logic.ML Isar/obtain.ML	\
    1.23 +  Isar/outer_keyword.ML Isar/outer_lex.ML Isar/outer_parse.ML		\
    1.24 +  Isar/outer_syntax.ML Isar/overloading.ML Isar/proof.ML		\
    1.25 +  Isar/proof_context.ML Isar/proof_display.ML Isar/proof_node.ML	\
    1.26 +  Isar/rule_cases.ML Isar/rule_insts.ML Isar/session.ML			\
    1.27 +  Isar/skip_proof.ML Isar/spec_parse.ML Isar/specification.ML		\
    1.28 +  Isar/theory_target.ML Isar/toplevel.ML Isar/value_parse.ML		\
    1.29 +  ML/ml_antiquote.ML ML/ml_context.ML ML/ml_lex.ML ML/ml_parse.ML	\
    1.30 +  ML/ml_syntax.ML ML/ml_thms.ML Proof/extraction.ML			\
    1.31    Proof/proof_rewrite_rules.ML Proof/proof_syntax.ML			\
    1.32    Proof/proofchecker.ML Proof/reconstruct.ML ProofGeneral/ROOT.ML	\
    1.33    ProofGeneral/pgip.ML ProofGeneral/pgip_input.ML			\
    1.34 @@ -84,16 +84,17 @@
    1.35    Syntax/syn_trans.ML Syntax/syntax.ML Syntax/type_ext.ML Thy/html.ML	\
    1.36    Thy/latex.ML Thy/present.ML Thy/term_style.ML Thy/thm_deps.ML		\
    1.37    Thy/thy_header.ML Thy/thy_info.ML Thy/thy_load.ML Thy/thy_output.ML	\
    1.38 -  Thy/thy_syntax.ML Tools/ROOT.ML Tools/isabelle_process.ML		\
    1.39 -  Tools/named_thms.ML Tools/xml_syntax.ML assumption.ML axclass.ML	\
    1.40 -  codegen.ML config.ML conjunction.ML consts.ML context.ML		\
    1.41 -  context_position.ML conv.ML defs.ML display.ML drule.ML envir.ML	\
    1.42 -  facts.ML goal.ML interpretation.ML library.ML logic.ML		\
    1.43 -  meta_simplifier.ML more_thm.ML morphism.ML name.ML net.ML		\
    1.44 -  old_goals.ML old_term.ML pattern.ML primitive_defs.ML proofterm.ML	\
    1.45 -  pure_setup.ML pure_thy.ML search.ML sign.ML simplifier.ML sorts.ML	\
    1.46 -  subgoal.ML tactic.ML tctical.ML term.ML term_ord.ML term_subst.ML	\
    1.47 -  theory.ML thm.ML type.ML type_infer.ML unify.ML variable.ML
    1.48 +  Thy/thy_syntax.ML Tools/ROOT.ML Tools/find_consts.ML			\
    1.49 +  Tools/find_theorems.ML Tools/isabelle_process.ML Tools/named_thms.ML	\
    1.50 +  Tools/xml_syntax.ML assumption.ML axclass.ML codegen.ML config.ML	\
    1.51 +  conjunction.ML consts.ML context.ML context_position.ML conv.ML	\
    1.52 +  defs.ML display.ML drule.ML envir.ML facts.ML goal.ML			\
    1.53 +  interpretation.ML library.ML logic.ML meta_simplifier.ML more_thm.ML	\
    1.54 +  morphism.ML name.ML net.ML old_goals.ML old_term.ML pattern.ML	\
    1.55 +  primitive_defs.ML proofterm.ML pure_setup.ML pure_thy.ML search.ML	\
    1.56 +  sign.ML simplifier.ML sorts.ML subgoal.ML tactic.ML tctical.ML	\
    1.57 +  term.ML term_ord.ML term_subst.ML theory.ML thm.ML type.ML		\
    1.58 +  type_infer.ML unify.ML variable.ML
    1.59  	@./mk
    1.60  
    1.61  
     2.1 --- a/src/Pure/Isar/ROOT.ML	Fri Feb 27 12:28:28 2009 +0100
     2.2 +++ b/src/Pure/Isar/ROOT.ML	Fri Feb 27 15:46:22 2009 +0100
     2.3 @@ -89,7 +89,5 @@
     2.4  (*theory and proof operations*)
     2.5  use "rule_insts.ML";
     2.6  use "../Thy/thm_deps.ML";
     2.7 -use "find_theorems.ML";
     2.8 -use "find_consts.ML";
     2.9  use "isar_cmd.ML";
    2.10  use "isar_syn.ML";
     3.1 --- a/src/Pure/Isar/find_consts.ML	Fri Feb 27 12:28:28 2009 +0100
     3.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     3.3 @@ -1,120 +0,0 @@
     3.4 -(*  Title:      find_consts.ML
     3.5 -    Author:     Timothy Bourke and Gerwin Klein, NICTA
     3.6 -
     3.7 -  Hoogle-like (http://www-users.cs.york.ac.uk/~ndm/hoogle) searching by type
     3.8 -  over constants, but matching is not fuzzy
     3.9 -*)
    3.10 -
    3.11 -signature FIND_CONSTS =
    3.12 -sig
    3.13 -  datatype criterion = Strict of string
    3.14 -                     | Loose of string
    3.15 -                     | Name of string
    3.16 -
    3.17 -  val default_criteria : (bool * criterion) list ref
    3.18 -
    3.19 -  val find_consts : Proof.context -> (bool * criterion) list -> unit
    3.20 -end;
    3.21 -
    3.22 -structure FindConsts : FIND_CONSTS =
    3.23 -struct
    3.24 -
    3.25 -datatype criterion = Strict of string
    3.26 -                   | Loose of string
    3.27 -                   | Name of string;
    3.28 -
    3.29 -val default_criteria = ref [(false, Name ".sko_")];
    3.30 -
    3.31 -fun add_tye (_, (_, t)) n = size_of_typ t + n;
    3.32 -
    3.33 -fun matches_subtype thy typat = let
    3.34 -    val p = can (fn ty => Sign.typ_match thy (typat, ty) Vartab.empty);
    3.35 -
    3.36 -    fun fs [] = false
    3.37 -      | fs (t::ts) = f t orelse fs ts
    3.38 -
    3.39 -    and f (t as Type (_, ars)) = p t orelse fs ars
    3.40 -      | f t = p t;
    3.41 -  in f end;
    3.42 -
    3.43 -fun check_const p (nm, (ty, _)) = if p (nm, ty)
    3.44 -                                  then SOME (size_of_typ ty)
    3.45 -                                  else NONE;
    3.46 -
    3.47 -fun opt_not f (c as (_, (ty, _))) = if is_some (f c)
    3.48 -                                    then NONE else SOME (size_of_typ ty);
    3.49 -
    3.50 -fun filter_const (_, NONE) = NONE
    3.51 -  | filter_const (f, (SOME (c, r))) = Option.map
    3.52 -                                        (pair c o ((curry Int.min) r)) (f c);
    3.53 -
    3.54 -fun pretty_criterion (b, c) =
    3.55 -  let
    3.56 -    fun prfx s = if b then s else "-" ^ s;
    3.57 -  in
    3.58 -    (case c of
    3.59 -      Strict pat => Pretty.str (prfx "strict: " ^ quote pat)
    3.60 -    | Loose pat => Pretty.str (prfx (quote pat))
    3.61 -    | Name name => Pretty.str (prfx "name: " ^ quote name))
    3.62 -  end;
    3.63 -
    3.64 -fun pretty_const ctxt (nm, ty) = let
    3.65 -    val ty' = Logic.unvarifyT ty;
    3.66 -  in
    3.67 -    Pretty.block [Pretty.quote (Pretty.str nm), Pretty.fbrk,
    3.68 -                  Pretty.str "::", Pretty.brk 1,
    3.69 -                  Pretty.quote (Syntax.pretty_typ ctxt ty')]
    3.70 -  end;
    3.71 -
    3.72 -fun find_consts ctxt raw_criteria = let
    3.73 -    val start = start_timing ();
    3.74 -
    3.75 -    val thy = ProofContext.theory_of ctxt;
    3.76 -    val low_ranking = 10000;
    3.77 -
    3.78 -    fun make_pattern crit = ProofContext.read_term_pattern ctxt ("_::" ^ crit)
    3.79 -                            |> type_of;
    3.80 -
    3.81 -    fun make_match (Strict arg) =
    3.82 -          let val qty = make_pattern arg; in
    3.83 -            fn (_, (ty, _)) => let
    3.84 -                val tye = Sign.typ_match thy (qty, ty) Vartab.empty;
    3.85 -                val sub_size = Vartab.fold add_tye tye 0;
    3.86 -              in SOME sub_size end handle MATCH => NONE
    3.87 -          end
    3.88 -
    3.89 -      | make_match (Loose arg) =
    3.90 -          check_const (matches_subtype thy (make_pattern arg) o snd)
    3.91 -      
    3.92 -      | make_match (Name arg) = check_const (match_string arg o fst);
    3.93 -
    3.94 -    fun make_criterion (b, crit) = (if b then I else opt_not) (make_match crit);
    3.95 -    val criteria = map make_criterion ((!default_criteria) @ raw_criteria);
    3.96 -
    3.97 -    val (_, consts) = (#constants o Consts.dest o Sign.consts_of) thy;
    3.98 -    fun eval_entry c = foldl filter_const (SOME (c, low_ranking)) criteria;
    3.99 -
   3.100 -    val matches = Symtab.fold (cons o eval_entry) consts []
   3.101 -                  |> map_filter I
   3.102 -                  |> sort (rev_order o int_ord o pairself snd)
   3.103 -                  |> map ((apsnd fst) o fst);
   3.104 -
   3.105 -    val end_msg = " in " ^
   3.106 -                  (List.nth (String.tokens Char.isSpace (end_timing start), 3))
   3.107 -                  ^ " secs"
   3.108 -  in
   3.109 -    Pretty.big_list "searched for:" (map pretty_criterion raw_criteria)
   3.110 -      :: Pretty.str ""
   3.111 -      :: (Pretty.str o concat)
   3.112 -           (if null matches
   3.113 -            then ["nothing found", end_msg]
   3.114 -            else ["found ", (string_of_int o length) matches,
   3.115 -                  " constants", end_msg, ":"])
   3.116 -      :: Pretty.str ""
   3.117 -      :: map (pretty_const ctxt) matches
   3.118 -    |> Pretty.chunks
   3.119 -    |> Pretty.writeln
   3.120 -  end handle ERROR s => Output.error_msg s
   3.121 -
   3.122 -end;
   3.123 -
     4.1 --- a/src/Pure/Isar/find_theorems.ML	Fri Feb 27 12:28:28 2009 +0100
     4.2 +++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
     4.3 @@ -1,378 +0,0 @@
     4.4 -(*  Title:      Pure/Isar/find_theorems.ML
     4.5 -    Author:     Rafal Kolanski and Gerwin Klein, NICTA
     4.6 -
     4.7 -Retrieve theorems from proof context.
     4.8 -*)
     4.9 -
    4.10 -signature FIND_THEOREMS =
    4.11 -sig
    4.12 -  val limit: int ref
    4.13 -  val tac_limit: int ref
    4.14 -
    4.15 -  datatype 'term criterion =
    4.16 -    Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
    4.17 -    Pattern of 'term
    4.18 -
    4.19 -  val find_theorems: Proof.context -> thm option -> bool ->
    4.20 -    (bool * string criterion) list -> (Facts.ref * thm) list
    4.21 -
    4.22 -  val print_theorems: Proof.context -> thm option -> int option -> bool ->
    4.23 -    (bool * string criterion) list -> unit
    4.24 -end;
    4.25 -
    4.26 -structure FindTheorems: FIND_THEOREMS =
    4.27 -struct
    4.28 -
    4.29 -(** search criteria **)
    4.30 -
    4.31 -datatype 'term criterion =
    4.32 -  Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
    4.33 -  Pattern of 'term;
    4.34 -
    4.35 -fun read_criterion _ (Name name) = Name name
    4.36 -  | read_criterion _ Intro = Intro
    4.37 -  | read_criterion _ Elim = Elim
    4.38 -  | read_criterion _ Dest = Dest
    4.39 -  | read_criterion _ Solves = Solves
    4.40 -  | read_criterion ctxt (Simp str) = Simp (ProofContext.read_term_pattern ctxt str)
    4.41 -  | read_criterion ctxt (Pattern str) = Pattern (ProofContext.read_term_pattern ctxt str);
    4.42 -
    4.43 -fun pretty_criterion ctxt (b, c) =
    4.44 -  let
    4.45 -    fun prfx s = if b then s else "-" ^ s;
    4.46 -  in
    4.47 -    (case c of
    4.48 -      Name name => Pretty.str (prfx "name: " ^ quote name)
    4.49 -    | Intro => Pretty.str (prfx "intro")
    4.50 -    | Elim => Pretty.str (prfx "elim")
    4.51 -    | Dest => Pretty.str (prfx "dest")
    4.52 -    | Solves => Pretty.str (prfx "solves")
    4.53 -    | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
    4.54 -        Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
    4.55 -    | Pattern pat => Pretty.enclose (prfx " \"") "\""
    4.56 -        [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
    4.57 -  end;
    4.58 -
    4.59 -(** search criterion filters **)
    4.60 -
    4.61 -(*generated filters are to be of the form
    4.62 -  input: (Facts.ref * thm)
    4.63 -  output: (p:int, s:int) option, where
    4.64 -    NONE indicates no match
    4.65 -    p is the primary sorting criterion
    4.66 -      (eg. number of assumptions in the theorem)
    4.67 -    s is the secondary sorting criterion
    4.68 -      (eg. size of the substitution for intro, elim and dest)
    4.69 -  when applying a set of filters to a thm, fold results in:
    4.70 -    (biggest p, sum of all s)
    4.71 -  currently p and s only matter for intro, elim, dest and simp filters,
    4.72 -  otherwise the default ordering is used.
    4.73 -*)
    4.74 -
    4.75 -
    4.76 -(* matching theorems *)
    4.77 -
    4.78 -fun is_nontrivial thy = Term.is_Const o Term.head_of o ObjectLogic.drop_judgment thy;
    4.79 -
    4.80 -(*extract terms from term_src, refine them to the parts that concern us,
    4.81 -  if po try match them against obj else vice versa.
    4.82 -  trivial matches are ignored.
    4.83 -  returns: smallest substitution size*)
    4.84 -fun is_matching_thm (extract_terms, refine_term) ctxt po obj term_src =
    4.85 -  let
    4.86 -    val thy = ProofContext.theory_of ctxt;
    4.87 -
    4.88 -    fun matches pat =
    4.89 -      is_nontrivial thy pat andalso
    4.90 -      Pattern.matches thy (if po then (pat, obj) else (obj, pat));
    4.91 -
    4.92 -    fun substsize pat =
    4.93 -      let val (_, subst) =
    4.94 -        Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
    4.95 -      in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
    4.96 -
    4.97 -    fun bestmatch [] = NONE
    4.98 -     |  bestmatch xs = SOME (foldr1 Int.min xs);
    4.99 -
   4.100 -    val match_thm = matches o refine_term;
   4.101 -  in
   4.102 -    map (substsize o refine_term) (filter match_thm (extract_terms term_src))
   4.103 -    |> bestmatch
   4.104 -  end;
   4.105 -
   4.106 -
   4.107 -(* filter_name *)
   4.108 -
   4.109 -fun filter_name str_pat (thmref, _) =
   4.110 -  if match_string str_pat (Facts.name_of_ref thmref)
   4.111 -  then SOME (0, 0) else NONE;
   4.112 -
   4.113 -(* filter intro/elim/dest/solves rules *)
   4.114 -
   4.115 -fun filter_dest ctxt goal (_, thm) =
   4.116 -  let
   4.117 -    val extract_dest =
   4.118 -     (fn thm => if Thm.no_prems thm then [] else [Thm.full_prop_of thm],
   4.119 -      hd o Logic.strip_imp_prems);
   4.120 -    val prems = Logic.prems_of_goal goal 1;
   4.121 -
   4.122 -    fun try_subst prem = is_matching_thm extract_dest ctxt true prem thm;
   4.123 -    val successful = prems |> map_filter try_subst;
   4.124 -  in
   4.125 -    (*if possible, keep best substitution (one with smallest size)*)
   4.126 -    (*dest rules always have assumptions, so a dest with one
   4.127 -      assumption is as good as an intro rule with none*)
   4.128 -    if not (null successful)
   4.129 -    then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
   4.130 -  end;
   4.131 -
   4.132 -fun filter_intro ctxt goal (_, thm) =
   4.133 -  let
   4.134 -    val extract_intro = (single o Thm.full_prop_of, Logic.strip_imp_concl);
   4.135 -    val concl = Logic.concl_of_goal goal 1;
   4.136 -    val ss = is_matching_thm extract_intro ctxt true concl thm;
   4.137 -  in
   4.138 -    if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
   4.139 -  end;
   4.140 -
   4.141 -fun filter_elim ctxt goal (_, thm) =
   4.142 -  if not (Thm.no_prems thm) then
   4.143 -    let
   4.144 -      val rule = Thm.full_prop_of thm;
   4.145 -      val prems = Logic.prems_of_goal goal 1;
   4.146 -      val goal_concl = Logic.concl_of_goal goal 1;
   4.147 -      val rule_mp = hd (Logic.strip_imp_prems rule);
   4.148 -      val rule_concl = Logic.strip_imp_concl rule;
   4.149 -      fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);
   4.150 -      val rule_tree = combine rule_mp rule_concl;
   4.151 -      fun goal_tree prem = combine prem goal_concl;
   4.152 -      fun try_subst prem =
   4.153 -        is_matching_thm (single, I) ctxt true (goal_tree prem) rule_tree;
   4.154 -      val successful = prems |> map_filter try_subst;
   4.155 -    in
   4.156 -    (*elim rules always have assumptions, so an elim with one
   4.157 -      assumption is as good as an intro rule with none*)
   4.158 -      if is_nontrivial (ProofContext.theory_of ctxt) (Thm.major_prem_of thm)
   4.159 -        andalso not (null successful)
   4.160 -      then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
   4.161 -    end
   4.162 -  else NONE
   4.163 -
   4.164 -val tac_limit = ref 5;
   4.165 -
   4.166 -fun filter_solves ctxt goal = let
   4.167 -    val baregoal = Logic.get_goal (prop_of goal) 1;
   4.168 -
   4.169 -    fun etacn thm i = Seq.take (!tac_limit) o etac thm i;
   4.170 -    fun try_thm thm = if Thm.no_prems thm then rtac thm 1 goal
   4.171 -                      else (etacn thm THEN_ALL_NEW
   4.172 -                             (Goal.norm_hhf_tac THEN'
   4.173 -                               Method.assumption_tac ctxt)) 1 goal;
   4.174 -  in
   4.175 -    fn (_, thm) => if (is_some o Seq.pull o try_thm) thm
   4.176 -                   then SOME (Thm.nprems_of thm, 0) else NONE
   4.177 -  end;
   4.178 -
   4.179 -(* filter_simp *)
   4.180 -
   4.181 -fun filter_simp ctxt t (_, thm) =
   4.182 -  let
   4.183 -    val (_, {mk_rews = {mk, ...}, ...}) =
   4.184 -      Simplifier.rep_ss (Simplifier.local_simpset_of ctxt);
   4.185 -    val extract_simp =
   4.186 -      (map Thm.full_prop_of o mk, #1 o Logic.dest_equals o Logic.strip_imp_concl);
   4.187 -    val ss = is_matching_thm extract_simp ctxt false t thm
   4.188 -  in
   4.189 -    if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
   4.190 -  end;
   4.191 -
   4.192 -
   4.193 -(* filter_pattern *)
   4.194 -
   4.195 -fun get_names t = (Term.add_const_names t []) union (Term.add_free_names t []);
   4.196 -fun get_thm_names (_, thm) = get_names (Thm.full_prop_of thm);
   4.197 -  (* Including all constants and frees is only sound because
   4.198 -     matching uses higher-order patterns. If full matching
   4.199 -     were used, then constants that may be subject to
   4.200 -     beta-reduction after substitution of frees should
   4.201 -     not be included for LHS set because they could be
   4.202 -     thrown away by the substituted function.
   4.203 -     e.g. for (?F 1 2) do not include 1 or 2, if it were
   4.204 -          possible for ?F to be (% x y. 3)
   4.205 -     The largest possible set should always be included on
   4.206 -     the RHS. *)
   4.207 -
   4.208 -fun filter_pattern ctxt pat = let
   4.209 -    val pat_consts = get_names pat;
   4.210 -
   4.211 -    fun check (t, NONE) = check (t, SOME (get_thm_names t))
   4.212 -      | check ((_, thm), c as SOME thm_consts) =
   4.213 -          (if pat_consts subset_string thm_consts
   4.214 -              andalso (Pattern.matches_subterm (ProofContext.theory_of ctxt)
   4.215 -                                               (pat, Thm.full_prop_of thm))
   4.216 -           then SOME (0, 0) else NONE, c);
   4.217 -  in check end;
   4.218 -
   4.219 -(* interpret criteria as filters *)
   4.220 -
   4.221 -local
   4.222 -
   4.223 -fun err_no_goal c =
   4.224 -  error ("Current goal required for " ^ c ^ " search criterion");
   4.225 -
   4.226 -val fix_goal = Thm.prop_of;
   4.227 -val fix_goalo = Option.map fix_goal;
   4.228 -
   4.229 -fun filter_crit _ _ (Name name) = apfst (filter_name name)
   4.230 -  | filter_crit _ NONE Intro = err_no_goal "intro"
   4.231 -  | filter_crit _ NONE Elim = err_no_goal "elim"
   4.232 -  | filter_crit _ NONE Dest = err_no_goal "dest"
   4.233 -  | filter_crit _ NONE Solves = err_no_goal "solves"
   4.234 -  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt
   4.235 -                                                  (fix_goal goal))
   4.236 -  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt 
   4.237 -                                                  (fix_goal goal))
   4.238 -  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt
   4.239 -                                                  (fix_goal goal))
   4.240 -  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
   4.241 -  | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
   4.242 -  | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
   4.243 -
   4.244 -fun opt_not x = if is_some x then NONE else SOME (0, 0);
   4.245 -
   4.246 -fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
   4.247 -  | opt_add _ _ = NONE;
   4.248 -
   4.249 -fun app_filters thm = let
   4.250 -    fun app (NONE, _, _) = NONE
   4.251 -      | app (SOME v, consts, []) = SOME (v, thm)
   4.252 -      | app (r, consts, f::fs) = let val (r', consts') = f (thm, consts)
   4.253 -                                 in app (opt_add r r', consts', fs) end;
   4.254 -  in app end;
   4.255 -
   4.256 -in
   4.257 -
   4.258 -fun filter_criterion ctxt opt_goal (b, c) =
   4.259 -  (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
   4.260 -
   4.261 -fun all_filters filters thms =
   4.262 -  let
   4.263 -    fun eval_filters thm = app_filters thm (SOME (0, 0), NONE, filters);
   4.264 -
   4.265 -    (*filters return: (number of assumptions, substitution size) option, so
   4.266 -      sort (desc. in both cases) according to number of assumptions first,
   4.267 -      then by the substitution size*)
   4.268 -    fun thm_ord (((p0, s0), _), ((p1, s1), _)) =
   4.269 -      prod_ord int_ord int_ord ((p1, s1), (p0, s0));
   4.270 -  in map_filter eval_filters thms |> sort thm_ord |> map #2 end;
   4.271 -
   4.272 -end;
   4.273 -
   4.274 -
   4.275 -(* removing duplicates, preferring nicer names, roughly n log n *)
   4.276 -
   4.277 -local
   4.278 -
   4.279 -val index_ord = option_ord (K EQUAL);
   4.280 -val hidden_ord = bool_ord o pairself NameSpace.is_hidden;
   4.281 -val qual_ord = int_ord o pairself (length o NameSpace.explode);
   4.282 -val txt_ord = int_ord o pairself size;
   4.283 -
   4.284 -fun nicer_name (x, i) (y, j) =
   4.285 -  (case hidden_ord (x, y) of EQUAL =>
   4.286 -    (case index_ord (i, j) of EQUAL =>
   4.287 -      (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
   4.288 -    | ord => ord)
   4.289 -  | ord => ord) <> GREATER;
   4.290 -
   4.291 -fun rem_cdups nicer xs =
   4.292 -  let
   4.293 -    fun rem_c rev_seen [] = rev rev_seen
   4.294 -      | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
   4.295 -      | rem_c rev_seen ((x as ((n, t), _)) :: (y as ((n', t'), _)) :: xs) =
   4.296 -        if Thm.eq_thm_prop (t, t')
   4.297 -        then rem_c rev_seen ((if nicer n n' then x else y) :: xs)
   4.298 -        else rem_c (x :: rev_seen) (y :: xs)
   4.299 -  in rem_c [] xs end;
   4.300 -
   4.301 -in
   4.302 -
   4.303 -fun nicer_shortest ctxt = let
   4.304 -    val ns = ProofContext.theory_of ctxt
   4.305 -             |> PureThy.facts_of
   4.306 -             |> Facts.space_of;
   4.307 -
   4.308 -    val len_sort = sort (int_ord o (pairself size));
   4.309 -    fun shorten s = (case len_sort (NameSpace.get_accesses ns s) of
   4.310 -                       [] => s
   4.311 -                     | s'::_ => s');
   4.312 -
   4.313 -    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
   4.314 -          nicer_name (shorten x, i) (shorten y, j)
   4.315 -      | nicer (Facts.Fact _) (Facts.Named _) = true
   4.316 -      | nicer (Facts.Named _) (Facts.Fact _) = false;
   4.317 -  in nicer end;
   4.318 -
   4.319 -fun rem_thm_dups nicer xs =
   4.320 -  xs ~~ (1 upto length xs)
   4.321 -  |> sort (TermOrd.fast_term_ord o pairself (Thm.prop_of o #2 o #1))
   4.322 -  |> rem_cdups nicer
   4.323 -  |> sort (int_ord o pairself #2)
   4.324 -  |> map #1;
   4.325 -
   4.326 -end;
   4.327 -
   4.328 -
   4.329 -(* print_theorems *)
   4.330 -
   4.331 -fun all_facts_of ctxt =
   4.332 -  maps Facts.selections
   4.333 -   (Facts.dest_static [] (PureThy.facts_of (ProofContext.theory_of ctxt)) @
   4.334 -    Facts.dest_static [] (ProofContext.facts_of ctxt));
   4.335 -
   4.336 -val limit = ref 40;
   4.337 -
   4.338 -fun find_theorems ctxt opt_goal rem_dups raw_criteria =
   4.339 -  let
   4.340 -    val add_prems = Seq.hd o (TRY (Method.insert_tac
   4.341 -                                     (Assumption.prems_of ctxt) 1));
   4.342 -    val opt_goal' = Option.map add_prems opt_goal;
   4.343 -
   4.344 -    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   4.345 -    val filters = map (filter_criterion ctxt opt_goal') criteria;
   4.346 -
   4.347 -    val raw_matches = all_filters filters (all_facts_of ctxt);
   4.348 -
   4.349 -    val matches =
   4.350 -      if rem_dups
   4.351 -      then rem_thm_dups (nicer_shortest ctxt) raw_matches
   4.352 -      else raw_matches;
   4.353 -  in matches end;
   4.354 -
   4.355 -fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria = let
   4.356 -    val start = start_timing ();
   4.357 -
   4.358 -    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   4.359 -    val matches = find_theorems ctxt opt_goal rem_dups raw_criteria;
   4.360 -
   4.361 -    val len = length matches;
   4.362 -    val lim = the_default (! limit) opt_limit;
   4.363 -    val thms = Library.drop (len - lim, matches);
   4.364 -
   4.365 -    val end_msg = " in " ^
   4.366 -                  (List.nth (String.tokens Char.isSpace (end_timing start), 3))
   4.367 -                  ^ " secs"
   4.368 -  in
   4.369 -    Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria)
   4.370 -        :: Pretty.str "" ::
   4.371 -     (if null thms then [Pretty.str ("nothing found" ^ end_msg)]
   4.372 -      else
   4.373 -        [Pretty.str ("found " ^ string_of_int len ^ " theorems" ^
   4.374 -          (if len <= lim then ""
   4.375 -           else " (" ^ string_of_int lim ^ " displayed)")
   4.376 -           ^ end_msg ^ ":"), Pretty.str ""] @
   4.377 -        map Display.pretty_fact thms)
   4.378 -    |> Pretty.chunks |> Pretty.writeln
   4.379 -  end
   4.380 -
   4.381 -end;
     5.1 --- a/src/Pure/Isar/isar_cmd.ML	Fri Feb 27 12:28:28 2009 +0100
     5.2 +++ b/src/Pure/Isar/isar_cmd.ML	Fri Feb 27 15:46:22 2009 +0100
     5.3 @@ -62,10 +62,6 @@
     5.4    val class_deps: Toplevel.transition -> Toplevel.transition
     5.5    val thy_deps: Toplevel.transition -> Toplevel.transition
     5.6    val thm_deps: (Facts.ref * Attrib.src list) list -> Toplevel.transition -> Toplevel.transition
     5.7 -  val find_theorems: (int option * bool) * (bool * string FindTheorems.criterion) list
     5.8 -    -> Toplevel.transition -> Toplevel.transition
     5.9 -  val find_consts: (bool * FindConsts.criterion) list ->
    5.10 -                   Toplevel.transition -> Toplevel.transition
    5.11    val unused_thms: (string list * string list option) option ->
    5.12      Toplevel.transition -> Toplevel.transition
    5.13    val print_binds: Toplevel.transition -> Toplevel.transition
    5.14 @@ -403,20 +399,9 @@
    5.15        |> sort (int_ord o pairself #1) |> map #2;
    5.16    in Present.display_graph gr end);
    5.17  
    5.18 -
    5.19 -(* retrieve theorems *)
    5.20 -
    5.21  fun thm_deps args = Toplevel.unknown_theory o Toplevel.keep (fn state =>
    5.22    ThmDeps.thm_deps (Proof.get_thmss (Toplevel.enter_proof_body state) args));
    5.23  
    5.24 -fun find_theorems ((opt_lim, rem_dups), spec) =
    5.25 -  Toplevel.unknown_theory o Toplevel.keep (fn state =>
    5.26 -  let
    5.27 -    val proof_state = Toplevel.enter_proof_body state;
    5.28 -    val ctxt = Proof.context_of proof_state;
    5.29 -    val opt_goal = try Proof.get_goal proof_state |> Option.map (#2 o #2);
    5.30 -  in FindTheorems.print_theorems ctxt opt_goal opt_lim rem_dups spec end);
    5.31 -
    5.32  
    5.33  (* find unused theorems *)
    5.34  
    5.35 @@ -434,12 +419,6 @@
    5.36      |> map pretty_thm |> Pretty.chunks |> Pretty.writeln
    5.37    end);
    5.38  
    5.39 -(* retrieve constants *)
    5.40 -
    5.41 -fun find_consts spec =
    5.42 -  Toplevel.unknown_theory o Toplevel.keep (fn state =>
    5.43 -  let val ctxt = (Proof.context_of o Toplevel.enter_proof_body) state
    5.44 -  in FindConsts.find_consts ctxt spec end);
    5.45  
    5.46  (* print proof context contents *)
    5.47  
     6.1 --- a/src/Pure/Isar/isar_syn.ML	Fri Feb 27 12:28:28 2009 +0100
     6.2 +++ b/src/Pure/Isar/isar_syn.ML	Fri Feb 27 15:46:22 2009 +0100
     6.3 @@ -37,6 +37,7 @@
     6.4      (Scan.succeed (Toplevel.exit o Toplevel.end_local_theory));
     6.5  
     6.6  
     6.7 +
     6.8  (** markup commands **)
     6.9  
    6.10  val _ = OuterSyntax.markup_command ThyOutput.Markup "header" "theory header" K.diag
    6.11 @@ -79,7 +80,7 @@
    6.12  
    6.13  
    6.14  
    6.15 -(** theory sections **)
    6.16 +(** theory commands **)
    6.17  
    6.18  (* classes and sorts *)
    6.19  
    6.20 @@ -853,47 +854,6 @@
    6.21    OuterSyntax.improper_command "thm_deps" "visualize theorem dependencies"
    6.22      K.diag (SpecParse.xthms1 >> (Toplevel.no_timing oo IsarCmd.thm_deps));
    6.23  
    6.24 -local
    6.25 -
    6.26 -val criterion =
    6.27 -  P.reserved "name" |-- P.!!! (P.$$$ ":" |-- P.xname) >> FindTheorems.Name ||
    6.28 -  P.reserved "intro" >> K FindTheorems.Intro ||
    6.29 -  P.reserved "elim" >> K FindTheorems.Elim ||
    6.30 -  P.reserved "dest" >> K FindTheorems.Dest ||
    6.31 -  P.reserved "solves" >> K FindTheorems.Solves ||
    6.32 -  P.reserved "simp" |-- P.!!! (P.$$$ ":" |-- P.term) >> FindTheorems.Simp ||
    6.33 -  P.term >> FindTheorems.Pattern;
    6.34 -
    6.35 -val options =
    6.36 -  Scan.optional
    6.37 -    (P.$$$ "(" |--
    6.38 -      P.!!! (Scan.option P.nat -- Scan.optional (P.reserved "with_dups" >> K false) true
    6.39 -        --| P.$$$ ")")) (NONE, true);
    6.40 -in
    6.41 -
    6.42 -val _ =
    6.43 -  OuterSyntax.improper_command "find_theorems" "print theorems meeting specified criteria" K.diag
    6.44 -    (options -- Scan.repeat (((Scan.option P.minus >> is_none) -- criterion))
    6.45 -      >> (Toplevel.no_timing oo IsarCmd.find_theorems));
    6.46 -
    6.47 -end;
    6.48 -
    6.49 -local
    6.50 -
    6.51 -val criterion =
    6.52 -  P.reserved "strict" |-- P.!!! (P.$$$ ":" |-- P.xname) >> FindConsts.Strict ||
    6.53 -  P.reserved "name" |-- P.!!! (P.$$$ ":" |-- P.xname) >> FindConsts.Name ||
    6.54 -  P.xname >> FindConsts.Loose;
    6.55 -
    6.56 -in
    6.57 -
    6.58 -val _ =
    6.59 -  OuterSyntax.improper_command "find_consts" "search constants by type pattern"
    6.60 -    K.diag (Scan.repeat (((Scan.option P.minus >> is_none) -- criterion))
    6.61 -            >> (Toplevel.no_timing oo IsarCmd.find_consts));
    6.62 -
    6.63 -end;
    6.64 -
    6.65  val _ =
    6.66    OuterSyntax.improper_command "print_binds" "print term bindings of proof context" K.diag
    6.67      (Scan.succeed (Toplevel.no_timing o IsarCmd.print_binds));
    6.68 @@ -948,6 +908,7 @@
    6.69           (Toplevel.no_timing oo IsarCmd.unused_thms));
    6.70  
    6.71  
    6.72 +
    6.73  (** system commands (for interactive mode only) **)
    6.74  
    6.75  val _ =
     7.1 --- a/src/Pure/Tools/ROOT.ML	Fri Feb 27 12:28:28 2009 +0100
     7.2 +++ b/src/Pure/Tools/ROOT.ML	Fri Feb 27 15:46:22 2009 +0100
     7.3 @@ -9,6 +9,9 @@
     7.4  (*basic XML support*)
     7.5  use "xml_syntax.ML";
     7.6  
     7.7 +use "find_theorems.ML";
     7.8 +use "find_consts.ML";
     7.9 +
    7.10  (*quickcheck/autosolve needed here because of pg preferences*)
    7.11  use "../../Tools/quickcheck.ML";
    7.12  use "../../Tools/auto_solve.ML";
     8.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     8.2 +++ b/src/Pure/Tools/find_consts.ML	Fri Feb 27 15:46:22 2009 +0100
     8.3 @@ -0,0 +1,146 @@
     8.4 +(*  Title:      find_consts.ML
     8.5 +    Author:     Timothy Bourke and Gerwin Klein, NICTA
     8.6 +
     8.7 +  Hoogle-like (http://www-users.cs.york.ac.uk/~ndm/hoogle) searching by type
     8.8 +  over constants, but matching is not fuzzy
     8.9 +*)
    8.10 +
    8.11 +signature FIND_CONSTS =
    8.12 +sig
    8.13 +  datatype criterion = Strict of string
    8.14 +                     | Loose of string
    8.15 +                     | Name of string
    8.16 +
    8.17 +  val default_criteria : (bool * criterion) list ref
    8.18 +
    8.19 +  val find_consts : Proof.context -> (bool * criterion) list -> unit
    8.20 +end;
    8.21 +
    8.22 +structure FindConsts : FIND_CONSTS =
    8.23 +struct
    8.24 +
    8.25 +datatype criterion = Strict of string
    8.26 +                   | Loose of string
    8.27 +                   | Name of string;
    8.28 +
    8.29 +val default_criteria = ref [(false, Name ".sko_")];
    8.30 +
    8.31 +fun add_tye (_, (_, t)) n = size_of_typ t + n;
    8.32 +
    8.33 +fun matches_subtype thy typat = let
    8.34 +    val p = can (fn ty => Sign.typ_match thy (typat, ty) Vartab.empty);
    8.35 +
    8.36 +    fun fs [] = false
    8.37 +      | fs (t::ts) = f t orelse fs ts
    8.38 +
    8.39 +    and f (t as Type (_, ars)) = p t orelse fs ars
    8.40 +      | f t = p t;
    8.41 +  in f end;
    8.42 +
    8.43 +fun check_const p (nm, (ty, _)) = if p (nm, ty)
    8.44 +                                  then SOME (size_of_typ ty)
    8.45 +                                  else NONE;
    8.46 +
    8.47 +fun opt_not f (c as (_, (ty, _))) = if is_some (f c)
    8.48 +                                    then NONE else SOME (size_of_typ ty);
    8.49 +
    8.50 +fun filter_const (_, NONE) = NONE
    8.51 +  | filter_const (f, (SOME (c, r))) = Option.map
    8.52 +                                        (pair c o ((curry Int.min) r)) (f c);
    8.53 +
    8.54 +fun pretty_criterion (b, c) =
    8.55 +  let
    8.56 +    fun prfx s = if b then s else "-" ^ s;
    8.57 +  in
    8.58 +    (case c of
    8.59 +      Strict pat => Pretty.str (prfx "strict: " ^ quote pat)
    8.60 +    | Loose pat => Pretty.str (prfx (quote pat))
    8.61 +    | Name name => Pretty.str (prfx "name: " ^ quote name))
    8.62 +  end;
    8.63 +
    8.64 +fun pretty_const ctxt (nm, ty) = let
    8.65 +    val ty' = Logic.unvarifyT ty;
    8.66 +  in
    8.67 +    Pretty.block [Pretty.quote (Pretty.str nm), Pretty.fbrk,
    8.68 +                  Pretty.str "::", Pretty.brk 1,
    8.69 +                  Pretty.quote (Syntax.pretty_typ ctxt ty')]
    8.70 +  end;
    8.71 +
    8.72 +fun find_consts ctxt raw_criteria = let
    8.73 +    val start = start_timing ();
    8.74 +
    8.75 +    val thy = ProofContext.theory_of ctxt;
    8.76 +    val low_ranking = 10000;
    8.77 +
    8.78 +    fun make_pattern crit = ProofContext.read_term_pattern ctxt ("_::" ^ crit)
    8.79 +                            |> type_of;
    8.80 +
    8.81 +    fun make_match (Strict arg) =
    8.82 +          let val qty = make_pattern arg; in
    8.83 +            fn (_, (ty, _)) => let
    8.84 +                val tye = Sign.typ_match thy (qty, ty) Vartab.empty;
    8.85 +                val sub_size = Vartab.fold add_tye tye 0;
    8.86 +              in SOME sub_size end handle MATCH => NONE
    8.87 +          end
    8.88 +
    8.89 +      | make_match (Loose arg) =
    8.90 +          check_const (matches_subtype thy (make_pattern arg) o snd)
    8.91 +      
    8.92 +      | make_match (Name arg) = check_const (match_string arg o fst);
    8.93 +
    8.94 +    fun make_criterion (b, crit) = (if b then I else opt_not) (make_match crit);
    8.95 +    val criteria = map make_criterion ((!default_criteria) @ raw_criteria);
    8.96 +
    8.97 +    val (_, consts) = (#constants o Consts.dest o Sign.consts_of) thy;
    8.98 +    fun eval_entry c = foldl filter_const (SOME (c, low_ranking)) criteria;
    8.99 +
   8.100 +    val matches = Symtab.fold (cons o eval_entry) consts []
   8.101 +                  |> map_filter I
   8.102 +                  |> sort (rev_order o int_ord o pairself snd)
   8.103 +                  |> map ((apsnd fst) o fst);
   8.104 +
   8.105 +    val end_msg = " in " ^
   8.106 +                  (List.nth (String.tokens Char.isSpace (end_timing start), 3))
   8.107 +                  ^ " secs"
   8.108 +  in
   8.109 +    Pretty.big_list "searched for:" (map pretty_criterion raw_criteria)
   8.110 +      :: Pretty.str ""
   8.111 +      :: (Pretty.str o concat)
   8.112 +           (if null matches
   8.113 +            then ["nothing found", end_msg]
   8.114 +            else ["found ", (string_of_int o length) matches,
   8.115 +                  " constants", end_msg, ":"])
   8.116 +      :: Pretty.str ""
   8.117 +      :: map (pretty_const ctxt) matches
   8.118 +    |> Pretty.chunks
   8.119 +    |> Pretty.writeln
   8.120 +  end handle ERROR s => Output.error_msg s
   8.121 +
   8.122 +
   8.123 +
   8.124 +(** command syntax **)
   8.125 +
   8.126 +fun find_consts_cmd spec =
   8.127 +  Toplevel.unknown_theory o Toplevel.keep (fn state =>
   8.128 +    find_consts (Proof.context_of (Toplevel.enter_proof_body state)) spec);
   8.129 +
   8.130 +local
   8.131 +
   8.132 +structure P = OuterParse and K = OuterKeyword;
   8.133 +
   8.134 +val criterion =
   8.135 +  P.reserved "strict" |-- P.!!! (P.$$$ ":" |-- P.xname) >> Strict ||
   8.136 +  P.reserved "name" |-- P.!!! (P.$$$ ":" |-- P.xname) >> Name ||
   8.137 +  P.xname >> Loose;
   8.138 +
   8.139 +in
   8.140 +
   8.141 +val _ =
   8.142 +  OuterSyntax.improper_command "find_consts" "search constants by type pattern" K.diag
   8.143 +    (Scan.repeat (((Scan.option P.minus >> is_none) -- criterion))
   8.144 +      >> (Toplevel.no_timing oo find_consts_cmd));
   8.145 +
   8.146 +end;
   8.147 +
   8.148 +end;
   8.149 +
     9.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     9.2 +++ b/src/Pure/Tools/find_theorems.ML	Fri Feb 27 15:46:22 2009 +0100
     9.3 @@ -0,0 +1,422 @@
     9.4 +(*  Title:      Pure/Isar/find_theorems.ML
     9.5 +    Author:     Rafal Kolanski and Gerwin Klein, NICTA
     9.6 +
     9.7 +Retrieve theorems from proof context.
     9.8 +*)
     9.9 +
    9.10 +signature FIND_THEOREMS =
    9.11 +sig
    9.12 +  val limit: int ref
    9.13 +  val tac_limit: int ref
    9.14 +
    9.15 +  datatype 'term criterion =
    9.16 +    Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
    9.17 +    Pattern of 'term
    9.18 +
    9.19 +  val find_theorems: Proof.context -> thm option -> bool ->
    9.20 +    (bool * string criterion) list -> (Facts.ref * thm) list
    9.21 +
    9.22 +  val print_theorems: Proof.context -> thm option -> int option -> bool ->
    9.23 +    (bool * string criterion) list -> unit
    9.24 +end;
    9.25 +
    9.26 +structure FindTheorems: FIND_THEOREMS =
    9.27 +struct
    9.28 +
    9.29 +(** search criteria **)
    9.30 +
    9.31 +datatype 'term criterion =
    9.32 +  Name of string | Intro | Elim | Dest | Solves | Simp of 'term |
    9.33 +  Pattern of 'term;
    9.34 +
    9.35 +fun read_criterion _ (Name name) = Name name
    9.36 +  | read_criterion _ Intro = Intro
    9.37 +  | read_criterion _ Elim = Elim
    9.38 +  | read_criterion _ Dest = Dest
    9.39 +  | read_criterion _ Solves = Solves
    9.40 +  | read_criterion ctxt (Simp str) = Simp (ProofContext.read_term_pattern ctxt str)
    9.41 +  | read_criterion ctxt (Pattern str) = Pattern (ProofContext.read_term_pattern ctxt str);
    9.42 +
    9.43 +fun pretty_criterion ctxt (b, c) =
    9.44 +  let
    9.45 +    fun prfx s = if b then s else "-" ^ s;
    9.46 +  in
    9.47 +    (case c of
    9.48 +      Name name => Pretty.str (prfx "name: " ^ quote name)
    9.49 +    | Intro => Pretty.str (prfx "intro")
    9.50 +    | Elim => Pretty.str (prfx "elim")
    9.51 +    | Dest => Pretty.str (prfx "dest")
    9.52 +    | Solves => Pretty.str (prfx "solves")
    9.53 +    | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
    9.54 +        Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
    9.55 +    | Pattern pat => Pretty.enclose (prfx " \"") "\""
    9.56 +        [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
    9.57 +  end;
    9.58 +
    9.59 +
    9.60 +
    9.61 +(** search criterion filters **)
    9.62 +
    9.63 +(*generated filters are to be of the form
    9.64 +  input: (Facts.ref * thm)
    9.65 +  output: (p:int, s:int) option, where
    9.66 +    NONE indicates no match
    9.67 +    p is the primary sorting criterion
    9.68 +      (eg. number of assumptions in the theorem)
    9.69 +    s is the secondary sorting criterion
    9.70 +      (eg. size of the substitution for intro, elim and dest)
    9.71 +  when applying a set of filters to a thm, fold results in:
    9.72 +    (biggest p, sum of all s)
    9.73 +  currently p and s only matter for intro, elim, dest and simp filters,
    9.74 +  otherwise the default ordering is used.
    9.75 +*)
    9.76 +
    9.77 +
    9.78 +(* matching theorems *)
    9.79 +
    9.80 +fun is_nontrivial thy = Term.is_Const o Term.head_of o ObjectLogic.drop_judgment thy;
    9.81 +
    9.82 +(*extract terms from term_src, refine them to the parts that concern us,
    9.83 +  if po try match them against obj else vice versa.
    9.84 +  trivial matches are ignored.
    9.85 +  returns: smallest substitution size*)
    9.86 +fun is_matching_thm (extract_terms, refine_term) ctxt po obj term_src =
    9.87 +  let
    9.88 +    val thy = ProofContext.theory_of ctxt;
    9.89 +
    9.90 +    fun matches pat =
    9.91 +      is_nontrivial thy pat andalso
    9.92 +      Pattern.matches thy (if po then (pat, obj) else (obj, pat));
    9.93 +
    9.94 +    fun substsize pat =
    9.95 +      let val (_, subst) =
    9.96 +        Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
    9.97 +      in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
    9.98 +
    9.99 +    fun bestmatch [] = NONE
   9.100 +     |  bestmatch xs = SOME (foldr1 Int.min xs);
   9.101 +
   9.102 +    val match_thm = matches o refine_term;
   9.103 +  in
   9.104 +    map (substsize o refine_term) (filter match_thm (extract_terms term_src))
   9.105 +    |> bestmatch
   9.106 +  end;
   9.107 +
   9.108 +
   9.109 +(* filter_name *)
   9.110 +
   9.111 +fun filter_name str_pat (thmref, _) =
   9.112 +  if match_string str_pat (Facts.name_of_ref thmref)
   9.113 +  then SOME (0, 0) else NONE;
   9.114 +
   9.115 +
   9.116 +(* filter intro/elim/dest/solves rules *)
   9.117 +
   9.118 +fun filter_dest ctxt goal (_, thm) =
   9.119 +  let
   9.120 +    val extract_dest =
   9.121 +     (fn thm => if Thm.no_prems thm then [] else [Thm.full_prop_of thm],
   9.122 +      hd o Logic.strip_imp_prems);
   9.123 +    val prems = Logic.prems_of_goal goal 1;
   9.124 +
   9.125 +    fun try_subst prem = is_matching_thm extract_dest ctxt true prem thm;
   9.126 +    val successful = prems |> map_filter try_subst;
   9.127 +  in
   9.128 +    (*if possible, keep best substitution (one with smallest size)*)
   9.129 +    (*dest rules always have assumptions, so a dest with one
   9.130 +      assumption is as good as an intro rule with none*)
   9.131 +    if not (null successful)
   9.132 +    then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
   9.133 +  end;
   9.134 +
   9.135 +fun filter_intro ctxt goal (_, thm) =
   9.136 +  let
   9.137 +    val extract_intro = (single o Thm.full_prop_of, Logic.strip_imp_concl);
   9.138 +    val concl = Logic.concl_of_goal goal 1;
   9.139 +    val ss = is_matching_thm extract_intro ctxt true concl thm;
   9.140 +  in
   9.141 +    if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
   9.142 +  end;
   9.143 +
   9.144 +fun filter_elim ctxt goal (_, thm) =
   9.145 +  if not (Thm.no_prems thm) then
   9.146 +    let
   9.147 +      val rule = Thm.full_prop_of thm;
   9.148 +      val prems = Logic.prems_of_goal goal 1;
   9.149 +      val goal_concl = Logic.concl_of_goal goal 1;
   9.150 +      val rule_mp = hd (Logic.strip_imp_prems rule);
   9.151 +      val rule_concl = Logic.strip_imp_concl rule;
   9.152 +      fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);
   9.153 +      val rule_tree = combine rule_mp rule_concl;
   9.154 +      fun goal_tree prem = combine prem goal_concl;
   9.155 +      fun try_subst prem =
   9.156 +        is_matching_thm (single, I) ctxt true (goal_tree prem) rule_tree;
   9.157 +      val successful = prems |> map_filter try_subst;
   9.158 +    in
   9.159 +    (*elim rules always have assumptions, so an elim with one
   9.160 +      assumption is as good as an intro rule with none*)
   9.161 +      if is_nontrivial (ProofContext.theory_of ctxt) (Thm.major_prem_of thm)
   9.162 +        andalso not (null successful)
   9.163 +      then SOME (Thm.nprems_of thm - 1, foldr1 Int.min successful) else NONE
   9.164 +    end
   9.165 +  else NONE
   9.166 +
   9.167 +val tac_limit = ref 5;
   9.168 +
   9.169 +fun filter_solves ctxt goal = let
   9.170 +    val baregoal = Logic.get_goal (prop_of goal) 1;
   9.171 +
   9.172 +    fun etacn thm i = Seq.take (!tac_limit) o etac thm i;
   9.173 +    fun try_thm thm = if Thm.no_prems thm then rtac thm 1 goal
   9.174 +                      else (etacn thm THEN_ALL_NEW
   9.175 +                             (Goal.norm_hhf_tac THEN'
   9.176 +                               Method.assumption_tac ctxt)) 1 goal;
   9.177 +  in
   9.178 +    fn (_, thm) => if (is_some o Seq.pull o try_thm) thm
   9.179 +                   then SOME (Thm.nprems_of thm, 0) else NONE
   9.180 +  end;
   9.181 +
   9.182 +
   9.183 +(* filter_simp *)
   9.184 +
   9.185 +fun filter_simp ctxt t (_, thm) =
   9.186 +  let
   9.187 +    val (_, {mk_rews = {mk, ...}, ...}) =
   9.188 +      Simplifier.rep_ss (Simplifier.local_simpset_of ctxt);
   9.189 +    val extract_simp =
   9.190 +      (map Thm.full_prop_of o mk, #1 o Logic.dest_equals o Logic.strip_imp_concl);
   9.191 +    val ss = is_matching_thm extract_simp ctxt false t thm
   9.192 +  in
   9.193 +    if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
   9.194 +  end;
   9.195 +
   9.196 +
   9.197 +(* filter_pattern *)
   9.198 +
   9.199 +fun get_names t = (Term.add_const_names t []) union (Term.add_free_names t []);
   9.200 +fun get_thm_names (_, thm) = get_names (Thm.full_prop_of thm);
   9.201 +  (* Including all constants and frees is only sound because
   9.202 +     matching uses higher-order patterns. If full matching
   9.203 +     were used, then constants that may be subject to
   9.204 +     beta-reduction after substitution of frees should
   9.205 +     not be included for LHS set because they could be
   9.206 +     thrown away by the substituted function.
   9.207 +     e.g. for (?F 1 2) do not include 1 or 2, if it were
   9.208 +          possible for ?F to be (% x y. 3)
   9.209 +     The largest possible set should always be included on
   9.210 +     the RHS. *)
   9.211 +
   9.212 +fun filter_pattern ctxt pat = let
   9.213 +    val pat_consts = get_names pat;
   9.214 +
   9.215 +    fun check (t, NONE) = check (t, SOME (get_thm_names t))
   9.216 +      | check ((_, thm), c as SOME thm_consts) =
   9.217 +          (if pat_consts subset_string thm_consts
   9.218 +              andalso (Pattern.matches_subterm (ProofContext.theory_of ctxt)
   9.219 +                                               (pat, Thm.full_prop_of thm))
   9.220 +           then SOME (0, 0) else NONE, c);
   9.221 +  in check end;
   9.222 +
   9.223 +
   9.224 +(* interpret criteria as filters *)
   9.225 +
   9.226 +local
   9.227 +
   9.228 +fun err_no_goal c =
   9.229 +  error ("Current goal required for " ^ c ^ " search criterion");
   9.230 +
   9.231 +val fix_goal = Thm.prop_of;
   9.232 +val fix_goalo = Option.map fix_goal;
   9.233 +
   9.234 +fun filter_crit _ _ (Name name) = apfst (filter_name name)
   9.235 +  | filter_crit _ NONE Intro = err_no_goal "intro"
   9.236 +  | filter_crit _ NONE Elim = err_no_goal "elim"
   9.237 +  | filter_crit _ NONE Dest = err_no_goal "dest"
   9.238 +  | filter_crit _ NONE Solves = err_no_goal "solves"
   9.239 +  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt
   9.240 +                                                  (fix_goal goal))
   9.241 +  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt 
   9.242 +                                                  (fix_goal goal))
   9.243 +  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt
   9.244 +                                                  (fix_goal goal))
   9.245 +  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
   9.246 +  | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
   9.247 +  | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
   9.248 +
   9.249 +fun opt_not x = if is_some x then NONE else SOME (0, 0);
   9.250 +
   9.251 +fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
   9.252 +  | opt_add _ _ = NONE;
   9.253 +
   9.254 +fun app_filters thm = let
   9.255 +    fun app (NONE, _, _) = NONE
   9.256 +      | app (SOME v, consts, []) = SOME (v, thm)
   9.257 +      | app (r, consts, f::fs) = let val (r', consts') = f (thm, consts)
   9.258 +                                 in app (opt_add r r', consts', fs) end;
   9.259 +  in app end;
   9.260 +
   9.261 +in
   9.262 +
   9.263 +fun filter_criterion ctxt opt_goal (b, c) =
   9.264 +  (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
   9.265 +
   9.266 +fun all_filters filters thms =
   9.267 +  let
   9.268 +    fun eval_filters thm = app_filters thm (SOME (0, 0), NONE, filters);
   9.269 +
   9.270 +    (*filters return: (number of assumptions, substitution size) option, so
   9.271 +      sort (desc. in both cases) according to number of assumptions first,
   9.272 +      then by the substitution size*)
   9.273 +    fun thm_ord (((p0, s0), _), ((p1, s1), _)) =
   9.274 +      prod_ord int_ord int_ord ((p1, s1), (p0, s0));
   9.275 +  in map_filter eval_filters thms |> sort thm_ord |> map #2 end;
   9.276 +
   9.277 +end;
   9.278 +
   9.279 +
   9.280 +(* removing duplicates, preferring nicer names, roughly n log n *)
   9.281 +
   9.282 +local
   9.283 +
   9.284 +val index_ord = option_ord (K EQUAL);
   9.285 +val hidden_ord = bool_ord o pairself NameSpace.is_hidden;
   9.286 +val qual_ord = int_ord o pairself (length o NameSpace.explode);
   9.287 +val txt_ord = int_ord o pairself size;
   9.288 +
   9.289 +fun nicer_name (x, i) (y, j) =
   9.290 +  (case hidden_ord (x, y) of EQUAL =>
   9.291 +    (case index_ord (i, j) of EQUAL =>
   9.292 +      (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
   9.293 +    | ord => ord)
   9.294 +  | ord => ord) <> GREATER;
   9.295 +
   9.296 +fun rem_cdups nicer xs =
   9.297 +  let
   9.298 +    fun rem_c rev_seen [] = rev rev_seen
   9.299 +      | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
   9.300 +      | rem_c rev_seen ((x as ((n, t), _)) :: (y as ((n', t'), _)) :: xs) =
   9.301 +        if Thm.eq_thm_prop (t, t')
   9.302 +        then rem_c rev_seen ((if nicer n n' then x else y) :: xs)
   9.303 +        else rem_c (x :: rev_seen) (y :: xs)
   9.304 +  in rem_c [] xs end;
   9.305 +
   9.306 +in
   9.307 +
   9.308 +fun nicer_shortest ctxt = let
   9.309 +    val ns = ProofContext.theory_of ctxt
   9.310 +             |> PureThy.facts_of
   9.311 +             |> Facts.space_of;
   9.312 +
   9.313 +    val len_sort = sort (int_ord o (pairself size));
   9.314 +    fun shorten s = (case len_sort (NameSpace.get_accesses ns s) of
   9.315 +                       [] => s
   9.316 +                     | s'::_ => s');
   9.317 +
   9.318 +    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
   9.319 +          nicer_name (shorten x, i) (shorten y, j)
   9.320 +      | nicer (Facts.Fact _) (Facts.Named _) = true
   9.321 +      | nicer (Facts.Named _) (Facts.Fact _) = false;
   9.322 +  in nicer end;
   9.323 +
   9.324 +fun rem_thm_dups nicer xs =
   9.325 +  xs ~~ (1 upto length xs)
   9.326 +  |> sort (TermOrd.fast_term_ord o pairself (Thm.prop_of o #2 o #1))
   9.327 +  |> rem_cdups nicer
   9.328 +  |> sort (int_ord o pairself #2)
   9.329 +  |> map #1;
   9.330 +
   9.331 +end;
   9.332 +
   9.333 +
   9.334 +(* print_theorems *)
   9.335 +
   9.336 +fun all_facts_of ctxt =
   9.337 +  maps Facts.selections
   9.338 +   (Facts.dest_static [] (PureThy.facts_of (ProofContext.theory_of ctxt)) @
   9.339 +    Facts.dest_static [] (ProofContext.facts_of ctxt));
   9.340 +
   9.341 +val limit = ref 40;
   9.342 +
   9.343 +fun find_theorems ctxt opt_goal rem_dups raw_criteria =
   9.344 +  let
   9.345 +    val add_prems = Seq.hd o (TRY (Method.insert_tac
   9.346 +                                     (Assumption.prems_of ctxt) 1));
   9.347 +    val opt_goal' = Option.map add_prems opt_goal;
   9.348 +
   9.349 +    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   9.350 +    val filters = map (filter_criterion ctxt opt_goal') criteria;
   9.351 +
   9.352 +    val raw_matches = all_filters filters (all_facts_of ctxt);
   9.353 +
   9.354 +    val matches =
   9.355 +      if rem_dups
   9.356 +      then rem_thm_dups (nicer_shortest ctxt) raw_matches
   9.357 +      else raw_matches;
   9.358 +  in matches end;
   9.359 +
   9.360 +fun print_theorems ctxt opt_goal opt_limit rem_dups raw_criteria = let
   9.361 +    val start = start_timing ();
   9.362 +
   9.363 +    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
   9.364 +    val matches = find_theorems ctxt opt_goal rem_dups raw_criteria;
   9.365 +
   9.366 +    val len = length matches;
   9.367 +    val lim = the_default (! limit) opt_limit;
   9.368 +    val thms = Library.drop (len - lim, matches);
   9.369 +
   9.370 +    val end_msg = " in " ^
   9.371 +                  (List.nth (String.tokens Char.isSpace (end_timing start), 3))
   9.372 +                  ^ " secs"
   9.373 +  in
   9.374 +    Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria)
   9.375 +        :: Pretty.str "" ::
   9.376 +     (if null thms then [Pretty.str ("nothing found" ^ end_msg)]
   9.377 +      else
   9.378 +        [Pretty.str ("found " ^ string_of_int len ^ " theorems" ^
   9.379 +          (if len <= lim then ""
   9.380 +           else " (" ^ string_of_int lim ^ " displayed)")
   9.381 +           ^ end_msg ^ ":"), Pretty.str ""] @
   9.382 +        map Display.pretty_fact thms)
   9.383 +    |> Pretty.chunks |> Pretty.writeln
   9.384 +  end;
   9.385 +
   9.386 +
   9.387 +
   9.388 +(** command syntax **)
   9.389 +
   9.390 +fun find_theorems_cmd ((opt_lim, rem_dups), spec) =
   9.391 +  Toplevel.unknown_theory o Toplevel.keep (fn state =>
   9.392 +  let
   9.393 +    val proof_state = Toplevel.enter_proof_body state;
   9.394 +    val ctxt = Proof.context_of proof_state;
   9.395 +    val opt_goal = try Proof.get_goal proof_state |> Option.map (#2 o #2);
   9.396 +  in print_theorems ctxt opt_goal opt_lim rem_dups spec end);
   9.397 +
   9.398 +local
   9.399 +
   9.400 +structure P = OuterParse and K = OuterKeyword;
   9.401 +
   9.402 +val criterion =
   9.403 +  P.reserved "name" |-- P.!!! (P.$$$ ":" |-- P.xname) >> Name ||
   9.404 +  P.reserved "intro" >> K Intro ||
   9.405 +  P.reserved "elim" >> K Elim ||
   9.406 +  P.reserved "dest" >> K Dest ||
   9.407 +  P.reserved "solves" >> K Solves ||
   9.408 +  P.reserved "simp" |-- P.!!! (P.$$$ ":" |-- P.term) >> Simp ||
   9.409 +  P.term >> Pattern;
   9.410 +
   9.411 +val options =
   9.412 +  Scan.optional
   9.413 +    (P.$$$ "(" |--
   9.414 +      P.!!! (Scan.option P.nat -- Scan.optional (P.reserved "with_dups" >> K false) true
   9.415 +        --| P.$$$ ")")) (NONE, true);
   9.416 +in
   9.417 +
   9.418 +val _ =
   9.419 +  OuterSyntax.improper_command "find_theorems" "print theorems meeting specified criteria" K.diag
   9.420 +    (options -- Scan.repeat (((Scan.option P.minus >> is_none) -- criterion))
   9.421 +      >> (Toplevel.no_timing oo find_theorems_cmd));
   9.422 +
   9.423 +end;
   9.424 +
   9.425 +end;