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

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