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