src/HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
author blanchet
Mon Aug 23 14:54:17 2010 +0200 (2010-08-23 ago)
changeset 38652 e063be321438
parent 38644 25bbbaf7ce65
child 38679 2cfd0777580f
permissions -rw-r--r--
perform eta-expansion of quantifier bodies in Sledgehammer translation when needed + transform elim rules later;
it's a mistake to transform the elim rules too early because then we lose some info, e.g. "no_atp" attributes
     1 (*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_filter.ML
     2     Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 *)
     5 
     6 signature SLEDGEHAMMER_FACT_FILTER =
     7 sig
     8   type relevance_override =
     9     {add: Facts.ref list,
    10      del: Facts.ref list,
    11      only: bool}
    12 
    13   val trace : bool Unsynchronized.ref
    14   val chained_prefix : string
    15   val name_thms_pair_from_ref :
    16     Proof.context -> thm list -> Facts.ref -> string * thm list
    17   val relevant_facts :
    18     bool -> real -> real -> bool -> int -> bool -> relevance_override
    19     -> Proof.context * (thm list * 'a) -> term list -> term
    20     -> (string * thm) list
    21 end;
    22 
    23 structure Sledgehammer_Fact_Filter : SLEDGEHAMMER_FACT_FILTER =
    24 struct
    25 
    26 open Sledgehammer_Util
    27 
    28 val trace = Unsynchronized.ref false
    29 fun trace_msg msg = if !trace then tracing (msg ()) else ()
    30 
    31 val respect_no_atp = true
    32 
    33 type relevance_override =
    34   {add: Facts.ref list,
    35    del: Facts.ref list,
    36    only: bool}
    37 
    38 val sledgehammer_prefix = "Sledgehammer" ^ Long_Name.separator
    39 (* Used to label theorems chained into the goal. *)
    40 val chained_prefix = sledgehammer_prefix ^ "chained_"
    41 
    42 fun name_thms_pair_from_ref ctxt chained_ths xref =
    43   let
    44     val ths = ProofContext.get_fact ctxt xref
    45     val name = Facts.string_of_ref xref
    46                |> forall (member Thm.eq_thm chained_ths) ths
    47                   ? prefix chained_prefix
    48   in (name, ths) end
    49 
    50 
    51 (***************************************************************)
    52 (* Relevance Filtering                                         *)
    53 (***************************************************************)
    54 
    55 (*** constants with types ***)
    56 
    57 (*An abstraction of Isabelle types*)
    58 datatype const_typ =  CTVar | CType of string * const_typ list
    59 
    60 (*Is the second type an instance of the first one?*)
    61 fun match_type (CType(con1,args1)) (CType(con2,args2)) =
    62       con1=con2 andalso match_types args1 args2
    63   | match_type CTVar _ = true
    64   | match_type _ CTVar = false
    65 and match_types [] [] = true
    66   | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
    67 
    68 (*Is there a unifiable constant?*)
    69 fun uni_mem goal_const_tab (c, c_typ) =
    70   exists (match_types c_typ) (these (Symtab.lookup goal_const_tab c))
    71 
    72 (*Maps a "real" type to a const_typ*)
    73 fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs)
    74   | const_typ_of (TFree _) = CTVar
    75   | const_typ_of (TVar _) = CTVar
    76 
    77 (*Pairs a constant with the list of its type instantiations (using const_typ)*)
    78 fun const_with_typ thy (c,typ) =
    79   let val tvars = Sign.const_typargs thy (c,typ) in
    80     (c, map const_typ_of tvars) end
    81   handle TYPE _ => (c, [])   (*Variable (locale constant): monomorphic*)
    82 
    83 (*Add a const/type pair to the table, but a [] entry means a standard connective,
    84   which we ignore.*)
    85 fun add_const_type_to_table (c, ctyps) =
    86   Symtab.map_default (c, [ctyps])
    87                      (fn [] => [] | ctypss => insert (op =) ctyps ctypss)
    88 
    89 val fresh_prefix = "Sledgehammer.FRESH."
    90 val flip = Option.map not
    91 (* These are typically simplified away by "Meson.presimplify". *)
    92 val boring_consts = [@{const_name If}, @{const_name Let}]
    93 
    94 fun get_consts_typs thy pos ts =
    95   let
    96     (* We include free variables, as well as constants, to handle locales. For
    97        each quantifiers that must necessarily be skolemized by the ATP, we
    98        introduce a fresh constant to simulate the effect of Skolemization. *)
    99     fun do_term t =
   100       case t of
   101         Const x => add_const_type_to_table (const_with_typ thy x)
   102       | Free (s, _) => add_const_type_to_table (s, [])
   103       | t1 $ t2 => do_term t1 #> do_term t2
   104       | Abs (_, _, t') => do_term t'
   105       | _ => I
   106     fun do_quantifier will_surely_be_skolemized body_t =
   107       do_formula pos body_t
   108       #> (if will_surely_be_skolemized then
   109             add_const_type_to_table (gensym fresh_prefix, [])
   110           else
   111             I)
   112     and do_term_or_formula T =
   113       if T = @{typ bool} orelse T = @{typ prop} then do_formula NONE
   114       else do_term
   115     and do_formula pos t =
   116       case t of
   117         Const (@{const_name all}, _) $ Abs (_, _, body_t) =>
   118         do_quantifier (pos = SOME false) body_t
   119       | @{const "==>"} $ t1 $ t2 =>
   120         do_formula (flip pos) t1 #> do_formula pos t2
   121       | Const (@{const_name "=="}, Type (_, [T, _])) $ t1 $ t2 =>
   122         fold (do_term_or_formula T) [t1, t2]
   123       | @{const Trueprop} $ t1 => do_formula pos t1
   124       | @{const Not} $ t1 => do_formula (flip pos) t1
   125       | Const (@{const_name All}, _) $ Abs (_, _, body_t) =>
   126         do_quantifier (pos = SOME false) body_t
   127       | Const (@{const_name Ex}, _) $ Abs (_, _, body_t) =>
   128         do_quantifier (pos = SOME true) body_t
   129       | @{const "op &"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
   130       | @{const "op |"} $ t1 $ t2 => fold (do_formula pos) [t1, t2]
   131       | @{const "op -->"} $ t1 $ t2 =>
   132         do_formula (flip pos) t1 #> do_formula pos t2
   133       | Const (@{const_name "op ="}, Type (_, [T, _])) $ t1 $ t2 =>
   134         fold (do_term_or_formula T) [t1, t2]
   135       | Const (@{const_name If}, Type (_, [_, Type (_, [T, _])]))
   136         $ t1 $ t2 $ t3 =>
   137         do_formula NONE t1 #> fold (do_term_or_formula T) [t2, t3]
   138       | Const (@{const_name Ex1}, _) $ Abs (_, _, body_t) =>
   139         do_quantifier (is_some pos) body_t
   140       | Const (@{const_name Ball}, _) $ t1 $ Abs (_, _, body_t) =>
   141         do_quantifier (pos = SOME false)
   142                       (HOLogic.mk_imp (incr_boundvars 1 t1 $ Bound 0, body_t))
   143       | Const (@{const_name Bex}, _) $ t1 $ Abs (_, _, body_t) =>
   144         do_quantifier (pos = SOME true)
   145                       (HOLogic.mk_conj (incr_boundvars 1 t1 $ Bound 0, body_t))
   146       | (t0 as Const (_, @{typ bool})) $ t1 =>
   147         do_term t0 #> do_formula pos t1  (* theory constant *)
   148       | _ => do_term t
   149   in
   150     Symtab.empty |> fold (Symtab.update o rpair []) boring_consts
   151                  |> fold (do_formula pos) ts
   152   end
   153 
   154 (*Inserts a dummy "constant" referring to the theory name, so that relevance
   155   takes the given theory into account.*)
   156 fun theory_const_prop_of theory_relevant th =
   157   if theory_relevant then
   158     let
   159       val name = Context.theory_name (theory_of_thm th)
   160       val t = Const (name ^ ". 1", @{typ bool})
   161     in t $ prop_of th end
   162   else
   163     prop_of th
   164 
   165 (**** Constant / Type Frequencies ****)
   166 
   167 (*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
   168   constant name and second by its list of type instantiations. For the latter, we need
   169   a linear ordering on type const_typ list.*)
   170 
   171 local
   172 
   173 fun cons_nr CTVar = 0
   174   | cons_nr (CType _) = 1;
   175 
   176 in
   177 
   178 fun const_typ_ord TU =
   179   case TU of
   180     (CType (a, Ts), CType (b, Us)) =>
   181       (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
   182   | (T, U) => int_ord (cons_nr T, cons_nr U);
   183 
   184 end;
   185 
   186 structure CTtab = Table(type key = const_typ list val ord = dict_ord const_typ_ord);
   187 
   188 fun count_axiom_consts theory_relevant thy (_, th) =
   189   let
   190     fun do_const (a, T) =
   191       let val (c, cts) = const_with_typ thy (a, T) in
   192         (* Two-dimensional table update. Constant maps to types maps to
   193            count. *)
   194         CTtab.map_default (cts, 0) (Integer.add 1)
   195         |> Symtab.map_default (c, CTtab.empty)
   196       end
   197     fun do_term (Const x) = do_const x
   198       | do_term (Free x) = do_const x
   199       | do_term (t $ u) = do_term t #> do_term u
   200       | do_term (Abs (_, _, t)) = do_term t
   201       | do_term _ = I
   202   in th |> theory_const_prop_of theory_relevant |> do_term end
   203 
   204 
   205 (**** Actual Filtering Code ****)
   206 
   207 (*The frequency of a constant is the sum of those of all instances of its type.*)
   208 fun const_frequency const_tab (c, cts) =
   209   CTtab.fold (fn (cts', m) => match_types cts cts' ? Integer.add m)
   210              (the (Symtab.lookup const_tab c)
   211               handle Option.Option => raise Fail ("Const: " ^ c)) 0
   212 
   213 (* A surprising number of theorems contain only a few significant constants.
   214    These include all induction rules, and other general theorems. *)
   215 
   216 (* "log" seems best in practice. A constant function of one ignores the constant
   217    frequencies. *)
   218 fun log_weight2 (x:real) = 1.0 + 2.0 / Math.ln (x + 1.0)
   219 
   220 (* Computes a constant's weight, as determined by its frequency. *)
   221 val ct_weight = log_weight2 o real oo const_frequency
   222 
   223 (*Relevant constants are weighted according to frequency,
   224   but irrelevant constants are simply counted. Otherwise, Skolem functions,
   225   which are rare, would harm a formula's chances of being picked.*)
   226 fun formula_weight const_tab gctyps consts_typs =
   227   let
   228     val rel = filter (uni_mem gctyps) consts_typs
   229     val rel_weight = fold (curry Real.+ o ct_weight const_tab) rel 0.0
   230     val res = rel_weight / (rel_weight + real (length consts_typs - length rel))
   231   in if Real.isFinite res then res else 0.0 end
   232 
   233 (*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
   234 fun add_expand_pairs (x,ys) xys = List.foldl (fn (y,acc) => (x,y)::acc) xys ys;
   235 
   236 fun consts_typs_of_term thy t =
   237   Symtab.fold add_expand_pairs (get_consts_typs thy (SOME true) [t]) []
   238 
   239 fun pair_consts_typs_axiom theory_relevant thy axiom =
   240   (axiom, axiom |> snd |> theory_const_prop_of theory_relevant
   241                 |> consts_typs_of_term thy)
   242 
   243 exception CONST_OR_FREE of unit
   244 
   245 fun dest_Const_or_Free (Const x) = x
   246   | dest_Const_or_Free (Free x) = x
   247   | dest_Const_or_Free _ = raise CONST_OR_FREE ()
   248 
   249 (*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
   250 fun defines thy thm gctypes =
   251     let val tm = prop_of thm
   252         fun defs lhs rhs =
   253             let val (rator,args) = strip_comb lhs
   254                 val ct = const_with_typ thy (dest_Const_or_Free rator)
   255             in
   256               forall is_Var args andalso uni_mem gctypes ct andalso
   257                 subset (op =) (Term.add_vars rhs [], Term.add_vars lhs [])
   258             end
   259             handle CONST_OR_FREE () => false
   260     in
   261         case tm of
   262           @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ lhs $ rhs) =>
   263             defs lhs rhs
   264         | _ => false
   265     end;
   266 
   267 type annotated_thm = (string * thm) * (string * const_typ list) list
   268 
   269 (*For a reverse sort, putting the largest values first.*)
   270 fun compare_pairs ((_, w1), (_, w2)) = Real.compare (w2, w1)
   271 
   272 (* Limit the number of new facts, to prevent runaway acceptance. *)
   273 fun take_best max_new (newpairs : (annotated_thm * real) list) =
   274   let val nnew = length newpairs in
   275     if nnew <= max_new then
   276       (map #1 newpairs, [])
   277     else
   278       let
   279         val newpairs = sort compare_pairs newpairs
   280         val accepted = List.take (newpairs, max_new)
   281       in
   282         trace_msg (fn () => ("Number of candidates, " ^ Int.toString nnew ^
   283                        ", exceeds the limit of " ^ Int.toString max_new));
   284         trace_msg (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
   285         trace_msg (fn () => "Actually passed: " ^
   286           space_implode ", " (map (fst o fst o fst) accepted));
   287         (map #1 accepted, map #1 (List.drop (newpairs, max_new)))
   288       end
   289   end;
   290 
   291 fun relevance_filter ctxt relevance_threshold relevance_convergence
   292                      defs_relevant max_new theory_relevant
   293                      ({add, del, ...} : relevance_override) axioms goal_ts =
   294   if relevance_threshold > 1.0 then
   295     []
   296   else if relevance_threshold < 0.0 then
   297     axioms
   298   else
   299     let
   300       val thy = ProofContext.theory_of ctxt
   301       val const_tab = fold (count_axiom_consts theory_relevant thy) axioms
   302                            Symtab.empty
   303       val goal_const_tab = get_consts_typs thy (SOME false) goal_ts
   304       val relevance_threshold = 0.8 * relevance_threshold (* FIXME *)
   305       val _ =
   306         trace_msg (fn () => "Initial constants: " ^
   307                             commas (goal_const_tab
   308                                     |> Symtab.dest
   309                                     |> filter (curry (op <>) [] o snd)
   310                                     |> map fst))
   311       val add_thms = maps (ProofContext.get_fact ctxt) add
   312       val del_thms = maps (ProofContext.get_fact ctxt) del
   313       fun iter threshold rel_const_tab =
   314         let
   315           fun relevant ([], rejects) [] =
   316               (* Nothing was added this iteration: Add "add:" facts. *)
   317               if null add_thms then
   318                 []
   319               else
   320                 map_filter (fn (p as (name, th), _) =>
   321                                if member Thm.eq_thm add_thms th then SOME p
   322                                else NONE) rejects
   323             | relevant (newpairs, rejects) [] =
   324               let
   325                 val (newrels, more_rejects) = take_best max_new newpairs
   326                 val new_consts = maps #2 newrels
   327                 val rel_const_tab =
   328                   rel_const_tab |> fold add_const_type_to_table new_consts
   329                 val threshold =
   330                   threshold + (1.0 - threshold) / relevance_convergence
   331               in
   332                 trace_msg (fn () => "relevant this iteration: " ^
   333                                     Int.toString (length newrels));
   334                 map #1 newrels @ iter threshold rel_const_tab
   335                     (more_rejects @ rejects)
   336               end
   337             | relevant (newrels, rejects)
   338                        ((ax as ((name, th), consts_typs)) :: axs) =
   339               let
   340                 val weight =
   341                   if member Thm.eq_thm del_thms th then 0.0
   342                   else formula_weight const_tab rel_const_tab consts_typs
   343               in
   344                 if weight >= threshold orelse
   345                    (defs_relevant andalso defines thy th rel_const_tab) then
   346                   (trace_msg (fn () =>
   347                        name ^ " passes: " ^ Real.toString weight
   348                        (* ^ " consts: " ^ commas (map fst consts_typs) *));
   349                    relevant ((ax, weight) :: newrels, rejects) axs)
   350                 else
   351                   relevant (newrels, ax :: rejects) axs
   352               end
   353           in
   354             trace_msg (fn () => "relevant_facts, current threshold: " ^
   355                                 Real.toString threshold);
   356             relevant ([], [])
   357           end
   358       val relevant = iter relevance_threshold goal_const_tab
   359                           (map (pair_consts_typs_axiom theory_relevant thy)
   360                                axioms)
   361     in
   362       trace_msg (fn () => "Total relevant: " ^ Int.toString (length relevant));
   363       relevant
   364     end
   365 
   366 (***************************************************************)
   367 (* Retrieving and filtering lemmas                             *)
   368 (***************************************************************)
   369 
   370 (*** retrieve lemmas and filter them ***)
   371 
   372 (*Reject theorems with names like "List.filter.filter_list_def" or
   373   "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
   374 fun is_package_def a =
   375   let val names = Long_Name.explode a
   376   in
   377      length names > 2 andalso
   378      not (hd names = "local") andalso
   379      String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
   380   end;
   381 
   382 fun make_fact_table xs =
   383   fold (Termtab.update o `(prop_of o snd)) xs Termtab.empty
   384 fun make_unique xs = Termtab.fold (cons o snd) (make_fact_table xs) []
   385 
   386 (* FIXME: put other record thms here, or declare as "no_atp" *)
   387 val multi_base_blacklist =
   388   ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
   389    "split_asm", "cases", "ext_cases"]
   390 
   391 val max_lambda_nesting = 3
   392 
   393 fun term_has_too_many_lambdas max (t1 $ t2) =
   394     exists (term_has_too_many_lambdas max) [t1, t2]
   395   | term_has_too_many_lambdas max (Abs (_, _, t)) =
   396     max = 0 orelse term_has_too_many_lambdas (max - 1) t
   397   | term_has_too_many_lambdas _ _ = false
   398 
   399 fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
   400 
   401 (* Don't count nested lambdas at the level of formulas, since they are
   402    quantifiers. *)
   403 fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
   404     formula_has_too_many_lambdas (T :: Ts) t
   405   | formula_has_too_many_lambdas Ts t =
   406     if is_formula_type (fastype_of1 (Ts, t)) then
   407       exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
   408     else
   409       term_has_too_many_lambdas max_lambda_nesting t
   410 
   411 (* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
   412    was 11. *)
   413 val max_apply_depth = 15
   414 
   415 fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
   416   | apply_depth (Abs (_, _, t)) = apply_depth t
   417   | apply_depth _ = 0
   418 
   419 fun is_formula_too_complex t =
   420   apply_depth t > max_apply_depth orelse formula_has_too_many_lambdas [] t
   421 
   422 val exists_sledgehammer_const =
   423   exists_Const (fn (s, _) => String.isPrefix sledgehammer_prefix s)
   424 
   425 fun is_strange_theorem th =
   426   case head_of (concl_of th) of
   427       Const (a, _) => (a <> @{const_name Trueprop} andalso
   428                        a <> @{const_name "=="})
   429     | _ => false
   430 
   431 val type_has_top_sort =
   432   exists_subtype (fn TFree (_, []) => true | TVar (_, []) => true | _ => false)
   433 
   434 (**** Predicates to detect unwanted facts (prolific or likely to cause
   435       unsoundness) ****)
   436 
   437 (* Too general means, positive equality literal with a variable X as one
   438    operand, when X does not occur properly in the other operand. This rules out
   439    clearly inconsistent facts such as X = a | X = b, though it by no means
   440    guarantees soundness. *)
   441 
   442 (* Unwanted equalities are those between a (bound or schematic) variable that
   443    does not properly occur in the second operand. *)
   444 val is_exhaustive_finite =
   445   let
   446     fun is_bad_equal (Var z) t =
   447         not (exists_subterm (fn Var z' => z = z' | _ => false) t)
   448       | is_bad_equal (Bound j) t = not (loose_bvar1 (t, j))
   449       | is_bad_equal _ _ = false
   450     fun do_equals t1 t2 = is_bad_equal t1 t2 orelse is_bad_equal t2 t1
   451     fun do_formula pos t =
   452       case (pos, t) of
   453         (_, @{const Trueprop} $ t1) => do_formula pos t1
   454       | (true, Const (@{const_name all}, _) $ Abs (_, _, t')) =>
   455         do_formula pos t'
   456       | (true, Const (@{const_name All}, _) $ Abs (_, _, t')) =>
   457         do_formula pos t'
   458       | (false, Const (@{const_name Ex}, _) $ Abs (_, _, t')) =>
   459         do_formula pos t'
   460       | (_, @{const "==>"} $ t1 $ t2) =>
   461         do_formula (not pos) t1 andalso
   462         (t2 = @{prop False} orelse do_formula pos t2)
   463       | (_, @{const "op -->"} $ t1 $ t2) =>
   464         do_formula (not pos) t1 andalso
   465         (t2 = @{const False} orelse do_formula pos t2)
   466       | (_, @{const Not} $ t1) => do_formula (not pos) t1
   467       | (true, @{const "op |"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   468       | (false, @{const "op &"} $ t1 $ t2) => forall (do_formula pos) [t1, t2]
   469       | (true, Const (@{const_name "op ="}, _) $ t1 $ t2) => do_equals t1 t2
   470       | (true, Const (@{const_name "=="}, _) $ t1 $ t2) => do_equals t1 t2
   471       | _ => false
   472   in do_formula true end
   473 
   474 fun has_bound_or_var_of_type tycons =
   475   exists_subterm (fn Var (_, Type (s, _)) => member (op =) tycons s
   476                    | Abs (_, Type (s, _), _) => member (op =) tycons s
   477                    | _ => false)
   478 
   479 (* Facts are forbidden to contain variables of these types. The typical reason
   480    is that they lead to unsoundness. Note that "unit" satisfies numerous
   481    equations like "?x = ()". The resulting clauses will have no type constraint,
   482    yielding false proofs. Even "bool" leads to many unsound proofs, though only
   483    for higher-order problems. *)
   484 val dangerous_types = [@{type_name unit}, @{type_name bool}, @{type_name prop}];
   485 
   486 (* Facts containing variables of type "unit" or "bool" or of the form
   487    "ALL x. x = A | x = B | x = C" are likely to lead to unsound proofs if types
   488    are omitted. *)
   489 fun is_dangerous_term full_types t =
   490   not full_types andalso
   491   ((has_bound_or_var_of_type dangerous_types t andalso
   492     has_bound_or_var_of_type dangerous_types (transform_elim_term t))
   493    orelse is_exhaustive_finite t)
   494 
   495 fun is_theorem_bad_for_atps full_types thm =
   496   let val t = prop_of thm in
   497     is_formula_too_complex t orelse exists_type type_has_top_sort t orelse
   498     is_dangerous_term full_types t orelse exists_sledgehammer_const t orelse
   499     is_strange_theorem thm
   500   end
   501 
   502 fun all_name_thms_pairs ctxt full_types add_thms chained_ths =
   503   let
   504     val global_facts = PureThy.facts_of (ProofContext.theory_of ctxt);
   505     val local_facts = ProofContext.facts_of ctxt
   506     val named_locals = local_facts |> Facts.dest_static []
   507     val unnamed_locals =
   508       local_facts |> Facts.props
   509       |> filter_out (fn th => exists (fn (_, ths) => member Thm.eq_thm ths th)
   510                                      named_locals)
   511       |> map (pair "" o single)
   512     val full_space =
   513       Name_Space.merge (Facts.space_of global_facts, Facts.space_of local_facts);
   514     fun valid_facts facts pairs =
   515       (pairs, []) |-> fold (fn (name, ths0) =>
   516         if name <> "" andalso
   517            forall (not o member Thm.eq_thm add_thms) ths0 andalso
   518            (Facts.is_concealed facts name orelse
   519             (respect_no_atp andalso is_package_def name) orelse
   520             member (op =) multi_base_blacklist (Long_Name.base_name name) orelse
   521             String.isSuffix "_def_raw" (* FIXME: crude hack *) name) then
   522           I
   523         else
   524           let
   525             fun check_thms a =
   526               (case try (ProofContext.get_thms ctxt) a of
   527                 NONE => false
   528               | SOME ths1 => Thm.eq_thms (ths0, ths1))
   529             val name1 = Facts.extern facts name;
   530             val name2 = Name_Space.extern full_space name;
   531             val ths =
   532               ths0 |> filter ((not o is_theorem_bad_for_atps full_types) orf
   533                               member Thm.eq_thm add_thms)
   534             val name' =
   535               case find_first check_thms [name1, name2, name] of
   536                 SOME name' => name'
   537               | NONE =>
   538                 ths |> map (fn th =>
   539                                "`" ^ Print_Mode.setmp [Print_Mode.input]
   540                                          (Syntax.string_of_term ctxt)
   541                                          (prop_of th) ^ "`")
   542                     |> space_implode " "
   543           in
   544             cons (name' |> forall (member Thm.eq_thm chained_ths) ths0
   545                            ? prefix chained_prefix, ths)
   546           end)
   547   in
   548     valid_facts local_facts (unnamed_locals @ named_locals) @
   549     valid_facts global_facts (Facts.dest_static [] global_facts)
   550   end
   551 
   552 fun multi_name a th (n, pairs) =
   553   (n + 1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs);
   554 
   555 fun add_names (_, []) pairs = pairs
   556   | add_names (a, [th]) pairs = (a, th) :: pairs
   557   | add_names (a, ths) pairs = #2 (fold (multi_name a) ths (1, pairs))
   558 
   559 fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
   560 
   561 (* The single-name theorems go after the multiple-name ones, so that single
   562    names are preferred when both are available. *)
   563 fun name_thm_pairs ctxt respect_no_atp name_thms_pairs =
   564   let
   565     val (mults, singles) = List.partition is_multi name_thms_pairs
   566     val ps = [] |> fold add_names singles |> fold add_names mults
   567   in ps |> respect_no_atp ? filter_out (No_ATPs.member ctxt o snd) end;
   568 
   569 fun is_named ("", th) =
   570     (warning ("No name for theorem " ^
   571               Display.string_of_thm_without_context th); false)
   572   | is_named _ = true
   573 fun checked_name_thm_pairs respect_no_atp ctxt =
   574   name_thm_pairs ctxt respect_no_atp
   575   #> tap (fn ps => trace_msg
   576                         (fn () => ("Considering " ^ Int.toString (length ps) ^
   577                                    " theorems")))
   578   #> filter is_named
   579 
   580 (***************************************************************)
   581 (* ATP invocation methods setup                                *)
   582 (***************************************************************)
   583 
   584 fun relevant_facts full_types relevance_threshold relevance_convergence
   585                    defs_relevant max_new theory_relevant
   586                    (relevance_override as {add, del, only})
   587                    (ctxt, (chained_ths, _)) hyp_ts concl_t =
   588   let
   589     val add_thms = maps (ProofContext.get_fact ctxt) add
   590     val axioms =
   591       checked_name_thm_pairs (respect_no_atp andalso not only) ctxt
   592           (if only then map (name_thms_pair_from_ref ctxt chained_ths) add
   593            else all_name_thms_pairs ctxt full_types add_thms chained_ths)
   594       |> make_unique
   595   in
   596     relevance_filter ctxt relevance_threshold relevance_convergence
   597                      defs_relevant max_new theory_relevant relevance_override
   598                      axioms (concl_t :: hyp_ts)
   599     |> sort_wrt fst
   600   end
   601 
   602 end;