src/Pure/drule.ML
author wenzelm
Fri Nov 10 19:09:40 2000 +0100 (2000-11-10)
changeset 10441 d727c39c4a4b
parent 10414 f7aeff3e9e1e
child 10515 8430c8fa8a9f
permissions -rw-r--r--
store_standard_thm "norm_hhf_eq";
     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;
    10 
    11 signature BASIC_DRULE =
    12 sig
    13   val mk_implies        : cterm * cterm -> cterm
    14   val list_implies      : cterm list * cterm -> cterm
    15   val dest_implies      : cterm -> cterm * cterm
    16   val dest_equals       : cterm -> cterm * cterm
    17   val skip_flexpairs    : cterm -> cterm
    18   val strip_imp_prems   : cterm -> cterm list
    19   val strip_imp_concl   : cterm -> cterm
    20   val cprems_of         : thm -> cterm list
    21   val read_insts        :
    22           Sign.sg -> (indexname -> typ option) * (indexname -> sort option)
    23                   -> (indexname -> typ option) * (indexname -> sort option)
    24                   -> string list -> (string*string)list
    25                   -> (indexname*ctyp)list * (cterm*cterm)list
    26   val types_sorts: thm -> (indexname-> typ option) * (indexname-> sort option)
    27   val strip_shyps_warning : thm -> thm
    28   val forall_intr_list  : cterm list -> thm -> thm
    29   val forall_intr_frees : thm -> thm
    30   val forall_intr_vars  : thm -> thm
    31   val forall_elim_list  : cterm list -> thm -> thm
    32   val forall_elim_var   : int -> thm -> thm
    33   val forall_elim_vars  : int -> thm -> thm
    34   val forall_elim_vars_safe  : thm -> thm
    35   val freeze_thaw       : thm -> thm * (thm -> thm)
    36   val implies_elim_list : thm -> thm list -> thm
    37   val implies_intr_list : cterm list -> thm -> thm
    38   val instantiate       :
    39     (indexname * ctyp) list * (cterm * cterm) list -> thm -> thm
    40   val zero_var_indexes  : thm -> thm
    41   val standard          : thm -> thm
    42   val rotate_prems      : int -> thm -> thm
    43   val assume_ax         : theory -> string -> 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 read_instantiate_sg: Sign.sg -> (string*string)list -> thm -> thm
    54   val read_instantiate  : (string*string)list -> thm -> thm
    55   val cterm_instantiate : (cterm*cterm)list -> thm -> thm
    56   val weak_eq_thm       : thm * thm -> bool
    57   val eq_thm_sg         : thm * thm -> bool
    58   val size_of_thm       : thm -> int
    59   val reflexive_thm     : thm
    60   val symmetric_thm     : thm
    61   val transitive_thm    : thm
    62   val refl_implies      : thm
    63   val symmetric_fun     : thm -> thm
    64   val imp_cong          : thm
    65   val swap_prems_eq     : thm
    66   val equal_abs_elim    : cterm  -> thm -> thm
    67   val equal_abs_elim_list: cterm list -> thm -> thm
    68   val flexpair_abs_elim_list: cterm list -> thm -> thm
    69   val asm_rl            : thm
    70   val cut_rl            : thm
    71   val revcut_rl         : thm
    72   val thin_rl           : thm
    73   val triv_forall_equality: thm
    74   val swap_prems_rl     : thm
    75   val equal_intr_rule   : thm
    76   val inst              : string -> string -> thm -> thm
    77   val instantiate'      : ctyp option list -> cterm option list -> thm -> thm
    78   val incr_indexes_wrt  : int list -> ctyp list -> cterm list -> thm list -> thm -> thm
    79 end;
    80 
    81 signature DRULE =
    82 sig
    83   include BASIC_DRULE
    84   val rule_attribute    : ('a -> thm -> thm) -> 'a attribute
    85   val tag_rule          : tag -> thm -> thm
    86   val untag_rule        : string -> thm -> thm
    87   val tag               : tag -> 'a attribute
    88   val untag             : string -> 'a attribute
    89   val tag_lemma         : 'a attribute
    90   val tag_assumption    : 'a attribute
    91   val tag_internal      : 'a attribute
    92   val has_internal	: tag list -> bool
    93   val compose_single    : thm * int * thm -> thm
    94   val add_rules		: thm list -> thm list -> thm list
    95   val del_rules		: thm list -> thm list -> thm list
    96   val merge_rules	: thm list * thm list -> thm list
    97   val norm_hhf_eq	: thm
    98   val triv_goal         : thm
    99   val rev_triv_goal     : thm
   100   val freeze_all        : thm -> thm
   101   val mk_triv_goal      : cterm -> thm
   102   val mk_cgoal          : cterm -> cterm
   103   val assume_goal       : cterm -> thm
   104   val tvars_of_terms    : term list -> (indexname * sort) list
   105   val vars_of_terms     : term list -> (indexname * typ) list
   106   val tvars_of          : thm -> (indexname * sort) list
   107   val vars_of           : thm -> (indexname * typ) list
   108   val unvarifyT         : thm -> thm
   109   val unvarify          : thm -> thm
   110   val tvars_intr_list	: string list -> thm -> thm
   111 end;
   112 
   113 structure Drule: DRULE =
   114 struct
   115 
   116 
   117 (** some cterm->cterm operations: much faster than calling cterm_of! **)
   118 
   119 (** SAME NAMES as in structure Logic: use compound identifiers! **)
   120 
   121 (*dest_implies for cterms. Note T=prop below*)
   122 fun dest_implies ct =
   123     case term_of ct of
   124         (Const("==>", _) $ _ $ _) =>
   125             let val (ct1,ct2) = dest_comb ct
   126             in  (#2 (dest_comb ct1), ct2)  end
   127       | _ => raise TERM ("dest_implies", [term_of ct]) ;
   128 
   129 fun dest_equals ct =
   130     case term_of ct of
   131         (Const("==", _) $ _ $ _) =>
   132             let val (ct1,ct2) = dest_comb ct
   133             in  (#2 (dest_comb ct1), ct2)  end
   134       | _ => raise TERM ("dest_equals", [term_of ct]) ;
   135 
   136 
   137 (*Discard flexflex pairs; return a cterm*)
   138 fun skip_flexpairs ct =
   139     case term_of ct of
   140         (Const("==>", _) $ (Const("=?=",_)$_$_) $ _) =>
   141             skip_flexpairs (#2 (dest_implies ct))
   142       | _ => ct;
   143 
   144 (* A1==>...An==>B  goes to  [A1,...,An], where B is not an implication *)
   145 fun strip_imp_prems ct =
   146     let val (cA,cB) = dest_implies ct
   147     in  cA :: strip_imp_prems cB  end
   148     handle TERM _ => [];
   149 
   150 (* A1==>...An==>B  goes to B, where B is not an implication *)
   151 fun strip_imp_concl ct =
   152     case term_of ct of (Const("==>", _) $ _ $ _) =>
   153         strip_imp_concl (#2 (dest_comb ct))
   154   | _ => ct;
   155 
   156 (*The premises of a theorem, as a cterm list*)
   157 val cprems_of = strip_imp_prems o skip_flexpairs o cprop_of;
   158 
   159 val proto_sign = Theory.sign_of ProtoPure.thy;
   160 
   161 val implies = cterm_of proto_sign Term.implies;
   162 
   163 (*cterm version of mk_implies*)
   164 fun mk_implies(A,B) = capply (capply implies A) B;
   165 
   166 (*cterm version of list_implies: [A1,...,An], B  goes to [|A1;==>;An|]==>B *)
   167 fun list_implies([], B) = B
   168   | list_implies(A::AS, B) = mk_implies (A, list_implies(AS,B));
   169 
   170 
   171 (** reading of instantiations **)
   172 
   173 fun absent ixn =
   174   error("No such variable in term: " ^ Syntax.string_of_vname ixn);
   175 
   176 fun inst_failure ixn =
   177   error("Instantiation of " ^ Syntax.string_of_vname ixn ^ " fails");
   178 
   179 fun read_insts sign (rtypes,rsorts) (types,sorts) used insts =
   180 let
   181     fun split([],tvs,vs) = (tvs,vs)
   182       | split((sv,st)::l,tvs,vs) = (case Symbol.explode sv of
   183                   "'"::cs => split(l,(Syntax.indexname cs,st)::tvs,vs)
   184                 | cs => split(l,tvs,(Syntax.indexname cs,st)::vs));
   185     val (tvs,vs) = split(insts,[],[]);
   186     fun readT((a,i),st) =
   187         let val ixn = ("'" ^ a,i);
   188             val S = case rsorts ixn of Some S => S | None => absent ixn;
   189             val T = Sign.read_typ (sign,sorts) st;
   190         in if Sign.typ_instance sign (T, TVar(ixn,S)) then (ixn,T)
   191            else inst_failure ixn
   192         end
   193     val tye = map readT tvs;
   194     fun mkty(ixn,st) = (case rtypes ixn of
   195                           Some T => (ixn,(st,typ_subst_TVars tye T))
   196                         | None => absent ixn);
   197     val ixnsTs = map mkty vs;
   198     val ixns = map fst ixnsTs
   199     and sTs  = map snd ixnsTs
   200     val (cts,tye2) = read_def_cterms(sign,types,sorts) used false sTs;
   201     fun mkcVar(ixn,T) =
   202         let val U = typ_subst_TVars tye2 T
   203         in cterm_of sign (Var(ixn,U)) end
   204     val ixnTs = ListPair.zip(ixns, map snd sTs)
   205 in (map (fn (ixn,T) => (ixn,ctyp_of sign T)) (tye2 @ tye),
   206     ListPair.zip(map mkcVar ixnTs,cts))
   207 end;
   208 
   209 
   210 (*** Find the type (sort) associated with a (T)Var or (T)Free in a term
   211      Used for establishing default types (of variables) and sorts (of
   212      type variables) when reading another term.
   213      Index -1 indicates that a (T)Free rather than a (T)Var is wanted.
   214 ***)
   215 
   216 fun types_sorts thm =
   217     let val {prop,hyps,...} = rep_thm thm;
   218         val big = list_comb(prop,hyps); (* bogus term! *)
   219         val vars = map dest_Var (term_vars big);
   220         val frees = map dest_Free (term_frees big);
   221         val tvars = term_tvars big;
   222         val tfrees = term_tfrees big;
   223         fun typ(a,i) = if i<0 then assoc(frees,a) else assoc(vars,(a,i));
   224         fun sort(a,i) = if i<0 then assoc(tfrees,a) else assoc(tvars,(a,i));
   225     in (typ,sort) end;
   226 
   227 
   228 
   229 (** basic attributes **)
   230 
   231 (* dependent rules *)
   232 
   233 fun rule_attribute f (x, thm) = (x, (f x thm));
   234 
   235 
   236 (* add / delete tags *)
   237 
   238 fun map_tags f thm =
   239   Thm.put_name_tags (Thm.name_of_thm thm, f (#2 (Thm.get_name_tags thm))) thm;
   240 
   241 fun tag_rule tg = map_tags (fn tgs => if tg mem tgs then tgs else tgs @ [tg]);
   242 fun untag_rule s = map_tags (filter_out (equal s o #1));
   243 
   244 fun tag tg x = rule_attribute (K (tag_rule tg)) x;
   245 fun untag s x = rule_attribute (K (untag_rule s)) x;
   246 
   247 fun simple_tag name x = tag (name, []) x;
   248 
   249 fun tag_lemma x = simple_tag "lemma" x;
   250 fun tag_assumption x = simple_tag "assumption" x;
   251 
   252 val internal_tag = ("internal", []);
   253 fun tag_internal x = tag internal_tag x;
   254 fun has_internal tags = exists (equal internal_tag) tags;
   255 
   256 
   257 
   258 (** Standardization of rules **)
   259 
   260 (*Strip extraneous shyps as far as possible*)
   261 fun strip_shyps_warning thm =
   262   let
   263     val str_of_sort = Sign.str_of_sort (Thm.sign_of_thm thm);
   264     val thm' = Thm.strip_shyps thm;
   265     val xshyps = Thm.extra_shyps thm';
   266   in
   267     if null xshyps then ()
   268     else warning ("Pending sort hypotheses: " ^ commas (map str_of_sort xshyps));
   269     thm'
   270   end;
   271 
   272 (*Generalization over a list of variables, IGNORING bad ones*)
   273 fun forall_intr_list [] th = th
   274   | forall_intr_list (y::ys) th =
   275         let val gth = forall_intr_list ys th
   276         in  forall_intr y gth   handle THM _ =>  gth  end;
   277 
   278 (*Generalization over all suitable Free variables*)
   279 fun forall_intr_frees th =
   280     let val {prop,sign,...} = rep_thm th
   281     in  forall_intr_list
   282          (map (cterm_of sign) (sort (make_ord atless) (term_frees prop)))
   283          th
   284     end;
   285 
   286 val forall_elim_var = PureThy.forall_elim_var;
   287 val forall_elim_vars = PureThy.forall_elim_vars;
   288 
   289 fun forall_elim_vars_safe th =
   290   forall_elim_vars_safe (forall_elim_var (#maxidx (Thm.rep_thm th) + 1) th)
   291     handle THM _ => th;
   292 
   293 
   294 (*Specialization over a list of cterms*)
   295 fun forall_elim_list cts th = foldr (uncurry forall_elim) (rev cts, th);
   296 
   297 (* maps [A1,...,An], B   to   [| A1;...;An |] ==> B  *)
   298 fun implies_intr_list cAs th = foldr (uncurry implies_intr) (cAs,th);
   299 
   300 (* maps [| A1;...;An |] ==> B and [A1,...,An]   to   B *)
   301 fun implies_elim_list impth ths = foldl (uncurry implies_elim) (impth,ths);
   302 
   303 (*Reset Var indexes to zero, renaming to preserve distinctness*)
   304 fun zero_var_indexes th =
   305     let val {prop,sign,...} = rep_thm th;
   306         val vars = term_vars prop
   307         val bs = foldl add_new_id ([], map (fn Var((a,_),_)=>a) vars)
   308         val inrs = add_term_tvars(prop,[]);
   309         val nms' = rev(foldl add_new_id ([], map (#1 o #1) inrs));
   310         val tye = ListPair.map (fn ((v,rs),a) => (v, TVar((a,0),rs)))
   311                      (inrs, nms')
   312         val ctye = map (fn (v,T) => (v,ctyp_of sign T)) tye;
   313         fun varpairs([],[]) = []
   314           | varpairs((var as Var(v,T)) :: vars, b::bs) =
   315                 let val T' = typ_subst_TVars tye T
   316                 in (cterm_of sign (Var(v,T')),
   317                     cterm_of sign (Var((b,0),T'))) :: varpairs(vars,bs)
   318                 end
   319           | varpairs _ = raise TERM("varpairs", []);
   320     in Thm.instantiate (ctye, varpairs(vars,rev bs)) th end;
   321 
   322 
   323 (*Standard form of object-rule: no hypotheses, Frees, or outer quantifiers;
   324     all generality expressed by Vars having index 0.*)
   325 fun standard th =
   326   let val {maxidx,...} = rep_thm th
   327   in
   328     th |> implies_intr_hyps
   329        |> forall_intr_frees |> forall_elim_vars (maxidx + 1)
   330        |> strip_shyps_warning
   331        |> zero_var_indexes |> Thm.varifyT |> Thm.compress
   332   end;
   333 
   334 
   335 (*Convert all Vars in a theorem to Frees.  Also return a function for
   336   reversing that operation.  DOES NOT WORK FOR TYPE VARIABLES.
   337   Similar code in type/freeze_thaw*)
   338 fun freeze_thaw th =
   339  let val fth = freezeT th
   340      val {prop,sign,...} = rep_thm fth
   341  in
   342    case term_vars prop of
   343        [] => (fth, fn x => x)
   344      | vars =>
   345          let fun newName (Var(ix,_), (pairs,used)) =
   346                    let val v = variant used (string_of_indexname ix)
   347                    in  ((ix,v)::pairs, v::used)  end;
   348              val (alist, _) = foldr newName
   349                                 (vars, ([], add_term_names (prop, [])))
   350              fun mk_inst (Var(v,T)) =
   351                  (cterm_of sign (Var(v,T)),
   352                   cterm_of sign (Free(the (assoc(alist,v)), T)))
   353              val insts = map mk_inst vars
   354              fun thaw th' =
   355                  th' |> forall_intr_list (map #2 insts)
   356                      |> forall_elim_list (map #1 insts)
   357          in  (Thm.instantiate ([],insts) fth, thaw)  end
   358  end;
   359 
   360 
   361 (*Rotates a rule's premises to the left by k*)
   362 val rotate_prems = permute_prems 0;
   363 
   364 
   365 (*Assume a new formula, read following the same conventions as axioms.
   366   Generalizes over Free variables,
   367   creates the assumption, and then strips quantifiers.
   368   Example is [| ALL x:?A. ?P(x) |] ==> [| ?P(?a) |]
   369              [ !(A,P,a)[| ALL x:A. P(x) |] ==> [| P(a) |] ]    *)
   370 fun assume_ax thy sP =
   371     let val sign = Theory.sign_of thy
   372         val prop = Logic.close_form (term_of (read_cterm sign (sP, propT)))
   373     in forall_elim_vars 0 (assume (cterm_of sign prop))  end;
   374 
   375 (*Resolution: exactly one resolvent must be produced.*)
   376 fun tha RSN (i,thb) =
   377   case Seq.chop (2, biresolution false [(false,tha)] i thb) of
   378       ([th],_) => th
   379     | ([],_)   => raise THM("RSN: no unifiers", i, [tha,thb])
   380     |      _   => raise THM("RSN: multiple unifiers", i, [tha,thb]);
   381 
   382 (*resolution: P==>Q, Q==>R gives P==>R. *)
   383 fun tha RS thb = tha RSN (1,thb);
   384 
   385 (*For joining lists of rules*)
   386 fun thas RLN (i,thbs) =
   387   let val resolve = biresolution false (map (pair false) thas) i
   388       fun resb thb = Seq.list_of (resolve thb) handle THM _ => []
   389   in  List.concat (map resb thbs)  end;
   390 
   391 fun thas RL thbs = thas RLN (1,thbs);
   392 
   393 (*Resolve a list of rules against bottom_rl from right to left;
   394   makes proof trees*)
   395 fun rls MRS bottom_rl =
   396   let fun rs_aux i [] = bottom_rl
   397         | rs_aux i (rl::rls) = rl RSN (i, rs_aux (i+1) rls)
   398   in  rs_aux 1 rls  end;
   399 
   400 (*As above, but for rule lists*)
   401 fun rlss MRL bottom_rls =
   402   let fun rs_aux i [] = bottom_rls
   403         | rs_aux i (rls::rlss) = rls RLN (i, rs_aux (i+1) rlss)
   404   in  rs_aux 1 rlss  end;
   405 
   406 (*A version of MRS with more appropriate argument order*)
   407 fun bottom_rl OF rls = rls MRS bottom_rl;
   408 
   409 (*compose Q and [...,Qi,Q(i+1),...]==>R to [...,Q(i+1),...]==>R
   410   with no lifting or renaming!  Q may contain ==> or meta-quants
   411   ALWAYS deletes premise i *)
   412 fun compose(tha,i,thb) =
   413     Seq.list_of (bicompose false (false,tha,0) i thb);
   414 
   415 fun compose_single (tha,i,thb) =
   416   (case compose (tha,i,thb) of
   417     [th] => th
   418   | _ => raise THM ("compose: unique result expected", i, [tha,thb]));
   419 
   420 (*compose Q and [Q1,Q2,...,Qk]==>R to [Q2,...,Qk]==>R getting unique result*)
   421 fun tha COMP thb =
   422     case compose(tha,1,thb) of
   423         [th] => th
   424       | _ =>   raise THM("COMP", 1, [tha,thb]);
   425 
   426 (** theorem equality **)
   427 
   428 (*Do the two theorems have the same signature?*)
   429 fun eq_thm_sg (th1,th2) = Sign.eq_sg(#sign(rep_thm th1), #sign(rep_thm th2));
   430 
   431 (*Useful "distance" function for BEST_FIRST*)
   432 val size_of_thm = size_of_term o #prop o rep_thm;
   433 
   434 (*maintain lists of theorems --- preserving canonical order*)
   435 fun del_rules rs rules = Library.gen_rems Thm.eq_thm (rules, rs);
   436 fun add_rules rs rules = rs @ del_rules rs rules;
   437 fun merge_rules (rules1, rules2) = Library.generic_merge Thm.eq_thm I I rules1 rules2;
   438 
   439 
   440 (** Mark Staples's weaker version of eq_thm: ignores variable renaming and
   441     (some) type variable renaming **)
   442 
   443  (* Can't use term_vars, because it sorts the resulting list of variable names.
   444     We instead need the unique list noramlised by the order of appearance
   445     in the term. *)
   446 fun term_vars' (t as Var(v,T)) = [t]
   447   | term_vars' (Abs(_,_,b)) = term_vars' b
   448   | term_vars' (f$a) = (term_vars' f) @ (term_vars' a)
   449   | term_vars' _ = [];
   450 
   451 fun forall_intr_vars th =
   452   let val {prop,sign,...} = rep_thm th;
   453       val vars = distinct (term_vars' prop);
   454   in forall_intr_list (map (cterm_of sign) vars) th end;
   455 
   456 fun weak_eq_thm (tha,thb) =
   457     eq_thm(forall_intr_vars (freezeT tha), forall_intr_vars (freezeT thb));
   458 
   459 
   460 
   461 (*** Meta-Rewriting Rules ***)
   462 
   463 fun read_prop s = read_cterm proto_sign (s, propT);
   464 
   465 fun store_thm name thm = hd (PureThy.smart_store_thms (name, [thm]));
   466 fun store_standard_thm name thm = store_thm name (standard thm);
   467 
   468 val reflexive_thm =
   469   let val cx = cterm_of proto_sign (Var(("x",0),TVar(("'a",0),logicS)))
   470   in store_standard_thm "reflexive" (Thm.reflexive cx) end;
   471 
   472 val symmetric_thm =
   473   let val xy = read_prop "x::'a::logic == y"
   474   in store_standard_thm "symmetric" (Thm.implies_intr_hyps (Thm.symmetric (Thm.assume xy))) end;
   475 
   476 val transitive_thm =
   477   let val xy = read_prop "x::'a::logic == y"
   478       val yz = read_prop "y::'a::logic == z"
   479       val xythm = Thm.assume xy and yzthm = Thm.assume yz
   480   in store_standard_thm "transitive" (Thm.implies_intr yz (Thm.transitive xythm yzthm)) end;
   481 
   482 fun symmetric_fun thm = thm RS symmetric_thm;
   483 
   484 val imp_cong =
   485   let
   486     val ABC = read_prop "PROP A ==> PROP B == PROP C"
   487     val AB = read_prop "PROP A ==> PROP B"
   488     val AC = read_prop "PROP A ==> PROP C"
   489     val A = read_prop "PROP A"
   490   in
   491     store_standard_thm "imp_cong2" (implies_intr ABC (equal_intr
   492       (implies_intr AB (implies_intr A
   493         (equal_elim (implies_elim (assume ABC) (assume A))
   494           (implies_elim (assume AB) (assume A)))))
   495       (implies_intr AC (implies_intr A
   496         (equal_elim (symmetric (implies_elim (assume ABC) (assume A)))
   497           (implies_elim (assume AC) (assume A)))))))
   498   end;
   499 
   500 val swap_prems_eq =
   501   let
   502     val ABC = read_prop "PROP A ==> PROP B ==> PROP C"
   503     val BAC = read_prop "PROP B ==> PROP A ==> PROP C"
   504     val A = read_prop "PROP A"
   505     val B = read_prop "PROP B"
   506   in
   507     store_standard_thm "swap_prems_eq" (equal_intr
   508       (implies_intr ABC (implies_intr B (implies_intr A
   509         (implies_elim (implies_elim (assume ABC) (assume A)) (assume B)))))
   510       (implies_intr BAC (implies_intr A (implies_intr B
   511         (implies_elim (implies_elim (assume BAC) (assume B)) (assume A))))))
   512   end;
   513 
   514 val refl_implies = reflexive implies;
   515 
   516 
   517 (*** Some useful meta-theorems ***)
   518 
   519 (*The rule V/V, obtains assumption solving for eresolve_tac*)
   520 val asm_rl = store_standard_thm "asm_rl" (Thm.trivial (read_prop "PROP ?psi"));
   521 val _ = store_thm "_" asm_rl;
   522 
   523 (*Meta-level cut rule: [| V==>W; V |] ==> W *)
   524 val cut_rl =
   525   store_standard_thm "cut_rl"
   526     (Thm.trivial (read_prop "PROP ?psi ==> PROP ?theta"));
   527 
   528 (*Generalized elim rule for one conclusion; cut_rl with reversed premises:
   529      [| PROP V;  PROP V ==> PROP W |] ==> PROP W *)
   530 val revcut_rl =
   531   let val V = read_prop "PROP V"
   532       and VW = read_prop "PROP V ==> PROP W";
   533   in
   534     store_standard_thm "revcut_rl"
   535       (implies_intr V (implies_intr VW (implies_elim (assume VW) (assume V))))
   536   end;
   537 
   538 (*for deleting an unwanted assumption*)
   539 val thin_rl =
   540   let val V = read_prop "PROP V"
   541       and W = read_prop "PROP W";
   542   in  store_standard_thm "thin_rl" (implies_intr V (implies_intr W (assume W)))
   543   end;
   544 
   545 (* (!!x. PROP ?V) == PROP ?V       Allows removal of redundant parameters*)
   546 val triv_forall_equality =
   547   let val V  = read_prop "PROP V"
   548       and QV = read_prop "!!x::'a. PROP V"
   549       and x  = read_cterm proto_sign ("x", TypeInfer.logicT);
   550   in
   551     store_standard_thm "triv_forall_equality"
   552       (standard (equal_intr (implies_intr QV (forall_elim x (assume QV)))
   553         (implies_intr V  (forall_intr x (assume V)))))
   554   end;
   555 
   556 (* (PROP ?PhiA ==> PROP ?PhiB ==> PROP ?Psi) ==>
   557    (PROP ?PhiB ==> PROP ?PhiA ==> PROP ?Psi)
   558    `thm COMP swap_prems_rl' swaps the first two premises of `thm'
   559 *)
   560 val swap_prems_rl =
   561   let val cmajor = read_prop "PROP PhiA ==> PROP PhiB ==> PROP Psi";
   562       val major = assume cmajor;
   563       val cminor1 = read_prop "PROP PhiA";
   564       val minor1 = assume cminor1;
   565       val cminor2 = read_prop "PROP PhiB";
   566       val minor2 = assume cminor2;
   567   in store_standard_thm "swap_prems_rl"
   568        (implies_intr cmajor (implies_intr cminor2 (implies_intr cminor1
   569          (implies_elim (implies_elim major minor1) minor2))))
   570   end;
   571 
   572 (* [| PROP ?phi ==> PROP ?psi; PROP ?psi ==> PROP ?phi |]
   573    ==> PROP ?phi == PROP ?psi
   574    Introduction rule for == as a meta-theorem.
   575 *)
   576 val equal_intr_rule =
   577   let val PQ = read_prop "PROP phi ==> PROP psi"
   578       and QP = read_prop "PROP psi ==> PROP phi"
   579   in
   580     store_standard_thm "equal_intr_rule"
   581       (implies_intr PQ (implies_intr QP (equal_intr (assume PQ) (assume QP))))
   582   end;
   583 
   584 
   585 (*(PROP ?phi ==> (!!x. PROP ?psi(x))) == (!!x. PROP ?phi ==> PROP ?psi(x))
   586   Rewrite rule for HHF normalization.
   587 
   588   Note: the syntax of ProtoPure is insufficient to handle this
   589   statement; storing it would be asking for trouble, e.g. when someone
   590   tries to print the theory later.
   591 *)
   592 
   593 val norm_hhf_eq =
   594   let
   595     val cert = Thm.cterm_of proto_sign;
   596     val aT = TFree ("'a", Term.logicS);
   597     val all = Term.all aT;
   598     val x = Free ("x", aT);
   599     val phi = Free ("phi", propT);
   600     val psi = Free ("psi", aT --> propT);
   601 
   602     val cx = cert x;
   603     val cphi = cert phi;
   604     val lhs = cert (Logic.mk_implies (phi, all $ Abs ("x", aT, psi $ Bound 0)));
   605     val rhs = cert (all $ Abs ("x", aT, Logic.mk_implies (phi, psi $ Bound 0)));
   606   in
   607     Thm.equal_intr
   608       (Thm.implies_elim (Thm.assume lhs) (Thm.assume cphi)
   609         |> Thm.forall_elim cx
   610         |> Thm.implies_intr cphi
   611         |> Thm.forall_intr cx
   612         |> Thm.implies_intr lhs)
   613       (Thm.implies_elim
   614           (Thm.assume rhs |> Thm.forall_elim cx) (Thm.assume cphi)
   615         |> Thm.forall_intr cx
   616         |> Thm.implies_intr cphi
   617         |> Thm.implies_intr rhs)
   618     |> store_standard_thm "norm_hhf_eq"
   619   end;
   620 
   621 
   622 (*** Instantiate theorem th, reading instantiations under signature sg ****)
   623 
   624 (*Version that normalizes the result: Thm.instantiate no longer does that*)
   625 fun instantiate instpair th = Thm.instantiate instpair th  COMP   asm_rl;
   626 
   627 fun read_instantiate_sg sg sinsts th =
   628     let val ts = types_sorts th;
   629         val used = add_term_tvarnames(#prop(rep_thm th),[]);
   630     in  instantiate (read_insts sg ts ts used sinsts) th  end;
   631 
   632 (*Instantiate theorem th, reading instantiations under theory of th*)
   633 fun read_instantiate sinsts th =
   634     read_instantiate_sg (#sign (rep_thm th)) sinsts th;
   635 
   636 
   637 (*Left-to-right replacements: tpairs = [...,(vi,ti),...].
   638   Instantiates distinct Vars by terms, inferring type instantiations. *)
   639 local
   640   fun add_types ((ct,cu), (sign,tye,maxidx)) =
   641     let val {sign=signt, t=t, T= T, maxidx=maxt,...} = rep_cterm ct
   642         and {sign=signu, t=u, T= U, maxidx=maxu,...} = rep_cterm cu;
   643         val maxi = Int.max(maxidx, Int.max(maxt, maxu));
   644         val sign' = Sign.merge(sign, Sign.merge(signt, signu))
   645         val (tye',maxi') = Type.unify (#tsig(Sign.rep_sg sign')) maxi tye (T,U)
   646           handle Type.TUNIFY => raise TYPE("Ill-typed instantiation", [T,U], [t,u])
   647     in  (sign', tye', maxi')  end;
   648 in
   649 fun cterm_instantiate ctpairs0 th =
   650   let val (sign,tye,_) = foldr add_types (ctpairs0, (#sign(rep_thm th), Vartab.empty, 0))
   651       fun instT(ct,cu) = let val inst = subst_TVars_Vartab tye
   652                          in (cterm_fun inst ct, cterm_fun inst cu) end
   653       fun ctyp2 (ix,T) = (ix, ctyp_of sign T)
   654   in  instantiate (map ctyp2 (Vartab.dest tye), map instT ctpairs0) th  end
   655   handle TERM _ =>
   656            raise THM("cterm_instantiate: incompatible signatures",0,[th])
   657        | TYPE (msg, _, _) => raise THM(msg, 0, [th])
   658 end;
   659 
   660 
   661 (** Derived rules mainly for METAHYPS **)
   662 
   663 (*Given the term "a", takes (%x.t)==(%x.u) to t[a/x]==u[a/x]*)
   664 fun equal_abs_elim ca eqth =
   665   let val {sign=signa, t=a, ...} = rep_cterm ca
   666       and combth = combination eqth (reflexive ca)
   667       val {sign,prop,...} = rep_thm eqth
   668       val (abst,absu) = Logic.dest_equals prop
   669       val cterm = cterm_of (Sign.merge (sign,signa))
   670   in  transitive (symmetric (beta_conversion false (cterm (abst$a))))
   671            (transitive combth (beta_conversion false (cterm (absu$a))))
   672   end
   673   handle THM _ => raise THM("equal_abs_elim", 0, [eqth]);
   674 
   675 (*Calling equal_abs_elim with multiple terms*)
   676 fun equal_abs_elim_list cts th = foldr (uncurry equal_abs_elim) (rev cts, th);
   677 
   678 local
   679   val alpha = TVar(("'a",0), [])     (*  type ?'a::{}  *)
   680   fun err th = raise THM("flexpair_inst: ", 0, [th])
   681   fun flexpair_inst def th =
   682     let val {prop = Const _ $ t $ u,  sign,...} = rep_thm th
   683         val cterm = cterm_of sign
   684         fun cvar a = cterm(Var((a,0),alpha))
   685         val def' = cterm_instantiate [(cvar"t", cterm t), (cvar"u", cterm u)]
   686                    def
   687     in  equal_elim def' th
   688     end
   689     handle THM _ => err th | Bind => err th
   690 in
   691 val flexpair_intr = flexpair_inst (symmetric ProtoPure.flexpair_def)
   692 and flexpair_elim = flexpair_inst ProtoPure.flexpair_def
   693 end;
   694 
   695 (*Version for flexflex pairs -- this supports lifting.*)
   696 fun flexpair_abs_elim_list cts =
   697     flexpair_intr o equal_abs_elim_list cts o flexpair_elim;
   698 
   699 
   700 (*** GOAL (PROP A) <==> PROP A ***)
   701 
   702 local
   703   val A = read_prop "PROP A";
   704   val G = read_prop "GOAL (PROP A)";
   705   val (G_def, _) = freeze_thaw ProtoPure.Goal_def;
   706 in
   707   val triv_goal = store_thm "triv_goal"
   708     (tag_rule internal_tag (standard (Thm.equal_elim (Thm.symmetric G_def) (Thm.assume A))));
   709   val rev_triv_goal = store_thm "rev_triv_goal"
   710     (tag_rule internal_tag (standard (Thm.equal_elim G_def (Thm.assume G))));
   711 end;
   712 
   713 val mk_cgoal = Thm.capply (Thm.cterm_of proto_sign Logic.goal_const);
   714 fun assume_goal ct = Thm.assume (mk_cgoal ct) RS rev_triv_goal;
   715 
   716 
   717 
   718 (** variations on instantiate **)
   719 
   720 (*shorthand for instantiating just one variable in the current theory*)
   721 fun inst x t = read_instantiate_sg (sign_of (the_context())) [(x,t)];
   722 
   723 
   724 (* collect vars *)
   725 
   726 val add_tvarsT = foldl_atyps (fn (vs, TVar v) => v ins vs | (vs, _) => vs);
   727 val add_tvars = foldl_types add_tvarsT;
   728 val add_vars = foldl_aterms (fn (vs, Var v) => v ins vs | (vs, _) => vs);
   729 
   730 fun tvars_of_terms ts = rev (foldl add_tvars ([], ts));
   731 fun vars_of_terms ts = rev (foldl add_vars ([], ts));
   732 
   733 fun tvars_of thm = tvars_of_terms [#prop (Thm.rep_thm thm)];
   734 fun vars_of thm = vars_of_terms [#prop (Thm.rep_thm thm)];
   735 
   736 
   737 (* instantiate by left-to-right occurrence of variables *)
   738 
   739 fun instantiate' cTs cts thm =
   740   let
   741     fun err msg =
   742       raise TYPE ("instantiate': " ^ msg,
   743         mapfilter (apsome Thm.typ_of) cTs,
   744         mapfilter (apsome Thm.term_of) cts);
   745 
   746     fun inst_of (v, ct) =
   747       (Thm.cterm_of (#sign (Thm.rep_cterm ct)) (Var v), ct)
   748         handle TYPE (msg, _, _) => err msg;
   749 
   750     fun zip_vars _ [] = []
   751       | zip_vars (_ :: vs) (None :: opt_ts) = zip_vars vs opt_ts
   752       | zip_vars (v :: vs) (Some t :: opt_ts) = (v, t) :: zip_vars vs opt_ts
   753       | zip_vars [] _ = err "more instantiations than variables in thm";
   754 
   755     (*instantiate types first!*)
   756     val thm' =
   757       if forall is_none cTs then thm
   758       else Thm.instantiate (zip_vars (map fst (tvars_of thm)) cTs, []) thm;
   759     in
   760       if forall is_none cts then thm'
   761       else Thm.instantiate ([], map inst_of (zip_vars (vars_of thm') cts)) thm'
   762     end;
   763 
   764 
   765 (* unvarify(T) *)
   766 
   767 (*assume thm in standard form, i.e. no frees, 0 var indexes*)
   768 
   769 fun unvarifyT thm =
   770   let
   771     val cT = Thm.ctyp_of (Thm.sign_of_thm thm);
   772     val tfrees = map (fn ((x, _), S) => Some (cT (TFree (x, S)))) (tvars_of thm);
   773   in instantiate' tfrees [] thm end;
   774 
   775 fun unvarify raw_thm =
   776   let
   777     val thm = unvarifyT raw_thm;
   778     val ct = Thm.cterm_of (Thm.sign_of_thm thm);
   779     val frees = map (fn ((x, _), T) => Some (ct (Free (x, T)))) (vars_of thm);
   780   in instantiate' [] frees thm end;
   781 
   782 
   783 (* tvars_intr_list *)
   784 
   785 fun tfrees_of thm =
   786   let val {hyps, prop, ...} = Thm.rep_thm thm
   787   in foldr Term.add_term_tfree_names (prop :: hyps, []) end;
   788 
   789 fun tvars_intr_list tfrees thm =
   790   Thm.varifyT' (tfrees_of thm \\ tfrees) thm;
   791 
   792 
   793 (* increment var indexes *)
   794 
   795 fun incr_indexes_wrt is cTs cts thms =
   796   let
   797     val maxidx =
   798       foldl Int.max (~1, is @
   799         map (maxidx_of_typ o #T o Thm.rep_ctyp) cTs @
   800         map (#maxidx o Thm.rep_cterm) cts @
   801         map (#maxidx o Thm.rep_thm) thms);
   802   in Thm.incr_indexes (maxidx + 1) end;
   803 
   804 
   805 (* freeze_all *)
   806 
   807 (*freeze all (T)Vars; assumes thm in standard form*)
   808 
   809 fun freeze_all_TVars thm =
   810   (case tvars_of thm of
   811     [] => thm
   812   | tvars =>
   813       let val cert = Thm.ctyp_of (Thm.sign_of_thm thm)
   814       in instantiate' (map (fn ((x, _), S) => Some (cert (TFree (x, S)))) tvars) [] thm end);
   815 
   816 fun freeze_all_Vars thm =
   817   (case vars_of thm of
   818     [] => thm
   819   | vars =>
   820       let val cert = Thm.cterm_of (Thm.sign_of_thm thm)
   821       in instantiate' [] (map (fn ((x, _), T) => Some (cert (Free (x, T)))) vars) thm end);
   822 
   823 val freeze_all = freeze_all_Vars o freeze_all_TVars;
   824 
   825 
   826 (* mk_triv_goal *)
   827 
   828 (*make an initial proof state, "PROP A ==> (PROP A)" *)
   829 fun mk_triv_goal ct = instantiate' [] [Some ct] triv_goal;
   830 
   831 end;
   832 
   833 
   834 structure BasicDrule: BASIC_DRULE = Drule;
   835 open BasicDrule;