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