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