src/Tools/isac/Interpret/script.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Tue, 18 Oct 2016 12:05:03 +0200
changeset 59252 7d3dbc1171ff
parent 59250 727dff4f6b2c
child 59253 f0bb15a046ae
permissions -rw-r--r--
back-track after desing error in previous changeset

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