src/HOL/Tools/ATP/atp_util.ML
author blanchet
Thu Aug 25 22:06:25 2011 +0200 (2011-08-25)
changeset 44500 dbd98b549597
parent 44491 ba22ed224b20
child 44784 c9a081ef441d
permissions -rw-r--r--
make default unsound mode less unsound
     1 (*  Title:      HOL/Tools/ATP/atp_util.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3 
     4 General-purpose functions used by the ATP module.
     5 *)
     6 
     7 signature ATP_UTIL =
     8 sig
     9   val timestamp : unit -> string
    10   val hash_string : string -> int
    11   val hash_term : term -> int
    12   val strip_spaces : bool -> (char -> bool) -> string -> string
    13   val nat_subscript : int -> string
    14   val unyxml : string -> string
    15   val maybe_quote : string -> string
    16   val string_from_ext_time : bool * Time.time -> string
    17   val string_from_time : Time.time -> string
    18   val type_instance : Proof.context -> typ -> typ -> bool
    19   val type_generalization : Proof.context -> typ -> typ -> bool
    20   val type_intersect : Proof.context -> typ -> typ -> bool
    21   val type_aconv : Proof.context -> typ * typ -> bool
    22   val varify_type : Proof.context -> typ -> typ
    23   val instantiate_type : theory -> typ -> typ -> typ -> typ
    24   val varify_and_instantiate_type : Proof.context -> typ -> typ -> typ -> typ
    25   val typ_of_dtyp :
    26     Datatype_Aux.descr -> (Datatype_Aux.dtyp * typ) list -> Datatype_Aux.dtyp
    27     -> typ
    28   val is_type_surely_finite : Proof.context -> typ -> bool
    29   val is_type_surely_infinite : Proof.context -> bool -> typ list -> typ -> bool
    30   val s_not : term -> term
    31   val s_conj : term * term -> term
    32   val s_disj : term * term -> term
    33   val s_imp : term * term -> term
    34   val s_iff : term * term -> term
    35   val close_form : term -> term
    36   val monomorphic_term : Type.tyenv -> term -> term
    37   val eta_expand : typ list -> term -> int -> term
    38   val transform_elim_prop : term -> term
    39   val specialize_type : theory -> (string * typ) -> term -> term
    40   val strip_subgoal :
    41     Proof.context -> thm -> int -> (string * typ) list * term list * term
    42 end;
    43 
    44 structure ATP_Util : ATP_UTIL =
    45 struct
    46 
    47 val timestamp = Date.fmt "%Y-%m-%d %H:%M:%S" o Date.fromTimeLocal o Time.now
    48 
    49 (* This hash function is recommended in "Compilers: Principles, Techniques, and
    50    Tools" by Aho, Sethi, and Ullman. The "hashpjw" function, which they
    51    particularly recommend, triggers a bug in versions of Poly/ML up to 4.2.0. *)
    52 fun hashw (u, w) = Word.+ (u, Word.* (0w65599, w))
    53 fun hashw_char (c, w) = hashw (Word.fromInt (Char.ord c), w)
    54 fun hashw_string (s : string, w) = CharVector.foldl hashw_char w s
    55 fun hashw_term (t1 $ t2) = hashw (hashw_term t1, hashw_term t2)
    56   | hashw_term (Const (s, _)) = hashw_string (s, 0w0)
    57   | hashw_term (Free (s, _)) = hashw_string (s, 0w0)
    58   | hashw_term _ = 0w0
    59 
    60 fun hash_string s = Word.toInt (hashw_string (s, 0w0))
    61 val hash_term = Word.toInt o hashw_term
    62 
    63 fun strip_c_style_comment _ [] = []
    64   | strip_c_style_comment is_evil (#"*" :: #"/" :: cs) =
    65     strip_spaces_in_list true is_evil cs
    66   | strip_c_style_comment is_evil (_ :: cs) = strip_c_style_comment is_evil cs
    67 and strip_spaces_in_list _ _ [] = []
    68   | strip_spaces_in_list true is_evil (#"%" :: cs) =
    69     strip_spaces_in_list true is_evil
    70                          (cs |> chop_while (not_equal #"\n") |> snd)
    71   | strip_spaces_in_list true is_evil (#"/" :: #"*" :: cs) =
    72     strip_c_style_comment is_evil cs
    73   | strip_spaces_in_list _ _ [c1] = if Char.isSpace c1 then [] else [str c1]
    74   | strip_spaces_in_list skip_comments is_evil [c1, c2] =
    75     strip_spaces_in_list skip_comments is_evil [c1] @
    76     strip_spaces_in_list skip_comments is_evil [c2]
    77   | strip_spaces_in_list skip_comments is_evil (c1 :: c2 :: c3 :: cs) =
    78     if Char.isSpace c1 then
    79       strip_spaces_in_list skip_comments is_evil (c2 :: c3 :: cs)
    80     else if Char.isSpace c2 then
    81       if Char.isSpace c3 then
    82         strip_spaces_in_list skip_comments is_evil (c1 :: c3 :: cs)
    83       else
    84         str c1 :: (if forall is_evil [c1, c3] then [" "] else []) @
    85         strip_spaces_in_list skip_comments is_evil (c3 :: cs)
    86     else
    87       str c1 :: strip_spaces_in_list skip_comments is_evil (c2 :: c3 :: cs)
    88 fun strip_spaces skip_comments is_evil =
    89   implode o strip_spaces_in_list skip_comments is_evil o String.explode
    90 
    91 val subscript = implode o map (prefix "\<^isub>") o raw_explode  (* FIXME Symbol.explode (?) *)
    92 fun nat_subscript n =
    93   n |> string_of_int |> print_mode_active Symbol.xsymbolsN ? subscript
    94 
    95 val unyxml = XML.content_of o YXML.parse_body
    96 
    97 val is_long_identifier = forall Lexicon.is_identifier o space_explode "."
    98 fun maybe_quote y =
    99   let val s = unyxml y in
   100     y |> ((not (is_long_identifier (perhaps (try (unprefix "'")) s)) andalso
   101            not (is_long_identifier (perhaps (try (unprefix "?")) s))) orelse
   102            Keyword.is_keyword s) ? quote
   103   end
   104 
   105 fun string_from_ext_time (plus, time) =
   106   let val ms = Time.toMilliseconds time in
   107     (if plus then "> " else "") ^
   108     (if plus andalso ms mod 1000 = 0 then
   109        signed_string_of_int (ms div 1000) ^ " s"
   110      else if ms < 1000 then
   111        signed_string_of_int ms ^ " ms"
   112      else
   113        string_of_real (0.01 * Real.fromInt (ms div 10)) ^ " s")
   114   end
   115 
   116 val string_from_time = string_from_ext_time o pair false
   117 
   118 fun type_instance ctxt T T' =
   119   Sign.typ_instance (Proof_Context.theory_of ctxt) (T, T')
   120 fun type_generalization ctxt T T' = type_instance ctxt T' T
   121 fun type_intersect ctxt T T' =
   122   type_instance ctxt T T' orelse type_generalization ctxt T T'
   123 fun type_aconv ctxt (T, T') =
   124   type_instance ctxt T T' andalso type_instance ctxt T' T
   125 
   126 fun varify_type ctxt T =
   127   Variable.polymorphic_types ctxt [Const (@{const_name undefined}, T)]
   128   |> snd |> the_single |> dest_Const |> snd
   129 
   130 (* TODO: use "Term_Subst.instantiateT" instead? *)
   131 fun instantiate_type thy T1 T1' T2 =
   132   Same.commit (Envir.subst_type_same
   133                    (Sign.typ_match thy (T1, T1') Vartab.empty)) T2
   134   handle Type.TYPE_MATCH => raise TYPE ("instantiate_type", [T1, T1'], [])
   135 
   136 fun varify_and_instantiate_type ctxt T1 T1' T2 =
   137   let val thy = Proof_Context.theory_of ctxt in
   138     instantiate_type thy (varify_type ctxt T1) T1' (varify_type ctxt T2)
   139   end
   140 
   141 fun typ_of_dtyp _ typ_assoc (Datatype_Aux.DtTFree a) =
   142     the (AList.lookup (op =) typ_assoc (Datatype_Aux.DtTFree a))
   143   | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtType (s, Us)) =
   144     Type (s, map (typ_of_dtyp descr typ_assoc) Us)
   145   | typ_of_dtyp descr typ_assoc (Datatype_Aux.DtRec i) =
   146     let val (s, ds, _) = the (AList.lookup (op =) descr i) in
   147       Type (s, map (typ_of_dtyp descr typ_assoc) ds)
   148     end
   149 
   150 fun datatype_constrs thy (T as Type (s, Ts)) =
   151     (case Datatype.get_info thy s of
   152        SOME {index, descr, ...} =>
   153        let val (_, dtyps, constrs) = AList.lookup (op =) descr index |> the in
   154          map (apsnd (fn Us => map (typ_of_dtyp descr (dtyps ~~ Ts)) Us ---> T))
   155              constrs
   156        end
   157      | NONE => [])
   158   | datatype_constrs _ _ = []
   159 
   160 (* Similar to "Nitpick_HOL.bounded_exact_card_of_type".
   161    0 means infinite type, 1 means singleton type (e.g., "unit"), and 2 means
   162    cardinality 2 or more. The specified default cardinality is returned if the
   163    cardinality of the type can't be determined. *)
   164 fun tiny_card_of_type ctxt sound assigns default_card T =
   165   let
   166     val thy = Proof_Context.theory_of ctxt
   167     val max = 2 (* 1 would be too small for the "fun" case *)
   168     fun aux slack avoid T =
   169       if member (op =) avoid T then
   170         0
   171       else case AList.lookup (type_aconv ctxt) assigns T of
   172         SOME k => k
   173       | NONE =>
   174         case T of
   175           Type (@{type_name fun}, [T1, T2]) =>
   176           (case (aux slack avoid T1, aux slack avoid T2) of
   177              (k, 1) => if slack andalso k = 0 then 0 else 1
   178            | (0, _) => 0
   179            | (_, 0) => 0
   180            | (k1, k2) =>
   181              if k1 >= max orelse k2 >= max then max
   182              else Int.min (max, Integer.pow k2 k1))
   183         | @{typ prop} => 2
   184         | @{typ bool} => 2 (* optimization *)
   185         | @{typ nat} => 0 (* optimization *)
   186         | Type ("Int.int", []) => 0 (* optimization *)
   187         | Type (s, _) =>
   188           (case datatype_constrs thy T of
   189              constrs as _ :: _ =>
   190              let
   191                val constr_cards =
   192                  map (Integer.prod o map (aux slack (T :: avoid)) o binder_types
   193                       o snd) constrs
   194              in
   195                if exists (curry (op =) 0) constr_cards then 0
   196                else Int.min (max, Integer.sum constr_cards)
   197              end
   198            | [] =>
   199              case Typedef.get_info ctxt s of
   200                ({abs_type, rep_type, ...}, _) :: _ =>
   201                (* We cheat here by assuming that typedef types are infinite if
   202                   their underlying type is infinite. This is unsound in general
   203                   but it's hard to think of a realistic example where this would
   204                   not be the case. We are also slack with representation types:
   205                   If a representation type has the form "sigma => tau", we
   206                   consider it enough to check "sigma" for infiniteness. (Look
   207                   for "slack" in this function.) *)
   208                (case varify_and_instantiate_type ctxt
   209                          (Logic.varifyT_global abs_type) T
   210                          (Logic.varifyT_global rep_type)
   211                      |> aux true avoid of
   212                   0 => 0
   213                 | 1 => 1
   214                 | _ => default_card)
   215              | [] => default_card)
   216           (* Very slightly unsound: Type variables are assumed not to be
   217              constrained to cardinality 1. (In practice, the user would most
   218              likely have used "unit" directly anyway.) *)
   219         | TFree _ =>
   220           if not sound andalso default_card = 1 then 2 else default_card
   221         | TVar _ => default_card
   222   in Int.min (max, aux false [] T) end
   223 
   224 fun is_type_surely_finite ctxt T = tiny_card_of_type ctxt true [] 0 T <> 0
   225 fun is_type_surely_infinite ctxt sound infinite_Ts T =
   226   tiny_card_of_type ctxt sound (map (rpair 0) infinite_Ts) 1 T = 0
   227 
   228 (* Simple simplifications to ensure that sort annotations don't leave a trail of
   229    spurious "True"s. *)
   230 fun s_not (Const (@{const_name All}, T) $ Abs (s, T', t')) =
   231     Const (@{const_name Ex}, T) $ Abs (s, T', s_not t')
   232   | s_not (Const (@{const_name Ex}, T) $ Abs (s, T', t')) =
   233     Const (@{const_name All}, T) $ Abs (s, T', s_not t')
   234   | s_not (@{const HOL.implies} $ t1 $ t2) = @{const HOL.conj} $ t1 $ s_not t2
   235   | s_not (@{const HOL.conj} $ t1 $ t2) =
   236     @{const HOL.disj} $ s_not t1 $ s_not t2
   237   | s_not (@{const HOL.disj} $ t1 $ t2) =
   238     @{const HOL.conj} $ s_not t1 $ s_not t2
   239   | s_not (@{const False}) = @{const True}
   240   | s_not (@{const True}) = @{const False}
   241   | s_not (@{const Not} $ t) = t
   242   | s_not t = @{const Not} $ t
   243 fun s_conj (@{const True}, t2) = t2
   244   | s_conj (t1, @{const True}) = t1
   245   | s_conj p = HOLogic.mk_conj p
   246 fun s_disj (@{const False}, t2) = t2
   247   | s_disj (t1, @{const False}) = t1
   248   | s_disj p = HOLogic.mk_disj p
   249 fun s_imp (@{const True}, t2) = t2
   250   | s_imp (t1, @{const False}) = s_not t1
   251   | s_imp p = HOLogic.mk_imp p
   252 fun s_iff (@{const True}, t2) = t2
   253   | s_iff (t1, @{const True}) = t1
   254   | s_iff (t1, t2) = HOLogic.eq_const HOLogic.boolT $ t1 $ t2
   255 
   256 fun close_form t =
   257   fold (fn ((x, i), T) => fn t' =>
   258            HOLogic.all_const T $ Abs (x, T, abstract_over (Var ((x, i), T), t')))
   259        (Term.add_vars t []) t
   260 
   261 fun monomorphic_term subst =
   262   map_types (map_type_tvar (fn v =>
   263       case Type.lookup subst v of
   264         SOME typ => typ
   265       | NONE => TVar v))
   266 
   267 fun eta_expand _ t 0 = t
   268   | eta_expand Ts (Abs (s, T, t')) n =
   269     Abs (s, T, eta_expand (T :: Ts) t' (n - 1))
   270   | eta_expand Ts t n =
   271     fold_rev (fn T => fn t' => Abs ("x" ^ nat_subscript n, T, t'))
   272              (List.take (binder_types (fastype_of1 (Ts, t)), n))
   273              (list_comb (incr_boundvars n t, map Bound (n - 1 downto 0)))
   274 
   275 (* Converts an elim-rule into an equivalent theorem that does not have the
   276    predicate variable. Leaves other theorems unchanged. We simply instantiate
   277    the conclusion variable to "False". (Cf. "transform_elim_theorem" in
   278    "Meson_Clausify".) *)
   279 fun transform_elim_prop t =
   280   case Logic.strip_imp_concl t of
   281     @{const Trueprop} $ Var (z, @{typ bool}) =>
   282     subst_Vars [(z, @{const False})] t
   283   | Var (z, @{typ prop}) => subst_Vars [(z, @{prop False})] t
   284   | _ => t
   285 
   286 fun specialize_type thy (s, T) t =
   287   let
   288     fun subst_for (Const (s', T')) =
   289       if s = s' then
   290         SOME (Sign.typ_match thy (T', T) Vartab.empty)
   291         handle Type.TYPE_MATCH => NONE
   292       else
   293         NONE
   294     | subst_for (t1 $ t2) =
   295       (case subst_for t1 of SOME x => SOME x | NONE => subst_for t2)
   296     | subst_for (Abs (_, _, t')) = subst_for t'
   297     | subst_for _ = NONE
   298   in
   299     case subst_for t of
   300       SOME subst => monomorphic_term subst t
   301     | NONE => raise Type.TYPE_MATCH
   302   end
   303 
   304 fun strip_subgoal ctxt goal i =
   305   let
   306     val (t, (frees, params)) =
   307       Logic.goal_params (prop_of goal) i
   308       ||> (map dest_Free #> Variable.variant_frees ctxt [] #> `(map Free))
   309     val hyp_ts = t |> Logic.strip_assums_hyp |> map (curry subst_bounds frees)
   310     val concl_t = t |> Logic.strip_assums_concl |> curry subst_bounds frees
   311   in (rev params, hyp_ts, concl_t) end
   312 
   313 end;