src/Tools/isac/Interpret/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Wed, 11 May 2011 16:51:30 +0200
branchdecompose-isar
changeset 41983 4c49adbfadab
parent 41972 22c5483e9bfb
child 41984 3f614796186e
permissions -rw-r--r--
intermed. ctxt ..: added ctxt to Subproblem'

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