src/Tools/isac/Interpret/ctree.sml
author Walther Neuper <neuper@ist.tugraz.at>
Fri, 20 May 2011 14:49:07 +0200
branchdecompose-isar
changeset 42018 11cf93cd02c6
parent 42009 5f5807893ceb
child 42023 927cb6806af1
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 (*WN0312 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    term 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' " ^
   651       (spair2str (strs2str pblID, spair2str (term2str scval, terms2str 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 fun delete_result pt (p:pos) =
  1251     (appl_obj (repl_result (fst (get_obj g_loc pt p), NONE) 
  1252 			   (e_term,[]) Incomplete) pt p);
  1253 
  1254 fun del_res (PblObj {cell, fmz, origin, spec, probl, meth, 
  1255 		     ctxt, env, loc=(l1,_), branch, result, ostate}) =
  1256     PblObj {cell=cell,fmz=fmz,origin=origin,spec=spec,probl=probl,meth=meth,
  1257 	    ctxt=ctxt,env=env, loc=(l1,NONE), branch=branch, result=(e_term,[]), 
  1258 	    ostate=Incomplete}
  1259 
  1260   | del_res (PrfObj {cell, form, tac, loc=(l1,_), branch, result, ostate}) =
  1261     PrfObj {cell=cell,form=form,tac=tac, loc=(l1,NONE), branch=branch, 
  1262 	    result=(e_term,[]), ostate=Incomplete};
  1263 
  1264 (*FIXME.WN0312 update_X X pos pt -> pt could be chained by o (efficiency?)*)
  1265 (*fun update_fmz  pt pos x = appl_obj (repl_fmz  x) pt pos; WN01xx *)
  1266 fun update_ctxt   pt pos x = appl_obj (repl_ctxt   x) pt pos; (*for use on PblObj, 
  1267 otherwise use fun generate1; compare fun get_ctxt*)
  1268 fun update_env    pt pos x = appl_obj (repl_env    x) pt pos;
  1269 fun update_domID  pt pos x = appl_obj (repl_domID  x) pt pos;
  1270 fun update_pblID  pt pos x = appl_obj (repl_pblID  x) pt pos;
  1271 fun update_metID  pt pos x = appl_obj (repl_metID  x) pt pos;
  1272 fun update_spec   pt pos x = appl_obj (repl_spec   x) pt pos;
  1273 fun update_pbl    pt pos x = appl_obj (repl_pbl    x) pt pos;
  1274 fun update_pblppc pt pos x = appl_obj (repl_pbl    x) pt pos;
  1275 fun update_met    pt pos x = appl_obj (repl_met    x) pt pos;
  1276 fun update_metppc pt pos x = appl_obj (repl_met    x) pt pos;		   
  1277 fun update_branch pt pos x = appl_obj (repl_branch x) pt pos;
  1278 fun update_tac    pt pos x = appl_obj (repl_tac    x) pt pos;
  1279 fun update_oris   pt pos x = appl_obj (repl_oris   x) pt pos;
  1280 fun update_orispec pt pos x = appl_obj (repl_orispec   x) pt pos;
  1281 
  1282 (*WN050305 for handling cut_tree in cappend_atomic + for testing*)
  1283 fun update_loc'   pt pos x = appl_obj (repl_loc    x) pt pos;
  1284 
  1285 (*13.8.02: options, because istate is no equalitype any more*)
  1286 fun get_loc EmptyPtree _ = (e_istate, e_ctxt)
  1287   | get_loc pt (p,Res) =
  1288     (case get_obj g_loc pt p of
  1289 	 (SOME i, NONE) => i
  1290        | (NONE  , NONE) => (e_istate, e_ctxt)
  1291        | (_     , SOME i) => i)
  1292   | get_loc pt (p,_) =
  1293     (case get_obj g_loc pt p of
  1294 	 (NONE  , SOME i) => i (*13.8.02 just copied from ^^^: too liberal ?*)
  1295        | (NONE  , NONE) => (e_istate, e_ctxt)
  1296        | (SOME i, _) => i);
  1297 fun get_istate pt p = get_loc pt p |> #1;
  1298 fun get_ctxt pt (pos as (p, p_)) =
  1299   if member op = [Frm, Res] p_
  1300   then get_loc pt pos |> #2 (*for script interpretation rely on fun get_loc*)
  1301   else get_obj g_ctxt pt p (*for specify phase take ctx from PblObj*)
  1302 
  1303 fun get_assumptions_ pt p = get_ctxt pt p |> get_assumptions;
  1304 
  1305 (*---------
  1306 end
  1307 
  1308 open Ptree;
  1309 ----------*)
  1310 
  1311 (*pos of the formula on FE relative to the current pos,
  1312   which is the next writepos*)
  1313 fun pre_pos ([]:pos) = []:pos
  1314   | pre_pos pp =
  1315   let val (ps,p) = split_last pp
  1316   in case p of 1 => ps | n => ps @ [n-1] end;
  1317 
  1318 (*WN.20.5.03 ... but not used*)
  1319 fun posless [] (_::_) = true
  1320   | posless (_::_) [] = false
  1321   | posless (p::ps) (q::qs) = if p = q then posless ps qs else p < q;
  1322 (* posless [2,3,4] [3,4,5];
  1323 true
  1324 >  posless [2,3,4] [1,2,3];
  1325 false
  1326 >  posless [2,3] [2,3,4];
  1327 true
  1328 >  posless [2,3,4] [2,3];
  1329 false                    
  1330 >  posless [6] [6,5,2];
  1331 true
  1332 +++ see Isabelle/../library.ML*)
  1333 
  1334 
  1335 (**.development for extracting an 'interval' from ptree.**)
  1336 
  1337 (*WN0510 version stopped in favour of get_interval with !!!move_dn, getFormulaeFromTo
  1338   actually used (inefficient) version with move_dn: see modspec.sml*)
  1339 local
  1340 
  1341 fun hdp [] = 1     | hdp [0] = 1     | hdp x = hd x;(*start with first*)
  1342 fun hdq	[] = 99999 | hdq [0] = 99999 | hdq x = hd x;(*take until last*)
  1343 fun tlp [] = [0]     | tlp [_] = [0]     | tlp x = tl x;
  1344 fun tlq [] = [99999] | tlq [_] = [99999] | tlq x = tl x;
  1345 
  1346 fun getnd i (b,p) q (Nd (po, nds)) =
  1347     (if  i <= 0 then [[b]] else []) @
  1348     (getnds (i-1) true (b@[hdp p], tlp p) (tlq q)
  1349 	   (take_fromto (hdp p) (hdq q) nds))
  1350 
  1351 and getnds _ _ _ _ [] = []                         (*no children*)
  1352   | getnds i _ (b,p) q [nd] = (getnd i (b,p) q nd) (*l+r-margin*)
  1353 
  1354   | getnds i true (b,p) q [n1, n2] =               (*l-margin,  r-margin*)
  1355     (getnd i      (       b, p ) [99999] n1) @
  1356     (getnd ~99999 (lev_on b,[0]) q       n2)
  1357 
  1358   | getnds i _    (b,p) q [n1, n2] =               (*intern,  r-margin*)
  1359     (getnd i      (       b,[0]) [99999] n1) @
  1360     (getnd ~99999 (lev_on b,[0]) q       n2)
  1361 
  1362   | getnds i true (b,p) q (nd::(nds as _::_)) =    (*l-margin, intern*)
  1363     (getnd i             (       b, p ) [99999] nd) @
  1364     (getnds ~99999 false (lev_on b,[0]) q nds)
  1365 
  1366   | getnds i _ (b,p) q (nd::(nds as _::_)) =       (*intern, ...*)
  1367     (getnd i             (       b,[0]) [99999] nd) @
  1368     (getnds ~99999 false (lev_on b,[0]) q nds); 
  1369 in
  1370 (*get an 'interval from to' from a ptree as 'intervals f t' of respective nodes
  1371   where 'from' are pos, i.e. a key as int list, 'f' an int (to,t analoguous)
  1372 (1) the 'f' are given 
  1373 (1a) by 'from' if 'f' = the respective element of 'from' (left margin)
  1374 (1b) -inifinity, if 'f' > the respective element of 'from' (internal node)
  1375 (2) the 't' ar given
  1376 (2a) by 'to' if 't' = the respective element of 'to' (right margin)
  1377 (2b) inifinity, if 't' < the respective element of 'to (internal node)'
  1378 the 'f' and 't' are set by hdp,... *)
  1379 fun get_trace pt p q =
  1380     (flat o (getnds ((length p) -1) true ([hdp p], tlp p) (tlq q))) 
  1381 	(take_fromto (hdp p) (hdq q) (children pt));
  1382 end;
  1383 
  1384 fun get_somespec ((dI,pI,mI):spec) ((dI',pI',mI'):spec) =
  1385     let val domID = if dI = e_domID
  1386 		    then if dI' = e_domID 
  1387 			 then error"pt_extract: no domID in probl,origin"
  1388 			 else dI'
  1389 		    else dI
  1390 	val pblID = if pI = e_pblID
  1391 		    then if pI' = e_pblID 
  1392 			 then error"pt_extract: no pblID in probl,origin"
  1393 			 else pI'
  1394 		    else pI
  1395 	val metID = if mI = e_metID
  1396 		    then if pI' = e_metID 
  1397 			 then error"pt_extract: no metID in probl,origin"
  1398 			 else mI'
  1399 		    else mI
  1400     in (domID, pblID, metID):spec end;
  1401 fun get_somespec' ((dI,pI,mI):spec) ((dI',pI',mI'):spec) =
  1402     let val domID = if dI = e_domID then dI' else dI
  1403 	val pblID = if pI = e_pblID then pI' else pI
  1404 	val metID = if mI = e_metID then mI' else mI
  1405     in (domID, pblID, metID):spec end;
  1406 
  1407 (*extract a formula or model from ptree for itms2itemppc or model2xml*)
  1408 fun preconds2str bts = 
  1409     (strs2str o (map (linefeed o pair2str o
  1410 		      (apsnd term2str) o 
  1411 		      (apfst bool2str)))) bts;
  1412 fun ocalhd2str ((b, p, hdf, itms, prec, spec):ocalhd) =
  1413     "("^bool2str b^", "^pos_2str p^", "^term2str hdf^
  1414     ", "^itms2str_ (thy2ctxt' "Isac") itms^
  1415     ", "^preconds2str prec^", \n"^spec2str spec^" )";
  1416 
  1417 
  1418 
  1419 fun is_pblnd (Nd (ppobj, _)) = is_pblobj ppobj;
  1420 
  1421 
  1422 (**.functions for the 'ptree iterator' as seen from the FE-Kernel interface.**)
  1423 
  1424 (*move one step down into existing nodes of ptree; regard TransitiveB
  1425 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##################
  1426 fun move_dn _ (Nd (c, ns)) ([],p_) = (*root problem*)
  1427 (* val (Nd (c, ns), ([],p_)) = (pt, get_pos cI uI);
  1428    *)
  1429     if is_pblobj c 
  1430     then case p_ of (*Frm => ([], Pbl) 1.12.03
  1431 		  |*) Res => raise PTREE "move_dn: end of calculation"
  1432 		  | _ => if null ns (*go down from Pbl + Met*)
  1433 			 then raise PTREE "move_dn: solve problem not started"
  1434 			 else ([1], Frm)
  1435     else (case p_ of Res => raise PTREE "move_dn: end of (sub-)tree"
  1436 		  | _ => if null ns
  1437 			 then raise PTREE "move_dn: pos not existent 1"
  1438 			 else ([1], Frm))
  1439 
  1440   (*iterate towards end of pos*)
  1441 (* val (P,(Nd (_, ns)),(p::(ps as (_::_)),p_)) = ([]:pos, pt, get_pos cI uI);
  1442    val (P,(Nd (_, ns)),(p::(ps as (_::_)),p_)) = ((P@[p]),(nth p ns),(ps, p_));
  1443    *) 
  1444  | move_dn P  (Nd (_, ns)) (p::(ps as (_::_)),p_) =
  1445     if p > length ns then raise PTREE "move_dn: pos not existent 2"
  1446     else move_dn ((P@[p]): pos) (nth p ns) (ps, p_)
  1447 (* val (P, (Nd (c, ns)), ([p], p_)) = ((P@[p]), (nth p ns), (ps, p_));
  1448    val (P, (Nd (c, ns)), ([p], p_)) = ([],pt,get_pos cI uI);
  1449    *)
  1450   | move_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1451     if p > length ns then raise PTREE "move_dn: pos not existent 3"
  1452     else if is_pblnd (nth p ns)  then
  1453 	((*tracing("### move_dn: is_pblnd (nth p ns), P= "^ints2str' P^", \n"^
  1454 		 "length ns= "^((string_of_int o length) ns)^
  1455 		 ", p= "^string_of_int p^", p_= "^pos_2str p_);*)
  1456 	 case p_ of Res => if p = length ns 
  1457 			   then if g_ostate c = Complete then (P, Res)
  1458 				else raise PTREE (ints2str' P^" not complete")
  1459 			   (*FIXME here handle not-sequent-branches*)
  1460 			   else if g_branch c = TransitiveB 
  1461 				   andalso (not o is_pblnd o (nth (p+1))) ns
  1462 			   then (P@[p+1], Res)
  1463 			   else (P@[p+1], if is_pblnd (nth (p+1) ns) 
  1464 					  then Pbl else Frm)
  1465 		  | _ => if (null o children o (nth p)) ns (*go down from Pbl*)
  1466 			 then raise PTREE "move_dn: solve subproblem not started"
  1467 			 else (P @ [p, 1], 
  1468 			       if (is_pblnd o hd o children o (nth p)) ns
  1469 			       then Pbl else Frm)
  1470 			      )
  1471     (* val (P, Nd (c, ns), ([p], p_)) = ([], pt, ([1], Frm));
  1472         *)
  1473     else case p_ of Frm => if (null o children o (nth p)) ns 
  1474 			 (*then if g_ostate c = Complete then (P@[p],Res)*)
  1475 			   then if g_ostate' (nth p ns) = Complete 
  1476 				then (P@[p],Res)
  1477 				else raise PTREE "move_dn: pos not existent 4"
  1478 			   else (P @ [p, 1], (*go down*) 
  1479 				 if (is_pblnd o hd o children o (nth p)) ns
  1480 				 then Pbl else Frm)
  1481 		  | Res => if p = length ns 
  1482 			   then 
  1483 			      if g_ostate c = Complete then (P, Res)
  1484 			      else raise PTREE (ints2str' P^" not complete")
  1485 			   else 
  1486 			       if g_branch c = TransitiveB 
  1487 				  andalso (not o is_pblnd o (nth (p+1))) ns
  1488 			       then if (null o children o (nth (p+1))) ns
  1489 				    then (P@[p+1], Res)
  1490 				    else (P@[p+1,1], Frm)(*040221*)
  1491 			       else (P@[p+1], if is_pblnd (nth (p+1) ns) 
  1492 					      then Pbl else Frm); 
  1493 *)
  1494 (*.move one step down into existing nodes of ptree; skip Res = Frm.nxt;
  1495    move_dn at the end of the calc-tree raises PTREE.*)
  1496 fun move_dn _ (Nd (c, ns)) ([],p_) = (*root problem*)
  1497     (case p_ of 
  1498 	     Res => raise PTREE "move_dn: end of calculation"
  1499 	   | _ => if null ns (*go down from Pbl + Met*)
  1500 		  then raise PTREE "move_dn: solve problem not started"
  1501 		  else ([1], Frm))
  1502   | move_dn P  (Nd (_, ns)) (p::(ps as (_::_)),p_) =(*iterate to end of pos*)
  1503     if p > length ns then raise PTREE "move_dn: pos not existent 2"
  1504     else move_dn ((P@[p]): pos) (nth p ns) (ps, p_)
  1505 
  1506   | move_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1507     if p > length ns then raise PTREE "move_dn: pos not existent 3"
  1508     else case p_ of 
  1509 	     Res => 
  1510 	     if p = length ns (*last Res on this level: go a level up*)
  1511 	     then if g_ostate c = Complete then (P, Res)
  1512 		  else raise PTREE (ints2str' P^" not complete 1")
  1513 	     else (*go to the next Nd on this level, or down into the next Nd*)
  1514 		 if is_pblnd (nth (p+1) ns) then (P@[p+1], Pbl)
  1515 		 else 
  1516 		     if g_res' (nth p ns) = g_form' (nth (p+1) ns)
  1517 		     then if (null o children o (nth (p+1))) ns
  1518 			  then (*take the Res if Complete*) 
  1519 			      if g_ostate' (nth (p+1) ns) = Complete 
  1520 			      then (P@[p+1], Res)
  1521 			      else raise PTREE (ints2str' (P@[p+1])^
  1522 						" not complete 2")
  1523 			  else (P@[p+1,1], Frm)(*go down into the next PrfObj*)
  1524 		     else (P@[p+1], Frm)(*take Frm: exists if the Nd exists*)
  1525 	   | Frm => (*go down or to the Res of this Nd*)
  1526 	     if (null o children o (nth p)) ns
  1527 	     then if g_ostate' (nth p ns) = Complete then (P @ [p], Res)
  1528 		  else raise PTREE (ints2str' (P @ [p])^" not complete 3")
  1529 	     else (P @ [p, 1], Frm)
  1530 	   | _ => (*is Pbl or Met*)
  1531 	     if (null o children o (nth p)) ns
  1532 	     then raise PTREE "move_dn:solve subproblem not startd"
  1533 	     else (P @ [p, 1], 
  1534 		   if (is_pblnd o hd o children o (nth p)) ns
  1535 		   then Pbl else Frm);
  1536 
  1537 
  1538 (*.go one level down into ptree.*)
  1539 fun movelevel_dn [] (Nd (c, ns)) ([],p_) = (*root problem*)
  1540     if is_pblobj c 
  1541     then if null ns 
  1542 	 then raise PTREE "solve problem not started"
  1543 	 else ([1], if (is_pblnd o hd) ns then Pbl else Frm)
  1544     else raise PTREE "pos not existent 1"
  1545 
  1546   (*iterate towards end of pos*)
  1547   | movelevel_dn P (Nd (_, ns)) (p::(ps as (_::_)),p_) =
  1548     if p > length ns then raise PTREE "pos not existent 2"
  1549     else movelevel_dn (P@[p]) (nth p ns) (ps, p_)
  1550 
  1551   | movelevel_dn P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1552     if p > length ns then raise PTREE "pos not existent 3" else
  1553     case p_ of Res => 
  1554 	       if p = length ns 
  1555 	       then raise PTREE "no children"
  1556 	       else 
  1557 		   if g_branch c = TransitiveB
  1558 		   then if (null o children o (nth (p+1))) ns
  1559 			then raise PTREE "no children"
  1560 			else (P @ [p+1, 1], 
  1561 			      if (is_pblnd o hd o children o (nth (p+1))) ns
  1562 			      then Pbl else Frm)
  1563 		   else if (null o children o (nth p)) ns
  1564 		   then raise PTREE "no children"
  1565 		   else (P @ [p, 1], if (is_pblnd o hd o children o (nth p)) ns
  1566 				     then Pbl else Frm)
  1567 	     | _ => if (null o children o (nth p)) ns 
  1568 		    then raise PTREE "no children"
  1569 		    else (P @ [p, 1], (*go down*)
  1570 			  if (is_pblnd o hd o children o (nth p)) ns
  1571 			  then Pbl else Frm);
  1572 
  1573 
  1574 
  1575 (*.go to the previous position in ptree; regard TransitiveB.*)
  1576 fun move_up _ (Nd (c, ns)) (([],p_):pos') = (*root problem*)
  1577     if is_pblobj c 
  1578     then case p_ of Res => if null ns then ([], Pbl) (*Res -> Pbl (not Met)!*)
  1579 			   else ([length ns], Res)
  1580 		  | _  => raise PTREE "begin of calculation"
  1581     else raise PTREE "pos not existent"
  1582 
  1583   | move_up P  (Nd (_, ns)) (p::(ps as (_::_)),p_) = (*iterate to end of pos*)
  1584     if p > length ns then raise PTREE "pos not existent"
  1585     else move_up (P@[p]) (nth p ns) (ps,p_)
  1586 
  1587   | move_up P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1588     if p > length ns then raise PTREE "pos not existent"
  1589     else if is_pblnd (nth p ns)  then
  1590 	case p_ of Res => 
  1591 		   let val nc = (length o children o (nth p)) ns
  1592 		   in if nc = 0 then (P@[p], Pbl) (*Res -> Pbl (not Met)!*)
  1593 		      else (P @ [p, nc], Res) end (*go down*)
  1594 		 | _ => if p = 1 then (P, Pbl) else (P@[p-1], Res) 
  1595     else case p_ of Frm => if p <> 1 then (P, Frm) 
  1596 			  else if is_pblobj c then (P, Pbl) else (P, Frm)
  1597 		  | Res => 
  1598 		    let val nc = (length o children o (nth p)) ns
  1599 		    in if nc = 0 (*cannot go down*)
  1600 		       then if g_branch c = TransitiveB andalso p <> 1
  1601 			    then (P@[p-1], Res) else (P@[p], Frm)
  1602 		       else (P @ [p, nc], Res) end; (*go down*)
  1603 
  1604 
  1605 
  1606 (*.go one level up in ptree; sets the position on Frm.*)
  1607 fun movelevel_up _ (Nd (c, ns)) (([],p_):pos') = (*root problem*)
  1608     raise PTREE "pos not existent"
  1609 
  1610   (*iterate towards end of pos*)
  1611   | movelevel_up P  (Nd (_, ns)) (p::(ps as (_::_)),p_) = 
  1612     if p > length ns then raise PTREE "pos not existent"
  1613     else movelevel_up (P@[p]) (nth p ns) (ps,p_)
  1614 
  1615   | movelevel_up P (Nd (c, ns)) ([p], p_) = (*act on last element of pos*)
  1616     if p > length ns then raise PTREE "pos not existent"
  1617     else if is_pblobj c then (P, Pbl) else (P, Frm);
  1618 
  1619 
  1620 (*.go to the next calc-head up in the calc-tree.*)
  1621 fun movecalchd_up pt ((p, Res):pos') =
  1622     (par_pblobj pt p, Pbl):pos'
  1623   | movecalchd_up pt (p, _) =
  1624     if is_pblobj (get_obj I pt p) 
  1625     then (p, Pbl) else (par_pblobj pt p, Pbl);
  1626 
  1627 (*.determine the previous pos' on the same level.*)
  1628 (*WN0502 made for interSteps; _only_ works for branch TransitiveB*)
  1629 fun lev_pred' pt (pos:pos' as ([],Res)) = ([],Pbl):pos'
  1630   | lev_pred' pt (pos:pos' as (p, Res)) =
  1631     let val (p', last) = split_last p
  1632     in if last = 1 
  1633        then if (is_pblobj o (get_obj I pt)) p then (p,Pbl) else (p, Frm)
  1634        else if get_obj g_res pt (p' @ [last - 1]) = get_obj g_form pt p
  1635        then (p' @ [last - 1], Res) (*TransitiveB*)
  1636        else if (is_pblobj o (get_obj I pt)) p then (p,Pbl) else (p, Frm)
  1637     end;
  1638 
  1639 (*.determine the next pos' on the same level.*)
  1640 fun lev_on' pt (([],Pbl):pos') = ([],Res):pos'
  1641   | lev_on' pt (p, Res) =
  1642     if get_obj g_res pt p = get_obj g_form pt (lev_on p)(*TransitiveB*)
  1643     then if existpt' (lev_on p, Res) pt then (lev_on p, Res)
  1644 	 else error ("lev_on': (p, Res) -> (p, Res) not existent, \
  1645 		      \p = "^ints2str' (lev_on p))
  1646     else (lev_on p, Frm)
  1647   | lev_on' pt (p, _) =
  1648     if existpt' (p, Res) pt then (p, Res)
  1649     else error ("lev_on': (p, Frm) -> (p, Res) not existent, \
  1650 		      \p = "^ints2str' p);
  1651 
  1652 fun exist_lev_on' pt p = (lev_on' pt p; true) handle _ => false;
  1653 
  1654 (*.is the pos' at the last element of a calulation _AND_ can be continued.*)
  1655 (* val (pt, pos as (p,p_)) = (pt, ([1],Frm));
  1656    *)
  1657 fun is_curr_endof_calc pt (([],Res) : pos') = false
  1658   | is_curr_endof_calc pt (pos as (p,_)) =
  1659     not (exist_lev_on' pt pos) 
  1660     andalso get_obj g_ostate pt (lev_up p) = Incomplete;
  1661 
  1662 
  1663 (**.insert into ctree and cut branches accordingly.**)
  1664   
  1665 (*.get all positions of certain intervals on the ctree.*)
  1666 (*OLD VERSION without move_dn; kept for occasional redesign
  1667    get all pos's to be cut in a ptree
  1668    below a pos or from a ptree list after i-th element (NO level_up).*)
  1669 fun get_allpos' (_:pos, _:posel) EmptyPtree   = ([]:pos' list)
  1670   | get_allpos' (p, 1) (Nd (b, bs)) = (*p is pos of Nd*)
  1671     if g_ostate b = Incomplete 
  1672     then ((*tracing("get_allpos' (p, 1) Incomplete: p="^ints2str' p);*)
  1673 	  [(p,Frm)] @ (get_allpos's (p, 1) bs)
  1674 	  )
  1675     else ((*tracing("get_allpos' (p, 1) else: p="^ints2str' p);*)
  1676 	  [(p,Frm)] @ (get_allpos's (p, 1) bs) @ [(p,Res)]
  1677 	  )
  1678     (*WN041020 here we assume what is presented on the worksheet ?!*)
  1679   | get_allpos' (p, i) (Nd (b, bs)) = (*p is pos of Nd*)
  1680     if length bs > 0 orelse is_pblobj b
  1681     then if g_ostate b = Incomplete 
  1682 	 then [(p,Frm)] @ (get_allpos's (p, 1) bs)
  1683 	 else [(p,Frm)] @ (get_allpos's (p, 1) bs) @ [(p,Res)]
  1684     else 
  1685 	if g_ostate b = Incomplete 
  1686 	then []
  1687 	else [(p,Res)]
  1688 (*WN041020 here we assume what is presented on the worksheet ?!*)
  1689 and get_allpos's _ [] = []
  1690   | get_allpos's (p, i) (pt::pts) = (*p is pos of parent-Nd*)
  1691     (get_allpos' (p@[i], i) pt) @ (get_allpos's (p, i+1) pts);
  1692 
  1693 (*.get all positions of certain intervals on the ctree.*)
  1694 (*NEW version WN050225*)
  1695 
  1696 
  1697 (*.cut branches.*)
  1698 (*before WN041019......
  1699 val cut_branch = (test_trans, curry take):
  1700     (ppobj -> bool) * (int -> ptree list -> ptree list);
  1701 .. formlery used for ...
  1702 fun cut_tree''' _ [] = EmptyPtree
  1703   | cut_tree''' pt pos = 
  1704   let val (pt',cut) = appl_branch cut_branch pt pos
  1705   in if cut andalso length pos > 1 then cut_tree''' pt' (lev_up pos)
  1706      else pt' end;
  1707 *)
  1708 (*OLD version before WN050225*)
  1709 (*WN050106 like cut_level, but deletes exactly 1 node --- for tests ONLY*)
  1710 fun cut_level_'_ (_:pos' list) (_:pos) EmptyPtree (_:pos') =
  1711     raise PTREE "cut_level_'_ Empty _"
  1712   | cut_level_'_ _ _ (Nd ( _, _)) ([],_) = raise PTREE "cut_level_'_ _ []"
  1713   | cut_level_'_ cuts P (Nd (b, bs)) (p::[],p_) = 
  1714     if test_trans b 
  1715     then (Nd (b, drop_nth [] (p:posel, bs)),
  1716 	  (*     ~~~~~~~~~~~*)
  1717 	  cuts @ 
  1718 	  (if p_ = Frm then [(P@[p],Res)] else ([]:pos' list)) @
  1719 	  (*WN041020 here we assume what is presented on the worksheet ?!*)
  1720 	  (get_allpos's (P, p+1) (drop_nth [] (p, bs))))
  1721     (*                            ~~~~~~~~~~~*)
  1722     else (Nd (b, bs), cuts)
  1723   | cut_level_'_ cuts P (Nd (b, bs)) ((p::ps),p_) =
  1724     let val (bs',cuts') = cut_level_'_ cuts P (nth p bs) (ps, p_)
  1725     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
  1726 
  1727 (*before WN050219*)
  1728 fun cut_level (_:pos' list) (_:pos) EmptyPtree (_:pos') =
  1729     raise PTREE "cut_level EmptyPtree _"
  1730   | cut_level _ _ (Nd ( _, _)) ([],_) = raise PTREE "cut_level _ []"
  1731 
  1732   | cut_level cuts P (Nd (b, bs)) (p::[],p_) = 
  1733     if test_trans b 
  1734     then (Nd (b, take (p:posel, bs)),
  1735 	  cuts @ 
  1736 	  (if p_ = Frm andalso (*#*) g_ostate b = Complete
  1737 	   then [(P@[p],Res)] else ([]:pos' list)) @
  1738 	  (*WN041020 here we assume what is presented on the worksheet ?!*)
  1739 	  (get_allpos's (P, p+1) (takerest (p, bs))))
  1740     else (Nd (b, bs), cuts)
  1741 
  1742   | cut_level cuts P (Nd (b, bs)) ((p::ps),p_) =
  1743     let val (bs',cuts') = cut_level cuts P (nth p bs) (ps, p_)
  1744     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
  1745 
  1746 (*OLD version before WN050219, overwritten below*)
  1747 fun cut_tree _ (([],_):pos') = raise PTREE "cut_tree _ ([],_)"
  1748   | cut_tree pt (pos as ([p],_)) =
  1749     let	val (pt', cuts) = cut_level ([]:pos' list) [] pt pos
  1750     in (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete 
  1751 		     then [] else [([],Res)])) end
  1752   | cut_tree pt (p,p_) =
  1753     let	
  1754 	fun cutfn pt cuts (p,p_) = 
  1755 	    let val (pt', cuts') = cut_level [] (lev_up p) pt (p,p_)
  1756 		val cuts'' = if get_obj g_ostate pt (lev_up p) = Incomplete 
  1757 			     then [] else [(lev_up p, Res)]
  1758 	    in if length cuts' > 0 andalso length p > 1
  1759 	       then cutfn pt' (cuts @ cuts') (lev_up p, Frm(*-->(p,Res)*))
  1760 	       else (pt',cuts @ cuts') end
  1761 	val (pt', cuts) = cutfn pt [] (p,p_)
  1762     in (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete 
  1763 		     then [] else [([], Res)])) end;
  1764 
  1765 
  1766 (*########/ inserted from ctreeNEW.sml \#################################**)
  1767 
  1768 (*.get all positions in a ptree until ([],Res) or ostate=Incomplete
  1769 val get_allp = fn : 
  1770   pos' list -> : accumulated, start with []
  1771   pos ->       : the offset for subtrees wrt the root
  1772   ptree ->     : (sub)tree
  1773   pos'         : initialization (the last pos' before ...)
  1774   -> pos' list : of positions in this (sub) tree (relative to the root)
  1775 .*)
  1776 (* val (cuts, P, pt, pos) = ([], [3], get_nd pt [3], ([], Frm):pos');
  1777    val (cuts, P, pt, pos) = ([], [2], get_nd pt [2], ([], Frm):pos');
  1778    length (children pt);
  1779    *)
  1780 fun get_allp (cuts:pos' list) (P:pos, pos:pos') pt =
  1781     (let val nxt = move_dn [] pt pos (*exn if Incomplete reached*)
  1782      in if nxt <> ([],Res) 
  1783 	then get_allp (cuts @ [nxt]) (P, nxt) pt
  1784 	else (map (apfst (curry op@ P)) (cuts @ [nxt])): pos' list
  1785      end) handle PTREE _ => (map (apfst (curry op@ P)) cuts);
  1786 
  1787 
  1788 (*the pts are assumed to be on the same level*)
  1789 fun get_allps (cuts: pos' list) (P:pos) [] = cuts
  1790   | get_allps cuts P (pt::pts) =
  1791     let val below = get_allp [] (P, ([], Frm)) pt
  1792 	val levfrm = 
  1793 	    if is_pblnd pt 
  1794 	    then (P, Pbl)::below
  1795 	    else if last_elem P = 1 
  1796 	    then (P, Frm)::below
  1797 	    else (*Trans*) below
  1798 	val levres = levfrm @ (if null below then [(P, Res)] else [])
  1799     in get_allps (cuts @ levres) (lev_on P) pts end;
  1800 
  1801 
  1802 (**.these 2 funs decide on how far cut_tree goes.**)
  1803 (*.shall the nodes _after_ the pos to be inserted at be deleted?.*)
  1804 fun test_trans (PrfObj{branch = Transitive,...}) = true
  1805   | test_trans (PrfObj{branch = NoBranch,...}) = true
  1806   | test_trans (PblObj{branch = Transitive,...}) = true 
  1807   | test_trans (PblObj{branch = NoBranch,...}) = true 
  1808   | test_trans _ = false;
  1809 (*.shall cutting be continued on the higher level(s)?
  1810    the Nd regarded will NOT be changed.*)
  1811 fun cutlevup (PblObj _) = false (*for tests of LK0502*)
  1812   | cutlevup _ = true;
  1813 val cutlevup = test_trans;(*WN060727 after summerterm tests.LK0502 withdrawn*)
  1814     
  1815 (*cut_bottom new sml603..608
  1816 cut the level at the bottom of the pos (used by cappend_...)
  1817 and handle the parent in order to avoid extra case for root
  1818 fn: ptree ->         : the _whole_ ptree for cut_levup
  1819     pos * posel ->   : the pos after split_last
  1820     ptree ->         : the parent of the Nd to be cut
  1821 return
  1822     (ptree *         : the updated ptree
  1823      pos' list) *    : the pos's cut
  1824      bool            : cutting shall be continued on the higher level(s)
  1825 *)
  1826 fun cut_bottom _ (pt' as Nd (b, [])) = ((pt', []), cutlevup b)
  1827   | cut_bottom (P:pos, p:posel) (Nd (b, bs)) =
  1828     let (*divide level into 3 parts...*)
  1829 	val keep = take (p - 1, bs)
  1830 	val pt' as Nd (_,bs') = nth p bs
  1831 	(*^^^^^_here_ will be 'insert'ed by 'append_..'*)
  1832 	val (tail, tp) = (takerest (p, bs), 
  1833 			  if null (takerest (p, bs)) then 0 else p + 1)
  1834 	val (children, cuts) = 
  1835 	    if test_trans b
  1836 	    then (keep,
  1837 		  (if is_pblnd pt' then [(P @ [p], Pbl)] else [])
  1838 		  @ (get_allp  [] (P @ [p], (P, Frm)) pt')
  1839 		  @ (get_allps [] (P @ [p+1]) tail))
  1840 	    else (keep @ [(*'insert'ed by 'append_..'*)] @ tail,
  1841 		  get_allp  [] (P @ [p], (P, Frm)) pt')
  1842 	val (pt'', cuts) = 
  1843 	    if cutlevup b
  1844 	    then (Nd (del_res b, children), 
  1845 		  cuts @ (if g_ostate b = Incomplete then [] else [(P,Res)]))
  1846 	    else (Nd (b, children), cuts)
  1847 	(*val _= tracing("####cut_bottom (P, p)="^pos2str (P @ [p])^
  1848 		       ", Nd=.............................................")
  1849 	val _= show_pt pt''
  1850 	val _= tracing("####cut_bottom form='"^
  1851 		       term2str (get_obj g_form pt'' []))
  1852 	val _= tracing("####cut_bottom cuts#="^string_of_int (length cuts)^
  1853 		       ", cuts="^pos's2str cuts)*)
  1854     in ((pt'', cuts:pos' list), cutlevup b) end;
  1855 
  1856 
  1857 (*.go all levels from the bottom of 'pos' up to the root, 
  1858  on each level compose the children of a node and accumulate the cut Nds
  1859 args
  1860    pos' list ->      : for accumulation
  1861    bool -> 	     : cutting shall be continued on the higher level(s)
  1862    ptree -> 	     : the whole ptree for 'get_nd pt P' on each level
  1863    ptree -> 	     : the Nd from the lower level for insertion at path
  1864    pos * posel ->    : pos=path split for convenience
  1865    ptree -> 	     : Nd the children of are under consideration on this call 
  1866 returns		     :
  1867    ptree * pos' list : the updated parent-Nd and the pos's of the Nds cut
  1868 .*)
  1869 fun cut_levup (cuts:pos' list) clevup pt pt' (P:pos, p:posel) (Nd (b, bs)) =
  1870     let (*divide level into 3 parts...*)
  1871 	val keep = take (p - 1, bs)
  1872 	(*val pt' comes as argument from below*)
  1873 	val (tail, tp) = (takerest (p, bs), 
  1874 			  if null (takerest (p, bs)) then 0 else p + 1)
  1875 	val (children, cuts') = 
  1876 	    if clevup
  1877 	    then (keep @ [pt'], get_allps [] (P @ [p+1]) tail)
  1878 	    else (keep @ [pt'] @ tail, [])
  1879 	val clevup' = if clevup then cutlevup b else false 
  1880 	(*the first Nd with false stops cutting on all levels above*)
  1881 	val (pt'', cuts') = 
  1882 	    if clevup'
  1883 	    then (Nd (del_res b, children), 
  1884 		  cuts' @ (if g_ostate b = Incomplete then [] else [(P,Res)]))
  1885 	    else (Nd (b, children), cuts')
  1886 	(*val _= tracing("#####cut_levup clevup= "^bool2str clevup)
  1887 	val _= tracing("#####cut_levup cutlevup b= "^bool2str (cutlevup b))
  1888 	val _= tracing("#####cut_levup (P, p)="^pos2str (P @ [p])^
  1889 		       ", Nd=.............................................")
  1890 	val _= show_pt pt''
  1891 	val _= tracing("#####cut_levup form='"^
  1892 		       term2str (get_obj g_form pt'' []))
  1893 	val _= tracing("#####cut_levup cuts#="^string_of_int (length cuts)^
  1894 		       ", cuts="^pos's2str cuts)*)
  1895     in if null P then (pt'', (cuts @ cuts'):pos' list)
  1896        else let val (P, p) = split_last P
  1897 	    in cut_levup (cuts @ cuts') clevup' pt pt'' (P, p) (get_nd pt P)
  1898 	    end
  1899     end;
  1900  
  1901 (*.cut nodes after and below an inserted node in the ctree;
  1902    the cuts range is limited by the predicate 'fun cutlevup'.*)
  1903 fun cut_tree pt (pos,_) =
  1904     if not (existpt pos pt) 
  1905     then (pt,[]) (*appending a formula never cuts anything*)
  1906     else let val (P, p) = split_last pos
  1907 	     val ((pt', cuts), clevup) = cut_bottom (P, p) (get_nd pt P)
  1908 	 (*        pt' is the updated parent of the Nd to cappend_..*)
  1909 	 in if null P then (pt', cuts)
  1910 	    else let val (P, p) = split_last P
  1911 		 in cut_levup cuts clevup pt pt' (P, p) (get_nd pt P)
  1912 		 end
  1913 	 end;
  1914 
  1915 fun append_atomic p l f r f' s pt = 
  1916   let (**val _= tracing("#@append_atomic: pos ="^pos2str p)**)
  1917 	val (iss, f) = if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  1918 		     then (*after Take*)
  1919 			 ((fst (get_obj g_loc pt p), SOME l), 
  1920 			  get_obj g_form pt p) 
  1921 		     else ((NONE, SOME l), f)
  1922   in insert (PrfObj {cell = NONE,
  1923 		     form  = f,
  1924 		     tac  = r,
  1925 		     loc   = iss,
  1926 		     branch= NoBranch,
  1927 		     result= f',
  1928 		     ostate= s}) pt p end;
  1929 
  1930 
  1931 (*20.8.02: cappend_* FIXXXXME cut branches below cannot be decided here:
  1932   detail - generate - cappend: inserted, not appended !!!
  1933 
  1934   cut decided in applicable_in !?!
  1935 *)
  1936 fun cappend_atomic pt p loc f r f' s = 
  1937 (* val (pt, p, loc, f, r, f', s) = 
  1938        (pt,p,l,f,Rewrite_Set_Inst (subst2subs subs',id_rls rls'),
  1939 	(f',asm),Complete);
  1940    *)
  1941 ((*tracing("##@cappend_atomic: pos ="^pos2str p);*)
  1942   apfst (append_atomic p loc f r f' s) (cut_tree pt (p,Frm))
  1943 );
  1944 (*TODO.WN050305 redesign the handling of istates*)
  1945 fun cappend_atomic pt p ist_res f r f' s = 
  1946       if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  1947       then (*after Take: transfer Frm and respective istate*)
  1948 	      let
  1949           val (ist_form, f) =
  1950             (get_loc pt (p,Frm), get_obj g_form pt p)
  1951 	        val (pt, cs) = cut_tree pt (p,Frm)
  1952 	        val pt = append_atomic p (e_istate, e_ctxt) f r f' s pt
  1953 	        val pt = update_loc' pt p (SOME ist_form, SOME ist_res)
  1954 	      in (pt, cs) end
  1955       else apfst (append_atomic p ist_res f r f' s) (cut_tree pt (p,Frm));
  1956 
  1957 (* called by Take *)
  1958 fun append_form p l f pt = 
  1959 ((*tracing("##@append_form: pos ="^pos2str p);*)
  1960   insert (PrfObj {cell = NONE,
  1961 		  form  = (*if existpt p pt 
  1962 		  andalso get_obj g_tac pt p = Empty_Tac 
  1963 			    (*distinction from 'old' (+complete!) pobjs*)
  1964 			    then get_obj g_form pt p else*) f,
  1965 		  tac  = Empty_Tac,
  1966 		  loc   = (SOME l, NONE),
  1967 		  branch= NoBranch,
  1968 		  result= (e_term,[]),
  1969 		  ostate= Incomplete}) pt p
  1970 );
  1971 (* val (p,loc,f) = ([1], e_istate, str2term "x + 1 = 2");
  1972    val (p,loc,f) = (fst p, e_istate, str2term "-1 + x = 0");
  1973    *)
  1974 fun cappend_form pt p loc f =
  1975 ((*tracing("##@cappend_form: pos ="^pos2str p);*)
  1976   apfst (append_form p loc f) (cut_tree pt (p,Frm))
  1977 );
  1978 fun cappend_form pt p loc f =
  1979 let (*val _= tracing("##@cappend_form: pos ="^pos2str p)
  1980     val _= tracing("##@cappend_form before cut_tree: loc ="^istate2str loc)*)
  1981     val (pt', cs) = cut_tree pt (p,Frm)
  1982     val pt'' = append_form p loc f pt'
  1983     (*val _= tracing("##@cappend_form after append: loc ="^
  1984 		   istates2str (get_obj g_loc pt'' p))*)
  1985 in (pt'', cs) end;
  1986 
  1987 
  1988     
  1989 fun append_result pt p l f s =
  1990 ((*tracing("##@append_result: pos ="^pos2str p);*)
  1991     (appl_obj (repl_result (fst (get_obj g_loc pt p),
  1992 			    SOME l) f s) pt p, [])
  1993 );
  1994 
  1995 
  1996 (*WN041022 deprecated, still for kbtest/diffapp.sml, /systest/root-equ.sml*)
  1997 fun append_parent p l f r b pt = 
  1998   let (*val _= tracing("###append_parent: pos ="^pos2str p);*)
  1999     val (ll,f) = if existpt p pt andalso get_obj g_tac pt p=Empty_Tac
  2000 		  then ((fst (get_obj g_loc pt p), SOME l), 
  2001 			get_obj g_form pt p) 
  2002 		 else ((SOME l, NONE), f)
  2003   in insert (PrfObj 
  2004 	  {cell = NONE,
  2005 	   form  = f,
  2006 	   tac  = r,
  2007 	   loc   = ll,
  2008 	   branch= b,
  2009 	   result= (e_term,[]),
  2010 	   ostate= Incomplete}) pt p end;
  2011 fun cappend_parent pt p loc f r b =
  2012 ((*tracing("###cappend_parent: pos ="^pos2str p);*)
  2013   apfst (append_parent p loc f r b) (cut_tree pt (p,Und))
  2014 );
  2015 
  2016 
  2017 fun append_problem [] l fmz (strs,spec,hdf) _ =
  2018 ((*tracing("###append_problem: pos = []");*)
  2019   (Nd (PblObj 
  2020 	       {cell  = NONE,
  2021 		origin= (strs,spec,hdf),
  2022 		fmz   = fmz,
  2023 		spec  = empty_spec,
  2024 		probl = []:itm list,
  2025 		meth  = []:itm list,
  2026     ctxt  = e_ctxt,
  2027 		env   = NONE,
  2028 		loc   = (SOME l, NONE),
  2029 		branch= TransitiveB,(*FIXXXXXME.27.8.03: for equations only*)
  2030 		result= (e_term,[]),
  2031 		ostate= Incomplete},[]))
  2032 )
  2033   | append_problem p l fmz (strs,spec,hdf) pt =
  2034 ((*tracing("###append_problem: pos ="^pos2str p);*)
  2035   insert (PblObj 
  2036 	  {cell  = NONE,
  2037 	   origin= (strs,spec,hdf),
  2038 	   fmz   = fmz,
  2039 	   spec  = empty_spec,
  2040 	   probl = []:itm list,
  2041 	   meth  = []:itm list,
  2042      ctxt  = e_ctxt,
  2043 	   env   = NONE,
  2044 	   loc   = (SOME l, NONE),
  2045 	   branch= TransitiveB,
  2046 	   result= (e_term,[]),
  2047 	   ostate= Incomplete}) pt p
  2048 );
  2049 fun cappend_problem _ [] loc fmz ori =
  2050 ((*tracing("###cappend_problem: pos = []");*)
  2051   (append_problem [] loc fmz ori EmptyPtree,[])
  2052 )
  2053   | cappend_problem pt p loc fmz ori = 
  2054 ((*tracing("###cappend_problem: pos ="^pos2str p);*)
  2055   apfst (append_problem p (loc:(istate * Proof.context)) fmz ori) (cut_tree pt (p,Frm))
  2056 );
  2057 
  2058 (*.get the theory explicitly specified for the rootpbl;
  2059    thus use this function _after_ finishing specification.*)
  2060 fun rootthy (Nd (PblObj {spec=(thyID, _, _), ...}, _)) = assoc_thy thyID
  2061   | rootthy _ = error "rootthy";
  2062