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