src/Pure/tactic.ML
author paulson
Mon Dec 07 18:26:25 1998 +0100 (1998-12-07)
changeset 6019 0e55c2fb2ebb
parent 5974 6acf3ff0f486
child 6390 5d58c100ca3f
permissions -rw-r--r--
tidying
     1 (*  Title: 	Pure/tactic.ML
     2     ID:         $Id$
     3     Author: 	Lawrence C Paulson, Cambridge University Computer Laboratory
     4     Copyright   1991  University of Cambridge
     5 
     6 Tactics 
     7 *)
     8 
     9 signature TACTIC =
    10   sig
    11   val ares_tac		: thm list -> int -> tactic
    12   val asm_rewrite_goal_tac:
    13     bool*bool*bool -> (meta_simpset -> tactic) -> meta_simpset -> int -> tactic
    14   val assume_tac	: int -> tactic
    15   val atac	: int ->tactic
    16   val bimatch_from_nets_tac: 
    17       (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net -> int -> tactic
    18   val bimatch_tac	: (bool*thm)list -> int -> tactic
    19   val biresolution_from_nets_tac: 
    20 	('a list -> (bool * thm) list) ->
    21 	bool -> 'a Net.net * 'a Net.net -> int -> tactic
    22   val biresolve_from_nets_tac: 
    23       (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net -> int -> tactic
    24   val biresolve_tac	: (bool*thm)list -> int -> tactic
    25   val build_net	: thm list -> (int*thm) Net.net
    26   val build_netpair:    (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net ->
    27       (bool*thm)list -> (int*(bool*thm)) Net.net * (int*(bool*thm)) Net.net
    28   val compose_inst_tac	: (string*string)list -> (bool*thm*int) -> 
    29                           int -> tactic
    30   val compose_tac	: (bool * thm * int) -> int -> tactic 
    31   val cut_facts_tac	: thm list -> int -> tactic
    32   val cut_inst_tac	: (string*string)list -> thm -> int -> tactic   
    33   val defer_tac 	: int -> tactic
    34   val distinct_subgoals_tac	: tactic
    35   val dmatch_tac	: thm list -> int -> tactic
    36   val dresolve_tac	: thm list -> int -> tactic
    37   val dres_inst_tac	: (string*string)list -> thm -> int -> tactic   
    38   val dtac		: thm -> int ->tactic
    39   val etac		: thm -> int ->tactic
    40   val eq_assume_tac	: int -> tactic   
    41   val ematch_tac	: thm list -> int -> tactic
    42   val eresolve_tac	: thm list -> int -> tactic
    43   val eres_inst_tac	: (string*string)list -> thm -> int -> tactic
    44   val filter_prems_tac  : (term -> bool) -> int -> tactic  
    45   val filter_thms	: (term*term->bool) -> int*term*thm list -> thm list
    46   val filt_resolve_tac	: thm list -> int -> int -> tactic
    47   val flexflex_tac	: tactic
    48   val fold_goals_tac	: thm list -> tactic
    49   val fold_tac		: thm list -> tactic
    50   val forward_tac	: thm list -> int -> tactic   
    51   val forw_inst_tac	: (string*string)list -> thm -> int -> tactic
    52   val insert_tagged_brl : ('a*(bool*thm)) * 
    53                           (('a*(bool*thm))Net.net * ('a*(bool*thm))Net.net) ->
    54                           ('a*(bool*thm))Net.net * ('a*(bool*thm))Net.net
    55   val delete_tagged_brl	: (bool*thm) * 
    56                          ((int*(bool*thm))Net.net * (int*(bool*thm))Net.net) ->
    57                     (int*(bool*thm))Net.net * (int*(bool*thm))Net.net
    58   val is_fact		: thm -> bool
    59   val lessb		: (bool * thm) * (bool * thm) -> bool
    60   val lift_inst_rule	: thm * int * (string*string)list * thm -> thm
    61   val make_elim		: thm -> thm
    62   val match_from_net_tac	: (int*thm) Net.net -> int -> tactic
    63   val match_tac	: thm list -> int -> tactic
    64   val metacut_tac	: thm -> int -> tactic
    65   val metacuts_tac	: thm list -> int -> tactic   
    66   val net_bimatch_tac	: (bool*thm) list -> int -> tactic
    67   val net_biresolve_tac	: (bool*thm) list -> int -> tactic
    68   val net_match_tac	: thm list -> int -> tactic
    69   val net_resolve_tac	: thm list -> int -> tactic
    70   val orderlist		: (int * 'a) list -> 'a list
    71   val PRIMITIVE		: (thm -> thm) -> tactic  
    72   val PRIMSEQ		: (thm -> thm Seq.seq) -> tactic  
    73   val prune_params_tac	: tactic
    74   val rename_tac	: string -> int -> tactic
    75   val rename_last_tac	: string -> string list -> int -> tactic
    76   val resolve_from_net_tac	: (int*thm) Net.net -> int -> tactic
    77   val resolve_tac	: thm list -> int -> tactic
    78   val res_inst_tac	: (string*string)list -> thm -> int -> tactic   
    79   val rewrite_goals_rule: thm list -> thm -> thm
    80   val rewrite_rule	: thm list -> thm -> thm
    81   val rewrite_goals_tac	: thm list -> tactic
    82   val rewrite_tac	: thm list -> tactic
    83   val rewtac		: thm -> tactic
    84   val rotate_tac	: int -> int -> tactic
    85   val rtac		: thm -> int -> tactic
    86   val rule_by_tactic	: tactic -> thm -> thm
    87   val solve_tac		: thm list -> int -> tactic
    88   val subgoal_tac	: string -> int -> tactic
    89   val subgoals_tac	: string list -> int -> tactic
    90   val subgoals_of_brl	: bool * thm -> int
    91   val term_lift_inst_rule	:
    92       thm * int * (indexname*typ)list * ((indexname*typ)*term)list  * thm
    93       -> thm
    94   val thin_tac		: string -> int -> tactic
    95   val trace_goalno_tac	: (int -> tactic) -> int -> tactic
    96   end;
    97 
    98 
    99 structure Tactic : TACTIC = 
   100 struct
   101 
   102 (*Discover which goal is chosen:  SOMEGOAL(trace_goalno_tac tac) *)
   103 fun trace_goalno_tac tac i st =  
   104     case Seq.pull(tac i st) of
   105 	None    => Seq.empty
   106       | seqcell => (writeln ("Subgoal " ^ string_of_int i ^ " selected"); 
   107     			 Seq.make(fn()=> seqcell));
   108 
   109 
   110 (*Rotates the given subgoal to be the last.  Useful when re-playing
   111   an old proof script, when the proof of an early subgoal fails.
   112   DOES NOT WORK FOR TYPE VARIABLES.
   113   Similar to drule/rotate_prems*)
   114 fun defer_tac i state = 
   115     let val (state',thaw) = freeze_thaw state
   116 	val hyps = Drule.strip_imp_prems (adjust_maxidx (cprop_of state'))
   117 	val hyp::hyps' = List.drop(hyps, i-1)
   118     in  implies_intr hyp (implies_elim_list state' (map assume hyps)) 
   119         |> implies_intr_list (List.take(hyps, i-1) @ hyps')
   120         |> thaw
   121         |> Seq.single
   122     end
   123     handle _ => Seq.empty;
   124 
   125 
   126 (*Makes a rule by applying a tactic to an existing rule*)
   127 fun rule_by_tactic tac rl =
   128   let val (st, thaw) = freeze_thaw (zero_var_indexes rl)
   129   in case Seq.pull (tac st)  of
   130 	None        => raise THM("rule_by_tactic", 0, [rl])
   131       | Some(st',_) => Thm.varifyT (thaw st')
   132   end;
   133  
   134 (*** Basic tactics ***)
   135 
   136 (*Makes a tactic whose effect on a state is given by thmfun: thm->thm seq.*)
   137 fun PRIMSEQ thmfun st =  thmfun st handle THM _ => Seq.empty;
   138 
   139 (*Makes a tactic whose effect on a state is given by thmfun: thm->thm.*)
   140 fun PRIMITIVE thmfun = PRIMSEQ (Seq.single o thmfun);
   141 
   142 (*** The following fail if the goal number is out of range:
   143      thus (REPEAT (resolve_tac rules i)) stops once subgoal i disappears. *)
   144 
   145 (*Solve subgoal i by assumption*)
   146 fun assume_tac i = PRIMSEQ (assumption i);
   147 
   148 (*Solve subgoal i by assumption, using no unification*)
   149 fun eq_assume_tac i = PRIMITIVE (eq_assumption i);
   150 
   151 (** Resolution/matching tactics **)
   152 
   153 (*The composition rule/state: no lifting or var renaming.
   154   The arg = (bires_flg, orule, m) ;  see bicompose for explanation.*)
   155 fun compose_tac arg i = PRIMSEQ (bicompose false arg i);
   156 
   157 (*Converts a "destruct" rule like P&Q==>P to an "elimination" rule
   158   like [| P&Q; P==>R |] ==> R *)
   159 fun make_elim rl = zero_var_indexes (rl RS revcut_rl);
   160 
   161 (*Attack subgoal i by resolution, using flags to indicate elimination rules*)
   162 fun biresolve_tac brules i = PRIMSEQ (biresolution false brules i);
   163 
   164 (*Resolution: the simple case, works for introduction rules*)
   165 fun resolve_tac rules = biresolve_tac (map (pair false) rules);
   166 
   167 (*Resolution with elimination rules only*)
   168 fun eresolve_tac rules = biresolve_tac (map (pair true) rules);
   169 
   170 (*Forward reasoning using destruction rules.*)
   171 fun forward_tac rls = resolve_tac (map make_elim rls) THEN' assume_tac;
   172 
   173 (*Like forward_tac, but deletes the assumption after use.*)
   174 fun dresolve_tac rls = eresolve_tac (map make_elim rls);
   175 
   176 (*Shorthand versions: for resolution with a single theorem*)
   177 fun rtac rl = resolve_tac [rl];
   178 fun etac rl = eresolve_tac [rl];
   179 fun dtac rl = dresolve_tac [rl];
   180 val atac = assume_tac;
   181 
   182 (*Use an assumption or some rules ... A popular combination!*)
   183 fun ares_tac rules = assume_tac  ORELSE'  resolve_tac rules;
   184 
   185 fun solve_tac rules = resolve_tac rules THEN_ALL_NEW assume_tac;
   186 
   187 (*Matching tactics -- as above, but forbid updating of state*)
   188 fun bimatch_tac brules i = PRIMSEQ (biresolution true brules i);
   189 fun match_tac rules  = bimatch_tac (map (pair false) rules);
   190 fun ematch_tac rules = bimatch_tac (map (pair true) rules);
   191 fun dmatch_tac rls   = ematch_tac (map make_elim rls);
   192 
   193 (*Smash all flex-flex disagreement pairs in the proof state.*)
   194 val flexflex_tac = PRIMSEQ flexflex_rule;
   195 
   196 
   197 (*Remove duplicate subgoals.  By Mark Staples*)
   198 local
   199 fun cterm_aconv (a,b) = #t (rep_cterm a) aconv #t (rep_cterm b);
   200 in
   201 fun distinct_subgoals_tac state = 
   202     let val (frozth,thawfn) = freeze_thaw state
   203 	val froz_prems = cprems_of frozth
   204 	val assumed = implies_elim_list frozth (map assume froz_prems)
   205 	val implied = implies_intr_list (gen_distinct cterm_aconv froz_prems)
   206 					assumed;
   207     in  Seq.single (thawfn implied)  end
   208 end; 
   209 
   210 
   211 (*Lift and instantiate a rule wrt the given state and subgoal number *)
   212 fun lift_inst_rule (st, i, sinsts, rule) =
   213 let val {maxidx,sign,...} = rep_thm st
   214     val (_, _, Bi, _) = dest_state(st,i)
   215     val params = Logic.strip_params Bi	        (*params of subgoal i*)
   216     val params = rev(rename_wrt_term Bi params) (*as they are printed*)
   217     val paramTs = map #2 params
   218     and inc = maxidx+1
   219     fun liftvar (Var ((a,j), T)) = Var((a, j+inc), paramTs---> incr_tvar inc T)
   220       | liftvar t = raise TERM("Variable expected", [t]);
   221     fun liftterm t = list_abs_free (params, 
   222 				    Logic.incr_indexes(paramTs,inc) t)
   223     (*Lifts instantiation pair over params*)
   224     fun liftpair (cv,ct) = (cterm_fun liftvar cv, cterm_fun liftterm ct)
   225     fun lifttvar((a,i),ctyp) =
   226 	let val {T,sign} = rep_ctyp ctyp
   227 	in  ((a,i+inc), ctyp_of sign (incr_tvar inc T)) end
   228     val rts = types_sorts rule and (types,sorts) = types_sorts st
   229     fun types'(a,~1) = (case assoc(params,a) of None => types(a,~1) | sm => sm)
   230       | types'(ixn) = types ixn;
   231     val used = add_term_tvarnames
   232                   (#prop(rep_thm st) $ #prop(rep_thm rule),[])
   233     val (Tinsts,insts) = read_insts sign rts (types',sorts) used sinsts
   234 in instantiate (map lifttvar Tinsts, map liftpair insts)
   235                (lift_rule (st,i) rule)
   236 end;
   237 
   238 (*
   239 Like lift_inst_rule but takes terms, not strings, where the terms may contain
   240 Bounds referring to parameters of the subgoal.
   241 
   242 insts: [...,(vj,tj),...]
   243 
   244 The tj may contain references to parameters of subgoal i of the state st
   245 in the form of Bound k, i.e. the tj may be subterms of the subgoal.
   246 To saturate the lose bound vars, the tj are enclosed in abstractions
   247 corresponding to the parameters of subgoal i, thus turning them into
   248 functions. At the same time, the types of the vj are lifted.
   249 
   250 NB: the types in insts must be correctly instantiated already,
   251     i.e. Tinsts is not applied to insts.
   252 *)
   253 fun term_lift_inst_rule (st, i, Tinsts, insts, rule) =
   254 let val {maxidx,sign,...} = rep_thm st
   255     val (_, _, Bi, _) = dest_state(st,i)
   256     val params = Logic.strip_params Bi          (*params of subgoal i*)
   257     val paramTs = map #2 params
   258     and inc = maxidx+1
   259     fun liftvar ((a,j), T) = Var((a, j+inc), paramTs---> incr_tvar inc T)
   260     (*lift only Var, not term, which must be lifted already*)
   261     fun liftpair (v,t) = (cterm_of sign (liftvar v), cterm_of sign t)
   262     fun liftTpair((a,i),T) = ((a,i+inc), ctyp_of sign (incr_tvar inc T))
   263 in instantiate (map liftTpair Tinsts, map liftpair insts)
   264                (lift_rule (st,i) rule)
   265 end;
   266 
   267 (*** Resolve after lifting and instantation; may refer to parameters of the
   268      subgoal.  Fails if "i" is out of range.  ***)
   269 
   270 (*compose version: arguments are as for bicompose.*)
   271 fun compose_inst_tac sinsts (bires_flg, rule, nsubgoal) i st = st |>
   272   (compose_tac (bires_flg, lift_inst_rule (st, i, sinsts, rule), nsubgoal) i
   273    handle TERM (msg,_)   => (writeln msg;  no_tac)
   274 	| THM  (msg,_,_) => (writeln msg;  no_tac));
   275 
   276 (*"Resolve" version.  Note: res_inst_tac cannot behave sensibly if the
   277   terms that are substituted contain (term or type) unknowns from the
   278   goal, because it is unable to instantiate goal unknowns at the same time.
   279 
   280   The type checker is instructed not to freeze flexible type vars that
   281   were introduced during type inference and still remain in the term at the
   282   end.  This increases flexibility but can introduce schematic type vars in
   283   goals.
   284 *)
   285 fun res_inst_tac sinsts rule i =
   286     compose_inst_tac sinsts (false, rule, nprems_of rule) i;
   287 
   288 (*eresolve elimination version*)
   289 fun eres_inst_tac sinsts rule i =
   290     compose_inst_tac sinsts (true, rule, nprems_of rule) i;
   291 
   292 (*For forw_inst_tac and dres_inst_tac.  Preserve Var indexes of rl;
   293   increment revcut_rl instead.*)
   294 fun make_elim_preserve rl = 
   295   let val {maxidx,...} = rep_thm rl
   296       fun cvar ixn = cterm_of (sign_of ProtoPure.thy) (Var(ixn,propT));
   297       val revcut_rl' = 
   298 	  instantiate ([],  [(cvar("V",0), cvar("V",maxidx+1)),
   299 			     (cvar("W",0), cvar("W",maxidx+1))]) revcut_rl
   300       val arg = (false, rl, nprems_of rl)
   301       val [th] = Seq.list_of (bicompose false arg 1 revcut_rl')
   302   in  th  end
   303   handle Bind => raise THM("make_elim_preserve", 1, [rl]);
   304 
   305 (*instantiate and cut -- for a FACT, anyway...*)
   306 fun cut_inst_tac sinsts rule = res_inst_tac sinsts (make_elim_preserve rule);
   307 
   308 (*forward tactic applies a RULE to an assumption without deleting it*)
   309 fun forw_inst_tac sinsts rule = cut_inst_tac sinsts rule THEN' assume_tac;
   310 
   311 (*dresolve tactic applies a RULE to replace an assumption*)
   312 fun dres_inst_tac sinsts rule = eres_inst_tac sinsts (make_elim_preserve rule);
   313 
   314 (*Deletion of an assumption*)
   315 fun thin_tac s = eres_inst_tac [("V",s)] thin_rl;
   316 
   317 (*** Applications of cut_rl ***)
   318 
   319 (*Used by metacut_tac*)
   320 fun bires_cut_tac arg i =
   321     resolve_tac [cut_rl] i  THEN  biresolve_tac arg (i+1) ;
   322 
   323 (*The conclusion of the rule gets assumed in subgoal i,
   324   while subgoal i+1,... are the premises of the rule.*)
   325 fun metacut_tac rule = bires_cut_tac [(false,rule)];
   326 fun metacuts_tac rules i = EVERY (map (fn th => metacut_tac th i) rules);
   327 
   328 (*Recognizes theorems that are not rules, but simple propositions*)
   329 fun is_fact rl =
   330     case prems_of rl of
   331 	[] => true  |  _::_ => false;
   332 
   333 (*"Cut" all facts from theorem list into the goal as assumptions. *)
   334 fun cut_facts_tac ths i =
   335     EVERY (map (fn th => metacut_tac th i) (filter is_fact ths));
   336 
   337 (*Introduce the given proposition as a lemma and subgoal*)
   338 fun subgoal_tac sprop i st = 
   339   let val st'    = Seq.hd (res_inst_tac [("psi", sprop)] cut_rl i st)
   340       val concl' = Logic.strip_assums_concl (List.nth(prems_of st', i))
   341   in  
   342       if null (term_tvars concl') then ()
   343       else warning"Type variables in new subgoal: add a type constraint?";
   344       Seq.single st'
   345   end;
   346 
   347 (*Introduce a list of lemmas and subgoals*)
   348 fun subgoals_tac sprops = EVERY' (map subgoal_tac sprops);
   349 
   350 
   351 (**** Indexing and filtering of theorems ****)
   352 
   353 (*Returns the list of potentially resolvable theorems for the goal "prem",
   354 	using the predicate  could(subgoal,concl).
   355   Resulting list is no longer than "limit"*)
   356 fun filter_thms could (limit, prem, ths) =
   357   let val pb = Logic.strip_assums_concl prem;   (*delete assumptions*)
   358       fun filtr (limit, []) = []
   359 	| filtr (limit, th::ths) =
   360 	    if limit=0 then  []
   361 	    else if could(pb, concl_of th)  then th :: filtr(limit-1, ths)
   362 	    else filtr(limit,ths)
   363   in  filtr(limit,ths)  end;
   364 
   365 
   366 (*** biresolution and resolution using nets ***)
   367 
   368 (** To preserve the order of the rules, tag them with increasing integers **)
   369 
   370 (*insert tags*)
   371 fun taglist k [] = []
   372   | taglist k (x::xs) = (k,x) :: taglist (k+1) xs;
   373 
   374 (*remove tags and suppress duplicates -- list is assumed sorted!*)
   375 fun untaglist [] = []
   376   | untaglist [(k:int,x)] = [x]
   377   | untaglist ((k,x) :: (rest as (k',x')::_)) =
   378       if k=k' then untaglist rest
   379       else    x :: untaglist rest;
   380 
   381 (*return list elements in original order*)
   382 fun orderlist kbrls = untaglist (sort (int_ord o pairself fst) kbrls); 
   383 
   384 (*insert one tagged brl into the pair of nets*)
   385 fun insert_tagged_brl (kbrl as (k,(eres,th)), (inet,enet)) =
   386     if eres then 
   387 	case prems_of th of
   388 	    prem::_ => (inet, Net.insert_term ((prem,kbrl), enet, K false))
   389 	  | [] => error"insert_tagged_brl: elimination rule with no premises"
   390     else (Net.insert_term ((concl_of th, kbrl), inet, K false), enet);
   391 
   392 (*build a pair of nets for biresolution*)
   393 fun build_netpair netpair brls = 
   394     foldr insert_tagged_brl (taglist 1 brls, netpair);
   395 
   396 (*delete one kbrl from the pair of nets;
   397   we don't know the value of k, so we use 0 and ignore it in the comparison*)
   398 local
   399   fun eq_kbrl ((k,(eres,th)), (k',(eres',th'))) = eq_thm (th,th')
   400 in
   401 fun delete_tagged_brl (brl as (eres,th), (inet,enet)) =
   402     if eres then 
   403 	case prems_of th of
   404 	    prem::_ => (inet, Net.delete_term ((prem, (0,brl)), enet, eq_kbrl))
   405 	  | []      => (inet,enet)     (*no major premise: ignore*)
   406     else (Net.delete_term ((concl_of th, (0,brl)), inet, eq_kbrl), enet);
   407 end;
   408 
   409 
   410 (*biresolution using a pair of nets rather than rules.  
   411     function "order" must sort and possibly filter the list of brls.
   412     boolean "match" indicates matching or unification.*)
   413 fun biresolution_from_nets_tac order match (inet,enet) =
   414   SUBGOAL
   415     (fn (prem,i) =>
   416       let val hyps = Logic.strip_assums_hyp prem
   417           and concl = Logic.strip_assums_concl prem 
   418           val kbrls = Net.unify_term inet concl @
   419                       List.concat (map (Net.unify_term enet) hyps)
   420       in PRIMSEQ (biresolution match (order kbrls) i) end);
   421 
   422 (*versions taking pre-built nets.  No filtering of brls*)
   423 val biresolve_from_nets_tac = biresolution_from_nets_tac orderlist false;
   424 val bimatch_from_nets_tac   = biresolution_from_nets_tac orderlist true;
   425 
   426 (*fast versions using nets internally*)
   427 val net_biresolve_tac =
   428     biresolve_from_nets_tac o build_netpair(Net.empty,Net.empty);
   429 
   430 val net_bimatch_tac =
   431     bimatch_from_nets_tac o build_netpair(Net.empty,Net.empty);
   432 
   433 (*** Simpler version for resolve_tac -- only one net, and no hyps ***)
   434 
   435 (*insert one tagged rl into the net*)
   436 fun insert_krl (krl as (k,th), net) =
   437     Net.insert_term ((concl_of th, krl), net, K false);
   438 
   439 (*build a net of rules for resolution*)
   440 fun build_net rls = 
   441     foldr insert_krl (taglist 1 rls, Net.empty);
   442 
   443 (*resolution using a net rather than rules; pred supports filt_resolve_tac*)
   444 fun filt_resolution_from_net_tac match pred net =
   445   SUBGOAL
   446     (fn (prem,i) =>
   447       let val krls = Net.unify_term net (Logic.strip_assums_concl prem)
   448       in 
   449 	 if pred krls  
   450          then PRIMSEQ
   451 		(biresolution match (map (pair false) (orderlist krls)) i)
   452          else no_tac
   453       end);
   454 
   455 (*Resolve the subgoal using the rules (making a net) unless too flexible,
   456    which means more than maxr rules are unifiable.      *)
   457 fun filt_resolve_tac rules maxr = 
   458     let fun pred krls = length krls <= maxr
   459     in  filt_resolution_from_net_tac false pred (build_net rules)  end;
   460 
   461 (*versions taking pre-built nets*)
   462 val resolve_from_net_tac = filt_resolution_from_net_tac false (K true);
   463 val match_from_net_tac = filt_resolution_from_net_tac true (K true);
   464 
   465 (*fast versions using nets internally*)
   466 val net_resolve_tac = resolve_from_net_tac o build_net;
   467 val net_match_tac = match_from_net_tac o build_net;
   468 
   469 
   470 (*** For Natural Deduction using (bires_flg, rule) pairs ***)
   471 
   472 (*The number of new subgoals produced by the brule*)
   473 fun subgoals_of_brl (true,rule)  = nprems_of rule - 1
   474   | subgoals_of_brl (false,rule) = nprems_of rule;
   475 
   476 (*Less-than test: for sorting to minimize number of new subgoals*)
   477 fun lessb (brl1,brl2) = subgoals_of_brl brl1 < subgoals_of_brl brl2;
   478 
   479 
   480 (*** Meta-Rewriting Tactics ***)
   481 
   482 fun result1 tacf mss thm =
   483   apsome fst (Seq.pull (tacf mss thm));
   484 
   485 val simple_prover =
   486   result1 (fn mss => ALLGOALS (resolve_tac (prems_of_mss mss)));
   487 
   488 val rewrite_rule = Drule.rewrite_rule_aux simple_prover;
   489 val rewrite_goals_rule = Drule.rewrite_goals_rule_aux simple_prover;
   490 
   491 
   492 (*Rewrite subgoal i only.  SELECT_GOAL avoids inefficiencies in goals_conv.*)
   493 fun asm_rewrite_goal_tac mode prover_tac mss =
   494       SELECT_GOAL 
   495         (PRIMITIVE
   496 	   (rewrite_goal_rule mode (result1 prover_tac) mss 1));
   497 
   498 (*Rewrite throughout proof state. *)
   499 fun rewrite_tac defs = PRIMITIVE(rewrite_rule defs);
   500 
   501 (*Rewrite subgoals only, not main goal. *)
   502 fun rewrite_goals_tac defs = PRIMITIVE (rewrite_goals_rule defs);
   503 
   504 fun rewtac def = rewrite_goals_tac [def];
   505 
   506 
   507 (*** for folding definitions, handling critical pairs ***)
   508 
   509 (*The depth of nesting in a term*)
   510 fun term_depth (Abs(a,T,t)) = 1 + term_depth t
   511   | term_depth (f$t) = 1 + Int.max(term_depth f, term_depth t)
   512   | term_depth _ = 0;
   513 
   514 val lhs_of_thm = #1 o Logic.dest_equals o #prop o rep_thm;
   515 
   516 (*folding should handle critical pairs!  E.g. K == Inl(0),  S == Inr(Inl(0))
   517   Returns longest lhs first to avoid folding its subexpressions.*)
   518 fun sort_lhs_depths defs =
   519   let val keylist = make_keylist (term_depth o lhs_of_thm) defs
   520       val keys = distinct (sort (rev_order o int_ord) (map #2 keylist))
   521   in  map (keyfilter keylist) keys  end;
   522 
   523 fun fold_tac defs = EVERY 
   524     (map rewrite_tac (sort_lhs_depths (map symmetric defs)));
   525 
   526 fun fold_goals_tac defs = EVERY 
   527     (map rewrite_goals_tac (sort_lhs_depths (map symmetric defs)));
   528 
   529 
   530 (*** Renaming of parameters in a subgoal
   531      Names may contain letters, digits or primes and must be
   532      separated by blanks ***)
   533 
   534 (*Calling this will generate the warning "Same as previous level" since
   535   it affects nothing but the names of bound variables!*)
   536 fun rename_tac str i = 
   537   let val cs = Symbol.explode str 
   538   in  
   539   if !Logic.auto_rename 
   540   then (warning "Resetting Logic.auto_rename"; 
   541 	Logic.auto_rename := false)
   542   else ();
   543   case #2 (take_prefix (Symbol.is_letdig orf Symbol.is_blank) cs) of
   544       [] => PRIMITIVE (rename_params_rule (scanwords Symbol.is_letdig cs, i))
   545     | c::_ => error ("Illegal character: " ^ c)
   546   end;
   547 
   548 (*Rename recent parameters using names generated from a and the suffixes,
   549   provided the string a, which represents a term, is an identifier. *)
   550 fun rename_last_tac a sufs i = 
   551   let val names = map (curry op^ a) sufs
   552   in  if Syntax.is_identifier a
   553       then PRIMITIVE (rename_params_rule (names,i))
   554       else all_tac
   555   end;
   556 
   557 (*Prunes all redundant parameters from the proof state by rewriting.
   558   DOES NOT rewrite main goal, where quantification over an unused bound
   559     variable is sometimes done to avoid the need for cut_facts_tac.*)
   560 val prune_params_tac = rewrite_goals_tac [triv_forall_equality];
   561 
   562 (*rotate_tac n i: rotate the assumptions of subgoal i by n positions, from
   563   right to left if n is positive, and from left to right if n is negative.*)
   564 fun rotate_tac 0 i = all_tac
   565   | rotate_tac k i = PRIMITIVE (rotate_rule k i);
   566 
   567 (* remove premises that do not satisfy p; fails if all prems satisfy p *)
   568 fun filter_prems_tac p =
   569   let fun Then None tac = Some tac
   570         | Then (Some tac) tac' = Some(tac THEN' tac');
   571       fun thins ((tac,n),H) =
   572         if p H then (tac,n+1)
   573         else (Then tac (rotate_tac n THEN' etac thin_rl),0);
   574   in SUBGOAL(fn (subg,n) =>
   575        let val Hs = Logic.strip_assums_hyp subg
   576        in case fst(foldl thins ((None,0),Hs)) of
   577             None => no_tac | Some tac => tac n
   578        end)
   579   end;
   580 
   581 end;
   582 
   583 open Tactic;