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