src/Tools/isac/Interpret/script.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Fri, 02 Mar 2018 14:19:59 +0100
changeset 59389 627d25067f2f
parent 59380 8b08d9296654
child 59390 f6374c995ac5
permissions -rw-r--r--
separate structure TermC : TERMC
     1 (* Title:  interpreter for scripts
     2    Author: Walther Neuper 2000
     3    (c) due to copyright terms
     4 *)
     5 
     6 signature LUCAS_INTERPRETER =
     7 sig
     8 
     9   type step = Tac.tac_ * Generate.mout * Ctree.ctree * Ctree.pos' * Ctree.pos' list
    10   datatype locate = NotLocatable | Steps of Selem.istate * step list
    11   
    12   val next_tac : (*diss: next-tactic-function*)
    13     theory' * rls -> Ctree.state -> scr -> Selem.istate * 'a -> Tac.tac_ * (Selem.istate * 'a) * (term * Selem.safe)
    14   val locate_gen : (*diss: locate-function*)
    15     theory' * rls -> Tac.tac_ -> Ctree.state -> scr * 'a -> Selem.istate * Proof.context -> locate
    16                          
    17 (* can these functions be local to Lucin or part of LItools ? *)
    18   val sel_rules : Ctree.ctree -> Ctree.pos' -> Tac.tac list 
    19   val init_form : 'a -> scr -> (term * term) list -> term option
    20   val tac_2tac : Tac.tac_ -> Tac.tac
    21   val init_scrstate : theory -> Model.itm list -> metID -> Selem.istate * Proof.context * scr
    22   val from_pblobj' : theory' -> Ctree.pos' -> Ctree.ctree -> rls * (Selem.istate * Proof.context) * scr
    23   val from_pblobj_or_detail' : theory' -> Ctree.pos' -> Ctree.ctree -> 
    24     rls * (Selem.istate * Proof.context) * scr
    25   val rule2thm'' : rule -> thm''
    26   val rule2rls' : rule -> string
    27 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
    28   val sel_appl_atomic_tacs : Ctree.ctree -> Ctree.pos' -> Tac.tac list
    29 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
    30   datatype asap = Aundef | AssOnly | AssGen
    31   datatype appy = Appy of Tac.tac_ * Selem.scrstate | Napp of LTool.env | Skip of term * LTool.env
    32   datatype appy_ = Napp_ | Skip_
    33   val appy : theory' * rls -> Ctree.state -> LTool.env -> lrd list -> term -> term option -> term -> appy
    34   val formal_args : term -> term list
    35   val get_stac : 'a -> term -> term option 
    36   val go : loc_ -> term -> term
    37   val handle_leaf : string -> theory' -> rls -> LTool.env -> term option -> term -> term -> 
    38     term option * LTool.stacexpr
    39   val id_of_scr : term -> string
    40    val is_spec_pos : Ctree.pos_ -> bool
    41   val itms2args : 'a -> metID -> Model.itm list -> term list
    42   val nstep_up : theory' * rls -> Ctree.state -> scr -> LTool.env -> lrd list -> appy_ -> 
    43     term option -> term -> appy
    44   val stac2tac : Ctree.ctree -> theory -> term -> Tac.tac
    45   val stac2tac_ : Ctree.ctree -> theory -> term -> Tac.tac * Tac.tac_
    46   val upd_env_opt : LTool.env -> term option * term -> LTool.env
    47 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
    48 
    49 (*----- unused code, kept as hints to design ideas ---------------------------------------------*)
    50   type assoc
    51   val assoc2str : assoc -> string
    52 end 
    53 
    54 (* traces the leaves (ie. non-tactical nodes) of Prog found by next_tac, see "and scr" *)   
    55 val trace_script = Unsynchronized.ref false; (* TODO: how are traces done in Isabelle? *)
    56 
    57 structure Lucin(**): LUCAS_INTERPRETER(**) =
    58 struct
    59 open Ctree
    60 
    61 (**)
    62 (* data for creating a new node in ctree; designed for use as:
    63    fun ass* scrstate steps = / ... case ass* scrstate steps of /
    64    Assoc (scrstate, steps) => ... ass* scrstate steps *)
    65 type step =
    66     Tac.tac_        (*transformed from associated tac                   *)
    67     * Generate.mout (*result with indentation etc.                      *)
    68     * ctree         (*containing node created by tac_ + resp. scrstate  *)
    69     * pos'          (*position in ctree; ctree * pos' is the proofstate *)
    70     * pos' list;    (*of ctree-nodes probably cut (by fst tac_)         *)
    71 
    72 fun rule2thm'' (Thm (id, thm)) = (id, thm) : thm''
    73   | rule2thm'' r = error ("rule2thm': not defined for " ^ rule2str r);
    74 fun rule2rls' (Rls_ rls) = id_rls rls
    75   | rule2rls' r = error ("rule2rls': not defined for " ^ rule2str r);
    76 
    77 (*.makes a (rule,term) list to a Step (m, mout, pt', p', cid) for solve;
    78    complicated with current t in rrlsstate.*)
    79 fun rts2steps steps ((pt, p), (f, f'', rss, rts), (thy', ro, er, pa)) [(r, (f', am))] =
    80       let
    81         val thy = assoc_thy thy'
    82         val ctxt = get_ctxt pt p |> Stool.insert_assumptions am
    83 	      val m = Tac.Rewrite' (thy', ro, er, pa, rule2thm'' r, f, (f', am))
    84 	      val is = Selem.RrlsState (f', f'', rss, rts)
    85 	      val p = case p of (_, Frm) => p | (p', Res) => (lev_on p', Res) | _ => error "rts2steps: p1"
    86 	      val (p', cid, mout, pt') = Generate.generate1 thy m (is, ctxt) p pt
    87       in (is, (m, mout, pt', p', cid) :: steps) end
    88   | rts2steps steps ((pt, p) ,(f, f'', rss, rts), (thy', ro, er, pa)) ((r, (f', am)) :: rts') =
    89       let
    90         val thy = assoc_thy thy'
    91         val ctxt = get_ctxt pt p |> Stool.insert_assumptions am
    92 	      val m = Tac.Rewrite' (thy', ro, er, pa, rule2thm'' r, f, (f', am))
    93 	      val is = Selem.RrlsState (f', f'', rss, rts)
    94 	      val p = case p of (_, Frm) => p | (p', Res) => (lev_on p', Res) | _ => error "rts2steps: p1"
    95 	      val (p', cid, mout, pt') = Generate.generate1 thy m (is, ctxt) p pt
    96       in rts2steps ((m, mout, pt', p', cid)::steps) 
    97 		    ((pt', p'), (f', f'', rss, rts), (thy', ro, er, pa)) rts'
    98 		  end
    99   | rts2steps _ _ _ = error "rts2steps: uncovered fun-def"
   100 
   101 (* functions for the environment stack: NOT YET IMPLEMENTED
   102 fun accessenv id es = the (assoc ((top es) : LTool.env, id))
   103     handle _ => error ("accessenv: " ^ free2str id ^ " not in LTool.env");
   104 fun updateenv id vl (es : LTool.env stack) = 
   105     (push (overwrite(top es, (id, vl))) (pop es)) : LTool.env stack;
   106 fun pushenv id vl (es : LTool.env stack) = 
   107     (push (overwrite(top es, (id, vl))) es) : LTool.env stack;
   108 val popenv = pop : LTool.env stack -> LTool.env stack;
   109 *)
   110 
   111 fun de_esc_underscore str =
   112   let
   113     fun scan [] = []
   114     | scan (s :: ss) = if s = "'" then (scan ss) else (s :: (scan ss))
   115   in (implode o scan o Symbol.explode) str end;
   116 
   117 (*go at a location in a script and fetch the contents*)
   118 fun go [] t = t
   119   | go (D::p) (Abs(_, _, t0)) = go (p : loc_) t0
   120   | go (L::p) (t1 $ _) = go p t1
   121   | go (R::p) (_ $ t2) = go p t2
   122   | go l _ = error ("go: no " ^ loc_2str l);
   123 
   124 (*.get argument of first stactic in a script for init_form.*)
   125 fun get_stac thy (_ $ body) =
   126   let
   127     fun get_t y (Const ("Script.Seq",_) $ e1 $ e2) a = 
   128     	  (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   129       | get_t y (Const ("Script.Seq",_) $ e1 $ e2 $ a) _ = 
   130     	  (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   131       | get_t y (Const ("Script.Try",_) $ e) a = get_t y e a
   132       | get_t y (Const ("Script.Try",_) $ e $ a) _ = get_t y e a
   133       | get_t y (Const ("Script.Repeat",_) $ e) a = get_t y e a
   134       | get_t y (Const ("Script.Repeat",_) $ e $ a) _ = get_t y e a
   135       | get_t y (Const ("Script.Or",_) $e1 $ e2) a =
   136     	  (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   137       | get_t y (Const ("Script.Or",_) $e1 $ e2 $ a) _ =
   138     	  (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   139       | get_t y (Const ("Script.While",_) $ _ $ e) a = get_t y e a
   140       | get_t y (Const ("Script.While",_) $ _ $ e $ a) _ = get_t y e a
   141       | get_t y (Const ("Script.Letpar",_) $ e1 $ Abs (_, _, e2)) a = 
   142     	  (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   143     (*| get_t y (Const ("HOL.Let",_) $ e1 $ Abs (_,_,e2)) a =
   144 	      (case get_t y e1 a of NONE => get_t y e2 a | la => la)
   145       | get_t y (Abs (_,_,e)) a = get_t y e a*)
   146       | get_t y (Const ("HOL.Let",_) $ e1 $ Abs (_, _, _)) a =
   147     	get_t y e1 a (*don't go deeper without evaluation !*)
   148       | get_t _ (Const ("If", _) $ _ $ _ $ _) _ = NONE
   149     	(*(case get_t y e1 a of NONE => get_t y e2 a | la => la)*)
   150     
   151       | get_t _ (Const ("Script.Rewrite",_) $ _ $ _ $ a) _ = SOME a
   152       | get_t _ (Const ("Script.Rewrite",_) $ _ $ _    ) a = SOME a
   153       | get_t _ (Const ("Script.Rewrite'_Inst",_) $ _ $ _ $ _ $ a) _ = SOME a
   154       | get_t _ (Const ("Script.Rewrite'_Inst",_) $ _ $ _ $ _ )    a = SOME a
   155       | get_t _ (Const ("Script.Rewrite'_Set",_) $ _ $ _ $ a) _ = SOME a
   156       | get_t _ (Const ("Script.Rewrite'_Set",_) $ _ $ _ )    a = SOME a
   157       | get_t _ (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ _ $ _ $a)_ =SOME a
   158       | get_t _ (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ _ $ _ )  a =SOME a
   159       | get_t _ (Const ("Script.Calculate",_) $ _ $ a) _ = SOME a
   160       | get_t _ (Const ("Script.Calculate",_) $ _ )    a = SOME a
   161     
   162       | get_t _ (Const ("Script.Substitute",_) $ _ $ a) _ = SOME a
   163       | get_t _ (Const ("Script.Substitute",_) $ _ )    a = SOME a
   164     
   165       | get_t _ (Const ("Script.SubProblem",_) $ _ $ _) _ = NONE
   166 
   167       | get_t _ _ _ = ((*tracing ("### get_t yac: list-expr "^(term2str x));*) NONE)
   168     in get_t thy body e_term end
   169   | get_stac _ t = error ("get_stac: no fun-def. for " ^ term2str t);
   170     
   171 fun init_form thy (Prog sc) env =
   172     (case get_stac thy sc of NONE => NONE | SOME stac => SOME (subst_atomic env stac))
   173   | init_form _ _ _ = error "init_form: no match";
   174 
   175 (* get the arguments of the script out of the scripts parsetree *)
   176 fun formal_args scr = (fst o split_last o snd o strip_comb) scr;
   177 
   178 (* get the identifier of the script out of the scripts parsetree *)
   179 fun id_of_scr sc = (id_of o fst o strip_comb) sc;
   180 
   181 (*WN020526: not clear, when a is available in ass_up for eval_true*)
   182 (*WN060906: in "fun handle_leaf" eg. uses "SOME M__"(from some PREVIOUS
   183   curried Rewrite) for CURRENT value (which may be different from PREVIOUS);
   184   thus "NONE" must be set at the end of currying (ill designed anyway)*)
   185 fun upd_env_opt env (SOME a, v) = LTool.upd_env env (a, v)
   186   | upd_env_opt env (NONE, _) = 
   187       ((*tracing ("*** upd_env_opt: (NONE," ^ term2str v ^ ")");*) env);
   188 
   189 type dsc = typ; (* <-> nam..unknow in Descript.thy *)
   190 
   191 (*.create the actual parameters (args) of script: their order 
   192   is given by the order in met.pat .*)
   193 (*WN.5.5.03: ?: does this allow for different descriptions ???
   194              ?: why not taken from formal args of script ???
   195 !: FIXXXME penv: push it here in itms2args into script-evaluation*)
   196 (* val (thy, mI, itms) = (thy, metID, itms);
   197    *)
   198 val errmsg = "ERROR: the guard is missing (#ppc in 'type met' added in prep_met)."
   199 fun itms2args _ mI itms =
   200   let
   201     val mvat = Model.max_vt itms
   202     fun okv mvat (_, vats, b, _, _) = member op = vats mvat andalso b
   203     val itms = filter (okv mvat) itms
   204     fun test_dsc d (_, _, _, _, itm_) = (d = Model.d_in itm_)
   205     fun itm2arg itms (_,(d,_)) =
   206         case find_first (test_dsc d) itms of
   207           NONE => error ("itms2args: '" ^ term2str d ^ "' not in itms")
   208         | SOME (_, _, _, _, itm_) => Model.penvval_in itm_
   209       (*| SOME (_,_,_,_,itm_) => mk_arg thy (Model.d_in itm_) (ts_in itm_);
   210             penv postponed; presently penv holds already LTool.env for script*)
   211     val pats = (#ppc o Specify.get_met) mI
   212     val _ = if pats = [] then raise ERROR errmsg else ()
   213   in (flat o (map (itm2arg itms))) pats end;
   214 
   215 (* convert a script-tac 'stac' to a tactic 'tac';
   216    if stac is an initac, then convert to a 'tac_' (as required in appy).
   217    arg ctree for pushing the thy specified in rootpbl into subpbls    *)
   218 fun stac2tac_ _ thy (Const ("Script.Rewrite", _) $ Free (thmID, _) $ _ $ _) =
   219     let
   220       val tid = (de_esc_underscore o strip_thy) thmID
   221     in (Tac.Rewrite (tid, Rewrite.assoc_thm'' thy tid), Tac.Empty_Tac_) end
   222   | stac2tac_ _ thy (Const ("Script.Rewrite'_Inst", _) $ sub $ Free (thmID, _) $ _ $ _) =
   223     let
   224       val subML = ((map TermC.isapair2pair) o TermC.isalist2list) sub
   225       val subStr = Selem.subst2subs subML
   226       val tid = (de_esc_underscore o strip_thy) thmID (*4.10.02 unnoetig*)
   227     in (Tac.Rewrite_Inst (subStr, (tid, Rewrite.assoc_thm'' thy tid)), Tac.Empty_Tac_) end
   228   | stac2tac_ _ _ (Const ("Script.Rewrite'_Set",_) $ Free (rls, _) $ _ $ _) =
   229      (Tac.Rewrite_Set ((de_esc_underscore o strip_thy) rls), Tac.Empty_Tac_)
   230   | stac2tac_ _ _ (Const ("Script.Rewrite'_Set'_Inst", _) $ sub $ Free (rls, _) $ _ $ _) =
   231     let
   232       val subML = ((map TermC.isapair2pair) o TermC.isalist2list) sub;
   233       val subStr = Selem.subst2subs subML;
   234     in (Tac.Rewrite_Set_Inst (subStr, rls), Tac.Empty_Tac_) end
   235   | stac2tac_ _ _ (Const ("Script.Calculate", _) $ Free (op_, _) $ _) = (Tac.Calculate op_, Tac.Empty_Tac_)
   236   | stac2tac_ _ _ (Const ("Script.Take", _) $ t) = (Tac.Take (term2str t), Tac.Empty_Tac_)
   237   | stac2tac_ _ _ (Const ("Script.Substitute", _) $ isasub $ _) =
   238     (Tac.Substitute ((Selem.subte2sube o TermC.isalist2list) isasub), Tac.Empty_Tac_)
   239   | stac2tac_ _ thy (Const("Script.Check'_elementwise", _) $ _ $ 
   240     (Const ("Set.Collect", _) $ Abs (_, _, pred))) =
   241       (Tac.Check_elementwise (term_to_string''' thy pred), Tac.Empty_Tac_)
   242   | stac2tac_ _ _ (Const("Script.Or'_to'_List", _) $ _ ) = (Tac.Or_to_List, Tac.Empty_Tac_)
   243   | stac2tac_ _ _ (Const ("Script.Tac", _) $ Free (str, _)) = 
   244     (Tac.Tac ((de_esc_underscore o strip_thy) str),  Tac.Empty_Tac_) 
   245 
   246     (*compare "| assod _ (Subproblem'"*)
   247   | stac2tac_ pt _ (stac as Const ("Script.SubProblem",_) $
   248 	  (Const ("Product_Type.Pair",_) $Free (dI', _) $ (Const ("Product_Type.Pair", _) $ pI' $ mI')) $ 
   249 	    ags') =
   250     let
   251       val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   252       val thy = maxthy (assoc_thy dI) (rootthy pt);
   253 	    val pI = ((map (de_esc_underscore o TermC.free2str)) o TermC.isalist2list) pI';
   254 	    val mI = ((map (de_esc_underscore o TermC.free2str)) o TermC.isalist2list) mI';
   255 	    val ags = TermC.isalist2list ags';
   256 	    val (pI, pors, mI) = 
   257 	      if mI = ["no_met"] 
   258 	      then
   259           let
   260             val pors = (Chead.match_ags thy ((#ppc o Specify.get_pbt) pI) ags)
   261 		          handle ERROR "actual args do not match formal args" 
   262 			        => (Chead.match_ags_msg pI stac ags(*raise exn*); [])
   263 		        val pI' = Specify.refine_ori' pors pI;
   264 		      in (pI', pors (* refinement over models with diff.prec only *), 
   265 		          (hd o #met o Specify.get_pbt) pI') end
   266 	      else (pI, (Chead.match_ags thy ((#ppc o Specify.get_pbt) pI) ags)
   267 		      handle ERROR "actual args do not match formal args"
   268 		      => (Chead.match_ags_msg pI stac ags(*raise exn*); []), mI);
   269       val (fmz_, vals) = Chead.oris2fmz_vals pors;
   270 	    val {cas,ppc,thy,...} = Specify.get_pbt pI
   271 	    val dI = theory2theory' thy (*.take dI from _refined_ pbl.*)
   272 	    val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt));
   273       val ctxt = dI |> Thy_Info_get_theory |> Proof_Context.init_global |> Stool.declare_constraints' vals
   274 	    val hdl =
   275         case cas of
   276 		      NONE => LTool.pblterm dI pI
   277 		    | SOME t => subst_atomic ((Chead.vars_of_pbl_' ppc) ~~~ vals) t
   278       val f = LTool.subpbl (strip_thy dI) pI
   279     in (Tac.Subproblem (dI, pI),	Tac.Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f))
   280     end
   281   | stac2tac_ _ thy t = error ("stac2tac_ TODO: no match for " ^ term_to_string''' thy t);
   282 
   283 fun stac2tac pt thy t = (fst o stac2tac_ pt thy) t;
   284 
   285 datatype ass = 
   286     Ass of
   287       Tac.tac_ *  (* SubProblem gets args instantiated in assod *)
   288   	  term        (* for itr_arg, result in ets *)
   289   | AssWeak of
   290       Tac.tac_ *
   291   	  term     (*for itr_arg,result in ets*)
   292   | NotAss;
   293 
   294 (* check if tac_ is associated with stac.
   295    Additional task: check if term t (the result has been calculated from) in tac_
   296    has been changed (see "datatype tac_"); if yes, recalculate result
   297    TODO.WN120106 recalculate impl.only for Substitute'
   298 args
   299   pt     : ctree for pushing the thy specified in rootpbl into subpbls
   300   d      : unused (planned for data for comparison)
   301   tac_   : from user (via applicable_in); to be compared with ...
   302   stac   : found in Script
   303 returns
   304   Ass    : associated: e.g. thmID in stac = thmID in m
   305                        +++ arg   in stac = arg   in m
   306   AssWeak: weakly ass.:e.g. thmID in stac = thmID in m, //arg//
   307   NotAss :             e.g. thmID in stac/=/thmID in m (not =)
   308 *)
   309 fun assod _ _ (m as Tac.Rewrite_Inst' (_, _, _, _, _, thm'' as (thmID, _), f, (f', _))) stac =
   310     (case stac of
   311 	    (Const ("Script.Rewrite'_Inst", _) $ _ $ Free (thmID_, _) $ _ $ f_) =>
   312 	      if thmID = thmID_
   313         then 
   314 	        if f = f_ 
   315           then ((*tracing"3### assod ..Ass";*) Ass (m,f')) 
   316 	        else ((*tracing"3### assod ..AssWeak";*) AssWeak(m, f'))
   317 	      else ((*tracing"3### assod ..NotAss";*) NotAss)
   318     | (Const ("Script.Rewrite'_Set'_Inst",_) $ _ $ Free (rls_, _) $ _ $ f_) =>
   319 	      if Rtools.contains_rule (Thm thm'') (assoc_rls rls_)
   320         then if f = f_ then Ass (m,f') else AssWeak (m,f')
   321 	      else NotAss
   322     | _ => NotAss)
   323   | assod _ _ (m as Tac.Rewrite' (_, _, _, _, thm'' as (thmID, _), f, (f', _))) stac =
   324     (case stac of
   325 	    (Const ("Script.Rewrite", _) $ Free (thmID_, _) $ _ $ f_) =>
   326 	      ((*tracing ("3### assod: stac = " ^ ter2str t);
   327 	       tracing ("3### assod: f(m)= " ^ term2str f);*)
   328 	      if thmID = thmID_
   329         then 
   330 	        if f = f_
   331           then ((*tracing"3### assod ..Ass";*) Ass (m,f')) 
   332 	        else 
   333             ((*tracing"### assod ..AssWeak";
   334 		         tracing("### assod: f(m)  = " ^ term2str f);
   335 		         tracing("### assod: f(stac)= " ^ term2str f_)*)
   336 		         AssWeak (m,f'))
   337 	      else ((*tracing"3### assod ..NotAss";*) NotAss))
   338     | (Const ("Script.Rewrite'_Set", _) $ Free (rls_, _) $ _ $ f_) =>
   339 	       if Rtools.contains_rule (Thm thm'') (assoc_rls rls_)
   340          then if f = f_ then Ass (m, f') else AssWeak (m, f')
   341 	       else NotAss
   342     | _ => NotAss)
   343   | assod _ _ (m as Tac.Rewrite_Set_Inst' (_, _, _, rls, f, (f', _))) 
   344       (Const ("Script.Rewrite'_Set'_Inst", _) $ _ $ Free (rls_, _) $ _ $ f_) = 
   345     if id_rls rls = rls_ 
   346     then if f = f_ then Ass (m, f') else AssWeak (m ,f')
   347     else NotAss
   348   | assod _ _ (m as Tac.Detail_Set_Inst' (_, _, _, rls, f, (f',_))) 
   349       (Const ("Script.Rewrite'_Set'_Inst", _) $ _ $ Free (rls_, _) $ _ $ f_) = 
   350     if id_rls rls = rls_
   351     then if f = f_ then Ass (m, f') else AssWeak (m, f')
   352     else NotAss
   353   | assod _ _ (m as Tac.Rewrite_Set' (_, _, rls, f, (f', _))) 
   354       (Const ("Script.Rewrite'_Set", _) $ Free (rls_, _) $ _ $ f_) = 
   355     if id_rls rls = rls_
   356     then if f = f_ then Ass (m, f') else AssWeak (m, f')
   357     else NotAss
   358   | assod _ _ (m as Tac.Detail_Set' (_, _, rls, f, (f', _))) 
   359       (Const ("Script.Rewrite'_Set", _) $ Free (rls_, _) $ _ $ f_) = 
   360     if id_rls rls = rls_
   361     then if f = f_ then Ass (m, f') else AssWeak (m, f')
   362     else NotAss
   363   | assod _ _ (m as Tac.Calculate' (_, op_, f, (f', _))) stac =
   364     (case stac of
   365 	    (Const ("Script.Calculate",_) $ Free (op__,_) $ f_) =>
   366 	      if op_ = op__
   367         then if f = f_ then Ass (m, f') else AssWeak (m, f')
   368 	      else NotAss
   369     | (Const ("Script.Rewrite'_Set'_Inst", _) $ _ $ Free(rls_,_) $_$f_)  =>
   370         let val thy = assoc_thy "Isac";
   371         in
   372           if Rtools.contains_rule (Calc (assoc_calc' thy op_ |> snd)) (assoc_rls rls_)
   373           then if f = f_ then Ass (m, f') else AssWeak (m, f')
   374           else NotAss
   375         end
   376     | (Const ("Script.Rewrite'_Set",_) $ Free (rls_, _) $ _ $ f_) =>
   377         let val thy = assoc_thy "Isac";
   378         in
   379           if Rtools.contains_rule (Calc (assoc_calc' thy op_ |> snd)) (assoc_rls rls_)
   380           then if f = f_ then Ass (m,f') else AssWeak (m,f')
   381           else NotAss
   382         end
   383     | _ => NotAss)
   384   | assod _ _ (m as Tac.Check_elementwise' (consts, _, (consts_chkd, _)))
   385       (Const ("Script.Check'_elementwise",_) $ consts' $ _) =
   386     if consts = consts'
   387     then Ass (m, consts_chkd)
   388     else NotAss
   389   | assod _ _ (m as Tac.Or_to_List' (_, list)) (Const ("Script.Or'_to'_List", _) $ _) = Ass (m, list) 
   390   | assod _ _ (m as Tac.Take' term) (Const ("Script.Take", _) $ _) = Ass (m, term)
   391   | assod _ _ (m as Tac.Substitute' (ro, erls, subte, f, f')) (Const ("Script.Substitute", _) $ _ $ t) =
   392 	  if f = t then Ass (m, f')
   393 	  else (*compare | applicable_in (p,p_) pt (m as Substitute sube)*)
   394 		  if foldl and_ (true, map TermC.contains_Var subte)
   395 		  then
   396 		    let val t' = subst_atomic (map HOLogic.dest_eq subte (*TODO subte2subst*)) t
   397 		    in if t = t' then error "assod: Substitute' not applicable to val of Expr"
   398 		       else Ass (Tac.Substitute' (ro, erls, subte, t, t'), t')
   399 		    end
   400 		  else (case Rewrite.rewrite_terms_ (Isac()) ro erls subte t of
   401 		         SOME (t', _) =>  Ass (Tac.Substitute' (ro, erls, subte, t, t'), t')
   402 		       | NONE => error "assod: Substitute' not applicable to val of Expr")
   403   | assod _ _ (m as Tac.Tac_ (thy, _, id, f')) (Const ("Script.Tac",_) $ Free (id', _)) =
   404     if id = id'
   405     then Ass (m, ((Thm.term_of o the o (TermC.parse thy)) f'))
   406     else NotAss
   407 
   408     (*compare "| stac2tac_ thy (Const ("Script.SubProblem",_)"*)
   409   | assod pt _ (Tac.Subproblem' ((domID, pblID, _), _, _, _, _, _))
   410 	    (stac as Const ("Script.SubProblem",_) $ (Const ("Product_Type.Pair",_) $
   411 		    Free (dI',_) $ (Const ("Product_Type.Pair",_) $ pI' $ mI')) $ ags') =
   412     let 
   413       val dI = ((implode o drop_last(*.."'"*) o Symbol.explode) dI')(*^""*);
   414       val thy = maxthy (assoc_thy dI) (rootthy pt);
   415 	    val pI = ((map (de_esc_underscore o TermC.free2str)) o TermC.isalist2list) pI';
   416 	    val mI = ((map (de_esc_underscore o TermC.free2str)) o TermC.isalist2list) mI';
   417 	    val ags = TermC.isalist2list ags';
   418 	    val (pI, pors, mI) = 
   419 	      if mI = ["no_met"] 
   420 	      then
   421           let
   422             val pors = (Chead.match_ags thy ((#ppc o Specify.get_pbt) pI) ags)
   423 		          handle ERROR "actual args do not match formal args"
   424 			          => (Chead.match_ags_msg pI stac ags(*raise exn*);[]);
   425 		        val pI' = Specify.refine_ori' pors pI;
   426 		      in (pI', pors (*refinement over models with diff.prec only*), (hd o #met o Specify.get_pbt) pI')
   427           end
   428 	      else (pI, (Chead.match_ags thy ((#ppc o Specify.get_pbt) pI) ags)
   429 		      handle ERROR "actual args do not match formal args"
   430 		      => (Chead.match_ags_msg pI stac ags(*raise exn*); []), mI);
   431       val (fmz_, vals) = Chead.oris2fmz_vals pors;
   432 	    val {cas, ppc, thy, ...} = Specify.get_pbt pI
   433 	    val dI = theory2theory' thy (*take dI from _refined_ pbl*)
   434 	    val dI = theory2theory' (maxthy (assoc_thy dI) (rootthy pt))
   435 	    val ctxt = dI |> Thy_Info_get_theory |> Proof_Context.init_global |> Stool.declare_constraints' vals
   436 	    val hdl = 
   437         case cas of
   438 		      NONE => LTool.pblterm dI pI
   439 		    | SOME t => subst_atomic ((Chead.vars_of_pbl_' ppc) ~~~ vals) t
   440       val f = LTool.subpbl (strip_thy dI) pI
   441     in 
   442       if domID = dI andalso pblID = pI
   443       then Ass (Tac.Subproblem' ((dI, pI, mI), pors, hdl, fmz_, ctxt, f), f) 
   444       else NotAss
   445     end
   446   | assod _ _ m _ = 
   447     (if (!trace_script) 
   448      then tracing("@@@ the 'tac_' proposed to apply does NOT match the leaf found in the script:\n"
   449 		   ^ "@@@ tac_ = " ^ Tac.tac_2str m)
   450      else ();
   451     NotAss);
   452 
   453 fun tac_2tac (Tac.Refine_Tacitly' (pI, _, _, _, _)) = Tac.Refine_Tacitly pI
   454   | tac_2tac (Tac.Model_Problem' (_, _, _)) = Tac.Model_Problem
   455   | tac_2tac (Tac.Add_Given' (t, _)) = Tac.Add_Given t
   456   | tac_2tac (Tac.Add_Find' (t, _)) = Tac.Add_Find t
   457   | tac_2tac (Tac.Add_Relation' (t, _)) = Tac.Add_Relation t
   458  
   459   | tac_2tac (Tac.Specify_Theory' dI) = Tac.Specify_Theory dI
   460   | tac_2tac (Tac.Specify_Problem' (dI, _)) = Tac.Specify_Problem dI
   461   | tac_2tac (Tac.Specify_Method' (dI, _, _)) = Tac.Specify_Method dI
   462   
   463   | tac_2tac (Tac.Rewrite' (_, _, _, _, thm, _, _)) = Tac.Rewrite thm
   464   | tac_2tac (Tac.Rewrite_Inst' (_, _, _, _, sub, thm, _, _)) = Tac.Rewrite_Inst (Selem.subst2subs sub, thm)
   465 
   466   | tac_2tac (Tac.Rewrite_Set' (_, _, rls, _, _)) = Tac.Rewrite_Set (id_rls rls)
   467   | tac_2tac (Tac.Detail_Set' (_, _, rls, _, _)) = Tac.Detail_Set (id_rls rls)
   468 
   469   | tac_2tac (Tac.Rewrite_Set_Inst' (_, _, sub, rls, _, _)) = 
   470     Tac.Rewrite_Set_Inst (Selem.subst2subs sub,id_rls rls)
   471   | tac_2tac (Tac.Detail_Set_Inst' (_, _, sub, rls, _, _)) = 
   472     Tac.Detail_Set_Inst (Selem.subst2subs sub,id_rls rls)
   473 
   474   | tac_2tac (Tac.Calculate' (_, op_, _, _)) = Tac.Calculate (op_)
   475   | tac_2tac (Tac.Check_elementwise' (_, pred, _)) = Tac.Check_elementwise pred
   476 
   477   | tac_2tac (Tac.Or_to_List' _) = Tac.Or_to_List
   478   | tac_2tac (Tac.Take' term) = Tac.Take (term2str term)
   479   | tac_2tac (Tac.Substitute' (_, _, subte, _, _)) = Tac.Substitute (Selem.subte2sube subte) 
   480   | tac_2tac (Tac.Tac_ (_, _, id, _)) = Tac.Tac id
   481 
   482   | tac_2tac (Tac.Subproblem' ((domID, pblID, _), _, _, _,_ ,_)) = Tac.Subproblem (domID, pblID)
   483   | tac_2tac (Tac.Check_Postcond' (pblID, _)) = Tac.Check_Postcond pblID
   484   | tac_2tac Tac.Empty_Tac_ = Tac.Empty_Tac
   485   | tac_2tac m = error ("tac_2tac: not impl. for "^(Tac.tac_2str m));
   486 
   487 val idT = Type ("Script.ID", []);
   488 
   489 fun make_rule thy t =
   490   let val ct = Thm.global_cterm_of thy (TermC.Trueprop $ t)
   491   in Thm (term_to_string''' thy (Thm.term_of ct), Thm.make_thm ct) end;
   492 
   493 fun rep_tac_ (Tac.Rewrite_Inst' (thy', _, _, put, subs, (thmID, _), f, (f', _))) = 
   494     let val fT = type_of f;
   495       val b = if put then @{term True} else @{term False};
   496       val sT = (type_of o fst o hd) subs;
   497       val subs' = TermC.list2isalist (HOLogic.mk_prodT (sT, sT)) (map HOLogic.mk_prod subs);
   498       val sT' = type_of subs';
   499       val lhs = Const ("Script.Rewrite'_Inst", [sT', idT, TermC.bool, fT] ---> fT) 
   500         $ subs' $ Free (thmID, idT) $ b $ f;
   501     in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs, f'), (lhs, f')) end
   502   | rep_tac_ (Tac.Rewrite' (thy', _, _, put, (thmID, _), f, (f', _)))=
   503     let 
   504       val fT = type_of f;
   505       val b = if put then @{term True} else @{term False};
   506       val lhs = Const ("Script.Rewrite", [idT, HOLogic.boolT, fT] ---> fT)
   507         $ Free (thmID, idT) $ b $ f;
   508     in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs, f'), (lhs, f')) end
   509   | rep_tac_ (Tac.Rewrite_Set_Inst' (_, _, _, _, _, (f', _))) = (e_rule, (e_term, f'))
   510   | rep_tac_ (Tac.Rewrite_Set' (thy', put, rls, f, (f', _))) =
   511     let 
   512       val fT = type_of f;
   513       val b = if put then @{term True} else @{term False};
   514       val lhs = Const ("Script.Rewrite'_Set", [idT, TermC.bool, fT] ---> fT) 
   515         $ Free (id_rls rls, idT) $ b $ f;
   516     in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   517   | rep_tac_ (Tac.Calculate' (thy', op_, f, (f', _)))=
   518     let
   519       val fT = type_of f;
   520       val lhs = Const ("Script.Calculate",[idT,fT] ---> fT) $ Free (op_,idT) $ f
   521     in (((make_rule (assoc_thy thy')) o HOLogic.mk_eq) (lhs,f'),(lhs,f')) end
   522   | rep_tac_ (Tac.Check_elementwise' (_, _, (t', _))) = (Erule, (e_term, t'))
   523   | rep_tac_ (Tac.Subproblem' (_, _, _, _, _, t')) = (Erule, (e_term, t'))
   524   | rep_tac_ (Tac.Take' t') = (Erule, (e_term, t'))
   525   | rep_tac_ (Tac.Substitute' (_, _, _, t, t')) = (Erule, (t, t'))
   526   | rep_tac_ (Tac.Or_to_List' (t, t')) = (Erule, (t, t'))
   527   | rep_tac_ m = error ("rep_tac_: not impl.for " ^ Tac.tac_2str m)
   528 
   529 fun tac_2res m = (snd o snd o rep_tac_) m;
   530 
   531 (* handle a leaf at the end of recursive descent:
   532    a leaf is either a tactic or an 'expr' in "let v = expr"
   533    where "expr" does not contain a tactic.
   534    Handling a leaf comprises
   535    (1) 'subst_stacexpr' substitute LTool.env and complete curried tactic
   536    (2) rewrite the leaf by 'srls'
   537 *)
   538 fun handle_leaf call thy srls E a v t =
   539       (*WN050916 'upd_env_opt' is a blind copy from previous version*)
   540     case LTool.subst_stacexpr E a v t of
   541 	    (a', LTool.STac stac) => (*script-tactic*)
   542 	      let val stac' =
   543             Rewrite.eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) stac)
   544 	      in
   545           (if (! trace_script) 
   546 	         then tracing ("@@@ "^call^" leaf '"^term2str t^"' ---> STac '"^term2str stac ^"'")
   547 	         else ();
   548 	         (a', LTool.STac stac'))
   549 	      end
   550     | (a', LTool.Expr lexpr) => (*leaf-expression*)
   551 	      let val lexpr' =
   552             Rewrite.eval_listexpr_ (assoc_thy thy) srls (subst_atomic (upd_env_opt E (a,v)) lexpr)
   553 	      in
   554           (if (! trace_script) 
   555 	         then tracing("@@@ "^call^" leaf '"^term2str t^"' ---> Expr '"^term2str lexpr'^"'")
   556 	         else ();
   557 	         (a', LTool.Expr lexpr')) (*lexpr' is the value of the Expr*)
   558 	      end;
   559 
   560 (** locate an applicable stac in a script **)
   561 datatype assoc =   (* ExprVal in the sense of denotational semantics               *)
   562   Assoc of         (* the stac is associated, strongly or weakly                   *)
   563   Selem.scrstate * (* the current; returned for next_tac etc. outside ass*         *)  
   564   (step list)      (* list of steps done until associated stac found;
   565 	                    initiated with the data for doing the 1st step,
   566                       thus the head holds these data further on,
   567 		                  while the tail holds steps finished (incl.scrstate in ctree) *)
   568 | NasApp of        (* stac not associated, but applicable, ctree-node generated    *)
   569   Selem.scrstate * (step list)
   570 | NasNap of        (* stac not associated, not applicable, nothing generated;
   571 	                    for distinction in Or, for leaving iterations, leaving Seq,
   572 		                  evaluate scriptexpressions                                   *)
   573   term * LTool.env;
   574 fun assoc2str (Assoc _) = "Assoc"
   575   | assoc2str (NasNap _) = "NasNap"
   576   | assoc2str (NasApp _) = "NasApp";
   577 
   578 datatype asap = (* arg. of assy _only_ for distinction w.r.t. Or                 *)
   579   Aundef        (* undefined: set only by (topmost) Or                           *)
   580 | AssOnly       (* do not execute appl stacs - there could be an associated
   581 	                 in parallel Or-branch                                         *)
   582 | AssGen;       (* no Ass(Weak) found within Or, thus 
   583                    search for _applicable_ stacs, execute and generate pt        *)
   584 (*this constructions doesnt allow arbitrary nesting of Or !!!                    *)
   585 
   586 (* assy, ass_up, astep_up scan for locate_gen in a script.
   587    search is clearly separated into (1)-(2):
   588    (1) assy is recursive descent;
   589    (2) ass_up resumes interpretation at a location somewhere in the script;
   590        astep_up does only get to the parentnode of the scriptexpr.
   591    consequence:
   592    * call of (2) means _always_ that in this branch below
   593      there was an appl.stac (Repeat, Or e1, ...) found by the previous step.
   594 *)
   595 (*WN161112 blanks between list elements left as is until istate is introduced here*)
   596 fun assy ya ((E,l,a,v,S,b),ss) (Const ("HOL.Let",_) $ e $ (Abs (id,T,body))) =
   597     (case assy ya ((E , l @ [L, R], a,v,S,b),ss) e of
   598        NasApp ((E',l,a,v,S,_),ss) => 
   599          let
   600            val id' = TermC.mk_Free (id, T);
   601            val E' = LTool.upd_env E' (id', v);
   602          in assy ya ((E', l @ [R, D], a,v,S,b),ss) body end
   603      | NasNap (v,E) =>
   604          let
   605            val id' = TermC.mk_Free (id, T);
   606            val E' = LTool.upd_env E (id', v);
   607          in assy ya ((E', l @ [R, D], a,v,S,b),ss) body end
   608      | ay => ay)
   609   | assy (ya as (thy,_,srls,_,_)) ((E,l,_,v,S,b),ss) (Const ("Script.While",_) $ c $ e $ a) =
   610     if Rewrite.eval_true_ thy srls (subst_atomic (LTool.upd_env E (a,v)) c) 
   611     then assy ya ((E, l @ [L, R], SOME a,v,S,b),ss)  e
   612     else NasNap (v, E)
   613   | assy (ya as (thy,_,srls,_,_)) ((E,l,a,v,S,b),ss) (Const ("Script.While",_) $ c $ e) =
   614     if Rewrite.eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   615     then assy ya ((E, l @ [R], a,v,S,b),ss) e
   616     else NasNap (v, E)
   617   | assy (ya as (thy,_,srls,_,_)) ((E,l,a,v,S,b),ss) (Const ("If",_) $ c $ e1 $ e2) =
   618     if Rewrite.eval_true_ thy srls (subst_atomic (upd_env_opt E (a,v)) c) 
   619     then assy ya ((E, l @ [L, R], a,v,S,b),ss) e1
   620     else assy ya ((E, l @ [R], a,v,S,b),ss) e2 
   621   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Try",_) $ e $ a) =
   622     (case assy ya ((E, l @ [L, R], SOME a,v,S,b),ss) e of ay => ay) 
   623   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Try",_) $ e) =
   624     (case assy ya ((E, l @ [R], a,v,S,b),ss) e of ay => ay)
   625   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2 $ a) =
   626     (case assy ya ((E, l @ [L, L, R], SOME a,v,S,b),ss) e1 of
   627 	     NasNap (v, E) => assy ya ((E, l @ [L, R], SOME a,v,S,b),ss) e2
   628      | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l @ [L, R], SOME a,v,S,b),ss) e2
   629      | ay => ay)
   630   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Seq",_) $e1 $ e2) =
   631     (case assy ya ((E, l @ [L, R], a,v,S,b),ss) e1 of
   632 	     NasNap (v, E) => assy ya ((E, l @ [R], a,v,S,b),ss) e2
   633      | NasApp ((E,_,_,v,_,_),ss) => assy ya ((E, l @ [R], a,v,S,b),ss) e2
   634      | ay => ay)
   635   | assy ya ((E,l,_,v,S,b),ss) (Const ("Script.Repeat",_) $ e $ a) =
   636     assy ya ((E,(l @ [L, R]),SOME a,v,S,b),ss) e
   637   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Repeat",_) $ e) =
   638     assy ya ((E,(l @ [R]),a,v,S,b),ss) e
   639   | assy (y,x,s,sc,Aundef) ((E,l,_,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2 $ a) =
   640     (case assy (y,x,s,sc,AssOnly) ((E,(l @ [L, L, R]),SOME a,v,S,b),ss) e1 of
   641 	     NasNap (v, E) => 
   642 	       (case assy (y,x,s,sc,AssOnly) ((E,(l @ [L, R]),SOME a,v,S,b),ss) e2 of
   643 	          NasNap (v, E) => 
   644 	            (case assy (y,x,s,sc,AssGen) ((E,(l @ [L, L, R]),SOME a,v,S,b),ss) e1 of
   645 	               NasNap (v, E) => 
   646 	                 assy (y,x,s,sc,AssGen) ((E, (l @ [L, R]), SOME a,v,S,b),ss) e2
   647 	             | ay => ay)
   648 	        | ay =>ay)
   649      | NasApp _ => error ("assy: FIXXXME ///must not return NasApp///")
   650      | ay => (ay))
   651   | assy ya ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $e1 $ e2) =
   652     (case assy ya ((E,(l @ [L, R]),a,v,S,b),ss) e1 of
   653 	     NasNap (v, E) => assy ya ((E,(l @ [R]),a,v,S,b),ss) e2
   654      | ay => (ay))
   655     (*here is not a tactical like TRY etc, but a tactic creating a step in calculation*)
   656   | assy (thy',ctxt,sr,d,ap) ((E,l,a,v,S,_), (m,_,pt,(p,p_),c)::ss) t =
   657     (case handle_leaf "locate" thy' sr E a v t of
   658 	     (a', LTool.Expr _) => 
   659 	        (NasNap (Rewrite.eval_listexpr_ (assoc_thy thy') sr
   660 		     (subst_atomic (upd_env_opt E (a',v)) t), E))
   661      | (a', LTool.STac stac) =>
   662 	       let
   663            val p' = 
   664              case p_ of Frm => p 
   665              | Res => lev_on p
   666 		         | _ => error ("assy: call by " ^ pos'2str (p,p_));
   667 	       in
   668            case assod pt d m stac of
   669 	         Ass (m,v') =>
   670 	           let val (p'',c',f',pt') =
   671                  Generate.generate1 (assoc_thy thy') m (Selem.ScrState (E,l,a',v',S,true), ctxt) (p',p_) pt;
   672 	           in Assoc ((E,l,a',v',S,true), (m,f',pt',p'',c @ c')::ss) end
   673            | AssWeak (m,v') => 
   674 	           let val (p'',c',f',pt') =
   675                Generate.generate1 (assoc_thy thy') m (Selem.ScrState (E,l,a',v',S,false), ctxt) (p',p_) pt;
   676 	           in Assoc ((E,l,a',v',S,false), (m,f',pt',p'',c @ c')::ss) end
   677            | NotAss =>
   678              (case ap of   (*switch for Or: 1st AssOnly, 2nd AssGen*)
   679                 AssOnly => (NasNap (v, E))
   680               | _ =>
   681                   (case Applicable.applicable_in (p,p_) pt (stac2tac pt (assoc_thy thy') stac) of
   682 		                 Chead.Appl m' =>
   683 		                   let
   684                          val is = (E,l,a',tac_2res m',S,false(*FIXXXME.WN0?*))
   685 		                     val (p'',c',f',pt') =
   686 		                       Generate.generate1 (assoc_thy thy') m' (Selem.ScrState is, ctxt) (p', p_) pt;
   687 		                   in NasApp (is,(m,f',pt',p'',c @ c')::ss) end
   688 		               | Chead.Notappl _ => (NasNap (v, E))
   689 		              )
   690 		         )
   691          end)
   692   | assy _ (_, []) t = error ("assy: uncovered fun-def with " ^ term2str t);
   693 
   694 (*WN161112 blanks between list elements left as is until istate is introduced here*)
   695 fun ass_up (ys as (y,ctxt,s,Prog sc,d)) ((E,l,a,v,S,b),ss) (Const ("HOL.Let",_) $ _) =
   696     let 
   697 	    val l = drop_last l; (*comes from e, goes to Abs*)
   698       val (i, T, body) =
   699         (case go l sc of
   700            Const ("HOL.Let",_) $ _ $ (Abs (i, T, body)) => (i, T, body)
   701          | t => error ("ass_up..HOL.Let $ _ with " ^ term2str t))
   702       val i = TermC.mk_Free (i, T);
   703       val E = LTool.upd_env E (i, v);
   704     in case assy (y,ctxt,s,d,Aundef) ((E, l @ [R, D], a,v,S,b),ss) body of
   705 	       Assoc iss => Assoc iss
   706 	     | NasApp iss => astep_up ys iss 
   707 	     | NasNap (v, E) => astep_up ys ((E,l,a,v,S,b),ss) 
   708 	  end
   709   | ass_up ys iss (Abs (_,_,_)) = astep_up ys iss (*TODO 5.9.00: LTool.env ?*)
   710   | ass_up ys iss (Const ("HOL.Let",_) $ _ $ (Abs _)) = astep_up ys iss (*TODO 5.9.00: LTool.env ?*)
   711   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _ $ _) =
   712     astep_up ysa iss (*all has been done in (*2*) below*)
   713   | ass_up ysa iss (Const ("Script.Seq",_) $ _ $ _) =
   714     astep_up ysa iss (*2*: comes from e2*)
   715 
   716   | ass_up (ysa as (y,ctxt,s,Prog sc,d)) ((E,l,a,v,S,b),ss)
   717 	  (Const ("Script.Seq",_) $ _ ) = (*2*: comes from e1, goes to e2*)
   718      let 
   719        val up = drop_last l;
   720      val e2 =
   721        (case go up sc of
   722           Const ("Script.Seq",_) $ _ $ e2 => e2
   723         | t => error ("ass_up..Script.Seq $ _ with " ^ term2str t))
   724      in case assy (y,ctxt,s,d,Aundef) ((E, up @ [R], a,v,S,b),ss) e2 of
   725          NasNap (v,E) => astep_up ysa ((E,up,a,v,S,b),ss)
   726        | NasApp iss => astep_up ysa iss
   727        | ay => ay 
   728      end
   729   | ass_up ysa iss (Const ("Script.Try",_) $ _ $ _) = astep_up ysa iss
   730   | ass_up ysa iss (Const ("Script.Try",_) $ _) = astep_up ysa iss
   731   | ass_up (ys as (y,ctxt,s,_,d)) ((E,l,_,v,S,b),ss)
   732 	   (*(Const ("Script.While",_) $ c $ e $ a) = WN050930 blind fix*)
   733 	    (t as Const ("Script.While",_) $ c $ e $ a) =
   734     if Rewrite.eval_true_ y s (subst_atomic (LTool.upd_env E (a,v)) c)
   735     then case assy (y,ctxt,s,d,Aundef) ((E, l @ [L, R], SOME a,v,S,b),ss) e of 
   736       NasNap (v,E') => astep_up ys ((E',l, SOME a,v,S,b),ss)
   737     | NasApp ((E',l,a,v,S,b),ss) =>
   738       ass_up ys ((E',l,a,v,S,b),ss) t (*WN050930 't' was not assigned*)
   739     | ay => ay
   740     else astep_up ys ((E,l, SOME a,v,S,b),ss)
   741   | ass_up (ys as (y,ctxt,s,_,d)) ((E,l,a,v,S,b),ss)
   742 	   (*(Const ("Script.While",_) $ c $ e) = WN050930 blind fix*)
   743 	     (t as Const ("Script.While",_) $ c $ e) =
   744     if Rewrite.eval_true_ y s (subst_atomic (upd_env_opt E (a,v)) c)
   745     then case assy (y,ctxt,s,d,Aundef) ((E, l @ [R], a,v,S,b),ss) e of 
   746        NasNap (v,E') => astep_up ys ((E',l, a,v,S,b),ss)
   747      | NasApp ((E',l,a,v,S,b),ss) =>
   748        ass_up ys ((E',l,a,v,S,b),ss) t (*WN050930 't' was not assigned*)
   749      | ay => ay
   750     else astep_up ys ((E,l, a,v,S,b),ss)
   751   | ass_up y iss (Const ("If",_) $ _ $ _ $ _) = astep_up y iss
   752   | ass_up (ys as (y,ctxt,s,_,d)) ((E,l,_,v,S,b),ss)
   753 	    (t as Const ("Script.Repeat",_) $ e $ a) =
   754     (case assy (y,ctxt,s,d, Aundef) ((E, (l @ [L, R]), SOME a,v,S,b),ss) e of 
   755       NasNap (v,E') => astep_up ys ((E',l, SOME a,v,S,b),ss)
   756     | NasApp ((E',l,a,v,S,b),ss) =>
   757       ass_up ys ((E',l,a,v,S,b),ss) t
   758     | ay => ay)
   759   | ass_up (ys as (y,ctxt,s,_,d)) ((E,l,a,v,S,b),ss)
   760 	    (t as Const ("Script.Repeat",_) $ e) =
   761     (case assy (y,ctxt,s,d,Aundef) ((E, (l @ [R]), a,v,S,b),ss) e of 
   762        NasNap (v', E') => astep_up ys ((E',l,a,v',S,b),ss)
   763      | NasApp ((E',l,a,v',S,_),ss) => ass_up ys ((E',l,a,v',S,b),ss) t
   764      | ay => ay)
   765   | ass_up y iss (Const ("Script.Or",_) $ _ $ _ $ _) = astep_up y iss
   766   | ass_up y iss (Const ("Script.Or",_) $ _ $ _) = astep_up y iss
   767   | ass_up y ((E,l,a,v,S,b),ss) (Const ("Script.Or",_) $ _ ) = 
   768     astep_up y ((E, (drop_last l), a,v,S,b),ss)
   769   | ass_up _ _ t =
   770     error ("ass_up not impl for t= " ^ term2str t)
   771 and astep_up (ys as (_,_,_,Prog sc,_)) ((E,l,a,v,S,b),ss) =
   772   if 1 < length l
   773   then 
   774     let val up = drop_last l;
   775     in ass_up ys ((E,up,a,v,S,b),ss) (go up sc) end
   776   else (NasNap (v, E))
   777   | astep_up _ ((_,l,_,_,_,_),_) = error ("astep_up: uncovered fun-def with " ^ loc_2str l)
   778 
   779 (*check if there are tacs for rewriting only*)
   780 fun rew_only ([]:step list) = true
   781   | rew_only (((Tac.Rewrite' _          ,_,_,_,_))::ss) = rew_only ss
   782   | rew_only (((Tac.Rewrite_Inst' _     ,_,_,_,_))::ss) = rew_only ss
   783   | rew_only (((Tac.Rewrite_Set' _      ,_,_,_,_))::ss) = rew_only ss
   784   | rew_only (((Tac.Rewrite_Set_Inst' _ ,_,_,_,_))::ss) = rew_only ss
   785   | rew_only (((Tac.Calculate' _        ,_,_,_,_))::ss) = rew_only ss
   786   | rew_only (((Tac.Begin_Trans' _      ,_,_,_,_))::ss) = rew_only ss
   787   | rew_only (((Tac.End_Trans' _        ,_,_,_,_))::ss) = rew_only ss
   788   | rew_only _ = false; 
   789 
   790 datatype locate =
   791   Steps of Selem.istate (* producing hd of step list (which was latest)
   792 	                         for next_tac, for reporting Safe|Unsafe to DG  *)
   793 	   * step             (* (scrstate producing this step is in ctree !)   *) 
   794 		 list               (* locate_gen may produce intermediate steps      *)
   795 | NotLocatable;         (* no (m Ass m') or (m AssWeak m') found          *)
   796 
   797 (* locate_gen tries to locate an input tac m in the script. 
   798    pursuing this goal the script is executed until an (m' equiv m) is found,
   799    or the end of the script
   800 args
   801    m   : input by the user, already checked by applicable_in,
   802          (to be searched within Or; and _not_ an m doing the step on ctree !)
   803    p,pt: (incl ets) at the time of input
   804    scr : the script
   805    d   : canonical simplifier for locating Take, Substitute, Subproblems etc.
   806    ets : ets at the time of input
   807    l   : the location (in scr) of the stac which generated the current formula
   808 returns
   809    Steps: pt,p (incl. ets) with m done
   810           pos' list of proofobjs cut (from generate)
   811           safe: implied from last proofobj
   812 	  ets:
   813    ///ToDo : ets contains a list of tacs to be done before m can be done
   814           NOT IMPL. -- "error: do other step before"
   815    NotLocatable: thus generate_hard
   816 *)
   817 (*WN161112 blanks between list elements left as is until istate is introduced here*)
   818 fun locate_gen (thy', _) (Tac.Rewrite' (_, ro, er, pa, thm, f, _)) (pt, p) 
   819 	    (Rfuns {locate_rule=lo,...}, _) (Selem.RrlsState (_,f'',rss,rts), _) = 
   820     (case lo rss f (Thm thm) of
   821 	    [] => NotLocatable
   822     | rts' => Steps (rts2steps [] ((pt,p),(f,f'',rss,rts),(thy',ro,er,pa)) rts'))
   823   | locate_gen (thy', srls) m (pt, p)
   824 	    (scr as Prog (_ $ body),d) (Selem.ScrState (E,l,a,v,S,b), ctxt)  = 
   825     let val thy = assoc_thy thy';
   826     in case if l = [] orelse (
   827 		       (*init.in solve..Apply_Method...*)(last_elem o fst) p = 0 andalso snd p = Res)
   828 	       then (assy (thy',ctxt,srls,d,Aundef) ((E,[R],a,v,S,b), [(m,Generate.EmptyMout,pt,p,[])]) body)
   829 	       else (astep_up (thy',ctxt,srls,scr,d) ((E,l,a,v,S,b), [(m,Generate.EmptyMout,pt,p,[])]) ) of
   830 	    Assoc ((is as (_,_,_,_,_,strong_ass), ss as (_ :: _))) =>
   831 	      (if strong_ass
   832          then (Steps (Selem.ScrState is, ss))
   833 	       else
   834            if rew_only ss (*andalso 'not strong_ass'= associated weakly*)
   835 	         then
   836              let
   837                val (po,p_) = p
   838                val po' = case p_ of Frm => po | Res => lev_on po | _ => error ("locate_gen " ^ pos_2str p_)
   839                val (p'',c'',f'',pt'') = Generate.generate1 thy m (Selem.ScrState is, ctxt) (po',p_) pt
   840 	           in Steps (Selem.ScrState is, [(m, f'',pt'',p'',c'')]) end
   841 	         else Steps (Selem.ScrState is, ss))
   842 	  
   843     | NasApp _ => NotLocatable
   844     | err => error ("not-found-in-script: NotLocatable from " ^ @{make_string} err)
   845     end
   846   | locate_gen _ m _ (sc,_) (is, _) = 
   847     error ("locate_gen: wrong arguments,\n tac= " ^ Tac.tac_2str m ^ ",\n " ^
   848       "scr= " ^ scr2str sc ^ ",\n istate= " ^ Selem.istate2str is);
   849 
   850 (** find the next stactic in a script **)
   851 
   852 (*appy, nxt_up, nstep_up scanning for next_tac.
   853   search is clearly separated into (1)-(2):
   854   (1) appy is recursive descent;
   855   (2) nxt_up resumes interpretation at a location somewhere in the script;
   856       nstep_up does only get to the parentnode of the scriptexpr.
   857   consequence:
   858   * call of (2) means _always_ that in this branch below
   859     there was an applicable stac (Repeat, Or e1, ...)
   860 *)
   861 datatype appy =    (* ExprVal in the sense of denotational semantics  *)
   862     Appy of        (* applicable stac found, search stalled           *)
   863     Tac.tac_ *     (* tac_ associated (fun assod) with stac           *)
   864     Selem.scrstate (* after determination of stac WN.18.8.03          *)
   865   | Napp of        (* stac found was not applicable; 
   866 	                    this mode may become Skip in Repeat, Try and Or *)
   867     LTool.env      (* popped while nxt_up                             *)
   868   | Skip of        (* for restart after Appy, for leaving iterations,
   869 	                    for passing the value of scriptexpressions,
   870 		                  and for finishing the script successfully       *)
   871     term * LTool.env  (*a stack*);
   872 
   873 datatype appy_ = (* as argument in nxt_up, nstep_up, from appy               *)
   874 (*Appy              is only (final) returnvalue, not argument during search  *)
   875   Napp_          (* ev. detects 'script is not appropriate for this example' *)
   876 | Skip_;         (* detects 'script successfully finished'
   877 		                also used as init-value for resuming; this works,
   878 	                  because 'nxt_up Or e1' treats as Appy                    *)
   879 
   880 fun appy thy ptp E l (Const ("HOL.Let",_) $ e $ (Abs (i,T,b))) a v =
   881     (case appy thy ptp E (l @ [L, R]) e a v of
   882       Skip (res, E) => 
   883         let val E' = LTool.upd_env E (Free (i,T), res);
   884         in appy thy ptp E' (l @ [R, D]) b a v end
   885     | ay => ay)
   886   | appy (thy as (th,sr)) ptp E l (Const ("Script.While"(*1*),_) $ c $ e $ a) _ v =
   887     (if Rewrite.eval_true_ th sr (subst_atomic (LTool.upd_env E (a,v)) c)
   888      then appy thy ptp E (l @ [L, R]) e (SOME a) v
   889      else Skip (v, E))
   890   | appy (thy as (th,sr)) ptp E l (Const ("Script.While"(*2*),_) $ c $ e) a v =
   891     (if Rewrite.eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
   892      then appy thy ptp E (l @ [R]) e a v
   893      else Skip (v, E))
   894   | appy (thy as (th,sr)) ptp E l (Const ("If",_) $ c $ e1 $ e2) a v =
   895     (if Rewrite.eval_true_ th sr (subst_atomic (upd_env_opt E (a,v)) c)
   896      then appy thy ptp E (l @ [L, R]) e1 a v
   897      else appy thy ptp E (l @ [R]) e2 a v)
   898   | appy thy ptp E l (Const ("Script.Repeat"(*1*),_) $ e $ a) _ v = 
   899     appy thy ptp E (l @ [L, R]) e (SOME a) v
   900   | appy thy ptp E l (Const ("Script.Repeat"(*2*),_) $ e) a v = appy thy ptp E (l @ [R]) e a v
   901   | appy thy ptp E l (Const ("Script.Try",_) $ e $ a) _ v =
   902     (case appy thy ptp E (l @ [L, R]) e (SOME a) v of
   903       Napp E => (Skip (v, E))
   904     | ay => ay)
   905   | appy thy ptp E l(Const ("Script.Try",_) $ e) a v =
   906     (case appy thy ptp E (l @ [R]) e a v of
   907       Napp E => (Skip (v, E))
   908     | ay => ay)
   909   | appy thy ptp E l (Const ("Script.Or"(*1*),_) $e1 $ e2 $ a) _ v =
   910     (case appy thy ptp E (l @ [L, L, R]) e1 (SOME a) v of
   911 	    Appy lme => Appy lme
   912     | _ => appy thy ptp E (*LTool.env*) (l @ [L, R]) e2 (SOME a) v)
   913   | appy thy ptp E l (Const ("Script.Or"(*2*),_) $e1 $ e2) a v =
   914     (case appy thy ptp E (l @ [L, R]) e1 a v of
   915 	    Appy lme => Appy lme
   916     | _ => appy thy ptp E (l @ [R]) e2 a v)
   917   | appy thy ptp E l (Const ("Script.Seq"(*1*),_) $ e1 $ e2 $ a) _ v =
   918     (case appy thy ptp E (l @ [L, L, R]) e1 (SOME a) v of
   919 	    Skip (v,E) => appy thy ptp E (l @ [L, R]) e2 (SOME a) v
   920     | ay => ay)
   921   | appy thy ptp E l (Const ("Script.Seq",_) $ e1 $ e2) a v =
   922     (case appy thy ptp E (l @ [L,R]) e1 a v of
   923 	    Skip (v,E) => appy thy ptp E (l @ [R]) e2 a v
   924     | ay => ay)
   925   (* a leaf has been found *)   
   926   | appy ((th,sr)) (pt, p) E l t a v =
   927     case handle_leaf "next  " th sr E a v t of
   928 	    (_, LTool.Expr s) => Skip (s, E)
   929     | (a', LTool.STac stac) =>
   930 	    let val (m,m') = stac2tac_ pt (assoc_thy th) stac
   931       in case m of 
   932 	      Tac.Subproblem _ => Appy (m', (E,l,a',tac_2res m',Selem.Sundef,false))
   933 	    | _ =>
   934         (case Applicable.applicable_in p pt m of
   935 		       Chead.Appl m' => (Appy (m', (E,l,a',tac_2res m',Selem.Sundef,false)))
   936 		     | _ => Napp E)
   937 	    end
   938 (*GOON*)
   939 fun nxt_up thy ptp (scr as (Prog sc)) E l ay (Const ("HOL.Let", _) $ _) a v = (*comes from let=...*)
   940     if ay = Napp_
   941     then nstep_up thy ptp scr E (drop_last l) Napp_ a v
   942     else (*Skip_*)
   943 	    let
   944         val up = drop_last l
   945         val (i, T, body) =
   946           (case go up sc of
   947              Const ("HOL.Let",_) $ _ $ (Abs aa) => aa
   948            | t => error ("nxt_up..HOL.Let $ _ with " ^ term2str t))
   949         val i = TermC.mk_Free (i, T)
   950         val E = LTool.upd_env E (i, v)
   951       in
   952         case appy thy ptp E (up @ [R,D]) body a v  of
   953 	        Appy lre => Appy lre
   954 	      | Napp E => nstep_up thy ptp scr E up Napp_ a v
   955 	      | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v
   956 	    end
   957   | nxt_up thy ptp scr E l ay (Abs _) a v =  nstep_up thy ptp scr E l ay a v
   958   | nxt_up thy ptp scr E l ay (Const ("HOL.Let",_) $ _ $ (Abs _)) a v =
   959     nstep_up thy ptp scr E l ay a v
   960   (*no appy_: never causes Napp -> Helpless*)
   961   | nxt_up (thy as (th, sr)) ptp scr E l _ (Const ("Script.While"(*1*), _) $ c $ e $ _) a v = 
   962     if Rewrite.eval_true_ th sr (subst_atomic (upd_env_opt E (a, v)) c) 
   963     then case appy thy ptp E (l @ [L,R]) e a v of
   964 	     Appy lr => Appy lr
   965 	  | Napp E => nstep_up thy ptp scr E l Skip_ a v
   966 	  | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
   967     else nstep_up thy ptp scr E l Skip_ a v
   968   (*no appy_: never causes Napp - Helpless*)
   969   | nxt_up (thy as (th, sr)) ptp scr E l _ (Const ("Script.While"(*2*), _) $ c $ e) a v = 
   970     if Rewrite.eval_true_ th sr (subst_atomic (upd_env_opt E (a, v)) c) 
   971     then case appy thy ptp E (l @ [R]) e a v of
   972 	    Appy lr => Appy lr
   973 	  | Napp E => nstep_up thy ptp scr E l Skip_ a v
   974 	  | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v
   975     else nstep_up thy ptp scr E l Skip_ a v
   976   | nxt_up thy ptp scr E l ay (Const ("If", _) $ _ $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
   977   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
   978       (Const ("Script.Repeat"(*1*), _) $ e $ _) a v =
   979     (case appy thy ptp (*upd_env*) E (*a,v)*) ((l @ [L, R]):loc_) e a v  of
   980       Appy lr => Appy lr
   981     | Napp E =>  nstep_up thy ptp scr E l Skip_ a v
   982     | Skip (v,E) =>  nstep_up thy ptp scr E l Skip_ a v)
   983   | nxt_up thy ptp scr E l _ (*no appy_: there was already a stac below*)
   984       (Const ("Script.Repeat"(*2*), _) $ e) a v =
   985     (case appy thy ptp (*upd_env*) E (*a,v)*) (l @ [R]) e a v  of
   986       Appy lr => Appy lr
   987     | Napp E => nstep_up thy ptp scr E l Skip_ a v
   988     | Skip (v,E) => nstep_up thy ptp scr E l Skip_ a v)
   989   | nxt_up thy ptp scr E l _ (Const ("Script.Try",_) $ _ $ _) a v = (*makes Napp to Skip*)
   990     nstep_up thy ptp scr E l Skip_ a v
   991 
   992   | nxt_up thy ptp scr E l _ (Const ("Script.Try"(*2*), _) $ _) a v = (*makes Napp to Skip*)
   993     nstep_up thy ptp scr E l Skip_ a v
   994   | nxt_up thy ptp scr E l ay (Const ("Script.Or",_) $ _ $ _ $ _) a v =
   995     nstep_up thy ptp scr E l ay a v
   996   | nxt_up thy ptp scr E l ay (Const ("Script.Or",_) $ _ $ _) a v = nstep_up thy ptp scr E l ay a v
   997   | nxt_up thy ptp scr E l ay (Const ("Script.Or",_) $ _ ) a v = 
   998     nstep_up thy ptp scr E (drop_last l) ay a v
   999   | nxt_up thy ptp scr E l ay (Const ("Script.Seq"(*1*),_) $ _ $ _ $ _) a v =
  1000     (*all has been done in (*2*) below*) nstep_up thy ptp scr E l ay a v
  1001   | nxt_up thy ptp scr E l ay (Const ("Script.Seq"(*2*),_) $ _ $ _) a v = (*comes from e2*)
  1002     nstep_up thy ptp scr E l ay a v
  1003   | nxt_up thy ptp (scr as Prog sc) E l ay (Const ("Script.Seq",_) $ _) a v = (*comes from e1*)
  1004     if ay = Napp_
  1005     then nstep_up thy ptp scr E (drop_last l) Napp_ a v
  1006     else (*Skip_*)
  1007       let val up = drop_last l;
  1008           val e2 =
  1009             (case go up sc of
  1010                Const ("Script.Seq"(*2*), _) $ _ $ e2 => e2
  1011              | t => error ("nxt_up..Script.Seq $ _ with " ^ term2str t))
  1012       in case appy thy ptp E (up @ [R]) e2 a v  of
  1013         Appy lr => Appy lr
  1014       | Napp E => nstep_up thy ptp scr E up Napp_ a v
  1015       | Skip (v,E) => nstep_up thy ptp scr E up Skip_ a v end
  1016   | nxt_up _ _ _ _ _ _ t _ _ = error ("nxt_up not impl for " ^ term2str t)
  1017 and nstep_up thy ptp (Prog sc) E l ay a v = 
  1018     if 1 < length l
  1019     then 
  1020       let val up = drop_last l; 
  1021       in (nxt_up thy ptp (Prog sc) E up ay (go up sc) a v ) end
  1022     else (*interpreted to end*)
  1023       if ay = Skip_ then Skip (v, E) else Napp E 
  1024   | nstep_up _ _ _ _ l _ _ _ = error ("nstep_up: uncovered fun-def at " ^ loc_2str l)
  1025 
  1026 (* decide for the next applicable stac in the script;
  1027    returns (stactic, value) - the value in case the script is finished 
  1028    12.8.02:         ~~~~~ and no assumptions ??? FIXME ???
  1029    20.8.02: must return p in case of finished, because the next script
  1030             consulted need not be the calling script:
  1031             in case of detail ie. _inserted_ PrfObjs, the next stac
  1032             has to searched in a script with PblObj.status<>Complete !
  1033             (.. not true for other details ..PrfObj ??????????????????
  1034    20.8.02: do NOT return safe (is only changed in locate !!!)
  1035 *)
  1036 fun next_tac (thy,_) _ (Rfuns {next_rule, ...}) (Selem.RrlsState(f, f', rss, _), ctxt) =
  1037     if f = f'
  1038     then (Tac.End_Detail' (f',[])(*8.6.03*), (Selem.Uistate, ctxt), 
  1039     	(f', Selem.Sundef(*FIXME is no value of next_tac! vor 8.6.03*)))                (*finished*)
  1040     else
  1041       (case next_rule rss f of
  1042     	  NONE => (Tac.Empty_Tac_, (Selem.Uistate, ctxt), (e_term, Selem.Sundef))       (*helpless*)
  1043     	| SOME (Thm thm'')(*8.6.03: muss auch f' liefern ?!!*) => 
  1044     	    (Tac.Rewrite' (thy, "e_rew_ord", e_rls, false, thm'', f, (e_term, [(*!?!8.6.03*)])),
  1045   	         (Selem.Uistate, ctxt), (e_term, Selem.Sundef))                          (*next stac*)
  1046       | _ => error "next_tac: uncovered case next_rule")
  1047   | next_tac thy (ptp as (pt, (p, _)):ctree * pos') (sc as Prog (_ $ body)) 
  1048 	    (Selem.ScrState (E,l,a,v,s,_), ctxt) =
  1049     (case if l = [] then appy thy ptp E [R] body NONE v
  1050           else nstep_up thy ptp sc E l Skip_ a v of
  1051        Skip (v, _) =>                                                                 (*finished*)
  1052          (case par_pbl_det pt p of
  1053 	          (true, p', _) => 
  1054 	             let
  1055 	               val (_,pblID,_) = get_obj g_spec pt p';
  1056 	              in (Tac.Check_Postcond' (pblID, (v, [(*assigned in next step*)])), 
  1057 	                   (Selem.e_istate, ctxt), (v,s)) 
  1058                 end
  1059 	        | _ => (Tac.End_Detail' (e_term,[])(*8.6.03*), (Selem.e_istate, ctxt), (v,s)))
  1060      | Napp _ => (Tac.Empty_Tac_, (Selem.e_istate, ctxt), (e_term, Selem.Sundef))     (*helpless*)
  1061      | Appy (m', scrst as (_,_,_,v,_,_)) =>
  1062          (m', (Selem.ScrState scrst, ctxt), (v, Selem.Sundef)))                      (*next stac*)
  1063   | next_tac _ _ _ (is, _) = error ("next_tac: not impl for " ^ (Selem.istate2str is));
  1064 
  1065 (*.create the initial interpreter state from the items of the guard.*)
  1066 local
  1067 val errmsg = "ERROR: found no actual arguments for prog. of "
  1068 fun msg_miss (sc, metID, formals, actuals) =
  1069   "ERROR in creating the environment for '" ^ id_of_scr sc ^ 
  1070 	"' from \nthe items of the guard of " ^ metID2str metID ^ ",\n" ^
  1071 	"formal arg(s), from the script, miss actual arg(s), from the guards LTool.env:\n" ^
  1072 	(string_of_int o length) formals ^ " formals: " ^ terms2str formals ^ "\n" ^
  1073 	(string_of_int o length) actuals ^ " actuals: " ^ terms2str actuals
  1074 fun msg_type (sc, metID, a, f, formals, actuals) =
  1075   "ERROR in creating the environment for '" ^
  1076 	id_of_scr sc ^ "' from \nthe items of the guard of " ^
  1077 	metID2str metID ^ ",\n" ^
  1078 	"different types of formal arg, from the script, " ^
  1079 	"and actual arg, from the guards LTool.env:'\n" ^
  1080 	"formal: '" ^ term2str a ^ "::" ^ (type2str o type_of) a ^ "'\n" ^
  1081 	"actual: '" ^ term2str f ^ "::" ^ (type2str o type_of) f ^ "'\n" ^
  1082 	"in\n" ^
  1083 	"formals: " ^ terms2str formals ^ "\n" ^
  1084 	"actuals: " ^ terms2str actuals
  1085 in
  1086 fun init_scrstate thy itms metID =
  1087   let
  1088     val actuals = itms2args thy metID itms
  1089     val _ = if actuals <> [] then () else raise ERROR (errmsg ^ strs2str' metID)
  1090     val (scr, sc) = (case (#scr o Specify.get_met) metID of
  1091        scr as Prog sc => (scr, sc) | _ => raise ERROR ("init_scrstate with " ^ metID2str metID))
  1092     val formals = formal_args sc    
  1093 	  (*expects same sequence of (actual) args in itms and (formal) args in met*)
  1094 	  fun relate_args env [] [] = env
  1095 	    | relate_args _ _ [] = error (msg_miss (sc, metID, formals, actuals))
  1096 	    | relate_args env [] _ = env (*may drop Find!*)
  1097 	    | relate_args env (a::aa) (f::ff) = 
  1098 	      if type_of a = type_of f 
  1099 	      then relate_args (env @ [(a, f)]) aa ff
  1100         else error (msg_type (sc, metID, a, f, formals, actuals))
  1101     val env = relate_args [] formals actuals;
  1102     val ctxt = Proof_Context.init_global thy |> Stool.declare_constraints' actuals
  1103     val {pre, prls, ...} = Specify.get_met metID;
  1104     val pres = Stool.check_preconds thy prls pre itms |> map snd;
  1105     val ctxt = ctxt |> Stool.insert_assumptions pres;
  1106   in (Selem.ScrState (env, [], NONE, e_term, Selem.Safe, true), ctxt, scr) end;
  1107 end (*local*)
  1108 
  1109 (* decide, where to get script/istate from:
  1110    (* 1 *) from PblObj.LTool.env: at begin of script if no init_form
  1111    (* 2 *) from PblObj/PrfObj: if stac is in the middle of the script
  1112    (* 3 *) from rls/PrfObj: in case of detail a ruleset *)
  1113 fun from_pblobj_or_detail' _ (p, p_) pt =
  1114   if member op = [Pbl, Met] p_
  1115   then case get_obj g_env pt p of
  1116     NONE => error "from_pblobj_or_detail': no istate"
  1117   | SOME is =>
  1118       let
  1119         val metID = get_obj g_metID pt p
  1120         val {srls, ...} = Specify.get_met metID
  1121       in (srls, is, (#scr o Specify.get_met) metID) end
  1122   else
  1123     let val (pbl, p', rls') = par_pbl_det pt p
  1124     in if pbl 
  1125        then (*if last_elem p = 0 nothing written to pt yet*)                                (* 2 *)
  1126          let
  1127 	         val metID = get_obj g_metID pt p'
  1128 	         val {srls,...} = Specify.get_met metID
  1129 	       in (srls, get_loc pt (p,p_), (#scr o Specify.get_met) metID) end
  1130        else (*FIXME.WN0?: get from pbl or met !!! unused for Rrls in locate_gen, next_tac*) (* 3 *)
  1131 	       (e_rls, get_loc pt (p,p_),
  1132 	          case rls' of
  1133 		          Rls {scr = scr,...} => scr
  1134 	          | Seq {scr = scr,...} => scr
  1135 	          | Rrls {scr=rfuns,...} => rfuns
  1136 	          | Erls => error "from_pblobj_or_detail' with Erls")
  1137     end
  1138 
  1139 (*.get script and istate from PblObj, see                                                  ( * 1 *)
  1140 fun from_pblobj' thy' (p,p_) pt =
  1141   let
  1142     val p' = par_pblobj pt p
  1143 	  val thy = assoc_thy thy'
  1144 	  val itms =
  1145 	    (case get_obj I pt p' of
  1146 	      PblObj {meth = itms, ...} => itms
  1147 	    | PrfObj _ => error "from_pblobj' NOT with PrfObj")
  1148 	  val metID = get_obj g_metID pt p'
  1149 	  val {srls, scr, ...} = Specify.get_met metID
  1150   in
  1151     if last_elem p = 0 (*nothing written to pt yet*)
  1152     then
  1153        let val (is, ctxt, scr) = init_scrstate thy itms metID
  1154 	     in (srls, (is, ctxt), scr) end
  1155     else (srls, get_loc pt (p,p_), scr)
  1156   end;
  1157     
  1158 (*.get the stactics and problems of a script as tacs
  1159   instantiated with the current environment;
  1160   l is the location which generated the given formula.*)
  1161 (*WN.12.5.03: quick-and-dirty repair for listexpressions*)
  1162 fun is_spec_pos Pbl = true
  1163   | is_spec_pos Met = true
  1164   | is_spec_pos _ = false;
  1165 
  1166 (*. fetch _all_ tactics from script .*)
  1167 fun sel_rules _ (([],Res):pos') = 
  1168     raise PTREE "no tactics applicable at the end of a calculation"
  1169   | sel_rules pt (p,p_) =
  1170     if is_spec_pos p_ 
  1171     then [get_obj g_tac pt p]
  1172     else
  1173       let
  1174         val pp = par_pblobj pt p;
  1175         val thy' = (get_obj g_domID pt pp):theory';
  1176         val thy = assoc_thy thy';
  1177         val metID = get_obj g_metID pt pp;
  1178         val metID' = if metID =e_metID then (thd3 o snd3) (get_obj g_origin pt pp) else metID
  1179         val (sc, srls) = (case Specify.get_met metID' of
  1180             {scr = Prog sc, srls, ...} => (sc, srls) | _ => error "sel_rules 1")
  1181         val (env, a, v) = (case get_istate pt (p, p_) of
  1182             Selem.ScrState (env, _, a, v, _, _) => (env, a, v) | _ => error "sel_rules 2")
  1183       in map ((stac2tac pt thy) o LTool.rep_stacexpr o #2 o
  1184   	    (handle_leaf "selrul" thy' srls env a v)) (LTool.stacpbls sc)
  1185   	  end;
  1186 
  1187 (* fetch tactics from script and filter _applicable_ tactics;
  1188    in case of Rewrite_Set* go down to _atomic_ rewrite-tactics *)
  1189 fun sel_appl_atomic_tacs _ (([], Res) : pos') = 
  1190     raise PTREE "no tactics applicable at the end of a calculation"
  1191   | sel_appl_atomic_tacs pt (p, p_) =
  1192     if is_spec_pos p_ 
  1193     then [get_obj g_tac pt p]
  1194     else
  1195       let
  1196         val pp = par_pblobj pt p
  1197         val thy' = (get_obj g_domID pt pp):theory'
  1198         val thy = assoc_thy thy'
  1199         val metID = get_obj g_metID pt pp
  1200         val metID' =
  1201           if metID = e_metID 
  1202           then (thd3 o snd3) (get_obj g_origin pt pp)
  1203           else metID
  1204         val (sc, srls, erls, ro) = (case Specify.get_met metID' of
  1205             {scr = Prog sc, srls, erls, rew_ord' = ro, ...} => (sc, srls, erls, ro)
  1206           | _ => error "sel_appl_atomic_tacs 1")
  1207         val (env, a, v) = (case get_istate pt (p, p_) of
  1208             Selem.ScrState (env, _, a, v, _, _) => (env, a, v) | _ => error "sel_appl_atomic_tacs 2")
  1209         val alltacs = (*we expect at least 1 stac in a script*)
  1210           map ((stac2tac pt thy) o LTool.rep_stacexpr o #2 o
  1211            (handle_leaf "selrul" thy' srls env a v)) (LTool.stacpbls sc)
  1212         val f =
  1213           (case p_ of Frm => get_obj g_form pt p | Res => (fst o (get_obj g_result pt)) p
  1214           | _ => error "")
  1215           (*WN071231 ? replace atomic_appl_tacs with applicable_in (ineff!) ?*)
  1216       in ((gen_distinct Tac.eq_tac) o flat o (map (Rtools.atomic_appl_tacs thy ro erls f))) alltacs end;
  1217 (**)
  1218 end
  1219 (**)