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