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