src/Tools/isac/Interpret/ctree.sml
author Walther Neuper <neuper@ist.tugraz.at>
Tue, 28 Sep 2010 09:06:56 +0200
branchisac-update-Isa09-2
changeset 38031 460c24a6a6ba
parent 38015 67ba02dffacc
child 38050 4c52ad406c20
permissions -rw-r--r--
tuned error and writeln

# raise error --> error
# writeln in atomtyp, atomty, atomt and xmlsrc
     1 (* use"../ME/ctree.sml";
     2    use"ME/ctree.sml";
     3    use"ctree.sml";
     4    W.N.26.10.99
     5 
     6 tracing (pr_ptree pr_short pt); 
     7 
     8 val Nd ( _, ns) = pt;
     9 
    10 *)
    11 
    12 (*structure Ptree (**): PTREE (**) = ###### outcommented ######*)
    13 signature PTREE =
    14 sig
    15   type ptree
    16   type envp
    17   val e_ptree : ptree
    18   exception PTREE of string
    19   type branch
    20   type ostate
    21   type cellID
    22   type cid
    23   type posel
    24   type pos
    25   type pos'
    26   type loc
    27   type domID
    28   type pblID
    29   type metID
    30   type spec
    31   type 'a ppc
    32   type con
    33   type subs
    34   type subst
    35   type env
    36   type ets
    37   val ets2str : ets -> string
    38   type item
    39   type tac
    40   type tac_
    41   val tac_2str : tac_ -> string
    42   type safe
    43   val safe2str : safe -> string
    44 
    45   type meth
    46   val cappend_atomic : ptree -> pos -> loc -> cterm' -> tac
    47     -> cterm' -> ostate -> cid -> ptree * posel list * cid
    48   val cappend_form : ptree
    49     -> pos -> loc -> cterm' -> cid -> ptree * pos * cid
    50   val cappend_parent : ptree -> pos -> loc -> cterm' -> tac
    51     -> branch -> cid -> ptree * int list * cid
    52   val cappend_problem : ptree -> posel list(*FIXME*) -> loc
    53     -> cterm' list * spec -> cid -> ptree * int list * cellID list
    54   val append_result : ptree -> pos -> cterm' -> ostate -> ptree * pos
    55 
    56   type ppobj
    57   val g_branch : ppobj -> branch
    58   val g_cell : ppobj -> cid
    59   val g_args : ppobj -> (int * (term list)) list (*args of scr*)
    60   val g_form : ppobj -> cterm'
    61   val g_loc : ppobj -> loc
    62   val g_met : ppobj -> meth
    63   val g_domID : ppobj -> domID
    64   val g_metID : ppobj -> metID
    65   val g_model : ppobj -> cterm' ppc
    66   val g_tac : ppobj -> tac
    67   val g_origin : ppobj -> cterm' list * spec
    68   val g_ostate : ppobj -> ostate
    69   val g_pbl : ppobj -> pblID * item ppc
    70   val g_result : ppobj -> cterm'
    71   val g_spec : ppobj -> spec
    72 (*  val get_all : (ppobj -> 'a) -> ptree -> 'a list
    73   val get_alls : (ppobj -> 'a) -> ptree list -> 'a list *)
    74   val get_obj : (ppobj -> 'a) -> ptree -> pos -> 'a     
    75   val gpt_cell : ptree -> cid
    76   val par_pblobj : ptree -> pos -> pos
    77   val pre_pos : pos -> pos
    78   val lev_dn : int list -> int list
    79   val lev_on : pos -> posel list
    80   val lev_pred : pos -> pos
    81   val lev_up : pos -> pos
    82 (*  val pr_cell : pos -> ppobj -> string
    83   val pr_pos : int list -> string        *)
    84   val pr_ptree : (pos -> ppobj -> string) -> ptree -> string
    85   val pr_short : pos -> ppobj -> string
    86 (*  val repl : 'a list -> int -> 'a -> 'a list
    87   val repl_app : 'a list -> int -> 'a -> 'a list
    88   val repl_branch : branch -> ppobj -> ppobj
    89   val repl_domID : domID -> ppobj -> ppobj
    90   val repl_form : cterm' -> ppobj -> ppobj
    91   val repl_met : item ppc -> ppobj -> ppobj
    92   val repl_metID : metID -> ppobj -> ppobj
    93   val repl_model : cterm' list -> ppobj -> ppobj
    94   val repl_tac : tac -> ppobj -> ppobj
    95   val repl_pbl : item ppc -> ppobj -> ppobj
    96   val repl_pblID : pblID -> ppobj -> ppobj
    97   val repl_result : cterm' -> ostate -> ppobj -> ppobj
    98   val repl_spec : spec -> ppobj -> ppobj
    99   val repl_subs : (string * string) list -> ppobj -> ppobj     *)
   100   val rootthy : ptree -> domID
   101 (*  val test_trans : ppobj -> bool
   102   val uni__asm : (string * pos) list -> ppobj -> ppobj
   103   val uni__cid : cellID list -> ppobj -> ppobj                 *)
   104   val union_asm : ptree -> pos -> (string * pos) list -> ptree
   105   val union_cid : ptree -> pos -> cellID list -> ptree
   106   val update_branch : ptree -> pos -> branch -> ptree
   107   val update_domID : ptree -> pos -> domID -> ptree
   108   val update_met : ptree -> pos -> meth -> ptree
   109   val update_metppc : ptree -> pos -> item ppc -> ptree
   110   val update_metID : ptree -> pos -> metID -> ptree
   111   val update_tac : ptree -> pos -> tac -> ptree
   112   val update_pbl : ptree -> pos -> pblID * item ppc -> ptree
   113   val update_pblppc : ptree -> pos -> item ppc -> ptree
   114   val update_pblID : ptree -> pos -> pblID -> ptree
   115   val update_spec : ptree -> pos -> spec -> ptree
   116   val update_subs : ptree -> pos -> (string * string) list -> ptree
   117 
   118   val rep_pblobj : ppobj
   119     -> {branch:branch, cell:cid, env:envp, loc:loc, meth:meth, model:cterm' ppc,
   120         origin:cterm' list * spec, ostate:ostate, probl:pblID * item ppc,
   121         result:cterm', spec:spec}
   122   val rep_prfobj : ppobj
   123     -> {branch:branch, cell:cid, form:cterm', loc:loc, tac:tac,
   124         ostate:ostate, result:cterm'}
   125 end 
   126 
   127 (* -------------- 
   128 structure Ptree (**): PTREE (**) =
   129 struct
   130  -------------- *)
   131 
   132 type env = (term * term) list;
   133 
   134    
   135 datatype branch = 
   136 	 NoBranch | AndB | OrB 
   137        | TransitiveB  (* FIXXXME.8.03: set branch from met in Apply_Method
   138                          FIXXXME.0402: -"- in Begin_Trans'*)
   139        | SequenceB | IntersectB | CollectB | MapB;
   140 fun branch2str NoBranch = "NoBranch"
   141   | branch2str AndB = "AndB"
   142   | branch2str OrB = "OrB"
   143   | branch2str TransitiveB = "TransitiveB" 
   144   | branch2str SequenceB = "SequenceB"
   145   | branch2str IntersectB = "IntersectB"
   146   | branch2str CollectB = "CollectB"
   147   | branch2str MapB = "MapB";
   148 
   149 datatype ostate = 
   150     Incomplete | Complete | Inconsistent(*WN041020 latter unused*);
   151 fun ostate2str Incomplete = "Incomplete"
   152   | ostate2str Complete = "Complete"
   153   | ostate2str Inconsistent = "Inconsistent";
   154 
   155 type cellID = int;     
   156 type cid = cellID list;
   157 
   158 type posel = int;     (* roundabout for (some of) nice signatures *)
   159 type pos = posel list;
   160 val pos2str = ints2str';
   161 datatype pos_ = 
   162     Pbl    (*PblObj-position: problem-type*)
   163   | Met    (*PblObj-position: method*)
   164   | Frm    (*PblObj-position: -> Pbl in ME (not by moveDown !)
   165            | PrfObj-position: formula*)
   166   | Res    (*PblObj | PrfObj-position: result*)
   167   | Und;   (*undefined*)
   168 fun pos_2str Pbl = "Pbl"
   169   | pos_2str Met = "Met"
   170   | pos_2str Frm = "Frm"
   171   | pos_2str Res = "Res"
   172   | pos_2str Und = "Und";
   173 
   174 type pos' = pos * pos_;
   175 (*WN.12.03 remembering interator (pos * pos_) for ptree 
   176 	   pos : lev_on, lev_dn, lev_up, 
   177                  lev_onFrm, lev_dnRes (..see solve Apply_Method !) 
   178            pos_:
   179 # generate1 sets pos_ if possible  ...?WN0502?NOT...
   180 # generate1 does NOT set pos, because certain nodes can be lev_on OR lev_dn
   181                      exceptions: Begin/End_Trans
   182 # thus generate(1) called in
   183 .# assy, locate_gen 
   184 .# nxt_solv (tac_ -cases); general case: 
   185   val pos' = case pos' of (p,Res) => (lev_on p',Res) | _ => pos'
   186 # WN050220, S(604):
   187   generate1...(Rewrite(f,..,res))..(pos, pos_)
   188      cappend_atomic.................pos //////  gets f+res always!!!
   189         cut_tree....................pos, pos_ 
   190 *)
   191 fun pos'2str (p,p_) = pair2str (ints2str' p, pos_2str p_);
   192 fun pos's2str ps = (strs2str' o (map pos'2str)) ps;
   193 val e_pos' = ([],Und):pos';
   194 
   195 fun res2str (t, ts) = pair2str (term2str t, terms2str ts);
   196 fun asm2str (t, p:pos) = pair2str (term2str t, ints2str' p);
   197 fun asms2str asms = (strs2str' o (map asm2str)) asms;
   198 
   199 
   200 
   201 (*26.4.02: never used after introduction of scripts !!!
   202 type loc =  loc_ *        (* + interpreter-state          *)
   203 	    (loc_ * rls') (* -"- for script of the ruleset*)
   204 		option;
   205 val e_loc = ([],NONE):loc;
   206 val ee_loc = (e_loc,e_loc);*)
   207 
   208 
   209 datatype safe = Sundef | Safe | Unsafe | Helpless;
   210 fun safe2str Sundef   = "Sundef"
   211   | safe2str Safe     = "Safe"
   212   | safe2str Unsafe   = "Unsafe" 
   213   | safe2str Helpless = "Helpless";
   214 
   215 type subs = cterm' list; (*16.11.00 for FE-KE*)
   216 val e_subs = ["(bdv, x)"];
   217 
   218 (*._sub_stitution as strings of _e_qualities.*)
   219 type sube = cterm' list;
   220 val e_sube = []:cterm' list;
   221 fun sube2str s = strs2str s;
   222 
   223 (*._sub_stitution as _t_erms of _e_qualities.*)
   224 type subte = term list;
   225 val e_subte = []:term list;
   226 fun subte2str ss = terms2str ss;
   227 
   228 fun subte2sube ss = map term2str ss;
   229 
   230 fun subst2subs s = map (pair2str o 
   231 			(apfst (Syntax.string_of_term (thy2ctxt' "Isac"))) o
   232 			(apsnd (Syntax.string_of_term (thy2ctxt' "Isac")))) s;
   233 fun subst2subs' s = map ((apfst (Syntax.string_of_term (thy2ctxt' "Isac"))) o
   234 			 (apsnd (Syntax.string_of_term (thy2ctxt' "Isac")))) s;
   235 fun subs2subst thy s = map (isapair2pair o term_of o the o (parse thy)) s;
   236 (*> subs2subst thy ["(bdv,x)","(err,#0)"];
   237 val it =
   238   [(Free ("bdv","RealDef.real"),Free ("x","RealDef.real")),
   239    (Free ("err","RealDef.real"),Free ("#0","RealDef.real"))] 
   240    : (term * term) list*)
   241 (*["bdv=x","err=0"] ---> [(bdv,x), (err,0)]*)
   242 fun sube2subst thy s = map (dest_equals' o term_of o the o (parse thy)) s;
   243 (* val ts = sube2subst thy ["bdv=x","err=0"];
   244    subst2str' ts;
   245    *)
   246 fun sube2subte ss = map str2term ss;
   247 
   248 
   249 fun isasub2subst isasub = ((map isapair2pair) o isalist2list) isasub;
   250 
   251 
   252 type scrstate =       (*state for script interpreter*)
   253 	 env(*stack*) (*used to instantiate tac for checking assod
   254 		       12.03.noticed: e_ not updated during execution ?!?*)
   255 	 * loc_       (*location of tac in script*)
   256 	 * term option(*argument of curried functions*)
   257 	 * term       (*value obtained by tac executed
   258 		       updated also after a derivation by 'new_val'*)
   259 	 * safe       (*estimation of how result will be obtained*)
   260 	 * bool;      (*true = strongly .., false = weakly associated: 
   261 					    only used during ass_dn/up*)
   262 val e_scrstate = ([],[],NONE,e_term,Sundef,false):scrstate;
   263 
   264 
   265 (*21.8.02 ---> definitions.sml for datatype scr 
   266 type rrlsstate =      (*state for reverse rewriting*)
   267      (term *          (*the current formula*)
   268       rule list      (*of reverse rewrite set (#1#)*)
   269 	    list *    (*may be serveral, eg. in norm_rational*)
   270       (rule *         (*Thm (+ Thm generated from Calc) resulting in ...*)
   271        (term *        (*... rewrite with ...*)
   272 	term list))   (*... assumptions*)
   273 	  list);      (*derivation from given term to normalform
   274 		       in reverse order with sym_thm; 
   275                        (#1#) could be extracted from here #1*) --------*)
   276      
   277 datatype istate =     (*interpreter state*)
   278 	 Uistate                 (*undefined in modspec, in '_deriv'ation*)
   279        | ScrState of scrstate    (*for script interpreter*)
   280        | RrlsState of rrlsstate; (*for reverse rewriting*)
   281 val e_istate = (ScrState ([],[],NONE,e_term,Sundef,false)):istate;
   282 
   283 type iist = istate option * istate option;
   284 (*val e_iist = (e_istate, e_istate); --- sinnlos f"ur NICHT-equality-type*) 
   285 
   286 
   287 fun rta2str (r,(t,a)) = "\n("^(rule2str r)^",("^(term2str t)^", "^
   288 		      (terms2str a)^"))";
   289 fun istate2str Uistate = "Uistate"
   290   | istate2str (ScrState (e,l,to,t,s,b):istate) =
   291     "ScrState ("^ subst2str e ^",\n "^ 
   292     loc_2str l ^", "^ termopt2str to ^",\n "^
   293     term2str t ^", "^ safe2str s ^", "^ bool2str b ^")"
   294   | istate2str (RrlsState (t,t1,rss,rtas)) = 
   295     "RrlsState ("^(term2str t)^", "^(term2str t1)^", "^
   296     ((strs2str o (map (strs2str o (map rule2str)))) rss)^", "^
   297     ((strs2str o (map rta2str)) rtas)^")";
   298 fun istates2str (NONE, NONE) = "(#NONE, #NONE)"
   299   | istates2str (NONE, SOME ist) = "(#NONE,\n#SOME "^istate2str ist^")"
   300   | istates2str (SOME ist, NONE) = "(#SOME "^istate2str ist^",\n #NONE)"
   301   | istates2str (SOME i1, SOME i2) = "(#SOME "^istate2str i1^",\n #SOME "^
   302 				     istate2str i2^")";
   303 
   304 fun new_val v (ScrState (env, loc_, topt, _, safe, bool)) =
   305     (ScrState (env, loc_, topt, v, safe, bool))
   306   | new_val _ _ = error "new_val: only for ScrState";
   307 
   308 datatype con = land | lor;
   309 
   310 
   311 type spec = 
   312      domID * (*WN.12.03: is replaced by thy from get_met ?FIXME? in:
   313 	      specify (Init_Proof..), nxt_specify_init_calc,
   314 	      assod (.SubProblem...), stac2tac (.SubProblem...)*)
   315      pblID * 
   316      metID;
   317 fun spec2str ((dom,pbl,met)(*:spec*)) = 
   318   "(" ^ (quote dom) ^ ", " ^ (strs2str pbl) ^ 
   319   ", " ^ (strs2str met) ^ ")";
   320 (*> spec2str empty_spec;
   321 val it = "(\"\", [], (\"\", \"\"))" : string *)
   322 val empty_spec = (e_domID,e_pblID,e_metID):spec;
   323 val e_spec = empty_spec;
   324 
   325 
   326 
   327 (*.tactics propagate the construction of the calc-tree;
   328    there are
   329    (a) 'specsteps' for the specify-phase, and others for the solve-phase
   330    (b) those of the solve-phase are 'initac's and others;
   331        initacs start with a formula different from the preceding formula.
   332    see 'type tac_' for the internal representation of tactics.*)
   333 datatype tac = 
   334   Init_Proof of ((cterm' list) * spec)
   335 (*'specsteps'...*)
   336 | Model_Problem
   337 | Refine_Problem of pblID              | Refine_Tacitly of pblID
   338 
   339 | Add_Given of cterm'                  | Del_Given of cterm'
   340 | Add_Find of cterm'                   | Del_Find of cterm'
   341 | Add_Relation of cterm'               | Del_Relation of cterm'
   342 
   343 | Specify_Theory of domID              | Specify_Problem of pblID
   344 | Specify_Method of metID
   345 (*...'specsteps'*)
   346 | Apply_Method of metID 
   347 (*.creates an 'istate' in PblObj.env; in case of 'init_form' 
   348    creates a formula at ((lev_on o lev_dn) p, Frm) and in this ppobj.'loc' 
   349    'SOME istate' (at fst of 'loc').
   350    As each step (in the solve-phase) has a resulting formula (at the front-end)
   351    Apply_Method also does the 1st step in the script (an 'initac') if there
   352    is no 'init_form' .*)
   353 | Check_Postcond of pblID
   354 | Free_Solve
   355 
   356 | Rewrite_Inst of ( subs * thm')       | Rewrite of thm'
   357                                        | Rewrite_Asm of thm'
   358 | Rewrite_Set_Inst of ( subs * rls')   | Rewrite_Set of rls'        
   359 | Detail_Set_Inst of ( subs * rls')    | Detail_Set of rls'
   360 | End_Detail  (*end of script from next_tac, 
   361                 in solve: switches back to parent script WN0509 drop!*)
   362 | Derive of rls' (*an input formula using rls WN0509 drop!*)
   363 | Calculate of string (* plus | minus | times | cancel | pow | sqrt *)
   364 | End_Ruleset
   365 | Substitute of sube                   | Apply_Assumption of cterm' list
   366 
   367 | Take of cterm'      (*an 'initac'*)
   368 | Take_Inst of cterm'  
   369 | Group of (con * int list ) 
   370 | Subproblem of (domID * pblID) (*an 'initac'*)
   371 | CAScmd of cterm'  (*6.6.02 URD: Function formula; WN0509 drop!*)
   372 | End_Subproblem    (*WN0509 drop!*)
   373 
   374 | Split_And                            | Conclude_And
   375 | Split_Or                             | Conclude_Or
   376 | Begin_Trans                          | End_Trans
   377 | Begin_Sequ                           | End_Sequ(* substitute root.env *)
   378 | Split_Intersect                      | End_Intersect
   379 | Check_elementwise of cterm'          | Collect_Trues
   380 | Or_to_List
   381 
   382 | Empty_Tac (*TODO.11.6.03 ... of string: could carry msg of (Notappl msg)
   383 	       in 'helpless'*)
   384 | Tac of string(* eg.'repeat'*WN0509 drop!*)
   385 | User                                 (*internal, for ets*WN0509 drop!*)
   386 | End_Proof';(* inout*)
   387 
   388 (* tac2str /--> library.sml: needed in dialog.sml for 'separable *)
   389 fun tac2str (ma:tac) = case ma of
   390     Init_Proof (ppc, spec)  => 
   391       "Init_Proof "^(pair2str (strs2str ppc, spec2str spec))
   392   | Model_Problem           => "Model_Problem "
   393   | Refine_Tacitly pblID    => "Refine_Tacitly "^(strs2str pblID)
   394   | Refine_Problem pblID    => "Refine_Problem "^(strs2str pblID)
   395   | Add_Given cterm'        => "Add_Given "^cterm'
   396   | Del_Given cterm'        => "Del_Given "^cterm'
   397   | Add_Find cterm'         => "Add_Find "^cterm'
   398   | Del_Find cterm'         => "Del_Find "^cterm'
   399   | Add_Relation cterm'     => "Add_Relation "^cterm'
   400   | Del_Relation cterm'     => "Del_Relation "^cterm'
   401 
   402   | Specify_Theory domID    => "Specify_Theory "^(quote domID    )
   403   | Specify_Problem pblID   => "Specify_Problem "^(strs2str pblID )
   404   | Specify_Method metID    => "Specify_Method "^(strs2str metID)
   405   | Apply_Method metID      => "Apply_Method "^(strs2str metID)
   406   | Check_Postcond pblID    => "Check_Postcond "^(strs2str pblID)
   407   | Free_Solve              => "Free_Solve"
   408 
   409   | Rewrite_Inst (subs,thm')=> 
   410       "Rewrite_Inst "^(pair2str (subs2str subs, spair2str thm'))
   411   | Rewrite thm'            => "Rewrite "^(spair2str thm')
   412   | Rewrite_Asm thm'        => "Rewrite_Asm "^(spair2str thm')
   413   | Rewrite_Set_Inst (subs, rls) => 
   414       "Rewrite_Set_Inst "^(pair2str (subs2str subs, quote rls))
   415   | Rewrite_Set rls         => "Rewrite_Set "^(quote rls    )
   416   | Detail_Set rls          => "Detail_Set "^(quote rls    )
   417   | Detail_Set_Inst (subs, rls) => 
   418       "Detail_Set_Inst "^(pair2str (subs2str subs, quote rls))
   419   | End_Detail              => "End_Detail"
   420   | Derive rls'             => "Derive "^rls' 
   421   | Calculate op_           => "Calculate "^op_ 
   422   | Substitute sube         => "Substitute "^sube2str sube	     
   423   | Apply_Assumption ct's   => "Apply_Assumption "^(strs2str ct's)
   424 
   425   | Take cterm'             => "Take "^(quote cterm'	)
   426   | Take_Inst cterm'        => "Take_Inst "^(quote cterm' )
   427   | Group (con, ints)       => 
   428       "Group "^(pair2str (con2str con, ints2str ints))
   429   | Subproblem (domID, pblID) => 
   430       "Subproblem "^(pair2str (domID, strs2str pblID))
   431 (*| Subproblem_Full (spec, cts') => 
   432       "Subproblem_Full "^(pair2str (spec2str spec, strs2str cts'))*)
   433   | End_Subproblem          => "End_Subproblem"
   434   | CAScmd cterm'           => "CAScmd "^(quote cterm')
   435 
   436   | Check_elementwise cterm'=> "Check_elementwise "^(quote cterm') 
   437   | Or_to_List              => "Or_to_List "
   438   | Collect_Trues           => "Collect_Trues"
   439 
   440   | Empty_Tac             => "Empty_Tac"
   441   | Tac string            => "Tac "^string
   442   | User                    => "User"
   443   | End_Proof'              => "tac End_Proof'"
   444   | _                       => "tac2str not impl. for ?!";
   445 
   446 fun is_rewset (Rewrite_Set_Inst _) = true
   447   | is_rewset (Rewrite_Set _) = true 
   448   | is_rewset _ = false;
   449 fun is_rewtac (Rewrite _) = true
   450   | is_rewtac (Rewrite_Inst _) = true
   451   | is_rewtac (Rewrite_Asm _) = true
   452   | is_rewtac tac = is_rewset tac;
   453 
   454 fun tac2IDstr (ma:tac) = case ma of
   455     Model_Problem           => "Model_Problem"
   456   | Refine_Tacitly pblID    => "Refine_Tacitly"
   457   | Refine_Problem pblID    => "Refine_Problem"
   458   | Add_Given cterm'        => "Add_Given"
   459   | Del_Given cterm'        => "Del_Given"
   460   | Add_Find cterm'         => "Add_Find"
   461   | Del_Find cterm'         => "Del_Find"
   462   | Add_Relation cterm'     => "Add_Relation"
   463   | Del_Relation cterm'     => "Del_Relation"
   464 
   465   | Specify_Theory domID    => "Specify_Theory"
   466   | Specify_Problem pblID   => "Specify_Problem"
   467   | Specify_Method metID    => "Specify_Method"
   468   | Apply_Method metID      => "Apply_Method"
   469   | Check_Postcond pblID    => "Check_Postcond"
   470   | Free_Solve              => "Free_Solve"
   471 
   472   | Rewrite_Inst (subs,thm')=> "Rewrite_Inst"
   473   | Rewrite thm'            => "Rewrite"
   474   | Rewrite_Asm thm'        => "Rewrite_Asm"
   475   | Rewrite_Set_Inst (subs, rls) => "Rewrite_Set_Inst"
   476   | Rewrite_Set rls         => "Rewrite_Set"
   477   | Detail_Set rls          => "Detail_Set"
   478   | Detail_Set_Inst (subs, rls) => "Detail_Set_Inst"
   479   | Derive rls'             => "Derive "
   480   | Calculate op_           => "Calculate "
   481   | Substitute subs         => "Substitute" 
   482   | Apply_Assumption ct's   => "Apply_Assumption"
   483 
   484   | Take cterm'             => "Take"
   485   | Take_Inst cterm'        => "Take_Inst"
   486   | Group (con, ints)       => "Group"
   487   | Subproblem (domID, pblID) => "Subproblem"
   488   | End_Subproblem          => "End_Subproblem"
   489   | CAScmd cterm'           => "CAScmd"
   490 
   491   | Check_elementwise cterm'=> "Check_elementwise"
   492   | Or_to_List              => "Or_to_List "
   493   | Collect_Trues           => "Collect_Trues"
   494 
   495   | Empty_Tac             => "Empty_Tac"
   496   | Tac string            => "Tac "
   497   | User                    => "User"
   498   | End_Proof'              => "End_Proof'"
   499   | _                       => "tac2str not impl. for ?!";
   500 
   501 fun rls_of (Rewrite_Set_Inst (_, rls)) = rls
   502   | rls_of (Rewrite_Set rls) = rls
   503   | rls_of tac = error ("rls_of: called with tac '"^tac2IDstr tac^"'");
   504 
   505 fun thm_of_rew (Rewrite_Inst (subs,(thmID,_))) = 
   506     (thmID, SOME ((subs2subst (assoc_thy "Isac.thy") subs):subst))
   507   | thm_of_rew (Rewrite  (thmID,_)) = (thmID, NONE)
   508   | thm_of_rew (Rewrite_Asm (thmID,_)) = (thmID, NONE);
   509 
   510 fun rls_of_rewset (Rewrite_Set_Inst (subs,rls)) = 
   511     (rls, SOME ((subs2subst (assoc_thy "Isac.thy") subs):subst))
   512   | rls_of_rewset (Rewrite_Set rls) = (rls, NONE)
   513   | rls_of_rewset (Detail_Set rls) = (rls, NONE)
   514   | rls_of_rewset (Detail_Set_Inst (subs, rls)) = 
   515     (rls, SOME ((subs2subst (assoc_thy "Isac.thy") subs):subst));
   516 
   517 fun rule2tac _ (Calc (opID, thm)) = Calculate (calID2calcID opID)
   518   | rule2tac [] (Thm (thmID, thm)) = Rewrite (thmID, string_of_thmI thm)
   519   | rule2tac subst (Thm (thmID, thm)) = 
   520     Rewrite_Inst (subst2subs subst, (thmID, string_of_thmI thm))
   521   | rule2tac [] (Rls_ rls) = Rewrite_Set (id_rls rls)
   522   | rule2tac subst (Rls_ rls) = 
   523     Rewrite_Set_Inst (subst2subs subst, (id_rls rls))
   524   | rule2tac _ rule = 
   525     error ("rule2tac: called with '" ^ rule2str rule ^ "'");
   526 
   527 type fmz_ = cterm' list;
   528 
   529 (*.a formalization of an example containing data 
   530    sufficient for mechanically finding the solution for the example.*)
   531 (*FIXME.WN051014: dont store fmz = (_,spec) in the PblObj, 
   532   this is done in origin*)
   533 type fmz = fmz_ * spec;
   534 val e_fmz = ([],e_spec);
   535 
   536 (*tac_ is made from tac in applicable_in,
   537   and carries all data necessary for generate;*)
   538 datatype tac_ = 
   539 (* datatype tac = *)
   540   Init_Proof' of ((cterm' list) * spec)
   541                 (* ori list !: code specify -> applicable*)
   542 | Model_Problem' of pblID * 
   543 		    itm list *  (*the 'untouched' pbl*)
   544 		    itm list    (*the casually completed met*)
   545 | Refine_Tacitly' of pblID *    (*input*)
   546 		     pblID *    (*the refined from applicable_in*)
   547 		     domID *    (*from new pbt?! filled in specify*)
   548 		     metID *    (*from new pbt?! filled in specify*)
   549 		     itm list   (*drop ! 9.03: remains [] for
   550                                   Model_Problem recognizing its activation*)
   551 | Refine_Problem' of (pblID * (itm list * (bool * Term.term) list))
   552  (*FIXME?040215 drop: done automatically in init_proof + Subproblem'*)
   553 | Add_Given'    of cterm' *
   554 		   itm list (*updated with input in fun specify_additem*)
   555 | Add_Find'     of cterm' *
   556 		   itm list (*updated with input in fun specify_additem*)
   557 | Add_Relation' of cterm' *
   558 		 itm list (*updated with input in fun specify_additem*)
   559 | Del_Given' of cterm'   | Del_Find' of cterm'   | Del_Relation' of cterm'
   560   (*4.00.: all..    term: in applicable_in ..? Syn ?only for FormFK?*)
   561 
   562 | Specify_Theory' of domID              
   563 | Specify_Problem' of (pblID *        (*               *)
   564 		       (bool *        (* matches	     *)
   565 			(itm list *   (* ppc	     *)
   566 			 (bool * term) list))) (* preconditions *)
   567 | Specify_Method' of metID *
   568 		     ori list * (*repl. "#undef"*)
   569 		     itm list   (*... updated from pbl to met*)
   570 | Apply_Method' of metID * 
   571 		   (term option) * (*init_form*)
   572 		   istate		        
   573 | Check_Postcond' of 
   574   pblID * 
   575   (term *      (*returnvalue of script in solve*)
   576    cterm' list)(*collect by get_assumptions_ in applicable_in, except if 
   577                  butlast tac is Check_elementwise: take only these asms*)
   578 | Free_Solve'
   579 
   580 | Rewrite_Inst' of theory' * rew_ord' * rls
   581 		   * bool * subst * thm' * term * (term  * term list)
   582 | Rewrite' of theory' * rew_ord' * rls * bool * thm' * 
   583 	      term * (term * term list)
   584 | Rewrite_Asm' of theory' * rew_ord' * rls * bool * thm' * 
   585   term * (term * term list)
   586 | Rewrite_Set_Inst' of theory' * bool * subst * rls * 
   587 		       term * (term * term list)
   588 | Detail_Set_Inst' of theory' * bool * subst * rls * 
   589 		      term * (term * term list)
   590 | Rewrite_Set' of theory' * bool * rls * term * (term * term list)
   591 | Detail_Set' of theory' * bool * rls * term * (term * term list)
   592 | End_Detail' of (term * (term list)) (*see End_Trans'*)
   593 | End_Ruleset' of term
   594 | Derive' of rls
   595 | Calculate' of theory' * string * term * (term * thm') 
   596 	      (*WN.29.4.03 asm?: * term list??*)
   597 | Substitute' of subte  (*the 'substitution': terms of type bool*) 
   598 		 * term (*to be substituted in*)
   599 		 * term (*resulting from the substitution*)
   600 | Apply_Assumption' of term list * term
   601 
   602 | Take' of term                         | Take_Inst' of term  
   603 | Group' of (con * int list * term)
   604 | Subproblem' of (spec * 
   605 		  (ori list) * (*filled in assod Subproblem'*)
   606 		  term *       (*-"-, headline of calc-head *)
   607 		  fmz_ * 
   608 		  term)        (*Subproblem(dom,pbl)*)  
   609 | CAScmd' of term
   610 | End_Subproblem' of term (*???*)
   611 | Split_And' of term                    | Conclude_And' of term
   612 | Split_Or' of term                     | Conclude_Or' of term
   613 | Begin_Trans' of term                  | End_Trans' of (term * (term list))
   614 | Begin_Sequ'                           | End_Sequ'(* substitute root.env*)
   615 | Split_Intersect' of term              | End_Intersect' of term
   616 | Check_elementwise' of (*special case:*)
   617   term *   (*(1)the current formula: [x=1,x=...]*)
   618   string * (*(2)the pred from Check_elementwise   *)
   619   (term *  (*(3)composed from (1) and (2): {x. pred}*)
   620    term list) (*20.5.03 assumptions*)
   621 
   622 | Or_to_List' of term * term            (* (a | b, [a,b]) *)
   623 | Collect_Trues' of term
   624 
   625 | Empty_Tac_                          | Tac_ of  (*for dummies*)
   626                                             theory *
   627                                             string * (*form*)
   628 					    string * (*in Tac*)
   629 					    string   (*result of Tac".."*)
   630 | User' (*internal for ets*)            | End_Proof'';(*End_Proof:inout*)
   631 
   632 fun tac_2str ma = case ma of
   633     Init_Proof' (ppc, spec)  => 
   634       "Init_Proof' "^(pair2str (strs2str ppc, spec2str spec))
   635   | Model_Problem' (pblID,_,_)     => "Model_Problem' "^(strs2str pblID )
   636   | Refine_Tacitly'(p,prefin,domID,metID,itms)=> 
   637     "Refine_Tacitly' ("
   638     ^(strs2str p)^", "^(strs2str prefin)^", "
   639     ^domID^", "^(strs2str metID)^", pbl-itms)"
   640   | Refine_Problem' ms       => "Refine_Problem' ("^(*matchs2str ms*)"..."^")"
   641 (*| Match_Problem' (pI, (ok, (itms, pre))) => 
   642     "Match_Problem' "^(spair2str (strs2str pI,
   643 				  spair2str (bool2str ok,
   644 					     spair2str ("itms2str_ itms", 
   645 							"items2str pre"))))*)
   646   | Add_Given' cterm'        => "Add_Given' "(*^cterm'*)
   647   | Del_Given' cterm'        => "Del_Given' "(*^cterm'*)
   648   | Add_Find' cterm'         => "Add_Find' "(*^cterm'*)
   649   | Del_Find' cterm'         => "Del_Find' "(*^cterm'*)
   650   | Add_Relation' cterm'     => "Add_Relation' "(*^cterm'*)
   651   | Del_Relation' cterm'     => "Del_Relation' "(*^cterm'*)
   652 
   653   | Specify_Theory' domID    => "Specify_Theory' "^(quote domID    )
   654   | Specify_Problem' (pI, (ok, (itms, pre))) => 
   655     "Specify_Problem' "^(spair2str (strs2str pI,
   656 				  spair2str (bool2str ok,
   657 					     spair2str ("itms2str_ itms", 
   658 							"items2str pre"))))
   659   | Specify_Method' (pI,oris,itms) => 
   660     "Specify_Method' ("^metID2str pI^", "^oris2str oris^", )"
   661 
   662   | Apply_Method' (metID,_,_)      => "Apply_Method' "^(strs2str metID)
   663   | Check_Postcond' (pblID,(scval,asm)) => 
   664       "Check_Postcond' "^(spair2str(strs2str pblID, 
   665 				    spair2str (term2str scval, strs2str asm)))
   666 
   667   | Free_Solve'              => "Free_Solve'"
   668 
   669   | Rewrite_Inst' (*subs,thm'*) _ => 
   670       "Rewrite_Inst' "(*^(pair2str (subs2str subs, spair2str thm'))*)
   671   | Rewrite' thm'            => "Rewrite' "(*^(spair2str thm')*)
   672   | Rewrite_Asm' thm'        => "Rewrite_Asm' "(*^(spair2str thm')*)
   673   | Rewrite_Set_Inst' (*subs,thm'*) _ => 
   674       "Rewrite_Set_Inst' "(*^(pair2str (subs2str subs, quote rls))*)
   675   | Rewrite_Set'(thy',pasm,rls',f,(f',asm))          
   676     => "Rewrite_Set' ("^thy'^","^(bool2str pasm)^","^(id_rls rls')^","
   677     ^(Syntax.string_of_term (thy2ctxt' "Isac") f)^",("^(Syntax.string_of_term (thy2ctxt' "Isac") f')
   678     ^","^((strs2str o (map (Syntax.string_of_term (thy2ctxt' "Isac")))) asm)^"))"
   679 
   680   | End_Detail' _             => "End_Detail' xxx"
   681   | Detail_Set' _             => "Detail_Set' xxx"
   682   | Detail_Set_Inst' _        => "Detail_Set_Inst' xxx"
   683 
   684   | Derive' rls              => "Derive' "^id_rls rls
   685   | Calculate'  _            => "Calculate' "
   686   | Substitute' subs         => "Substitute' "(*^(subs2str subs)*)    
   687   | Apply_Assumption' ct's   => "Apply_Assumption' "(*^(strs2str ct's)*)
   688 
   689   | Take' cterm'             => "Take' "(*^(quote cterm'	)*)
   690   | Take_Inst' cterm'        => "Take_Inst' "(*^(quote cterm' )*)
   691   | Group' (con, ints, _)     => 
   692       "Group' "^(pair2str (con2str con, ints2str ints))
   693   | Subproblem' (spec, oris, _,_,pbl_form) => 
   694       "Subproblem' "(*^(pair2str (domID, strs2str ,...))*)
   695   | End_Subproblem'  _       => "End_Subproblem'"
   696   | CAScmd' cterm'           => "CAScmd' "(*^(quote cterm')*)
   697 
   698   | Empty_Tac_             => "Empty_Tac_"
   699   | User'                    => "User'"
   700   | Tac_ (_,form,id,result) => "Tac_ (thy,"^form^","^id^","^result^")"
   701   | _                       => "tac_2str not impl. for arg";
   702 
   703 (*'executed tactics' (tac_s) with local environment etc.;
   704   used for continuing eval script + for generate*)
   705 type ets =
   706     (loc_ *      (* of tactic in scr, tactic (weakly) associated with tac_*)
   707      (tac_ * 	 (* (for generate)  *)
   708       env *      (* with 'tactic=result' as a rule, tactic ev. _not_ ready:
   709 		  for handling 'parallel let'*)
   710       env *      (* with results of (ready) tacs        *)
   711       term *     (* itr_arg of tactic, for upd. env at Repeat, Try*)
   712       term * 	 (* result value of the tac         *)
   713       safe))
   714     list;
   715 val Ets = []:ets;
   716 
   717 
   718 fun ets2s (l,(m,eno,env,iar,res,s)) = 
   719   "\n("^(loc_2str l)^",("^(tac_2str m)^
   720   ",\n  ens= "^(subst2str eno)^
   721   ",\n  env= "^(subst2str env)^
   722   ",\n  iar= "^(Syntax.string_of_term (thy2ctxt' "Isac") iar)^
   723   ",\n  res= "^(Syntax.string_of_term (thy2ctxt' "Isac") res)^
   724   ",\n  "^(safe2str s)^"))";
   725 fun ets2str (ets:ets) = (strs2str o (map ets2s)) ets;
   726 
   727 
   728 type envp =(*9.5.03: unused, delete with field in ptree.PblObj FIXXXME*)
   729    (int * term list) list * (*assoc-list: args of met*)
   730    (int * rls) list *       (*assoc-list: tacs already done ///15.9.00*)
   731    (int * ets) list *       (*assoc-list: tacs etc. already done*)
   732    (string * pos) list;     (*asms * from where*)
   733 val empty_envp = ([],[],[],[]):envp; 
   734 
   735 datatype ppobj = 
   736     PrfObj of {cell  : lrd option, (*where in form tac has been applied*)
   737 	       (*^^^FIXME.WN0607 rename this field*)
   738 	       form  : term,    
   739 	       tac   : tac,         (* also in istate*)
   740 	       loc   : istate option * istate option, (*for form, result 
   741 13.8.02: (NONE,NONE) <==> e_istate ! see update_loc, get_loc*)
   742 	       branch: branch,
   743 	       result: term * term list,    
   744 	       ostate: ostate}    (*Complete <=> result is OK*)
   745   | PblObj of {cell  : lrd option,(*unused: meaningful only for some _Prf_Obj*)
   746 	       fmz   : fmz,       (*from init:FIXME never use this spec;-drop*)
   747 	       origin: (ori list) * (*representation from fmz+pbt
   748                                   for efficiently adding items in probl, meth*)
   749 		       spec *     (*updated by Refine_Tacitly*)
   750 		       term,      (*headline of calc-head, as calculated 
   751 							      initially(!)*)
   752 		       (*# the origin of a root-pbl is created from fmz
   753                            (thus providing help for input to the user),
   754 			 # the origin of a sub-pbl is created from the argument
   755 			   -list of a script-tac 'SubProblem (spec) [arg-list]'
   756 			   by 'match_ags'*)
   757 	       spec  : spec,      (*explicitly input*)
   758 	       probl : itm list,  (*itms explicitly input*)
   759 	       meth  : itm list,  (*itms automatically added to copy of probl
   760 				   TODO: input like to 'probl'*)
   761 	       env   : istate option,(*for problem with initac in script*)
   762 	       loc   : istate option * istate option, (*for pbl+met * result*)
   763 	       branch: branch,
   764 	       result: term * term list,
   765 	       ostate: ostate};   (*Complete <=> result is _proven_ OK*)
   766 
   767 (*.this tree contains isac's calculations; TODO.WN03 rename to ctree;
   768    the structure has been copied from an early version of Theorema(c);
   769    it has the disadvantage, that there is no space 
   770    for the first tactic in a script generating the first formula at (p,Frm);
   771    this trouble has been covered by 'init_form' and 'Take' so far,
   772    but it is crucial if the first tactic in a script is eg. 'Subproblem';
   773    see 'type tac ', Apply_Method.
   774 .*)
   775 datatype ptree = 
   776     EmptyPtree
   777   | Nd of ppobj * (ptree list);
   778 val e_ptree = EmptyPtree;
   779 
   780 fun rep_prfobj (PrfObj {cell,form,tac,loc,branch,result,ostate}) =
   781   {cell=cell,form=form,tac=tac,loc=loc,branch=branch,result=result,ostate=ostate};
   782 fun rep_pblobj (PblObj {cell,origin,fmz,spec,probl,meth,env,
   783 			loc,branch,result,ostate}) =
   784   {cell=cell,origin=origin,fmz=fmz,spec=spec,probl=probl,meth=meth,
   785    env=env,loc=loc,branch=branch,result=result,ostate=ostate};
   786 fun is_prfobj (PrfObj _) = true
   787   | is_prfobj _ =false;
   788 (*val is_prfobj' = get_obj is_prfobj; *)
   789 fun is_pblobj (PblObj _) = true
   790   | is_pblobj _ = false;
   791 (*val is_pblobj' = get_obj is_pblobj; 'Error: unbound constructor get_obj'*)
   792 
   793 
   794 exception PTREE of string;
   795 fun nth _ []      = raise PTREE "nth _ []"
   796   | nth 1 (x::xs) = x
   797   | nth n (x::xs) = nth (n-1) xs;
   798 (*> nth 2 [11,22,33]; -->> val it = 22 : int*)
   799 
   800 fun lev_up ([]:pos) = raise PTREE "lev_up []"
   801   | lev_up p = (drop_last p):pos;
   802 fun lev_on ([]:pos) = raise PTREE "lev_on []"
   803   | lev_on pos = 
   804     let val len = length pos
   805     in (drop_last pos) @ [(nth len pos)+1] end;
   806 fun lev_onFrm ((p,_):pos') = (lev_on p,Frm):pos'
   807   | lev_onFrm p = raise PTREE ("*** lev_onFrm: pos'="^(pos'2str p));
   808 (*040216: for inform --> embed_deriv: remains on same level*)
   809 fun lev_back (([],_):pos') = raise PTREE "lev_on_back: called by ([],_)"
   810   | lev_back (p,_) =
   811     if last_elem p <= 1 then (p, Frm):pos' 
   812     else ((drop_last p) @ [(nth (length p) p) - 1], Res);
   813 (*.increase pos by n within a level.*)
   814 fun pos_plus 0 pos = pos
   815   | pos_plus n ((p,Frm):pos') = pos_plus (n-1) (p, Res)
   816   | pos_plus n ((p,  _):pos') = pos_plus (n-1) (lev_on p, Res);
   817 
   818 
   819 
   820 fun lev_pred ([]:pos) = raise PTREE "lev_pred []"
   821   | lev_pred (pos:pos) = 
   822     let val len = length pos
   823     in ((drop_last pos) @ [(nth len pos)-1]):pos end;
   824 (*lev_pred [1,2,3];
   825 val it = [1,2,2] : pos
   826 > lev_pred [1];
   827 val it = [0] : pos          *)
   828 
   829 fun lev_dn p = p @ [0];
   830 (*> (lev_dn o lev_on) [1,2,3];
   831 val it = [1,2,4,0] : pos    *)
   832 (*fun lev_dn' ((p,p_):pos') = (lev_dn p, Frm):pos'; WN.3.12.03: never used*)
   833 fun lev_dnRes ((p,_):pos') = (lev_dn p, Res):pos';
   834 
   835 (*4.4.00*)
   836 fun lev_up_ ((p,Res):pos') = (lev_up p,Res):pos'
   837   | lev_up_ p' = error ("lev_up_: called for "^(pos'2str p'));
   838 fun lev_dn_ ((p,_):pos') = (lev_dn p,Res):pos'
   839 fun ind ((p,_):pos') = length p; (*WN050108 deprecated in favour of lev_of*)
   840 fun lev_of ((p,_):pos') = length p;
   841 
   842 
   843 (** convert ptree to a string **)
   844 
   845 (* convert a pos from list to string *)
   846 fun pr_pos ps = (space_implode "." (map string_of_int ps))^".   ";
   847 (* show hd origin or form only *)
   848 fun pr_short (p:pos) (PblObj {origin = (ori,_,_),...}) = 
   849   ((pr_pos p) ^ " ----- pblobj -----\n")
   850 (*   ((((Syntax.string_of_term (thy2ctxt' "Isac")) o #4 o hd) ori)^" "^
   851     (((Syntax.string_of_term (thy2ctxt' "Isac")) o hd(*!?!*) o #5 o hd) ori))^
   852    "\n") *)
   853   | pr_short p (PrfObj {form = form,...}) =
   854   ((pr_pos p) ^ (term2str form) ^ "\n");
   855 (*
   856 fun pr_cell (p:pos) (PblObj {cell = c, origin = (ori,_,_),...}) = 
   857   ((ints2str c) ^"   "^ 
   858    ((((Syntax.string_of_term (thy2ctxt' "Isac")) o #4 o hd) ori)^" "^
   859     (((Syntax.string_of_term (thy2ctxt' "Isac")) o hd(*!?!*) o #5 o hd) ori))^
   860    "\n")
   861   | pr_cell p (PrfObj {cell = c, form = form,...}) =
   862   ((ints2str c) ^"   "^ (term2str form) ^ "\n");
   863 *)
   864 
   865 (* convert ptree *)
   866 fun pr_ptree f pt =
   867   let
   868     fun pr_pt pfn _  EmptyPtree = ""
   869       | pr_pt pfn ps (Nd (b, [])) = pfn ps b
   870       | pr_pt pfn ps (Nd (b, ts)) = (pfn ps b)^
   871       (prts pfn (ps:pos) 1 ts)
   872     and prts pfn ps p [] = ""
   873       | prts pfn ps p (t::ts) = (pr_pt pfn (ps @ [p]) t)^
   874       (prts pfn ps (p+1) ts)
   875   in pr_pt f [] pt end;
   876 (*
   877 > fun prfn ps b = (pr_pos ps)^"   "^b(*TODO*)^"\n";
   878 > val pt = Unsynchronized.ref EmptyPtree;
   879 > pt:=Nd("root'",
   880        [Nd("xx1",[]),
   881 	Nd("xx2",
   882 	   [Nd("xx2.1.",[]),
   883 	    Nd("xx2.2.",[])]),
   884 	Nd("xx3",[])]);
   885 > tracing (pr_ptree prfn (!pt));
   886 *)
   887 
   888 
   889 (** access the branches of ptree **)
   890 
   891 fun ins_nth 1 e l  = e::l
   892   | ins_nth n e [] = raise PTREE "ins_nth n e []"
   893   | ins_nth n e (l::ls) = l::(ins_nth (n-1) e ls);
   894 fun repl []      _ _ = raise PTREE "repl [] _ _"
   895   | repl (l::ls) 1 e = e::ls
   896   | repl (l::ls) n e = l::(repl ls (n-1) e);
   897 fun repl_app ls n e = 
   898     let val lim = 1 + length ls
   899     in if n > lim then raise PTREE "repl_app: n > lim"
   900        else if n = lim then ls @ [e]
   901 	    else repl ls n e end;
   902 (*  
   903 > repl [1,2,3] 2 22222;
   904 val it = [1,22222,3] : int list
   905 > repl_app [1,2,3,4] 5 5555;
   906 val it = [1,2,3,4,5555] : int list
   907 > repl_app [1,2,3] 2 22222;
   908 val it = [1,22222,3] : int list
   909 > repl_app [1] 2 22222 ;
   910 val it = [1,22222] : int list
   911 *)
   912 
   913 
   914 (*.get from obj at pos by f : ppobj -> 'a.*)
   915 fun get_obj f EmptyPtree  (_:pos)  = raise PTREE "get_obj f EmptyPtree"
   916   | get_obj f (Nd (b,  _)) []      = f b
   917   | get_obj f (Nd (b, bs)) (p::ps) =
   918 (* val (f, Nd (b, bs), (p::ps)) = (I, pt, p);
   919    *)
   920   let val _ = (nth p bs) handle _ => raise PTREE ("get_obj: pos = "^
   921 			   (ints2str' (p::ps))^" does not exist");
   922   in (get_obj f (nth p bs) (ps:pos)) 
   923       (*before WN050419: 'wrong type..' raised also if pos doesn't exist*)
   924     handle _ => raise PTREE (*"get_obj: at pos = "^
   925 			     (ints2str' (p::ps))^" wrong type of ppobj"*)
   926 			  ("get_obj: pos = "^
   927 			   (ints2str' (p::ps))^" does not exist")
   928   end;
   929 fun get_nd EmptyPtree _ = raise PTREE "get_nd EmptyPtree"
   930   | get_nd n [] = n
   931   | get_nd (Nd (_,nds)) (pos as p::(ps:pos)) = (get_nd (nth p nds) ps)
   932     handle _ => raise PTREE ("get_nd: not existent pos = "^(ints2str' pos));
   933 
   934 
   935 (* for use by get_obj *)
   936 fun g_cell   (PblObj {cell = c,...}) = NONE
   937   | g_cell   (PrfObj {cell = c,...}) = c;(*WN0607 hack for quick introduction of lrd + rewrite-at (thms, calcs)*)
   938 fun g_form   (PrfObj {form = f,...}) = f
   939   | g_form   (PblObj {origin=(_,_,f),...}) = f;
   940 fun g_form' (Nd (PrfObj {form = f,...}, _)) = f
   941   | g_form' (Nd (PblObj {origin=(_,_,f),...}, _)) = f;
   942 (*  | g_form   _ = raise PTREE "g_form not for PblObj";*)
   943 fun g_origin (PblObj {origin = ori,...}) = ori
   944   | g_origin _ = raise PTREE "g_origin not for PrfObj";
   945 fun g_fmz (PblObj {fmz = f,...}) = f
   946   | g_fmz _ = raise PTREE "g_fmz not for PrfObj";
   947 fun g_spec   (PblObj {spec = s,...}) = s
   948   | g_spec _   = raise PTREE "g_spec not for PrfObj";
   949 fun g_pbl    (PblObj {probl = p,...}) = p
   950   | g_pbl  _   = raise PTREE "g_pbl not for PrfObj";
   951 fun g_met    (PblObj {meth = p,...}) = p
   952   | g_met  _   = raise PTREE "g_met not for PrfObj";
   953 fun g_domID  (PblObj {spec = (d,_,_),...}) = d
   954   | g_domID  _ = raise PTREE "g_metID not for PrfObj";
   955 fun g_metID  (PblObj {spec = (_,_,m),...}) = m
   956   | g_metID  _ = raise PTREE "g_metID not for PrfObj";
   957 fun g_env    (PblObj {env,...}) = env
   958   | g_env    _ = raise PTREE "g_env not for PrfObj"; 
   959 fun g_loc    (PblObj {loc = l,...}) = l
   960   | g_loc    (PrfObj {loc = l,...}) = l;
   961 fun g_branch (PblObj {branch = b,...}) = b
   962   | g_branch (PrfObj {branch = b,...}) = b;
   963 fun g_tac  (PblObj {spec = (d,p,m),...}) = Apply_Method m
   964   | g_tac  (PrfObj {tac = m,...}) = m;
   965 fun g_result (PblObj {result = r,...}) = r
   966   | g_result (PrfObj {result = r,...}) = r;
   967 fun g_res (PblObj {result = (r,_),...}) = r
   968   | g_res (PrfObj {result = (r,_),...}) = r;
   969 fun g_res' (Nd (PblObj {result = (r,_),...}, _)) = r
   970   | g_res' (Nd (PrfObj {result = (r,_),...}, _)) = r;
   971 fun g_ostate (PblObj {ostate = r,...}) = r
   972   | g_ostate (PrfObj {ostate = r,...}) = r;
   973 fun g_ostate' (Nd (PblObj {ostate = r,...}, _)) = r
   974   | g_ostate' (Nd (PrfObj {ostate = r,...}, _)) = r;
   975 
   976 fun gpt_cell (Nd (PblObj {cell = c,...},_)) = NONE
   977   | gpt_cell (Nd (PrfObj {cell = c,...},_)) = c;
   978 
   979 (*in CalcTree/Subproblem an 'just_created_' model is created;
   980   this is filled to 'untouched' by Model/Refine_Problem*)
   981 fun just_created_ (PblObj {meth, probl, spec, ...}) = 
   982     null meth andalso null probl andalso spec = e_spec;
   983 val e_origin = ([],e_spec,e_term): (ori list) * spec * term;
   984 
   985 fun just_created (pt,(p,_):pos') =
   986     let val ppobj = get_obj I pt p
   987     in is_pblobj ppobj andalso just_created_ ppobj end;
   988 
   989 (*.does the pos in the ctree exist ?.*)
   990 fun existpt pos pt = can (get_obj I pt) pos;
   991 (*.does the pos' in the ctree exist, ie. extra check for result in the node.*)
   992 fun existpt' ((p,p_):pos') pt = 
   993     if can (get_obj I pt) p 
   994     then case p_ of 
   995 	     Res => get_obj g_ostate pt p = Complete
   996 	   | _ => true
   997     else false;
   998 
   999 (*.is this position appropriate for calculating intermediate steps?.*)
  1000 fun is_interpos ((_, Res):pos') = true
  1001   | is_interpos _ = false;
  1002 
  1003 fun last_onlev pt pos = not (existpt (lev_on pos) pt);
  1004 
  1005 
  1006 (*.find the position of the next parent which is a PblObj in ptree.*)
  1007 fun par_pblobj pt ([]:pos) = ([]:pos)
  1008   | par_pblobj pt p =
  1009     let fun par pt [] = []
  1010 	  | par pt p = if is_pblobj (get_obj I pt p) then p
  1011 		       else par pt (lev_up p)
  1012     in par pt (lev_up p) end; 
  1013 (* lev_up for hard_gen operating with pos = [...,0] *)
  1014 
  1015 (*.find the position and the children of the next parent which is a PblObj.*)
  1016 fun par_children (Nd (PblObj _, children)) ([]:pos) = (children, []:pos)
  1017   | par_children (pt as Nd (PblObj _, children)) p =
  1018     let fun par [] = (children, [])
  1019 	  | par p = let val Nd (obj, children) = get_nd pt p
  1020 		    in if is_pblobj obj then (children, p) else par (lev_up p)
  1021 		    end;
  1022     in par (lev_up p) end; 
  1023 
  1024 (*.get the children of a node in ptree.*)
  1025 fun children (Nd (PblObj _, cn)) = cn
  1026   | children (Nd (PrfObj _, cn)) = cn;
  1027 
  1028 
  1029 (*.find the next parent, which is either a PblObj (return true)
  1030   or a PrfObj with tac = Detail_Set (return false).*)
  1031 (*FIXME.3.4.03:re-organize par_pbl_det after rls' --> rls*)
  1032 fun par_pbl_det pt ([]:pos) = (true, []:pos, Erls)
  1033   | par_pbl_det pt p =
  1034     let fun par pt [] = (true, [], Erls)
  1035 	  | par pt p = if is_pblobj (get_obj I pt p) then (true, p, Erls)
  1036 		       else case get_obj g_tac pt p of
  1037 				(*Detail_Set rls' => (false, p, assoc_rls rls')
  1038 			      (*^^^--- before 040206 after ---vvv*)
  1039 			      |*)Rewrite_Set rls' => (false, p, assoc_rls rls')
  1040 			      | Rewrite_Set_Inst (_, rls') => 
  1041 				(false, p, assoc_rls rls')
  1042 			      | _ => par pt (lev_up p)
  1043     in par pt (lev_up p) end; 
  1044 
  1045 
  1046 
  1047 
  1048 (*.get from the whole ptree by f : ppobj -> 'a.*)
  1049 fun get_all f EmptyPtree   = []
  1050   | get_all f (Nd (b, [])) = [f b]
  1051   | get_all f (Nd (b, bs)) = [f b] @ (get_alls f bs)
  1052 and get_alls f [] = []
  1053   | get_alls f pts = flat (map (get_all f) pts);
  1054 
  1055 
  1056 (*.insert obj b into ptree at pos, ev.overwriting this pos.*)
  1057 fun insert b EmptyPtree   ([]:pos)  = Nd (b, [])
  1058   | insert b EmptyPtree    _        = raise PTREE "insert b Empty _"
  1059   | insert b (Nd ( _,  _)) []       = raise PTREE "insert b _ []"
  1060   | insert b (Nd (b', bs)) (p::[])  = 
  1061      Nd (b', repl_app bs p (Nd (b,[]))) 
  1062   | insert b (Nd (b', bs)) (p::ps)  =
  1063      Nd (b', repl_app bs p (insert b (nth p bs) ps));
  1064 (*
  1065 > type ppobj = string;
  1066 > tracing (pr_ptree prfn (!pt));
  1067   val pt = Unsynchronized.ref Empty;
  1068   pt:= insert ("root'":ppobj) EmptyPtree [];
  1069   pt:= insert ("xx1":ppobj) (!pt) [1];
  1070   pt:= insert ("xx2":ppobj) (!pt) [2];
  1071   pt:= insert ("xx3":ppobj) (!pt) [3];
  1072   pt:= insert ("xx2.1":ppobj) (!pt) [2,1];
  1073   pt:= insert ("xx2.2":ppobj) (!pt) [2,2];
  1074   pt:= insert ("xx2.1.1":ppobj) (!pt) [2,1,1];
  1075   pt:= insert ("xx2.1.2":ppobj) (!pt) [2,1,2];
  1076   pt:= insert ("xx2.1.3":ppobj) (!pt) [2,1,3];
  1077 *)
  1078 
  1079 (*.insert children to a node without children.*)
  1080 (*compare: fun insert*)
  1081 fun ins_chn _  EmptyPtree   (_:pos) = raise PTREE "ins_chn: EmptyPtree"
  1082   | ins_chn ns (Nd _)       []      = raise PTREE "ins_chn: pos = []"
  1083   | ins_chn ns (Nd (b, bs)) (p::[]) =
  1084     if p > length bs then raise PTREE "ins_chn: pos not existent"
  1085     else let val Nd (b', bs') = nth p bs
  1086 	 in if null bs' then Nd (b, repl_app bs p (Nd (b', ns)))
  1087 	    else raise PTREE "ins_chn: pos mustNOT be overwritten" end
  1088   | ins_chn ns (Nd (b, bs)) (p::ps) =
  1089      Nd (b, repl_app bs p (ins_chn ns (nth p bs) ps));
  1090 
  1091 (* print_depth 11;ins_chn;print_depth 3; ###insert#########################*);
  1092 
  1093 
  1094 (** apply f to obj at pos, f: ppobj -> ppobj **)
  1095 
  1096 fun appl_to_node f (Nd (b,bs)) = Nd (f b, bs);
  1097 fun appl_obj f EmptyPtree    []      = EmptyPtree
  1098   | appl_obj f EmptyPtree    _       = raise PTREE "appl_obj f Empty _"
  1099   | appl_obj f (Nd (b, bs)) []       = Nd (f b, bs)
  1100   | appl_obj f (Nd (b, bs)) (p::[])  = 
  1101      Nd (b, repl_app bs p (((appl_to_node f) o (nth p)) bs))
  1102   | appl_obj f (Nd (b, bs)) (p::ps)  =
  1103      Nd (b, repl_app bs p (appl_obj f (nth p bs) (ps:pos)));
  1104  
  1105 (* for use by appl_obj *) 
  1106 fun repl_form f (PrfObj {cell=c,form= _,tac=tac,loc=loc,
  1107 			 branch=branch,result=result,ostate=ostate}) =
  1108     PrfObj {cell=c,form= f,tac=tac,loc=loc,
  1109 	    branch=branch,result=result,ostate=ostate}
  1110   | repl_form _ _ = raise PTREE "repl_form takes no PblObj";
  1111 fun repl_pbl x    (PblObj {cell=cell,origin=origin,fmz=fmz,
  1112 			   spec=spec,probl=_,meth=meth,env=env,loc=loc,
  1113 			   branch=branch,result=result,ostate=ostate}) =
  1114   PblObj {cell=cell,origin=origin,fmz=fmz,spec=spec,probl= x,
  1115 	  meth=meth,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1116   | repl_pbl _ _ = raise PTREE "repl_pbl takes no PrfObj";
  1117 fun repl_met x    (PblObj {cell=cell,origin=origin,fmz=fmz,
  1118 			   spec=spec,probl=probl,meth=_,env=env,loc=loc,
  1119 			   branch=branch,result=result,ostate=ostate}) =
  1120   PblObj {cell=cell,origin=origin,fmz=fmz,spec=spec,probl=probl,
  1121 	  meth= x,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1122   | repl_met _ _ = raise PTREE "repl_pbl takes no PrfObj";
  1123 
  1124 fun repl_spec  x    (PblObj {cell=cell,origin=origin,fmz=fmz,
  1125 			   spec= _,probl=probl,meth=meth,env=env,loc=loc,
  1126 			   branch=branch,result=result,ostate=ostate}) =
  1127   PblObj {cell=cell,origin=origin,fmz=fmz,spec= x,probl=probl,
  1128 	  meth=meth,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1129   | repl_spec  _ _ = raise PTREE "repl_domID takes no PrfObj";
  1130 fun repl_domID x    (PblObj {cell=cell,origin=origin,fmz=fmz,
  1131 			   spec=(_,p,m),probl=probl,meth=meth,env=env,loc=loc,
  1132 			   branch=branch,result=result,ostate=ostate}) =
  1133   PblObj {cell=cell,origin=origin,fmz=fmz,spec=(x,p,m),probl=probl,
  1134 	  meth=meth,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1135   | repl_domID _ _ = raise PTREE "repl_domID takes no PrfObj";
  1136 fun repl_pblID x    (PblObj {cell=cell,origin=origin,fmz=fmz,
  1137 			   spec=(d,_,m),probl=probl,meth=meth,env=env,loc=loc,
  1138 			   branch=branch,result=result,ostate=ostate}) =
  1139   PblObj {cell=cell,origin=origin,fmz=fmz,spec=(d,x,m),probl=probl,
  1140 	  meth=meth,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1141   | repl_pblID _ _ = raise PTREE "repl_pblID takes no PrfObj";
  1142 fun repl_metID x (PblObj {cell=cell,origin=origin,fmz=fmz,
  1143 			   spec=(d,p,_),probl=probl,meth=meth,env=env,loc=loc,
  1144 			   branch=branch,result=result,ostate=ostate}) =
  1145   PblObj {cell=cell,origin=origin,fmz=fmz,spec=(d,p,x),probl=probl,
  1146 	  meth=meth,env=env,loc=loc,branch=branch,result=result,ostate=ostate}
  1147   | repl_metID _ _ = raise PTREE "repl_metID takes no PrfObj";
  1148 
  1149 fun repl_result l f' s (PrfObj {cell=cell,form=form,tac=tac,loc=_,
  1150 			     branch=branch,result = _ ,ostate = _}) =
  1151     PrfObj {cell=cell,form=form,tac=tac,loc= l,
  1152 	    branch=branch,result = f',ostate = s}
  1153   | repl_result l f' s (PblObj {cell=cell,origin=origin,fmz=fmz,
  1154 			     spec=spec,probl=probl,meth=meth,env=env,loc=_,
  1155 			     branch=branch,result= _ ,ostate= _}) =
  1156     PblObj {cell=cell,origin=origin,fmz=fmz,
  1157 	    spec=spec,probl=probl,meth=meth,env=env,loc= l,
  1158 	    branch=branch,result= f',ostate= s};
  1159 
  1160 fun repl_tac x (PrfObj {cell=cell,form=form,tac= _,loc=loc,
  1161 			  branch=branch,result=result,ostate=ostate}) =
  1162     PrfObj {cell=cell,form=form,tac= x,loc=loc,
  1163 	    branch=branch,result=result,ostate=ostate}
  1164   | repl_tac _ _ = raise PTREE "repl_tac takes no PblObj";
  1165 
  1166 fun repl_branch b (PblObj {cell=cell,origin=origin,fmz=fmz,
  1167 			   spec=spec,probl=probl,meth=meth,env=env,loc=loc,
  1168 			   branch= _,result=result,ostate=ostate}) =
  1169   PblObj {cell=cell,origin=origin,fmz=fmz,spec=spec,probl=probl,
  1170 	  meth=meth,env=env,loc=loc,branch= b,result=result,ostate=ostate}
  1171   | repl_branch b (PrfObj {cell=cell,form=form,tac=tac,loc=loc,
  1172 			  branch= _,result=result,ostate=ostate}) =
  1173     PrfObj {cell=cell,form=form,tac=tac,loc=loc,
  1174 	    branch= b,result=result,ostate=ostate};
  1175 
  1176 fun repl_env e
  1177   (PblObj {cell=cell,origin=origin,fmz=fmz,
  1178 	   spec=spec,probl=probl,meth=meth,env=_,loc=loc,
  1179 	   branch=branch,result=result,ostate=ostate}) =
  1180   PblObj {cell=cell,origin=origin,fmz=fmz,spec=spec,probl=probl,
  1181 	  meth=meth,env=e,loc=loc,branch=branch,
  1182 	  result=result,ostate=ostate}
  1183   | repl_env _ _ = raise PTREE "repl_ets takes no PrfObj";
  1184 
  1185 fun repl_oris oris
  1186   (PblObj {cell=cell,origin=(_,spe,hdf),fmz=fmz,
  1187 	   spec=spec,probl=probl,meth=meth,env=env,loc=loc,
  1188 	   branch=branch,result=result,ostate=ostate}) =
  1189   PblObj{cell=cell,origin=(oris,spe,hdf),fmz=fmz,spec=spec,probl=probl,
  1190 	  meth=meth,env=env,loc=loc,branch=branch,
  1191 	  result=result,ostate=ostate}
  1192   | repl_oris _ _ = raise PTREE "repl_oris takes no PrfObj";
  1193 fun repl_orispec spe
  1194   (PblObj {cell=cell,origin=(oris,_,hdf),fmz=fmz,
  1195 	   spec=spec,probl=probl,meth=meth,env=env,loc=loc,
  1196 	   branch=branch,result=result,ostate=ostate}) =
  1197   PblObj{cell=cell,origin=(oris,spe,hdf),fmz=fmz,spec=spec,probl=probl,
  1198 	  meth=meth,env=env,loc=loc,branch=branch,
  1199 	  result=result,ostate=ostate}
  1200   | repl_orispec _ _ = raise PTREE "repl_orispec takes no PrfObj";
  1201 
  1202 fun repl_loc l (PblObj {cell=cell,origin=origin,fmz=fmz,
  1203 			spec=spec,probl=probl,meth=meth,env=env,loc=_,
  1204 			branch=branch,result=result,ostate=ostate}) =
  1205   PblObj {cell=cell,origin=origin,fmz=fmz,spec=spec,probl=probl,
  1206 	  meth=meth,env=env,loc=l,branch=branch,result=result,ostate=ostate}
  1207   | repl_loc l (PrfObj {cell=cell,form=form,tac=tac,loc=_,
  1208 			branch=branch,result=result,ostate=ostate}) =
  1209   PrfObj {cell=cell,form=form,tac=tac,loc= l,
  1210 	  branch=branch,result=result,ostate=ostate};
  1211 (*
  1212 fun uni__cid cell' 
  1213   (PblObj {cell=cell,origin=origin,fmz=fmz,
  1214 	   spec=spec,probl=probl,meth=meth,env=env,loc=loc,
  1215 	   branch=branch,result=result,ostate=ostate}) =
  1216   PblObj {cell=cell union cell',origin=origin,fmz=fmz,spec=spec,probl=probl,
  1217 	  meth=meth,env=env,loc=loc,branch=branch,
  1218 	  result=result,ostate=ostate}
  1219   | uni__cid cell'
  1220   (PrfObj {cell=cell,form=form,tac=tac,loc=loc,
  1221 	   branch=branch,result=result,ostate=ostate}) =
  1222   PrfObj {cell=cell union cell',form=form,tac=tac,loc=loc,
  1223 	  branch=branch,result=result,ostate=ostate};
  1224 *)
  1225 
  1226 (*WN050219 put here for interpreting code for cut_tree below...*)
  1227 type ocalhd =
  1228      bool *                (*ALL itms+preconds true*)
  1229      pos_ *                (*model belongs to Problem | Method*)
  1230      term *                (*header: Problem... or Cas
  1231 				FIXXXME.12.03: item! for marking syntaxerrors*)
  1232      itm list *            (*model: given, find, relate*)
  1233      ((bool * term) list) *(*model: preconds*)
  1234      spec;                 (*specification*)
  1235 val e_ocalhd = (false, Und, e_term, [e_itm], [(false, e_term)], e_spec);
  1236 
  1237 datatype ptform =
  1238 	 Form of term
  1239        | ModSpec of ocalhd;
  1240 val e_ptform = Form e_term;
  1241 val e_ptform' = ModSpec e_ocalhd;
  1242 
  1243 
  1244 
  1245 (*.applies (snd f) to the branches at a pos if ((fst f) b),
  1246    f : (ppobj -> bool) * (int -> ptree list -> ptree list).*)
  1247 
  1248 fun appl_branch f EmptyPtree [] = (EmptyPtree, false)
  1249   | appl_branch f EmptyPtree _  = raise PTREE "appl_branch f Empty _"
  1250   | appl_branch f (Nd ( _, _)) [] = raise PTREE "appl_branch f _ []"
  1251   | appl_branch f (Nd (b, bs)) (p::[]) = 
  1252     if (fst f) b then (Nd (b, (snd f) (p:posel) bs), true)
  1253     else (Nd (b, bs), false)
  1254   | appl_branch f (Nd (b, bs)) (p::ps) =
  1255 	let val (b',bool) = appl_branch f (nth p bs) ps
  1256 	in (Nd (b, repl_app bs p b'), bool) end;
  1257 
  1258 (* for cut_level;  appl_branch(deprecated) *)
  1259 fun test_trans (PrfObj{branch = Transitive,...}) = true
  1260   | test_trans (PblObj{branch = Transitive,...}) = true
  1261   | test_trans _ = false;
  1262 
  1263 fun is_pblobj' pt (p:pos) =
  1264     let val ppobj = get_obj I pt p
  1265     in is_pblobj ppobj end;
  1266 
  1267 
  1268 fun delete_result pt (p:pos) =
  1269     (appl_obj (repl_result (fst (get_obj g_loc pt p), NONE) 
  1270 			   (e_term,[]) Incomplete) pt p);
  1271 
  1272 fun del_res (PblObj {cell, fmz, origin, spec, probl, meth, 
  1273 		     env, loc=(l1,_), branch, result, ostate}) =
  1274     PblObj {cell=cell,fmz=fmz,origin=origin,spec=spec,probl=probl,meth=meth,
  1275 	    env=env, loc=(l1,NONE), branch=branch, result=(e_term,[]), 
  1276 	    ostate=Incomplete}
  1277 
  1278   | del_res (PrfObj {cell, form, tac, loc=(l1,_), branch, result, ostate}) =
  1279     PrfObj {cell=cell,form=form,tac=tac, loc=(l1,NONE), branch=branch, 
  1280 	    result=(e_term,[]), ostate=Incomplete};
  1281 
  1282 
  1283 (*
  1284 fun update_fmz  pt pos x = appl_obj (repl_fmz  x) pt pos;
  1285                                        1.00 not used anymore*)
  1286 
  1287 (*FIXME.WN.12.03: update_X X pos pt -> pt could be chained by o (efficiency?)*)
  1288 fun update_env    pt pos x = appl_obj (repl_env    x) pt pos;
  1289 fun update_domID  pt pos x = appl_obj (repl_domID  x) pt pos;
  1290 fun update_pblID  pt pos x = appl_obj (repl_pblID  x) pt pos;
  1291 fun update_metID  pt pos x = appl_obj (repl_metID  x) pt pos;
  1292 fun update_spec   pt pos x = appl_obj (repl_spec   x) pt pos;
  1293 
  1294 fun update_pbl    pt pos x = appl_obj (repl_pbl    x) pt pos;
  1295 fun update_pblppc pt pos x = appl_obj (repl_pbl    x) pt pos;
  1296 
  1297 fun update_met    pt pos x = appl_obj (repl_met    x) pt pos;
  1298 (*1.09.01 ----
  1299 fun update_metppc pt pos x = 
  1300   let val {rew_ord'=od,rls'=rs,asm_thm=at,asm_rls=ar,...} =
  1301     get_obj g_met pt pos
  1302   in appl_obj (repl_met 
  1303      {rew_ord'=od,rls'=rs,asm_thm=at,asm_rls=ar,ppc=x}) 
  1304     pt pos end;*)
  1305 fun update_metppc pt pos x = appl_obj (repl_met    x) pt pos;
  1306 			 			   
  1307 (*fun union_cid     pt pos x = appl_obj (uni__cid    x) pt pos;*)
  1308 
  1309 fun update_branch pt pos x = appl_obj (repl_branch x) pt pos;
  1310 fun update_tac  pt pos x = appl_obj (repl_tac  x) pt pos;
  1311 
  1312 fun update_oris   pt pos x = appl_obj (repl_oris   x) pt pos;
  1313 fun update_orispec   pt pos x = appl_obj (repl_orispec   x) pt pos;
  1314 
  1315  (*done by append_* !! 3.5.02;  ununsed WN050305 thus outcommented
  1316 fun update_loc pt (p,_) (ScrState ([],[],NONE,
  1317 				   Const ("empty",_),Sundef,false)) = 
  1318     appl_obj (repl_loc (NONE,NONE)) pt p
  1319   | update_loc pt (p,Res) x =  
  1320     let val (lform,_) = get_obj g_loc pt p
  1321     in appl_obj (repl_loc (lform,SOME x)) pt p end
  1322 
  1323   | update_loc pt (p,_) x = 
  1324     let val (_,lres) = get_obj g_loc pt p
  1325     in appl_obj (repl_loc (SOME x,lres)) pt p end;-------------*)
  1326 
  1327 (*WN050305 for handling cut_tree in cappend_atomic -- TODO redesign !*)
  1328 fun update_loc' pt p iss = appl_obj (repl_loc iss) pt p;
  1329 
  1330 (*13.8.02---------------------------
  1331 fun get_loc EmptyPtree _ = NONE
  1332   | get_loc pt (p,Res) =
  1333   let val (lfrm,lres) = get_obj g_loc pt p
  1334   in if lres = e_istate then lfrm else lres end
  1335   | get_loc pt (p,_) =
  1336   let val (lfrm,lres) = get_obj g_loc pt p
  1337   in if lfrm = e_istate then lres else lfrm end;  5.10.00: too liberal ?*)
  1338 (*13.8.02: options, because istate is no equalitype any more*)
  1339 fun get_loc EmptyPtree _ = e_istate
  1340   | get_loc pt (p,Res) =
  1341     (case get_obj g_loc pt p of
  1342 	 (SOME i, NONE) => i
  1343        | (NONE  , NONE) => e_istate
  1344        | (_     , SOME i) => i)
  1345   | get_loc pt (p,_) =
  1346     (case get_obj g_loc pt p of
  1347 	 (NONE  , SOME i) => i (*13.8.02 just copied from ^^^: too liberal ?*)
  1348        | (NONE  , NONE) => e_istate
  1349        | (SOME i, _) => i);
  1350 val get_istate = get_loc; (*3.5.02*)
  1351 
  1352 (*.collect the assumptions within a problem up to a certain position.*)
  1353 type asms = (term * pos) list;(*WN0502 should be (pos' * term) list
  1354 				       ...........===^===*)
  1355 
  1356 fun get_asm (b:pos, p:pos) (Nd (PblObj {result=(_,asm),...},_)) = 
  1357     ((*tracing ("### get_asm PblObj:(b,p)= "^
  1358 		(pair2str(ints2str b, ints2str p)));*)
  1359      (map (rpair b) asm):asms)
  1360   | get_asm (b, p) (Nd (PrfObj {result=(_,asm),...}, [])) = 
  1361     ((*tracing ("### get_asm PrfObj []:(b,p)= "^
  1362 	      (pair2str(ints2str b, ints2str p)));*)
  1363      (map (rpair b) asm))
  1364   | get_asm (b, p:pos) (Nd (PrfObj _, nds)) = 
  1365     let (*val _= tracing ("### get_asm PrfObj nds:(b,p)= "^
  1366 	      (pair2str(ints2str b, ints2str p)));*)
  1367 	val levdn = 
  1368 	    if p <> [] then (b @ [hd p]:pos, tl p:pos) 
  1369 	    else (b @ [1], [99999]) (*_deeper_ nesting is always _before_ p*)
  1370     in gets_asm levdn 1 nds end
  1371 and gets_asm _ _ [] = []
  1372   | gets_asm (b, p' as p::ps) i (nd::nds) = 
  1373     if p < i then [] 
  1374     else ((*tracing ("### gets_asm: (b,p')= "^(pair2str(ints2str b,
  1375 						      ints2str p')));*)
  1376 	  (get_asm (b @ [i], ps) nd) @ (gets_asm (b, p') (i + 1) nds));
  1377 
  1378 fun get_assumptions_ (Nd (PblObj {result=(r,asm),...}, cn)) (([], _):pos') = 
  1379     if r = e_term then gets_asm ([], [99999]) 1 cn
  1380     else map (rpair []) asm
  1381   | get_assumptions_ pt (p,p_) =
  1382     let val (cn, base) = par_children pt p
  1383 	val offset = drop (length base, p)
  1384 	val base' = replicate (length base) 1
  1385 	val offset' = case p_ of 
  1386 			 Frm => let val (qs,q) = split_last offset
  1387 				in qs @ [q - 1] end
  1388 		       | _ => offset
  1389         (*val _= tracing ("... get_assumptions: (b,o)= "^
  1390 			(pair2str(ints2str base',ints2str offset)))*)
  1391     in gets_asm (base', offset) 1 cn end;
  1392 
  1393 
  1394 (*---------
  1395 end
  1396 
  1397 open Ptree;
  1398 ----------*)
  1399 
  1400 (*pos of the formula on FE relative to the current pos,
  1401   which is the next writepos*)
  1402 fun pre_pos ([]:pos) = []:pos
  1403   | pre_pos pp =
  1404   let val (ps,p) = split_last pp
  1405   in case p of 1 => ps | n => ps @ [n-1] end;
  1406 
  1407 (*WN.20.5.03 ... but not used*)
  1408 fun posless [] (_::_) = true
  1409   | posless (_::_) [] = false
  1410   | posless (p::ps) (q::qs) = if p = q then posless ps qs else p < q;
  1411 (* posless [2,3,4] [3,4,5];
  1412 true
  1413 >  posless [2,3,4] [1,2,3];
  1414 false
  1415 >  posless [2,3] [2,3,4];
  1416 true
  1417 >  posless [2,3,4] [2,3];
  1418 false                    
  1419 >  posless [6] [6,5,2];
  1420 true
  1421 +++ see Isabelle/../library.ML*)
  1422 
  1423 
  1424 (**.development for extracting an 'interval' from ptree.**)
  1425 
  1426 (*version 1 stopped 8.03 in favour of get_interval with !!!move_dn
  1427   actually used (inefficient) version with move_dn: see modspec.sml*)
  1428 local
  1429 
  1430 fun hdp [] = 1     | hdp [0] = 1     | hdp x = hd x;(*start with first*)
  1431 fun hdq	[] = 99999 | hdq [0] = 99999 | hdq x = hd x;(*take until last*)
  1432 fun tlp [] = [0]     | tlp [_] = [0]     | tlp x = tl x;
  1433 fun tlq [] = [99999] | tlq [_] = [99999] | tlq x = tl x;
  1434 
  1435 fun getnd i (b,p) q (Nd (po, nds)) =
  1436     (if  i <= 0 then [[b]] else []) @
  1437     (getnds (i-1) true (b@[hdp p], tlp p) (tlq q)
  1438 	   (take_fromto (hdp p) (hdq q) nds))
  1439 
  1440 and getnds _ _ _ _ [] = []                         (*no children*)
  1441   | getnds i _ (b,p) q [nd] = (getnd i (b,p) q nd) (*l+r-margin*)
  1442 
  1443   | getnds i true (b,p) q [n1, n2] =               (*l-margin,  r-margin*)
  1444     (getnd i      (       b, p ) [99999] n1) @
  1445     (getnd ~99999 (lev_on b,[0]) q       n2)
  1446 
  1447   | getnds i _    (b,p) q [n1, n2] =               (*intern,  r-margin*)
  1448     (getnd i      (       b,[0]) [99999] n1) @
  1449     (getnd ~99999 (lev_on b,[0]) q       n2)
  1450 
  1451   | getnds i true (b,p) q (nd::(nds as _::_)) =    (*l-margin, intern*)
  1452     (getnd i             (       b, p ) [99999] nd) @
  1453     (getnds ~99999 false (lev_on b,[0]) q nds)
  1454 
  1455   | getnds i _ (b,p) q (nd::(nds as _::_)) =       (*intern, ...*)
  1456     (getnd i             (       b,[0]) [99999] nd) @
  1457     (getnds ~99999 false (lev_on b,[0]) q nds); 
  1458 in
  1459 (*get an 'interval from to' from a ptree as 'intervals f t' of respective nodes
  1460   where 'from' are pos, i.e. a key as int list, 'f' an int (to,t analoguous)
  1461 (1) the 'f' are given 
  1462 (1a) by 'from' if 'f' = the respective element of 'from' (left margin)
  1463 (1b) -inifinity, if 'f' > the respective element of 'from' (internal node)
  1464 (2) the 't' ar given
  1465 (2a) by 'to' if 't' = the respective element of 'to' (right margin)
  1466 (2b) inifinity, if 't' < the respective element of 'to (internal node)'
  1467 the 'f' and 't' are set by hdp,... *)
  1468 fun get_trace pt p q =
  1469     (flat o (getnds ((length p) -1) true ([hdp p], tlp p) (tlq q))) 
  1470 	(take_fromto (hdp p) (hdq q) (children pt));
  1471 end;
  1472 (*WN0510 stoppde this development;
  1473  actually used (inefficient) version with move_dn: getFormulaeFromTo*)
  1474 
  1475 
  1476 
  1477 
  1478 fun get_somespec ((dI,pI,mI):spec) ((dI',pI',mI'):spec) =
  1479     let val domID = if dI = e_domID
  1480 		    then if dI' = e_domID 
  1481 			 then error"pt_extract: no domID in probl,origin"
  1482 			 else dI'
  1483 		    else dI
  1484 	val pblID = if pI = e_pblID
  1485 		    then if pI' = e_pblID 
  1486 			 then error"pt_extract: no pblID in probl,origin"
  1487 			 else pI'
  1488 		    else pI
  1489 	val metID = if mI = e_metID
  1490 		    then if pI' = e_metID 
  1491 			 then error"pt_extract: no metID in probl,origin"
  1492 			 else mI'
  1493 		    else mI
  1494     in (domID, pblID, metID):spec end;
  1495 fun get_somespec' ((dI,pI,mI):spec) ((dI',pI',mI'):spec) =
  1496     let val domID = if dI = e_domID then dI' else dI
  1497 	val pblID = if pI = e_pblID then pI' else pI
  1498 	val metID = if mI = e_metID then mI' else mI
  1499     in (domID, pblID, metID):spec end;
  1500 
  1501 (*extract a formula or model from ptree for itms2itemppc or model2xml*)
  1502 fun preconds2str bts = 
  1503     (strs2str o (map (linefeed o pair2str o
  1504 		      (apsnd term2str) o 
  1505 		      (apfst bool2str)))) bts;
  1506 fun ocalhd2str ((b, p, hdf, itms, prec, spec):ocalhd) =
  1507     "("^bool2str b^", "^pos_2str p^", "^term2str hdf^
  1508     ", "^itms2str_ (thy2ctxt' "Isac") itms^
  1509     ", "^preconds2str prec^", \n"^spec2str spec^" )";
  1510 
  1511 
  1512 
  1513 fun is_pblnd (Nd (ppobj, _)) = is_pblobj ppobj;
  1514 
  1515 
  1516 (**.functions for the 'ptree iterator' as seen from the FE-Kernel interface.**)
  1517 
  1518 (*move one step down into existing nodes of ptree; regard TransitiveB
  1519 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##################
  1520 fun move_dn _ (Nd (c, ns)) ([],p_) = (*root problem*)
  1521 (* val (Nd (c, ns), ([],p_)) = (pt, get_pos cI uI);
  1522    *)
  1523     if is_pblobj c 
  1524     then case p_ of (*Frm => ([], Pbl) 1.12.03
  1525 		  |*) Res => raise PTREE "move_dn: end of calculation"
  1526 		  | _ => if null ns (*go down from Pbl + Met*)
  1527 			 then raise PTREE "move_dn: solve problem not started"
  1528 			 else ([1], Frm)
  1529     else (case p_ of Res => raise PTREE "move_dn: end of (sub-)tree"
  1530 		  | _ => if null ns
  1531 			 then raise PTREE "move_dn: pos not existent 1"
  1532 			 else ([1], Frm))
  1533 
  1534   (*iterate towards end of pos*)
  1535 (* val (P,(Nd (_, ns)),(p::(ps as (_::_)),p_)) = ([]:pos, pt, get_pos cI uI);
  1536    val (P,(Nd (_, ns)),(p::(ps as (_::_)),p_)) = ((P@[p]),(nth p ns),(ps, p_));
  1537    *) 
  1538  | move_dn P  (Nd (_, ns)) (p::(ps as (_::_)),p_) =
  1539     if p > length ns then raise PTREE "move_dn: pos not existent 2"
  1540     else move_dn ((P@[p]): pos) (nth p ns) (ps, p_)
  1541 (* val (P, (Nd (c, ns)), ([p], p_)) = ((P@[p]), (nth p ns), (ps, p_));
  1542    val (P, (Nd (c, ns)), ([p], p_)) = ([],pt,get_pos cI uI);
  1543    *)
  1544   | move_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1545     if p > length ns then raise PTREE "move_dn: pos not existent 3"
  1546     else if is_pblnd (nth p ns)  then
  1547 	((*tracing("### move_dn: is_pblnd (nth p ns), P= "^ints2str' P^", \n"^
  1548 		 "length ns= "^((string_of_int o length) ns)^
  1549 		 ", p= "^string_of_int p^", p_= "^pos_2str p_);*)
  1550 	 case p_ of Res => if p = length ns 
  1551 			   then if g_ostate c = Complete then (P, Res)
  1552 				else raise PTREE (ints2str' P^" not complete")
  1553 			   (*FIXME here handle not-sequent-branches*)
  1554 			   else if g_branch c = TransitiveB 
  1555 				   andalso (not o is_pblnd o (nth (p+1))) ns
  1556 			   then (P@[p+1], Res)
  1557 			   else (P@[p+1], if is_pblnd (nth (p+1) ns) 
  1558 					  then Pbl else Frm)
  1559 		  | _ => if (null o children o (nth p)) ns (*go down from Pbl*)
  1560 			 then raise PTREE "move_dn: solve subproblem not started"
  1561 			 else (P @ [p, 1], 
  1562 			       if (is_pblnd o hd o children o (nth p)) ns
  1563 			       then Pbl else Frm)
  1564 			      )
  1565     (* val (P, Nd (c, ns), ([p], p_)) = ([], pt, ([1], Frm));
  1566         *)
  1567     else case p_ of Frm => if (null o children o (nth p)) ns 
  1568 			 (*then if g_ostate c = Complete then (P@[p],Res)*)
  1569 			   then if g_ostate' (nth p ns) = Complete 
  1570 				then (P@[p],Res)
  1571 				else raise PTREE "move_dn: pos not existent 4"
  1572 			   else (P @ [p, 1], (*go down*) 
  1573 				 if (is_pblnd o hd o children o (nth p)) ns
  1574 				 then Pbl else Frm)
  1575 		  | Res => if p = length ns 
  1576 			   then 
  1577 			      if g_ostate c = Complete then (P, Res)
  1578 			      else raise PTREE (ints2str' P^" not complete")
  1579 			   else 
  1580 			       if g_branch c = TransitiveB 
  1581 				  andalso (not o is_pblnd o (nth (p+1))) ns
  1582 			       then if (null o children o (nth (p+1))) ns
  1583 				    then (P@[p+1], Res)
  1584 				    else (P@[p+1,1], Frm)(*040221*)
  1585 			       else (P@[p+1], if is_pblnd (nth (p+1) ns) 
  1586 					      then Pbl else Frm); 
  1587 *)
  1588 (*.move one step down into existing nodes of ptree; skip Res = Frm.nxt;
  1589    move_dn at the end of the calc-tree raises PTREE.*)
  1590 fun move_dn _ (Nd (c, ns)) ([],p_) = (*root problem*)
  1591     (case p_ of 
  1592 	     Res => raise PTREE "move_dn: end of calculation"
  1593 	   | _ => if null ns (*go down from Pbl + Met*)
  1594 		  then raise PTREE "move_dn: solve problem not started"
  1595 		  else ([1], Frm))
  1596   | move_dn P  (Nd (_, ns)) (p::(ps as (_::_)),p_) =(*iterate to end of pos*)
  1597     if p > length ns then raise PTREE "move_dn: pos not existent 2"
  1598     else move_dn ((P@[p]): pos) (nth p ns) (ps, p_)
  1599 
  1600   | move_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1601     if p > length ns then raise PTREE "move_dn: pos not existent 3"
  1602     else case p_ of 
  1603 	     Res => 
  1604 	     if p = length ns (*last Res on this level: go a level up*)
  1605 	     then if g_ostate c = Complete then (P, Res)
  1606 		  else raise PTREE (ints2str' P^" not complete 1")
  1607 	     else (*go to the next Nd on this level, or down into the next Nd*)
  1608 		 if is_pblnd (nth (p+1) ns) then (P@[p+1], Pbl)
  1609 		 else 
  1610 		     if g_res' (nth p ns) = g_form' (nth (p+1) ns)
  1611 		     then if (null o children o (nth (p+1))) ns
  1612 			  then (*take the Res if Complete*) 
  1613 			      if g_ostate' (nth (p+1) ns) = Complete 
  1614 			      then (P@[p+1], Res)
  1615 			      else raise PTREE (ints2str' (P@[p+1])^
  1616 						" not complete 2")
  1617 			  else (P@[p+1,1], Frm)(*go down into the next PrfObj*)
  1618 		     else (P@[p+1], Frm)(*take Frm: exists if the Nd exists*)
  1619 	   | Frm => (*go down or to the Res of this Nd*)
  1620 	     if (null o children o (nth p)) ns
  1621 	     then if g_ostate' (nth p ns) = Complete then (P @ [p], Res)
  1622 		  else raise PTREE (ints2str' (P @ [p])^" not complete 3")
  1623 	     else (P @ [p, 1], Frm)
  1624 	   | _ => (*is Pbl or Met*)
  1625 	     if (null o children o (nth p)) ns
  1626 	     then raise PTREE "move_dn:solve subproblem not startd"
  1627 	     else (P @ [p, 1], 
  1628 		   if (is_pblnd o hd o children o (nth p)) ns
  1629 		   then Pbl else Frm);
  1630 
  1631 
  1632 (*.go one level down into ptree.*)
  1633 fun movelevel_dn [] (Nd (c, ns)) ([],p_) = (*root problem*)
  1634     if is_pblobj c 
  1635     then if null ns 
  1636 	 then raise PTREE "solve problem not started"
  1637 	 else ([1], if (is_pblnd o hd) ns then Pbl else Frm)
  1638     else raise PTREE "pos not existent 1"
  1639 
  1640   (*iterate towards end of pos*)
  1641   | movelevel_dn P (Nd (_, ns)) (p::(ps as (_::_)),p_) =
  1642     if p > length ns then raise PTREE "pos not existent 2"
  1643     else movelevel_dn (P@[p]) (nth p ns) (ps, p_)
  1644 
  1645   | movelevel_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1646     if p > length ns then raise PTREE "pos not existent 3" else
  1647     case p_ of Res => 
  1648 	       if p = length ns 
  1649 	       then raise PTREE "no children"
  1650 	       else 
  1651 		   if g_branch c = TransitiveB
  1652 		   then if (null o children o (nth (p+1))) ns
  1653 			then raise PTREE "no children"
  1654 			else (P @ [p+1, 1], 
  1655 			      if (is_pblnd o hd o children o (nth (p+1))) ns
  1656 			      then Pbl else Frm)
  1657 		   else if (null o children o (nth p)) ns
  1658 		   then raise PTREE "no children"
  1659 		   else (P @ [p, 1], if (is_pblnd o hd o children o (nth p)) ns
  1660 				     then Pbl else Frm)
  1661 	     | _ => if (null o children o (nth p)) ns 
  1662 		    then raise PTREE "no children"
  1663 		    else (P @ [p, 1], (*go down*)
  1664 			  if (is_pblnd o hd o children o (nth p)) ns
  1665 			  then Pbl else Frm);
  1666 
  1667 
  1668 
  1669 (*.go to the previous position in ptree; regard TransitiveB.*)
  1670 fun move_up _ (Nd (c, ns)) (([],p_):pos') = (*root problem*)
  1671     if is_pblobj c 
  1672     then case p_ of Res => if null ns then ([], Pbl) (*Res -> Pbl (not Met)!*)
  1673 			   else ([length ns], Res)
  1674 		  | _  => raise PTREE "begin of calculation"
  1675     else raise PTREE "pos not existent"
  1676 
  1677   | move_up P  (Nd (_, ns)) (p::(ps as (_::_)),p_) = (*iterate to end of pos*)
  1678     if p > length ns then raise PTREE "pos not existent"
  1679     else move_up (P@[p]) (nth p ns) (ps,p_)
  1680 
  1681   | move_up P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1682     if p > length ns then raise PTREE "pos not existent"
  1683     else if is_pblnd (nth p ns)  then
  1684 	case p_ of Res => 
  1685 		   let val nc = (length o children o (nth p)) ns
  1686 		   in if nc = 0 then (P@[p], Pbl) (*Res -> Pbl (not Met)!*)
  1687 		      else (P @ [p, nc], Res) end (*go down*)
  1688 		 | _ => if p = 1 then (P, Pbl) else (P@[p-1], Res) 
  1689     else case p_ of Frm => if p <> 1 then (P, Frm) 
  1690 			  else if is_pblobj c then (P, Pbl) else (P, Frm)
  1691 		  | Res => 
  1692 		    let val nc = (length o children o (nth p)) ns
  1693 		    in if nc = 0 (*cannot go down*)
  1694 		       then if g_branch c = TransitiveB andalso p <> 1
  1695 			    then (P@[p-1], Res) else (P@[p], Frm)
  1696 		       else (P @ [p, nc], Res) end; (*go down*)
  1697 
  1698 
  1699 
  1700 (*.go one level up in ptree; sets the position on Frm.*)
  1701 fun movelevel_up _ (Nd (c, ns)) (([],p_):pos') = (*root problem*)
  1702     raise PTREE "pos not existent"
  1703 
  1704   (*iterate towards end of pos*)
  1705   | movelevel_up P  (Nd (_, ns)) (p::(ps as (_::_)),p_) = 
  1706     if p > length ns then raise PTREE "pos not existent"
  1707     else movelevel_up (P@[p]) (nth p ns) (ps,p_)
  1708 
  1709   | movelevel_up P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1710     if p > length ns then raise PTREE "pos not existent"
  1711     else if is_pblobj c then (P, Pbl) else (P, Frm);
  1712 
  1713 
  1714 (*.go to the next calc-head up in the calc-tree.*)
  1715 fun movecalchd_up pt ((p, Res):pos') =
  1716     (par_pblobj pt p, Pbl):pos'
  1717   | movecalchd_up pt (p, _) =
  1718     if is_pblobj (get_obj I pt p) 
  1719     then (p, Pbl) else (par_pblobj pt p, Pbl);
  1720 
  1721 (*.determine the previous pos' on the same level.*)
  1722 (*WN0502 made for interSteps; _only_ works for branch TransitiveB*)
  1723 fun lev_pred' pt (pos:pos' as ([],Res)) = ([],Pbl):pos'
  1724   | lev_pred' pt (pos:pos' as (p, Res)) =
  1725     let val (p', last) = split_last p
  1726     in if last = 1 
  1727        then if (is_pblobj o (get_obj I pt)) p then (p,Pbl) else (p, Frm)
  1728        else if get_obj g_res pt (p' @ [last - 1]) = get_obj g_form pt p
  1729        then (p' @ [last - 1], Res) (*TransitiveB*)
  1730        else if (is_pblobj o (get_obj I pt)) p then (p,Pbl) else (p, Frm)
  1731     end;
  1732 
  1733 (*.determine the next pos' on the same level.*)
  1734 fun lev_on' pt (([],Pbl):pos') = ([],Res):pos'
  1735   | lev_on' pt (p, Res) =
  1736     if get_obj g_res pt p = get_obj g_form pt (lev_on p)(*TransitiveB*)
  1737     then if existpt' (lev_on p, Res) pt then (lev_on p, Res)
  1738 	 else error ("lev_on': (p, Res) -> (p, Res) not existent, \
  1739 		      \p = "^ints2str' (lev_on p))
  1740     else (lev_on p, Frm)
  1741   | lev_on' pt (p, _) =
  1742     if existpt' (p, Res) pt then (p, Res)
  1743     else error ("lev_on': (p, Frm) -> (p, Res) not existent, \
  1744 		      \p = "^ints2str' p);
  1745 
  1746 fun exist_lev_on' pt p = (lev_on' pt p; true) handle _ => false;
  1747 
  1748 (*.is the pos' at the last element of a calulation _AND_ can be continued.*)
  1749 (* val (pt, pos as (p,p_)) = (pt, ([1],Frm));
  1750    *)
  1751 fun is_curr_endof_calc pt (([],Res) : pos') = false
  1752   | is_curr_endof_calc pt (pos as (p,_)) =
  1753     not (exist_lev_on' pt pos) 
  1754     andalso get_obj g_ostate pt (lev_up p) = Incomplete;
  1755 
  1756 
  1757 (**.insert into ctree and cut branches accordingly.**)
  1758   
  1759 (*.get all positions of certain intervals on the ctree.*)
  1760 (*OLD VERSION without move_dn; kept for occasional redesign
  1761    get all pos's to be cut in a ptree
  1762    below a pos or from a ptree list after i-th element (NO level_up).*)
  1763 fun get_allpos' (_:pos, _:posel) EmptyPtree   = ([]:pos' list)
  1764   | get_allpos' (p, 1) (Nd (b, bs)) = (*p is pos of Nd*)
  1765     if g_ostate b = Incomplete 
  1766     then ((*tracing("get_allpos' (p, 1) Incomplete: p="^ints2str' p);*)
  1767 	  [(p,Frm)] @ (get_allpos's (p, 1) bs)
  1768 	  )
  1769     else ((*tracing("get_allpos' (p, 1) else: p="^ints2str' p);*)
  1770 	  [(p,Frm)] @ (get_allpos's (p, 1) bs) @ [(p,Res)]
  1771 	  )
  1772     (*WN041020 here we assume what is presented on the worksheet ?!*)
  1773   | get_allpos' (p, i) (Nd (b, bs)) = (*p is pos of Nd*)
  1774     if length bs > 0 orelse is_pblobj b
  1775     then if g_ostate b = Incomplete 
  1776 	 then [(p,Frm)] @ (get_allpos's (p, 1) bs)
  1777 	 else [(p,Frm)] @ (get_allpos's (p, 1) bs) @ [(p,Res)]
  1778     else 
  1779 	if g_ostate b = Incomplete 
  1780 	then []
  1781 	else [(p,Res)]
  1782 (*WN041020 here we assume what is presented on the worksheet ?!*)
  1783 and get_allpos's _ [] = []
  1784   | get_allpos's (p, i) (pt::pts) = (*p is pos of parent-Nd*)
  1785     (get_allpos' (p@[i], i) pt) @ (get_allpos's (p, i+1) pts);
  1786 
  1787 (*.get all positions of certain intervals on the ctree.*)
  1788 (*NEW version WN050225*)
  1789 
  1790 
  1791 (*.cut branches.*)
  1792 (*before WN041019......
  1793 val cut_branch = (test_trans, curry take):
  1794     (ppobj -> bool) * (int -> ptree list -> ptree list);
  1795 .. formlery used for ...
  1796 fun cut_tree''' _ [] = EmptyPtree
  1797   | cut_tree''' pt pos = 
  1798   let val (pt',cut) = appl_branch cut_branch pt pos
  1799   in if cut andalso length pos > 1 then cut_tree''' pt' (lev_up pos)
  1800      else pt' end;
  1801 *)
  1802 (*OLD version before WN050225*)
  1803 (*WN050106 like cut_level, but deletes exactly 1 node --- for tests ONLY*)
  1804 fun cut_level_'_ (_:pos' list) (_:pos) EmptyPtree (_:pos') =
  1805     raise PTREE "cut_level_'_ Empty _"
  1806   | cut_level_'_ _ _ (Nd ( _, _)) ([],_) = raise PTREE "cut_level_'_ _ []"
  1807   | cut_level_'_ cuts P (Nd (b, bs)) (p::[],p_) = 
  1808     if test_trans b 
  1809     then (Nd (b, drop_nth [] (p:posel, bs)),
  1810 	  (*     ~~~~~~~~~~~*)
  1811 	  cuts @ 
  1812 	  (if p_ = Frm then [(P@[p],Res)] else ([]:pos' list)) @
  1813 	  (*WN041020 here we assume what is presented on the worksheet ?!*)
  1814 	  (get_allpos's (P, p+1) (drop_nth [] (p, bs))))
  1815     (*                            ~~~~~~~~~~~*)
  1816     else (Nd (b, bs), cuts)
  1817   | cut_level_'_ cuts P (Nd (b, bs)) ((p::ps),p_) =
  1818     let val (bs',cuts') = cut_level_'_ cuts P (nth p bs) (ps, p_)
  1819     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
  1820 
  1821 (*before WN050219*)
  1822 fun cut_level (_:pos' list) (_:pos) EmptyPtree (_:pos') =
  1823     raise PTREE "cut_level EmptyPtree _"
  1824   | cut_level _ _ (Nd ( _, _)) ([],_) = raise PTREE "cut_level _ []"
  1825 
  1826   | cut_level cuts P (Nd (b, bs)) (p::[],p_) = 
  1827     if test_trans b 
  1828     then (Nd (b, take (p:posel, bs)),
  1829 	  cuts @ 
  1830 	  (if p_ = Frm andalso (*#*) g_ostate b = Complete
  1831 	   then [(P@[p],Res)] else ([]:pos' list)) @
  1832 	  (*WN041020 here we assume what is presented on the worksheet ?!*)
  1833 	  (get_allpos's (P, p+1) (takerest (p, bs))))
  1834     else (Nd (b, bs), cuts)
  1835 
  1836   | cut_level cuts P (Nd (b, bs)) ((p::ps),p_) =
  1837     let val (bs',cuts') = cut_level cuts P (nth p bs) (ps, p_)
  1838     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
  1839 
  1840 (*OLD version before WN050219, overwritten below*)
  1841 fun cut_tree _ (([],_):pos') = raise PTREE "cut_tree _ ([],_)"
  1842   | cut_tree pt (pos as ([p],_)) =
  1843     let	val (pt', cuts) = cut_level ([]:pos' list) [] pt pos
  1844     in (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete 
  1845 		     then [] else [([],Res)])) end
  1846   | cut_tree pt (p,p_) =
  1847     let	
  1848 	fun cutfn pt cuts (p,p_) = 
  1849 	    let val (pt', cuts') = cut_level [] (lev_up p) pt (p,p_)
  1850 		val cuts'' = if get_obj g_ostate pt (lev_up p) = Incomplete 
  1851 			     then [] else [(lev_up p, Res)]
  1852 	    in if length cuts' > 0 andalso length p > 1
  1853 	       then cutfn pt' (cuts @ cuts') (lev_up p, Frm(*-->(p,Res)*))
  1854 	       else (pt',cuts @ cuts') end
  1855 	val (pt', cuts) = cutfn pt [] (p,p_)
  1856     in (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete 
  1857 		     then [] else [([], Res)])) end;
  1858 
  1859 
  1860 (*########/ inserted from ctreeNEW.sml \#################################**)
  1861 
  1862 (*.get all positions in a ptree until ([],Res) or ostate=Incomplete
  1863 val get_allp = fn : 
  1864   pos' list -> : accumulated, start with []
  1865   pos ->       : the offset for subtrees wrt the root
  1866   ptree ->     : (sub)tree
  1867   pos'         : initialization (the last pos' before ...)
  1868   -> pos' list : of positions in this (sub) tree (relative to the root)
  1869 .*)
  1870 (* val (cuts, P, pt, pos) = ([], [3], get_nd pt [3], ([], Frm):pos');
  1871    val (cuts, P, pt, pos) = ([], [2], get_nd pt [2], ([], Frm):pos');
  1872    length (children pt);
  1873    *)
  1874 fun get_allp (cuts:pos' list) (P:pos, pos:pos') pt =
  1875     (let val nxt = move_dn [] pt pos (*exn if Incomplete reached*)
  1876      in if nxt <> ([],Res) 
  1877 	then get_allp (cuts @ [nxt]) (P, nxt) pt
  1878 	else (map (apfst (curry op@ P)) (cuts @ [nxt])): pos' list
  1879      end) handle PTREE _ => (map (apfst (curry op@ P)) cuts);
  1880 
  1881 
  1882 (*the pts are assumed to be on the same level*)
  1883 fun get_allps (cuts: pos' list) (P:pos) [] = cuts
  1884   | get_allps cuts P (pt::pts) =
  1885     let val below = get_allp [] (P, ([], Frm)) pt
  1886 	val levfrm = 
  1887 	    if is_pblnd pt 
  1888 	    then (P, Pbl)::below
  1889 	    else if last_elem P = 1 
  1890 	    then (P, Frm)::below
  1891 	    else (*Trans*) below
  1892 	val levres = levfrm @ (if null below then [(P, Res)] else [])
  1893     in get_allps (cuts @ levres) (lev_on P) pts end;
  1894 
  1895 
  1896 (**.these 2 funs decide on how far cut_tree goes.**)
  1897 (*.shall the nodes _after_ the pos to be inserted at be deleted?.*)
  1898 fun test_trans (PrfObj{branch = Transitive,...}) = true
  1899   | test_trans (PrfObj{branch = NoBranch,...}) = true
  1900   | test_trans (PblObj{branch = Transitive,...}) = true 
  1901   | test_trans (PblObj{branch = NoBranch,...}) = true 
  1902   | test_trans _ = false;
  1903 (*.shall cutting be continued on the higher level(s)?
  1904    the Nd regarded will NOT be changed.*)
  1905 fun cutlevup (PblObj _) = false (*for tests of LK0502*)
  1906   | cutlevup _ = true;
  1907 val cutlevup = test_trans;(*WN060727 after summerterm tests.LK0502 withdrawn*)
  1908     
  1909 (*cut_bottom new sml603..608
  1910 cut the level at the bottom of the pos (used by cappend_...)
  1911 and handle the parent in order to avoid extra case for root
  1912 fn: ptree ->         : the _whole_ ptree for cut_levup
  1913     pos * posel ->   : the pos after split_last
  1914     ptree ->         : the parent of the Nd to be cut
  1915 return
  1916     (ptree *         : the updated ptree
  1917      pos' list) *    : the pos's cut
  1918      bool            : cutting shall be continued on the higher level(s)
  1919 *)
  1920 fun cut_bottom _ (pt' as Nd (b, [])) = ((pt', []), cutlevup b)
  1921   | cut_bottom (P:pos, p:posel) (Nd (b, bs)) =
  1922     let (*divide level into 3 parts...*)
  1923 	val keep = take (p - 1, bs)
  1924 	val pt' as Nd (_,bs') = nth p bs
  1925 	(*^^^^^_here_ will be 'insert'ed by 'append_..'*)
  1926 	val (tail, tp) = (takerest (p, bs), 
  1927 			  if null (takerest (p, bs)) then 0 else p + 1)
  1928 	val (children, cuts) = 
  1929 	    if test_trans b
  1930 	    then (keep,
  1931 		  (if is_pblnd pt' then [(P @ [p], Pbl)] else [])
  1932 		  @ (get_allp  [] (P @ [p], (P, Frm)) pt')
  1933 		  @ (get_allps [] (P @ [p+1]) tail))
  1934 	    else (keep @ [(*'insert'ed by 'append_..'*)] @ tail,
  1935 		  get_allp  [] (P @ [p], (P, Frm)) pt')
  1936 	val (pt'', cuts) = 
  1937 	    if cutlevup b
  1938 	    then (Nd (del_res b, children), 
  1939 		  cuts @ (if g_ostate b = Incomplete then [] else [(P,Res)]))
  1940 	    else (Nd (b, children), cuts)
  1941 	(*val _= tracing("####cut_bottom (P, p)="^pos2str (P @ [p])^
  1942 		       ", Nd=.............................................")
  1943 	val _= show_pt pt''
  1944 	val _= tracing("####cut_bottom form='"^
  1945 		       term2str (get_obj g_form pt'' []))
  1946 	val _= tracing("####cut_bottom cuts#="^string_of_int (length cuts)^
  1947 		       ", cuts="^pos's2str cuts)*)
  1948     in ((pt'', cuts:pos' list), cutlevup b) end;
  1949 
  1950 
  1951 (*.go all levels from the bottom of 'pos' up to the root, 
  1952  on each level compose the children of a node and accumulate the cut Nds
  1953 args
  1954    pos' list ->      : for accumulation
  1955    bool -> 	     : cutting shall be continued on the higher level(s)
  1956    ptree -> 	     : the whole ptree for 'get_nd pt P' on each level
  1957    ptree -> 	     : the Nd from the lower level for insertion at path
  1958    pos * posel ->    : pos=path split for convenience
  1959    ptree -> 	     : Nd the children of are under consideration on this call 
  1960 returns		     :
  1961    ptree * pos' list : the updated parent-Nd and the pos's of the Nds cut
  1962 .*)
  1963 fun cut_levup (cuts:pos' list) clevup pt pt' (P:pos, p:posel) (Nd (b, bs)) =
  1964     let (*divide level into 3 parts...*)
  1965 	val keep = take (p - 1, bs)
  1966 	(*val pt' comes as argument from below*)
  1967 	val (tail, tp) = (takerest (p, bs), 
  1968 			  if null (takerest (p, bs)) then 0 else p + 1)
  1969 	val (children, cuts') = 
  1970 	    if clevup
  1971 	    then (keep @ [pt'], get_allps [] (P @ [p+1]) tail)
  1972 	    else (keep @ [pt'] @ tail, [])
  1973 	val clevup' = if clevup then cutlevup b else false 
  1974 	(*the first Nd with false stops cutting on all levels above*)
  1975 	val (pt'', cuts') = 
  1976 	    if clevup'
  1977 	    then (Nd (del_res b, children), 
  1978 		  cuts' @ (if g_ostate b = Incomplete then [] else [(P,Res)]))
  1979 	    else (Nd (b, children), cuts')
  1980 	(*val _= tracing("#####cut_levup clevup= "^bool2str clevup)
  1981 	val _= tracing("#####cut_levup cutlevup b= "^bool2str (cutlevup b))
  1982 	val _= tracing("#####cut_levup (P, p)="^pos2str (P @ [p])^
  1983 		       ", Nd=.............................................")
  1984 	val _= show_pt pt''
  1985 	val _= tracing("#####cut_levup form='"^
  1986 		       term2str (get_obj g_form pt'' []))
  1987 	val _= tracing("#####cut_levup cuts#="^string_of_int (length cuts)^
  1988 		       ", cuts="^pos's2str cuts)*)
  1989     in if null P then (pt'', (cuts @ cuts'):pos' list)
  1990        else let val (P, p) = split_last P
  1991 	    in cut_levup (cuts @ cuts') clevup' pt pt'' (P, p) (get_nd pt P)
  1992 	    end
  1993     end;
  1994  
  1995 (*.cut nodes after and below an inserted node in the ctree;
  1996    the cuts range is limited by the predicate 'fun cutlevup'.*)
  1997 fun cut_tree pt (pos,_) =
  1998     if not (existpt pos pt) 
  1999     then (pt,[]) (*appending a formula never cuts anything*)
  2000     else let val (P, p) = split_last pos
  2001 	     val ((pt', cuts), clevup) = cut_bottom (P, p) (get_nd pt P)
  2002 	 (*        pt' is the updated parent of the Nd to cappend_..*)
  2003 	 in if null P then (pt', cuts)
  2004 	    else let val (P, p) = split_last P
  2005 		 in cut_levup cuts clevup pt pt' (P, p) (get_nd pt P)
  2006 		 end
  2007 	 end;
  2008 
  2009 fun append_atomic p l f r f' s pt = 
  2010   let (**val _= tracing("#@append_atomic: pos ="^pos2str p)**)
  2011 	val (iss, f) = if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  2012 		     then (*after Take*)
  2013 			 ((fst (get_obj g_loc pt p), SOME l), 
  2014 			  get_obj g_form pt p) 
  2015 		     else ((NONE, SOME l), f)
  2016   in insert (PrfObj {cell = NONE,
  2017 		     form  = f,
  2018 		     tac  = r,
  2019 		     loc   = iss,
  2020 		     branch= NoBranch,
  2021 		     result= f',
  2022 		     ostate= s}) pt p end;
  2023 
  2024 
  2025 (*20.8.02: cappend_* FIXXXXME cut branches below cannot be decided here:
  2026   detail - generate - cappend: inserted, not appended !!!
  2027 
  2028   cut decided in applicable_in !?!
  2029 *)
  2030 fun cappend_atomic pt p loc f r f' s = 
  2031 (* val (pt, p, loc, f, r, f', s) = 
  2032        (pt,p,l,f,Rewrite_Set_Inst (subst2subs subs',id_rls rls'),
  2033 	(f',asm),Complete);
  2034    *)
  2035 ((*tracing("##@cappend_atomic: pos ="^pos2str p);*)
  2036   apfst (append_atomic p loc f r f' s) (cut_tree pt (p,Frm))
  2037 );
  2038 (*TODO.WN050305 redesign the handling of istates*)
  2039 fun cappend_atomic pt p ist_res f r f' s = 
  2040     if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  2041     then (*after Take: transfer Frm and respective istate*)
  2042 	let val (ist_form, f) = (get_loc pt (p,Frm), 
  2043 				 get_obj g_form pt p)
  2044 	    val (pt, cs) = cut_tree pt (p,Frm)
  2045 	    val pt = append_atomic p e_istate f r f' s pt
  2046 	    val pt = update_loc' pt p (SOME ist_form, SOME ist_res)
  2047 	in (pt, cs) end
  2048     else apfst (append_atomic p ist_res f r f' s) (cut_tree pt (p,Frm));
  2049 
  2050 
  2051 (* called by Take *)
  2052 fun append_form p l f pt = 
  2053 ((*tracing("##@append_form: pos ="^pos2str p);*)
  2054   insert (PrfObj {cell = NONE,
  2055 		  form  = (*if existpt p pt 
  2056 		  andalso get_obj g_tac pt p = Empty_Tac 
  2057 			    (*distinction from 'old' (+complete!) pobjs*)
  2058 			    then get_obj g_form pt p else*) f,
  2059 		  tac  = Empty_Tac,
  2060 		  loc   = (SOME l, NONE),
  2061 		  branch= NoBranch,
  2062 		  result= (e_term,[]),
  2063 		  ostate= Incomplete}) pt p
  2064 );
  2065 (* val (p,loc,f) = ([1], e_istate, str2term "x + 1 = 2");
  2066    val (p,loc,f) = (fst p, e_istate, str2term "-1 + x = 0");
  2067    *)
  2068 fun cappend_form pt p loc f =
  2069 ((*tracing("##@cappend_form: pos ="^pos2str p);*)
  2070   apfst (append_form p loc f) (cut_tree pt (p,Frm))
  2071 );
  2072 fun cappend_form pt p loc f =
  2073 let (*val _= tracing("##@cappend_form: pos ="^pos2str p)
  2074     val _= tracing("##@cappend_form before cut_tree: loc ="^istate2str loc)*)
  2075     val (pt', cs) = cut_tree pt (p,Frm)
  2076     val pt'' = append_form p loc f pt'
  2077     (*val _= tracing("##@cappend_form after append: loc ="^
  2078 		   istates2str (get_obj g_loc pt'' p))*)
  2079 in (pt'', cs) end;
  2080 
  2081 
  2082     
  2083 fun append_result pt p l f s =
  2084 ((*tracing("##@append_result: pos ="^pos2str p);*)
  2085     (appl_obj (repl_result (fst (get_obj g_loc pt p),
  2086 			    SOME l) f s) pt p, [])
  2087 );
  2088 
  2089 
  2090 (*WN041022 deprecated, still for kbtest/diffapp.sml, /systest/root-equ.sml*)
  2091 fun append_parent p l f r b pt = 
  2092   let (*val _= tracing("###append_parent: pos ="^pos2str p);*)
  2093     val (ll,f) = if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  2094 		  then ((fst (get_obj g_loc pt p), SOME l), 
  2095 			get_obj g_form pt p) 
  2096 		 else ((SOME l, NONE), f)
  2097   in insert (PrfObj 
  2098 	  {cell = NONE,
  2099 	   form  = f,
  2100 	   tac  = r,
  2101 	   loc   = ll,
  2102 	   branch= b,
  2103 	   result= (e_term,[]),
  2104 	   ostate= Incomplete}) pt p end;
  2105 fun cappend_parent pt p loc f r b =
  2106 ((*tracing("###cappend_parent: pos ="^pos2str p);*)
  2107   apfst (append_parent p loc f r b) (cut_tree pt (p,Und))
  2108 );
  2109 
  2110 
  2111 fun append_problem [] l fmz (strs,spec,hdf) _ =
  2112 ((*tracing("###append_problem: pos = []");*)
  2113   (Nd (PblObj 
  2114 	       {cell  = NONE,
  2115 		origin= (strs,spec,hdf),
  2116 		fmz   = fmz,
  2117 		spec  = empty_spec,
  2118 		probl = []:itm list,
  2119 		meth  = []:itm list,
  2120 		env   = NONE,
  2121 		loc   = (SOME l, NONE),
  2122 		branch= TransitiveB,(*FIXXXXXME.27.8.03: for equations only*)
  2123 		result= (e_term,[]),
  2124 		ostate= Incomplete},[]))
  2125 )
  2126   | append_problem p l fmz (strs,spec,hdf) pt =
  2127 ((*tracing("###append_problem: pos ="^pos2str p);*)
  2128   insert (PblObj 
  2129 	  {cell  = NONE,
  2130 	   origin= (strs,spec,hdf),
  2131 	   fmz   = fmz,
  2132 	   spec  = empty_spec,
  2133 	   probl = []:itm list,
  2134 	   meth  = []:itm list,
  2135 	   env   = NONE,
  2136 	   loc   = (SOME l, NONE),
  2137 	   branch= TransitiveB,
  2138 	   result= (e_term,[]),
  2139 	   ostate= Incomplete}) pt p
  2140 );
  2141 fun cappend_problem _ [] loc fmz ori =
  2142 ((*tracing("###cappend_problem: pos = []");*)
  2143   (append_problem [] loc fmz ori EmptyPtree,[])
  2144 )
  2145   | cappend_problem pt p loc fmz ori = 
  2146 ((*tracing("###cappend_problem: pos ="^pos2str p);*)
  2147   apfst (append_problem p (loc:istate) fmz ori) (cut_tree pt (p,Frm))
  2148 );
  2149 
  2150 (*.get the theory explicitly specified for the rootpbl;
  2151    thus use this function _after_ finishing specification.*)
  2152 fun rootthy (Nd (PblObj {spec=(thyID, _, _),...}, _)) = assoc_thy thyID
  2153   | rootthy _ = error "rootthy";
  2154