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