src/Pure/drule.ML
author wenzelm
Thu May 31 23:47:36 2007 +0200 (2007-05-31 ago)
changeset 23178 07ba6b58b3d2
parent 22939 2afc93a3d8f4
child 23423 b2d64f86d21b
permissions -rw-r--r--
simplified/unified list fold;
     1 (*  Title:      Pure/drule.ML
     2     ID:         $Id$
     3     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1993  University of Cambridge
     5 
     6 Derived rules and other operations on theorems.
     7 *)
     8 
     9 infix 0 RS RSN RL RLN MRS MRL OF COMP INCR_COMP COMP_INCR;
    10 
    11 signature BASIC_DRULE =
    12 sig
    13   val mk_implies: cterm * cterm -> cterm
    14   val list_implies: cterm list * cterm -> cterm
    15   val strip_imp_prems: cterm -> cterm list
    16   val strip_imp_concl: cterm -> cterm
    17   val cprems_of: thm -> cterm list
    18   val cterm_fun: (term -> term) -> (cterm -> cterm)
    19   val ctyp_fun: (typ -> typ) -> (ctyp -> ctyp)
    20   val read_insts: theory -> (indexname -> typ option) * (indexname -> sort option) ->
    21     (indexname -> typ option) * (indexname -> sort option) -> string list ->
    22     (indexname * string) list -> (ctyp * ctyp) list * (cterm * cterm) list
    23   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    24   val forall_intr_list: cterm list -> thm -> thm
    25   val forall_intr_frees: thm -> thm
    26   val forall_intr_vars: thm -> thm
    27   val forall_elim_list: cterm list -> thm -> thm
    28   val forall_elim_var: int -> thm -> thm
    29   val forall_elim_vars: int -> thm -> thm
    30   val gen_all: thm -> thm
    31   val lift_all: cterm -> thm -> thm
    32   val freeze_thaw: thm -> thm * (thm -> thm)
    33   val freeze_thaw_robust: thm -> thm * (int -> thm -> thm)
    34   val implies_elim_list: thm -> thm list -> thm
    35   val implies_intr_list: cterm list -> thm -> thm
    36   val instantiate: (ctyp * ctyp) list * (cterm * cterm) list -> thm -> thm
    37   val zero_var_indexes_list: thm list -> thm list
    38   val zero_var_indexes: thm -> thm
    39   val implies_intr_hyps: thm -> thm
    40   val standard: thm -> thm
    41   val standard': thm -> thm
    42   val rotate_prems: int -> thm -> thm
    43   val rearrange_prems: int list -> thm -> thm
    44   val RSN: thm * (int * thm) -> thm
    45   val RS: thm * thm -> thm
    46   val RLN: thm list * (int * thm list) -> thm list
    47   val RL: thm list * thm list -> thm list
    48   val MRS: thm list * thm -> thm
    49   val MRL: thm list list * thm list -> thm list
    50   val OF: thm * thm list -> thm
    51   val compose: thm * int * thm -> thm list
    52   val COMP: thm * thm -> thm
    53   val INCR_COMP: thm * thm -> thm
    54   val COMP_INCR: thm * thm -> thm
    55   val read_instantiate_sg: theory -> (string*string)list -> thm -> thm
    56   val read_instantiate: (string*string)list -> thm -> thm
    57   val cterm_instantiate: (cterm*cterm)list -> thm -> thm
    58   val size_of_thm: thm -> int
    59   val reflexive_thm: thm
    60   val symmetric_thm: thm
    61   val transitive_thm: thm
    62   val symmetric_fun: thm -> thm
    63   val extensional: thm -> thm
    64   val equals_cong: thm
    65   val imp_cong: thm
    66   val swap_prems_eq: thm
    67   val asm_rl: thm
    68   val cut_rl: thm
    69   val revcut_rl: thm
    70   val thin_rl: thm
    71   val triv_forall_equality: thm
    72   val distinct_prems_rl: thm
    73   val swap_prems_rl: thm
    74   val equal_intr_rule: thm
    75   val equal_elim_rule1: thm
    76   val equal_elim_rule2: thm
    77   val instantiate': ctyp option list -> cterm option list -> thm -> thm
    78 end;
    79 
    80 signature DRULE =
    81 sig
    82   include BASIC_DRULE
    83   val generalize: string list * string list -> thm -> thm
    84   val list_comb: cterm * cterm list -> cterm
    85   val strip_comb: cterm -> cterm * cterm list
    86   val strip_type: ctyp -> ctyp list * ctyp
    87   val beta_conv: cterm -> cterm -> cterm
    88   val add_used: thm -> string list -> string list
    89   val flexflex_unique: thm -> thm
    90   val close_derivation: thm -> thm
    91   val store_thm: bstring -> thm -> thm
    92   val store_standard_thm: bstring -> thm -> thm
    93   val store_thm_open: bstring -> thm -> thm
    94   val store_standard_thm_open: bstring -> thm -> thm
    95   val compose_single: thm * int * thm -> thm
    96   val add_rule: thm -> thm list -> thm list
    97   val del_rule: thm -> thm list -> thm list
    98   val merge_rules: thm list * thm list -> thm list
    99   val imp_cong_rule: thm -> thm -> thm
   100   val arg_cong_rule: cterm -> thm -> thm
   101   val fun_cong_rule: thm -> cterm -> thm
   102   val beta_eta_conversion: cterm -> thm
   103   val eta_long_conversion: cterm -> thm
   104   val eta_contraction_rule: thm -> thm
   105   val norm_hhf_eq: thm
   106   val is_norm_hhf: term -> bool
   107   val norm_hhf: theory -> term -> term
   108   val norm_hhf_cterm: cterm -> cterm
   109   val unvarify: thm -> thm
   110   val protect: cterm -> cterm
   111   val protectI: thm
   112   val protectD: thm
   113   val protect_cong: thm
   114   val implies_intr_protected: cterm list -> thm -> thm
   115   val termI: thm
   116   val mk_term: cterm -> thm
   117   val dest_term: thm -> cterm
   118   val cterm_rule: (thm -> thm) -> cterm -> cterm
   119   val term_rule: theory -> (thm -> thm) -> term -> term
   120   val sort_triv: theory -> typ * sort -> thm list
   121   val unconstrainTs: thm -> thm
   122   val rename_bvars: (string * string) list -> thm -> thm
   123   val rename_bvars': string option list -> thm -> thm
   124   val incr_indexes: thm -> thm -> thm
   125   val incr_indexes2: thm -> thm -> thm -> thm
   126   val remdups_rl: thm
   127   val multi_resolve: thm list -> thm -> thm Seq.seq
   128   val multi_resolves: thm list -> thm list -> thm Seq.seq
   129   val abs_def: thm -> thm
   130   val read_instantiate_sg': theory -> (indexname * string) list -> thm -> thm
   131   val read_instantiate': (indexname * string) list -> thm -> thm
   132 end;
   133 
   134 structure Drule: DRULE =
   135 struct
   136 
   137 
   138 (** some cterm->cterm operations: faster than calling cterm_of! **)
   139 
   140 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   141 fun strip_imp_prems ct =
   142   let val (cA, cB) = Thm.dest_implies ct
   143   in cA :: strip_imp_prems cB end
   144   handle TERM _ => [];
   145 
   146 (* A1==>...An==>B  goes to B, where B is not an implication *)
   147 fun strip_imp_concl ct =
   148   (case Thm.term_of ct of
   149     Const ("==>", _) $ _ $ _ => strip_imp_concl (Thm.dest_arg ct)
   150   | _ => ct);
   151 
   152 (*The premises of a theorem, as a cterm list*)
   153 val cprems_of = strip_imp_prems o cprop_of;
   154 
   155 fun cterm_fun f ct =
   156   let val {t, thy, ...} = Thm.rep_cterm ct
   157   in Thm.cterm_of thy (f t) end;
   158 
   159 fun ctyp_fun f cT =
   160   let val {T, thy, ...} = Thm.rep_ctyp cT
   161   in Thm.ctyp_of thy (f T) end;
   162 
   163 val cert = cterm_of ProtoPure.thy;
   164 
   165 val implies = cert Term.implies;
   166 fun mk_implies (A, B) = Thm.capply (Thm.capply implies A) B;
   167 
   168 (*cterm version of list_implies: [A1,...,An], B  goes to [|A1;==>;An|]==>B *)
   169 fun list_implies([], B) = B
   170   | list_implies(A::AS, B) = mk_implies (A, list_implies(AS,B));
   171 
   172 (*cterm version of list_comb: maps  (f, [t1,...,tn])  to  f(t1,...,tn) *)
   173 fun list_comb (f, []) = f
   174   | list_comb (f, t::ts) = list_comb (Thm.capply f t, ts);
   175 
   176 (*cterm version of strip_comb: maps  f(t1,...,tn)  to  (f, [t1,...,tn]) *)
   177 fun strip_comb ct =
   178   let
   179     fun stripc (p as (ct, cts)) =
   180       let val (ct1, ct2) = Thm.dest_comb ct
   181       in stripc (ct1, ct2 :: cts) end handle CTERM _ => p
   182   in stripc (ct, []) end;
   183 
   184 (* cterm version of strip_type: maps  [T1,...,Tn]--->T  to   ([T1,T2,...,Tn], T) *)
   185 fun strip_type cT = (case Thm.typ_of cT of
   186     Type ("fun", _) =>
   187       let
   188         val [cT1, cT2] = Thm.dest_ctyp cT;
   189         val (cTs, cT') = strip_type cT2
   190       in (cT1 :: cTs, cT') end
   191   | _ => ([], cT));
   192 
   193 (*Beta-conversion for cterms, where x is an abstraction. Simply returns the rhs
   194   of the meta-equality returned by the beta_conversion rule.*)
   195 fun beta_conv x y =
   196   Thm.dest_arg (cprop_of (Thm.beta_conversion false (Thm.capply x y)));
   197 
   198 
   199 
   200 (** reading of instantiations **)
   201 
   202 fun absent ixn =
   203   error("No such variable in term: " ^ Term.string_of_vname ixn);
   204 
   205 fun inst_failure ixn =
   206   error("Instantiation of " ^ Term.string_of_vname ixn ^ " fails");
   207 
   208 fun read_insts thy (rtypes,rsorts) (types,sorts) used insts =
   209 let
   210     fun is_tv ((a, _), _) =
   211       (case Symbol.explode a of "'" :: _ => true | _ => false);
   212     val (tvs, vs) = List.partition is_tv insts;
   213     fun sort_of ixn = case rsorts ixn of SOME S => S | NONE => absent ixn;
   214     fun readT (ixn, st) =
   215         let val S = sort_of ixn;
   216             val T = Sign.read_def_typ (thy,sorts) st;
   217         in if Sign.typ_instance thy (T, TVar(ixn,S)) then (ixn,T)
   218            else inst_failure ixn
   219         end
   220     val tye = map readT tvs;
   221     fun mkty(ixn,st) = (case rtypes ixn of
   222                           SOME T => (ixn,(st,typ_subst_TVars tye T))
   223                         | NONE => absent ixn);
   224     val ixnsTs = map mkty vs;
   225     val ixns = map fst ixnsTs
   226     and sTs  = map snd ixnsTs
   227     val (cts,tye2) = Thm.read_def_cterms(thy,types,sorts) used false sTs;
   228     fun mkcVar(ixn,T) =
   229         let val U = typ_subst_TVars tye2 T
   230         in cterm_of thy (Var(ixn,U)) end
   231     val ixnTs = ListPair.zip(ixns, map snd sTs)
   232 in (map (fn (ixn, T) => (ctyp_of thy (TVar (ixn, sort_of ixn)),
   233       ctyp_of thy T)) (tye2 @ tye),
   234     ListPair.zip(map mkcVar ixnTs,cts))
   235 end;
   236 
   237 
   238 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   239      Used for establishing default types (of variables) and sorts (of
   240      type variables) when reading another term.
   241      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   242 ***)
   243 
   244 fun types_sorts thm =
   245   let
   246     val vars = Thm.fold_terms Term.add_vars thm [];
   247     val frees = Thm.fold_terms Term.add_frees thm [];
   248     val tvars = Thm.fold_terms Term.add_tvars thm [];
   249     val tfrees = Thm.fold_terms Term.add_tfrees thm [];
   250     fun types (a, i) =
   251       if i < 0 then AList.lookup (op =) frees a else AList.lookup (op =) vars (a, i);
   252     fun sorts (a, i) =
   253       if i < 0 then AList.lookup (op =) tfrees a else AList.lookup (op =) tvars (a, i);
   254   in (types, sorts) end;
   255 
   256 val add_used =
   257   (Thm.fold_terms o fold_types o fold_atyps)
   258     (fn TFree (a, _) => insert (op =) a
   259       | TVar ((a, _), _) => insert (op =) a
   260       | _ => I);
   261 
   262 
   263 
   264 (** Standardization of rules **)
   265 
   266 (* type classes and sorts *)
   267 
   268 fun sort_triv thy (T, S) =
   269   let
   270     val certT = Thm.ctyp_of thy;
   271     val cT = certT T;
   272     fun class_triv c =
   273       Thm.class_triv thy c
   274       |> Thm.instantiate ([(certT (TVar (("'a", 0), [c])), cT)], []);
   275   in map class_triv S end;
   276 
   277 fun unconstrainTs th =
   278   fold (Thm.unconstrainT o Thm.ctyp_of (Thm.theory_of_thm th) o TVar)
   279     (Thm.fold_terms Term.add_tvars th []) th;
   280 
   281 (*Generalization over a list of variables*)
   282 val forall_intr_list = fold_rev forall_intr;
   283 
   284 (*Generalization over all suitable Free variables*)
   285 fun forall_intr_frees th =
   286     let
   287       val {prop, hyps, tpairs, thy,...} = rep_thm th;
   288       val fixed = fold Term.add_frees (Thm.terms_of_tpairs tpairs @ hyps) [];
   289       val frees = Term.fold_aterms (fn Free v =>
   290         if member (op =) fixed v then I else insert (op =) v | _ => I) prop [];
   291     in fold (forall_intr o cterm_of thy o Free) frees th end;
   292 
   293 (*Generalization over Vars -- canonical order*)
   294 fun forall_intr_vars th =
   295   fold forall_intr
   296     (map (Thm.cterm_of (Thm.theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th [])) th;
   297 
   298 val forall_elim_var = PureThy.forall_elim_var;
   299 val forall_elim_vars = PureThy.forall_elim_vars;
   300 
   301 fun outer_params t =
   302   let val vs = Term.strip_all_vars t
   303   in Name.variant_list [] (map (Name.clean o #1) vs) ~~ map #2 vs end;
   304 
   305 (*generalize outermost parameters*)
   306 fun gen_all th =
   307   let
   308     val {thy, prop, maxidx, ...} = Thm.rep_thm th;
   309     val cert = Thm.cterm_of thy;
   310     fun elim (x, T) = Thm.forall_elim (cert (Var ((x, maxidx + 1), T)));
   311   in fold elim (outer_params prop) th end;
   312 
   313 (*lift vars wrt. outermost goal parameters
   314   -- reverses the effect of gen_all modulo higher-order unification*)
   315 fun lift_all goal th =
   316   let
   317     val thy = Theory.merge (Thm.theory_of_cterm goal, Thm.theory_of_thm th);
   318     val cert = Thm.cterm_of thy;
   319     val maxidx = Thm.maxidx_of th;
   320     val ps = outer_params (Thm.term_of goal)
   321       |> map (fn (x, T) => Var ((x, maxidx + 1), Logic.incr_tvar (maxidx + 1) T));
   322     val Ts = map Term.fastype_of ps;
   323     val inst = Thm.fold_terms Term.add_vars th [] |> map (fn (xi, T) =>
   324       (cert (Var (xi, T)), cert (Term.list_comb (Var (xi, Ts ---> T), ps))));
   325   in
   326     th |> Thm.instantiate ([], inst)
   327     |> fold_rev (Thm.forall_intr o cert) ps
   328   end;
   329 
   330 (*direct generalization*)
   331 fun generalize names th = Thm.generalize names (Thm.maxidx_of th + 1) th;
   332 
   333 (*specialization over a list of cterms*)
   334 val forall_elim_list = fold forall_elim;
   335 
   336 (*maps A1,...,An |- B  to  [| A1;...;An |] ==> B*)
   337 val implies_intr_list = fold_rev implies_intr;
   338 
   339 (*maps [| A1;...;An |] ==> B and [A1,...,An]  to  B*)
   340 fun implies_elim_list impth ths = Library.foldl (uncurry implies_elim) (impth,ths);
   341 
   342 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   343 fun zero_var_indexes_list [] = []
   344   | zero_var_indexes_list ths =
   345       let
   346         val thy = Theory.merge_list (map Thm.theory_of_thm ths);
   347         val certT = Thm.ctyp_of thy and cert = Thm.cterm_of thy;
   348         val (instT, inst) = TermSubst.zero_var_indexes_inst (map Thm.full_prop_of ths);
   349         val cinstT = map (fn (v, T) => (certT (TVar v), certT T)) instT;
   350         val cinst = map (fn (v, t) => (cert (Var v), cert t)) inst;
   351       in map (Thm.adjust_maxidx_thm ~1 o Thm.instantiate (cinstT, cinst)) ths end;
   352 
   353 val zero_var_indexes = singleton zero_var_indexes_list;
   354 
   355 
   356 (** Standard form of object-rule: no hypotheses, flexflex constraints,
   357     Frees, or outer quantifiers; all generality expressed by Vars of index 0.**)
   358 
   359 (*Discharge all hypotheses.*)
   360 fun implies_intr_hyps th =
   361   fold Thm.implies_intr (#hyps (Thm.crep_thm th)) th;
   362 
   363 (*Squash a theorem's flexflex constraints provided it can be done uniquely.
   364   This step can lose information.*)
   365 fun flexflex_unique th =
   366   if null (tpairs_of th) then th else
   367     case Seq.chop 2 (flexflex_rule th) of
   368       ([th],_) => th
   369     | ([],_)   => raise THM("flexflex_unique: impossible constraints", 0, [th])
   370     |      _   => raise THM("flexflex_unique: multiple unifiers", 0, [th]);
   371 
   372 fun close_derivation thm =
   373   if Thm.get_name thm = "" then Thm.put_name "" thm
   374   else thm;
   375 
   376 
   377 (* legacy standard operations *)
   378 
   379 val standard' =
   380   implies_intr_hyps
   381   #> forall_intr_frees
   382   #> `Thm.maxidx_of
   383   #-> (fn maxidx =>
   384     forall_elim_vars (maxidx + 1)
   385     #> Thm.strip_shyps
   386     #> zero_var_indexes
   387     #> Thm.varifyT
   388     #> Thm.compress);
   389 
   390 val standard =
   391   flexflex_unique
   392   #> standard'
   393   #> close_derivation;
   394 
   395 
   396 (*Convert all Vars in a theorem to Frees.  Also return a function for
   397   reversing that operation.  DOES NOT WORK FOR TYPE VARIABLES.
   398   Similar code in type/freeze_thaw*)
   399 
   400 fun freeze_thaw_robust th =
   401  let val fth = Thm.freezeT th
   402      val {prop, tpairs, thy, ...} = rep_thm fth
   403  in
   404    case List.foldr add_term_vars [] (prop :: Thm.terms_of_tpairs tpairs) of
   405        [] => (fth, fn i => fn x => x)   (*No vars: nothing to do!*)
   406      | vars =>
   407          let fun newName (Var(ix,_)) = (ix, gensym (string_of_indexname ix))
   408              val alist = map newName vars
   409              fun mk_inst (Var(v,T)) =
   410                  (cterm_of thy (Var(v,T)),
   411                   cterm_of thy (Free(((the o AList.lookup (op =) alist) v), T)))
   412              val insts = map mk_inst vars
   413              fun thaw i th' = (*i is non-negative increment for Var indexes*)
   414                  th' |> forall_intr_list (map #2 insts)
   415                      |> forall_elim_list (map (Thm.incr_indexes_cterm i o #1) insts)
   416          in  (Thm.instantiate ([],insts) fth, thaw)  end
   417  end;
   418 
   419 (*Basic version of the function above. No option to rename Vars apart in thaw.
   420   The Frees created from Vars have nice names. FIXME: does not check for
   421   clashes with variables in the assumptions, so delete and use freeze_thaw_robust instead?*)
   422 fun freeze_thaw th =
   423  let val fth = Thm.freezeT th
   424      val {prop, tpairs, thy, ...} = rep_thm fth
   425  in
   426    case List.foldr add_term_vars [] (prop :: Thm.terms_of_tpairs tpairs) of
   427        [] => (fth, fn x => x)
   428      | vars =>
   429          let fun newName (Var(ix,_), (pairs,used)) =
   430                    let val v = Name.variant used (string_of_indexname ix)
   431                    in  ((ix,v)::pairs, v::used)  end;
   432              val (alist, _) = List.foldr newName ([], Library.foldr add_term_names
   433                (prop :: Thm.terms_of_tpairs tpairs, [])) vars
   434              fun mk_inst (Var(v,T)) =
   435                  (cterm_of thy (Var(v,T)),
   436                   cterm_of thy (Free(((the o AList.lookup (op =) alist) v), T)))
   437              val insts = map mk_inst vars
   438              fun thaw th' =
   439                  th' |> forall_intr_list (map #2 insts)
   440                      |> forall_elim_list (map #1 insts)
   441          in  (Thm.instantiate ([],insts) fth, thaw)  end
   442  end;
   443 
   444 (*Rotates a rule's premises to the left by k*)
   445 val rotate_prems = permute_prems 0;
   446 
   447 (* permute prems, where the i-th position in the argument list (counting from 0)
   448    gives the position within the original thm to be transferred to position i.
   449    Any remaining trailing positions are left unchanged. *)
   450 val rearrange_prems = let
   451   fun rearr new []      thm = thm
   452   |   rearr new (p::ps) thm = rearr (new+1)
   453      (map (fn q => if new<=q andalso q<p then q+1 else q) ps)
   454      (permute_prems (new+1) (new-p) (permute_prems new (p-new) thm))
   455   in rearr 0 end;
   456 
   457 (*Resolution: exactly one resolvent must be produced.*)
   458 fun tha RSN (i,thb) =
   459   case Seq.chop 2 (biresolution false [(false,tha)] i thb) of
   460       ([th],_) => th
   461     | ([],_)   => raise THM("RSN: no unifiers", i, [tha,thb])
   462     |      _   => raise THM("RSN: multiple unifiers", i, [tha,thb]);
   463 
   464 (*resolution: P==>Q, Q==>R gives P==>R. *)
   465 fun tha RS thb = tha RSN (1,thb);
   466 
   467 (*For joining lists of rules*)
   468 fun thas RLN (i,thbs) =
   469   let val resolve = biresolution false (map (pair false) thas) i
   470       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   471   in maps resb thbs end;
   472 
   473 fun thas RL thbs = thas RLN (1,thbs);
   474 
   475 (*Resolve a list of rules against bottom_rl from right to left;
   476   makes proof trees*)
   477 fun rls MRS bottom_rl =
   478   let fun rs_aux i [] = bottom_rl
   479         | rs_aux i (rl::rls) = rl RSN (i, rs_aux (i+1) rls)
   480   in  rs_aux 1 rls  end;
   481 
   482 (*As above, but for rule lists*)
   483 fun rlss MRL bottom_rls =
   484   let fun rs_aux i [] = bottom_rls
   485         | rs_aux i (rls::rlss) = rls RLN (i, rs_aux (i+1) rlss)
   486   in  rs_aux 1 rlss  end;
   487 
   488 (*A version of MRS with more appropriate argument order*)
   489 fun bottom_rl OF rls = rls MRS bottom_rl;
   490 
   491 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   492   with no lifting or renaming!  Q may contain ==> or meta-quants
   493   ALWAYS deletes premise i *)
   494 fun compose(tha,i,thb) =
   495     Seq.list_of (bicompose false (false,tha,0) i thb);
   496 
   497 fun compose_single (tha,i,thb) =
   498   (case compose (tha,i,thb) of
   499     [th] => th
   500   | _ => raise THM ("compose: unique result expected", i, [tha,thb]));
   501 
   502 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   503 fun tha COMP thb =
   504     case distinct Thm.eq_thm (compose(tha,1,thb)) of
   505         [th] => th
   506       | _ =>   raise THM("COMP", 1, [tha,thb]);
   507 
   508 
   509 (** theorem equality **)
   510 
   511 (*Useful "distance" function for BEST_FIRST*)
   512 val size_of_thm = size_of_term o Thm.full_prop_of;
   513 
   514 (*maintain lists of theorems --- preserving canonical order*)
   515 val del_rule = remove Thm.eq_thm_prop;
   516 fun add_rule th = cons th o del_rule th;
   517 val merge_rules = Library.merge Thm.eq_thm_prop;
   518 
   519 
   520 
   521 (*** Meta-Rewriting Rules ***)
   522 
   523 fun read_prop s = Thm.read_cterm ProtoPure.thy (s, propT);
   524 
   525 fun store_thm name thm = hd (PureThy.smart_store_thms (name, [thm]));
   526 fun store_standard_thm name thm = store_thm name (standard thm);
   527 fun store_thm_open name thm = hd (PureThy.smart_store_thms_open (name, [thm]));
   528 fun store_standard_thm_open name thm = store_thm_open name (standard' thm);
   529 
   530 val reflexive_thm =
   531   let val cx = cert (Var(("x",0),TVar(("'a",0),[])))
   532   in store_standard_thm_open "reflexive" (Thm.reflexive cx) end;
   533 
   534 val symmetric_thm =
   535   let val xy = read_prop "x == y"
   536   in store_standard_thm_open "symmetric" (Thm.implies_intr xy (Thm.symmetric (Thm.assume xy))) end;
   537 
   538 val transitive_thm =
   539   let val xy = read_prop "x == y"
   540       val yz = read_prop "y == z"
   541       val xythm = Thm.assume xy and yzthm = Thm.assume yz
   542   in store_standard_thm_open "transitive" (Thm.implies_intr yz (Thm.transitive xythm yzthm)) end;
   543 
   544 fun symmetric_fun thm = thm RS symmetric_thm;
   545 
   546 fun extensional eq =
   547   let val eq' =
   548     abstract_rule "x" (Thm.dest_arg (fst (Thm.dest_equals (cprop_of eq)))) eq
   549   in equal_elim (eta_conversion (cprop_of eq')) eq' end;
   550 
   551 val equals_cong =
   552   store_standard_thm_open "equals_cong" (Thm.reflexive (read_prop "x == y"));
   553 
   554 val imp_cong =
   555   let
   556     val ABC = read_prop "PROP A ==> PROP B == PROP C"
   557     val AB = read_prop "PROP A ==> PROP B"
   558     val AC = read_prop "PROP A ==> PROP C"
   559     val A = read_prop "PROP A"
   560   in
   561     store_standard_thm_open "imp_cong" (implies_intr ABC (equal_intr
   562       (implies_intr AB (implies_intr A
   563         (equal_elim (implies_elim (assume ABC) (assume A))
   564           (implies_elim (assume AB) (assume A)))))
   565       (implies_intr AC (implies_intr A
   566         (equal_elim (symmetric (implies_elim (assume ABC) (assume A)))
   567           (implies_elim (assume AC) (assume A)))))))
   568   end;
   569 
   570 val swap_prems_eq =
   571   let
   572     val ABC = read_prop "PROP A ==> PROP B ==> PROP C"
   573     val BAC = read_prop "PROP B ==> PROP A ==> PROP C"
   574     val A = read_prop "PROP A"
   575     val B = read_prop "PROP B"
   576   in
   577     store_standard_thm_open "swap_prems_eq" (equal_intr
   578       (implies_intr ABC (implies_intr B (implies_intr A
   579         (implies_elim (implies_elim (assume ABC) (assume A)) (assume B)))))
   580       (implies_intr BAC (implies_intr A (implies_intr B
   581         (implies_elim (implies_elim (assume BAC) (assume B)) (assume A))))))
   582   end;
   583 
   584 val imp_cong_rule = Thm.combination o Thm.combination (Thm.reflexive implies);
   585 
   586 fun arg_cong_rule ct th = Thm.combination (Thm.reflexive ct) th;    (*AP_TERM*)
   587 fun fun_cong_rule th ct = Thm.combination th (Thm.reflexive ct);    (*AP_THM*)
   588 
   589 local
   590   val dest_eq = Thm.dest_equals o cprop_of
   591   val rhs_of = snd o dest_eq
   592 in
   593 fun beta_eta_conversion t =
   594   let val thm = beta_conversion true t
   595   in transitive thm (eta_conversion (rhs_of thm)) end
   596 end;
   597 
   598 fun eta_long_conversion ct = transitive (beta_eta_conversion ct)
   599   (symmetric (beta_eta_conversion (cterm_fun (Pattern.eta_long []) ct)));
   600 
   601 (*Contract all eta-redexes in the theorem, lest they give rise to needless abstractions*)
   602 fun eta_contraction_rule th =
   603   equal_elim (eta_conversion (cprop_of th)) th;
   604 
   605 val abs_def =
   606   let
   607     fun contract_lhs th =
   608       Thm.transitive (Thm.symmetric (beta_eta_conversion
   609         (fst (Thm.dest_equals (cprop_of th))))) th;
   610     fun abstract cx th = Thm.abstract_rule
   611         (case Thm.term_of cx of Var ((x, _), _) => x | Free (x, _) => x | _ => "x") cx th
   612       handle THM _ => raise THM ("Malformed definitional equation", 0, [th]);
   613   in
   614     contract_lhs
   615     #> `(snd o strip_comb o fst o Thm.dest_equals o cprop_of)
   616     #-> fold_rev abstract
   617     #> contract_lhs
   618   end;
   619 
   620 
   621 (*** Some useful meta-theorems ***)
   622 
   623 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   624 val asm_rl = store_standard_thm_open "asm_rl" (Thm.trivial (read_prop "PROP ?psi"));
   625 val _ = store_thm "_" asm_rl;
   626 
   627 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   628 val cut_rl =
   629   store_standard_thm_open "cut_rl"
   630     (Thm.trivial (read_prop "PROP ?psi ==> PROP ?theta"));
   631 
   632 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   633      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   634 val revcut_rl =
   635   let val V = read_prop "PROP V"
   636       and VW = read_prop "PROP V ==> PROP W";
   637   in
   638     store_standard_thm_open "revcut_rl"
   639       (implies_intr V (implies_intr VW (implies_elim (assume VW) (assume V))))
   640   end;
   641 
   642 (*for deleting an unwanted assumption*)
   643 val thin_rl =
   644   let val V = read_prop "PROP V"
   645       and W = read_prop "PROP W";
   646   in store_standard_thm_open "thin_rl" (implies_intr V (implies_intr W (assume W))) end;
   647 
   648 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   649 val triv_forall_equality =
   650   let val V  = read_prop "PROP V"
   651       and QV = read_prop "!!x::'a. PROP V"
   652       and x  = cert (Free ("x", Term.aT []));
   653   in
   654     store_standard_thm_open "triv_forall_equality"
   655       (equal_intr (implies_intr QV (forall_elim x (assume QV)))
   656         (implies_intr V  (forall_intr x (assume V))))
   657   end;
   658 
   659 (* (PROP ?Phi ==> PROP ?Phi ==> PROP ?Psi) ==>
   660    (PROP ?Phi ==> PROP ?Psi)
   661 *)
   662 val distinct_prems_rl =
   663   let
   664     val AAB = read_prop "PROP Phi ==> PROP Phi ==> PROP Psi"
   665     val A = read_prop "PROP Phi";
   666   in
   667     store_standard_thm_open "distinct_prems_rl"
   668       (implies_intr_list [AAB, A] (implies_elim_list (assume AAB) [assume A, assume A]))
   669   end;
   670 
   671 (* (PROP ?PhiA ==> PROP ?PhiB ==> PROP ?Psi) ==>
   672    (PROP ?PhiB ==> PROP ?PhiA ==> PROP ?Psi)
   673    `thm COMP swap_prems_rl' swaps the first two premises of `thm'
   674 *)
   675 val swap_prems_rl =
   676   let val cmajor = read_prop "PROP PhiA ==> PROP PhiB ==> PROP Psi";
   677       val major = assume cmajor;
   678       val cminor1 = read_prop "PROP PhiA";
   679       val minor1 = assume cminor1;
   680       val cminor2 = read_prop "PROP PhiB";
   681       val minor2 = assume cminor2;
   682   in store_standard_thm_open "swap_prems_rl"
   683        (implies_intr cmajor (implies_intr cminor2 (implies_intr cminor1
   684          (implies_elim (implies_elim major minor1) minor2))))
   685   end;
   686 
   687 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   688    ==> PROP ?phi == PROP ?psi
   689    Introduction rule for == as a meta-theorem.
   690 *)
   691 val equal_intr_rule =
   692   let val PQ = read_prop "PROP phi ==> PROP psi"
   693       and QP = read_prop "PROP psi ==> PROP phi"
   694   in
   695     store_standard_thm_open "equal_intr_rule"
   696       (implies_intr PQ (implies_intr QP (equal_intr (assume PQ) (assume QP))))
   697   end;
   698 
   699 (* PROP ?phi == PROP ?psi ==> PROP ?phi ==> PROP ?psi *)
   700 val equal_elim_rule1 =
   701   let val eq = read_prop "PROP phi == PROP psi"
   702       and P = read_prop "PROP phi"
   703   in store_standard_thm_open "equal_elim_rule1"
   704     (Thm.equal_elim (assume eq) (assume P) |> implies_intr_list [eq, P])
   705   end;
   706 
   707 (* PROP ?psi == PROP ?phi ==> PROP ?phi ==> PROP ?psi *)
   708 val equal_elim_rule2 =
   709   store_standard_thm_open "equal_elim_rule2" (symmetric_thm RS equal_elim_rule1);
   710 
   711 (* "[| PROP ?phi; PROP ?phi; PROP ?psi |] ==> PROP ?psi" *)
   712 val remdups_rl =
   713   let val P = read_prop "PROP phi" and Q = read_prop "PROP psi";
   714   in store_standard_thm_open "remdups_rl" (implies_intr_list [P, P, Q] (Thm.assume Q)) end;
   715 
   716 
   717 (*(PROP ?phi ==> (!!x. PROP ?psi(x))) == (!!x. PROP ?phi ==> PROP ?psi(x))
   718   Rewrite rule for HHF normalization.*)
   719 
   720 val norm_hhf_eq =
   721   let
   722     val aT = TFree ("'a", []);
   723     val all = Term.all aT;
   724     val x = Free ("x", aT);
   725     val phi = Free ("phi", propT);
   726     val psi = Free ("psi", aT --> propT);
   727 
   728     val cx = cert x;
   729     val cphi = cert phi;
   730     val lhs = cert (Logic.mk_implies (phi, all $ Abs ("x", aT, psi $ Bound 0)));
   731     val rhs = cert (all $ Abs ("x", aT, Logic.mk_implies (phi, psi $ Bound 0)));
   732   in
   733     Thm.equal_intr
   734       (Thm.implies_elim (Thm.assume lhs) (Thm.assume cphi)
   735         |> Thm.forall_elim cx
   736         |> Thm.implies_intr cphi
   737         |> Thm.forall_intr cx
   738         |> Thm.implies_intr lhs)
   739       (Thm.implies_elim
   740           (Thm.assume rhs |> Thm.forall_elim cx) (Thm.assume cphi)
   741         |> Thm.forall_intr cx
   742         |> Thm.implies_intr cphi
   743         |> Thm.implies_intr rhs)
   744     |> store_standard_thm_open "norm_hhf_eq"
   745   end;
   746 
   747 val norm_hhf_prop = Logic.dest_equals (Thm.prop_of norm_hhf_eq);
   748 
   749 fun is_norm_hhf tm =
   750   let
   751     fun is_norm (Const ("==>", _) $ _ $ (Const ("all", _) $ _)) = false
   752       | is_norm (t $ u) = is_norm t andalso is_norm u
   753       | is_norm (Abs (_, _, t)) = is_norm t
   754       | is_norm _ = true;
   755   in is_norm (Envir.beta_eta_contract tm) end;
   756 
   757 fun norm_hhf thy t =
   758   if is_norm_hhf t then t
   759   else Pattern.rewrite_term thy [norm_hhf_prop] [] t;
   760 
   761 fun norm_hhf_cterm ct =
   762   if is_norm_hhf (Thm.term_of ct) then ct
   763   else cterm_fun (Pattern.rewrite_term (Thm.theory_of_cterm ct) [norm_hhf_prop] []) ct;
   764 
   765 
   766 (* var indexes *)
   767 
   768 fun incr_indexes th = Thm.incr_indexes (Thm.maxidx_of th + 1);
   769 
   770 fun incr_indexes2 th1 th2 =
   771   Thm.incr_indexes (Int.max (Thm.maxidx_of th1, Thm.maxidx_of th2) + 1);
   772 
   773 fun th1 INCR_COMP th2 = incr_indexes th2 th1 COMP th2;
   774 fun th1 COMP_INCR th2 = th1 COMP incr_indexes th1 th2;
   775 
   776 
   777 (*** Instantiate theorem th, reading instantiations in theory thy ****)
   778 
   779 (*Version that normalizes the result: Thm.instantiate no longer does that*)
   780 fun instantiate instpair th =
   781   Thm.adjust_maxidx_thm ~1 (Thm.instantiate instpair th COMP_INCR asm_rl);
   782 
   783 fun read_instantiate_sg' thy sinsts th =
   784     let val ts = types_sorts th;
   785         val used = add_used th [];
   786     in  instantiate (read_insts thy ts ts used sinsts) th  end;
   787 
   788 fun read_instantiate_sg thy sinsts th =
   789   read_instantiate_sg' thy (map (apfst Syntax.read_indexname) sinsts) th;
   790 
   791 (*Instantiate theorem th, reading instantiations under theory of th*)
   792 fun read_instantiate sinsts th =
   793     read_instantiate_sg (Thm.theory_of_thm th) sinsts th;
   794 
   795 fun read_instantiate' sinsts th =
   796     read_instantiate_sg' (Thm.theory_of_thm th) sinsts th;
   797 
   798 
   799 (*Left-to-right replacements: tpairs = [...,(vi,ti),...].
   800   Instantiates distinct Vars by terms, inferring type instantiations. *)
   801 local
   802   fun add_types ((ct,cu), (thy,tye,maxidx)) =
   803     let val {thy=thyt, t=t, T= T, maxidx=maxt,...} = rep_cterm ct
   804         and {thy=thyu, t=u, T= U, maxidx=maxu,...} = rep_cterm cu;
   805         val maxi = Int.max(maxidx, Int.max(maxt, maxu));
   806         val thy' = Theory.merge(thy, Theory.merge(thyt, thyu))
   807         val (tye',maxi') = Sign.typ_unify thy' (T, U) (tye, maxi)
   808           handle Type.TUNIFY => raise TYPE("Ill-typed instantiation", [T,U], [t,u])
   809     in  (thy', tye', maxi')  end;
   810 in
   811 fun cterm_instantiate [] th = th
   812   | cterm_instantiate ctpairs0 th =
   813   let val (thy,tye,_) = List.foldr add_types (Thm.theory_of_thm th, Vartab.empty, 0) ctpairs0
   814       fun instT(ct,cu) =
   815         let val inst = cterm_of thy o Term.map_types (Envir.norm_type tye) o term_of
   816         in (inst ct, inst cu) end
   817       fun ctyp2 (ixn, (S, T)) = (ctyp_of thy (TVar (ixn, S)), ctyp_of thy (Envir.norm_type tye T))
   818   in  instantiate (map ctyp2 (Vartab.dest tye), map instT ctpairs0) th  end
   819   handle TERM _ =>
   820            raise THM("cterm_instantiate: incompatible theories",0,[th])
   821        | TYPE (msg, _, _) => raise THM(msg, 0, [th])
   822 end;
   823 
   824 
   825 (* global schematic variables *)
   826 
   827 fun unvarify th =
   828   let
   829     val thy = Thm.theory_of_thm th;
   830     val cert = Thm.cterm_of thy;
   831     val certT = Thm.ctyp_of thy;
   832 
   833     val prop = Thm.full_prop_of th;
   834     val _ = map Logic.unvarify (prop :: Thm.hyps_of th)
   835       handle TERM (msg, _) => raise THM (msg, 0, [th]);
   836 
   837     val instT0 = rev (Term.add_tvars prop []) |> map (fn v as ((a, _), S) => (v, TFree (a, S)));
   838     val instT = map (fn (v, T) => (certT (TVar v), certT T)) instT0;
   839     val inst = rev (Term.add_vars prop []) |> map (fn ((a, i), T) =>
   840       let val T' = TermSubst.instantiateT instT0 T
   841       in (cert (Var ((a, i), T')), cert (Free ((a, T')))) end);
   842   in Thm.instantiate (instT, inst) th end;
   843 
   844 
   845 (** protected propositions and embedded terms **)
   846 
   847 local
   848   val A = cert (Free ("A", propT));
   849   val prop_def = unvarify ProtoPure.prop_def;
   850   val term_def = unvarify ProtoPure.term_def;
   851 in
   852   val protect = Thm.capply (cert Logic.protectC);
   853   val protectI = store_thm "protectI" (PureThy.kind_rule Thm.internalK (standard
   854       (Thm.equal_elim (Thm.symmetric prop_def) (Thm.assume A))));
   855   val protectD = store_thm "protectD" (PureThy.kind_rule Thm.internalK (standard
   856       (Thm.equal_elim prop_def (Thm.assume (protect A)))));
   857   val protect_cong = store_standard_thm_open "protect_cong" (Thm.reflexive (protect A));
   858 
   859   val termI = store_thm "termI" (PureThy.kind_rule Thm.internalK (standard
   860       (Thm.equal_elim (Thm.symmetric term_def) (Thm.forall_intr A (Thm.trivial A)))));
   861 end;
   862 
   863 fun implies_intr_protected asms th =
   864   let val asms' = map protect asms in
   865     implies_elim_list
   866       (implies_intr_list asms th)
   867       (map (fn asm' => Thm.assume asm' RS protectD) asms')
   868     |> implies_intr_list asms'
   869   end;
   870 
   871 fun mk_term ct =
   872   let
   873     val {thy, T, ...} = Thm.rep_cterm ct;
   874     val cert = Thm.cterm_of thy;
   875     val certT = Thm.ctyp_of thy;
   876     val a = certT (TVar (("'a", 0), []));
   877     val x = cert (Var (("x", 0), T));
   878   in Thm.instantiate ([(a, certT T)], [(x, ct)]) termI end;
   879 
   880 fun dest_term th =
   881   let val cprop = strip_imp_concl (Thm.cprop_of th) in
   882     if can Logic.dest_term (Thm.term_of cprop) then
   883       Thm.dest_arg cprop
   884     else raise THM ("dest_term", 0, [th])
   885   end;
   886 
   887 fun cterm_rule f = dest_term o f o mk_term;
   888 fun term_rule thy f t = Thm.term_of (cterm_rule f (Thm.cterm_of thy t));
   889 
   890 
   891 
   892 (** variations on instantiate **)
   893 
   894 (* instantiate by left-to-right occurrence of variables *)
   895 
   896 fun instantiate' cTs cts thm =
   897   let
   898     fun err msg =
   899       raise TYPE ("instantiate': " ^ msg,
   900         map_filter (Option.map Thm.typ_of) cTs,
   901         map_filter (Option.map Thm.term_of) cts);
   902 
   903     fun inst_of (v, ct) =
   904       (Thm.cterm_of (Thm.theory_of_cterm ct) (Var v), ct)
   905         handle TYPE (msg, _, _) => err msg;
   906 
   907     fun tyinst_of (v, cT) =
   908       (Thm.ctyp_of (Thm.theory_of_ctyp cT) (TVar v), cT)
   909         handle TYPE (msg, _, _) => err msg;
   910 
   911     fun zip_vars xs ys =
   912       zip_options xs ys handle Library.UnequalLengths =>
   913         err "more instantiations than variables in thm";
   914 
   915     (*instantiate types first!*)
   916     val thm' =
   917       if forall is_none cTs then thm
   918       else Thm.instantiate
   919         (map tyinst_of (zip_vars (rev (Thm.fold_terms Term.add_tvars thm [])) cTs), []) thm;
   920     val thm'' =
   921       if forall is_none cts then thm'
   922       else Thm.instantiate
   923         ([], map inst_of (zip_vars (rev (Thm.fold_terms Term.add_vars thm' [])) cts)) thm';
   924     in thm'' end;
   925 
   926 
   927 
   928 (** renaming of bound variables **)
   929 
   930 (* replace bound variables x_i in thm by y_i *)
   931 (* where vs = [(x_1, y_1), ..., (x_n, y_n)]  *)
   932 
   933 fun rename_bvars [] thm = thm
   934   | rename_bvars vs thm =
   935     let
   936       val {thy, prop, ...} = rep_thm thm;
   937       fun ren (Abs (x, T, t)) = Abs (AList.lookup (op =) vs x |> the_default x, T, ren t)
   938         | ren (t $ u) = ren t $ ren u
   939         | ren t = t;
   940     in equal_elim (reflexive (cterm_of thy (ren prop))) thm end;
   941 
   942 
   943 (* renaming in left-to-right order *)
   944 
   945 fun rename_bvars' xs thm =
   946   let
   947     val {thy, prop, ...} = rep_thm thm;
   948     fun rename [] t = ([], t)
   949       | rename (x' :: xs) (Abs (x, T, t)) =
   950           let val (xs', t') = rename xs t
   951           in (xs', Abs (the_default x x', T, t')) end
   952       | rename xs (t $ u) =
   953           let
   954             val (xs', t') = rename xs t;
   955             val (xs'', u') = rename xs' u
   956           in (xs'', t' $ u') end
   957       | rename xs t = (xs, t);
   958   in case rename xs prop of
   959       ([], prop') => equal_elim (reflexive (cterm_of thy prop')) thm
   960     | _ => error "More names than abstractions in theorem"
   961   end;
   962 
   963 
   964 
   965 (** multi_resolve **)
   966 
   967 local
   968 
   969 fun res th i rule =
   970   Thm.biresolution false [(false, th)] i rule handle THM _ => Seq.empty;
   971 
   972 fun multi_res _ [] rule = Seq.single rule
   973   | multi_res i (th :: ths) rule = Seq.maps (res th i) (multi_res (i + 1) ths rule);
   974 
   975 in
   976 
   977 val multi_resolve = multi_res 1;
   978 fun multi_resolves facts rules = Seq.maps (multi_resolve facts) (Seq.of_list rules);
   979 
   980 end;
   981 
   982 end;
   983 
   984 structure BasicDrule: BASIC_DRULE = Drule;
   985 open BasicDrule;