src/Pure/Tools/find_theorems.ML
author wenzelm
Fri Aug 09 17:25:47 2013 +0200 (2013-08-09)
changeset 52943 14ddcc0ad7df
parent 52942 07093b66fc9d
child 52954 b8b77a148ada
permissions -rw-r--r--
enable search in pre-loaded theory;
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@16036
    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@43620
    92
krauss@41845
    93
(** theorems, either internal or external (without proof) **)
krauss@41844
    94
krauss@41844
    95
datatype theorem =
krauss@41844
    96
  Internal of Facts.ref * thm |
krauss@43071
    97
  External of Facts.ref * term; (* FIXME: Facts.ref not appropriate *)
krauss@43071
    98
krauss@43071
    99
fun fact_ref_markup (Facts.Named ((name, pos), SOME [Facts.Single i])) =
krauss@43071
   100
      Position.markup pos o Markup.properties [("name", name), ("index", Markup.print_int i)]
krauss@43071
   101
  | fact_ref_markup (Facts.Named ((name, pos), NONE)) =
krauss@43071
   102
      Position.markup pos o Markup.properties [("name", name)]
wenzelm@43620
   103
  | fact_ref_markup fact_ref = raise Fail "bad fact ref";
krauss@43071
   104
krauss@41844
   105
fun prop_of (Internal (_, thm)) = Thm.full_prop_of thm
krauss@41844
   106
  | prop_of (External (_, prop)) = prop;
krauss@41844
   107
krauss@41844
   108
fun nprems_of (Internal (_, thm)) = Thm.nprems_of thm
krauss@41844
   109
  | nprems_of (External (_, prop)) = Logic.count_prems prop;
krauss@41844
   110
krauss@41844
   111
fun major_prem_of (Internal (_, thm)) = Thm.major_prem_of thm
krauss@41844
   112
  | major_prem_of (External (_, prop)) =
krauss@41844
   113
      Logic.strip_assums_concl (hd (Logic.strip_imp_prems prop));
krauss@41844
   114
krauss@41844
   115
fun fact_ref_of (Internal (fact_ref, _)) = fact_ref
krauss@41844
   116
  | fact_ref_of (External (fact_ref, _)) = fact_ref;
wenzelm@30142
   117
wenzelm@43620
   118
wenzelm@43620
   119
wenzelm@16033
   120
(** search criterion filters **)
wenzelm@16033
   121
kleing@16895
   122
(*generated filters are to be of the form
krauss@41844
   123
  input: theorem
wenzelm@17106
   124
  output: (p:int, s:int) option, where
kleing@16895
   125
    NONE indicates no match
wenzelm@17106
   126
    p is the primary sorting criterion
kleing@16895
   127
      (eg. number of assumptions in the theorem)
kleing@16895
   128
    s is the secondary sorting criterion
kleing@16895
   129
      (eg. size of the substitution for intro, elim and dest)
kleing@16895
   130
  when applying a set of filters to a thm, fold results in:
kleing@16895
   131
    (biggest p, sum of all s)
wenzelm@17106
   132
  currently p and s only matter for intro, elim, dest and simp filters,
wenzelm@17106
   133
  otherwise the default ordering is used.
kleing@16895
   134
*)
kleing@16895
   135
kleing@16088
   136
kleing@16088
   137
(* matching theorems *)
wenzelm@17106
   138
wenzelm@35625
   139
fun is_nontrivial thy = Term.is_Const o Term.head_of o Object_Logic.drop_judgment thy;
kleing@16088
   140
kleing@16964
   141
(*extract terms from term_src, refine them to the parts that concern us,
kleing@16964
   142
  if po try match them against obj else vice versa.
kleing@16964
   143
  trivial matches are ignored.
kleing@16964
   144
  returns: smallest substitution size*)
wenzelm@46717
   145
fun is_matching_thm (extract_terms, refine_term) ctxt po obj term_src =
kleing@16088
   146
  let
wenzelm@42360
   147
    val thy = Proof_Context.theory_of ctxt;
kleing@16088
   148
wenzelm@16486
   149
    fun matches pat =
wenzelm@46717
   150
      is_nontrivial thy pat andalso
wenzelm@46717
   151
      Pattern.matches thy (if po then (pat, obj) else (obj, pat));
kleing@16895
   152
wenzelm@52940
   153
    fun subst_size pat =
wenzelm@18184
   154
      let val (_, subst) =
wenzelm@18184
   155
        Pattern.match thy (if po then (pat, obj) else (obj, pat)) (Vartab.empty, Vartab.empty)
wenzelm@17205
   156
      in Vartab.fold (fn (_, (_, t)) => fn n => size_of_term t + n) subst 0 end;
kleing@16088
   157
wenzelm@52941
   158
    fun best_match [] = NONE
wenzelm@52941
   159
      | best_match xs = SOME (foldl1 Int.min xs);
kleing@16895
   160
kleing@16964
   161
    val match_thm = matches o refine_term;
wenzelm@16486
   162
  in
wenzelm@52940
   163
    map (subst_size o refine_term) (filter match_thm (extract_terms term_src))
wenzelm@52941
   164
    |> best_match
kleing@16088
   165
  end;
kleing@16088
   166
kleing@16088
   167
wenzelm@16033
   168
(* filter_name *)
wenzelm@16033
   169
krauss@41844
   170
fun filter_name str_pat theorem =
krauss@41844
   171
  if match_string str_pat (Facts.name_of_ref (fact_ref_of theorem))
wenzelm@17205
   172
  then SOME (0, 0) else NONE;
wenzelm@16033
   173
wenzelm@30142
   174
kleing@29857
   175
(* filter intro/elim/dest/solves rules *)
wenzelm@16033
   176
krauss@41844
   177
fun filter_dest ctxt goal theorem =
wenzelm@16033
   178
  let
kleing@16964
   179
    val extract_dest =
krauss@41844
   180
     (fn theorem => if nprems_of theorem = 0 then [] else [prop_of theorem],
wenzelm@16033
   181
      hd o Logic.strip_imp_prems);
wenzelm@16033
   182
    val prems = Logic.prems_of_goal goal 1;
kleing@16895
   183
wenzelm@46717
   184
    fun try_subst prem = is_matching_thm extract_dest ctxt true prem theorem;
wenzelm@19482
   185
    val successful = prems |> map_filter try_subst;
wenzelm@16033
   186
  in
kleing@16895
   187
    (*if possible, keep best substitution (one with smallest size)*)
wenzelm@17106
   188
    (*dest rules always have assumptions, so a dest with one
kleing@16895
   189
      assumption is as good as an intro rule with none*)
wenzelm@17205
   190
    if not (null successful)
krauss@41844
   191
    then SOME (nprems_of theorem - 1, foldl1 Int.min successful) else NONE
wenzelm@16033
   192
  end;
wenzelm@16033
   193
wenzelm@46717
   194
fun filter_intro ctxt goal theorem =
wenzelm@16033
   195
  let
krauss@41844
   196
    val extract_intro = (single o prop_of, Logic.strip_imp_concl);
wenzelm@16036
   197
    val concl = Logic.concl_of_goal goal 1;
wenzelm@46717
   198
    val ss = is_matching_thm extract_intro ctxt true concl theorem;
wenzelm@16033
   199
  in
krauss@41844
   200
    if is_some ss then SOME (nprems_of theorem, the ss) else NONE
wenzelm@16033
   201
  end;
wenzelm@16033
   202
krauss@41844
   203
fun filter_elim ctxt goal theorem =
krauss@41844
   204
  if nprems_of theorem > 0 then
kleing@16964
   205
    let
krauss@41844
   206
      val rule = prop_of theorem;
kleing@16964
   207
      val prems = Logic.prems_of_goal goal 1;
kleing@16964
   208
      val goal_concl = Logic.concl_of_goal goal 1;
wenzelm@26283
   209
      val rule_mp = hd (Logic.strip_imp_prems rule);
kleing@16964
   210
      val rule_concl = Logic.strip_imp_concl rule;
wenzelm@52941
   211
      fun combine t1 t2 = Const ("*combine*", dummyT --> dummyT) $ (t1 $ t2);  (* FIXME ?? *)
kleing@16964
   212
      val rule_tree = combine rule_mp rule_concl;
wenzelm@26283
   213
      fun goal_tree prem = combine prem goal_concl;
wenzelm@46717
   214
      fun try_subst prem = is_matching_thm (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*)
wenzelm@42360
   219
      if is_nontrivial (Proof_Context.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
wenzelm@46718
   223
  else NONE;
wenzelm@16036
   224
wenzelm@30143
   225
fun filter_solves ctxt goal =
wenzelm@30143
   226
  let
wenzelm@52704
   227
    val thy' =
wenzelm@52704
   228
      Proof_Context.theory_of ctxt
wenzelm@52788
   229
      |> Context_Position.set_visible_global (Context_Position.is_visible ctxt);
wenzelm@52704
   230
    val ctxt' = Proof_Context.transfer thy' ctxt;
wenzelm@52704
   231
    val goal' = Thm.transfer thy' goal;
wenzelm@52704
   232
wenzelm@52941
   233
    fun limited_etac thm i =
wenzelm@52702
   234
      Seq.take (Options.default_int @{option find_theorems_tac_limit}) o etac thm i;
wenzelm@30143
   235
    fun try_thm thm =
wenzelm@52704
   236
      if Thm.no_prems thm then rtac thm 1 goal'
wenzelm@52941
   237
      else (limited_etac thm THEN_ALL_NEW (Goal.norm_hhf_tac THEN' Method.assm_tac ctxt')) 1 goal';
kleing@29857
   238
  in
krauss@41844
   239
    fn Internal (_, thm) =>
wenzelm@43620
   240
        if is_some (Seq.pull (try_thm thm))
wenzelm@43620
   241
        then SOME (Thm.nprems_of thm, 0) else NONE
krauss@41844
   242
     | External _ => NONE
kleing@29857
   243
  end;
wenzelm@16033
   244
wenzelm@30142
   245
kleing@16074
   246
(* filter_simp *)
wenzelm@16033
   247
krauss@41844
   248
fun filter_simp ctxt t (Internal (_, thm)) =
krauss@41844
   249
      let
wenzelm@51717
   250
        val mksimps = Simplifier.mksimps ctxt;
krauss@41844
   251
        val extract_simp =
krauss@41844
   252
          (map Thm.full_prop_of o mksimps, #1 o Logic.dest_equals o Logic.strip_imp_concl);
wenzelm@46717
   253
        val ss = is_matching_thm extract_simp ctxt false t thm;
krauss@41844
   254
      in
krauss@41844
   255
        if is_some ss then SOME (Thm.nprems_of thm, the ss) else NONE
krauss@41844
   256
      end
krauss@41844
   257
  | filter_simp _ _ (External _) = NONE;
wenzelm@16033
   258
wenzelm@16033
   259
wenzelm@16033
   260
(* filter_pattern *)
wenzelm@16033
   261
wenzelm@32798
   262
fun get_names t = Term.add_const_names t (Term.add_free_names t []);
kleing@28900
   263
wenzelm@52940
   264
(*Including all constants and frees is only sound because matching
wenzelm@52940
   265
  uses higher-order patterns. If full matching were used, then
wenzelm@52940
   266
  constants that may be subject to beta-reduction after substitution
wenzelm@52940
   267
  of frees should not be included for LHS set because they could be
wenzelm@52940
   268
  thrown away by the substituted function.  E.g. for (?F 1 2) do not
wenzelm@52940
   269
  include 1 or 2, if it were possible for ?F to be (%x y. 3).  The
wenzelm@52940
   270
  largest possible set should always be included on the RHS.*)
wenzelm@30143
   271
wenzelm@30143
   272
fun filter_pattern ctxt pat =
wenzelm@30143
   273
  let
kleing@29857
   274
    val pat_consts = get_names pat;
kleing@28900
   275
krauss@41844
   276
    fun check (theorem, NONE) = check (theorem, SOME (get_names (prop_of theorem)))
krauss@41844
   277
      | check (theorem, c as SOME thm_consts) =
haftmann@33038
   278
         (if subset (op =) (pat_consts, thm_consts) andalso
wenzelm@42360
   279
            Pattern.matches_subterm (Proof_Context.theory_of ctxt) (pat, prop_of theorem)
wenzelm@32798
   280
          then SOME (0, 0) else NONE, c);
kleing@28900
   281
  in check end;
wenzelm@16033
   282
wenzelm@30142
   283
wenzelm@16033
   284
(* interpret criteria as filters *)
wenzelm@16033
   285
wenzelm@16036
   286
local
wenzelm@16036
   287
wenzelm@16036
   288
fun err_no_goal c =
wenzelm@16036
   289
  error ("Current goal required for " ^ c ^ " search criterion");
wenzelm@16036
   290
kleing@28900
   291
fun filter_crit _ _ (Name name) = apfst (filter_name name)
wenzelm@16036
   292
  | filter_crit _ NONE Intro = err_no_goal "intro"
wenzelm@16036
   293
  | filter_crit _ NONE Elim = err_no_goal "elim"
wenzelm@16036
   294
  | filter_crit _ NONE Dest = err_no_goal "dest"
kleing@29857
   295
  | filter_crit _ NONE Solves = err_no_goal "solves"
wenzelm@52940
   296
  | filter_crit ctxt (SOME goal) Intro = apfst (filter_intro ctxt (Thm.prop_of goal))
wenzelm@52940
   297
  | filter_crit ctxt (SOME goal) Elim = apfst (filter_elim ctxt (Thm.prop_of goal))
wenzelm@52940
   298
  | filter_crit ctxt (SOME goal) Dest = apfst (filter_dest ctxt (Thm.prop_of goal))
kleing@29857
   299
  | filter_crit ctxt (SOME goal) Solves = apfst (filter_solves ctxt goal)
kleing@28900
   300
  | filter_crit ctxt _ (Simp pat) = apfst (filter_simp ctxt pat)
kleing@16088
   301
  | filter_crit ctxt _ (Pattern pat) = filter_pattern ctxt pat;
wenzelm@16036
   302
wenzelm@19502
   303
fun opt_not x = if is_some x then NONE else SOME (0, 0);
kleing@16895
   304
wenzelm@17756
   305
fun opt_add (SOME (a, x)) (SOME (b, y)) = SOME (Int.max (a, b), x + y : int)
wenzelm@26283
   306
  | opt_add _ _ = NONE;
kleing@16895
   307
wenzelm@30143
   308
fun app_filters thm =
wenzelm@30143
   309
  let
kleing@28900
   310
    fun app (NONE, _, _) = NONE
wenzelm@32798
   311
      | app (SOME v, _, []) = SOME (v, thm)
wenzelm@30143
   312
      | app (r, consts, f :: fs) =
wenzelm@30143
   313
          let val (r', consts') = f (thm, consts)
wenzelm@30143
   314
          in app (opt_add r r', consts', fs) end;
kleing@28900
   315
  in app end;
kleing@28900
   316
wenzelm@16036
   317
in
wenzelm@16033
   318
wenzelm@16033
   319
fun filter_criterion ctxt opt_goal (b, c) =
kleing@28900
   320
  (if b then I else (apfst opt_not)) o filter_crit ctxt opt_goal c;
kleing@16895
   321
krauss@41844
   322
fun sorted_filter filters theorems =
kleing@16895
   323
  let
krauss@41844
   324
    fun eval_filters theorem = app_filters theorem (SOME (0, 0), NONE, filters);
wenzelm@16033
   325
kleing@16895
   326
    (*filters return: (number of assumptions, substitution size) option, so
kleing@16964
   327
      sort (desc. in both cases) according to number of assumptions first,
kleing@16895
   328
      then by the substitution size*)
krauss@41844
   329
    fun result_ord (((p0, s0), _), ((p1, s1), _)) =
wenzelm@17205
   330
      prod_ord int_ord int_ord ((p1, s1), (p0, s0));
wenzelm@46977
   331
  in
wenzelm@46977
   332
    grouped 100 Par_List.map eval_filters theorems
wenzelm@46977
   333
    |> map_filter I |> sort result_ord |> map #2
wenzelm@46977
   334
  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
    and first_match [] = NONE
wenzelm@30822
   340
      | first_match (thm :: thms) =
wenzelm@30822
   341
          (case app_filters thm (SOME (0, 0), NONE, filters) of
Timothy@30785
   342
            NONE => first_match thms
wenzelm@30822
   343
          | SOME (_, t) => SOME (t, lazy_match thms));
Timothy@30785
   344
  in lazy_match end;
wenzelm@30822
   345
wenzelm@16036
   346
end;
wenzelm@16036
   347
wenzelm@16033
   348
wenzelm@52940
   349
(* removing duplicates, preferring nicer names, roughly O(n log n) *)
kleing@22340
   350
wenzelm@25226
   351
local
wenzelm@25226
   352
huffman@27486
   353
val index_ord = option_ord (K EQUAL);
wenzelm@33095
   354
val hidden_ord = bool_ord o pairself Name_Space.is_hidden;
wenzelm@30364
   355
val qual_ord = int_ord o pairself (length o Long_Name.explode);
wenzelm@25226
   356
val txt_ord = int_ord o pairself size;
wenzelm@25226
   357
huffman@27486
   358
fun nicer_name (x, i) (y, j) =
huffman@27486
   359
  (case hidden_ord (x, y) of EQUAL =>
huffman@27486
   360
    (case index_ord (i, j) of EQUAL =>
huffman@27486
   361
      (case qual_ord (x, y) of EQUAL => txt_ord (x, y) | ord => ord)
huffman@27486
   362
    | ord => ord)
wenzelm@25226
   363
  | ord => ord) <> GREATER;
wenzelm@25226
   364
Timothy@29848
   365
fun rem_cdups nicer xs =
wenzelm@26336
   366
  let
wenzelm@26336
   367
    fun rem_c rev_seen [] = rev rev_seen
wenzelm@26336
   368
      | rem_c rev_seen [x] = rem_c (x :: rev_seen) []
krauss@41844
   369
      | rem_c rev_seen ((x as (t, _)) :: (y as (t', _)) :: xs) =
krauss@41844
   370
          if (prop_of t) aconv (prop_of t')
krauss@41844
   371
          then rem_c rev_seen ((if nicer (fact_ref_of t) (fact_ref_of t') then x else y) :: xs)
wenzelm@30822
   372
          else rem_c (x :: rev_seen) (y :: xs)
wenzelm@26336
   373
  in rem_c [] xs end;
wenzelm@25226
   374
wenzelm@26336
   375
in
wenzelm@25226
   376
wenzelm@30143
   377
fun nicer_shortest ctxt =
wenzelm@30143
   378
  let
wenzelm@46718
   379
    (* FIXME Why global name space!?? *)
wenzelm@42360
   380
    val space = Facts.space_of (Global_Theory.facts_of (Proof_Context.theory_of ctxt));
Timothy@29848
   381
wenzelm@30216
   382
    val shorten =
wenzelm@42358
   383
      Name_Space.extern
wenzelm@42358
   384
        (ctxt
wenzelm@42669
   385
          |> Config.put Name_Space.names_long false
wenzelm@42669
   386
          |> Config.put Name_Space.names_short false
wenzelm@42669
   387
          |> Config.put Name_Space.names_unique false) space;
Timothy@29848
   388
Timothy@29848
   389
    fun nicer (Facts.Named ((x, _), i)) (Facts.Named ((y, _), j)) =
Timothy@29848
   390
          nicer_name (shorten x, i) (shorten y, j)
Timothy@29848
   391
      | nicer (Facts.Fact _) (Facts.Named _) = true
Timothy@29848
   392
      | nicer (Facts.Named _) (Facts.Fact _) = false;
Timothy@29848
   393
  in nicer end;
Timothy@29848
   394
Timothy@29848
   395
fun rem_thm_dups nicer xs =
wenzelm@52940
   396
  (xs ~~ (1 upto length xs))
krauss@41844
   397
  |> sort (Term_Ord.fast_term_ord o pairself (prop_of o #1))
Timothy@29848
   398
  |> rem_cdups nicer
wenzelm@26336
   399
  |> sort (int_ord o pairself #2)
wenzelm@26336
   400
  |> map #1;
kleing@22340
   401
wenzelm@26336
   402
end;
kleing@22340
   403
kleing@22340
   404
wenzelm@52941
   405
wenzelm@52941
   406
(** main operations **)
wenzelm@52941
   407
wenzelm@52941
   408
(* filter_theorems *)
wenzelm@16033
   409
wenzelm@26283
   410
fun all_facts_of ctxt =
krauss@33381
   411
  let
wenzelm@33382
   412
    fun visible_facts facts =
wenzelm@33382
   413
      Facts.dest_static [] facts
wenzelm@33382
   414
      |> filter_out (Facts.is_concealed facts o #1);
krauss@33381
   415
  in
krauss@33381
   416
    maps Facts.selections
wenzelm@42360
   417
     (visible_facts (Global_Theory.facts_of (Proof_Context.theory_of ctxt)) @
wenzelm@42360
   418
      visible_facts (Proof_Context.facts_of ctxt))
krauss@33381
   419
  end;
wenzelm@17972
   420
krauss@43070
   421
fun filter_theorems ctxt theorems query =
wenzelm@16033
   422
  let
wenzelm@46718
   423
    val {goal = opt_goal, limit = opt_limit, rem_dups, criteria} = query;
krauss@43069
   424
    val filters = map (filter_criterion ctxt opt_goal) criteria;
wenzelm@16033
   425
krauss@41844
   426
    fun find_all theorems =
Timothy@30785
   427
      let
krauss@41844
   428
        val raw_matches = sorted_filter filters theorems;
Timothy@30785
   429
Timothy@30785
   430
        val matches =
Timothy@30785
   431
          if rem_dups
Timothy@30785
   432
          then rem_thm_dups (nicer_shortest ctxt) raw_matches
Timothy@30785
   433
          else raw_matches;
kleing@28900
   434
Timothy@30785
   435
        val len = length matches;
wenzelm@52702
   436
        val lim = the_default (Options.default_int @{option find_theorems_limit}) opt_limit;
haftmann@34088
   437
      in (SOME len, drop (Int.max (len - lim, 0)) matches) end;
Timothy@30785
   438
Timothy@30785
   439
    val find =
Timothy@30785
   440
      if rem_dups orelse is_none opt_limit
Timothy@30785
   441
      then find_all
wenzelm@30822
   442
      else pair NONE o Seq.list_of o Seq.take (the opt_limit) o lazy_filter filters;
Timothy@30785
   443
krauss@41844
   444
  in find theorems end;
kleing@29857
   445
wenzelm@46718
   446
fun filter_theorems_cmd ctxt theorems raw_query =
wenzelm@52941
   447
  filter_theorems ctxt theorems (map_criteria (map (apsnd (read_criterion ctxt))) raw_query);
wenzelm@52941
   448
wenzelm@52941
   449
wenzelm@52941
   450
(* find_theorems *)
wenzelm@52941
   451
wenzelm@52941
   452
local
krauss@43067
   453
krauss@43067
   454
fun gen_find_theorems filter ctxt opt_goal opt_limit rem_dups raw_criteria =
krauss@43069
   455
  let
krauss@43069
   456
    val assms =
krauss@43069
   457
      Proof_Context.get_fact ctxt (Facts.named "local.assms")
krauss@43069
   458
        handle ERROR _ => [];
krauss@43069
   459
    val add_prems = Seq.hd o TRY (Method.insert_tac assms 1);
krauss@43069
   460
    val opt_goal' = Option.map add_prems opt_goal;
krauss@43069
   461
  in
wenzelm@46718
   462
    filter ctxt (map Internal (all_facts_of ctxt))
wenzelm@46718
   463
      {goal = opt_goal', limit = opt_limit, rem_dups = rem_dups, criteria = raw_criteria}
krauss@43069
   464
    |> apsnd (map (fn Internal f => f))
krauss@43069
   465
  end;
wenzelm@30186
   466
wenzelm@52941
   467
in
wenzelm@52941
   468
krauss@43067
   469
val find_theorems = gen_find_theorems filter_theorems;
krauss@43067
   470
val find_theorems_cmd = gen_find_theorems filter_theorems_cmd;
krauss@43067
   471
wenzelm@52941
   472
end;
wenzelm@52941
   473
wenzelm@52941
   474
wenzelm@52941
   475
(* pretty_theorems *)
wenzelm@52941
   476
wenzelm@52941
   477
local
wenzelm@52941
   478
wenzelm@49888
   479
fun pretty_ref ctxt thmref =
wenzelm@49888
   480
  let
wenzelm@49888
   481
    val (name, sel) =
wenzelm@49888
   482
      (case thmref of
wenzelm@49888
   483
        Facts.Named ((name, _), sel) => (name, sel)
wenzelm@49888
   484
      | Facts.Fact _ => raise Fail "Illegal literal fact");
wenzelm@49888
   485
  in
wenzelm@49888
   486
    [Pretty.mark (Proof_Context.markup_fact ctxt name) (Pretty.str name),
wenzelm@49888
   487
      Pretty.str (Facts.string_of_selection sel), Pretty.str ":", Pretty.brk 1]
wenzelm@49888
   488
  end;
wenzelm@49888
   489
wenzelm@49888
   490
fun pretty_theorem ctxt (Internal (thmref, thm)) =
wenzelm@49888
   491
      Pretty.block (pretty_ref ctxt thmref @ [Display.pretty_thm ctxt thm])
wenzelm@49888
   492
  | pretty_theorem ctxt (External (thmref, prop)) =
wenzelm@49888
   493
      Pretty.block (pretty_ref ctxt thmref @ [Syntax.unparse_term ctxt prop]);
wenzelm@30186
   494
wenzelm@52941
   495
in
wenzelm@52941
   496
krauss@41845
   497
fun pretty_thm ctxt (thmref, thm) = pretty_theorem ctxt (Internal (thmref, thm));
krauss@41845
   498
wenzelm@52941
   499
fun pretty_theorems state opt_limit rem_dups raw_criteria =
wenzelm@30143
   500
  let
wenzelm@52941
   501
    val ctxt = Proof.context_of state;
wenzelm@52941
   502
    val opt_goal = try Proof.simple_goal state |> Option.map #goal;
kleing@29857
   503
    val criteria = map (apsnd (read_criterion ctxt)) raw_criteria;
wenzelm@52941
   504
wenzelm@52940
   505
    val (opt_found, theorems) =
wenzelm@52855
   506
      filter_theorems ctxt (map Internal (all_facts_of ctxt))
wenzelm@52855
   507
        {goal = opt_goal, limit = opt_limit, rem_dups = rem_dups, criteria = criteria};
krauss@41845
   508
    val returned = length theorems;
wenzelm@31684
   509
Timothy@30785
   510
    val tally_msg =
wenzelm@52940
   511
      (case opt_found of
wenzelm@38335
   512
        NONE => "displaying " ^ string_of_int returned ^ " theorem(s)"
wenzelm@30822
   513
      | SOME found =>
wenzelm@38335
   514
          "found " ^ string_of_int found ^ " theorem(s)" ^
wenzelm@30822
   515
            (if returned < found
wenzelm@30822
   516
             then " (" ^ string_of_int returned ^ " displayed)"
wenzelm@30822
   517
             else ""));
wenzelm@16033
   518
  in
wenzelm@38335
   519
    Pretty.big_list "searched for:" (map (pretty_criterion ctxt) criteria) ::
wenzelm@38335
   520
    Pretty.str "" ::
wenzelm@46716
   521
    (if null theorems then [Pretty.str "nothing found"]
wenzelm@38335
   522
     else
wenzelm@46716
   523
      [Pretty.str (tally_msg ^ ":"), Pretty.str ""] @
wenzelm@52927
   524
        grouped 10 Par_List.map (Pretty.item o single o pretty_theorem ctxt) theorems)
wenzelm@52855
   525
  end |> Pretty.fbreaks |> curry Pretty.blk 0;
wenzelm@30142
   526
wenzelm@52941
   527
end;
wenzelm@30142
   528
wenzelm@32798
   529
wenzelm@46718
   530
wenzelm@52865
   531
(** Isar command syntax **)
wenzelm@30142
   532
wenzelm@52941
   533
fun proof_state st =
wenzelm@52941
   534
  (case try Toplevel.proof_of st of
wenzelm@52941
   535
    SOME state => state
wenzelm@52941
   536
  | NONE => Proof.init (Toplevel.context_of st));
wenzelm@52941
   537
wenzelm@30142
   538
local
wenzelm@30142
   539
wenzelm@30142
   540
val criterion =
wenzelm@36950
   541
  Parse.reserved "name" |-- Parse.!!! (Parse.$$$ ":" |-- Parse.xname) >> Name ||
wenzelm@36950
   542
  Parse.reserved "intro" >> K Intro ||
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@52855
   554
wenzelm@52925
   555
val query = Scan.repeat ((Scan.option Parse.minus >> is_none) -- criterion);
wenzelm@52855
   556
wenzelm@30142
   557
in
wenzelm@30142
   558
wenzelm@52925
   559
fun read_query pos str =
wenzelm@52925
   560
  Outer_Syntax.scan pos str
wenzelm@52855
   561
  |> filter Token.is_proper
wenzelm@52925
   562
  |> Scan.error (Scan.finite Token.stopper (Parse.!!! (query --| Scan.ahead Parse.eof)))
wenzelm@52925
   563
  |> #1;
krauss@43068
   564
wenzelm@30142
   565
val _ =
wenzelm@48646
   566
  Outer_Syntax.improper_command @{command_spec "find_theorems"}
wenzelm@50214
   567
    "find theorems meeting specified criteria"
wenzelm@52925
   568
    (options -- query >> (fn ((opt_lim, rem_dups), spec) =>
wenzelm@52941
   569
      Toplevel.keep (fn st =>
wenzelm@52941
   570
        Pretty.writeln (pretty_theorems (proof_state st) opt_lim rem_dups spec))));
wenzelm@16033
   571
wenzelm@16033
   572
end;
wenzelm@30142
   573
wenzelm@52851
   574
wenzelm@52851
   575
wenzelm@52865
   576
(** PIDE query operation **)
wenzelm@52854
   577
wenzelm@52865
   578
val _ =
wenzelm@52943
   579
  Query_Operation.register "find_theorems"
wenzelm@52943
   580
    (fn st => fn [limit_arg, allow_dups_arg, context_arg, query_arg] =>
wenzelm@52943
   581
      if can Toplevel.context_of st then
wenzelm@52943
   582
        let
wenzelm@52943
   583
          val state =
wenzelm@52943
   584
            if context_arg = "" then proof_state st
wenzelm@52943
   585
            else Proof.init (Proof_Context.init_global (Thy_Info.get_theory context_arg));
wenzelm@52943
   586
          val opt_limit = Int.fromString limit_arg;
wenzelm@52943
   587
          val rem_dups = allow_dups_arg = "false";
wenzelm@52943
   588
          val criteria = read_query Position.none query_arg;
wenzelm@52943
   589
        in Pretty.string_of (pretty_theorems state opt_limit rem_dups criteria) end
wenzelm@52943
   590
      else error "Unknown context");
wenzelm@52851
   591
wenzelm@30142
   592
end;