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