src/Pure/Tools/find_theorems.ML
author wenzelm
Wed Nov 26 20:05:34 2014 +0100 (2014-11-26)
changeset 59058 a78612c67ec0
parent 58928 23d0ffd48006
child 59083 88b0b1f28adc
permissions -rw-r--r--
renamed "pairself" to "apply2", in accordance to @{apply 2};
wenzelm@30143
     1
(*  Title:      Pure/Tools/find_theorems.ML
wenzelm@26283
     2
    Author:     Rafal Kolanski and Gerwin Klein, NICTA
wenzelm@46718
     3
    Author:     Lars Noschinski and Alexander Krauss, TU Muenchen
wenzelm@16033
     4
wenzelm@16033
     5
Retrieve theorems from proof context.
wenzelm@16033
     6
*)
wenzelm@16033
     7
wenzelm@16033
     8
signature FIND_THEOREMS =
wenzelm@16033
     9
sig
wenzelm@16036
    10
  datatype 'term criterion =
wenzelm@46717
    11
    Name of string | Intro | Elim | Dest | Solves | Simp of 'term | Pattern of 'term
krauss@43070
    12
  type 'term query = {
krauss@43070
    13
    goal: thm option,
krauss@43070
    14
    limit: int option,
krauss@43070
    15
    rem_dups: bool,
krauss@43070
    16
    criteria: (bool * 'term criterion) list
krauss@43070
    17
  }
wenzelm@52925
    18
  val read_query: Position.T -> string -> (bool * string criterion) list
Timothy@30785
    19
  val find_theorems: Proof.context -> thm option -> int option -> bool ->
krauss@43067
    20
    (bool * term criterion) list -> int option * (Facts.ref * thm) list
krauss@43067
    21
  val find_theorems_cmd: Proof.context -> thm option -> int option -> bool ->
Timothy@30785
    22
    (bool * string criterion) list -> int option * (Facts.ref * thm) list
wenzelm@30186
    23
  val pretty_thm: Proof.context -> Facts.ref * thm -> Pretty.T
wenzelm@16033
    24
end;
wenzelm@16033
    25
wenzelm@33301
    26
structure Find_Theorems: FIND_THEOREMS =
wenzelm@16033
    27
struct
wenzelm@16033
    28
wenzelm@16033
    29
(** search criteria **)
wenzelm@16033
    30
wenzelm@16036
    31
datatype 'term criterion =
wenzelm@46717
    32
  Name of string | Intro | Elim | Dest | Solves | Simp of 'term | Pattern of 'term;
wenzelm@16036
    33
kleing@33036
    34
fun apply_dummies tm =
wenzelm@33301
    35
  let
wenzelm@33301
    36
    val (xs, _) = Term.strip_abs tm;
wenzelm@33301
    37
    val tm' = Term.betapplys (tm, map (Term.dummy_pattern o #2) xs);
wenzelm@33301
    38
  in #1 (Term.replace_dummy_patterns tm' 1) end;
kleing@33036
    39
kleing@33036
    40
fun parse_pattern ctxt nm =
kleing@33036
    41
  let
wenzelm@42360
    42
    val consts = Proof_Context.consts_of ctxt;
wenzelm@33301
    43
    val nm' =
wenzelm@33301
    44
      (case Syntax.parse_term ctxt nm of
wenzelm@33301
    45
        Const (c, _) => c
wenzelm@33301
    46
      | _ => Consts.intern consts nm);
kleing@33036
    47
  in
wenzelm@33301
    48
    (case try (Consts.the_abbreviation consts) nm' of
wenzelm@42360
    49
      SOME (_, rhs) => apply_dummies (Proof_Context.expand_abbrevs ctxt rhs)
wenzelm@42360
    50
    | NONE => Proof_Context.read_term_pattern ctxt nm)
kleing@33036
    51
  end;
kleing@33036
    52
wenzelm@16036
    53
fun read_criterion _ (Name name) = Name name
wenzelm@16036
    54
  | read_criterion _ Intro = Intro
wenzelm@16036
    55
  | read_criterion _ Elim = Elim
wenzelm@16036
    56
  | read_criterion _ Dest = Dest
kleing@29857
    57
  | read_criterion _ Solves = Solves
wenzelm@42360
    58
  | read_criterion ctxt (Simp str) = Simp (Proof_Context.read_term_pattern ctxt str)
kleing@33036
    59
  | read_criterion ctxt (Pattern str) = Pattern (parse_pattern ctxt str);
wenzelm@16033
    60
wenzelm@16036
    61
fun pretty_criterion ctxt (b, c) =
wenzelm@16036
    62
  let
wenzelm@16036
    63
    fun prfx s = if b then s else "-" ^ s;
wenzelm@16036
    64
  in
wenzelm@16036
    65
    (case c of
wenzelm@16036
    66
      Name name => Pretty.str (prfx "name: " ^ quote name)
wenzelm@16036
    67
    | Intro => Pretty.str (prfx "intro")
wenzelm@16036
    68
    | Elim => Pretty.str (prfx "elim")
wenzelm@16036
    69
    | Dest => Pretty.str (prfx "dest")
kleing@29857
    70
    | Solves => Pretty.str (prfx "solves")
kleing@16088
    71
    | Simp pat => Pretty.block [Pretty.str (prfx "simp:"), Pretty.brk 1,
wenzelm@24920
    72
        Pretty.quote (Syntax.pretty_term ctxt (Term.show_dummy_patterns pat))]
wenzelm@56914
    73
    | Pattern pat => Pretty.enclose (prfx "\"") "\""
wenzelm@24920
    74
        [Syntax.pretty_term ctxt (Term.show_dummy_patterns pat)])
wenzelm@16036
    75
  end;
wenzelm@16033
    76
wenzelm@30142
    77
wenzelm@43620
    78
krauss@43070
    79
(** queries **)
krauss@43070
    80
krauss@43070
    81
type 'term query = {
krauss@43070
    82
  goal: thm option,
krauss@43070
    83
  limit: int option,
krauss@43070
    84
  rem_dups: bool,
krauss@43070
    85
  criteria: (bool * 'term criterion) list
krauss@43070
    86
};
krauss@43070
    87
krauss@43070
    88
fun map_criteria f {goal, limit, rem_dups, criteria} =
wenzelm@46718
    89
  {goal = goal, limit = limit, rem_dups = rem_dups, criteria = f criteria};
krauss@43070
    90
wenzelm@43620
    91
wenzelm@16033
    92
(** search criterion filters **)
wenzelm@16033
    93
kleing@16895
    94
(*generated filters are to be of the form
wenzelm@55671
    95
  input: (Facts.ref * thm)
kleing@53632
    96
  output: (p:int, s:int, t:int) option, where
kleing@16895
    97
    NONE indicates no match
wenzelm@17106
    98
    p is the primary sorting criterion
kleing@53632
    99
      (eg. size of term)
kleing@53632
   100
    s is the secondary sorting criterion
kleing@16895
   101
      (eg. number of assumptions in the theorem)
kleing@53632
   102
    t is the tertiary sorting criterion
kleing@16895
   103
      (eg. size of the substitution for intro, elim and dest)
kleing@16895
   104
  when applying a set of filters to a thm, fold results in:
kleing@53632
   105
    (max p, max s, sum of all t)
kleing@16895
   106
*)
kleing@16895
   107
kleing@16088
   108
kleing@16088
   109
(* matching theorems *)
wenzelm@17106
   110
wenzelm@35625
   111
fun is_nontrivial thy = Term.is_Const o Term.head_of o Object_Logic.drop_judgment thy;
kleing@16088
   112
kleing@16964
   113
(*extract terms from term_src, refine them to the parts that concern us,
kleing@16964
   114
  if po try match them against obj else vice versa.
kleing@16964
   115
  trivial matches are ignored.
kleing@16964
   116
  returns: smallest substitution size*)
wenzelm@46717
   117
fun is_matching_thm (extract_terms, refine_term) ctxt po obj term_src =
kleing@16088
   118
  let
wenzelm@42360
   119
    val thy = Proof_Context.theory_of ctxt;
kleing@16088
   120
wenzelm@16486
   121
    fun matches pat =
wenzelm@46717
   122
      is_nontrivial thy pat andalso
wenzelm@46717
   123
      Pattern.matches thy (if po then (pat, obj) else (obj, pat));
kleing@16895
   124
wenzelm@52940
   125
    fun subst_size pat =
wenzelm@18184
   126
      let val (_, subst) =
wenzelm@18184
   127
        Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
wenzelm@17205
   128
      in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
kleing@16088
   129
wenzelm@52941
   130
    fun best_match [] = NONE
wenzelm@52941
   131
      | best_match xs = SOME (foldl1 Int.min xs);
kleing@16895
   132
kleing@16964
   133
    val match_thm = matches o refine_term;
wenzelm@16486
   134
  in
wenzelm@52940
   135
    map (subst_size o refine_term) (filter match_thm (extract_terms term_src))
wenzelm@52941
   136
    |> best_match
kleing@16088
   137
  end;
kleing@16088
   138
kleing@16088
   139
wenzelm@16033
   140
(* filter_name *)
wenzelm@16033
   141
wenzelm@55671
   142
fun filter_name str_pat (thmref, _) =
wenzelm@55671
   143
  if match_string str_pat (Facts.name_of_ref thmref)
kleing@53632
   144
  then SOME (0, 0, 0) else NONE;
wenzelm@16033
   145
wenzelm@30142
   146
kleing@29857
   147
(* filter intro/elim/dest/solves rules *)
wenzelm@16033
   148
wenzelm@55671
   149
fun filter_dest ctxt goal (_, thm) =
wenzelm@16033
   150
  let
kleing@16964
   151
    val extract_dest =
wenzelm@55671
   152
     (fn thm => if Thm.no_prems thm then [] else [Thm.full_prop_of thm],
wenzelm@16033
   153
      hd o Logic.strip_imp_prems);
wenzelm@16033
   154
    val prems = Logic.prems_of_goal goal 1;
kleing@16895
   155
wenzelm@55671
   156
    fun try_subst prem = is_matching_thm extract_dest ctxt true prem thm;
wenzelm@19482
   157
    val successful = prems |> map_filter try_subst;
wenzelm@16033
   158
  in
kleing@16895
   159
    (*if possible, keep best substitution (one with smallest size)*)
wenzelm@17106
   160
    (*dest rules always have assumptions, so a dest with one
kleing@16895
   161
      assumption is as good as an intro rule with none*)
wenzelm@55671
   162
    if not (null successful) then
wenzelm@55671
   163
      SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm - 1, foldl1 Int.min successful)
wenzelm@55671
   164
    else NONE
wenzelm@16033
   165
  end;
wenzelm@16033
   166
wenzelm@55671
   167
fun filter_intro ctxt goal (_, thm) =
wenzelm@16033
   168
  let
wenzelm@55671
   169
    val extract_intro = (single o Thm.full_prop_of, Logic.strip_imp_concl);
wenzelm@16036
   170
    val concl = Logic.concl_of_goal goal 1;
wenzelm@16033
   171
  in
wenzelm@55671
   172
    (case is_matching_thm extract_intro ctxt true concl thm of
wenzelm@55671
   173
      SOME ss => SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm, ss)
wenzelm@55671
   174
    | NONE => NONE)
wenzelm@16033
   175
  end;
wenzelm@16033
   176
wenzelm@55671
   177
fun filter_elim ctxt goal (_, thm) =
wenzelm@55671
   178
  if Thm.nprems_of thm > 0 then
kleing@16964
   179
    let
wenzelm@55671
   180
      val rule = Thm.full_prop_of thm;
kleing@16964
   181
      val prems = Logic.prems_of_goal goal 1;
kleing@16964
   182
      val goal_concl = Logic.concl_of_goal goal 1;
wenzelm@26283
   183
      val rule_mp = hd (Logic.strip_imp_prems rule);
kleing@16964
   184
      val rule_concl = Logic.strip_imp_concl rule;
wenzelm@57690
   185
      fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);  (* FIXME ?!? *)
kleing@16964
   186
      val rule_tree = combine rule_mp rule_concl;
wenzelm@26283
   187
      fun goal_tree prem = combine prem goal_concl;
wenzelm@46717
   188
      fun try_subst prem = is_matching_thm (single, I) ctxt true (goal_tree prem) rule_tree;
wenzelm@19482
   189
      val successful = prems |> map_filter try_subst;
kleing@16964
   190
    in
wenzelm@32798
   191
      (*elim rules always have assumptions, so an elim with one
wenzelm@32798
   192
        assumption is as good as an intro rule with none*)
wenzelm@55671
   193
      if is_nontrivial (Proof_Context.theory_of ctxt) (Thm.major_prem_of thm)
wenzelm@55671
   194
          andalso not (null successful) then
wenzelm@55671
   195
        SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm - 1, foldl1 Int.min successful)
wenzelm@55671
   196
      else NONE
kleing@16964
   197
    end
wenzelm@46718
   198
  else NONE;
wenzelm@16036
   199
wenzelm@30143
   200
fun filter_solves ctxt goal =
wenzelm@30143
   201
  let
wenzelm@52704
   202
    val thy' =
wenzelm@52704
   203
      Proof_Context.theory_of ctxt
wenzelm@52788
   204
      |> Context_Position.set_visible_global (Context_Position.is_visible ctxt);
wenzelm@52704
   205
    val ctxt' = Proof_Context.transfer thy' ctxt;
wenzelm@52704
   206
    val goal' = Thm.transfer thy' goal;
wenzelm@52704
   207
wenzelm@52941
   208
    fun limited_etac thm i =
wenzelm@58837
   209
      Seq.take (Options.default_int @{system_option find_theorems_tactic_limit}) o
wenzelm@58837
   210
        eresolve_tac [thm] i;
wenzelm@30143
   211
    fun try_thm thm =
wenzelm@58837
   212
      if Thm.no_prems thm then resolve_tac [thm] 1 goal'
wenzelm@54742
   213
      else
wenzelm@54742
   214
        (limited_etac thm THEN_ALL_NEW (Goal.norm_hhf_tac ctxt' THEN' Method.assm_tac ctxt'))
wenzelm@54742
   215
          1 goal';
kleing@29857
   216
  in
wenzelm@55671
   217
    fn (_, thm) =>
wenzelm@55671
   218
      if is_some (Seq.pull (try_thm thm))
wenzelm@55671
   219
      then SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm, 0)
wenzelm@55671
   220
      else NONE
kleing@29857
   221
  end;
wenzelm@16033
   222
wenzelm@30142
   223
kleing@16074
   224
(* filter_simp *)
wenzelm@16033
   225
wenzelm@55671
   226
fun filter_simp ctxt t (_, thm) =
wenzelm@55671
   227
  let
wenzelm@55671
   228
    val mksimps = Simplifier.mksimps ctxt;
wenzelm@55671
   229
    val extract_simp =
wenzelm@55671
   230
      (map Thm.full_prop_of o mksimps, #1 o Logic.dest_equals o Logic.strip_imp_concl);
wenzelm@55671
   231
  in
wenzelm@55671
   232
    (case is_matching_thm extract_simp ctxt false t thm of
wenzelm@55671
   233
      SOME ss => SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm, ss)
wenzelm@55671
   234
    | NONE => NONE)
wenzelm@55671
   235
  end;
wenzelm@16033
   236
wenzelm@16033
   237
wenzelm@16033
   238
(* filter_pattern *)
wenzelm@16033
   239
wenzelm@32798
   240
fun get_names t = Term.add_const_names t (Term.add_free_names t []);
kleing@28900
   241
wenzelm@52940
   242
(*Including all constants and frees is only sound because matching
wenzelm@52940
   243
  uses higher-order patterns. If full matching were used, then
wenzelm@52940
   244
  constants that may be subject to beta-reduction after substitution
wenzelm@52940
   245
  of frees should not be included for LHS set because they could be
wenzelm@52940
   246
  thrown away by the substituted function.  E.g. for (?F 1 2) do not
wenzelm@52940
   247
  include 1 or 2, if it were possible for ?F to be (%x y. 3).  The
wenzelm@52940
   248
  largest possible set should always be included on the RHS.*)
wenzelm@30143
   249
wenzelm@30143
   250
fun filter_pattern ctxt pat =
wenzelm@30143
   251
  let
kleing@29857
   252
    val pat_consts = get_names pat;
kleing@28900
   253
wenzelm@55671
   254
    fun check ((x, thm), NONE) = check ((x, thm), SOME (get_names (Thm.full_prop_of thm)))
wenzelm@55671
   255
      | check ((_, thm), c as SOME thm_consts) =
haftmann@33038
   256
         (if subset (op =) (pat_consts, thm_consts) andalso
wenzelm@55671
   257
            Pattern.matches_subterm (Proof_Context.theory_of ctxt) (pat, Thm.full_prop_of thm)
wenzelm@55671
   258
          then SOME (size_of_term (Thm.prop_of thm), Thm.nprems_of thm, 0) else NONE, c);
kleing@28900
   259
  in check end;
wenzelm@16033
   260
wenzelm@30142
   261
wenzelm@16033
   262
(* interpret criteria as filters *)
wenzelm@16033
   263
wenzelm@16036
   264
local
wenzelm@16036
   265
wenzelm@16036
   266
fun err_no_goal c =
wenzelm@16036
   267
  error ("Current goal required for " ^ c ^ " search criterion");
wenzelm@16036
   268
kleing@28900
   269
fun filter_crit _ _ (Name name) = apfst (filter_name name)
wenzelm@16036
   270
  | filter_crit _ NONE Intro = err_no_goal "intro"
wenzelm@16036
   271
  | filter_crit _ NONE Elim = err_no_goal "elim"
wenzelm@16036
   272
  | filter_crit _ NONE Dest = err_no_goal "dest"
kleing@29857
   273
  | filter_crit _ NONE Solves = err_no_goal "solves"
wenzelm@52940
   274
  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt (Thm.prop_of goal))
wenzelm@52940
   275
  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (Thm.prop_of goal))
wenzelm@52940
   276
  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (Thm.prop_of goal))
kleing@29857
   277
  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
kleing@28900
   278
  | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
kleing@16088
   279
  | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
wenzelm@16036
   280
kleing@53632
   281
fun opt_not x = if is_some x then NONE else SOME (0, 0, 0);
kleing@16895
   282
kleing@53632
   283
fun opt_add (SOME (a, c, x)) (SOME (b, d, y)) = SOME (Int.max (a,b), Int.max (c, d), x + y : int)
wenzelm@26283
   284
  | opt_add _ _ = NONE;
kleing@16895
   285
wenzelm@30143
   286
fun app_filters thm =
wenzelm@30143
   287
  let
kleing@28900
   288
    fun app (NONE, _, _) = NONE
wenzelm@32798
   289
      | app (SOME v, _, []) = SOME (v, thm)
wenzelm@30143
   290
      | app (r, consts, f :: fs) =
wenzelm@30143
   291
          let val (r', consts') = f (thm, consts)
wenzelm@30143
   292
          in app (opt_add r r', consts', fs) end;
kleing@28900
   293
  in app end;
kleing@28900
   294
wenzelm@16036
   295
in
wenzelm@16033
   296
wenzelm@16033
   297
fun filter_criterion ctxt opt_goal (b, c) =
kleing@28900
   298
  (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
kleing@16895
   299
wenzelm@55671
   300
fun sorted_filter filters thms =
kleing@16895
   301
  let
wenzelm@55671
   302
    fun eval_filters thm = app_filters thm (SOME (0, 0, 0), NONE, filters);
wenzelm@16033
   303
kleing@53632
   304
    (*filters return: (thm size, number of assumptions, substitution size) option, so
kleing@53632
   305
      sort according to size of thm first, then number of assumptions,
kleing@53632
   306
      then by the substitution size, then by term order *)
wenzelm@55671
   307
    fun result_ord (((p0, s0, t0), (_, thm0)), ((p1, s1, t1), (_, thm1))) =
wenzelm@55671
   308
      prod_ord int_ord (prod_ord int_ord (prod_ord int_ord Term_Ord.term_ord))
wenzelm@55671
   309
         ((p1, (s1, (t1, Thm.full_prop_of thm1))), (p0, (s0, (t0, Thm.full_prop_of thm0))));
wenzelm@46977
   310
  in
wenzelm@55671
   311
    grouped 100 Par_List.map eval_filters thms
wenzelm@46977
   312
    |> map_filter I |> sort result_ord |> map #2
wenzelm@46977
   313
  end;
wenzelm@16033
   314
wenzelm@30822
   315
fun lazy_filter filters =
wenzelm@30822
   316
  let
Timothy@30785
   317
    fun lazy_match thms = Seq.make (fn () => first_match thms)
Timothy@30785
   318
    and first_match [] = NONE
wenzelm@30822
   319
      | first_match (thm :: thms) =
kleing@53632
   320
          (case app_filters thm (SOME (0, 0, 0), NONE, filters) of
Timothy@30785
   321
            NONE => first_match thms
wenzelm@30822
   322
          | SOME (_, t) => SOME (t, lazy_match thms));
Timothy@30785
   323
  in lazy_match end;
wenzelm@30822
   324
wenzelm@16036
   325
end;
wenzelm@16036
   326
wenzelm@16033
   327
wenzelm@52940
   328
(* removing duplicates, preferring nicer names, roughly O(n log n) *)
kleing@22340
   329
wenzelm@25226
   330
local
wenzelm@25226
   331
huffman@27486
   332
val index_ord = option_ord (K EQUAL);
wenzelm@59058
   333
val hidden_ord = bool_ord o apply2 Long_Name.is_hidden;
wenzelm@59058
   334
val qual_ord = int_ord o apply2 Long_Name.qualification;
wenzelm@59058
   335
val txt_ord = int_ord o apply2 size;
wenzelm@25226
   336
huffman@27486
   337
fun nicer_name (x, i) (y, j) =
huffman@27486
   338
  (case hidden_ord (x, y) of EQUAL =>
huffman@27486
   339
    (case index_ord (i, j) of EQUAL =>
huffman@27486
   340
      (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
huffman@27486
   341
    | ord => ord)
wenzelm@25226
   342
  | ord => ord) <> GREATER;
wenzelm@25226
   343
Timothy@29848
   344
fun rem_cdups nicer xs =
wenzelm@26336
   345
  let
wenzelm@26336
   346
    fun rem_c rev_seen [] = rev rev_seen
wenzelm@26336
   347
      | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
wenzelm@55671
   348
      | rem_c rev_seen ((x as ((n, thm), _)) :: (y as ((n', thm'), _)) :: rest) =
wenzelm@55671
   349
          if Thm.eq_thm_prop (thm, thm')
wenzelm@55671
   350
          then rem_c rev_seen ((if nicer n n' then x else y) :: rest)
wenzelm@55671
   351
          else rem_c (x :: rev_seen) (y :: rest);
wenzelm@26336
   352
  in rem_c [] xs end;
wenzelm@25226
   353
wenzelm@26336
   354
in
wenzelm@25226
   355
wenzelm@30143
   356
fun nicer_shortest ctxt =
wenzelm@30143
   357
  let
wenzelm@56143
   358
    fun extern_shortest name =
wenzelm@56143
   359
      Name_Space.extern_shortest ctxt
wenzelm@56143
   360
        (Facts.space_of (Proof_Context.facts_of_fact ctxt name)) name;
Timothy@29848
   361
Timothy@29848
   362
    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
wenzelm@55672
   363
          nicer_name (extern_shortest x, i) (extern_shortest y, j)
Timothy@29848
   364
      | nicer (Facts.Fact _) (Facts.Named _) = true
wenzelm@55670
   365
      | nicer (Facts.Named _) (Facts.Fact _) = false
wenzelm@55670
   366
      | nicer (Facts.Fact _) (Facts.Fact _) = true;
Timothy@29848
   367
  in nicer end;
Timothy@29848
   368
Timothy@29848
   369
fun rem_thm_dups nicer xs =
wenzelm@52940
   370
  (xs ~~ (1 upto length xs))
wenzelm@59058
   371
  |> sort (Term_Ord.fast_term_ord o apply2 (Thm.full_prop_of o #2 o #1))
Timothy@29848
   372
  |> rem_cdups nicer
wenzelm@59058
   373
  |> sort (int_ord o apply2 #2)
wenzelm@26336
   374
  |> map #1;
kleing@22340
   375
wenzelm@26336
   376
end;
kleing@22340
   377
kleing@22340
   378
wenzelm@52941
   379
wenzelm@52941
   380
(** main operations **)
wenzelm@52941
   381
wenzelm@52941
   382
(* filter_theorems *)
wenzelm@16033
   383
wenzelm@26283
   384
fun all_facts_of ctxt =
krauss@33381
   385
  let
wenzelm@56158
   386
    val local_facts = Proof_Context.facts_of ctxt;
wenzelm@56158
   387
    val global_facts = Global_Theory.facts_of (Proof_Context.theory_of ctxt);
wenzelm@56141
   388
  in
wenzelm@56141
   389
    maps Facts.selections
wenzelm@56159
   390
     (Facts.dest_static false [global_facts] local_facts @
wenzelm@56158
   391
      Facts.dest_static false [] global_facts)
wenzelm@56141
   392
  end;
wenzelm@17972
   393
krauss@43070
   394
fun filter_theorems ctxt theorems query =
wenzelm@16033
   395
  let
wenzelm@46718
   396
    val {goal = opt_goal, limit = opt_limit, rem_dups, criteria} = query;
krauss@43069
   397
    val filters = map (filter_criterion ctxt opt_goal) criteria;
wenzelm@16033
   398
krauss@41844
   399
    fun find_all theorems =
Timothy@30785
   400
      let
krauss@41844
   401
        val raw_matches = sorted_filter filters theorems;
Timothy@30785
   402
Timothy@30785
   403
        val matches =
Timothy@30785
   404
          if rem_dups
Timothy@30785
   405
          then rem_thm_dups (nicer_shortest ctxt) raw_matches
Timothy@30785
   406
          else raw_matches;
kleing@28900
   407
Timothy@30785
   408
        val len = length matches;
wenzelm@56467
   409
        val lim = the_default (Options.default_int @{system_option find_theorems_limit}) opt_limit;
haftmann@34088
   410
      in (SOME len, drop (Int.max (len - lim, 0)) matches) end;
Timothy@30785
   411
Timothy@30785
   412
    val find =
Timothy@30785
   413
      if rem_dups orelse is_none opt_limit
Timothy@30785
   414
      then find_all
wenzelm@30822
   415
      else pair NONE o Seq.list_of o Seq.take (the opt_limit) o lazy_filter filters;
Timothy@30785
   416
krauss@41844
   417
  in find theorems end;
kleing@29857
   418
wenzelm@46718
   419
fun filter_theorems_cmd ctxt theorems raw_query =
wenzelm@52941
   420
  filter_theorems ctxt theorems (map_criteria (map (apsnd (read_criterion ctxt))) raw_query);
wenzelm@52941
   421
wenzelm@52941
   422
wenzelm@52941
   423
(* find_theorems *)
wenzelm@52941
   424
wenzelm@52941
   425
local
krauss@43067
   426
krauss@43067
   427
fun gen_find_theorems filter ctxt opt_goal opt_limit rem_dups raw_criteria =
krauss@43069
   428
  let
krauss@43069
   429
    val assms =
krauss@43069
   430
      Proof_Context.get_fact ctxt (Facts.named "local.assms")
krauss@43069
   431
        handle ERROR _ => [];
krauss@43069
   432
    val add_prems = Seq.hd o TRY (Method.insert_tac assms 1);
krauss@43069
   433
    val opt_goal' = Option.map add_prems opt_goal;
krauss@43069
   434
  in
wenzelm@55671
   435
    filter ctxt (all_facts_of ctxt)
wenzelm@46718
   436
      {goal = opt_goal', limit = opt_limit, rem_dups = rem_dups, criteria = raw_criteria}
krauss@43069
   437
  end;
wenzelm@30186
   438
wenzelm@52941
   439
in
wenzelm@52941
   440
krauss@43067
   441
val find_theorems = gen_find_theorems filter_theorems;
krauss@43067
   442
val find_theorems_cmd = gen_find_theorems filter_theorems_cmd;
krauss@43067
   443
wenzelm@52941
   444
end;
wenzelm@52941
   445
wenzelm@52941
   446
wenzelm@52941
   447
(* pretty_theorems *)
wenzelm@52941
   448
wenzelm@52941
   449
local
wenzelm@52941
   450
wenzelm@49888
   451
fun pretty_ref ctxt thmref =
wenzelm@49888
   452
  let
wenzelm@49888
   453
    val (name, sel) =
wenzelm@49888
   454
      (case thmref of
wenzelm@49888
   455
        Facts.Named ((name, _), sel) => (name, sel)
wenzelm@49888
   456
      | Facts.Fact _ => raise Fail "Illegal literal fact");
wenzelm@49888
   457
  in
wenzelm@56141
   458
    [Pretty.mark (#1 (Proof_Context.markup_extern_fact ctxt name)) (Pretty.str name),
wenzelm@56141
   459
      Pretty.str (Facts.string_of_selection sel), Pretty.str ":", Pretty.brk 1]
wenzelm@49888
   460
  end;
wenzelm@49888
   461
wenzelm@52941
   462
in
wenzelm@52941
   463
wenzelm@55671
   464
fun pretty_thm ctxt (thmref, thm) =
wenzelm@55671
   465
  Pretty.block (pretty_ref ctxt thmref @ [Display.pretty_thm ctxt thm]);
krauss@41845
   466
wenzelm@52941
   467
fun pretty_theorems state opt_limit rem_dups raw_criteria =
wenzelm@30143
   468
  let
wenzelm@52941
   469
    val ctxt = Proof.context_of state;
wenzelm@52941
   470
    val opt_goal = try Proof.simple_goal state |> Option.map #goal;
kleing@29857
   471
    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
wenzelm@52941
   472
wenzelm@52940
   473
    val (opt_found, theorems) =
wenzelm@55671
   474
      filter_theorems ctxt (all_facts_of ctxt)
wenzelm@52855
   475
        {goal = opt_goal, limit = opt_limit, rem_dups = rem_dups, criteria = criteria};
krauss@41845
   476
    val returned = length theorems;
wenzelm@31684
   477
Timothy@30785
   478
    val tally_msg =
wenzelm@52940
   479
      (case opt_found of
wenzelm@38335
   480
        NONE => "displaying " ^ string_of_int returned ^ " theorem(s)"
wenzelm@30822
   481
      | SOME found =>
wenzelm@38335
   482
          "found " ^ string_of_int found ^ " theorem(s)" ^
wenzelm@30822
   483
            (if returned < found
wenzelm@30822
   484
             then " (" ^ string_of_int returned ^ " displayed)"
wenzelm@30822
   485
             else ""));
wenzelm@56912
   486
    val position_markup = Position.markup (Position.thread_data ()) Markup.position;
wenzelm@16033
   487
  in
wenzelm@56891
   488
    Pretty.block
wenzelm@56912
   489
      (Pretty.fbreaks
wenzelm@56912
   490
        (Pretty.mark position_markup (Pretty.keyword1 "find_theorems") ::
wenzelm@56912
   491
          map (pretty_criterion ctxt) criteria)) ::
wenzelm@38335
   492
    Pretty.str "" ::
wenzelm@56908
   493
    (if null theorems then [Pretty.str "found nothing"]
wenzelm@38335
   494
     else
wenzelm@56908
   495
       Pretty.str (tally_msg ^ ":") ::
wenzelm@56908
   496
       grouped 10 Par_List.map (Pretty.item o single o pretty_thm ctxt) (rev theorems))
wenzelm@52855
   497
  end |> Pretty.fbreaks |> curry Pretty.blk 0;
wenzelm@30142
   498
wenzelm@52941
   499
end;
wenzelm@30142
   500
wenzelm@32798
   501
wenzelm@46718
   502
wenzelm@52865
   503
(** Isar command syntax **)
wenzelm@30142
   504
wenzelm@52941
   505
fun proof_state st =
wenzelm@52941
   506
  (case try Toplevel.proof_of st of
wenzelm@52941
   507
    SOME state => state
wenzelm@52941
   508
  | NONE => Proof.init (Toplevel.context_of st));
wenzelm@52941
   509
wenzelm@30142
   510
local
wenzelm@30142
   511
wenzelm@30142
   512
val criterion =
wenzelm@36950
   513
  Parse.reserved "name" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.xname) >> Name ||
wenzelm@36950
   514
  Parse.reserved "intro" >> K Intro ||
wenzelm@36950
   515
  Parse.reserved "elim" >> K Elim ||
wenzelm@36950
   516
  Parse.reserved "dest" >> K Dest ||
wenzelm@36950
   517
  Parse.reserved "solves" >> K Solves ||
wenzelm@36950
   518
  Parse.reserved "simp" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.term) >> Simp ||
wenzelm@36950
   519
  Parse.term >> Pattern;
wenzelm@30142
   520
wenzelm@30142
   521
val options =
wenzelm@30142
   522
  Scan.optional
wenzelm@36950
   523
    (Parse.$$$ "(" |--
wenzelm@36950
   524
      Parse.!!! (Scan.option Parse.nat -- Scan.optional (Parse.reserved "with_dups" >> K false) true
wenzelm@36950
   525
        --| Parse.$$$ ")")) (NONE, true);
wenzelm@52855
   526
wenzelm@52925
   527
val query = Scan.repeat ((Scan.option Parse.minus >> is_none) -- criterion);
wenzelm@52855
   528
wenzelm@58928
   529
val query_keywords = Keyword.add_keywords [(":", NONE)] Keyword.empty_keywords;
wenzelm@58905
   530
wenzelm@30142
   531
in
wenzelm@30142
   532
wenzelm@52925
   533
fun read_query pos str =
wenzelm@58905
   534
  Outer_Syntax.scan query_keywords pos str
wenzelm@52855
   535
  |> filter Token.is_proper
wenzelm@52925
   536
  |> Scan.error (Scan.finite Token.stopper (Parse.!!! (query --| Scan.ahead Parse.eof)))
wenzelm@52925
   537
  |> #1;
krauss@43068
   538
wenzelm@30142
   539
val _ =
wenzelm@58893
   540
  Outer_Syntax.command @{command_spec "find_theorems"}
wenzelm@50214
   541
    "find theorems meeting specified criteria"
wenzelm@52925
   542
    (options -- query >> (fn ((opt_lim, rem_dups), spec) =>
wenzelm@52941
   543
      Toplevel.keep (fn st =>
wenzelm@52941
   544
        Pretty.writeln (pretty_theorems (proof_state st) opt_lim rem_dups spec))));
wenzelm@16033
   545
wenzelm@16033
   546
end;
wenzelm@30142
   547
wenzelm@52851
   548
wenzelm@52851
   549
wenzelm@52865
   550
(** PIDE query operation **)
wenzelm@52854
   551
wenzelm@52865
   552
val _ =
wenzelm@52982
   553
  Query_Operation.register "find_theorems" (fn {state = st, args, output_result} =>
wenzelm@52982
   554
    if can Toplevel.context_of st then
wenzelm@52982
   555
      let
wenzelm@56621
   556
        val [limit_arg, allow_dups_arg, query_arg] = args;
wenzelm@56621
   557
        val state = proof_state st;
wenzelm@52982
   558
        val opt_limit = Int.fromString limit_arg;
wenzelm@52982
   559
        val rem_dups = allow_dups_arg = "false";
wenzelm@52982
   560
        val criteria = read_query Position.none query_arg;
wenzelm@52982
   561
      in output_result (Pretty.string_of (pretty_theorems state opt_limit rem_dups criteria)) end
wenzelm@52982
   562
    else error "Unknown context");
wenzelm@52851
   563
wenzelm@30142
   564
end;