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