src/Tools/isac/Interpret/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Tue, 17 May 2011 14:56:54 +0200
branchdecompose-isar
changeset 41997 71704991fbb2
parent 41996 4e81dae36cab
child 41999 2d5a8c47f0c2
permissions -rw-r--r--
intermed. ctxt ..: finished check e_ctxt

results of tests still the same: x+1=2 until Check_Postcond
scanning code suggests to reconsider storing ctxt in *Obj{loc,...}
     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     	(tracing("get_t: Let e1= "^(term2str e1)^", e2= "^(term2str e2));
   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 (*["BOOL (1+x=2)","REAL x"] --match_ags--> oris 
   353   --oris2fmz_vals--> ["equality (1+x=2)","boundVariable x","solutions L"]*)
   354 fun oris2fmz_vals oris =
   355     let fun ori2fmz_vals ((_,_,_,dsc,ts):ori) = 
   356 	    ((term2str o comp_dts') (dsc, ts), last_elem ts) 
   357 	    handle _ => error ("ori2fmz_env called with "^terms2str ts)
   358     in (split_list o (map ori2fmz_vals)) oris end;
   359 
   360 (*detour necessary, because generate1 delivers a string-result*)
   361 fun mout2term thy (Form' (FormKF (_,_,_,_,res))) = 
   362   (term_of o the o (parse (assoc_thy thy))) res
   363   | mout2term thy (Form' (PpcKF _)) = e_term;(*3.8.01: res of subpbl 
   364 					   at time of detection in script*)
   365 
   366 (*.convert a script-tac 'stac' to a tactic 'tac'; if stac is an initac,
   367    then convert to a 'tac_' (as required in appy).
   368    arg pt:ptree for pushing the thy specified in rootpbl into subpbls.*)
   369 fun stac2tac_ pt thy (Const ("Script.Rewrite",_) $ Free (thmID,_) $ _ $ f) =
   370       let
   371         val tid = (de_esc_underscore o strip_thy) thmID
   372       in (Rewrite (tid, (string_of_thmI o (assoc_thm' thy)) (tid,"")), Empty_Tac_)
   373       end
   374 
   375   | stac2tac_ pt thy (Const ("Script.Rewrite'_Inst",_) $ sub $ Free (thmID,_) $ _ $ f) =
   376       let
   377         val subML = ((map isapair2pair) o isalist2list) sub
   378         val subStr = subst2subs subML
   379         val tid = (de_esc_underscore o strip_thy) thmID (*4.10.02 unnoetig*)
   380       in (Rewrite_Inst (subStr, (tid, (string_of_thmI o (assoc_thm' thy)) (tid,""))), Empty_Tac_)
   381       end
   382       
   383   | stac2tac_ pt thy (Const ("Script.Rewrite'_Set",_) $ Free (rls,_) $ _ $ f) =
   384       (Rewrite_Set ((de_esc_underscore o strip_thy) rls), Empty_Tac_)
   385 
   386   | stac2tac_ pt thy (Const ("Script.Rewrite'_Set'_Inst",_) $ sub $ Free (rls,_) $ _ $ f) =
   387       let
   388         val subML = ((map isapair2pair) o isalist2list) sub;
   389         val subStr = subst2subs subML;
   390       in (Rewrite_Set_Inst (subStr,rls), Empty_Tac_) end
   391 
   392   | stac2tac_ pt thy (Const ("Script.Calculate",_) $ Free (op_,_) $ f) =
   393       (Calculate op_, Empty_Tac_)
   394 
   395   | stac2tac_ pt thy (Const ("Script.Take",_) $ t) =
   396       (Take (term2str t), Empty_Tac_)
   397 
   398   | stac2tac_ pt thy (Const ("Script.Substitute",_) $ isasub $ arg) =
   399       (Substitute ((subte2sube o isalist2list) isasub), Empty_Tac_)
   400 
   401   | stac2tac_ pt thy (Const("Script.Check'_elementwise",_) $ _ $ 
   402 		(set as Const ("Collect",_) $ Abs (_,_,pred))) = 
   403       (Check_elementwise (Print_Mode.setmp [] (Syntax.string_of_term 
   404                           (thy2ctxt thy)) pred), (*set*)Empty_Tac_)
   405 
   406   | stac2tac_ pt thy (Const("Script.Or'_to'_List",_) $ _ ) = 
   407       (Or_to_List, Empty_Tac_)
   408 
   409     (*12.1.01.for subproblem_equation_dummy in root-equation *)
   410   | stac2tac_ pt thy (Const ("Script.Tac",_) $ Free (str,_)) = 
   411       (Tac ((de_esc_underscore o strip_thy) str),  Empty_Tac_) 
   412 
   413     (*compare "| assod _ (Subproblem'"*)
   414   | stac2tac_ pt thy (stac as Const ("Script.SubProblem",_) $
   415 	  (Const ("Product_Type.Pair",_) $Free (dI',_) $ 
   416 		 (Const ("Product_Type.Pair",_) $ pI' $ mI')) $ ags') =
   417       let
   418         val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   419         val thy = maxthy (assoc_thy dI) (rootthy pt);
   420 	      val pI = ((map (de_esc_underscore o free2str)) o isalist2list) pI';
   421 	      val mI = ((map (de_esc_underscore o free2str)) o isalist2list) mI';
   422 	      val ags = isalist2list ags';
   423 	      val (pI, pors, mI) = 
   424 	        if mI = ["no_met"] 
   425 	        then
   426             let
   427               val pors = (match_ags thy ((#ppc o get_pbt) pI) ags)
   428 			          handle ERROR "actual args do not match formal args" 
   429 				        => (match_ags_msg pI stac ags(*raise exn*); [])
   430 		          val pI' = refine_ori' pors pI;
   431 		        in (pI', pors (*refinement over models with diff.prec only*), 
   432 		            (hd o #met o get_pbt) pI') end
   433 	        else (pI, (match_ags thy ((#ppc o get_pbt) pI) ags)
   434 		        handle ERROR "actual args do not match formal args"
   435 			      => (match_ags_msg pI stac ags(*raise exn*); []), mI);
   436         val (fmz_, vals) = oris2fmz_vals pors;
   437 	      val {cas,ppc,thy,...} = get_pbt pI
   438 	      val dI = theory2theory' thy (*.take dI from _refined_ pbl.*)
   439 	      val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt));
   440         val ctxt = ProofContext.init_global 
   441         val ctxt = dI |> Thy_Info.get_theory |> ProofContext.init_global 
   442           |> declare_constraints' vals
   443 	      val hdl =
   444           case cas of
   445 		        NONE => pblterm dI pI
   446 		      | SOME t => subst_atomic ((vars_of_pbl_' ppc) ~~~ vals) t
   447         val f = subpbl (strip_thy dI) pI
   448       in (Subproblem (dI, pI),	Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f))
   449       end
   450 
   451   | stac2tac_ pt thy t = error 
   452   ("stac2tac_ TODO: no match for " ^
   453    (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy)) t));
   454 
   455 fun stac2tac pt thy t = (fst o stac2tac_ pt thy) t;
   456 
   457 (*test a term for being a _list_ (set ?) of constants; could be more rigorous*)
   458 fun list_of_consts (Const ("List.list.Cons",_) $ _ $ _) = true
   459   | list_of_consts (Const ("List.list.Nil",_)) = true
   460   | list_of_consts _ = false;
   461 (*val ttt = (term_of o the o (parse thy)) "[x=#1,x=#2,x=#3]";
   462 > list_of_consts ttt;
   463 val it = true : bool
   464 > val ttt = (term_of o the o (parse thy)) "[]";
   465 > list_of_consts ttt;
   466 val it = true : bool*)
   467 
   468 
   469 
   470 datatype ass = 
   471     Ass of
   472       tac_ *   (* SubProblem gets args instantiated in assod *)
   473   	  term     (* for itr_arg, result in ets *)
   474   | AssWeak of
   475       tac_ *
   476   	  term     (*for itr_arg,result in ets*)
   477   | NotAss;
   478 
   479 (*.assod: tac_ associated with stac w.r.t. d
   480 args
   481  pt:ptree for pushing the thy specified in rootpbl into subpbls
   482 returns
   483  Ass    : associated: e.g. thmID in stac = thmID in m
   484                        +++ arg   in stac = arg   in m
   485  AssWeak: weakly ass.:e.g. thmID in stac = thmID in m, //arg//
   486  NotAss :             e.g. thmID in stac/=/thmID in m (not =)
   487 8.01:
   488  tac_ SubProblem with args completed from script
   489 .*)
   490 fun assod pt d (m as Rewrite_Inst' (thy',rod,rls,put,subs,(thmID,thm),f,(f',asm))) stac =
   491       (case stac of
   492 	       (Const ("Script.Rewrite'_Inst",_) $ subs_ $ Free (thmID_,idT) $b$f_) =>
   493 	          if thmID = thmID_
   494             then 
   495 	            if f = f_ 
   496               then ((*tracing"3### assod ..Ass";*)Ass (m,f')) 
   497 	            else ((*tracing"3### assod ..AssWeak";*)AssWeak(m, f'))
   498 	          else ((*tracing"3### assod ..NotAss";*)NotAss)
   499        | (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $_$f_) =>
   500 	          if contains_rule (Thm (thmID, refl(*dummy*))) (assoc_rls rls_)
   501             then 
   502 	            if f = f_ then Ass (m,f') else AssWeak (m,f')
   503 	          else NotAss
   504        | _ => NotAss)
   505 
   506   | assod pt d (m as Rewrite' (thy,rod,rls,put,(thmID,thm),f,(f',asm))) stac =
   507       (case stac of
   508 	       (t as Const ("Script.Rewrite",_) $ Free (thmID_,idT) $ b $ f_) =>
   509 	         ((*tracing ("3### assod: stac = " ^ ter2str t);
   510 	          tracing ("3### assod: f(m)= " ^ term2str f);*)
   511 	          if thmID = thmID_
   512             then 
   513 	            if f = f_
   514               then ((*tracing"3### assod ..Ass";*)Ass (m,f')) 
   515 	            else 
   516                 ((*tracing"### assod ..AssWeak";
   517 		             tracing("### assod: f(m)  = " ^ term2str f);
   518 		             tracing("### assod: f(stac)= " ^ term2str f_)*)
   519 		             AssWeak (m,f'))
   520 	          else ((*tracing"3### assod ..NotAss";*)NotAss))
   521        | (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) =>
   522 	          if contains_rule (Thm (thmID, refl(*dummy*))) (assoc_rls rls_)
   523             then
   524 	            if f = f_ then Ass (m,f') else AssWeak (m,f')
   525 	          else NotAss
   526        | _ => NotAss)
   527 
   528   | assod pt d (m as Rewrite_Set_Inst' (thy',put,sub,rls,f,(f',asm))) 
   529     (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $ _ $ f_) = 
   530       if id_rls rls = rls_ 
   531       then 
   532         if f = f_ then Ass (m,f') else AssWeak (m,f')
   533       else NotAss
   534 
   535   | assod pt d (m as Detail_Set_Inst' (thy',put,sub,rls,f,(f',asm))) 
   536     (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free (rls_,_) $ _ $ f_) = 
   537       if id_rls rls = rls_
   538       then 
   539         if f = f_ then Ass (m,f') else AssWeak (m,f')
   540       else NotAss
   541 
   542   | assod pt d (m as Rewrite_Set' (thy,put,rls,f,(f',asm))) 
   543     (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) = 
   544       if id_rls rls = rls_
   545       then 
   546         if f = f_ then Ass (m,f') else AssWeak (m,f')
   547       else NotAss
   548 
   549   | assod pt d (m as Detail_Set' (thy,put,rls,f,(f',asm))) 
   550     (Const ("Script.Rewrite'_Set",_) $ Free (rls_,_) $ _ $ f_) = 
   551       if id_rls rls = rls_
   552       then 
   553         if f = f_ then Ass (m,f') else AssWeak (m,f')
   554       else NotAss
   555 
   556   | assod pt d (m as Calculate' (thy',op_,f,(f',thm'))) stac =
   557       (case stac of
   558 	       (Const ("Script.Calculate",_) $ Free (op__,_) $ f_) =>
   559 	         if op_ = op__
   560            then
   561 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   562 	         else NotAss
   563        | (Const ("Script.Rewrite'_Set'_Inst",_) $ sub_ $ Free(rls_,_) $_$f_)  => 
   564 	         if contains_rule (Calc (snd (assoc1 (!calclist', op_)))) (assoc_rls rls_)
   565            then
   566 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   567 	         else NotAss
   568        | (Const ("Script.Rewrite'_Set",_) $ Free (rls_, _) $ _ $ f_) =>
   569 	         if contains_rule (Calc (snd (assoc1 (!calclist', op_)))) (assoc_rls rls_)
   570            then
   571 	           if f = f_ then Ass (m,f') else AssWeak (m,f')
   572 	         else NotAss
   573        | _ => NotAss)
   574 
   575   | assod pt _ (m as Check_elementwise' (consts,_,(consts_chkd,_)))
   576     (Const ("Script.Check'_elementwise",_) $ consts' $ _) =
   577       ((*tracing("### assod Check'_elementwise: consts= "^(term2str consts)^
   578 	     ", consts'= "^(term2str consts'));
   579        atomty consts; atomty consts';*)
   580        if consts = consts'
   581        then ((*tracing"### assod Check'_elementwise: Ass";*) Ass (m, consts_chkd))
   582        else ((*tracing"### assod Check'_elementwise: NotAss";*) NotAss))
   583 
   584   | assod pt _ (m as Or_to_List' (ors, list)) (Const ("Script.Or'_to'_List",_) $ _) =
   585 	    Ass (m, list) 
   586 
   587   | assod pt _ (m as Take' term) (Const ("Script.Take",_) $ _) =
   588 	    Ass (m, term)
   589 
   590   | assod pt _ (m as Substitute' (_, _, res)) (Const ("Script.Substitute",_) $ _ $ _) =
   591 	    Ass (m, res) 
   592 
   593   | assod pt _ (m as Tac_ (thy,f,id,f')) (Const ("Script.Tac",_) $ Free (id',_)) =
   594       if id = id'
   595       then Ass (m, ((term_of o the o (parse thy)) f'))
   596       else NotAss
   597 
   598     (*compare "| stac2tac_ thy (Const ("Script.SubProblem",_)"*)
   599   | assod pt _ (Subproblem' ((domID,pblID,metID),_,_,_,_,f))
   600 	  (stac as Const ("Script.SubProblem",_) $ (Const ("Product_Type.Pair",_) $
   601 		 Free (dI',_) $ (Const ("Product_Type.Pair",_) $ pI' $ mI')) $ ags') =
   602       let 
   603         val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   604         val thy = maxthy (assoc_thy dI) (rootthy pt);
   605 	      val pI = ((map (de_esc_underscore o free2str)) o isalist2list) pI';
   606 	      val mI = ((map (de_esc_underscore o free2str)) o isalist2list) mI';
   607 	      val ags = isalist2list ags';
   608 	      val (pI, pors, mI) = 
   609 	        if mI = ["no_met"] 
   610 	        then
   611             let
   612               val pors = (match_ags thy ((#ppc o get_pbt) pI) ags)
   613 			          handle ERROR "actual args do not match formal args"
   614 				        => (match_ags_msg pI stac ags(*raise exn*);[]);
   615 		          val pI' = refine_ori' pors pI;
   616 		        in (pI', pors (*refinement over models with diff.prec only*), 
   617 		            (hd o #met o get_pbt) pI')
   618             end
   619 	        else (pI, (match_ags thy ((#ppc o get_pbt) pI) ags)
   620 		        handle ERROR "actual args do not match formal args"
   621 			      => (match_ags_msg pI stac ags(*raise exn*);[]), mI);
   622         val (fmz_, vals) = oris2fmz_vals pors;
   623 	      val {cas, ppc, thy,...} = get_pbt pI
   624 	      val dI = theory2theory' thy (*take dI from _refined_ pbl*)
   625 	      val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt))
   626 	      val ctxt = dI |> Thy_Info.get_theory |> ProofContext.init_global 
   627           |> declare_constraints' vals
   628 	      val hdl = 
   629           case cas of
   630 		        NONE => pblterm dI pI
   631 		      | SOME t => subst_atomic ((vars_of_pbl_' ppc) ~~~ vals) t
   632         val f = subpbl (strip_thy dI) pI
   633       in 
   634         if domID = dI andalso pblID = pI
   635         then Ass (Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f), f) 
   636         else NotAss
   637       end
   638 
   639   | assod pt d m t = 
   640       (if (!trace_script) 
   641        then tracing("@@@ the 'tac_' proposed to apply does NOT match the leaf found in the script:\n"^
   642 		     "@@@ tac_ = "^(tac_2str m))
   643        else ();
   644        NotAss);
   645 
   646 fun tac_2tac (Refine_Tacitly' (pI,_,_,_,_)) = Refine_Tacitly pI
   647   | tac_2tac (Model_Problem' (pI,_,_))      = Model_Problem
   648   | tac_2tac (Add_Given' (t,_))             = Add_Given t
   649   | tac_2tac (Add_Find' (t,_))              = Add_Find t
   650   | tac_2tac (Add_Relation' (t,_))          = Add_Relation t
   651  
   652   | tac_2tac (Specify_Theory' dI)           = Specify_Theory dI
   653   | tac_2tac (Specify_Problem' (dI,_))      = Specify_Problem dI
   654   | tac_2tac (Specify_Method' (dI,_,_))     = Specify_Method dI
   655   
   656   | tac_2tac (Rewrite' (thy,rod,erls,put,(thmID,thm),f,(f',asm))) =
   657     Rewrite (thmID,thm)
   658 
   659   | tac_2tac (Rewrite_Inst' (thy,rod,erls,put,sub,(thmID,thm),f,(f',asm)))=
   660     Rewrite_Inst (subst2subs sub,(thmID,thm))
   661 
   662   | tac_2tac (Rewrite_Set' (thy,put,rls,f,(f',asm))) = 
   663     Rewrite_Set (id_rls rls)
   664 
   665   | tac_2tac (Detail_Set' (thy,put,rls,f,(f',asm))) = 
   666     Detail_Set (id_rls rls)
   667 
   668   | tac_2tac (Rewrite_Set_Inst' (thy,put,sub,rls,f,(f',asm))) = 
   669     Rewrite_Set_Inst (subst2subs sub,id_rls rls)
   670 
   671   | tac_2tac (Detail_Set_Inst' (thy,put,sub,rls,f,(f',asm))) = 
   672     Detail_Set_Inst (subst2subs sub,id_rls rls)
   673 
   674   | tac_2tac (Calculate' (thy,op_,t,(t',thm'))) = Calculate (op_)
   675 
   676   | tac_2tac (Check_elementwise' (consts,pred,consts')) =
   677     Check_elementwise pred
   678 
   679   | tac_2tac (Or_to_List' _) = Or_to_List
   680   | tac_2tac (Take' term) = Take (term2str term)
   681   | tac_2tac (Substitute' (subte, t, res)) = Substitute (subte2sube subte) 
   682 
   683   | tac_2tac (Tac_ (_,f,id,f')) = Tac id
   684 
   685   | tac_2tac (Subproblem' ((domID, pblID, _), _, _, _,_ ,_)) = 
   686 		  Subproblem (domID, pblID)
   687   | tac_2tac (Check_Postcond' (pblID, _)) = 
   688 		  Check_Postcond pblID
   689   | tac_2tac Empty_Tac_ = Empty_Tac
   690 
   691   | tac_2tac m = 
   692   error ("tac_2tac: not impl. for "^(tac_2str m));
   693 
   694 
   695 
   696 
   697 (** decompose tac_ to a rule and to (lhs,rhs)
   698     unly needed                          --- **)
   699 
   700 val idT = Type ("Script.ID",[]);
   701 (*val tt = (term_of o the o (parse thy)) "square_equation_left::ID";
   702 type_of tt = idT;
   703 val it = true : bool
   704 *)
   705 
   706 fun make_rule thy t =
   707   let val ct = cterm_of thy (Trueprop $ t)
   708   in Thm (Print_Mode.setmp [] (Syntax.string_of_term (thy2ctxt thy))
   709                            (term_of ct), make_thm ct) end;
   710 
   711 (* val (Rewrite_Inst'(thy',rod,rls,put,subs,(thmID,thm),f,(f',asm)))=m;
   712    *)
   713 (*decompose tac_ to a rule and to (lhs,rhs) for ets FIXME.12.03: obsolete!
   714  NOTE.12.03: also used for msg 'not locatable' ?!: 'Subproblem' missing !!!
   715 WN0508 only use in tac_2res, which uses only last return-value*)
   716 fun rep_tac_ (Rewrite_Inst' 
   717 		 (thy',rod,rls,put,subs,(thmID,thm),f,(f',asm))) = 
   718   let val fT = type_of f;
   719     val b = if put then HOLogic.true_const else HOLogic.false_const;
   720     val sT = (type_of o fst o hd) subs;
   721     val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   722       (map HOLogic.mk_prod subs);
   723     val sT' = type_of subs';
   724     val lhs = Const ("Script.Rewrite'_Inst",[sT',idT,(*fT*)bool,fT] ---> fT) 
   725       $ subs' $ Free (thmID,idT) $ b $ f;
   726   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   727 (*Fehlersuche 25.4.01
   728 (a)----- als String zusammensetzen:
   729 ML> term2str f; 
   730 val it = "d_d x #4 + d_d x (x ^^^ #2 + #3 * x)" : string
   731 ML> term2str f'; 
   732 val it = "#0 + d_d x (x ^^^ #2 + #3 * x)" : string
   733 ML> subs;
   734 val it = [(Free ("bdv","RealDef.real"),Free ("x","RealDef.real"))] : subst
   735 > val tt = (term_of o the o (parse thy))
   736   "(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))";
   737 > atomty tt;
   738 ML> tracing (term2str tt); 
   739 (Rewrite_Inst [(bdv,x)] diff_const False d_d x #4 + d_d x (x ^^^ #2 + #3 * x)) =
   740  #0 + d_d x (x ^^^ #2 + #3 * x)
   741 
   742 (b)----- laut rep_tac_:
   743 > val ttt=HOLogic.mk_eq (lhs,f');
   744 > atomty ttt;
   745 
   746 
   747 (*Fehlersuche 1-2Monate vor 4.01:*)
   748 > val tt = (term_of o the o (parse thy))
   749   "Rewrite_Inst[(bdv,x)]square_equation_left True(x=#1+#2)";
   750 > atomty tt;
   751 
   752 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   753 > val f' = (term_of o the o (parse thy)) "x=#3";
   754 > val subs = [((term_of o the o (parse thy)) "bdv",
   755 	       (term_of o the o (parse thy)) "x")];
   756 > val sT = (type_of o fst o hd) subs;
   757 > val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   758 			      (map HOLogic.mk_prod subs);
   759 > val sT' = type_of subs';
   760 > val lhs = Const ("Script.Rewrite'_Inst",[sT',idT,fT,fT] ---> fT) 
   761   $ subs' $ Free (thmID,idT) $ HOLogic.true_const $ f;
   762 > lhs = tt;
   763 val it = true : bool
   764 > rep_tac_ (Rewrite_Inst' 
   765 	       ("Script","tless_true","eval_rls",false,subs,
   766 		("square_equation_left",""),f,(f',[])));
   767 *)
   768   | rep_tac_ (Rewrite' (thy',rod,rls,put,(thmID,thm),f,(f',asm)))=
   769   let 
   770     val fT = type_of f;
   771     val b = if put then HOLogic.true_const else HOLogic.false_const;
   772     val lhs = Const ("Script.Rewrite",[idT,HOLogic.boolT,fT] ---> fT)
   773       $ Free (thmID,idT) $ b $ f;
   774   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   775 (* 
   776 > val tt = (term_of o the o (parse thy)) (*____   ____..test*)
   777   "Rewrite square_equation_left True (x=#1+#2) = (x=#3)";
   778 
   779 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   780 > val f' = (term_of o the o (parse thy)) "x=#3";
   781 > val Thm (id,thm) = 
   782   rep_tac_ (Rewrite' 
   783    ("Script","tless_true","eval_rls",false,
   784     ("square_equation_left",""),f,(f',[])));
   785 > val SOME ct = parse thy   
   786   "Rewrite square_equation_left True (x=#1+#2)"; 
   787 > rewrite_ Script.thy tless_true eval_rls true thm ct;
   788 val it = SOME ("x = #3",[]) : (cterm * cterm list) option
   789 *)
   790   | rep_tac_ (Rewrite_Set_Inst' 
   791 		 (thy',put,subs,rls,f,(f',asm))) =
   792     (e_rule, (e_term, f'))
   793 (*WN050824: type error ...
   794   let val fT = type_of f;
   795     val sT = (type_of o fst o hd) subs;
   796     val subs' = list2isalist (HOLogic.mk_prodT (sT, sT))
   797       (map HOLogic.mk_prod subs);
   798     val sT' = type_of subs';
   799     val b = if put then HOLogic.true_const else HOLogic.false_const
   800     val lhs = Const ("Script.Rewrite'_Set'_Inst",
   801 		     [sT',idT,fT,fT] ---> fT) 
   802       $ subs' $ Free (id_rls rls,idT) $ b $ f;
   803   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end*)
   804 (* ... vals from Rewrite_Inst' ...
   805 > rep_tac_ (Rewrite_Set_Inst' 
   806 	       ("Script",false,subs,
   807 		"isolate_bdv",f,(f',[])));
   808 *)
   809 (* val (Rewrite_Set' (thy',put,rls,f,(f',asm)))=m;
   810 *)
   811   | rep_tac_ (Rewrite_Set' (thy',put,rls,f,(f',asm)))=
   812   let val fT = type_of f;
   813     val b = if put then HOLogic.true_const else HOLogic.false_const;
   814     val lhs = Const ("Script.Rewrite'_Set",[idT,bool,fT] ---> fT) 
   815       $ Free (id_rls rls,idT) $ b $ f;
   816   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   817 (* 13.3.01:
   818 val thy = assoc_thy thy';
   819 val t = HOLogic.mk_eq (lhs,f');
   820 make_rule thy t;
   821 --------------------------------------------------
   822 val lll = (term_of o the o (parse thy)) 
   823   "Rewrite_Set SqRoot_simplify False (d_d x (x ^^^ #2 + #3 * x) + d_d x #4)";
   824 
   825 --------------------------------------------------
   826 > val f = (term_of o the o (parse thy)) "x=#1+#2";
   827 > val f' = (term_of o the o (parse thy)) "x=#3";
   828 > val Thm (id,thm) = 
   829   rep_tac_ (Rewrite_Set' 
   830    ("Script",false,"SqRoot_simplify",f,(f',[])));
   831 val id = "(Rewrite_Set SqRoot_simplify True x = #1 + #2) = (x = #3)" : string
   832 val thm = "(Rewrite_Set SqRoot_simplify True x = #1 + #2) = (x = #3)" : thm
   833 *)
   834   | rep_tac_ (Calculate' (thy',op_,f,(f',thm')))=
   835   let val fT = type_of f;
   836     val lhs = Const ("Script.Calculate",[idT,fT] ---> fT) 
   837       $ Free (op_,idT) $ f
   838   in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   839 (*
   840 > val lhs'=(term_of o the o (parse thy))"Calculate plus (#1+#2)";
   841   ... test-root-equ.sml: calculate ...
   842 > val Appl m'=applicable_in p pt (Calculate "PLUS");
   843 > val (lhs,_)=tac_2etac m';
   844 > lhs'=lhs;
   845 val it = true : bool*)
   846   | rep_tac_ (Check_elementwise' (t,str,(t',asm)))  = (Erule, (e_term, t'))
   847   | rep_tac_ (Subproblem' (_, _, _, _, _, t'))  = (Erule, (e_term, t'))
   848   | rep_tac_ (Take' (t'))  = (Erule, (e_term, t'))
   849   | rep_tac_ (Substitute' (subst,t,t'))  = (Erule, (t, t'))
   850   | rep_tac_ (Or_to_List' (t, t'))  = (Erule, (t, t'))
   851   | rep_tac_ m = error ("rep_tac_: not impl.for "^
   852 				 (tac_2str m));
   853 
   854 (*"N.3.6.03------
   855 fun tac_2rule m = (fst o rep_tac_) m;
   856 fun tac_2etac m = (snd o rep_tac_) m;
   857 fun tac_2tac m = (fst o snd o rep_tac_) m;*)
   858 fun tac_2res m = (snd o snd o rep_tac_) m;(*ONLYuse of rep_tac_
   859 					        FIXXXXME: simplify rep_tac_*)
   860 
   861 
   862 (* handle a leaf at the end of recursive descent:
   863    a leaf is either a tactic or an 'exp' in 'let v = expr'
   864    where 'exp' does not contain a tactic.
   865    handling a leaf comprises
   866    (1) 'subst_stacexpr' substitute env and complete curried tactic
   867    (2) rewrite the leaf by 'srls'
   868 *)
   869 fun handle_leaf call thy srls E a v t =
   870       (*WN050916 'upd_env_opt' is a blind copy from previous version*)
   871        case subst_stacexpr E a v t of
   872 	       (a', STac stac) => (*script-tactic*)
   873 	         let val stac' =
   874              eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) stac)
   875 	         in
   876              (if (!trace_script) 
   877 	            then tracing ("@@@ "^call^" leaf '"^term2str t^"' ---> STac '"^term2str stac'^"'")
   878 	            else ();
   879 	            (a', STac stac'))
   880 	         end
   881        | (a', Expr lexpr) => (*leaf-expression*)
   882 	         let val lexpr' =
   883              eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) lexpr)
   884 	         in
   885              (if (!trace_script) 
   886 	            then tracing("@@@ "^call^" leaf '"^term2str t^"' ---> Expr '"^term2str lexpr'^"'")
   887 	            else ();
   888 	            (a', Expr lexpr'))
   889 	         end;
   890 
   891 
   892 (** locate an applicable stactic in a script **)
   893 
   894 datatype assoc = (*ExprVal in the sense of denotational semantics*)
   895   Assoc of     (*the stac is associated, strongly or weakly*)
   896   scrstate *       (*the current; returned for next_tac etc. outside ass* *)  
   897   (step list)    (*list of steps done until associated stac found;
   898 	           initiated with the data for doing the 1st step,
   899                    thus the head holds these data further on,
   900 		   while the tail holds steps finished (incl.scrstate in ptree)*)
   901 | NasApp of   (*stac not associated, but applicable, ptree-node generated*)
   902   scrstate * (step list)
   903 | NasNap of     (*stac not associated, not applicable, nothing generated;
   904 	         for distinction in Or, for leaving iterations, leaving Seq,
   905 		 evaluate scriptexpressions*)
   906   term * env;
   907 fun assoc2str (Assoc     _) = "Assoc"
   908   | assoc2str (NasNap  _) = "NasNap"
   909   | assoc2str (NasApp _) = "NasApp";
   910 
   911 
   912 datatype asap = (*arg. of assy _only_ for distinction w.r.t. Or*)
   913   Aundef   (*undefined: set only by (topmost) Or*)
   914 | AssOnly  (*do not execute appl stacs - there could be an associated
   915 	     in parallel Or-branch*)
   916 | AssGen;  (*no Ass(Weak) found within Or, thus 
   917              search for _applicable_ stacs, execute and generate pt*)
   918 (*this constructions doesnt allow arbitrary nesting of Or !!!*)
   919 
   920 
   921 (*assy, ass_up, astep_up scanning for locate_gen at stactic in a script.
   922   search is clearly separated into (1)-(2):
   923   (1) assy is recursive descent;
   924   (2) ass_up resumes interpretation at a location somewhere in the script;
   925       astep_up does only get to the parentnode of the scriptexpr.
   926   consequence:
   927   * call of (2) means _always_ that in this branch below
   928     there was an appl.stac (Repeat, Or e1, ...) found by the previous step.
   929 *)
   930 fun assy ya (is as (E,l,a,v,S,b),ss) (Const ("HOL.Let",_) $ e $ (Abs (id,T,body))) =
   931       (case assy ya ((E , l@[L,R], a,v,S,b),ss) e of
   932 	       NasApp ((E',l,a,v,S,bb),ss) => 
   933 	         let
   934              val id' = mk_Free (id, T);
   935 	           val E' = upd_env E' (id', v);
   936 	         in assy ya ((E', l@[R,D], a,v,S,b),ss) body end
   937        | NasNap (v,E) => 	 
   938 	         let
   939              val id' = mk_Free (id, T);
   940 	           val E' = upd_env E (id', v);
   941 	         in assy ya ((E', l@[R,D], a,v,S,b),ss) body end
   942        | ay => ay)
   943 
   944   | assy (ya as (((thy,srls),_),_)) ((E,l,_,v,S,b),ss) (Const ("Script.While",_) $ c $ e $ a) =
   945       (if eval_true_ thy srls (subst_atomic (upd_env E (a,v)) c) 
   946        then assy ya ((E, l@[L,R], SOME a,v,S,b),ss)  e
   947        else NasNap (v, E))   
   948   | assy (ya as (((thy,srls),_),_)) ((E,l,a,v,S,b),ss) (Const ("Script.While",_) $ c $ e) =
   949       (if eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   950        then assy ya ((E, l@[R], a,v,S,b),ss) e
   951        else NasNap (v, E)) 
   952 
   953   | assy (ya as (((thy,srls),_),_)) ((E,l,a,v,S,b),ss) (Const ("If",_) $ c $ e1 $ e2) =
   954       (if eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   955        then assy ya ((E, l@[L,R], a,v,S,b),ss) e1
   956        else assy ya ((E, l@[  R], a,v,S,b),ss) e2) 
   957 
   958   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Try",_) $ e $ a) =
   959       (case assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e of
   960          ay => ay) 
   961   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Try",_) $ e) =
   962       (case assy ya ((E, l@[R], a,v,S,b),ss) e of
   963          ay => ay)
   964 
   965   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2 $ a) =
   966       (case assy ya ((E, l@[L,L,R], SOME a,v,S,b),ss) e1 of
   967 	       NasNap (v, E) => assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e2
   968        | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l@[L,R], SOME a,v,S,b),ss) e2
   969        | ay => ay)
   970   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2) =
   971       (case assy ya ((E, l@[L,R], a,v,S,b),ss) e1 of
   972 	       NasNap (v, E) => assy ya ((E, l@[R], a,v,S,b),ss) e2
   973        | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l@[R], a,v,S,b),ss) e2
   974        | ay => ay)
   975     
   976   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Repeat",_) $ e $ a) =
   977       assy ya ((E,(l@[L,R]),SOME a,v,S,b),ss) e
   978   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Repeat",_) $ e) =
   979       assy ya ((E,(l@[R]),a,v,S,b),ss) e
   980 
   981   | assy (y, Aundef) ((E,l,_,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2 $ a) =
   982       (case assy (y, AssOnly) ((E,(l@[L,L,R]),SOME a,v,S,b),ss) e1 of
   983 	       NasNap (v, E) => 
   984 	         (case assy (y, AssOnly) ((E,(l@[L,R]),SOME a,v,S,b),ss) e2 of
   985 	            NasNap (v, E) => 
   986 	              (case assy (y, AssGen) ((E,(l@[L,L,R]),SOME a,v,S,b),ss) e1 of
   987 	                 NasNap (v, E) => 
   988 	                   assy (y, AssGen) ((E, (l@[L,R]), SOME a,v,S,b),ss) e2
   989 	               | ay => ay)
   990 	          | ay =>(ay))
   991        | NasApp _ => error ("assy: FIXXXME ///must not return NasApp///")
   992        | ay => (ay))
   993   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2) =
   994       (case assy ya ((E,(l@[L,R]),a,v,S,b),ss) e1 of
   995 	       NasNap (v, E) => assy ya ((E,(l@[R]),a,v,S,b),ss) e2
   996        | ay => (ay)) 
   997 
   998   | assy (((thy',sr),d),ap) (is as (E,l,a,v,S,b), (m,_,pt,(p,p_),c)::ss) t =
   999       (case handle_leaf "locate" thy' sr E a v t of
  1000 	       (a', Expr s) => 
  1001 	          (NasNap (eval_listexpr_ (assoc_thy thy') sr
  1002 			         (subst_atomic (upd_env_opt E (a',v)) t), E))
  1003        | (a', STac stac) =>
  1004 	         let
  1005              val ctxt = get_ctxt pt (p,p_)
  1006              val p' = 
  1007                case p_ of Frm => p 
  1008                | Res => lev_on p
  1009 			         | _ => error ("assy: call by " ^ pos'2str (p,p_));
  1010 	         in
  1011              case assod pt d m stac of
  1012 	             Ass (m,v') =>
  1013 	               let val (p'',c',f',pt') =
  1014                    generate1 (assoc_thy thy') m (ScrState (E,l,a',v',S,true), ctxt) (p',p_) pt;
  1015 	               in Assoc ((E,l,a',v',S,true), (m,f',pt',p'',c @ c')::ss) end
  1016              | AssWeak (m,v') => 
  1017 	               let val (p'',c',f',pt') =
  1018                    generate1 (assoc_thy thy') m (ScrState (E,l,a',v',S,false), ctxt) (p',p_) pt;
  1019 	               in Assoc ((E,l,a',v',S,false), (m,f',pt',p'',c @ c')::ss) end
  1020              | NotAss =>
  1021                  (case ap of   (*switch for Or: 1st AssOnly, 2nd AssGen*)
  1022                     AssOnly => (NasNap (v, E))
  1023                   | gen =>
  1024                       (case applicable_in (p,p_) pt (stac2tac pt (assoc_thy thy') stac) of
  1025 			                   Appl m' =>
  1026 			                     let
  1027                              val is = (E,l,a',tac_2res m',S,false(*FIXXXME.WN0?*))
  1028 			                       val (p'',c',f',pt') =
  1029 			                         generate1 (assoc_thy thy') m' (ScrState is, ctxt) (p',p_) pt;
  1030 			                     in NasApp (is,(m,f',pt',p'',c @ c')::ss) end
  1031 		                   | Notappl _ => (NasNap (v, E))
  1032 			                )
  1033 		             )
  1034            end);
  1035 
  1036 fun ass_up (ys as (y,s,Script sc,d)) (is as (E,l,a,v,S,b),ss) 
  1037 	   (Const ("HOL.Let",_) $ _) =
  1038     let (*val _= tracing("### ass_up1 Let$e: is=")
  1039 	val _= tracing(istate2str (ScrState is))*)
  1040 	val l = drop_last l; (*comes from e, goes to Abs*)
  1041       val (Const ("HOL.Let",_) $ e $ (Abs (i,T,body))) = go l sc;
  1042       val i = mk_Free (i, T);
  1043       val E = upd_env E (i, v);
  1044       (*val _=tracing("### ass_up2 Let$e: E="^(subst2str E));*)
  1045     in case assy (((y,s),d),Aundef) ((E, l@[R,D], a,v,S,b),ss) body of
  1046 	   Assoc iss => Assoc iss
  1047 	 | NasApp iss => astep_up ys iss 
  1048 	 | NasNap (v, E) => astep_up ys ((E,l,a,v,S,b),ss) end
  1049 
  1050   | ass_up ys (iss as (is,_)) (Abs (_,_,_)) = 
  1051     ((*tracing("### ass_up  Abs: is=");
  1052      tracing(istate2str (ScrState is));*)
  1053      astep_up ys iss) (*TODO 5.9.00: env ?*)
  1054 
  1055   | ass_up ys (iss as (is,_)) (Const ("HOL.Let",_) $ e $ (Abs (i,T,b)))=
  1056     ((*tracing("### ass_up Let $ e $ Abs: is=");
  1057      tracing(istate2str (ScrState is));*)
  1058      astep_up ys iss) (*TODO 5.9.00: env ?*)
  1059 
  1060     (* val (ysa, iss,                 (Const ("Script.Seq",_) $ _ $ _ $ _)) =
  1061 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1062        *)
  1063   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _ $ _) =
  1064     astep_up ysa iss (*all has been done in (*2*) below*)
  1065 
  1066   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _) =
  1067     (* val (ysa, iss,                 (Const ("Script.Seq",_) $ _ $ _)) =
  1068 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1069        *)
  1070     astep_up ysa iss (*2*: comes from e2*)
  1071 
  1072   | ass_up (ysa as (y,s,Script sc,d)) (is as (E,l,a,v,S,b),ss)
  1073 	   (Const ("Script.Seq",_) $ _ ) = (*2*: comes from e1, goes to e2*)
  1074 	   (* val ((ysa as (y,s,Script sc,d)), (is as (E,l,a,v,S,b),ss),
  1075 	                                  (Const ("Script.Seq",_) $ _ )) = 
  1076 		  (ys,   ((E,up,a,v,S,b),ss), (go up sc));
  1077 	      *)
  1078     let val up = drop_last l;
  1079 	val Const ("Script.Seq",_) $ _ $ e2 = go up sc
  1080 	(*val _= tracing("### ass_up Seq$e: is=")
  1081 	val _= tracing(istate2str (ScrState is))*)
  1082     in case assy (((y,s),d),Aundef) ((E, up@[R], a,v,S,b),ss) e2 of
  1083 	   NasNap (v,E) => astep_up ysa ((E,up,a,v,S,b),ss)
  1084 	 | NasApp iss => astep_up ysa iss
  1085 	 | ay => ay end
  1086 
  1087     (* val (ysa, iss,                 (Const ("Script.Try",_) $ e $ _)) =
  1088 	   (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1089        *)
  1090   | ass_up ysa iss (Const ("Script.Try",_) $ e $ _) =
  1091     astep_up ysa iss
  1092 
  1093   (* val (ysa, iss, (Const ("Script.Try",_) $ e)) =
  1094 	 (ys,  ((E,up,a,v,S,b),ss), (go up sc));
  1095      *)
  1096   | ass_up ysa iss (Const ("Script.Try",_) $ e) =
  1097     ((*tracing("### ass_up Try $ e");*)
  1098      astep_up ysa iss)
  1099 
  1100   | ass_up (ys as (y,s,_,d)) ((E,l,_,v,S,b),ss)
  1101 	   (*(Const ("Script.While",_) $ c $ e $ a) = WN050930 blind fix*)
  1102 	   (t as Const ("Script.While",_) $ c $ e $ a) =
  1103     ((*tracing("### ass_up: While c= "^
  1104 	     (term2str (subst_atomic (upd_env E (a,v)) c)));*)
  1105      if eval_true_ y s (subst_atomic (upd_env E (a,v)) c)
  1106     then (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 (*WN050930 't' was not assigned*)
  1110      | ay => ay)
  1111     else astep_up ys ((E,l, SOME a,v,S,b),ss)
  1112 	 )
  1113 
  1114   | ass_up (ys as (y,s,_,d)) ((E,l,a,v,S,b),ss)
  1115 	   (*(Const ("Script.While",_) $ c $ e) = WN050930 blind fix*)
  1116 	   (t as Const ("Script.While",_) $ c $ e) =
  1117     if eval_true_ y s (subst_atomic (upd_env_opt E (a,v)) c)
  1118     then (case assy (((y,s),d),Aundef) ((E, l@[R], a,v,S,b),ss) e of 
  1119        NasNap (v,E') => astep_up ys ((E',l, a,v,S,b),ss)
  1120      | NasApp ((E',l,a,v,S,b),ss) =>
  1121        ass_up ys ((E',l,a,v,S,b),ss) t (*WN050930 't' was not assigned*)
  1122      | ay => ay)
  1123     else astep_up ys ((E,l, a,v,S,b),ss)
  1124 
  1125   | ass_up y iss (Const ("If",_) $ _ $ _ $ _) = astep_up y iss
  1126 
  1127   | ass_up (ys as (y,s,_,d)) ((E,l,_,v,S,b),ss)
  1128 	   (t as Const ("Script.Repeat",_) $ e $ a) =
  1129   (case assy (((y,s),d), Aundef) ((E, (l@[L,R]), SOME a,v,S,b),ss) e of 
  1130        NasNap (v,E') => astep_up ys ((E',l, SOME a,v,S,b),ss)
  1131      | NasApp ((E',l,a,v,S,b),ss) =>
  1132        ass_up ys ((E',l,a,v,S,b),ss) t
  1133      | ay => ay)
  1134 
  1135   | ass_up (ys as (y,s,_,d)) (is as ((E,l,a,v,S,b),ss)) 
  1136 	   (t as Const ("Script.Repeat",_) $ e) =
  1137   (case assy (((y,s),d), Aundef) ((E, (l@[R]), a,v,S,b),ss) e of 
  1138        NasNap (v', E') => astep_up ys ((E',l,a,v',S,b),ss)
  1139      | NasApp ((E',l,a,v',S,bb),ss) => 
  1140        ass_up ys ((E',l,a,v',S,b),ss) t
  1141      | ay => ay)
  1142 
  1143   | ass_up y iss (Const ("Script.Or",_) $ _ $ _ $ _) = astep_up y iss
  1144 
  1145   | ass_up y iss (Const ("Script.Or",_) $ _ $ _) = astep_up y iss
  1146 
  1147   | ass_up y ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $ _ ) = 
  1148     astep_up y ((E, (drop_last l), a,v,S,b),ss)
  1149 
  1150   | ass_up y iss t =
  1151     error ("ass_up not impl for t= "^(term2str t))
  1152 (* 9.6.03
  1153    val (ys as (_,_,Script sc,_), ss) = 
  1154        ((thy',srls,scr,d), [(m,EmptyMout,pt,p,[])]:step list);
  1155    astep_up ys ((E,l,a,v,S,b),ss);
  1156    val ((ys as (_,_,Script sc,_)), ((E,l,a,v,S,b),ss)) = 
  1157        (ysa, iss);
  1158    val ((ys as (_,_,Script sc,_)), ((E,l,a,v,S,b),ss)) = 
  1159        ((thy',srls,scr,d), ((E,l,a,v,S,b), [(m,EmptyMout,pt,p,[])]));
  1160    *)  
  1161 and astep_up (ys as (_,_,Script sc,_)) ((E,l,a,v,S,b),ss) =
  1162   if 1 < length l
  1163     then 
  1164       let val up = drop_last l;
  1165 	  (*val _= tracing("### astep_up: E= "^env2str E);*)
  1166       in ass_up ys ((E,up,a,v,S,b),ss) (go up sc) end
  1167   else (NasNap (v, E))
  1168 ;
  1169 
  1170 
  1171 
  1172 
  1173 
  1174 (* use"ME/script.sml";
  1175    use"script.sml";
  1176  term2str (go up sc);
  1177 
  1178    *)
  1179 
  1180 (*check if there are tacs for rewriting only*)
  1181 fun rew_only ([]:step list) = true
  1182   | rew_only (((Rewrite' _          ,_,_,_,_))::ss) = rew_only ss
  1183   | rew_only (((Rewrite_Inst' _     ,_,_,_,_))::ss) = rew_only ss
  1184   | rew_only (((Rewrite_Set' _      ,_,_,_,_))::ss) = rew_only ss
  1185   | rew_only (((Rewrite_Set_Inst' _ ,_,_,_,_))::ss) = rew_only ss
  1186   | rew_only (((Calculate' _        ,_,_,_,_))::ss) = rew_only ss
  1187   | rew_only (((Begin_Trans' _      ,_,_,_,_))::ss) = rew_only ss
  1188   | rew_only (((End_Trans' _        ,_,_,_,_))::ss) = rew_only ss
  1189   | rew_only _ = false; 
  1190   
  1191 
  1192 datatype locate =
  1193   Steps of istate      (*producing hd of step list (which was latest)
  1194 	                 for next_tac, for reporting Safe|Unsafe to DG*)
  1195 	   * step      (*(scrstate producing this step is in ptree !)*) 
  1196 		 list  (*locate_gen may produce intermediate steps*)
  1197 | NotLocatable;        (*no (m Ass m') or (m AssWeak m') found*)
  1198 
  1199 
  1200 
  1201 (* locate_gen tries to locate an input tac m in the script. 
  1202    pursuing this goal the script is executed until an (m' equiv m) is found,
  1203    or the end of the script
  1204 args
  1205    m   : input by the user, already checked by applicable_in,
  1206          (to be searched within Or; and _not_ an m doing the step on ptree !)
  1207    p,pt: (incl ets) at the time of input
  1208    scr : the script
  1209    d   : canonical simplifier for locating Take, Substitute, Subproblems etc.
  1210    ets : ets at the time of input
  1211    l   : the location (in scr) of the stac which generated the current formula
  1212 returns
  1213    Steps: pt,p (incl. ets) with m done
  1214           pos' list of proofobjs cut (from generate)
  1215           safe: implied from last proofobj
  1216 	  ets:
  1217    ///ToDo : ets contains a list of tacs to be done before m can be done
  1218           NOT IMPL. -- "error: do other step before"
  1219    NotLocatable: thus generate_hard
  1220 *)
  1221 (* val (Rewrite'(_,ro,er,pa,(id,str),f,_), p, Rfuns {locate_rule=lo,...},
  1222 	RrlsState (_,f'',rss,rts)) = (m, (p,p_), sc, is);
  1223    *)
  1224 fun locate_gen (thy',_) (Rewrite'(_,ro,er,pa,(id,str),f,_)) (pt,p) 
  1225 	       (Rfuns {locate_rule=lo,...}, d) (RrlsState (_,f'',rss,rts), ctxt) = 
  1226     (case lo rss f (Thm (id, mk_thm (assoc_thy thy') str)) of
  1227 	 [] => NotLocatable
  1228        | rts' => 
  1229 	 Steps (rts2steps [] ((pt,p),(f,f'',rss,rts),(thy',ro,er,pa)) rts'))
  1230 
  1231   | locate_gen (ts as (thy',srls)) (m:tac_) ((pt,p):ptree * pos') 
  1232 	       (scr as Script (h $ body),d) (ScrState (E,l,a,v,S,b), ctxt)  = 
  1233   let (*val _= tracing("### locate_gen-----------------: is=");
  1234       val _= tracing( istate2str (ScrState (E,l,a,v,S,b)));
  1235       val _= tracing("### locate_gen: l= "^loc_2str l^", p= "^pos'2str p)*)
  1236       val thy = assoc_thy thy';
  1237   in case if l=[] orelse ((*init.in solve..Apply_Method...*)
  1238 			  (last_elem o fst) p = 0 andalso snd p = Res)
  1239 	  then (assy ((ts,d),Aundef) ((E,[R],a,v,S,b),
  1240 				      [(m,EmptyMout,pt,p,[])]) body)
  1241 (* val Assoc (iss as (is as (_,_,_,_,_,bb), ss as ((m',f',pt',p',c')::_))) =
  1242        (astep_up (thy',srls,scr,d) ((E,l,a,v,S,b),[(m,EmptyMout,pt,p,[])]));
  1243        (assy ((ts,d),Aundef) ((E,[R],a,v,S,b),[(m,EmptyMout,pt,p,[])]) body);
  1244   *)
  1245 	  else (astep_up (thy',srls,scr,d) ((E,l,a,v,S,b),
  1246 					    [(m,EmptyMout,pt,p,[])]) ) of
  1247 	 Assoc (iss as (is as (_,_,_,_,_,bb), ss as ((m',f',pt',p',c')::_))) =>
  1248 (* val Assoc (iss as (is as (_,_,_,_,_,bb), ss as ((m',f',pt',p',c')::_))) =
  1249        (astep_up (thy',srls,scr,d) ((E,l,a,v,S,b),
  1250 				    [(m,EmptyMout,pt,p,[])]) );
  1251    *)
  1252 	 ((*tracing("### locate_gen Assoc: p'="^(pos'2str p'));*)
  1253 	  if bb then Steps (ScrState is, ss)
  1254 	  else if rew_only ss (*andalso 'not bb'= associated weakly*)
  1255 	  then let val (po,p_) = p
  1256                    val po' = case p_ of Frm => po | Res => lev_on po
  1257 		  (*WN.12.03: noticed, that pos is also updated in assy !?!
  1258 		   instead take p' from Assoc ?????????????????????????????*)
  1259                   val (p'',c'',f'',pt'') = 
  1260 		      generate1 thy m (ScrState is, ctxt) (po',p_) pt;
  1261 	      (*val _=tracing("### locate_gen, aft g1: p''="^(pos'2str p''));*)
  1262 	      (*drop the intermediate steps !*)
  1263 	      in Steps (ScrState is, [(m, f'',pt'',p'',c'')]) end
  1264 	 else Steps (ScrState is, ss))
  1265 	
  1266      | NasApp _ (*[((E,l,a,v,S,bb),(m',f',pt',p',c'))] => 
  1267 	   error ("locate_gen: should not have got NasApp, ets =")*)
  1268        => NotLocatable
  1269      | NasNap (_,_) =>
  1270        if l=[] then NotLocatable
  1271        else (*scan from begin of script for rew_only*)
  1272 	   (case assy ((ts,d),Aundef) ((E,[R],a,v,Unsafe,b),
  1273 					 [(m,EmptyMout,pt,p,[])]) body  of
  1274 		Assoc (iss as (is as (_,_,_,_,_,bb), 
  1275 			       ss as ((m',f',pt',p',c')::_))) =>
  1276 		    ((*tracing"4### locate_gen Assoc after Fini";*)
  1277 		     if rew_only ss
  1278 		     then let val(p'',c'',f'',pt'') = 
  1279 				 generate1 thy m (ScrState is, ctxt) p' pt;
  1280 			  (*drop the intermediate steps !*)
  1281 			  in Steps (ScrState is, [(m, f'',pt'',p'',c'')]) end
  1282 		     else NotLocatable)
  1283 	      | _ => ((*tracing ("#### locate_gen: after Fini");*)
  1284 		      NotLocatable))
  1285   end
  1286   | locate_gen _ m _ (sc,_) (is, _) = 
  1287     error ("locate_gen: wrong arguments,\n tac= "^(tac_2str m)^
  1288 		 ",\n scr= "^(scr2str sc)^",\n istate= "^(istate2str is));
  1289 
  1290 
  1291 
  1292 (** find the next stactic in a script **)
  1293 
  1294 datatype appy =  (*ExprVal in the sense of denotational semantics*)
  1295     Appy of      (*applicable stac found, search stalled*)
  1296     tac_ *       (*tac_ associated (fun assod) with stac*)
  1297     scrstate     (*after determination of stac WN.18.8.03*)
  1298   | Napp of      (*stac found was not applicable; 
  1299 	           this mode may become Skip in Repeat, Try and Or*)
  1300     env (*stack*)  (*popped while nxt_up*)
  1301   | Skip of      (*for restart after Appy, for leaving iterations,
  1302 	           for passing the value of scriptexpressions,
  1303 		   and for finishing the script successfully*)
  1304     term * env (*stack*);
  1305 
  1306 (*appy, nxt_up, nstep_up scanning for next_tac.
  1307   search is clearly separated into (1)-(2):
  1308   (1) appy is recursive descent;
  1309   (2) nxt_up resumes interpretation at a location somewhere in the script;
  1310       nstep_up does only get to the parentnode of the scriptexpr.
  1311   consequence:
  1312   * call of (2) means _always_ that in this branch below
  1313     there was an applicable stac (Repeat, Or e1, ...)
  1314 *)
  1315 
  1316 
  1317 datatype appy_ = (*as argument in nxt_up, nstep_up, from appy*)
  1318        (*  Appy is only (final) returnvalue, not argument during search
  1319        |*) Napp_ (*ev. detects 'script is not appropriate for this example'*)
  1320        | Skip_;  (*detects 'script successfully finished'
  1321 		   also used as init-value for resuming; this works,
  1322 	           because 'nxt_up Or e1' treats as Appy*)
  1323 
  1324 fun appy thy ptp E l
  1325   (t as Const ("HOL.Let",_) $ e $ (Abs (i,T,b))) a v =
  1326 (* val (thy, ptp, E, l,        t as Const ("HOL.Let",_) $ e $ (Abs (i,T,b)),a, v)=
  1327        (thy, ptp, E, up@[R,D], body,                                    a, v);
  1328    appy thy ptp E l t a v;
  1329    *)
  1330   ((*tracing("### appy Let$e$Abs: is=");
  1331    tracing(istate2str (ScrState (E,l,a,v,Sundef,false)));*)
  1332    case appy thy ptp E (l@[L,R]) e a v of
  1333      Skip (res, E) => 
  1334        let (*val _= tracing("### appy Let "^(term2str t));
  1335 	 val _= tracing("### appy Let: Skip res ="^(term2str res));*)
  1336        (*val (i',b') = variant_abs (i,T,b); WN.15.5.03
  1337 	 val i = mk_Free(i',T);             WN.15.5.03 *)   
  1338 	 val E' = upd_env E (Free (i,T), res);
  1339        in appy thy ptp E' (l@[R,D]) b a v end
  1340    | ay => ay)
  1341 
  1342   | appy (thy as (th,sr)) ptp E l
  1343   (t as Const ("Script.While"(*1*),_) $ c $ e $ a) _ v = (*ohne n. 28.9.00*)
  1344   ((*tracing("### appy While $ c $ e $ a, upd_env= "^
  1345 	   (subst2str (upd_env E (a,v))));*)
  1346    if eval_true_ th sr (subst_atomic (upd_env E (a,v)) c)
  1347     then appy thy ptp E (l@[L,R]) e (SOME a) v
  1348   else Skip (v, E))
  1349 
  1350   | appy (thy as (th,sr)) ptp E l
  1351   (t as Const ("Script.While"(*2*),_) $ c $ e) a v =(*ohne nachdenken 28.9.00*)
  1352   ((*tracing("### appy While $ c $ e, upd_env= "^
  1353 	   (subst2str (upd_env_opt E (a,v))));*)
  1354    if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
  1355     then appy thy ptp E (l@[R]) e a v
  1356   else Skip (v, E))
  1357 
  1358   | appy (thy as (th,sr)) ptp E l (t as Const ("If",_) $ c $ e1 $ e2) a v =
  1359     ((*tracing("### appy If: t= "^(term2str t));
  1360      tracing("### appy If: c= "^(term2str(subst_atomic(upd_env_opt E(a,v))c)));
  1361      tracing("### appy If: thy= "^(fst thy));*)
  1362      if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
  1363      then ((*tracing("### appy If: true");*)appy thy ptp E (l@[L,R]) e1 a v)
  1364      else ((*tracing("### appy If: false");*)appy thy ptp E (l@[  R]) e2 a v))
  1365 (* val (thy, ptp, E, l,     (Const ("Script.Repeat",_) $ e $ a), _, v) =
  1366        (thy, ptp, E, (l@[R]), e,                                 a, v);
  1367    *)
  1368   | appy thy ptp E (*env*) l
  1369   (Const ("Script.Repeat"(*1*),_) $ e $ a) _ v = 
  1370     ((*tracing("### appy Repeat a: ");*)
  1371      appy thy ptp E (*env*) (l@[L,R]) e (SOME a) v)
  1372 (* val (thy, ptp, E, l,     (Const ("Script.Repeat",_) $ e), _, v) =
  1373        (thy, ptp, E, (l@[R]), e,                             a, v);
  1374    *)
  1375   | appy thy ptp E (*env*) l
  1376   (Const ("Script.Repeat"(*2*),_) $ e) a v = 
  1377     ((*tracing("3### appy Repeat: a= " ^ term2str a);*)
  1378      appy thy ptp E (*env*) (l@[R]) e a v)
  1379 (* val (thy, ptp, E, l,      (t as Const ("Script.Try",_) $ e $ a), _, v)=
  1380        (thy, ptp, E, (l@[R]), e2,                                   a, v);
  1381    *)
  1382   | appy thy ptp E l
  1383   (t as Const ("Script.Try",_) $ e $ a) _ v =
  1384   (case appy thy ptp E (l@[L,R]) e (SOME a) v of
  1385      Napp E => ((*tracing("### appy Try " ^ term2str t);*)
  1386 		 Skip (v, E))
  1387    | ay => ay)
  1388 (* val (thy, ptp, E, l,      (t as Const ("Script.Try",_) $ e), _, v)=
  1389        (thy, ptp, E, (l@[R]), e2,                               a, v);
  1390    val (thy, ptp, E, l,        (t as Const ("Script.Try",_) $ e), _, v)=
  1391        (thy, ptp, E, (l@[L,R]), e1,                               a, v);
  1392    *)
  1393   | appy thy ptp E l
  1394   (t as Const ("Script.Try",_) $ e) a v =
  1395   (case appy thy ptp E (l@[R]) e a v of
  1396      Napp E => ((*tracing("### appy Try " ^ term2str t);*)
  1397 		 Skip (v, E))
  1398    | ay => ay)
  1399 
  1400 
  1401   | appy thy ptp E l
  1402 	 (Const ("Script.Or"(*1*),_) $e1 $ e2 $ a) _ v =
  1403     (case appy thy ptp E (l@[L,L,R]) e1 (SOME a) v of
  1404 	 Appy lme => Appy lme
  1405        | _ => appy thy ptp E (*env*) (l@[L,R]) e2 (SOME a) v)
  1406     
  1407   | appy thy ptp E l
  1408 	 (Const ("Script.Or"(*2*),_) $e1 $ e2) a v =
  1409     (case appy thy ptp E (l@[L,R]) e1 a v of
  1410 	 Appy lme => Appy lme
  1411        | _ => appy thy ptp E (l@[R]) e2 a v)
  1412 
  1413 (* val (thy, ptp, E, l,     (Const ("Script.Seq",_) $ e1 $ e2 $ a), _, v)=
  1414        (thy, ptp, E,(up@[R]),e2,                                    a, v);
  1415    val (thy, ptp, E, l,     (Const ("Script.Seq",_) $ e1 $ e2 $ a), _, v)=
  1416        (thy, ptp, E,(up@[R,D]),body,                                a, v);
  1417    *)
  1418   | appy thy ptp E l
  1419 	 (Const ("Script.Seq"(*1*),_) $ e1 $ e2 $ a) _ v =
  1420     ((*tracing("### appy Seq $ e1 $ e2 $ a, upd_env= "^
  1421 	     (subst2str (upd_env E (a,v))));*)
  1422      case appy thy ptp E (l@[L,L,R]) e1 (SOME a) v of
  1423 	 Skip (v,E) => appy thy ptp E (l@[L,R]) e2 (SOME a) v
  1424        | ay => ay)
  1425 
  1426 (* val (thy, ptp, E, l,     (Const ("Script.Seq",_) $ e1 $ e2), _, v)=
  1427        (thy, ptp, E,(up@[R]),e2,                                a, v);
  1428    val (thy, ptp, E, l,     (Const ("Script.Seq",_) $ e1 $ e2), _, v)=
  1429        (thy, ptp, E,(l@[R]), e2,                                a, v);
  1430    val (thy, ptp, E, l,     (Const ("Script.Seq",_) $ e1 $ e2), _, v)=
  1431        (thy, ptp, E,(up@[R,D]),body,                            a, v);
  1432    *)
  1433   | appy thy ptp E l
  1434 	 (Const ("Script.Seq",_) $ e1 $ e2) a v =
  1435     (case appy thy ptp E (l@[L,R]) e1 a v of
  1436 	 Skip (v,E) => appy thy ptp E (l@[R]) e2 a v
  1437        | ay => ay)
  1438 
  1439   (*.a leaf has been found*)   
  1440   | appy (thy as (th,sr)) (pt, p) E l t a v =
  1441 (* val (thy as (th,sr),(pt, p),E, l,        t,    a, v) = 
  1442        (thy,            ptp,   E, up@[R,D], body, a, v);
  1443    val (thy as (th,sr),(pt, p),E, l,       t, a, v) = 
  1444        (thy,            ptp,   E, l@[L,R], e, a, v);
  1445    val (thy as (th,sr),(pt, p),E, l,       t, a, v) =
  1446        (thy,            ptp,   E,(l@[R]),  e, a, v);
  1447    *)
  1448     (case handle_leaf "next  " th sr E a v t of
  1449 (* val (a', Expr s) = handle_leaf "next  " th sr E a v t;
  1450    *)
  1451 	(a', Expr s) => Skip (s, E)
  1452 (* val (a', STac stac) = handle_leaf "next  " th sr E a v t;
  1453    *)
  1454      | (a', STac stac) =>
  1455 	let
  1456 	 (*val _= tracing("### appy t, vor  stac2tac_ is="); 
  1457            val _= tracing(istate2str (ScrState (E,l,a',v,Sundef,false)));*)
  1458 	   val (m,m') = stac2tac_ pt (assoc_thy th) stac
  1459        in case m of 
  1460 	      Subproblem _ => Appy (m', (E,l,a',tac_2res m',Sundef,false))
  1461 	    | _ => (case applicable_in p pt m of
  1462 (* val Appl m' = applicable_in p pt m;
  1463    *)
  1464 			Appl m' => 
  1465 			((*tracing("### appy: Appy");*)
  1466 			 Appy (m', (E,l,a',tac_2res m',Sundef,false)))
  1467 		      | _ => ((*tracing("### appy: Napp");*)Napp E)) 
  1468 	end);
  1469 	 
  1470 
  1471 (* val (scr as Script sc, l, t as Const ("HOL.Let",_) $ _) =
  1472        (Script sc, up, go up sc);
  1473    nxt_up thy ptp (Script sc) E l ay t a v;
  1474 
  1475    val (thy,ptp,scr as (Script sc),E,l, ay, t as Const ("HOL.Let",_) $ _, a, v)=
  1476        (thy,ptp,Script sc,         E,up,ay, go up sc,                 a, v);
  1477    nxt_up thy ptp scr E l ay t a v;
  1478    *)
  1479 fun nxt_up thy ptp (scr as (Script sc)) E l ay
  1480     (t as Const ("HOL.Let",_) $ _) a v = (*comes from let=...*)
  1481     ((*tracing("### nxt_up1 Let$e: is=");
  1482      tracing(istate2str (ScrState (E,l,a,v,Sundef,false)));*)
  1483      if ay = Napp_
  1484     then nstep_up thy ptp scr E (drop_last l) Napp_ a v
  1485     else (*Skip_*)
  1486 	let val up = drop_last l;
  1487 	    val (Const ("HOL.Let",_) $ e $ (Abs (i,T,body))) = go up sc;
  1488             val i = mk_Free (i, T);
  1489             val E = upd_env E (i, v);
  1490           (*val _= tracing("### nxt_up2 Let$e: is=");
  1491             val _= tracing(istate2str (ScrState (E,l,a,v,Sundef,false)));*)
  1492 	in case appy thy ptp (E) (up@[R,D]) body a v  of
  1493 	       Appy lre => Appy lre
  1494 	     | Napp E => nstep_up thy ptp scr E up Napp_ a v
  1495 	     | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v end)
  1496 	    
  1497   | nxt_up thy ptp scr E l ay
  1498     (t as Abs (_,_,_)) a v = 
  1499     ((*tracing("### nxt_up Abs: " ^ term2str t);*)
  1500      nstep_up thy ptp scr E (*enr*) l ay a v)
  1501 
  1502   | nxt_up thy ptp scr E l ay
  1503     (t as Const ("HOL.Let",_) $ e $ (Abs (i,T,b))) a v =
  1504     ((*tracing("### nxt_up Let$e$Abs: is=");
  1505      tracing(istate2str (ScrState (E,l,a,v,Sundef,false)));*)
  1506      (*tracing("### nxt_up Let e Abs: " ^ term2str t);*)
  1507      nstep_up thy ptp scr (*upd_env*) E (*a,v)*) 
  1508 	      (*eno,upd_env env (iar,res),iar,res,saf*) l ay a v)
  1509 
  1510   (*no appy_: never causes Napp -> Helpless*)
  1511   | nxt_up (thy as (th,sr)) ptp scr E l _ 
  1512   (Const ("Script.While"(*1*),_) $ c $ e $ _) a v = 
  1513   if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c) 
  1514     then case appy thy ptp E (l@[L,R]) e a v of
  1515 	     Appy lr => Appy lr
  1516 	   | Napp E => nstep_up thy ptp scr E l Skip_ a v
  1517 	   | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
  1518   else nstep_up thy ptp scr E l Skip_ a v
  1519 
  1520   (*no appy_: never causes Napp - Helpless*)
  1521   | nxt_up (thy as (th,sr)) ptp scr E l _ 
  1522   (Const ("Script.While"(*2*),_) $ c $ e) a v = 
  1523   if eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c) 
  1524     then case appy thy ptp E (l@[R]) e a v of
  1525 	     Appy lr => Appy lr
  1526 	   | Napp E => nstep_up thy ptp scr E l Skip_ a v
  1527 	   | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
  1528   else nstep_up thy ptp scr E l Skip_ a v
  1529 
  1530 (* val (scr, l) = (Script sc, up);
  1531    *)
  1532   | nxt_up thy ptp scr E l ay (Const ("If",_) $ _ $ _ $ _) a v = 
  1533     nstep_up thy ptp scr E l ay a v
  1534 
  1535   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
  1536   (Const ("Script.Repeat"(*1*),T) $ e $ _) a v =
  1537     (case appy thy ptp (*upd_env*) E (*a,v)*) ((l@[L,R]):loc_) e a v  of
  1538       Appy lr => Appy lr
  1539     | Napp E => ((*tracing("### nxt_up Repeat a: ");*)
  1540 		 nstep_up thy ptp scr E l Skip_ a v)
  1541     | Skip (v,E) => ((*tracing("### nxt_up Repeat: Skip res ="^
  1542 		(Sign.string_of_term(sign_of (assoc_thy thy)) res'));*)
  1543 		    nstep_up thy ptp scr E l Skip_ a v))
  1544 
  1545   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
  1546   (Const ("Script.Repeat"(*2*),T) $ e) a v =
  1547     (case appy thy ptp (*upd_env*) E (*a,v)*) ((l@[R]):loc_) e a v  of
  1548       Appy lr => Appy lr
  1549     | Napp E => ((*tracing("### nxt_up Repeat a: ");*)
  1550 		 nstep_up thy ptp scr E l Skip_ a v)
  1551     | Skip (v,E) => ((*tracing("### nxt_up Repeat: Skip res ="^
  1552 		(Sign.string_of_term(sign_of (assoc_thy thy)) res'));*)
  1553 		    nstep_up thy ptp scr E l Skip_ a v))
  1554 (* val (thy, ptp, scr, E, l,   _,(t as Const ("Script.Try",_) $ e $ _), a, v) =
  1555        (thy, ptp, (Script sc), 
  1556 	               E, up, ay,(go up sc),                            a, v);
  1557    *)
  1558   | nxt_up thy ptp scr E l _ (*makes Napp to Skip*)
  1559   (t as Const ("Script.Try",_) $ e $ _) a v = 
  1560     ((*tracing("### nxt_up Try " ^ term2str t);*)
  1561      nstep_up thy ptp scr E l Skip_ a v )
  1562 (* val (thy, ptp, scr, E, l,   _,(t as Const ("Script.Try",_) $ e), a, v) =
  1563        (thy, ptp, (Script sc), 
  1564 	               E, up, ay,(go up sc),                        a, v);
  1565    *)
  1566   | nxt_up thy ptp scr E l _ (*makes Napp to Skip*)
  1567   (t as Const ("Script.Try"(*2*),_) $ e) a v = 
  1568     ((*tracing("### nxt_up Try " ^ term2str t);*)
  1569      nstep_up thy ptp scr E l Skip_ a v)
  1570 
  1571 
  1572   | nxt_up thy ptp scr E l ay
  1573   (Const ("Script.Or",_) $ _ $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
  1574 
  1575   | nxt_up thy ptp scr E l ay
  1576   (Const ("Script.Or",_) $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
  1577 
  1578   | nxt_up thy ptp scr E l ay
  1579   (Const ("Script.Or",_) $ _ ) a v = 
  1580     nstep_up thy ptp scr E (drop_last l) ay a v
  1581 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _ $ _ $ _), a, v) =
  1582        (thy, ptp, (Script sc), 
  1583 		       E, up, ay,(go up sc),                           a, v);
  1584    *)
  1585   | nxt_up thy ptp scr E l ay (*all has been done in (*2*) below*)
  1586   (Const ("Script.Seq"(*1*),_) $ _ $ _ $ _) a v =
  1587     nstep_up thy ptp scr E l ay a v
  1588 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _ $ e2), a, v) =
  1589        (thy, ptp, (Script sc), 
  1590 		       E, up, ay,(go up sc),                        a, v);
  1591    *)
  1592   | nxt_up thy ptp scr E l ay (*comes from e2*)
  1593 	   (Const ("Script.Seq"(*2*),_) $ _ $ e2) a v =
  1594     nstep_up thy ptp scr E l ay a v
  1595 (* val (thy, ptp, scr, E, l, ay, (Const ("Script.Seq",_) $ _), a, v) =
  1596        (thy, ptp, (Script sc), 
  1597 		       E, up, ay,(go up sc),                   a, v);
  1598    *)
  1599   | nxt_up thy ptp (scr as Script sc) E l ay (*comes from e1*)
  1600 	   (Const ("Script.Seq",_) $ _) a v = 
  1601     if ay = Napp_
  1602     then nstep_up thy ptp scr E (drop_last l) Napp_ a v
  1603     else (*Skip_*)
  1604 	let val up = drop_last l;
  1605 	    val Const ("Script.Seq"(*2*),_) $ _ $ e2 = go up sc;
  1606 	in case appy thy ptp E (up@[R]) e2 a v  of
  1607 	    Appy lr => Appy lr
  1608 	  | Napp E => nstep_up thy ptp scr E up Napp_ a v
  1609 	  | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v end
  1610 
  1611   | nxt_up (thy,_) ptp scr E l ay t a v =
  1612     error ("nxt_up not impl for " ^ term2str t)
  1613 
  1614 (* val (thy, ptp, (Script sc), E, l, ay,    a, v)=
  1615        (thy, ptp, scr,         E, l, Skip_, a, v);
  1616    val (thy, ptp, (Script sc), E, l, ay,    a, v)=
  1617        (thy, ptp, sc,          E, l, Skip_, a, v);
  1618    *)
  1619 and nstep_up thy ptp (Script sc) E l ay a v = 
  1620   ((*tracing ("### nstep_up from: " ^ (loc_2str l));
  1621    tracing ("### nstep_up from: " ^ term2str (go l sc));*)
  1622    if 1 < length l
  1623    then 
  1624        let 
  1625 	   val up = drop_last l; 
  1626        in ((*tracing("### nstep_up to: " ^ term2str (go up sc));*)
  1627 	   nxt_up thy ptp (Script sc) E up ay (go up sc) a v ) end
  1628    else (*interpreted to end*)
  1629        if ay = Skip_ then Skip (v, E) else Napp E 
  1630 );
  1631 
  1632 (* decide for the next applicable stac in the script;
  1633    returns (stactic, value) - the value in case the script is finished 
  1634    12.8.02:         ~~~~~ and no assumptions ??? FIXME ???
  1635    20.8.02: must return p in case of finished, because the next script
  1636             consulted need not be the calling script:
  1637             in case of detail ie. _inserted_ PrfObjs, the next stac
  1638             has to searched in a script with PblObj.status<>Complete !
  1639             (.. not true for other details ..PrfObj ??????????????????
  1640    20.8.02: do NOT return safe (is only changed in locate !!!)
  1641 *)
  1642 fun next_tac (thy,_) (pt,p) (Rfuns {next_rule,...}) (RrlsState(f,f',rss,_), ctxt) =
  1643       let val ctxt = get_ctxt pt p
  1644       in
  1645         if f = f'
  1646         then (End_Detail' (f',[])(*8.6.03*), (Uistate, ctxt), 
  1647   		    (f', Sundef(*FIXME is no value of next_tac! vor 8.6.03*)))  (*finished*)
  1648         else
  1649           (case next_rule rss f of
  1650   	         NONE => (Empty_Tac_, (Uistate, ctxt), (e_term, Sundef))  (*helpless*)
  1651   	       | SOME (Thm (id,thm))(*8.6.03: muss auch f' liefern ?!!*) => 
  1652   	          (Rewrite' (thy, "e_rew_ord", e_rls,(*!?!8.6.03*) false,
  1653   			       (id, string_of_thmI thm), f,(e_term,[(*!?!8.6.03*)])),
  1654   	           (Uistate, ctxt), (e_term, Sundef)))                    (*next stac*)
  1655       end
  1656   | next_tac thy (ptp as (pt,pos as (p,_)):ptree * pos') (sc as Script (h $ body)) 
  1657 	  (ScrState (E,l,a,v,s,b), ctxt) =
  1658       let val ctxt = get_ctxt pt pos
  1659       in
  1660         (case if l = [] 
  1661               then appy thy ptp E [R] body NONE v
  1662               else nstep_up thy ptp sc E l Skip_ a v of
  1663             Skip (v, _) =>                                            (*finished*)
  1664               (case par_pbl_det pt p of
  1665 	               (true, p', _) => 
  1666 	                  let val (_,pblID,_) = get_obj g_spec pt p';
  1667 	                  in (Check_Postcond' (pblID, (v, [(*8.6.03 NO asms???*)])), 
  1668 	                    (e_istate, ctxt), (v,s)) 
  1669                     end
  1670 	             | (_, p', rls') => 
  1671                    (End_Detail' (e_term,[])(*8.6.03*), (e_istate, ctxt), (v,s)))
  1672          | Napp _ => (Empty_Tac_, (e_istate, ctxt), (e_term, Sundef)) (*helpless*)
  1673          | Appy (m', scrst as (_,_,_,v,_,_)) => 
  1674              (m', (ScrState scrst, ctxt), (v, Sundef)))               (*next stac*)
  1675       end
  1676   | next_tac _ _ _ (is, _) = error ("next_tac: not impl for " ^ (istate2str is));
  1677 
  1678 
  1679 (*.create the initial interpreter state from the items of the guard.*)
  1680 fun init_scrstate thy itms metID =
  1681   let
  1682     val actuals = itms2args thy metID itms;
  1683 	  val scr as Script sc = (#scr o get_met) metID;
  1684     val formals = formal_args sc
  1685 	  (*expects same sequence of (actual) args in itms and (formal) args in met*)
  1686 	  fun relate_args env [] [] = env
  1687 	    | relate_args env _ [] = 
  1688 	        error ("ERROR in creating the environment for '" ^
  1689 			    id_of_scr sc ^ "' from \nthe items of the guard of " ^
  1690 			    metID2str metID ^ ",\n" ^
  1691 			    "formal arg(s), from the script, miss actual arg(s), from the guards env:\n" ^
  1692 			    (string_of_int o length) formals ^
  1693 			    " formals: " ^ terms2str formals ^ "\n" ^
  1694 			    (string_of_int o length) actuals ^
  1695 			    " actuals: " ^ terms2str actuals)
  1696 	    | relate_args env [] actual_finds = env (*may drop Find!*)
  1697 	    | relate_args env (a::aa) (f::ff) = 
  1698 	        if type_of a = type_of f 
  1699 	        then relate_args (env @ [(a, f)]) aa ff
  1700           else 
  1701 	          error ("ERROR in creating the environment for '" ^
  1702 			      id_of_scr sc ^ "' from \nthe items of the guard of " ^
  1703 			      metID2str metID ^ ",\n" ^
  1704 			      "different types of formal arg, from the script, " ^
  1705 			      "and actual arg, from the guards env:'\n" ^
  1706 			      "formal: '" ^ term2str a ^ "::" ^ (type2str o type_of) a ^ "'\n" ^
  1707 			      "actual: '" ^ term2str f ^ "::" ^ (type2str o type_of) f ^ "'\n" ^
  1708 			      "in\n" ^
  1709 			      "formals: " ^ terms2str formals ^ "\n" ^
  1710 			      "actuals: " ^ terms2str actuals)
  1711      val env = relate_args [] formals actuals;
  1712    in (ScrState (env,[],NONE,e_term,Safe,true), (*FIXME.WN170511 remove*)e_ctxt, scr):istate * Proof.context * scr end;
  1713 
  1714 (* decide, where to get script/istate from:
  1715    (*1*) from PblObj.env: at begin of script if no init_form
  1716    (*2*) from PblObj/PrfObj: if stac is in the middle of the script
  1717    (*3*) from rls/PrfObj: in case of detail a ruleset *)
  1718 fun from_pblobj_or_detail' thy' (p,p_) pt =
  1719   let val ctxt = get_ctxt pt (p,p_)
  1720     in
  1721     if member op = [Pbl,Met] p_
  1722     then case get_obj g_env pt p of
  1723   	       NONE => error "from_pblobj_or_detail': no istate"
  1724   	     | SOME is =>
  1725   	         let
  1726                val metID = get_obj g_metID pt p
  1727   		         val {srls,...} = get_met metID
  1728   	         in (srls, is, (#scr o get_met) metID) end
  1729     else
  1730       let val (pbl,p',rls') = par_pbl_det pt p
  1731       in if pbl 
  1732          then                                                    (*2*)
  1733   	       let
  1734              val thy = assoc_thy thy'
  1735   	         val PblObj{meth=itms,...} = get_obj I pt p'
  1736 	           val metID = get_obj g_metID pt p'
  1737 	           val {srls,...} = get_met metID
  1738 	         in (*if last_elem p = 0 nothing written to pt yet*)
  1739 	           (srls, get_loc pt (p,p_), (#scr o get_met) metID)
  1740 	         end
  1741          else                                                    (*3*)
  1742 	         (e_rls, (*FIXME.WN0?: get from pbl or met !!! unused for Rrls in locate_gen, next_tac*)
  1743 	          get_loc pt (p,p_),
  1744 	            case rls' of
  1745 	  	          Rls {scr=scr,...} => scr
  1746 	            | Seq {scr=scr,...} => scr
  1747 	            | Rrls {scr=rfuns,...} => rfuns)
  1748     end
  1749   end;
  1750 
  1751 (*.get script and istate from PblObj, see                        (*1*) above.*)
  1752 fun from_pblobj' thy' (p,p_) pt =
  1753     let val p' = par_pblobj pt p
  1754 	val thy = assoc_thy thy'
  1755 	val PblObj{meth=itms,...} = get_obj I pt p'
  1756 	val metID = get_obj g_metID pt p'
  1757 	val {srls,scr,...} = get_met metID
  1758     in if last_elem p = 0 (*nothing written to pt yet*)
  1759        then let val (is, ctxt, scr) = init_scrstate thy itms metID
  1760 	    in (srls, (is, ctxt), scr) end
  1761        else (srls, get_loc pt (p,p_), scr)
  1762     end;
  1763     
  1764 (*.get the stactics and problems of a script as tacs
  1765   instantiated with the current environment;
  1766   l is the location which generated the given formula.*)
  1767 (*WN.12.5.03: quick-and-dirty repair for listexpressions*)
  1768 fun is_spec_pos Pbl = true
  1769   | is_spec_pos Met = true
  1770   | is_spec_pos _ = false;
  1771 
  1772 (*. fetch _all_ tactics from script .*)
  1773 fun sel_rules _ (([],Res):pos') = 
  1774     raise PTREE "no tactics applicable at the end of a calculation"
  1775 | sel_rules pt (p,p_) =
  1776   if is_spec_pos p_ 
  1777   then [get_obj g_tac pt p]
  1778   else
  1779     let val pp = par_pblobj pt p;
  1780 	val thy' = (get_obj g_domID pt pp):theory';
  1781 	val thy = assoc_thy thy';
  1782 	val metID = get_obj g_metID pt pp;
  1783 	val metID' =if metID =e_metID then(thd3 o snd3)(get_obj g_origin pt pp)
  1784 		     else metID
  1785 	val {scr=Script sc,srls,...} = get_met metID'
  1786 	val ScrState (env,_,a,v,_,_) = get_istate pt (p,p_);
  1787     in map ((stac2tac pt thy) o rep_stacexpr o #2 o
  1788 	    (handle_leaf "selrul" thy' srls env a v)) (stacpbls sc) end;
  1789 (*
  1790 > val Script sc = (#scr o get_met) ("SqRoot","sqrt-equ-test");
  1791 > val env = [((term_of o the o (parse (Thy_Info.get_theory "Isac"))) "bdv",
  1792              (term_of o the o (parse (Thy_Info.get_theory "Isac"))) "x")];
  1793 > map ((stac2tac pt thy) o #2 o(subst_stacexpr env NONE e_term)) (stacpbls sc);
  1794 *)
  1795 
  1796 
  1797 (*. fetch tactics from script and filter _applicable_ tactics;
  1798     in case of Rewrite_Set* go down to _atomic_ rewrite-tactics .*)
  1799 fun sel_appl_atomic_tacs _ (([],Res):pos') = 
  1800     raise PTREE "no tactics applicable at the end of a calculation"
  1801   | sel_appl_atomic_tacs pt (p,p_) =
  1802     if is_spec_pos p_ 
  1803     then [get_obj g_tac pt p]
  1804     else
  1805 	let val pp = par_pblobj pt p
  1806 	    val thy' = (get_obj g_domID pt pp):theory'
  1807 	    val thy = assoc_thy thy'
  1808 	    val metID = get_obj g_metID pt pp
  1809 	    val metID' =if metID = e_metID 
  1810 			then (thd3 o snd3) (get_obj g_origin pt pp)
  1811 			else metID
  1812 	    val {scr=Script sc,srls,erls,rew_ord'=ro,...} = get_met metID'
  1813 	    val ScrState (env,_,a,v,_,_) = get_istate pt (p,p_)
  1814 	    val alltacs = (*we expect at least 1 stac in a script*)
  1815 		map ((stac2tac pt thy) o rep_stacexpr o #2 o
  1816 		     (handle_leaf "selrul" thy' srls env a v)) (stacpbls sc)
  1817 	    val f = case p_ of
  1818 			Frm => get_obj g_form pt p
  1819 		      | Res => (fst o (get_obj g_result pt)) p
  1820 	(*WN071231 ? replace atomic_appl_tacs with applicable_in (ineff!) ?*)
  1821 	in (distinct o flat o 
  1822 	    (map (atomic_appl_tacs thy ro erls f))) alltacs end;
  1823 	
  1824 
  1825 (*
  1826 end
  1827 open Interpreter;
  1828 *)
  1829 
  1830 (* use"ME/script.sml";
  1831    use"script.sml";
  1832    *)