src/Tools/isac/Interpret/script.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Thu, 20 Oct 2016 10:26:29 +0200
changeset 59253 f0bb15a046ae
parent 59252 7d3dbc1171ff
child 59257 a1daf71787b1
permissions -rw-r--r--
simplify handling of theorems

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