src/Tools/isac/ME/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Fri, 20 Aug 2010 12:25:37 +0200
branchisac-update-Isa09-2
changeset 37934 56f10b13005e
parent 37933 b65c6037eb6d
child 37935 27d365c3dd31
permissions -rw-r--r--
finished update ME/calchead.sml + pushed updates over all sml+test

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