src/Tools/isac/Interpret/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Mon, 18 Jul 2011 09:29:17 +0200
branchdecompose-isar
changeset 42092 1a6d6089e594
parent 42082 2556b7865f9b
child 42133 f9a7294e6cd6
permissions -rw-r--r--
intermed: make autocalc..CompleteCalc run with x+1=2

runs, although correction not perfect
error WAS in fun all_modspec: ctxt from fmz and not pors
TODO: check all other "prep_ori fmz thy ppc |> #1"
     1 (* interpreter for scripts
     2    (c) Walther Neuper 2000
     3 
     4 use"ME/script.sml";
     5 use"script.sml";
     6 *)
     7 signature INTERPRETER =
     8 sig
     9   (*type ets (list of executed tactics) see sequent.sml*)
    10 
    11   datatype locate
    12     = NotLocatable
    13     | Steps of (tac_ * mout * ptree * pos' * cid * safe (* ets*)) list
    14 (*    | ToDo of ets 28.4.02*)
    15 
    16   (*diss: next-tactic-function*)
    17   val next_tac : theory' -> ptree * pos' -> metID -> scr -> ets -> tac_
    18   (*diss: locate-function*)
    19   val locate_gen : theory'
    20                    -> tac_
    21                       -> ptree * pos' -> scr * rls -> ets -> loc_ -> locate
    22 
    23   val sel_rules : ptree -> pos' -> tac list
    24   val init_form : scr -> ets -> loc_ * term option (*FIXME not up to date*)
    25   val formal_args : term -> term list
    26 
    27   (*shift to library ...*)
    28   val inst_abs : theory' -> term -> term
    29   val itms2args : metID -> itm list -> term list
    30   val user_interrupt : loc_ * (tac_ * env * env * term * term * safe)
    31   (*val empty : term*) 
    32 end 
    33 
    34 
    35 
    36 
    37 (*
    38 structure Interpreter : INTERPRETER =
    39 struct
    40 *)
    41 
    42 (*.traces the leaves (ie. non-tactical nodes) of the script
    43    found by next_tac.
    44    a leaf is either a tactic or an 'exp' in 'let v = expr'
    45    where 'exp' does not contain a tactic.*)   
    46 val trace_script = Unsynchronized.ref false;
    47 
    48 type step =     (*data for creating a new node in the ptree;
    49 		 designed for use:
    50                	 fun ass* scrstate steps =
    51                	 ... case ass* scrstate steps of
    52                	     Assoc (scrstate, steps) => ... ass* scrstate steps*)
    53     tac_       (*transformed from associated tac*)
    54     * mout       (*result with indentation etc.*)
    55     * ptree      (*containing node created by tac_ + resp. scrstate*)
    56     * pos'       (*position in ptree; ptree * pos' is the proofstate*)
    57     * pos' list; (*of ptree-nodes probably cut (by fst tac_)*)
    58 val e_step = (Empty_Tac_, EmptyMout, EmptyPtree, e_pos',[]:pos' list):step;
    59 
    60 fun rule2thm' (Thm (id, thm)) = (id, string_of_thmI thm):thm'
    61   | rule2thm' r = error ("rule2thm': not defined for "^(rule2str r));
    62 fun rule2rls' (Rls_ rls) = id_rls rls
    63   | rule2rls' r = error ("rule2rls': not defined for "^(rule2str r));
    64 
    65 (*.makes a (rule,term) list to a Step (m, mout, pt', p', cid) for solve;
    66    complicated with current t in rrlsstate.*)
    67 fun rts2steps steps ((pt,p),(f,f'',rss,rts),(thy',ro,er,pa)) [(r, (f', am))] =
    68       let
    69         val thy = assoc_thy thy'
    70         val ctxt = get_ctxt pt p |> insert_assumptions am
    71 	      val m = Rewrite' (thy', ro, er, pa, rule2thm' r, f, (f', am))
    72 	      val is = RrlsState (f', f'', rss, rts)
    73 	      val p = case p of (p',Frm) => p | (p',Res) => (lev_on p',Res)
    74 	      val (p', cid, mout, pt') = generate1 thy m (is, ctxt) p pt
    75       in (is, (m, mout, pt', p', cid) :: steps) end
    76   | rts2steps steps ((pt,p),(f,f'',rss,rts),(thy',ro,er,pa)) ((r, (f', am))::rts') =
    77       let
    78         val thy = assoc_thy thy'
    79         val ctxt = get_ctxt pt p |> insert_assumptions am
    80 	      val m = Rewrite' (thy',ro,er,pa, rule2thm' r, f, (f', am))
    81 	      val is = RrlsState (f',f'',rss,rts)
    82 	      val p = case p of (p',Frm) => p | (p',Res) => (lev_on p',Res)
    83 	      val (p', cid, mout, pt') = generate1 thy m (is, ctxt) p pt
    84       in rts2steps ((m, mout, pt', p', cid)::steps) 
    85 		    ((pt',p'),(f',f'',rss,rts),(thy',ro,er,pa)) rts' end;
    86 
    87 (*. functions for the environment stack .*)
    88 fun accessenv id es = the (assoc((top es):env, id))
    89     handle _ => error ("accessenv: "^(free2str id)^" not in env");
    90 fun updateenv id vl (es:env stack) = 
    91     (push (overwrite(top es, (id, vl))) (pop es)):env stack;
    92 fun pushenv id vl (es:env stack) = 
    93     (push (overwrite(top es, (id, vl))) es):env stack;
    94 val popenv = pop:env stack -> env stack;
    95 
    96 
    97 
    98 fun de_esc_underscore str =
    99   let fun scan [] = []
   100 	| scan (s::ss) = if s = "'" then (scan ss)
   101 			 else (s::(scan ss))
   102   in (implode o scan o Symbol.explode) str end;
   103 (*
   104 > val str = "Rewrite_Set_Inst";
   105 > val esc = esc_underscore str;
   106 val it = "Rewrite'_Set'_Inst" : string
   107 > val des = de_esc_underscore esc;
   108  val des = de_esc_underscore esc;*)
   109 
   110 (*go at a location in a script and fetch the contents*)
   111 fun go [] t = t
   112   | go (D::p) (Abs(s,ty,t0)) = go (p:loc_) t0
   113   | go (L::p) (t1 $ t2) = go p t1
   114   | go (R::p) (t1 $ t2) = go p t2
   115   | go l _ = error ("go: no "^(loc_2str l));
   116 (*
   117 > val t = (term_of o the o (parse thy)) "a+b";
   118 val it = Const (#,#) $ Free (#,#) $ Free ("b","RealDef.real") : term
   119 > val plus_a = go [L] t; 
   120 > val b = go [R] t; 
   121 > val plus = go [L,L] t; 
   122 > val a = go [L,R] t;
   123 
   124 > val t = (term_of o the o (parse thy)) "a+b+c";
   125 val t = Const (#,#) $ (# $ # $ Free #) $ Free ("c","RealDef.real") : term
   126 > val pl_pl_a_b = go [L] t; 
   127 > val c = go [R] t; 
   128 > val a = go [L,R,L,R] t; 
   129 > val b = go [L,R,R] t; 
   130 *)
   131 
   132 
   133 (* get a subterm t with test t, and record location *)
   134 fun get l test (t as Const (s,T)) = 
   135     if test t then SOME (l,t) else NONE
   136   | get l test (t as Free (s,T)) = 
   137     if test t then SOME (l,t) else NONE 
   138   | get l test (t as Bound n) =
   139     if test t then SOME (l,t) else NONE 
   140   | get l test (t as Var (s,T)) =
   141     if test t then SOME (l,t) else NONE
   142   | get l test (t as Abs (s,T,body)) =
   143     if test t then SOME (l:loc_,t) else get ((l@[D]):loc_) test body
   144   | get l test (t as t1 $ t2) =
   145     if test t then SOME (l,t) 
   146     else case get (l@[L]) test t1 of 
   147       NONE => get (l@[R]) test t2
   148     | SOME (l',t') => SOME (l',t');
   149 (*18.6.00
   150 > val sss = ((term_of o the o (parse thy))
   151   "Script Solve_root_equation (eq_::bool) (v_::real) (err_::bool) =\
   152    \ (let e_ = Try (Rewrite square_equation_left True eq_) \
   153    \  in [e_])");
   154           ______ compares head_of !!
   155 > get [] (eq_str "HOL.Let") sss;            [R]
   156 > get [] (eq_str "Script.Try") sss;     [R,L,R]
   157 > get [] (eq_str "Script.Rewrite") sss; [R,L,R,R]
   158 > get [] (eq_str "HOL.True") sss;           [R,L,R,R,L,R]
   159 > get [] (eq_str "e_") sss;             [R,R]
   160 *)
   161 
   162 fun test_negotiable t = 
   163     member op = (!negotiable) 
   164            ((strip_thy o (term_str (Thy_Info.get_theory "Script")) o head_of) t);
   165 
   166 (*.get argument of first stactic in a script for init_form.*)
   167 fun get_stac thy (h $ body) =
   168   let
   169     fun get_t y (Const ("Script.Seq",_) $ e1 $ e2) a = 
   170     	(case get_t y e1 a of NONE => get_t y e2 a | la => la)
   171       | get_t y (Const ("Script.Seq",_) $ e1 $ e2 $ a) _ = 
   172     	(case get_t y e1 a of NONE => get_t y e2 a | la => la)
   173       | get_t y (Const ("Script.Try",_) $ e) a = get_t y e a
   174       | get_t y (Const ("Script.Try",_) $ e $ a) _ = get_t y e a
   175       | get_t y (Const ("Script.Repeat",_) $ e) a = get_t y e a
   176       | get_t y (Const ("Script.Repeat",_) $ e $ a) _ = get_t y e a
   177       | get_t y (Const ("Script.Or",_) $e1 $ e2) a =
   178     	(case get_t y e1 a of NONE => get_t y e2 a | la => la)
   179       | get_t y (Const ("Script.Or",_) $e1 $ e2 $ a) _ =
   180     	(case get_t y e1 a of NONE => get_t y e2 a | la => la)
   181       | get_t y (Const ("Script.While",_) $ c $ e) a = get_t y e a
   182       | get_t y (Const ("Script.While",_) $ c $ e $ a) _ = get_t y e a
   183       | get_t y (Const ("Script.Letpar",_) $ e1 $ Abs (_,_,e2)) a = 
   184     	(case get_t y e1 a of NONE => get_t y e2 a | la => la)
   185     (*| get_t y (Const ("HOL.Let",_) $ e1 $ Abs (_,_,e2)) a =
   186 	    (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   187       | get_t y (Abs (_,_,e)) a = get_t y e a*)
   188       | get_t y (Const ("HOL.Let",_) $ e1 $ Abs (_,_,e2)) a =
   189     	get_t y e1 a (*don't go deeper without evaluation !*)
   190       | get_t y (Const ("If",_) $ c $ e1 $ e2) a = NONE
   191     	(*(case get_t y e1 a of NONE => get_t y e2 a | la => la)*)
   192     
   193       | get_t y (Const ("Script.Rewrite",_) $ _ $ _ $ a) _ = SOME a
   194       | get_t y (Const ("Script.Rewrite",_) $ _ $ _    ) a = SOME a
   195       | get_t y (Const ("Script.Rewrite'_Inst",_) $ _ $ _ $ _ $ a) _ = SOME a
   196       | get_t y (Const ("Script.Rewrite'_Inst",_) $ _ $ _ $ _ )    a = SOME a
   197       | get_t y (Const ("Script.Rewrite'_Set",_) $ _ $ _ $ a) _ = SOME a
   198       | get_t y (Const ("Script.Rewrite'_Set",_) $ _ $ _ )    a = SOME a
   199       | get_t y (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ _ $ _ $a)_ =SOME a
   200       | get_t y (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ _ $ _ )  a =SOME a
   201       | get_t y (Const ("Script.Calculate",_) $ _ $ a) _ = SOME a
   202       | get_t y (Const ("Script.Calculate",_) $ _ )    a = SOME a
   203     
   204       | get_t y (Const ("Script.Substitute",_) $ _ $ a) _ = SOME a
   205       | get_t y (Const ("Script.Substitute",_) $ _ )    a = SOME a
   206     
   207       | get_t y (Const ("Script.SubProblem",_) $ _ $ _) _ = NONE
   208 
   209       | get_t y x _ =  
   210 	((*tracing ("### get_t yac: list-expr "^(term2str x));*)
   211 	 NONE)
   212 in get_t thy body e_term end;
   213     
   214 (*FIXME: get 1st stac by next_stac [] instead of ... ?? 29.7.02*)
   215 (* val Script sc = scr;
   216    *)
   217 fun init_form thy (Script sc) env =
   218   (case get_stac thy sc of
   219      NONE => NONE 
   220              (*error ("init_form: no 1st stac in "^
   221 	      (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy)) sc))*)
   222    | SOME stac => SOME (subst_atomic env stac))
   223   | init_form _ _ _ = error "init_form: no match";
   224 
   225 (* use"ME/script.sml";
   226    use"script.sml";
   227    *)
   228 
   229 
   230 
   231 (*the 'iteration-argument' of a stac (args not eval)*)
   232 fun itr_arg _ (Const ("Script.Rewrite'_Inst",_) $ _ $ _ $ _ $ v) = v
   233   | itr_arg _ (Const ("Script.Rewrite",_) $ _ $ _ $ v) = v
   234   | itr_arg _ (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ _ $ _ $ v) = v
   235   | itr_arg _ (Const ("Script.Rewrite'_Set",_) $ _ $ _ $ v) = v
   236   | itr_arg _ (Const ("Script.Calculate",_) $ _ $ v) = v
   237   | itr_arg _ (Const ("Script.Check'_elementwise",_) $ consts $ _) = consts
   238   | itr_arg _ (Const ("Script.Or'_to'_List",_) $ _) = e_term
   239   | itr_arg _ (Const ("Script.Tac",_) $ _) = e_term
   240   | itr_arg _ (Const ("Script.SubProblem",_) $ _ $ _) = e_term
   241   | itr_arg thy t = error 
   242     ("itr_arg not impl. for " ^
   243     (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt (assoc_thy thy))) t));
   244 (* val t = (term_of o the o (parse thy))"Rewrite rroot_square_inv False e_";
   245 > itr_arg "Script" t;
   246 val it = Free ("e_","RealDef.real") : term 
   247 > val t = (term_of o the o (parse thy))"xxx";
   248 > itr_arg "Script" t;
   249 *** itr_arg not impl. for xxx
   250 uncaught exception ERROR
   251   raised at: library.ML:1114.35-1114.40*)
   252 
   253 
   254 (*.get the arguments of the script out of the scripts parsetree.*)
   255 fun formal_args scr = (fst o split_last o snd o strip_comb) scr;
   256 (*
   257 > formal_args scr;
   258   [Free ("f_","RealDef.real"),Free ("v_","RealDef.real"),
   259    Free ("eqs_","bool List.list")] : term list
   260 *)
   261 
   262 (*.get the identifier of the script out of the scripts parsetree.*)
   263 fun id_of_scr sc = (id_of o fst o strip_comb) sc;
   264 
   265 (*WN020526: not clear, when a is available in ass_up for eva-_true*)
   266 (*WN060906: in "fun handle_leaf" eg. uses "SOME M__"(from some PREVIOUS
   267   curried Rewrite) for CURRENT value (which may be different from PREVIOUS);
   268   thus "NONE" must be set at the end of currying (ill designed anyway)*)
   269 fun upd_env_opt env (SOME a, v) = upd_env env (a,v)
   270   | upd_env_opt env (NONE, v) = 
   271       (tracing ("*** upd_env_opt: (NONE," ^ term2str v ^ ")"); env);
   272 
   273 type dsc = typ; (*<-> nam..unknow in Descript.thy*)
   274 fun typ_str (Type (s,_)) = s
   275   | typ_str (TFree(s,_)) = s
   276   | typ_str (TVar ((s,i),_)) = s ^ (string_of_int i);
   277 	     
   278 (*get the _result_-type of a description*)
   279 fun dsc_valT (Const (_,(Type (_,[_,T])))) = (strip_thy o typ_str) T;
   280 (*> val t = (term_of o the o (parse thy)) "equality";
   281 > val T = type_of t;
   282 val T = "bool => Tools.una" : typ
   283 > val dsc = dsc_valT t;
   284 val dsc = "una" : string
   285 
   286 > val t = (term_of o the o (parse thy)) "fixedValues";
   287 > val T = type_of t;
   288 val T = "bool List.list => Tools.nam" : typ
   289 > val dsc = dsc_valT t;
   290 val dsc = "nam" : string*)
   291 
   292 (*.from penv in itm_ make args for script depending on type of description.*)
   293 (*6.5.03 TODO: push penv into script -- and drop mk_arg here || drop penv
   294   9.5.03 penv postponed: penv = env for script at the moment, (*mk_arg*)*)
   295 fun mk_arg thy d [] = 
   296     error ("mk_arg: no data for " ^
   297 	   (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy)) d))
   298   | mk_arg thy d [t] = 
   299     (case dsc_valT d of
   300 	 "una" => [t]
   301        | "nam" => 
   302 	 [case t of
   303 	      r as (Const ("HOL.eq",_) $ _ $ _) => r
   304 	    | _ => error ("mk_arg: dsc-typ 'nam' applied to non-equality "^
   305 		     (Print_Mode.setmp [] (Syntax.string_of_term
   306                                                (thy2ctxt thy)) t))]
   307        | s => error ("mk_arg: not impl. for "^s))
   308     
   309   | mk_arg thy d (t::ts) = (mk_arg thy d [t]) @ (mk_arg thy d ts);
   310 (* 
   311  val d = d_in itm_;
   312  val [t] = ts_in itm_;
   313 mk_arg thy
   314 *)
   315 
   316 
   317 
   318 
   319 (*.create the actual parameters (args) of script: their order 
   320   is given by the order in met.pat .*)
   321 (*WN.5.5.03: ?: does this allow for different descriptions ???
   322              ?: why not taken from formal args of script ???
   323 !: FIXXXME penv: push it here in itms2args into script-evaluation*)
   324 (* val (thy, mI, itms) = (thy, metID, itms);
   325    *)
   326 fun itms2args thy mI (itms:itm list) =
   327     let val mvat = max_vt itms
   328 	fun okv mvat (_,vats,b,_,_) = member op = vats mvat andalso b
   329 	val itms = filter (okv mvat) itms
   330 	fun test_dsc d (_,_,_,_,itm_) = (d = d_in itm_)
   331 	fun itm2arg itms (_,(d,_)) =
   332 	    case find_first (test_dsc d) itms of
   333 		NONE => 
   334 		error ("itms2args: '"^term2str d^"' not in itms")
   335 	      (*| SOME (_,_,_,_,itm_) => mk_arg thy (d_in itm_) (ts_in itm_);
   336                penv postponed; presently penv holds already env for script*)
   337 	      | SOME (_,_,_,_,itm_) => penvval_in itm_
   338 	fun sel_given_find (s,_) = (s = "#Given") orelse (s = "#Find")
   339 	val pats = (#ppc o get_met) mI
   340     in (flat o (map (itm2arg itms))) pats end;
   341 (*
   342 > val sc = ... Solve_root_equation ...
   343 > val mI = ("Script","sqrt-equ-test");
   344 > val PblObj{meth={ppc=itms,...},...} = get_obj I pt [];
   345 > val ts = itms2args thy mI itms;
   346 > map (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy))) ts;
   347 ["sqrt (#9 + #4 * x) = sqrt x + sqrt (#5 + x)","x","#0"] : string list
   348 *)
   349 
   350 
   351 (*detour necessary, because generate1 delivers a string-result*)
   352 fun mout2term thy (Form' (FormKF (_,_,_,_,res))) = 
   353   (term_of o the o (parse (assoc_thy thy))) res
   354   | mout2term thy (Form' (PpcKF _)) = e_term;(*3.8.01: res of subpbl 
   355 					   at time of detection in script*)
   356 
   357 (*.convert a script-tac 'stac' to a tactic 'tac'; if stac is an initac,
   358    then convert to a 'tac_' (as required in appy).
   359    arg pt:ptree for pushing the thy specified in rootpbl into subpbls.*)
   360 fun stac2tac_ pt thy (Const ("Script.Rewrite",_) $ Free (thmID,_) $ _ $ f) =
   361       let
   362         val tid = (de_esc_underscore o strip_thy) thmID
   363       in (Rewrite (tid, (string_of_thmI o (assoc_thm' thy)) (tid,"")), Empty_Tac_)
   364       end
   365 
   366   | stac2tac_ pt thy (Const ("Script.Rewrite'_Inst",_) $ sub $ Free (thmID,_) $ _ $ f) =
   367       let
   368         val subML = ((map isapair2pair) o isalist2list) sub
   369         val subStr = subst2subs subML
   370         val tid = (de_esc_underscore o strip_thy) thmID (*4.10.02 unnoetig*)
   371       in (Rewrite_Inst (subStr, (tid, (string_of_thmI o (assoc_thm' thy)) (tid,""))), Empty_Tac_)
   372       end
   373       
   374   | stac2tac_ pt thy (Const ("Script.Rewrite'_Set",_) $ Free (rls,_) $ _ $ f) =
   375       (Rewrite_Set ((de_esc_underscore o strip_thy) rls), Empty_Tac_)
   376 
   377   | stac2tac_ pt thy (Const ("Script.Rewrite'_Set'_Inst",_) $ sub $ Free (rls,_) $ _ $ f) =
   378       let
   379         val subML = ((map isapair2pair) o isalist2list) sub;
   380         val subStr = subst2subs subML;
   381       in (Rewrite_Set_Inst (subStr,rls), Empty_Tac_) end
   382 
   383   | stac2tac_ pt thy (Const ("Script.Calculate",_) $ Free (op_,_) $ f) =
   384       (Calculate op_, Empty_Tac_)
   385 
   386   | stac2tac_ pt thy (Const ("Script.Take",_) $ t) =
   387       (Take (term2str t), Empty_Tac_)
   388 
   389   | stac2tac_ pt thy (Const ("Script.Substitute",_) $ isasub $ arg) =
   390       (Substitute ((subte2sube o isalist2list) isasub), Empty_Tac_)
   391 
   392   | stac2tac_ pt thy (Const("Script.Check'_elementwise",_) $ _ $ 
   393 		(set as Const ("Set.Collect",_) $ Abs (_,_,pred))) = 
   394       (Check_elementwise (Print_Mode.setmp [] (Syntax.string_of_term 
   395                           (thy2ctxt thy)) pred), (*set*)Empty_Tac_)
   396 
   397   | stac2tac_ pt thy (Const("Script.Or'_to'_List",_) $ _ ) = 
   398       (Or_to_List, Empty_Tac_)
   399 
   400     (*12.1.01.for subproblem_equation_dummy in root-equation *)
   401   | stac2tac_ pt thy (Const ("Script.Tac",_) $ Free (str,_)) = 
   402       (Tac ((de_esc_underscore o strip_thy) str),  Empty_Tac_) 
   403 
   404     (*compare "| assod _ (Subproblem'"*)
   405   | stac2tac_ pt thy (stac as Const ("Script.SubProblem",_) $
   406 	  (Const ("Product_Type.Pair",_) $Free (dI',_) $ 
   407 		 (Const ("Product_Type.Pair",_) $ pI' $ mI')) $ ags') =
   408       let
   409         val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   410         val thy = maxthy (assoc_thy dI) (rootthy pt);
   411 	      val pI = ((map (de_esc_underscore o free2str)) o isalist2list) pI';
   412 	      val mI = ((map (de_esc_underscore o free2str)) o isalist2list) mI';
   413 	      val ags = isalist2list ags';
   414 	      val (pI, pors, mI) = 
   415 	        if mI = ["no_met"] 
   416 	        then
   417             let
   418               val pors = (match_ags thy ((#ppc o get_pbt) pI) ags)
   419 			          handle ERROR "actual args do not match formal args" 
   420 				        => (match_ags_msg pI stac ags(*raise exn*); [])
   421 		          val pI' = refine_ori' pors pI;
   422 		        in (pI', pors (*refinement over models with diff.prec only*), 
   423 		            (hd o #met o get_pbt) pI') end
   424 	        else (pI, (match_ags thy ((#ppc o get_pbt) pI) ags)
   425 		        handle ERROR "actual args do not match formal args"
   426 			      => (match_ags_msg pI stac ags(*raise exn*); []), mI);
   427         val (fmz_, vals) = oris2fmz_vals pors;
   428 	      val {cas,ppc,thy,...} = get_pbt pI
   429 	      val dI = theory2theory' thy (*.take dI from _refined_ pbl.*)
   430 	      val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt));
   431         val ctxt = ProofContext.init_global 
   432         val ctxt = dI |> Thy_Info.get_theory |> ProofContext.init_global 
   433           |> declare_constraints' vals
   434 	      val hdl =
   435           case cas of
   436 		        NONE => pblterm dI pI
   437 		      | SOME t => subst_atomic ((vars_of_pbl_' ppc) ~~~ vals) t
   438         val f = subpbl (strip_thy dI) pI
   439       in (Subproblem (dI, pI),	Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f))
   440       end
   441 
   442   | stac2tac_ pt thy t = error 
   443   ("stac2tac_ TODO: no match for " ^
   444    (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy)) t));
   445 
   446 fun stac2tac pt thy t = (fst o stac2tac_ pt thy) t;
   447 
   448 (*test a term for being a _list_ (set ?) of constants; could be more rigorous*)
   449 fun list_of_consts (Const ("List.list.Cons",_) $ _ $ _) = true
   450   | list_of_consts (Const ("List.list.Nil",_)) = true
   451   | list_of_consts _ = false;
   452 (*val ttt = (term_of o the o (parse thy)) "[x=#1,x=#2,x=#3]";
   453 > list_of_consts ttt;
   454 val it = true : bool
   455 > val ttt = (term_of o the o (parse thy)) "[]";
   456 > list_of_consts ttt;
   457 val it = true : bool*)
   458 
   459 
   460 
   461 datatype ass = 
   462     Ass of
   463       tac_ *   (* SubProblem gets args instantiated in assod *)
   464   	  term     (* for itr_arg, result in ets *)
   465   | AssWeak of
   466       tac_ *
   467   	  term     (*for itr_arg,result in ets*)
   468   | NotAss;
   469 
   470 (*.assod: tac_ associated with stac w.r.t. d
   471 args
   472  pt:ptree for pushing the thy specified in rootpbl into subpbls
   473 returns
   474  Ass    : associated: e.g. thmID in stac = thmID in m
   475                        +++ arg   in stac = arg   in m
   476  AssWeak: weakly ass.:e.g. thmID in stac = thmID in m, //arg//
   477  NotAss :             e.g. thmID in stac/=/thmID in m (not =)
   478 8.01:
   479  tac_ SubProblem with args completed from script
   480 .*)
   481 fun assod pt d (m as Rewrite_Inst' (thy',rod,rls,put,subs,(thmID,thm),f,(f',asm))) stac =
   482       (case stac of
   483 	       (Const ("Script.Rewrite'_Inst",_) $ subs_ $ Free (thmID_,idT) $b$f_) =>
   484 	          if thmID = thmID_
   485             then 
   486 	            if f = f_ 
   487               then ((*tracing"3### assod ..Ass";*)Ass (m,f')) 
   488 	            else ((*tracing"3### assod ..AssWeak";*)AssWeak(m, f'))
   489 	          else ((*tracing"3### assod ..NotAss";*)NotAss)
   490        | (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $_$f_) =>
   491 	          if contains_rule (Thm (thmID, refl(*dummy*))) (assoc_rls rls_)
   492             then 
   493 	            if f = f_ then Ass (m,f') else AssWeak (m,f')
   494 	          else NotAss
   495        | _ => NotAss)
   496 
   497   | assod pt d (m as Rewrite' (thy,rod,rls,put,(thmID,thm),f,(f',asm))) stac =
   498       (case stac of
   499 	       (t as Const ("Script.Rewrite",_) $ Free (thmID_,idT) $ b $ f_) =>
   500 	         ((*tracing ("3### assod: stac = " ^ ter2str t);
   501 	          tracing ("3### assod: f(m)= " ^ term2str f);*)
   502 	          if thmID = thmID_
   503             then 
   504 	            if f = f_
   505               then ((*tracing"3### assod ..Ass";*)Ass (m,f')) 
   506 	            else 
   507                 ((*tracing"### assod ..AssWeak";
   508 		             tracing("### assod: f(m)  = " ^ term2str f);
   509 		             tracing("### assod: f(stac)= " ^ term2str f_)*)
   510 		             AssWeak (m,f'))
   511 	          else ((*tracing"3### assod ..NotAss";*)NotAss))
   512        | (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) =>
   513 	          if contains_rule (Thm (thmID, refl(*dummy*))) (assoc_rls rls_)
   514             then
   515 	            if f = f_ then Ass (m,f') else AssWeak (m,f')
   516 	          else NotAss
   517        | _ => NotAss)
   518 
   519   | assod pt d (m as Rewrite_Set_Inst' (thy',put,sub,rls,f,(f',asm))) 
   520     (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $ _ $ f_) = 
   521       if id_rls rls = rls_ 
   522       then 
   523         if f = f_ then Ass (m,f') else AssWeak (m,f')
   524       else NotAss
   525 
   526   | assod pt d (m as Detail_Set_Inst' (thy',put,sub,rls,f,(f',asm))) 
   527     (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $ _ $ f_) = 
   528       if id_rls rls = rls_
   529       then 
   530         if f = f_ then Ass (m,f') else AssWeak (m,f')
   531       else NotAss
   532 
   533   | assod pt d (m as Rewrite_Set' (thy,put,rls,f,(f',asm))) 
   534     (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) = 
   535       if id_rls rls = rls_
   536       then 
   537         if f = f_ then Ass (m,f') else AssWeak (m,f')
   538       else NotAss
   539 
   540   | assod pt d (m as Detail_Set' (thy,put,rls,f,(f',asm))) 
   541     (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) = 
   542       if id_rls rls = rls_
   543       then 
   544         if f = f_ then Ass (m,f') else AssWeak (m,f')
   545       else NotAss
   546 
   547   | assod pt d (m as Calculate' (thy',op_,f,(f',thm'))) stac =
   548       (case stac of
   549 	       (Const ("Script.Calculate",_) $ Free (op__,_) $ f_) =>
   550 	         if op_ = op__
   551            then
   552 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   553 	         else NotAss
   554        | (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free(rls_,_) $_$f_)  => 
   555 	         if contains_rule (Calc (snd (assoc1 (!calclist', op_)))) (assoc_rls rls_)
   556            then
   557 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   558 	         else NotAss
   559        | (Const ("Script.Rewrite'_Set",_) $ Free (rls_, _) $ _ $ f_) =>
   560 	         if contains_rule (Calc (snd (assoc1 (!calclist', op_)))) (assoc_rls rls_)
   561            then
   562 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   563 	         else NotAss
   564        | _ => NotAss)
   565 
   566   | assod pt _ (m as Check_elementwise' (consts,_,(consts_chkd,_)))
   567     (Const ("Script.Check'_elementwise",_) $ consts' $ _) =
   568       ((*tracing("### assod Check'_elementwise: consts= "^(term2str consts)^
   569 	     ", consts'= "^(term2str consts'));
   570        atomty consts; atomty consts';*)
   571        if consts = consts'
   572        then ((*tracing"### assod Check'_elementwise: Ass";*) Ass (m, consts_chkd))
   573        else ((*tracing"### assod Check'_elementwise: NotAss";*) NotAss))
   574 
   575   | assod pt _ (m as Or_to_List' (ors, list)) (Const ("Script.Or'_to'_List",_) $ _) =
   576 	    Ass (m, list) 
   577 
   578   | assod pt _ (m as Take' term) (Const ("Script.Take",_) $ _) =
   579 	    Ass (m, term)
   580 
   581   | assod pt _ (m as Substitute' (_, _, res)) (Const ("Script.Substitute",_) $ _ $ _) =
   582 	    Ass (m, res) 
   583 
   584   | assod pt _ (m as Tac_ (thy,f,id,f')) (Const ("Script.Tac",_) $ Free (id',_)) =
   585       if id = id'
   586       then Ass (m, ((term_of o the o (parse thy)) f'))
   587       else NotAss
   588 
   589     (*compare "| stac2tac_ thy (Const ("Script.SubProblem",_)"*)
   590   | assod pt _ (Subproblem' ((domID,pblID,metID),_,_,_,_,f))
   591 	  (stac as Const ("Script.SubProblem",_) $ (Const ("Product_Type.Pair",_) $
   592 		 Free (dI',_) $ (Const ("Product_Type.Pair",_) $ pI' $ mI')) $ ags') =
   593       let 
   594         val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   595         val thy = maxthy (assoc_thy dI) (rootthy pt);
   596 	      val pI = ((map (de_esc_underscore o free2str)) o isalist2list) pI';
   597 	      val mI = ((map (de_esc_underscore o free2str)) o isalist2list) mI';
   598 	      val ags = isalist2list ags';
   599 	      val (pI, pors, mI) = 
   600 	        if mI = ["no_met"] 
   601 	        then
   602             let
   603               val pors = (match_ags thy ((#ppc o get_pbt) pI) ags)
   604 			          handle ERROR "actual args do not match formal args"
   605 				        => (match_ags_msg pI stac ags(*raise exn*);[]);
   606 		          val pI' = refine_ori' pors pI;
   607 		        in (pI', pors (*refinement over models with diff.prec only*), 
   608 		            (hd o #met o get_pbt) pI')
   609             end
   610 	        else (pI, (match_ags thy ((#ppc o get_pbt) pI) ags)
   611 		        handle ERROR "actual args do not match formal args"
   612 			      => (match_ags_msg pI stac ags(*raise exn*);[]), mI);
   613         val (fmz_, vals) = oris2fmz_vals pors;
   614 	      val {cas, ppc, thy,...} = get_pbt pI
   615 	      val dI = theory2theory' thy (*take dI from _refined_ pbl*)
   616 	      val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt))
   617 	      val ctxt = dI |> Thy_Info.get_theory |> ProofContext.init_global 
   618           |> declare_constraints' vals
   619 	      val hdl = 
   620           case cas of
   621 		        NONE => pblterm dI pI
   622 		      | SOME t => subst_atomic ((vars_of_pbl_' ppc) ~~~ vals) t
   623         val f = subpbl (strip_thy dI) pI
   624       in 
   625         if domID = dI andalso pblID = pI
   626         then Ass (Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f), f) 
   627         else NotAss
   628       end
   629 
   630   | assod pt d m t = 
   631       (if (!trace_script) 
   632        then tracing("@@@ the 'tac_' proposed to apply does NOT match the leaf found in the script:\n"^
   633 		     "@@@ tac_ = "^(tac_2str m))
   634        else ();
   635        NotAss);
   636 
   637 fun tac_2tac (Refine_Tacitly' (pI,_,_,_,_)) = Refine_Tacitly pI
   638   | tac_2tac (Model_Problem' (pI,_,_))      = Model_Problem
   639   | tac_2tac (Add_Given' (t,_))             = Add_Given t
   640   | tac_2tac (Add_Find' (t,_))              = Add_Find t
   641   | tac_2tac (Add_Relation' (t,_))          = Add_Relation t
   642  
   643   | tac_2tac (Specify_Theory' dI)           = Specify_Theory dI
   644   | tac_2tac (Specify_Problem' (dI,_))      = Specify_Problem dI
   645   | tac_2tac (Specify_Method' (dI,_,_))     = Specify_Method dI
   646   
   647   | tac_2tac (Rewrite' (thy,rod,erls,put,(thmID,thm),f,(f',asm))) = Rewrite (thmID,thm)
   648 
   649   | tac_2tac (Rewrite_Inst' (thy,rod,erls,put,sub,(thmID,thm),f,(f',asm)))=
   650       Rewrite_Inst (subst2subs sub,(thmID,thm))
   651 
   652   | tac_2tac (Rewrite_Set' (thy,put,rls,f,(f',asm))) = Rewrite_Set (id_rls rls)
   653   | tac_2tac (Detail_Set' (thy,put,rls,f,(f',asm))) = Detail_Set (id_rls rls)
   654 
   655   | tac_2tac (Rewrite_Set_Inst' (thy,put,sub,rls,f,(f',asm))) = 
   656       Rewrite_Set_Inst (subst2subs sub,id_rls rls)
   657   | tac_2tac (Detail_Set_Inst' (thy,put,sub,rls,f,(f',asm))) = 
   658       Detail_Set_Inst (subst2subs sub,id_rls rls)
   659 
   660   | tac_2tac (Calculate' (thy,op_,t,(t',thm'))) = Calculate (op_)
   661 
   662   | tac_2tac (Check_elementwise' (consts,pred,consts')) = Check_elementwise pred
   663 
   664   | tac_2tac (Or_to_List' _) = Or_to_List
   665   | tac_2tac (Take' term) = Take (term2str term)
   666   | tac_2tac (Substitute' (subte, t, res)) = Substitute (subte2sube subte) 
   667 
   668   | tac_2tac (Tac_ (_,f,id,f')) = Tac id
   669 
   670   | tac_2tac (Subproblem' ((domID, pblID, _), _, _, _,_ ,_)) = Subproblem (domID, pblID)
   671   | tac_2tac (Check_Postcond' (pblID, _)) = Check_Postcond pblID
   672   | tac_2tac Empty_Tac_ = Empty_Tac
   673   | tac_2tac m = 
   674       error ("tac_2tac: not impl. for "^(tac_2str m));
   675 
   676 
   677 
   678 
   679 (** decompose tac_ to a rule and to (lhs,rhs)
   680     unly needed                          --- **)
   681 
   682 val idT = Type ("Script.ID",[]);
   683 (*val tt = (term_of o the o (parse thy)) "square_equation_left::ID";
   684 type_of tt = idT;
   685 val it = true : bool
   686 *)
   687 
   688 fun make_rule thy t =
   689   let val ct = cterm_of thy (Trueprop $ t)
   690   in Thm (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy))
   691                            (term_of ct), make_thm ct) end;
   692 
   693 (* val (Rewrite_Inst'(thy',rod,rls,put,subs,(thmID,thm),f,(f',asm)))=m;
   694    *)
   695 (*decompose tac_ to a rule and to (lhs,rhs) for ets FIXME.12.03: obsolete!
   696  NOTE.12.03: also used for msg 'not locatable' ?!: 'Subproblem' missing !!!
   697 WN0508 only use in tac_2res, which uses only last return-value*)
   698 fun rep_tac_ (Rewrite_Inst' 
   699 		 (thy',rod,rls,put,subs,(thmID,thm),f,(f',asm))) = 
   700   let val fT = type_of f;
   701     val b = if put then HOLogic.true_const else HOLogic.false_const;
   702     val sT = (type_of o fst o hd) subs;
   703     val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   704       (map HOLogic.mk_prod subs);
   705     val sT' = type_of subs';
   706     val lhs = Const ("Script.Rewrite'_Inst",[sT',idT,(*fT*)bool,fT] ---> fT) 
   707       $ subs' $ Free (thmID,idT) $ b $ f;
   708   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   709 (*Fehlersuche 25.4.01
   710 (a)----- als String zusammensetzen:
   711 ML> term2str f; 
   712 val it = "d_d x #4 + d_d x (x ^^^ #2 + #3 * x)" : string
   713 ML> term2str f'; 
   714 val it = "#0 + d_d x (x ^^^ #2 + #3 * x)" : string
   715 ML> subs;
   716 val it = [(Free ("bdv","RealDef.real"),Free ("x","RealDef.real"))] : subst
   717 > val tt = (term_of o the o (parse thy))
   718   "(Rewrite_Inst[(bdv,x)]diff_const False(d_d x #4 + d_d x (x ^^^ #2 + #3 * x)))=(#0 + d_d x (x ^^^ #2 + #3 * x))";
   719 > atomty tt;
   720 ML> tracing (term2str tt); 
   721 (Rewrite_Inst [(bdv,x)] diff_const False d_d x #4 + d_d x (x ^^^ #2 + #3 * x)) =
   722  #0 + d_d x (x ^^^ #2 + #3 * x)
   723 
   724 (b)----- laut rep_tac_:
   725 > val ttt=HOLogic.mk_eq (lhs,f');
   726 > atomty ttt;
   727 
   728 
   729 (*Fehlersuche 1-2Monate vor 4.01:*)
   730 > val tt = (term_of o the o (parse thy))
   731   "Rewrite_Inst[(bdv,x)]square_equation_left True(x=#1+#2)";
   732 > atomty tt;
   733 
   734 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   735 > val f' = (term_of o the o (parse thy)) "x=#3";
   736 > val subs = [((term_of o the o (parse thy)) "bdv",
   737 	       (term_of o the o (parse thy)) "x")];
   738 > val sT = (type_of o fst o hd) subs;
   739 > val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   740 			      (map HOLogic.mk_prod subs);
   741 > val sT' = type_of subs';
   742 > val lhs = Const ("Script.Rewrite'_Inst",[sT',idT,fT,fT] ---> fT) 
   743   $ subs' $ Free (thmID,idT) $ HOLogic.true_const $ f;
   744 > lhs = tt;
   745 val it = true : bool
   746 > rep_tac_ (Rewrite_Inst' 
   747 	       ("Script","tless_true","eval_rls",false,subs,
   748 		("square_equation_left",""),f,(f',[])));
   749 *)
   750   | rep_tac_ (Rewrite' (thy',rod,rls,put,(thmID,thm),f,(f',asm)))=
   751   let 
   752     val fT = type_of f;
   753     val b = if put then HOLogic.true_const else HOLogic.false_const;
   754     val lhs = Const ("Script.Rewrite",[idT,HOLogic.boolT,fT] ---> fT)
   755       $ Free (thmID,idT) $ b $ f;
   756   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   757 (* 
   758 > val tt = (term_of o the o (parse thy)) (*____   ____..test*)
   759   "Rewrite square_equation_left True (x=#1+#2) = (x=#3)";
   760 
   761 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   762 > val f' = (term_of o the o (parse thy)) "x=#3";
   763 > val Thm (id,thm) = 
   764   rep_tac_ (Rewrite' 
   765    ("Script","tless_true","eval_rls",false,
   766     ("square_equation_left",""),f,(f',[])));
   767 > val SOME ct = parse thy   
   768   "Rewrite square_equation_left True (x=#1+#2)"; 
   769 > rewrite_ Script.thy tless_true eval_rls true thm ct;
   770 val it = SOME ("x = #3",[]) : (cterm * cterm list) option
   771 *)
   772   | rep_tac_ (Rewrite_Set_Inst' 
   773 		 (thy',put,subs,rls,f,(f',asm))) =
   774     (e_rule, (e_term, f'))
   775 (*WN050824: type error ...
   776   let val fT = type_of f;
   777     val sT = (type_of o fst o hd) subs;
   778     val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   779       (map HOLogic.mk_prod subs);
   780     val sT' = type_of subs';
   781     val b = if put then HOLogic.true_const else HOLogic.false_const
   782     val lhs = Const ("Script.Rewrite'_Set'_Inst",
   783 		     [sT',idT,fT,fT] ---> fT) 
   784       $ subs' $ Free (id_rls rls,idT) $ b $ f;
   785   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end*)
   786 (* ... vals from Rewrite_Inst' ...
   787 > rep_tac_ (Rewrite_Set_Inst' 
   788 	       ("Script",false,subs,
   789 		"isolate_bdv",f,(f',[])));
   790 *)
   791 (* val (Rewrite_Set' (thy',put,rls,f,(f',asm)))=m;
   792 *)
   793   | rep_tac_ (Rewrite_Set' (thy',put,rls,f,(f',asm)))=
   794   let val fT = type_of f;
   795     val b = if put then HOLogic.true_const else HOLogic.false_const;
   796     val lhs = Const ("Script.Rewrite'_Set",[idT,bool,fT] ---> fT) 
   797       $ Free (id_rls rls,idT) $ b $ f;
   798   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   799 (* 13.3.01:
   800 val thy = assoc_thy thy';
   801 val t = HOLogic.mk_eq (lhs,f');
   802 make_rule thy t;
   803 --------------------------------------------------
   804 val lll = (term_of o the o (parse thy)) 
   805   "Rewrite_Set SqRoot_simplify False (d_d x (x ^^^ #2 + #3 * x) + d_d x #4)";
   806 
   807 --------------------------------------------------
   808 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   809 > val f' = (term_of o the o (parse thy)) "x=#3";
   810 > val Thm (id,thm) = 
   811   rep_tac_ (Rewrite_Set' 
   812    ("Script",false,"SqRoot_simplify",f,(f',[])));
   813 val id = "(Rewrite_Set SqRoot_simplify True x = #1 + #2) = (x = #3)" : string
   814 val thm = "(Rewrite_Set SqRoot_simplify True x = #1 + #2) = (x = #3)" : thm
   815 *)
   816   | rep_tac_ (Calculate' (thy',op_,f,(f',thm')))=
   817   let val fT = type_of f;
   818     val lhs = Const ("Script.Calculate",[idT,fT] ---> fT) 
   819       $ Free (op_,idT) $ f
   820   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   821 (*
   822 > val lhs'=(term_of o the o (parse thy))"Calculate plus (#1+#2)";
   823   ... test-root-equ.sml: calculate ...
   824 > val Appl m'=applicable_in p pt (Calculate "PLUS");
   825 > val (lhs,_)=tac_2etac m';
   826 > lhs'=lhs;
   827 val it = true : bool*)
   828   | rep_tac_ (Check_elementwise' (t,str,(t',asm)))  = (Erule, (e_term, t'))
   829   | rep_tac_ (Subproblem' (_, _, _, _, _, t'))  = (Erule, (e_term, t'))
   830   | rep_tac_ (Take' (t'))  = (Erule, (e_term, t'))
   831   | rep_tac_ (Substitute' (subst,t,t'))  = (Erule, (t, t'))
   832   | rep_tac_ (Or_to_List' (t, t'))  = (Erule, (t, t'))
   833   | rep_tac_ m = error ("rep_tac_: not impl.for "^
   834 				 (tac_2str m));
   835 
   836 (*"N.3.6.03------
   837 fun tac_2rule m = (fst o rep_tac_) m;
   838 fun tac_2etac m = (snd o rep_tac_) m;
   839 fun tac_2tac m = (fst o snd o rep_tac_) m;*)
   840 fun tac_2res m = (snd o snd o rep_tac_) m;(*ONLYuse of rep_tac_
   841 					        FIXXXXME: simplify rep_tac_*)
   842 
   843 
   844 (* handle a leaf at the end of recursive descent:
   845    a leaf is either a tactic or an 'exp' in 'let v = expr'
   846    where 'exp' does not contain a tactic.
   847    handling a leaf comprises
   848    (1) 'subst_stacexpr' substitute env and complete curried tactic
   849    (2) rewrite the leaf by 'srls'
   850 *)
   851 fun handle_leaf call thy srls E a v t =
   852       (*WN050916 'upd_env_opt' is a blind copy from previous version*)
   853        case subst_stacexpr E a v t of
   854 	       (a', STac stac) => (*script-tactic*)
   855 	         let val stac' =
   856              eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) stac)
   857 	         in
   858              (if (!trace_script) 
   859 	            then tracing ("@@@ "^call^" leaf '"^term2str t^"' ---> STac '"^term2str stac'^"'")
   860 	            else ();
   861 	            (a', STac stac'))
   862 	         end
   863        | (a', Expr lexpr) => (*leaf-expression*)
   864 	         let val lexpr' =
   865              eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) lexpr)
   866 	         in
   867              (if (!trace_script) 
   868 	            then tracing("@@@ "^call^" leaf '"^term2str t^"' ---> Expr '"^term2str lexpr'^"'")
   869 	            else ();
   870 	            (a', Expr lexpr'))
   871 	         end;
   872 
   873 
   874 (** locate an applicable stactic in a script **)
   875 
   876 datatype assoc = (*ExprVal in the sense of denotational semantics*)
   877   Assoc of     (*the stac is associated, strongly or weakly*)
   878   scrstate *       (*the current; returned for next_tac etc. outside ass* *)  
   879   (step list)    (*list of steps done until associated stac found;
   880 	           initiated with the data for doing the 1st step,
   881                    thus the head holds these data further on,
   882 		   while the tail holds steps finished (incl.scrstate in ptree)*)
   883 | NasApp of   (*stac not associated, but applicable, ptree-node generated*)
   884   scrstate * (step list)
   885 | NasNap of     (*stac not associated, not applicable, nothing generated;
   886 	         for distinction in Or, for leaving iterations, leaving Seq,
   887 		 evaluate scriptexpressions*)
   888   term * env;
   889 fun assoc2str (Assoc     _) = "Assoc"
   890   | assoc2str (NasNap  _) = "NasNap"
   891   | assoc2str (NasApp _) = "NasApp";
   892 
   893 
   894 datatype asap = (*arg. of assy _only_ for distinction w.r.t. Or*)
   895   Aundef   (*undefined: set only by (topmost) Or*)
   896 | AssOnly  (*do not execute appl stacs - there could be an associated
   897 	     in parallel Or-branch*)
   898 | AssGen;  (*no Ass(Weak) found within Or, thus 
   899              search for _applicable_ stacs, execute and generate pt*)
   900 (*this constructions doesnt allow arbitrary nesting of Or !!!*)
   901 
   902 
   903 (*assy, ass_up, astep_up scan for locate_gen in a script.
   904   search is clearly separated into (1)-(2):
   905   (1) assy is recursive descent;
   906   (2) ass_up resumes interpretation at a location somewhere in the script;
   907       astep_up does only get to the parentnode of the scriptexpr.
   908   consequence:
   909   * call of (2) means _always_ that in this branch below
   910     there was an appl.stac (Repeat, Or e1, ...) found by the previous step.
   911 *)
   912 fun assy ya (is as (E,l,a,v,S,b),ss) (Const ("HOL.Let",_) $ e $ (Abs (id,T,body))) =
   913       (case assy ya ((E , l@[L,R], a,v,S,b),ss) e of
   914 	       NasApp ((E',l,a,v,S,bb),ss) => 
   915 	         let
   916              val id' = mk_Free (id, T);
   917 	           val E' = upd_env E' (id', v);
   918 	         in assy ya ((E', l@[R,D], a,v,S,b),ss) body end
   919        | NasNap (v,E) => 	 
   920 	         let
   921              val id' = mk_Free (id, T);
   922 	           val E' = upd_env E (id', v);
   923 	         in assy ya ((E', l@[R,D], a,v,S,b),ss) body end
   924        | ay => ay)
   925 
   926   | assy (ya as (((thy,srls),_),_)) ((E,l,_,v,S,b),ss) (Const ("Script.While",_) $ c $ e $ a) =
   927       (if eval_true_ thy srls (subst_atomic (upd_env E (a,v)) c) 
   928        then assy ya ((E, l@[L,R], SOME a,v,S,b),ss)  e
   929        else NasNap (v, E))   
   930   | assy (ya as (((thy,srls),_),_)) ((E,l,a,v,S,b),ss) (Const ("Script.While",_) $ c $ e) =
   931       (if eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   932        then assy ya ((E, l@[R], a,v,S,b),ss) e
   933        else NasNap (v, E)) 
   934 
   935   | assy (ya as (((thy,srls),_),_)) ((E,l,a,v,S,b),ss) (Const ("If",_) $ c $ e1 $ e2) =
   936       (if eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   937        then assy ya ((E, l@[L,R], a,v,S,b),ss) e1
   938        else assy ya ((E, l@[  R], a,v,S,b),ss) e2) 
   939 
   940   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Try",_) $ e $ a) =
   941       (case assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e of
   942          ay => ay) 
   943   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Try",_) $ e) =
   944       (case assy ya ((E, l@[R], a,v,S,b),ss) e of
   945          ay => ay)
   946 
   947   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2 $ a) =
   948       (case assy ya ((E, l@[L,L,R], SOME a,v,S,b),ss) e1 of
   949 	       NasNap (v, E) => assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e2
   950        | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e2
   951        | ay => ay)
   952   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2) =
   953       (case assy ya ((E, l@[L,R], a,v,S,b),ss) e1 of
   954 	       NasNap (v, E) => assy ya ((E, l@[R], a,v,S,b),ss) e2
   955        | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l@[R], a,v,S,b),ss) e2
   956        | ay => ay)
   957     
   958   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Repeat",_) $ e $ a) =
   959       assy ya ((E,(l@[L,R]),SOME a,v,S,b),ss) e
   960   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Repeat",_) $ e) =
   961       assy ya ((E,(l@[R]),a,v,S,b),ss) e
   962 
   963   | assy (y, Aundef) ((E,l,_,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2 $ a) =
   964       (case assy (y, AssOnly) ((E,(l@[L,L,R]),SOME a,v,S,b),ss) e1 of
   965 	       NasNap (v, E) => 
   966 	         (case assy (y, AssOnly) ((E,(l@[L,R]),SOME a,v,S,b),ss) e2 of
   967 	            NasNap (v, E) => 
   968 	              (case assy (y, AssGen) ((E,(l@[L,L,R]),SOME a,v,S,b),ss) e1 of
   969 	                 NasNap (v, E) => 
   970 	                   assy (y, AssGen) ((E, (l@[L,R]), SOME a,v,S,b),ss) e2
   971 	               | ay => ay)
   972 	          | ay =>(ay))
   973        | NasApp _ => error ("assy: FIXXXME ///must not return NasApp///")
   974        | ay => (ay))
   975   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2) =
   976       (case assy ya ((E,(l@[L,R]),a,v,S,b),ss) e1 of
   977 	       NasNap (v, E) => assy ya ((E,(l@[R]),a,v,S,b),ss) e2
   978        | ay => (ay)) 
   979 
   980   | assy (((thy',sr),d),ap) (is as (E,l,a,v,S,b), (m,_,pt,(p,p_),c)::ss) t =
   981       (case handle_leaf "locate" thy' sr E a v t of
   982 	       (a', Expr s) => 
   983 	          (NasNap (eval_listexpr_ (assoc_thy thy') sr
   984 			         (subst_atomic (upd_env_opt E (a',v)) t), E))
   985        | (a', STac stac) =>
   986 	         let
   987              val ctxt = get_ctxt pt (p,p_)
   988              val p' = 
   989                case p_ of Frm => p 
   990                | Res => lev_on p
   991 			         | _ => error ("assy: call by " ^ pos'2str (p,p_));
   992 	         in
   993              case assod pt d m stac of
   994 	             Ass (m,v') =>
   995 	               let val (p'',c',f',pt') =
   996                    generate1 (assoc_thy thy') m (ScrState (E,l,a',v',S,true), ctxt) (p',p_) pt;
   997 	               in Assoc ((E,l,a',v',S,true), (m,f',pt',p'',c @ c')::ss) end
   998              | AssWeak (m,v') => 
   999 	               let val (p'',c',f',pt') =
  1000                    generate1 (assoc_thy thy') m (ScrState (E,l,a',v',S,false), ctxt) (p',p_) pt;
  1001 	               in Assoc ((E,l,a',v',S,false), (m,f',pt',p'',c @ c')::ss) end
  1002              | NotAss =>
  1003                  (case ap of   (*switch for Or: 1st AssOnly, 2nd AssGen*)
  1004                     AssOnly => (NasNap (v, E))
  1005                   | gen =>
  1006                       (case applicable_in (p,p_) pt (stac2tac pt (assoc_thy thy') stac) of
  1007 			                   Appl m' =>
  1008 			                     let
  1009                              val is = (E,l,a',tac_2res m',S,false(*FIXXXME.WN0?*))
  1010 			                       val (p'',c',f',pt') =
  1011 			                         generate1 (assoc_thy thy') m' (ScrState is, ctxt) (p',p_) pt;
  1012 			                     in NasApp (is,(m,f',pt',p'',c @ c')::ss) end
  1013 		                   | Notappl _ => (NasNap (v, E))
  1014 			                )
  1015 		             )
  1016            end);
  1017 
  1018 fun ass_up (ys as (y,s,Script sc,d)) (is as (E,l,a,v,S,b),ss) 
  1019 	   (Const ("HOL.Let",_) $ _) =
  1020     let (*val _= tracing("### ass_up1 Let$e: is=")
  1021 	val _= tracing(istate2str (ScrState is))*)
  1022 	val l = drop_last l; (*comes from e, goes to Abs*)
  1023       val (Const ("HOL.Let",_) $ e $ (Abs (i,T,body))) = go l sc;
  1024       val i = mk_Free (i, T);
  1025       val E = upd_env E (i, v);
  1026       (*val _=tracing("### ass_up2 Let$e: E="^(subst2str E));*)
  1027     in case assy (((y,s),d),Aundef) ((E, l@[R,D], a,v,S,b),ss) body of
  1028 	   Assoc iss => Assoc iss
  1029 	 | NasApp iss => astep_up ys iss 
  1030 	 | NasNap (v, E) => astep_up ys ((E,l,a,v,S,b),ss) end
  1031 
  1032   | ass_up ys (iss as (is,_)) (Abs (_,_,_)) = 
  1033     ((*tracing("### ass_up  Abs: is=");
  1034      tracing(istate2str (ScrState is));*)
  1035      astep_up ys iss) (*TODO 5.9.00: env ?*)
  1036 
  1037   | ass_up ys (iss as (is,_)) (Const ("HOL.Let",_) $ e $ (Abs (i,T,b)))=
  1038     ((*tracing("### ass_up Let $ e $ Abs: is=");
  1039      tracing(istate2str (ScrState is));*)
  1040      astep_up ys iss) (*TODO 5.9.00: env ?*)
  1041 
  1042     (* val (ysa, iss,                 (Const ("Script.Seq",_) $ _ $ _ $ _)) =
  1043 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1044        *)
  1045   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _ $ _) =
  1046     astep_up ysa iss (*all has been done in (*2*) below*)
  1047 
  1048   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _) =
  1049     (* val (ysa, iss,                 (Const ("Script.Seq",_) $ _ $ _)) =
  1050 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1051        *)
  1052     astep_up ysa iss (*2*: comes from e2*)
  1053 
  1054   | ass_up (ysa as (y,s,Script sc,d)) (is as (E,l,a,v,S,b),ss)
  1055 	   (Const ("Script.Seq",_) $ _ ) = (*2*: comes from e1, goes to e2*)
  1056 	   (* val ((ysa as (y,s,Script sc,d)), (is as (E,l,a,v,S,b),ss),
  1057 	                                  (Const ("Script.Seq",_) $ _ )) = 
  1058 		  (ys,   ((E,up,a,v,S,b),ss), (go up sc));
  1059 	      *)
  1060     let val up = drop_last l;
  1061 	val Const ("Script.Seq",_) $ _ $ e2 = go up sc
  1062 	(*val _= tracing("### ass_up Seq$e: is=")
  1063 	val _= tracing(istate2str (ScrState is))*)
  1064     in case assy (((y,s),d),Aundef) ((E, up@[R], a,v,S,b),ss) e2 of
  1065 	   NasNap (v,E) => astep_up ysa ((E,up,a,v,S,b),ss)
  1066 	 | NasApp iss => astep_up ysa iss
  1067 	 | ay => ay end
  1068 
  1069     (* val (ysa, iss,                 (Const ("Script.Try",_) $ e $ _)) =
  1070 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1071        *)
  1072   | ass_up ysa iss (Const ("Script.Try",_) $ e $ _) =
  1073     astep_up ysa iss
  1074 
  1075   (* val (ysa, iss, (Const ("Script.Try",_) $ e)) =
  1076 	 (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1077      *)
  1078   | ass_up ysa iss (Const ("Script.Try",_) $ e) =
  1079     ((*tracing("### ass_up Try $ e");*)
  1080      astep_up ysa iss)
  1081 
  1082   | ass_up (ys as (y,s,_,d)) ((E,l,_,v,S,b),ss)
  1083 	   (*(Const ("Script.While",_) $ c $ e $ a) = WN050930 blind fix*)
  1084 	   (t as Const ("Script.While",_) $ c $ e $ a) =
  1085     ((*tracing("### ass_up: While c= "^
  1086 	     (term2str (subst_atomic (upd_env E (a,v)) c)));*)
  1087      if eval_true_ y s (subst_atomic (upd_env E (a,v)) c)
  1088     then (case assy (((y,s),d),Aundef) ((E, l@[L,R], SOME a,v,S,b),ss) e of 
  1089        NasNap (v,E') => astep_up ys ((E',l, SOME a,v,S,b),ss)
  1090      | NasApp ((E',l,a,v,S,b),ss) =>
  1091        ass_up ys ((E',l,a,v,S,b),ss) t (*WN050930 't' was not assigned*)
  1092      | ay => ay)
  1093     else astep_up ys ((E,l, SOME a,v,S,b),ss)
  1094 	 )
  1095 
  1096   | ass_up (ys as (y,s,_,d)) ((E,l,a,v,S,b),ss)
  1097 	   (*(Const ("Script.While",_) $ c $ e) = WN050930 blind fix*)
  1098 	   (t as Const ("Script.While",_) $ c $ e) =
  1099     if eval_true_ y s (subst_atomic (upd_env_opt E (a,v)) c)
  1100     then (case assy (((y,s),d),Aundef) ((E, l@[R], a,v,S,b),ss) e of 
  1101        NasNap (v,E') => astep_up ys ((E',l, a,v,S,b),ss)
  1102      | NasApp ((E',l,a,v,S,b),ss) =>
  1103        ass_up ys ((E',l,a,v,S,b),ss) t (*WN050930 't' was not assigned*)
  1104      | ay => ay)
  1105     else astep_up ys ((E,l, a,v,S,b),ss)
  1106 
  1107   | ass_up y iss (Const ("If",_) $ _ $ _ $ _) = astep_up y iss
  1108 
  1109   | ass_up (ys as (y,s,_,d)) ((E,l,_,v,S,b),ss)
  1110 	   (t as Const ("Script.Repeat",_) $ e $ a) =
  1111   (case assy (((y,s),d), Aundef) ((E, (l@[L,R]), SOME a,v,S,b),ss) e of 
  1112        NasNap (v,E') => astep_up ys ((E',l, SOME a,v,S,b),ss)
  1113      | NasApp ((E',l,a,v,S,b),ss) =>
  1114        ass_up ys ((E',l,a,v,S,b),ss) t
  1115      | ay => ay)
  1116 
  1117   | ass_up (ys as (y,s,_,d)) (is as ((E,l,a,v,S,b),ss)) 
  1118 	   (t as Const ("Script.Repeat",_) $ e) =
  1119   (case assy (((y,s),d), Aundef) ((E, (l@[R]), a,v,S,b),ss) e of 
  1120        NasNap (v', E') => astep_up ys ((E',l,a,v',S,b),ss)
  1121      | NasApp ((E',l,a,v',S,bb),ss) => 
  1122        ass_up ys ((E',l,a,v',S,b),ss) t
  1123      | ay => ay)
  1124 
  1125   | ass_up y iss (Const ("Script.Or",_) $ _ $ _ $ _) = astep_up y iss
  1126 
  1127   | ass_up y iss (Const ("Script.Or",_) $ _ $ _) = astep_up y iss
  1128 
  1129   | ass_up y ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $ _ ) = 
  1130     astep_up y ((E, (drop_last l), a,v,S,b),ss)
  1131 
  1132   | ass_up y iss t =
  1133     error ("ass_up not impl for t= "^(term2str t))
  1134 (* 9.6.03
  1135    val (ys as (_,_,Script sc,_), ss) = 
  1136        ((thy',srls,scr,d), [(m,EmptyMout,pt,p,[])]:step list);
  1137    astep_up ys ((E,l,a,v,S,b),ss);
  1138    val ((ys as (_,_,Script sc,_)), ((E,l,a,v,S,b),ss)) = 
  1139        (ysa, iss);
  1140    val ((ys as (_,_,Script sc,_)), ((E,l,a,v,S,b),ss)) = 
  1141        ((thy',srls,scr,d), ((E,l,a,v,S,b), [(m,EmptyMout,pt,p,[])]));
  1142    *)  
  1143 and astep_up (ys as (_,_,Script sc,_)) ((E,l,a,v,S,b),ss) =
  1144   if 1 < length l
  1145     then 
  1146       let val up = drop_last l;
  1147 	  (*val _= tracing("### astep_up: E= "^env2str E);*)
  1148       in ass_up ys ((E,up,a,v,S,b),ss) (go up sc) end
  1149   else (NasNap (v, E))
  1150 ;
  1151 
  1152 
  1153 
  1154 
  1155 
  1156 (* use"ME/script.sml";
  1157    use"script.sml";
  1158  term2str (go up sc);
  1159 
  1160    *)
  1161 
  1162 (*check if there are tacs for rewriting only*)
  1163 fun rew_only ([]:step list) = true
  1164   | rew_only (((Rewrite' _          ,_,_,_,_))::ss) = rew_only ss
  1165   | rew_only (((Rewrite_Inst' _     ,_,_,_,_))::ss) = rew_only ss
  1166   | rew_only (((Rewrite_Set' _      ,_,_,_,_))::ss) = rew_only ss
  1167   | rew_only (((Rewrite_Set_Inst' _ ,_,_,_,_))::ss) = rew_only ss
  1168   | rew_only (((Calculate' _        ,_,_,_,_))::ss) = rew_only ss
  1169   | rew_only (((Begin_Trans' _      ,_,_,_,_))::ss) = rew_only ss
  1170   | rew_only (((End_Trans' _        ,_,_,_,_))::ss) = rew_only ss
  1171   | rew_only _ = false; 
  1172   
  1173 
  1174 datatype locate =
  1175   Steps of istate      (*producing hd of step list (which was latest)
  1176 	                 for next_tac, for reporting Safe|Unsafe to DG*)
  1177 	   * step      (*(scrstate producing this step is in ptree !)*) 
  1178 		 list  (*locate_gen may produce intermediate steps*)
  1179 | NotLocatable;        (*no (m Ass m') or (m AssWeak m') found*)
  1180 
  1181 
  1182 
  1183 (* locate_gen tries to locate an input tac m in the script. 
  1184    pursuing this goal the script is executed until an (m' equiv m) is found,
  1185    or the end of the script
  1186 args
  1187    m   : input by the user, already checked by applicable_in,
  1188          (to be searched within Or; and _not_ an m doing the step on ptree !)
  1189    p,pt: (incl ets) at the time of input
  1190    scr : the script
  1191    d   : canonical simplifier for locating Take, Substitute, Subproblems etc.
  1192    ets : ets at the time of input
  1193    l   : the location (in scr) of the stac which generated the current formula
  1194 returns
  1195    Steps: pt,p (incl. ets) with m done
  1196           pos' list of proofobjs cut (from generate)
  1197           safe: implied from last proofobj
  1198 	  ets:
  1199    ///ToDo : ets contains a list of tacs to be done before m can be done
  1200           NOT IMPL. -- "error: do other step before"
  1201    NotLocatable: thus generate_hard
  1202 *)
  1203 fun locate_gen (thy',_) (Rewrite'(_,ro,er,pa,(id,str),f,_)) (pt,p) 
  1204 	  (Rfuns {locate_rule=lo,...}, d) (RrlsState (_,f'',rss,rts), ctxt) = 
  1205       (case lo rss f (Thm (id, mk_thm (assoc_thy thy') str)) of
  1206 	       [] => NotLocatable
  1207        | rts' => 
  1208 	         Steps (rts2steps [] ((pt,p),(f,f'',rss,rts),(thy',ro,er,pa)) rts'))
  1209 
  1210   | locate_gen (ts as (thy',srls)) (m:tac_) ((pt,p):ptree * pos') 
  1211 	  (scr as Script (h $ body),d) (ScrState (E,l,a,v,S,b), ctxt)  = 
  1212       let val thy = assoc_thy thy';
  1213       in
  1214         case if l = [] orelse ((*init.in solve..Apply_Method...*)
  1215 			         (last_elem o fst) p = 0 andalso snd p = Res)
  1216 	           then (assy ((ts,d),Aundef) ((E,[R],a,v,S,b), [(m,EmptyMout,pt,p,[])]) body)
  1217 	           else (astep_up (thy',srls,scr,d) ((E,l,a,v,S,b), [(m,EmptyMout,pt,p,[])]) ) of
  1218 	        Assoc (iss as (is as (_,_,_,_,_,bb), ss as ((m',f',pt',p',c')::_))) =>
  1219 	          (if bb
  1220              then Steps (ScrState is, ss)
  1221 	           else
  1222                if rew_only ss (*andalso 'not bb'= associated weakly*)
  1223 	             then
  1224                  let
  1225                    val (po,p_) = p
  1226                    val po' = case p_ of Frm => po | Res => lev_on po
  1227                    val (p'',c'',f'',pt'') = 
  1228 		                 generate1 thy m (ScrState is, ctxt) (po',p_) pt;
  1229 	               in Steps (ScrState is, [(m, f'',pt'',p'',c'')]) end
  1230 	             else Steps (ScrState is, ss))
  1231 	
  1232         | NasApp _ => NotLocatable
  1233       end
  1234 
  1235   | locate_gen _ m _ (sc,_) (is, _) = 
  1236       error ("locate_gen: wrong arguments,\n tac= " ^ tac_2str m ^ ",\n " ^
  1237 		    "scr= " ^ scr2str sc ^ ",\n istate= " ^ istate2str is);
  1238 
  1239 (** find the next stactic in a script **)
  1240 
  1241 datatype appy =  (*ExprVal in the sense of denotational semantics*)
  1242     Appy of      (*applicable stac found, search stalled*)
  1243     tac_ *       (*tac_ associated (fun assod) with stac*)
  1244     scrstate     (*after determination of stac WN.18.8.03*)
  1245   | Napp of      (*stac found was not applicable; 
  1246 	           this mode may become Skip in Repeat, Try and Or*)
  1247     env (*stack*)  (*popped while nxt_up*)
  1248   | Skip of      (*for restart after Appy, for leaving iterations,
  1249 	           for passing the value of scriptexpressions,
  1250 		   and for finishing the script successfully*)
  1251     term * env (*stack*);
  1252 
  1253 (*appy, nxt_up, nstep_up scanning for next_tac.
  1254   search is clearly separated into (1)-(2):
  1255   (1) appy is recursive descent;
  1256   (2) nxt_up resumes interpretation at a location somewhere in the script;
  1257       nstep_up does only get to the parentnode of the scriptexpr.
  1258   consequence:
  1259   * call of (2) means _always_ that in this branch below
  1260     there was an applicable stac (Repeat, Or e1, ...)
  1261 *)
  1262 
  1263 
  1264 datatype appy_ = (*as argument in nxt_up, nstep_up, from appy*)
  1265   (* Appy          is only (final) returnvalue, not argument during search *)
  1266      Napp_       (*ev. detects 'script is not appropriate for this example'*)
  1267    | Skip_;      (*detects 'script successfully finished'
  1268 		               also used as init-value for resuming; this works,
  1269 	                 because 'nxt_up Or e1' treats as Appy*)
  1270 
  1271 fun appy thy ptp E l (t as Const ("HOL.Let",_) $ e $ (Abs (i,T,b))) a v =
  1272       (case appy thy ptp E (l@[L,R]) e a v of
  1273          Skip (res, E) => 
  1274            let val E' = upd_env E (Free (i,T), res);
  1275            in appy thy ptp E' (l@[R,D]) b a v end
  1276        | ay => ay)
  1277 
  1278   | appy (thy as (th,sr)) ptp E l (t as Const ("Script.While"(*1*),_) $ c $ e $ a) _ v =
  1279       (if eval_true_ th sr (subst_atomic (upd_env E (a,v)) c)
  1280        then appy thy ptp E (l@[L,R]) e (SOME a) v
  1281        else Skip (v, E))
  1282 
  1283   | appy (thy as (th,sr)) ptp E l (t as Const ("Script.While"(*2*),_) $ c $ e) a v =
  1284       (if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
  1285        then appy thy ptp E (l@[R]) e a v
  1286        else Skip (v, E))
  1287 
  1288   | appy (thy as (th,sr)) ptp E l (t as Const ("If",_) $ c $ e1 $ e2) a v =
  1289       (if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
  1290        then ((*tracing("### appy If: true");*)appy thy ptp E (l@[L,R]) e1 a v)
  1291        else ((*tracing("### appy If: false");*)appy thy ptp E (l@[  R]) e2 a v))
  1292 
  1293   | appy thy ptp E l (Const ("Script.Repeat"(*1*),_) $ e $ a) _ v = 
  1294       (appy thy ptp E (l@[L,R]) e (SOME a) v)
  1295 
  1296   | appy thy ptp E l (Const ("Script.Repeat"(*2*),_) $ e) a v = 
  1297       (appy thy ptp E (l@[R]) e a v)
  1298 
  1299   | appy thy ptp E l (t as Const ("Script.Try",_) $ e $ a) _ v =
  1300      (case appy thy ptp E (l@[L,R]) e (SOME a) v of
  1301         Napp E => (Skip (v, E))
  1302       | ay => ay)
  1303 
  1304   | appy thy ptp E l(t as Const ("Script.Try",_) $ e) a v =
  1305      (case appy thy ptp E (l@[R]) e a v of
  1306         Napp E => (Skip (v, E))
  1307       | ay => ay)
  1308 
  1309   | appy thy ptp E l (Const ("Script.Or"(*1*),_) $e1 $ e2 $ a) _ v =
  1310      (case appy thy ptp E (l@[L,L,R]) e1 (SOME a) v of
  1311 	      Appy lme => Appy lme
  1312       | _ => appy thy ptp E (*env*) (l@[L,R]) e2 (SOME a) v)
  1313     
  1314   | appy thy ptp E l (Const ("Script.Or"(*2*),_) $e1 $ e2) a v =
  1315       (case appy thy ptp E (l@[L,R]) e1 a v of
  1316 	       Appy lme => Appy lme
  1317        | _ => appy thy ptp E (l@[R]) e2 a v)
  1318 
  1319   | appy thy ptp E l (Const ("Script.Seq"(*1*),_) $ e1 $ e2 $ a) _ v =
  1320       (case appy thy ptp E (l@[L,L,R]) e1 (SOME a) v of
  1321 	       Skip (v,E) => appy thy ptp E (l@[L,R]) e2 (SOME a) v
  1322        | ay => ay)
  1323 
  1324   | appy thy ptp E l (Const ("Script.Seq",_) $ e1 $ e2) a v =
  1325       (case appy thy ptp E (l@[L,R]) e1 a v of
  1326 	       Skip (v,E) => appy thy ptp E (l@[R]) e2 a v
  1327        | ay => ay)
  1328 
  1329   (* a leaf has been found *)   
  1330   | appy (thy as (th,sr)) (pt, p) E l t a v =
  1331       (case handle_leaf "next  " th sr E a v t of
  1332 	       (a', Expr s) => Skip (s, E)
  1333        | (a', STac stac) =>
  1334 	         let val (m,m') = stac2tac_ pt (assoc_thy th) stac
  1335            in
  1336              case m of 
  1337 	             Subproblem _ => Appy (m', (E,l,a',tac_2res m',Sundef,false))
  1338 	           | _ =>
  1339                (case applicable_in p pt m of
  1340 			            Appl m' => (Appy (m', (E,l,a',tac_2res m',Sundef,false)))
  1341 		         | _ => ((*tracing("### appy: Napp");*)Napp E)) 
  1342 	         end);
  1343 	 
  1344 fun nxt_up thy ptp (scr as (Script sc)) E l ay
  1345     (t as Const ("HOL.Let",_) $ _) a v = (*comes from let=...*)
  1346        (if ay = Napp_
  1347         then nstep_up thy ptp scr E (drop_last l) Napp_ a v
  1348         else (*Skip_*)
  1349 	        let
  1350             val up = drop_last l;
  1351 	          val (Const ("HOL.Let",_) $ e $ (Abs (i,T,body))) = go up sc;
  1352             val i = mk_Free (i, T);
  1353             val E = upd_env E (i, v);
  1354           in
  1355             case appy thy ptp E (up@[R,D]) body a v  of
  1356 	            Appy lre => Appy lre
  1357 	          | Napp E => nstep_up thy ptp scr E up Napp_ a v
  1358 	          | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v end)
  1359 	    
  1360   | nxt_up thy ptp scr E l ay
  1361     (t as Abs (_,_,_)) a v = 
  1362     ((*tracing("### nxt_up Abs: " ^ term2str t);*)
  1363      nstep_up thy ptp scr E (*enr*) l ay a v)
  1364 
  1365   | nxt_up thy ptp scr E l ay
  1366     (t as Const ("HOL.Let",_) $ e $ (Abs (i,T,b))) a v =
  1367     ((*tracing("### nxt_up Let$e$Abs: is=");
  1368      tracing(istate2str (ScrState (E,l,a,v,Sundef,false)));*)
  1369      (*tracing("### nxt_up Let e Abs: " ^ term2str t);*)
  1370      nstep_up thy ptp scr (*upd_env*) E (*a,v)*) 
  1371 	      (*eno,upd_env env (iar,res),iar,res,saf*) l ay a v)
  1372 
  1373   (*no appy_: never causes Napp -> Helpless*)
  1374   | nxt_up (thy as (th,sr)) ptp scr E l _ 
  1375   (Const ("Script.While"(*1*),_) $ c $ e $ _) a v = 
  1376   if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c) 
  1377     then case appy thy ptp E (l@[L,R]) e a v of
  1378 	     Appy lr => Appy lr
  1379 	   | Napp E => nstep_up thy ptp scr E l Skip_ a v
  1380 	   | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
  1381   else nstep_up thy ptp scr E l Skip_ a v
  1382 
  1383   (*no appy_: never causes Napp - Helpless*)
  1384   | nxt_up (thy as (th,sr)) ptp scr E l _ 
  1385   (Const ("Script.While"(*2*),_) $ c $ e) a v = 
  1386   if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c) 
  1387     then case appy thy ptp E (l@[R]) e a v of
  1388 	     Appy lr => Appy lr
  1389 	   | Napp E => nstep_up thy ptp scr E l Skip_ a v
  1390 	   | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
  1391   else nstep_up thy ptp scr E l Skip_ a v
  1392 
  1393 (* val (scr, l) = (Script sc, up);
  1394    *)
  1395   | nxt_up thy ptp scr E l ay (Const ("If",_) $ _ $ _ $ _) a v = 
  1396     nstep_up thy ptp scr E l ay a v
  1397 
  1398   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
  1399   (Const ("Script.Repeat"(*1*),T) $ e $ _) a v =
  1400     (case appy thy ptp (*upd_env*) E (*a,v)*) ((l@[L,R]):loc_) e a v  of
  1401       Appy lr => Appy lr
  1402     | Napp E => ((*tracing("### nxt_up Repeat a: ");*)
  1403 		 nstep_up thy ptp scr E l Skip_ a v)
  1404     | Skip (v,E) => ((*tracing("### nxt_up Repeat: Skip res ="^
  1405 		(Sign.string_of_term(sign_of (assoc_thy thy)) res'));*)
  1406 		    nstep_up thy ptp scr E l Skip_ a v))
  1407 
  1408   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
  1409   (Const ("Script.Repeat"(*2*),T) $ e) a v =
  1410     (case appy thy ptp (*upd_env*) E (*a,v)*) ((l@[R]):loc_) e a v  of
  1411       Appy lr => Appy lr
  1412     | Napp E => ((*tracing("### nxt_up Repeat a: ");*)
  1413 		 nstep_up thy ptp scr E l Skip_ a v)
  1414     | Skip (v,E) => ((*tracing("### nxt_up Repeat: Skip res ="^
  1415 		(Sign.string_of_term(sign_of (assoc_thy thy)) res'));*)
  1416 		    nstep_up thy ptp scr E l Skip_ a v))
  1417 (* val (thy, ptp, scr, E, l,   _,(t as Const ("Script.Try",_) $ e $ _), a, v) =
  1418        (thy, ptp, (Script sc), 
  1419 	               E, up, ay,(go up sc),                            a, v);
  1420    *)
  1421   | nxt_up thy ptp scr E l _ (*makes Napp to Skip*)
  1422   (t as Const ("Script.Try",_) $ e $ _) a v = 
  1423     ((*tracing("### nxt_up Try " ^ term2str t);*)
  1424      nstep_up thy ptp scr E l Skip_ a v )
  1425 (* val (thy, ptp, scr, E, l,   _,(t as Const ("Script.Try",_) $ e), a, v) =
  1426        (thy, ptp, (Script sc), 
  1427 	               E, up, ay,(go up sc),                        a, v);
  1428    *)
  1429   | nxt_up thy ptp scr E l _ (*makes Napp to Skip*)
  1430   (t as Const ("Script.Try"(*2*),_) $ e) a v = 
  1431     ((*tracing("### nxt_up Try " ^ term2str t);*)
  1432      nstep_up thy ptp scr E l Skip_ a v)
  1433 
  1434 
  1435   | nxt_up thy ptp scr E l ay
  1436   (Const ("Script.Or",_) $ _ $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
  1437 
  1438   | nxt_up thy ptp scr E l ay
  1439   (Const ("Script.Or",_) $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
  1440 
  1441   | nxt_up thy ptp scr E l ay
  1442   (Const ("Script.Or",_) $ _ ) a v = 
  1443     nstep_up thy ptp scr E (drop_last l) ay a v
  1444 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _ $ _ $ _), a, v) =
  1445        (thy, ptp, (Script sc), 
  1446 		       E, up, ay,(go up sc),                           a, v);
  1447    *)
  1448   | nxt_up thy ptp scr E l ay (*all has been done in (*2*) below*)
  1449   (Const ("Script.Seq"(*1*),_) $ _ $ _ $ _) a v =
  1450     nstep_up thy ptp scr E l ay a v
  1451 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _ $ e2), a, v) =
  1452        (thy, ptp, (Script sc), 
  1453 		       E, up, ay,(go up sc),                        a, v);
  1454    *)
  1455   | nxt_up thy ptp scr E l ay (*comes from e2*)
  1456 	   (Const ("Script.Seq"(*2*),_) $ _ $ e2) a v =
  1457     nstep_up thy ptp scr E l ay a v
  1458 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _), a, v) =
  1459        (thy, ptp, (Script sc), 
  1460 		       E, up, ay,(go up sc),                   a, v);
  1461    *)
  1462   | nxt_up thy ptp (scr as Script sc) E l ay (*comes from e1*)
  1463 	   (Const ("Script.Seq",_) $ _) a v = 
  1464     if ay = Napp_
  1465     then nstep_up thy ptp scr E (drop_last l) Napp_ a v
  1466     else (*Skip_*)
  1467 	let val up = drop_last l;
  1468 	    val Const ("Script.Seq"(*2*),_) $ _ $ e2 = go up sc;
  1469 	in case appy thy ptp E (up@[R]) e2 a v  of
  1470 	    Appy lr => Appy lr
  1471 	  | Napp E => nstep_up thy ptp scr E up Napp_ a v
  1472 	  | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v end
  1473 
  1474   | nxt_up (thy,_) ptp scr E l ay t a v =
  1475     error ("nxt_up not impl for " ^ term2str t)
  1476 
  1477 (* val (thy, ptp, (Script sc), E, l, ay,    a, v)=
  1478        (thy, ptp, scr,         E, l, Skip_, a, v);
  1479    val (thy, ptp, (Script sc), E, l, ay,    a, v)=
  1480        (thy, ptp, sc,          E, l, Skip_, a, v);
  1481    *)
  1482 and nstep_up thy ptp (Script sc) E l ay a v = 
  1483   (if 1 < length l
  1484    then 
  1485      let val up = drop_last l; 
  1486      in (nxt_up thy ptp (Script sc) E up ay (go up sc) a v ) end
  1487    else (*interpreted to end*)
  1488      if ay = Skip_ then Skip (v, E) else Napp E 
  1489 );
  1490 
  1491 (* decide for the next applicable stac in the script;
  1492    returns (stactic, value) - the value in case the script is finished 
  1493    12.8.02:         ~~~~~ and no assumptions ??? FIXME ???
  1494    20.8.02: must return p in case of finished, because the next script
  1495             consulted need not be the calling script:
  1496             in case of detail ie. _inserted_ PrfObjs, the next stac
  1497             has to searched in a script with PblObj.status<>Complete !
  1498             (.. not true for other details ..PrfObj ??????????????????
  1499    20.8.02: do NOT return safe (is only changed in locate !!!)
  1500 *)
  1501 fun next_tac (thy,_) (pt,p) (Rfuns {next_rule,...}) (RrlsState(f,f',rss,_), ctxt) =
  1502       let val ctxt = get_ctxt pt p
  1503       in
  1504         if f = f'
  1505         then (End_Detail' (f',[])(*8.6.03*), (Uistate, ctxt), 
  1506   		    (f', Sundef(*FIXME is no value of next_tac! vor 8.6.03*)))  (*finished*)
  1507         else
  1508           (case next_rule rss f of
  1509   	         NONE => (Empty_Tac_, (Uistate, ctxt), (e_term, Sundef))  (*helpless*)
  1510   	       | SOME (Thm (id,thm))(*8.6.03: muss auch f' liefern ?!!*) => 
  1511   	          (Rewrite' (thy, "e_rew_ord", e_rls,(*!?!8.6.03*) false,
  1512   			       (id, string_of_thmI thm), f,(e_term,[(*!?!8.6.03*)])),
  1513   	           (Uistate, ctxt), (e_term, Sundef)))                    (*next stac*)
  1514       end
  1515 
  1516   | next_tac thy (ptp as (pt, pos as (p, _)):ptree * pos') (sc as Script (h $ body)) 
  1517 	  (ScrState (E,l,a,v,s,b), ctxt) =
  1518       let val ctxt = get_ctxt pt pos (*WN110518 we have ctxt twice -- redesign*)
  1519       in
  1520         (case if l = [] 
  1521               then appy thy ptp E [R] body NONE v
  1522               else nstep_up thy ptp sc E l Skip_ a v of
  1523             Skip (v, _) =>                                            (*finished*)
  1524               (case par_pbl_det pt p of
  1525 	               (true, p', _) => 
  1526 	                  let val (_,pblID,_) = get_obj g_spec pt p';
  1527 	                  in (Check_Postcond' (pblID, (v, [(*assigned in next step*)])), 
  1528 	                    (e_istate, ctxt), (v,s)) 
  1529                     end
  1530 	             | (_, p', rls') => 
  1531                    (End_Detail' (e_term,[])(*8.6.03*), (e_istate, ctxt), (v,s)))
  1532          | Napp _ => (Empty_Tac_, (e_istate, ctxt), (e_term, Sundef)) (*helpless*)
  1533          | Appy (m', scrst as (_,_,_,v,_,_)) => 
  1534              (m', (ScrState scrst, ctxt), (v, Sundef)))               (*next stac*)
  1535       end
  1536 
  1537   | next_tac _ _ _ (is, _) = error ("next_tac: not impl for " ^ (istate2str is));
  1538 
  1539 
  1540 (*.create the initial interpreter state from the items of the guard.*)
  1541 fun init_scrstate thy itms metID =
  1542   let
  1543     val actuals = itms2args thy metID itms
  1544 	  val scr as Script sc = (#scr o get_met) metID
  1545     val formals = formal_args sc    
  1546 	  (*expects same sequence of (actual) args in itms and (formal) args in met*)
  1547 	  fun relate_args env [] [] = env
  1548 	    | relate_args env _ [] = 
  1549 	        error ("ERROR in creating the environment for '" ^
  1550 			    id_of_scr sc ^ "' from \nthe items of the guard of " ^
  1551 			    metID2str metID ^ ",\n" ^
  1552 			    "formal arg(s), from the script, miss actual arg(s), from the guards env:\n" ^
  1553 			    (string_of_int o length) formals ^
  1554 			    " formals: " ^ terms2str formals ^ "\n" ^
  1555 			    (string_of_int o length) actuals ^
  1556 			    " actuals: " ^ terms2str actuals)
  1557 	    | relate_args env [] actual_finds = env (*may drop Find!*)
  1558 	    | relate_args env (a::aa) (f::ff) = 
  1559 	        if type_of a = type_of f 
  1560 	        then relate_args (env @ [(a, f)]) aa ff
  1561           else 
  1562 	          error ("ERROR in creating the environment for '" ^
  1563 			      id_of_scr sc ^ "' from \nthe items of the guard of " ^
  1564 			      metID2str metID ^ ",\n" ^
  1565 			      "different types of formal arg, from the script, " ^
  1566 			      "and actual arg, from the guards env:'\n" ^
  1567 			      "formal: '" ^ term2str a ^ "::" ^ (type2str o type_of) a ^ "'\n" ^
  1568 			      "actual: '" ^ term2str f ^ "::" ^ (type2str o type_of) f ^ "'\n" ^
  1569 			      "in\n" ^
  1570 			      "formals: " ^ terms2str formals ^ "\n" ^
  1571 			      "actuals: " ^ terms2str actuals)
  1572      val env = relate_args [] formals actuals;
  1573      val ctxt = ProofContext.init_global thy |> declare_constraints' actuals
  1574      val {pre, prls, ...} = get_met metID;
  1575      val pres = check_preconds thy prls pre itms |> map snd;
  1576      val ctxt = ctxt |> insert_assumptions pres;
  1577    in (ScrState (env,[],NONE,e_term,Safe,true), ctxt, scr):istate * Proof.context * scr end;
  1578 
  1579 (* decide, where to get script/istate from:
  1580    (*1*) from PblObj.env: at begin of script if no init_form
  1581    (*2*) from PblObj/PrfObj: if stac is in the middle of the script
  1582    (*3*) from rls/PrfObj: in case of detail a ruleset *)
  1583 fun from_pblobj_or_detail' thy' (p,p_) pt =
  1584   let val ctxt = get_ctxt pt (p,p_)
  1585   in
  1586     if member op = [Pbl,Met] p_
  1587     then case get_obj g_env pt p of
  1588   	       NONE => error "from_pblobj_or_detail': no istate"
  1589   	     | SOME is =>
  1590   	         let
  1591                val metID = get_obj g_metID pt p
  1592   		         val {srls,...} = get_met metID
  1593   	         in (srls, is, (#scr o get_met) metID) end
  1594     else
  1595       let val (pbl,p',rls') = par_pbl_det pt p
  1596       in if pbl 
  1597          then                                                    (*2*)
  1598   	       let
  1599              val thy = assoc_thy thy'
  1600   	         val PblObj{meth=itms,...} = get_obj I pt p'
  1601 	           val metID = get_obj g_metID pt p'
  1602 	           val {srls,...} = get_met metID
  1603 	         in (*if last_elem p = 0 nothing written to pt yet*)
  1604 	           (srls, get_loc pt (p,p_), (#scr o get_met) metID)
  1605 	         end
  1606          else                                                    (*3*)
  1607 	         (e_rls, (*FIXME.WN0?: get from pbl or met !!! unused for Rrls in locate_gen, next_tac*)
  1608 	          get_loc pt (p,p_),
  1609 	            case rls' of
  1610 	  	          Rls {scr=scr,...} => scr
  1611 	            | Seq {scr=scr,...} => scr
  1612 	            | Rrls {scr=rfuns,...} => rfuns)
  1613       end
  1614   end;
  1615 
  1616 (*.get script and istate from PblObj, see                        (*1*) above.*)
  1617 fun from_pblobj' thy' (p,p_) pt =
  1618   let
  1619     val p' = par_pblobj pt p
  1620 	  val thy = assoc_thy thy'
  1621 	  val PblObj {meth=itms, ...} = get_obj I pt p'
  1622 	  val metID = get_obj g_metID pt p'
  1623 	  val {srls,scr,...} = get_met metID
  1624   in
  1625     if last_elem p = 0 (*nothing written to pt yet*)
  1626     then
  1627        let val (is, ctxt, scr) = init_scrstate thy itms metID
  1628 	     in (srls, (is, ctxt), scr) end
  1629        else (srls, get_loc pt (p,p_), scr)
  1630     end;
  1631     
  1632 (*.get the stactics and problems of a script as tacs
  1633   instantiated with the current environment;
  1634   l is the location which generated the given formula.*)
  1635 (*WN.12.5.03: quick-and-dirty repair for listexpressions*)
  1636 fun is_spec_pos Pbl = true
  1637   | is_spec_pos Met = true
  1638   | is_spec_pos _ = false;
  1639 
  1640 (*. fetch _all_ tactics from script .*)
  1641 fun sel_rules _ (([],Res):pos') = 
  1642     raise PTREE "no tactics applicable at the end of a calculation"
  1643 | sel_rules pt (p,p_) =
  1644   if is_spec_pos p_ 
  1645   then [get_obj g_tac pt p]
  1646   else
  1647     let val pp = par_pblobj pt p;
  1648 	val thy' = (get_obj g_domID pt pp):theory';
  1649 	val thy = assoc_thy thy';
  1650 	val metID = get_obj g_metID pt pp;
  1651 	val metID' =if metID =e_metID then(thd3 o snd3)(get_obj g_origin pt pp)
  1652 		     else metID
  1653 	val {scr=Script sc,srls,...} = get_met metID'
  1654 	val ScrState (env,_,a,v,_,_) = get_istate pt (p,p_);
  1655     in map ((stac2tac pt thy) o rep_stacexpr o #2 o
  1656 	    (handle_leaf "selrul" thy' srls env a v)) (stacpbls sc) end;
  1657 (*
  1658 > val Script sc = (#scr o get_met) ("SqRoot","sqrt-equ-test");
  1659 > val env = [((term_of o the o (parse (Thy_Info.get_theory "Isac"))) "bdv",
  1660              (term_of o the o (parse (Thy_Info.get_theory "Isac"))) "x")];
  1661 > map ((stac2tac pt thy) o #2 o(subst_stacexpr env NONE e_term)) (stacpbls sc);
  1662 *)
  1663 
  1664 
  1665 (*. fetch tactics from script and filter _applicable_ tactics;
  1666     in case of Rewrite_Set* go down to _atomic_ rewrite-tactics .*)
  1667 fun sel_appl_atomic_tacs _ (([],Res):pos') = 
  1668     raise PTREE "no tactics applicable at the end of a calculation"
  1669   | sel_appl_atomic_tacs pt (p,p_) =
  1670     if is_spec_pos p_ 
  1671     then [get_obj g_tac pt p]
  1672     else
  1673 	let val pp = par_pblobj pt p
  1674 	    val thy' = (get_obj g_domID pt pp):theory'
  1675 	    val thy = assoc_thy thy'
  1676 	    val metID = get_obj g_metID pt pp
  1677 	    val metID' =if metID = e_metID 
  1678 			then (thd3 o snd3) (get_obj g_origin pt pp)
  1679 			else metID
  1680 	    val {scr=Script sc,srls,erls,rew_ord'=ro,...} = get_met metID'
  1681 	    val ScrState (env,_,a,v,_,_) = get_istate pt (p,p_)
  1682 	    val alltacs = (*we expect at least 1 stac in a script*)
  1683 		map ((stac2tac pt thy) o rep_stacexpr o #2 o
  1684 		     (handle_leaf "selrul" thy' srls env a v)) (stacpbls sc)
  1685 	    val f = case p_ of
  1686 			Frm => get_obj g_form pt p
  1687 		      | Res => (fst o (get_obj g_result pt)) p
  1688 	(*WN071231 ? replace atomic_appl_tacs with applicable_in (ineff!) ?*)
  1689 	in (distinct o flat o 
  1690 	    (map (atomic_appl_tacs thy ro erls f))) alltacs end;
  1691 	
  1692 
  1693 (*
  1694 end
  1695 open Interpreter;
  1696 *)
  1697 
  1698 (* use"ME/script.sml";
  1699    use"script.sml";
  1700    *)