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