src/Tools/isac/Interpret/script.sml
author Walther Neuper <neuper@ist.tugraz.at>
Sun, 14 Oct 2012 20:00:27 +0200
changeset 48763 9b9936d79dbe
parent 48761 4162c4f6f897
child 52070 77138c64f4f6
permissions -rw-r--r--
2011-->2012: ...

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