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