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