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