src/Tools/isac/Interpret/script.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Mon, 07 Dec 2015 10:52:07 +0100
changeset 59185 dbc3a56ccd00
parent 59184 831fa972f73b
child 59186 d9c3e373f8f5
permissions -rw-r--r--
Isabelle2014-->15: Thm.thy is not open anymore, further funs qualified

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