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