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