src/Tools/isac/MathEngBasic/ctree-basic.sml
author wneuper <Walther.Neuper@jku.at>
Wed, 19 Oct 2022 10:43:04 +0200
changeset 60567 bb3140a02f3d
parent 60545 30b1475b2295
child 60586 007ef64dbb08
permissions -rw-r--r--
eliminate term2str in src, Prog_Tac.*_adapt_to_type
     1 (* Title: the calctree, which holds a calculation
     2    Author: Walther Neuper 1999
     3    (c) due to copyright terms
     4 
     5 Definitions required for Ctree, renamed later appropriately
     6 *)
     7 
     8 signature BASIC_CALC_TREE =
     9 sig
    10 (**** signature ****)
    11 (** the basic datatype **)
    12   type state
    13   val e_state: state
    14 
    15   type con
    16   eqtype cellID
    17 
    18   datatype branch  = AndB | CollectB | IntersectB | MapB | NoBranch | OrB | SequenceB | TransitiveB
    19   datatype ostate = Complete | Incomplete | Inconsistent
    20   type specify_data
    21   type solve_data
    22   datatype ppobj = PblObj of specify_data | PrfObj of solve_data
    23   datatype ctree = EmptyPtree | Nd of ppobj * ctree list
    24 
    25   val rep_solve_data: ppobj -> solve_data
    26   val rep_specify_data: ppobj -> specify_data
    27 
    28 (** basic functions **)
    29   val e_ctree : ctree (* TODO: replace by EmptyPtree*)
    30   val existpt' : Pos.pos' -> ctree -> bool
    31   val is_interpos : Pos.pos' -> bool
    32   val lev_pred' : ctree -> Pos.pos' -> Pos.pos'
    33   val ins_chn : ctree list -> ctree -> Pos.pos -> ctree
    34   val children : ctree -> ctree list
    35   val get_nd : ctree -> Pos.pos -> ctree
    36   val just_created_ : ppobj -> bool
    37   val just_created : state -> bool
    38   val e_origin : Model_Def.o_model * References_Def.T * term
    39 
    40   val is_pblobj : ppobj -> bool
    41   val is_pblobj' : ctree -> Pos.pos -> bool
    42   val is_pblnd : ctree -> bool
    43 
    44   val g_spec : ppobj -> References_Def.T
    45   val g_loc : ppobj -> (Istate_Def.T * Proof.context) option * (Istate_Def.T * Proof.context) option
    46   val g_form : ppobj -> term
    47   val g_pbl : ppobj -> Model_Def.i_model
    48   val g_met : ppobj -> Model_Def.i_model
    49   val g_metID : ppobj -> MethodC.id
    50   val g_result : ppobj -> Celem.result
    51   val g_tac : ppobj -> Tactic.input
    52   val g_domID : ppobj -> ThyC.id
    53 
    54   val g_origin : ppobj -> Model_Def.o_model * References_Def.T * term
    55   val get_loc : ctree -> Pos.pos' -> Istate_Def.T * Proof.context
    56   val get_istate_LI : ctree -> Pos.pos' -> Istate_Def.T
    57   val get_ctxt_LI: ctree -> Pos.pos' -> Proof.context
    58   val get_ctxt : ctree -> Pos.pos' -> Proof.context (*DEPRECATED*)
    59   val get_obj : (ppobj -> 'a) -> ctree -> Pos.pos -> 'a
    60   val get_curr_formula : state -> term
    61   val get_assumptions : ctree -> Pos.pos' -> term list
    62 
    63   val new_val : term -> Istate_Def.T -> Istate_Def.T
    64 
    65   type cid = cellID list
    66   datatype ptform = Form of term | ModSpec of Specification_Def.T
    67   val get_somespec' : References_Def.T -> References_Def.T -> References_Def.T
    68   exception PTREE of string;
    69   
    70   val rootthy : ctree -> theory
    71 (* ---- made visible ONLY for structure CTaccess : CALC_TREE_ACCESS --------------------------- *)
    72   val appl_obj : (ppobj -> ppobj) -> ctree -> Pos.pos -> ctree
    73   val existpt : Pos.pos -> ctree -> bool
    74   val cut_tree : ctree -> Pos.pos * 'a -> ctree * Pos.pos' list
    75   val insert_pt : ppobj -> ctree -> int list -> ctree
    76 (* ---- made visible ONLY for structure CTnavi : CALC_TREE_NAVIGATION ------------------------- *)
    77   val g_branch : ppobj -> branch
    78   val g_form' : ctree -> term
    79   val g_ostate : ppobj -> ostate
    80   val g_ostate' : ctree -> ostate
    81   val g_res : ppobj -> term
    82   val g_res' : ctree -> term 
    83 (*/---- duplicates in CTnavi, reconsider structs -----------------------------------------------
    84   val lev_dn : CTbasic.Pos.pos -> Pos.pos                        (* duplicate in ctree-navi.sml *)
    85   val par_pblobj : CTbasic.ctree -> Pos.pos -> Pos.pos           (* duplicate in ctree-navi.sml *)
    86    ---- duplicates in CTnavi, reconsider structs ----------------------------------------------/*)
    87 
    88 \<^isac_test>\<open>
    89   val pr_ctree : (Pos.pos -> ppobj -> string) -> ctree -> string
    90   val pr_short : Pos.pos -> ppobj -> string
    91   val g_ctxt : ppobj -> Proof.context
    92   val g_fmz : ppobj -> Model_Def.form_T
    93   val get_allp : Pos.pos' list -> Pos.pos * (int list * Pos.pos_) -> ctree -> Pos.pos' list
    94   val get_allps : (Pos.pos * Pos.pos_) list -> Pos.posel list -> ctree list -> Pos.pos' list
    95   val get_allpos' : Pos.pos * Pos.posel -> ctree -> Pos.pos' list
    96   val get_allpos's : Pos.pos * Pos.posel -> ctree list -> (Pos.pos * Pos.pos_) list
    97   val cut_bottom : Pos.pos * Pos.posel -> ctree -> (ctree * Pos.pos' list) * bool
    98   val cut_level : Pos.pos' list -> Pos.pos -> ctree -> int list * Pos.pos_ -> ctree * Pos.pos' list
    99   val cut_level__ : Pos.pos' list -> Pos.pos -> ctree -> int list * Pos.pos_ -> ctree * Pos.pos' list
   100   val get_trace : ctree -> int list -> int list -> int list list
   101   val branch2str : branch -> string
   102 \<close>
   103 end
   104 
   105 (**)
   106 structure CTbasic(**): BASIC_CALC_TREE(**) =
   107 struct
   108 (**)
   109 open Pos
   110 
   111 (**** Ctree ****)
   112 
   113 (*** general types* **)
   114 
   115 datatype branch = 
   116 	NoBranch | AndB | OrB 
   117 | TransitiveB  (* FIXXXME.0308: set branch from met in Apply_Method
   118                   FIXXXME.0402: -"- in Begin_Trans'*)
   119 | SequenceB | IntersectB | CollectB | MapB;
   120 
   121 \<^isac_test>\<open>
   122 fun branch2str NoBranch = "NoBranch"
   123   | branch2str AndB = "AndB"
   124   | branch2str OrB = "OrB"
   125   | branch2str TransitiveB = "TransitiveB" 
   126   | branch2str SequenceB = "SequenceB"
   127   | branch2str IntersectB = "IntersectB"
   128   | branch2str CollectB = "CollectB"
   129   | branch2str MapB = "MapB";
   130 \<close>
   131 
   132 datatype ostate = 
   133     Incomplete | Complete | Inconsistent (* WN041020 latter still unused *);
   134 \<^isac_test>\<open>
   135 fun ostate2str Incomplete = "Incomplete"
   136   | ostate2str Complete = "Complete"
   137   | ostate2str Inconsistent = "Inconsistent";
   138 \<close>
   139 
   140 type cellID = int;     
   141 type cid = cellID list;
   142 
   143 
   144 type iist = Istate_Def.T option * Istate_Def.T option;
   145 (*val e_iist = (empty, empty); --- sinnlos f"ur NICHT-equality-type*) 
   146 
   147 
   148 fun new_val v (Istate_Def.Pstate pst) =
   149     (Istate_Def.Pstate (Istate_Def.set_act v pst))
   150   | new_val _ _ = raise ERROR "new_val: only for Pstate";
   151 
   152 datatype con = land | lor;
   153 
   154 (* executed tactics (tac_s) with local environment etc.;
   155   used for continuing eval script + for generate *)
   156 type ets =
   157   (TermC.path *(* of tactic in scr, tactic (weakly) associated with tac_                   *)
   158    (Tactic.T * (* (for generate)                                                           *)
   159     Env.T *      (* with 'tactic=result' as  rule, tactic ev. _not_ ready for 'parallel let' *)
   160     Env.T *      (* with results of (ready) tacs                                             *)
   161     term *     (* itr_arg of tactic, for upd. env at Repeat, Try                           *)
   162     term *     (* result value of the tac                                                  *)
   163     Celem.safe))
   164   list;
   165 
   166 \<^isac_test>\<open>
   167 fun ets2s (l,(m,eno,env,iar,res,s)) = 
   168   "\n(" ^ TermC.string_of_path l ^ ",(" ^ Tactic.string_of m ^
   169   ",\n  ens= " ^ Env.subst2str eno ^
   170   ",\n  env= " ^ Env.subst2str env ^
   171   ",\n  iar= " ^ UnparseC.term iar ^
   172   ",\n  res= " ^ UnparseC.term res ^
   173   ",\n  " ^ Celem.safe2str s ^ "))";
   174 fun ets2str (ets: ets) = (strs2str o (map ets2s)) ets;
   175 \<close>
   176 
   177 type envp =(*9.5.03: unused, delete with field in ctree.PblObj FIXXXME*)
   178   (int * term list) list * (* assoc-list: args of met*)
   179   (int * Rule_Set.T) list * (* assoc-list: tacs already done ///15.9.00*)
   180   (int * ets) list *       (* assoc-list: tacs etc. already done*)
   181   (string * pos) list;     (* asms * from where*)
   182 
   183 
   184 (*** type Ctree ***)
   185 
   186 type specify_data =
   187    {fmz   : Model_Def.form_T, (* from init:FIXME never use this spec;-drop                     *)
   188     origin: (Model_Def.o_model) *(* = O_Model.T for efficiently checking input to I_Model      *)
   189 	           References_Def.T *  (* updated by Refine_Tacitly                                  *)
   190 	           term,            (* headline of calc-head, as calculated initially(!)             *)
   191     spec  : References_Def.T, (* explicitly input                                              *)
   192     probl : Model_Def.i_model,(* = I_Model.T for interactive input to a Problem                *)
   193     meth  : Model_Def.i_model,(* = I_Model.T for interactive input to a MethodC                *)
   194     ctxt  : Proof.context,    (* used while specifying this (Sub-)Problem and MethodC          *)
   195     loc   : (Istate_Def.T * Proof.context) option  (* like in PrfObj, calling this SubProblem  *)
   196           * (Istate_Def.T * Proof.context) option, (* like in PrfObj, finishing the SubProblem *)
   197     branch: branch,           (* like PrfObj                                                   *)
   198     result: Celem.result,     (* like PrfObj                                                   *)
   199     ostate: ostate};          (* like PrfObj                                                   *)
   200 type solve_data = (* TODO: arrange according to signature *)
   201    {form  : term,             (* where tactic is applied to                                    *)
   202 	  tac   : Tactic.input,     (* tactic as presented to users                                  *)
   203 	  loc   : (Istate_Def.T *   (* program interpreter state                                     *)
   204 	           Proof.context)   (* context for provers, type inference                           *)
   205             option *          (* both for interpreter location on Frm, Pbl, Met                *)
   206             (Istate_Def.T *   (* script interpreter state                                      *)
   207              Proof.context)   (* context for provers, type inference                           *)
   208             option,           (* both for interpreter location on Res, (NONE,NONE) == empty    *)
   209 	  branch: branch,           (* only rudimentary                                              *)
   210 	  result: Celem.result,     (* result and assumptions                                        *)
   211 	  ostate: ostate}           (* Complete <=> result is OK                                     *)
   212 
   213 datatype ppobj =
   214   PblObj of specify_data      (* data serving a whole specification-phase                      *)
   215 | PrfObj of solve_data;       (* data for a proof step triggered by a tactic                   *)
   216 
   217 (* this tree contains isac's calculations;
   218    the tree's structure has been copied from an early version of Theorema(c);
   219    it has the disadvantage, that there is no space 
   220    for the first tactic in a script generating the first formula at (p,Frm);
   221    this trouble has been covered by 'implicit_take' and 'Take' so far,
   222    but it is crucial if the first tactic in a script is eg. 'Subproblem';
   223    see 'type tac', Apply_Method.
   224 *)
   225 datatype ctree = 
   226   EmptyPtree
   227 | Nd of ppobj * (ctree list);
   228 val e_ctree = EmptyPtree;
   229 type state = ctree * pos'
   230 val e_state = (EmptyPtree , e_pos')
   231 
   232 fun rep_solve_data (PrfObj solve_data) = solve_data
   233   | rep_solve_data _ = raise ERROR "rep_solve_data ONLY for solve_data"
   234 fun rep_specify_data (PblObj specify_data) = specify_data
   235   | rep_specify_data _ = raise ERROR "rep_solve_data ONLY for solve_data"
   236 
   237 
   238 (*** minimal set of functions on Ctree* **)
   239 
   240 fun is_pblobj (PblObj _) = true
   241   | is_pblobj _ = false;
   242 
   243 exception PTREE of string;
   244 fun nth _ [] = raise PTREE "nth _ []"
   245   | nth 1 (x :: _) = x
   246   | nth n (_ :: xs) = nth (n - 1) xs;
   247 (*> nth 2 [11,22,33]; -->> val it = 22 : int*)
   248 
   249 
   250 (** convert ctree to a string **)
   251 
   252 \<^isac_test>\<open>
   253 (* convert a pos from list to string *)
   254 fun pr_pos ps = (space_implode "." (map string_of_int ps)) ^ ".   ";
   255 (* show hd origin or form only *)
   256 fun pr_short p (PblObj _) =  pr_pos p ^ " ----- pblobj -----\n"
   257   | pr_short p (PrfObj {form = form, ...}) = pr_pos p ^ UnparseC.term form ^ "\n";
   258 fun pr_ctree f pt =
   259   let
   260     fun pr_pt _ _  EmptyPtree = ""
   261       | pr_pt pfn ps (Nd (b, [])) = pfn ps b
   262       | pr_pt pfn ps (Nd (b, ts)) = pfn ps b ^ prts pfn ps 1 ts
   263     and prts _ _ _ [] = ""
   264       | prts pfn ps p (t :: ts) = (pr_pt pfn (ps @ [p]) t)^
   265       (prts pfn ps (p + 1) ts)
   266   in pr_pt f [] pt end;
   267 \<close>
   268 
   269 (** access the branches of ctree **)
   270 
   271 fun repl [] _ _ = raise PTREE "repl [] _ _"
   272   | repl (_ :: ls) 1 e = e :: ls
   273   | repl (l :: ls) n e = l :: (repl ls (n-1) e);
   274 fun repl_app ls n e = 
   275   let
   276     val lim = 1 + length ls
   277   in
   278     if n > lim
   279     then raise PTREE "repl_app: n > lim"
   280     else if n = lim
   281       then ls @ [e]
   282       else repl ls n e end;
   283 
   284 (* get from obj at pos by f : ppobj -> 'a *)
   285 fun get_obj _ EmptyPtree _ = raise PTREE "get_obj f EmptyPtree"
   286   | get_obj f (Nd (b, _)) [] = f b
   287   | get_obj f (Nd (_, bs)) (p :: ps) =
   288     case \<^try>\<open> get_obj f (nth p bs) ps \<close> of
   289       SOME obj => obj
   290     | NONE => raise PTREE ("get_obj: pos = " ^ ints2str' (p :: ps) ^ " does not exist");
   291 fun get_nd EmptyPtree _ = raise PTREE "get_nd EmptyPtree"
   292   | get_nd n [] = n
   293   | get_nd (Nd (_, nds)) (pos as p :: ps) =
   294     case \<^try>\<open> get_nd (nth p nds) ps \<close> of
   295       SOME nd => nd
   296     | NONE => raise PTREE ("get_nd: not existent pos = " ^ ints2str' pos);
   297 
   298 (* for use by get_obj *)
   299 fun g_form   (PrfObj {form = f,...}) = f
   300   | g_form   (PblObj {origin= (_,_,f),...}) = f;
   301 fun g_form' (Nd (PrfObj {form = f, ...}, _)) = f
   302   | g_form' (Nd (PblObj {origin= (_, _, f),...}, _)) = f
   303   | g_form' _ = raise ERROR "g_form': uncovered fun def.";
   304 (*  | g_form   _ = raise PTREE "g_form not for PblObj";*)
   305 fun g_origin (PblObj {origin = ori, ...}) = ori
   306   | g_origin _ = raise PTREE "g_origin not for PrfObj";
   307 \<^isac_test>\<open>
   308 fun g_fmz (PblObj {fmz = f, ...}) = f
   309   | g_fmz _ = raise PTREE "g_fmz not for PrfObj";
   310 \<close>
   311 fun g_spec   (PblObj {spec = s, ...}) = s
   312   | g_spec _   = raise PTREE "g_spec not for PrfObj";
   313 fun g_pbl    (PblObj {probl = p, ...}) = p
   314   | g_pbl  _   = raise PTREE "g_pbl not for PrfObj";
   315 fun g_met    (PblObj {meth = p, ...}) = p
   316   | g_met  _   = raise PTREE "g_met not for PrfObj";
   317 fun g_domID  (PblObj {spec = (d, _, _), ...}) = d
   318   | g_domID  _ = raise PTREE "g_metID not for PrfObj";
   319 fun g_metID  (PblObj {spec = (_, _, m), ...}) = m
   320   | g_metID  _ = raise PTREE "g_metID not for PrfObj";
   321 fun g_ctxt    (PblObj {ctxt, ...}) = ctxt
   322   | g_ctxt    _ = raise PTREE "g_ctxt not for PrfObj"; 
   323 fun g_loc    (PblObj {loc = l, ...}) = l
   324   | g_loc    (PrfObj {loc = l, ...}) = l;
   325 fun g_branch (PblObj {branch = b, ...}) = b
   326   | g_branch (PrfObj {branch = b, ...}) = b;
   327 fun g_tac  (PblObj {spec = (_, _, m),...}) = Tactic.Apply_Method m
   328   | g_tac  (PrfObj {tac = m, ...}) = m;
   329 fun g_result (PblObj {result = r, ...}) = r
   330   | g_result (PrfObj {result = r, ...}) = r;
   331 fun g_res (PblObj {result = (r, _) ,...}) = r
   332   | g_res (PrfObj {result = (r, _),...}) = r;
   333 fun g_res' (Nd (PblObj {result = (r, _), ...}, _)) = r
   334   | g_res' (Nd (PrfObj {result = (r, _),...}, _)) = r
   335   | g_res' _ = raise PTREE "g_res': uncovered fun def.";
   336 fun g_ostate (PblObj {ostate = r, ...}) = r
   337   | g_ostate (PrfObj {ostate = r, ...}) = r;
   338 fun g_ostate' (Nd (PblObj {ostate = r, ...}, _)) = r
   339   | g_ostate' (Nd (PrfObj {ostate = r, ...}, _)) = r
   340   | g_ostate' _ = raise PTREE "g_ostate': uncovered fun def.";
   341 
   342 (* get the formula preceeding the current position in a calculation *)
   343 fun get_curr_formula (pt, (p, p_)) = 
   344 	case p_ of
   345 	  Frm => get_obj g_form pt p
   346 	| Res => (fst o (get_obj g_result pt)) p
   347 	| _ => #3 (get_obj g_origin pt p); (* the headline*)
   348   
   349 (* in CalcTree/Subproblem an 'just_created_' model is created;
   350    this is filled to 'untouched' by Model/Refine_Problem   *)
   351 fun just_created_ (PblObj {meth, probl, spec, ...}) =
   352     null meth andalso null probl andalso spec = References_Def.empty
   353   | just_created_ _ = raise PTREE "g_ostate': uncovered fun def.";
   354 val e_origin = ([], References_Def.empty, TermC.empty);
   355 
   356 fun just_created (pt, (p, _)) =
   357     let val ppobj = get_obj I pt p
   358     in is_pblobj ppobj andalso just_created_ ppobj end;
   359 
   360 (* does the pos in the ctree exist ? *)
   361 fun existpt pos pt = can (get_obj I pt) pos;
   362 (* does the pos' in the ctree exist, ie. extra check for result in the node *)
   363 fun existpt' (p, p_) pt = 
   364   if can (get_obj I pt) p 
   365   then case p_ of 
   366 	  Res => get_obj g_ostate pt p = Complete
   367 	| _ => true
   368   else false;
   369 
   370 (* is this position appropriate for calculating intermediate steps? *)
   371 fun is_interpos (_, Res) = true
   372   | is_interpos _ = false;
   373 
   374 (* get the children of a node in ctree *)
   375 fun children (Nd (PblObj _, cn)) = cn
   376   | children (Nd (PrfObj _, cn)) = cn
   377   | children _ = raise ERROR "children: uncovered fun def.";
   378 
   379 (*/--------------- duplicates in ctree-navi.sml: required also here below ---------------\*)
   380 fun lev_up [] = raise PTREE "lev_up []"
   381   | lev_up p = (drop_last p):pos;
   382 (* find the position of the next parent which is a PblObj in ctree *)
   383 \<^isac_test>\<open>
   384 fun par_pblobj _ [] = []
   385   | par_pblobj pt p =
   386     let
   387       fun par _ [] = []
   388         | par pt p =
   389           if is_pblobj (get_obj I pt p) 
   390           then p
   391           else par pt (lev_up p)
   392     in par pt (lev_up p) end;
   393 \<close>
   394 (*\--------------- duplicates in ctree-navi.sml: required also here below ---------------/*)
   395 
   396 (* insert obj b into ctree at pos, ev.overwriting this pos *)
   397 fun insert_pt b EmptyPtree [] = Nd (b, [])
   398   | insert_pt _ EmptyPtree _ = raise PTREE "insert_pt b Empty _"
   399   | insert_pt b _ [] = Nd (b, [])
   400   | insert_pt b (Nd (b', bs)) (p :: []) = Nd (b', repl_app bs p (Nd (b, []))) 
   401   | insert_pt b (Nd (b', bs)) (p :: ps) = Nd (b', repl_app bs p (insert_pt b (nth p bs) ps));
   402 
   403 (* insert children to a node without children. compare: fun insert_pt *)
   404 fun ins_chn _  EmptyPtree _ = raise PTREE "ins_chn: EmptyPtree"
   405   | ins_chn _ (Nd _) [] = raise PTREE "ins_chn: pos = []"
   406   | ins_chn ns (Nd (b, bs)) (p :: []) =
   407     if p > length bs
   408     then raise PTREE "ins_chn: pos not existent"
   409     else
   410       let
   411         val (b', bs') = case nth p bs of
   412           Nd (b', bs') => (b', bs')
   413         | _ => raise ERROR "ins_chn: uncovered case nth"
   414       in
   415         if null bs'
   416         then Nd (b, repl_app bs p (Nd (b', ns)))
   417         else raise PTREE "ins_chn: pos mustNOT be overwritten"
   418       end
   419   | ins_chn ns (Nd (b, bs)) (p::ps) = Nd (b, repl_app bs p (ins_chn ns (nth p bs) ps));
   420 
   421 (* apply f to obj at pos, f: ppobj -> ppobj *)
   422 fun appl_to_node f (Nd (b, bs)) = Nd (f b, bs)
   423   | appl_to_node _ _ = raise ERROR "appl_to_node: uncovered fun def.";
   424 fun appl_obj _ EmptyPtree [] = EmptyPtree
   425   | appl_obj _ EmptyPtree _ = raise PTREE "appl_obj f Empty _"
   426   | appl_obj f (Nd (b, bs)) [] = Nd (f b, bs)
   427   | appl_obj f (Nd (b, bs)) (p :: []) = Nd (b, repl_app bs p (((appl_to_node f) o (nth p)) bs))
   428   | appl_obj f (Nd (b, bs)) (p :: ps) = Nd (b, repl_app bs p (appl_obj f (nth p bs) (ps:pos)));
   429 
   430 datatype ptform = Form of term | ModSpec of Specification_Def.T;
   431 
   432 \<^isac_test>\<open>
   433 fun test_trans (PrfObj {branch, ...}) = true andalso branch = TransitiveB
   434   | test_trans (PblObj {branch, ...}) = true andalso branch = TransitiveB;
   435 \<close>
   436 
   437 fun is_pblobj' pt p =
   438     let val ppobj = get_obj I pt p
   439     in is_pblobj ppobj end;
   440 
   441 fun del_res (PblObj {fmz, origin, spec, probl, meth, ctxt, loc = (l1, _), branch, ...}) =
   442     PblObj {fmz = fmz, origin = origin, spec = spec, probl = probl, meth = meth,
   443 	    ctxt = ctxt, loc= (l1, NONE), branch = branch,
   444 	    result = (TermC.empty, []), ostate = Incomplete}
   445   | del_res (PrfObj {form, tac, loc= (l1, _), branch, ...}) =
   446     PrfObj {form = form, tac = tac, loc = (l1, NONE), branch = branch, 
   447 	    result = (TermC.empty, []), ostate = Incomplete};
   448 
   449 
   450 fun get_loc EmptyPtree _ = (Istate_Def.empty, ContextC.empty)
   451   | get_loc pt (p, Res) =
   452     (case get_obj g_loc pt p of
   453       (SOME ist_ctxt, NONE) => ist_ctxt
   454     | (NONE         , NONE) => (Istate_Def.empty, ContextC.empty)
   455     | (_            , SOME ist_ctxt) => ist_ctxt)
   456   | get_loc pt (p, _) =
   457     (case get_obj g_loc pt p of
   458       (NONE         , SOME ist_ctxt) => ist_ctxt (* 020813 too liberal? *)
   459     | (NONE         , NONE) => (Istate_Def.empty, ContextC.empty)
   460     | (SOME ist_ctxt, _) => ist_ctxt);
   461 fun get_istate_LI pt p = get_loc pt p |> #1;
   462 fun get_ctxt_LI pt p = get_loc pt p |> #2;
   463 fun get_ctxt pt (pos as (p, p_)) =
   464   if member op = [Frm, Res] p_
   465   then get_loc pt pos |> #2 (*for program interpretation rely on fun get_loc*)
   466   else             (*p = Pbl: for specify phase take ctxt from PblObj       *)
   467     if (p |> get_obj g_origin pt |> LibraryC.fst3) = [] (*CAS-command ?     *)
   468     then (ThyC.get_theory "Isac_Knowledge"(*CAS-command unknown*)) |> Defs.global_context |> fst
   469     else get_obj g_ctxt pt p
   470 
   471 fun get_assumptions pt p = get_ctxt pt p |> ContextC.get_assumptions;
   472 
   473 fun get_somespec' (dI, pI, mI) (dI', pI', mI') =
   474   let
   475     val domID = if dI = ThyC.id_empty then dI' else dI
   476   	val pblID = if pI = Problem.id_empty then pI' else pI
   477   	val metID = if mI = MethodC.id_empty then mI' else mI
   478   in (domID, pblID, metID) end;
   479 
   480 (**.development for extracting an 'interval' from ptree.**)
   481 
   482 \<^isac_test>\<open>
   483 (*WN0510 version stopped in favour of get_interval with !!!move_dn, getFormulaeFromTo
   484   actually used (inefficient) version with move_dn: see modspec.sml*)
   485 local
   486 
   487 fun hdp [] = 1     | hdp [0] = 1     | hdp x = hd x;(*start with first*)
   488 fun hdq	[] = 99999 | hdq [0] = 99999 | hdq x = hd x;(*take until last*)
   489 fun tlp [] = [0]     | tlp [_] = [0]     | tlp x = tl x;
   490 fun tlq [] = [99999] | tlq [_] = [99999] | tlq x = tl x;
   491 
   492 fun getnd i (b,p) q (Nd (_, nds)) =
   493     (if  i <= 0 then [[b]] else []) @
   494     (getnds (i-1) true (b@[hdp p], tlp p) (tlq q)
   495 	   (take_fromto (hdp p) (hdq q) nds))
   496   | getnd _ _ _ _ = raise ERROR "getnd: uncovered case in fun.def."
   497 and getnds _ _ _ _ [] = []                         (*no children*)
   498   | getnds i _ (b,p) q [nd] = (getnd i (b,p) q nd) (*l+r-margin*)
   499 
   500   | getnds i true (b,p) q [n1, n2] =               (*l-margin,  r-margin*)
   501     (getnd i      (       b, p ) [99999] n1) @
   502     (getnd ~99999 (lev_on b,[0]) q       n2)
   503 
   504   | getnds i _    (b, _) q [n1, n2] =               (*intern,  r-margin*)
   505     (getnd i      (       b,[0]) [99999] n1) @
   506     (getnd ~99999 (lev_on b,[0]) q       n2)
   507 
   508   | getnds i true (b,p) q (nd::(nds as _::_)) =    (*l-margin, intern*)
   509     (getnd i             (       b, p ) [99999] nd) @
   510     (getnds ~99999 false (lev_on b,[0]) q nds)
   511 
   512   | getnds i _ (b, _) q (nd::(nds as _::_)) =       (*intern, ...*)
   513     (getnd i             (       b,[0]) [99999] nd) @
   514     (getnds ~99999 false (lev_on b,[0]) q nds); 
   515 in
   516 (*get an 'interval from to' from a ptree as 'intervals f t' of respective nodes
   517   where 'from' are pos, i.e. a key as int list, 'f' an int (to,t analoguous)
   518 (1) the 'f' are given 
   519 (1a) by 'from' if 'f' = the respective element of 'from' (left margin)
   520 (1b) -inifinity, if 'f' > the respective element of 'from' (internal node)
   521 (2) the 't' ar given
   522 (2a) by 'to' if 't' = the respective element of 'to' (right margin)
   523 (2b) inifinity, if 't' < the respective element of 'to (internal node)'
   524 the 'f' and 't' are set by hdp,... *)
   525 fun get_trace pt p q =
   526     (flat o (getnds ((length p) -1) true ([hdp p], tlp p) (tlq q))) 
   527 	(take_fromto (hdp p) (hdq q) (children pt));
   528 end;
   529 
   530 (*extract a formula or model from ctree for itms2itemppc or model2xml*)
   531 fun preconds2str bts = 
   532   (strs2str o (map (linefeed o pair2str o
   533 	  (apsnd UnparseC.term) o 
   534 	  (apfst bool2str)))) bts;
   535 
   536 fun ocalhd2str (b, p, hdf, itms, prec, spec) =
   537     "(" ^ bool2str b ^ ", " ^ pos_2str p ^ ", " ^ UnparseC.term hdf ^
   538     ", " ^ "\<forall>itms2str itms\<forall>" (*Model_Def.itms2str_ (ThyC.id_to_ctxt "Isac_Knowledge") itms*) ^
   539     ", " ^ preconds2str prec ^ ", \n" ^ References_Def.to_string spec ^ " )";
   540 \<close>
   541 
   542 
   543 fun is_pblnd (Nd (ppobj, _)) = is_pblobj ppobj
   544   | is_pblnd _ = raise ERROR "is_pblnd: uncovered fun def.";
   545 
   546 
   547 (* determine the previous pos' on the same level
   548    WN0502 made for interSteps;  _only_ works for branch TransitiveB WN120517 compare lev_back *)
   549 fun lev_pred' _ ([], Res) = ([], Pbl)
   550   | lev_pred' pt (p, Res) =
   551     let val (p', last) = split_last p
   552     in
   553       if last = 1 
   554       then if (is_pblobj o (get_obj I pt)) p then (p, Pbl) else (p, Frm)
   555       else if get_obj g_res pt (p' @ [last - 1]) = get_obj g_form pt p
   556         then (p' @ [last - 1], Res)                                            (* TransitiveB *)
   557         else if (is_pblobj o (get_obj I pt)) p then (p,Pbl) else (p, Frm)
   558     end
   559   | lev_pred' _ _ = raise ERROR "";
   560 
   561 
   562 (**.insert into ctree and cut branches accordingly.**)
   563   
   564 \<^isac_test>\<open>
   565 (* get all positions of certain intervals on the ctree.
   566    old VERSION without move_dn; kept for occasional redesign
   567    get all pos's to be cut in a ctree
   568    below a pos or from a ctree list after i-th element (NO level_up) *)
   569 fun get_allpos' (_, _) EmptyPtree = []
   570   | get_allpos' (p, 1) (Nd (b, bs)) =                                        (* p is pos of Nd *)
   571     if g_ostate b = Incomplete 
   572     then (p, Frm) :: (get_allpos's (p, 1) bs)
   573     else (p, Frm) :: (get_allpos's (p, 1) bs) @ [(p, Res)]
   574   | get_allpos' (p, _) (Nd (b, bs)) =                                        (* p is pos of Nd *)
   575     if length bs > 0 orelse is_pblobj b
   576     then if g_ostate b = Incomplete 
   577       then [(p,Frm)] @ (get_allpos's (p, 1) bs)
   578       else [(p,Frm)] @ (get_allpos's (p, 1) bs) @ [(p, Res)]
   579     else if g_ostate b = Incomplete then [] else [(p, Res)]
   580 and get_allpos's _ [] = []
   581   | get_allpos's (p, i) (pt :: pts) =                                 (* p is pos of parent-Nd *)
   582     (get_allpos' (p @ [i], i) pt) @ (get_allpos's (p, i + 1) pts);
   583 
   584 (*WN050106 like cut_level, but deletes exactly 1 node *)
   585 fun cut_level__  _ _ EmptyPtree _ =raise PTREE "cut_level__ Empty _"       (* for tests ONLY *)
   586   | cut_level__  _ _ (Nd ( _, _)) ([], _) = raise PTREE "cut_level__ _ []"
   587   | cut_level__ cuts P (Nd (b, bs)) (p :: [], p_) = 
   588     if test_trans b 
   589     then
   590       (Nd (b, drop_nth [] (p:Pos.posel, bs)),
   591         cuts @ (if p_ = Frm then [(P @ [p], Res)] else []) @
   592         (get_allpos's (P, p + 1) (drop_nth [] (p, bs))))
   593     else (Nd (b, bs), cuts)
   594   | cut_level__ cuts P (Nd (b, bs)) ((p :: ps), p_) =
   595     let
   596       val (bs', cuts') = cut_level__ cuts P (nth p bs) (ps, p_)
   597     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
   598 
   599 fun cut_level _ _ EmptyPtree _ = raise PTREE "cut_level EmptyPtree _"
   600   | cut_level _ _ (Nd ( _, _)) ([],_) = raise PTREE "cut_level _ []"
   601   | cut_level cuts P (Nd (b, bs)) (p :: [], p_) = 
   602     if test_trans b 
   603     then
   604       (Nd (b, take (p:Pos.posel, bs)),
   605         cuts @ 
   606         (if p_ = Frm andalso (*#*) g_ostate b = Complete then [(P@[p],Res)] else ([]:pos' list)) @
   607         (get_allpos's (P, p+1) (takerest (p, bs))))
   608     else (Nd (b, bs), cuts)
   609   | cut_level cuts P (Nd (b, bs)) ((p :: ps), p_) =
   610     let
   611       val (bs', cuts') = cut_level cuts P (nth p bs) (ps, p_)
   612     in (Nd (b, repl_app bs p bs'), cuts @ cuts') end;
   613 
   614 
   615 (*old version before WN050219, overwritten below*)
   616 fun cut_tree _ ([], _) = raise PTREE "cut_tree _ ([],_)"
   617   | cut_tree pt (pos as ([_], _)) =
   618     let
   619       val (pt', cuts) = cut_level [] [] pt pos
   620     in
   621       (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete  then [] else [([], Res)]))
   622     end
   623   | cut_tree pt (p,p_) =
   624     let	
   625       fun cutfn pt cuts (p, p_) = 
   626 	      let
   627 	        val (pt', cuts') = cut_level [] (lev_up p) pt (p,p_)
   628 	      in
   629 	        if length cuts' > 0 andalso length p > 1
   630 	        then cutfn pt' (cuts @ cuts') (lev_up p, Frm(*-->(p,Res)*))
   631 	        else (pt', cuts @ cuts')
   632 	      end
   633 	    val (pt', cuts) = cutfn pt [] (p, p_)
   634     in
   635       (pt', cuts @ (if get_obj g_ostate pt [] = Incomplete then [] else [([], Res)]))
   636     end;
   637 \<close>
   638 
   639 local
   640 fun move_dn _ (Nd (_, ns)) ([],p_) =                                            (* root problem *)
   641     (case p_ of 
   642 	     Res => raise PTREE "move_dn: end of calculation"
   643 	   | _ =>
   644 	     if null ns                                                     (* go down from Pbl + Met *)
   645 	     then raise PTREE "move_dn: solve problem not started"
   646 	     else ([1], Frm))
   647   | move_dn P  (Nd (_, ns)) (p :: (ps as (_ :: _)), p_) =              (* iterate to end of pos *)
   648     if p > length ns
   649     then raise PTREE "move_dn: pos not existent 2"
   650     else move_dn (P @ [p]) (nth p ns) (ps, p_)
   651   | move_dn P (Nd (c, ns)) ([p], p_) =                            (* act on last element of pos *)
   652     if p > length ns
   653     then raise PTREE "move_dn: pos not existent 3"
   654     else
   655       (case p_ of 
   656 	      Res => 
   657 	      if p = length ns                               (* last Res on this level: go a level up *)
   658 	      then if g_ostate c = Complete
   659 	        then (P, Res)
   660 	        else raise PTREE (ints2str' P ^ " not complete 1")
   661 	     else                        (* go to the next Nd on this level, or down into the next Nd *)
   662 		     if is_pblnd (nth (p + 1) ns) then (P@[p + 1], Pbl)
   663 		     else  if g_res' (nth p ns) = g_form' (nth (p + 1) ns)
   664 		       then if (null o children o (nth (p + 1))) ns
   665 			       then                                                   (* take the Res if Complete *) 
   666 			         if g_ostate' (nth (p + 1) ns) = Complete 
   667 			         then (P@[p + 1], Res)
   668 			         else raise PTREE (ints2str' (P@[p + 1]) ^ " not complete 2")
   669 			       else (P@[p + 1, 1], Frm)                           (* go down into the next PrfObj *)
   670 		       else (P@[p + 1], Frm)                           (* take Frm: exists if the Nd exists *)
   671 	   | Frm => (*go down or to the Res of this Nd*)
   672 	     if (null o children o (nth p)) ns
   673 	     then if g_ostate' (nth p ns) = Complete then (P @ [p], Res)
   674 		     else raise PTREE (ints2str' (P @ [p])^" not complete 3")
   675 	     else (P @ [p, 1], Frm)
   676 	   | _ =>                                                                    (* is Pbl or Met *)
   677 	     if (null o children o (nth p)) ns
   678 	     then raise PTREE "move_dn:solve subproblem not startd"
   679 	     else (P @ [p, 1], 
   680 		   if (is_pblnd o hd o children o (nth p)) ns
   681 		   then Pbl else Frm))
   682   | move_dn _ _ _ = raise ERROR "";
   683 in
   684 (* get all positions in a ctree until ([],Res) or ostate=Incomplete
   685 val get_allp = fn : 
   686   pos' list -> : accumulated, start with []
   687   pos ->       : the offset for subtrees wrt the root
   688   ctree ->     : (sub)tree
   689   pos'         : initialization (the last pos' before ...)
   690   -> pos' list : of positions in this (sub) tree (relative to the root)
   691 *)
   692 fun get_allp cuts (P, pos) pt =
   693   (let
   694     val nxt = move_dn [] pt pos (*exn if Incomplete reached*)
   695   in
   696     if nxt <> ([], Res) 
   697     then get_allp (cuts @ [nxt]) (P, nxt) pt
   698     else map (apfst (curry op @ P)) (cuts @ [nxt])
   699   end)
   700   handle PTREE _ => (map (apfst (curry op@ P)) cuts);
   701 end
   702 
   703 (* the pts are assumed to be on the same level *)
   704 fun get_allps cuts _ [] = cuts
   705   | get_allps cuts P (pt :: pts) =
   706     let
   707       val below = get_allp [] (P, ([], Frm)) pt
   708       val levfrm = 
   709 	      if is_pblnd pt 
   710 	      then (P, Pbl) :: below
   711 	      else if last_elem P = 1 
   712 	        then (P, Frm) :: below
   713 	        else (*Trans*) below
   714 	    val levres = levfrm @ (if null below then [(P, Res)] else [])
   715     in
   716       get_allps (cuts @ levres) (lev_on P) pts
   717     end;
   718 
   719 (** these 2 funs decide on how far cut_tree goes **)
   720 (* shall the nodes _after_ the pos to be inserted at be deleted?
   721    shall cutting be continued on the higher level(s)? the Nd regarded will NOT be changed *)
   722 fun test_trans (PrfObj {branch, ...}) = (branch = TransitiveB orelse branch = NoBranch)
   723   | test_trans (PblObj {branch, ...}) = (branch = TransitiveB orelse branch = NoBranch);
   724     
   725 (* cut_bottom new sml603..608
   726 cut the level at the bottom of the pos (used by cappend_...)
   727 and handle the parent in order to avoid extra case for root
   728 fn: ctree ->         : the _whole_ ctree for cut_levup
   729     pos * Pos.posel ->   : the pos after split_last
   730     ctree ->         : the parent of the Nd to be cut
   731 return
   732     (ctree *         : the updated ctree
   733      pos' list) *    : the pos's cut
   734      bool            : cutting shall be continued on the higher level(s)
   735 *)
   736 fun cut_bottom _ (pt' as Nd (b, [])) = ((pt', []), test_trans b)
   737   | cut_bottom (P, p) (Nd (b, bs)) =
   738     let (*divide level into 3 parts...*)
   739     	val keep = take (p - 1, bs)
   740     	val pt' = case nth p bs of
   741     	  pt' as Nd _ => pt'
   742     	| _ => raise ERROR "cut_bottom: uncovered case nth p bs"
   743     	(*^^^^^_here_ will be 'insert_pt'ed by 'append_..'*)
   744     	val (tail, _) = (takerest (p, bs), if null (takerest (p, bs)) then 0 else p + 1)
   745     	val (children, cuts) = 
   746     	  if test_trans b
   747     	  then
   748     	   (keep, (if is_pblnd pt' then [(P @ [p], Pbl)] else [])
   749     	     @ (get_allp  [] (P @ [p], (P, Frm)) pt')
   750     	     @ (get_allps [] (P @ [p + 1]) tail))
   751     	  else (keep @ [(*'insert_pt'ed by 'append_..'*)] @ tail,
   752     		get_allp  [] (P @ [p], (P, Frm)) pt')
   753     	val (pt'', cuts) = 
   754     	  if test_trans b
   755     	  then (Nd (del_res b, children), cuts @ (if g_ostate b = Incomplete then [] else [(P, Res)]))
   756     	  else (Nd (b, children), cuts)
   757     in ((pt'', cuts), test_trans b) end
   758   | cut_bottom _ _ = raise ERROR "cut_bottom: uncovered fun def.";
   759 
   760 
   761 (* go all levels from the bottom of 'pos' up to the root, 
   762  on each level compose the children of a node and accumulate the cut Nds
   763 args
   764    pos' list ->      : for accumulation
   765    bool -> 	     : cutting shall be continued on the higher level(s)
   766    ctree -> 	     : the whole ctree for 'get_nd pt P' on each level
   767    ctree -> 	     : the Nd from the lower level for insertion at path
   768    pos * Pos.posel ->    : pos=path split for convenience
   769    ctree -> 	     : Nd the children of are under consideration on this call 
   770 returns		     :
   771    ctree * pos' list : the updated parent-Nd and the pos's of the Nds cut
   772 *)
   773 fun cut_levup (cuts:pos' list) clevup pt pt' (P:pos, p:Pos.posel) (Nd (b, bs)) =
   774     let (*divide level into 3 parts...*)
   775     	val keep = take (p - 1, bs)
   776     	(*val pt' comes as argument from below*)
   777     	val (tail, _) =
   778     	 (takerest (p, bs), if null (takerest (p, bs)) then 0 else p + 1)
   779     	val (children, cuts') = 
   780     	  if clevup
   781     	  then (keep @ [pt'], get_allps [] (P @ [p+1]) tail)
   782     	  else (keep @ [pt'] @ tail, [])
   783     	val clevup' = if clevup then test_trans b else false 
   784     	(*the first Nd with false stops cutting on all levels above*)
   785     	val (pt'', cuts') = 
   786     	  if clevup'
   787     	  then (Nd (del_res b, children), cuts' @ (if g_ostate b = Incomplete then [] else [(P, Res)]))
   788     	  else (Nd (b, children), cuts')
   789     in
   790       if null P
   791       then (pt'', cuts @ cuts')
   792       else
   793         let val (P, p) = split_last P
   794         in cut_levup (cuts @ cuts') clevup' pt pt'' (P, p) (get_nd pt P) end
   795     end
   796   | cut_levup _ _ _ _ _ _ = raise ERROR "cut_levup: uncovered fun def.";
   797  
   798 (* cut nodes after and below an inserted node in the ctree;
   799    the cuts range is limited by the predicate 'fun cutlevup' *)
   800 fun cut_tree pt (pos, _) =
   801   if not (existpt pos pt) 
   802   then (pt,  []) (*appending a formula never cuts anything*)
   803   else
   804     let
   805       val (P, p) = split_last pos
   806       val ((pt', cuts), clevup) = cut_bottom (P, p) (get_nd pt P)
   807          (* pt' is the updated parent of the Nd to cappend_..*)
   808     in
   809       if null P
   810       then (pt', cuts)
   811       else
   812         let val (P, p) = split_last P
   813         in cut_levup cuts clevup pt pt' (P, p) (get_nd pt P) end
   814 	  end;
   815 
   816 (* get the theory explicitly specified for the rootpbl;
   817    thus use this function _after_ finishing specification *)
   818 fun rootthy (Nd (PblObj {spec = (thyID, _, _), ...}, _)) = ThyC.get_theory thyID
   819   | rootthy _ = raise ERROR "rootthy: uncovered fun def.";
   820 
   821 (**)
   822 end;
   823 (**)