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