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