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