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