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