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