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