src/Tools/isac/Interpret/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Sat, 10 Sep 2011 10:37:24 +0200
branchdecompose-isar
changeset 42255 6201b34bd323
parent 42248 ac50595ffe6b
child 42281 19d9ab32a0ce
permissions -rw-r--r--
method ["PolyEq", "solve_d2_polyeq_pq_equation"] works for jrocnik

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