src/Tools/isac/Interpret/script.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Mon, 10 Oct 2016 18:24:14 +0200
changeset 59250 727dff4f6b2c
parent 59240 bd9f7f08000c
child 59252 7d3dbc1171ff
permissions -rw-r--r--
transport terms in theorems to frontend

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