src/Tools/isac/calcelems.sml
author Walther Neuper <neuper@ist.tugraz.at>
Thu, 24 Jul 2014 15:44:50 +0200
changeset 55479 b629d1296ec6
parent 55477 1c66008ca7fb
child 55480 1738bef7d5d3
permissions -rw-r--r--
removed the only occurrence of (ill-named) string_of_thm: finished
     1 (* elements of calculations.
     2    they are partially held in association lists as ref's for
     3    switching language levels (meta-string, object-values).
     4    in order to keep these ref's during re-evaluation of code,
     5    they are defined here at the beginning of the code.
     6    Author: Walther Neuper 2003
     7    (c) copyright due to lincense terms
     8 *)
     9 
    10 (*
    11 structure CalcElems =
    12 struct
    13 *)
    14 val linefeed = (curry op^) "\n";
    15 type authors = string list;
    16 
    17 type cterm' = string;
    18 val empty_cterm' = "empty_cterm'";
    19 
    20 type thmID = string;    (* identifier for a thm (the shortest possible identifier)       *)
    21 type thmDeriv = string; (* WN120524 deprecated
    22   thyID ^"."^ xxx ^"."^ thmID, see fun thmID_of_derivation_name 
    23   WN120524: dont use Thm.derivation_name, this is destroyed by num_str;
    24   Thm.get_name_hint survives num_str and seems perfectly reliable *)
    25 
    26 type thm' = thmID * cterm';(*WN060610 deprecated in favour of thm''*)
    27 type thm'' = thmID * term;
    28 type rls' = string;
    29 
    30 (*.a 'guh'='globally unique handle' is a string unique for each element
    31    of isac's KEStore and persistent over time
    32    (in particular under shifts within the respective hierarchy);
    33    specialty for thys:
    34    # guh NOT resistant agains shifts from one thy to another
    35    (which is the price for Isabelle's design: thy's overwrite ids of subthy's)
    36    # requirement for matchTheory: induce guh from tac + current thy
    37    (see 'fun thy_containing_thm', 'fun thy_containing_rls' etc.)
    38    TODO: introduce to pbl, met.*)
    39 type guh = string;
    40 val e_guh = "e_guh":guh;
    41 
    42 type xml = string;
    43 
    44 (* eval function calling sml code during rewriting.
    45 Unifying "type cal" and "type calc" would make Lucas-Interpretation more efficient,
    46   see "fun rule2stac": instead of 
    47     Calc: calID * eval_fn -> rule
    48   would be better
    49     Calc: prog_calcID * (calID * eval_fn)) -> rule*)
    50 type eval_fn = (string -> term -> theory -> (string * term) option);
    51 fun e_evalfn (_:'a) (_:term) (_:theory) = NONE:(string * term) option;
    52 (*. op in isa-term 'Const(op,_)' .*)
    53 type calID = string;
    54 
    55 (* *)
    56 type cal = (calID * eval_fn);
    57 (*. fun calculate_ fetches the evaluation-function via this list. *)
    58 type prog_calcID = string;
    59 type calc = (prog_calcID * cal);
    60 type calc_elem =
    61   prog_calcID *   (* a simple identifier used in programs *)
    62   (calID *        (* a long identifier used in Const *)
    63     eval_fn)      (* an ML function *)
    64 fun calc_eq ((pi1, (ci1, _)) : calc_elem, (pi2, (ci2, _)) : calc_elem) =
    65   if pi1 = pi2
    66   then if ci1 = ci2 then true else error ("calc_eq: " ^ ci1 ^ " <> " ^ ci2)
    67   else false
    68 
    69 
    70 type subs' = (cterm' * cterm') list; (*16.11.00 for FE-KE*)
    71 type subst = (term * term) list; (*here for ets2str*)
    72 val e_subst = []:(term * term) list;
    73 
    74 (*TODO.WN060610 make use of "type rew_ord" total*)
    75 type rew_ord' = string;
    76 val e_rew_ord' = "e_rew_ord" : rew_ord';
    77 type rew_ord_ = subst -> Term.term * Term.term -> bool;
    78 fun dummy_ord (_:subst) (_:term,_:term) = true;
    79 val e_rew_ord_ = dummy_ord;
    80 type rew_ord = rew_ord' * rew_ord_;
    81 val e_rew_ord = dummy_ord; (* TODO.WN071231 clarify identifiers..e_rew_ordX*)
    82 val e_rew_ordX = (e_rew_ord', e_rew_ord_) : rew_ord;
    83 
    84 (* error patterns and fill patterns *)
    85 type errpatID = string
    86 type errpat =
    87   errpatID    (* one identifier for a list of patterns                       
    88                  DESIGN ?TODO: errpatID list for hierarchy of errpats ?      *)
    89   * term list (* error patterns                                              *)
    90   * thm list  (* thms related to error patterns; note that respective lhs 
    91                  do not match (which reflects student's error).
    92                  fillpatterns are stored with these thms.                    *)
    93 
    94 (* for (at least) 2 kinds of access:
    95   (1) given an errpatID, find the respective fillpats (e.g. in fun find_fill_pats)
    96   (2) given a thm, find respective fillpats *)
    97 type fillpatID = string
    98 type fillpat =
    99   fillpatID   (* DESIGN ?TODO: give an order w.r.t difficulty ? *)
   100   * term      (* the pattern with fill-in gaps                  *)
   101   * errpatID; (* which the fillpat would be a help for          
   102                  DESIGN ?TODO: list for several patterns ?      *)
   103 
   104 datatype rule =
   105   Erule                (*.the empty rule                     .*)
   106 | Thm of (string * Basic_Thm.thm)(*.a theorem, ie (identifier, Thm.thm).*)
   107 | Calc of string *     (*.sml-code manipulating a (sub)term  .*)
   108 	  (string -> term -> theory -> (string * term) option)
   109 | Cal1 of string *     (*.sml-code applied only to whole term
   110                           or left/right-hand-side of eqality .*)
   111 	  (string -> term -> theory -> (string * term) option)
   112 | Rls_ of rls          (*.ie. rule sets may be nested.*)
   113 and scr =
   114     EmptyScr
   115   | Prog of term (* for met *)
   116   | Rfuns of     (* for Rrls, usage see rational.sml ----- reverse rewrite -----      *)
   117     {init_state : (* initialise for reverse rewriting by the Interpreter              *)
   118       term ->         (* for this the rrlsstate is initialised:                       *)
   119       term *          (* the current formula: goes locate_gen -> next_tac via istate  *)
   120       term *          (* the final formula                                            *)
   121       rule list       (* of reverse rewrite set (#1#)                                 *)
   122         list *        (*   may be serveral, eg. in norm_rational                      *)
   123       ( rule *        (* Thm (+ Thm generated from Calc) resulting in ...             *)
   124         (term *       (*   ... rewrite with ...                                       *)
   125         term list))   (*   ... assumptions                                            *)
   126       list,           (* derivation from given term to normalform
   127                          in reverse order with sym_thm;
   128                                                 (#1#) could be extracted from here #1 *)  
   129 	  normal_form:  (* the function which drives the Rrls ##############################*)
   130 	    term -> (term * term list) option,
   131 	  locate_rule:  (* checks a rule R for being a cancel-rule, and if it is,
   132                      then return the list of rules (+ the terms they are rewriting to)
   133                      which need to be applied before R should be applied.
   134                      precondition: the rule is applicable to the argument-term.       *)
   135 	    rule list list -> (* the reverse rule list                                      *)
   136 	    term ->         (* ... to which the rule shall be applied                       *)
   137 	    rule ->         (* ... to be applied to term                                    *)
   138 	    ( rule *        (* value: a rule rewriting to ...                               *)
   139 	      (term *       (*   ... the resulting term ...                                 *)
   140 	      term list))   (*   ... with the assumptions ( //#0)                           *)
   141 	    list,           (*   there may be several such rules; the list is empty,          
   142                            if the rule has nothing to do with e.g. cancelation        *)
   143 	  next_rule:    (* for a given term return the next rules to be done for cancelling *)
   144 	    rule list list->(* the reverse rule list                                        *)
   145 	    term ->         (* the term for which ...                                       *)
   146 	    rule option,    (* ... this rule is appropriate for cancellation;
   147 		                     there may be no such rule (if the term is eg.canceled already*)
   148 	  attach_form:  (* checks an input term TI, if it may belong to e.g. a current 
   149                      cancellation, by trying to derive it from the given term TG.     
   150                      NOT IMPLEMENTED                                                 *)
   151 	    rule list list->(**)
   152 	    term ->         (* TG, the last one agreed upon by user + math-eng              *)
   153 	    term ->         (* TI, the next one input by the user                           *)
   154 	    ( rule *        (* the rule to be applied in order to reach TI                  *) 
   155 	      (term *       (* ... obtained by applying the rule ...                        *)
   156 	      term list))   (* ... and the respective assumptions                           *) 
   157 	    list}           (* there may be several such rules; the list is empty, if the 
   158                          users term does not belong to e.g. a cancellation of the term 
   159                          last agreed upon.                                            *)
   160 and rls =
   161     Erls                          (*for init e_rls*)
   162 
   163   | Rls of (*a confluent and terminating ruleset, in general         *)
   164     {id : string,          (*for trace_rewrite:=true                 *)
   165      preconds : term list, (*unused WN020820                         *)
   166      (*WN060616 for efficiency...
   167       bdvs    : false,       (*set in prep_rls' for get_bdvs *)*)
   168      rew_ord  : rew_ord,   (*for rules*)
   169      erls     : rls,       (*for the conditions in rules             *)
   170      srls     : rls,       (*for evaluation of list_fns in script    *)
   171      calc     : calc list, (*for Calculate in scr, set by prep_rls'   *)
   172      rules    : rule list,
   173      errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
   174      scr      : scr}       (*Prog term: generating intermed.steps  *)
   175   | Seq of (*a sequence of rules to be tried only once               *)
   176     {id : string,          (*for trace_rewrite:=true                 *)
   177      preconds : term list, (*unused 20.8.02                          *)
   178      (*WN060616 for efficiency...
   179       bdvs    : false,       (*set in prep_rls' for get_bdvs *)*)
   180      rew_ord  : rew_ord,   (*for rules                               *)
   181      erls     : rls,       (*for the conditions in rules             *)
   182      srls     : rls,       (*for evaluation of list_fns in script    *)
   183      calc     : calc list, (*for Calculate in scr, set by prep_rls'   *)
   184      rules    : rule list,
   185      errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
   186      scr      : scr}  (*Prog term  (how to restrict type ???)*)
   187 
   188   (*Rrls call SML-code and simulate an rls
   189     difference: there is always _ONE_ redex rewritten in 1 call,
   190     thus wrap Rrls by: Rls (Rls_ ...)*)
   191   | Rrls of (* SML-functions within rewriting; step-wise execution provided;   
   192                Rrls simulate an rls
   193                difference: there is always _ONE_ redex rewritten in 1 call,
   194                thus wrap Rrls by: Rls (Rls_ ...)                              *)
   195     {id : string,          (* for trace_rewrite := true                       *)
   196      prepat  : (term list *(* preconds, eval with subst from pattern;
   197                               if [@{term True}], match decides alone          *)
   198 		            term )     (* pattern matched with current (sub)term          *)
   199 		   list,               (* meta-conjunction is or                          *)
   200      rew_ord  : rew_ord,   (* for rules                                       *)
   201      erls     : rls,       (* for the conditions in rules and preconds        *)
   202      calc     : calc list, (* for Calculate in scr, set automatic.in prep_rls' *)
   203      errpatts : errpatID list,(*dialog-authoring in Build_Thydata.thy*)
   204      scr      : scr};      (* Rfuns {...}  (how to restrict type ???)         *)
   205 
   206 (*ad thm':
   207    there are two kinds of theorems ...
   208    (1) known by isabelle
   209    (2) not known, eg. calc_thm, instantiated rls
   210        the latter have a thmid "#..."
   211    and thus outside isa we ALWAYS transport both (thmid,string_of_thmI)
   212    and have a special assoc_thm / assoc_rls in this interface      *)
   213 type theory' = string; (* = domID ^".thy" WN.101011 ABOLISH !*)
   214 type domID = string;   (* domID ^".thy" = theory' WN.101011 replace by thyID*)
   215 type thyID = string;    (*WN.3.11.03 TODO: replace domID with thyID*)
   216      
   217 fun term_to_string' ctxt t =
   218   let
   219     val ctxt' = Config.put show_markup false ctxt
   220   in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
   221 fun term_to_string'' (thyID : thyID) t =
   222   let
   223     val ctxt' = Config.put show_markup false (Proof_Context.init_global (Thy_Info.get_theory thyID))
   224   in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
   225 fun term_to_string''' thy t =
   226   let
   227     val ctxt' = Config.put show_markup false (Proof_Context.init_global thy)
   228   in Print_Mode.setmp [] (Syntax.string_of_term ctxt') t end;
   229 
   230 fun thy2ctxt' thy' = Proof_Context.init_global (Thy_Info.get_theory thy');(*FIXXXME thy-ctxt*)
   231 fun thy2ctxt thy = Proof_Context.init_global thy;(*FIXXXME thy-ctxt*)
   232 
   233 fun term2str t = term_to_string' (thy2ctxt' "Isac") t;
   234 fun terms2strs ts = map term2str ts;
   235 (*terms2strs [t1,t2] = ["1 + 2", "abc"];*)
   236 val terms2str = strs2str o terms2strs;
   237 (*terms2str [t1,t2] = "[\"1 + 2\",\"abc\"]";*)
   238 val terms2str' = strs2str' o terms2strs;
   239 (*terms2str' [t1,t2] = "[1 + 2,abc]";*)
   240 
   241 fun termopt2str (SOME t) = "(SOME " ^ term2str t ^ ")"
   242   | termopt2str NONE = "NONE";
   243 
   244 fun type_to_string' ctxt t =
   245   let
   246     val ctxt' = Config.put show_markup false ctxt
   247   in Print_Mode.setmp [] (Syntax.string_of_typ ctxt') t end;
   248 fun type_to_string'' (thyID : thyID) t =
   249   let
   250     val ctxt' = Config.put show_markup false (Proof_Context.init_global (Thy_Info.get_theory thyID))
   251   in Print_Mode.setmp [] (Syntax.string_of_typ ctxt') t end;
   252 fun type_to_string''' thy t =
   253   let
   254     val ctxt' = Config.put show_markup false (Proof_Context.init_global thy)
   255   in Print_Mode.setmp [] (Syntax.string_of_typ ctxt') t end;
   256 
   257 fun type2str typ = type_to_string'' "Isac" typ; (*legacy*)
   258 val string_of_typ = type2str; (*legacy*)
   259 fun string_of_typ_thy thy typ = type_to_string'' thy typ; (*legacy*)
   260                  
   261 fun Isac _ = Proof_Context.theory_of (thy2ctxt' "Isac"); (*@{theory "Isac"}*)
   262                                      
   263 val e_rule = Thm ("refl", @{thm refl});
   264 fun id_of_thm (Thm (id, _)) = id
   265   | id_of_thm _ = error "error id_of_thm";
   266 fun thm_of_thm (Thm (_, thm)) = thm
   267   | thm_of_thm _ = error "error thm_of_thm";
   268 fun rep_thm_G' (Thm (thmid, thm)) = (thmid, thm);
   269 
   270 fun thmID_of_derivation_name dn = last_elem (space_explode "." dn);
   271 fun thyID_of_derivation_name dn = hd (space_explode "." dn);
   272 
   273 fun eq_thmI ((thmid1 : thmID, _ : thm), (thmid2 : thmID, _ : thm)) =
   274     (strip_thy thmid1) = (strip_thy thmid2);
   275 (*WN120201 weakened*)
   276 fun eq_thmI ((thmid1 : thmID, _ : thm), (thmid2 : thmID, _)) = thmid1 = thmid2;
   277 (*version typed weaker WN100910*)
   278 fun eq_thmI' ((thmid1, _), (thmid2, _)) =
   279     (thmID_of_derivation_name thmid1) = (thmID_of_derivation_name thmid2);
   280 
   281 fun thm'_of_thm thm =
   282   ((thmID_of_derivation_name o Thm.get_name_hint) thm, ""): thm'
   283 
   284 (*check for [.] as caused by "fun assoc_thm'"*)
   285 fun string_of_thmI thm =
   286     let val ct' = (de_quote o Thm.get_name_hint) thm
   287 	val (a, b) = split_nlast (5, Symbol.explode ct')
   288     in case b of
   289 	   [" ", " ","[", ".", "]"] => implode a
   290 	 | _ => ct'
   291     end;
   292 
   293 (*.id requested for all, Rls,Seq,Rrls.*)
   294 fun id_rls Erls = "e_rls" (*WN060714 quick and dirty: recursive defs!*)
   295   | id_rls (Rls {id,...}) = id
   296   | id_rls (Seq {id,...}) = id
   297   | id_rls (Rrls {id,...}) = id;
   298 val rls2str = id_rls;
   299 fun id_rule (Thm (id, _)) = id
   300   | id_rule (Calc (id, _)) = id
   301   | id_rule (Rls_ rls) = id_rls rls;
   302 
   303 fun get_rules (Rls {rules,...}) = rules
   304   | get_rules (Seq {rules,...}) = rules
   305   | get_rules (Rrls _) = [];
   306 
   307 fun rule2str Erule = "Erule"
   308   | rule2str (Thm (str, thm)) = "Thm (\""^str^"\","^(string_of_thmI thm)^")"
   309   | rule2str (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   310   | rule2str (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   311   | rule2str (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   312 fun rule2str' Erule = "Erule"
   313   | rule2str' (Thm (str, thm)) = "Thm (\""^str^"\",\"\")"
   314   | rule2str' (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   315   | rule2str' (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   316   | rule2str' (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   317 
   318 (*WN080102 compare eq_rule ?!?*)
   319 fun eqrule (Thm (id1,_), Thm (id2,_)) = id1 = id2
   320   | eqrule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   321   | eqrule (Cal1 (id1,_), Cal1 (id2,_)) = id1 = id2
   322   | eqrule (Rls_ _, Rls_ _) = false (*{id=id1}{id=id2} = id1 = id2 FIXXME*)
   323   | eqrule _ = false;
   324 
   325 type rrlsstate =  (* state for reverse rewriting, comments see type rule and scr | Rfuns *)
   326   (term * term * rule list list * (rule * (term * term list)) list);
   327 
   328 val e_type = Type("empty",[]);
   329 val a_type = TFree("'a",[]);
   330 val e_term = Const("empty",e_type);
   331 val a_term = Free("empty",a_type);
   332 val e_rrlsstate = (e_term,e_term,[[e_rule]],[(e_rule,(e_term,[]))]):rrlsstate;
   333 
   334 val e_term = Const("empty", Type("'a", []));
   335 val e_scr = Prog e_term;
   336 
   337 fun string_of_thy thy = Context.theory_name thy: theory';
   338 val theory2domID = string_of_thy;
   339 val theory2thyID = (get_thy o string_of_thy) : theory -> thyID;
   340 val theory2theory' = string_of_thy;
   341 val theory2str = string_of_thy; (*WN050903 ..most consistent naming*)
   342 val theory2str' = implode o (drop_last_n 4) o Symbol.explode o string_of_thy;
   343 (* fun theory'2theory = fun thyID2thy ... see fun assoc_thy (...Thy_Info.get_theory string);
   344 al it = "Isac" : string
   345 *)
   346 
   347 fun thyID2theory' (thyID:thyID) = thyID;
   348 (*
   349     let val ss = Symbol.explode thyID
   350 	val ext = implode (takelast (4, ss))
   351     in if ext = ".thy" then thyID : theory' (*disarm abuse of thyID*)
   352        else thyID ^ ".thy"
   353     end;
   354 *)
   355 (* thyID2theory' "Isac" (*ok*);
   356 val it = "Isac" : theory'
   357  > thyID2theory' "Isac" (*abuse, goes ok...*);
   358 val it = "Isac" : theory'
   359 *)
   360 
   361 fun theory'2thyID (theory':theory') = theory';
   362 (*
   363     let val ss = Symbol.explode theory'
   364 	val ext = implode (takelast (4, ss))
   365     in if ext = ".thy" then ((implode o (drop_last_n 4)) ss) : thyID
   366        else theory' (*disarm abuse of theory'*)
   367     end;
   368 *)
   369 (* theory'2thyID "Isac";
   370 val it = "Isac" : thyID
   371 > theory'2thyID "Isac";
   372 val it = "Isac" : thyID*)
   373 
   374 
   375 (*. WN0509 discussion:
   376 #############################################################################
   377 #   How to manage theorys in subproblems wrt. the requirement,              #
   378 #   that scripts should be re-usable ?                                      #
   379 #############################################################################
   380 
   381     eg. 'Script Solve_rat_equation' calls 'SubProblem (RatEq',..'
   382     which would not allow to 'solve (y'' = -M_b / EI, M_b)' by this script
   383     because Biegelinie.thy is subthy of RatEq.thy and thus Biegelinie.M_b
   384     is unknown in RatEq.thy and M_b cannot be parsed into the scripts guard
   385     (see match_ags).
   386 
   387     Preliminary solution:
   388     # the thy in 'SubProblem (thy', pbl, arglist)' is not taken automatically,
   389     # instead the 'maxthy (rootthy pt) thy' is taken for each subpbl
   390     # however, a thy specified by the user in the rootpbl may lead to
   391       errors in far-off subpbls (which are not yet reported properly !!!)
   392       and interactively specifiying thys in subpbl is not very relevant.
   393 
   394     Other solutions possible:
   395     # always parse and type-check with Thy_Info.get_theory "Isac"
   396       (rejected tue to the vague idea eg. to re-use equations for R in C etc.)
   397     # regard the subthy-relation in specifying thys of subpbls
   398     # specifically handle 'SubProblem (undefined, pbl, arglist)'
   399     # ???
   400 .*)
   401 (*WN0509 TODO "ProtoPure" ... would be more consistent
   402   with assoc_thy <--> theory2theory' +FIXME assoc_thy "e_domID" -> Script.thy*)
   403 val e_domID = "e_domID":domID;
   404 
   405 (*the key into the hierarchy ob theory elements*)
   406 type theID = string list;
   407 val e_theID = ["e_theID"];
   408 val theID2str = strs2str;
   409 (*theID eg. is ["IsacKnowledge", "Test", "Rulesets", "ac_plus_times"]*)
   410 fun theID2thyID (theID:theID) =
   411     if length theID >= 3 then (last_elem o (drop_last_n 2)) theID : thyID
   412     else error ("theID2thyID called with "^ theID2str theID);
   413 
   414 (*the key into the hierarchy ob problems*)
   415 type pblID = string list; (* domID::...*)
   416 val e_pblID = ["e_pblID"]:pblID;
   417 val pblID2str = strs2str;
   418 
   419 (*the key into the hierarchy ob methods*)
   420 type metID = string list;
   421 val e_metID = ["e_metID"]:metID;
   422 val metID2str = strs2str;
   423 
   424 type spec = 
   425      domID * (*WN.12.03: is replaced by thy from get_met ?FIXME? in:
   426 	      specify (Init_Proof..), nxt_specify_init_calc,
   427 	      assod (.SubProblem...), stac2tac (.SubProblem...)*)
   428      pblID * 
   429      metID;
   430 
   431 fun spec2str ((dom,pbl,met)(*:spec*)) = 
   432   "(" ^ (quote dom) ^ ", " ^ (strs2str pbl) ^ 
   433   ", " ^ (strs2str met) ^ ")";
   434 (*> spec2str empty_spec;
   435 val it = "(\"\", [], (\"\", \"\"))" : string *)
   436 val empty_spec = (e_domID,e_pblID,e_metID):spec;
   437 val e_spec = empty_spec;
   438 
   439 (*.association list with cas-commands, for generating a complete calc-head.*)
   440 type generate_fn = 
   441   (term list ->    (* the arguments of the cas-command, eg. (x+1=2, x) *)
   442     (term *        (* description of an element                        *)
   443       term list)   (* value of the element (always put into a list)    *)
   444   list)            (* of elements in the formalization                 *)
   445 type cas_elem = 
   446   (term *          (* cas-command, eg. 'solve'                         *)
   447     (spec *        (* theory, problem, method                          *)
   448     generate_fn))
   449 fun cas_eq ((t1, (_, _)) : cas_elem, (t2, (_, _)) : cas_elem) = t1 = t2
   450 
   451 (*either theID or pblID or metID*)
   452 type kestoreID = string list;
   453 val e_kestoreID = ["e_kestoreID"];
   454 val kestoreID2str = strs2str;
   455 
   456 (*for distinction of contexts WN130621: disambiguate with Isabelle's Context !*)
   457 datatype ketype = Exp_ | Thy_ | Pbl_ | Met_;
   458 fun ketype2str Exp_ = "Exp_"
   459   | ketype2str Thy_ = "Thy_"
   460   | ketype2str Pbl_ = "Pbl_"
   461   | ketype2str Met_ = "Met_";
   462 fun ketype2str' Exp_ = "Example"
   463   | ketype2str' Thy_ = "Theory"
   464   | ketype2str' Pbl_ = "Problem"
   465   | ketype2str' Met_ = "Method";
   466 
   467 (*rewrite orders, also stored in 'type met' and type 'and rls'
   468   The association list is required for 'rewrite.."rew_ord"..'
   469   WN0509 tests not well-organized: see smltest/Knowledge/termorder.sml*)
   470 val rew_ord' = Unsynchronized.ref
   471         ([]:(rew_ord' *        (*the key for the association list         *)
   472 	     (subst 	       (*the bound variables - they get high order*)
   473 	      -> (term * term) (*(t1, t2) to be compared                  *)
   474 	      -> bool))        (*if t1 <= t2 then true else false         *)
   475 		list);         (*association list                         *)
   476 
   477 rew_ord' := overwritel (!rew_ord', [("e_rew_ord", e_rew_ord),
   478 				    ("dummy_ord", dummy_ord)]);
   479 
   480 
   481 (* A tree for storing data defined in different theories 
   482   for access from the Interpreter and from dialogue authoring 
   483   using a string list as key.
   484   'a is for pbt | met | thydata; after WN030424 naming became inappropriate *)
   485 datatype 'a ptyp =
   486 	Ptyp of string * (* element of the key *)
   487 		'a list *      (* several pbts with different domIDs/thy TODO: select by subthy (isaref.p.69)
   488 			                presently only _ONE_ elem FOR ALL KINDS OF CONTENT pbt | met | thydata *)
   489 		('a ptyp) list;(* the children nodes *)
   490 
   491 (*.datatype for collecting thydata for hierarchy.*)
   492 (*WN060720 more consistent naming would be 'type thyelem' or 'thelem'*)
   493 (*WN0606 Htxt contains html which does not belong to the sml-kernel*)
   494 datatype thydata = Html of {guh: guh,
   495 			    coursedesign: authors,
   496 			    mathauthors: authors,
   497 			    html: string} (*html; for demos before database*)
   498 		 | Hthm of {guh: guh,
   499 			    coursedesign: authors,
   500 			    mathauthors: authors,
   501 			    fillpats: fillpat list,
   502 			    thm: term}
   503 		 | Hrls of {guh: guh,
   504 			    coursedesign: authors,
   505 			    mathauthors: authors,
   506 			    thy_rls: (thyID * rls)}
   507 		 | Hcal of {guh: guh,
   508 			    coursedesign: authors,
   509 			    mathauthors: authors,
   510 			    calc: calc}
   511 		 | Hord of {guh: guh,
   512 			    coursedesign: authors,
   513 			    mathauthors: authors,
   514 			    ord: (subst -> (term * term) -> bool)};
   515 val e_thydata = Html {guh="e_guh", coursedesign=[], mathauthors=[], html=""};
   516 fun the2str (Html {guh, coursedesign, mathauthors, html}) = guh : string
   517   | the2str (Hthm {guh, coursedesign, mathauthors, fillpats, thm}) = guh
   518   | the2str (Hrls {guh, coursedesign, mathauthors, thy_rls}) = guh
   519   | the2str (Hcal {guh, coursedesign, mathauthors, calc}) = guh
   520   | the2str (Hord {guh, coursedesign, mathauthors, ord}) = guh
   521 fun thes2str thes = map the2str thes |> list2str;
   522 
   523 type thehier = (thydata ptyp) list;
   524 (* required to determine sequence of main nodes of thehier in KEStore.thy *)
   525 fun part2guh ([str]:theID) =
   526     (case str of
   527 	"Isabelle" => "thy_isab_" ^ str ^ "-part" : guh
   528       | "IsacScripts" => "thy_scri_" ^ str ^ "-part"
   529       | "IsacKnowledge" => "thy_isac_" ^ str ^ "-part"
   530       | str => error ("thy2guh: called with '"^str^"'"))
   531   | part2guh theID = error ("part2guh called with theID = " ^ theID2str theID);
   532 
   533 fun thy2guh ([part, thyID] : theID) = (case part of
   534       "Isabelle" => "thy_isab_" ^ thyID : guh
   535     | "IsacScripts" => "thy_scri_" ^ thyID
   536     | "IsacKnowledge" => "thy_isac_" ^ thyID
   537     | str => error ("thy2guh: called with '" ^ str ^ "'"))
   538   | thy2guh theID = error ("thy2guh called with '" ^ strs2str' theID ^ "'");
   539 			
   540 fun thypart2guh ([part, thyID, thypart] : theID) = case part of
   541     "Isabelle" => "thy_isab_" ^ thyID ^ "-" ^ thypart : guh
   542   | "IsacScripts" => "thy_scri_" ^ thyID ^ "-" ^ thypart
   543   | "IsacKnowledge" => "thy_isac_" ^ thyID ^ "-" ^ thypart
   544   | str => error ("thypart2guh: called with '" ^ str ^ "'");
   545   
   546 (* convert the data got via contextToThy to a globally unique handle
   547    there is another way to get the guh out of the 'theID' in the hierarchy *)
   548 fun thm2guh (isa, thyID:thyID) (thmID:thmID) = case isa of
   549     "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID : guh
   550   | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
   551   | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
   552   | str => error ("thm2guh called with isa = '" ^ isa ^ "' for thm = " ^ thmID ^ "'");
   553 
   554 fun rls2guh (isa, thyID:thyID) (rls':rls') = case isa of
   555     "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-rls-" ^ rls' : guh
   556   | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-rls-" ^ rls'
   557   | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-rls-" ^ rls'
   558   | str => error ("rls2guh called with isa = '" ^ isa ^ "' for rls = '" ^ rls' ^ "'");
   559 			  
   560 fun cal2guh (isa, thyID:thyID) calID = case isa of
   561     "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-cal-" ^ calID : guh
   562   | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-cal-" ^ calID
   563   | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-cal-" ^ calID
   564   | str => error ("cal2guh called with isa = '" ^ isa ^ "' for cal = '" ^ calID ^ "'");
   565 			  
   566 fun ord2guh (isa, thyID:thyID) (rew_ord':rew_ord') = case isa of
   567     "Isabelle" => "thy_isab_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord' : guh
   568   | "IsacKnowledge" => "thy_isac_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord'
   569   | "IsacScripts" => "thy_scri_" ^ theory'2thyID thyID ^ "-ord-" ^ rew_ord'
   570   | str => error ("ord2guh called with isa = '" ^ isa ^ "' for ord = '" ^ rew_ord' ^ "'");
   571 
   572 (* not only for thydata, but also for thy's etc *)
   573 fun theID2guh (theID : theID) = case length theID of
   574     0 => error ("theID2guh: called with theID = " ^ strs2str' theID)
   575   | 1 => part2guh theID
   576   | 2 => thy2guh theID
   577   | 3 => thypart2guh theID
   578   | 4 => 
   579     let val [isa, thyID, typ, elemID] = theID
   580     in case typ of
   581         "Theorems" => thm2guh (isa, thyID) elemID
   582       | "Rulesets" => rls2guh (isa, thyID) elemID
   583       | "Calculations" => cal2guh (isa, thyID) elemID
   584       | "Orders" => ord2guh (isa, thyID) elemID
   585       | "Theorems" => thy2guh [isa, thyID]
   586       | str => error ("theID2guh: called with theID = " ^ strs2str' theID)
   587     end
   588   | n => error ("theID2guh called with theID = " ^ strs2str' theID);
   589 
   590 type path = string;
   591 type filename = string;
   592 
   593 (*val xxx = fn: a b => (a,b);   ??? fun-definition ???*)
   594 local
   595     fun ii (_:term) = e_rrlsstate;
   596     fun no (_:term) = SOME (e_term,[e_term]);
   597     fun lo (_:rule list list) (_:term) (_:rule) = [(e_rule,(e_term,[e_term]))];
   598     fun ne (_:rule list list) (_:term) = SOME e_rule;
   599     fun fo (_:rule list list) (_:term) (_:term) = [(e_rule,(e_term,[e_term]))];
   600 in
   601 val e_rfuns = Rfuns {init_state=ii,normal_form=no,locate_rule=lo,
   602 		     next_rule=ne,attach_form=fo};
   603 end;
   604 
   605 val e_rls =
   606   Rls {id = "e_rls", preconds = [], rew_ord = ("dummy_ord", dummy_ord), erls = Erls,
   607     srls = Erls, calc = [], rules = [], errpatts = [], scr = EmptyScr}: rls;
   608 val e_rrls =
   609   Rrls {id = "e_rrls", prepat = [], rew_ord = ("dummy_ord", dummy_ord), erls = Erls,
   610     calc = [], errpatts = [], scr=e_rfuns}:rls;
   611 
   612 fun rep_rls (Rls {id,preconds,rew_ord,erls,srls,calc,errpatts,rules,scr}) =
   613   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   614    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   615   | rep_rls (Seq {id,preconds,rew_ord,erls,srls,calc,errpatts,rules,scr}) =
   616   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   617    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   618   | rep_rls Erls = rep_rls e_rls
   619   | rep_rls (Rrls {id,...})  = rep_rls e_rls
   620     (*error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id)*);
   621 (*| rep_rls (Seq {id,...})  =
   622     error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id);
   623 --1.7.03*)
   624 fun rep_rrls (Rrls {id, calc, erls, prepat, rew_ord, errpatts,
   625 	      scr = Rfuns {attach_form, init_state, locate_rule, next_rule, normal_form}}) =
   626   {id=id, calc=calc, erls=erls, prepat=prepat,
   627      rew_ord=rew_ord, errpatts=errpatts, attach_form=attach_form, init_state=init_state,
   628      locate_rule=locate_rule, next_rule=next_rule, normal_form=normal_form}
   629   | rep_rrls (Rls {id,...}) =
   630     error ("rep_rrls doesn't take apart (normal) rule-sets: "^id)
   631   | rep_rrls (Seq {id,...}) =
   632     error ("rep_rrls doesn't take apart (normal) rule-sets: "^id);
   633 
   634 fun append_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   635 			rules =rs, errpatts=errpatts, scr=sc}) r =
   636     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   637 	 rules = rs @ r, errpatts=errpatts, scr=sc}:rls)
   638   | append_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   639 			rules =rs, errpatts=errpatts, scr=sc}) r =
   640     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   641 	 rules = rs @ r, errpatts=errpatts, scr=sc}:rls)
   642   | append_rls id (Rrls _) _ =
   643     error ("append_rls: not for reverse-rewrite-rule-set "^id);
   644 
   645 (*. are _atomic_ rules equal ?.*)
   646 (*WN080102 compare eqrule ?!?*)
   647 fun eq_rule (Thm (thm1,_), Thm (thm2,_)) = thm1 = thm2
   648   | eq_rule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   649   | eq_rule (Rls_ rls1, Rls_ rls2) = id_rls rls1 = id_rls rls2
   650   (*id_rls checks for Rls, Seq, Rrls*)
   651   | eq_rule _ = false;
   652 
   653 fun merge_ids rls1 rls2 =
   654   let 
   655     val id1 = (#id o rep_rls) rls1
   656     val id2 = (#id o rep_rls) rls2
   657   in
   658     if id1 = id2 then id1
   659     else "merged_" ^ id1 ^ "_" ^ id2
   660   end
   661 fun merge_rls _ Erls rls = rls
   662   | merge_rls _ rls Erls = rls
   663   | merge_rls _ (Rrls x) _ = Rrls x (* required for merging Theory_Data *)
   664   | merge_rls _ _ (Rrls x) = Rrls x
   665   | merge_rls id
   666 	  (Rls {preconds = pc1, rew_ord = ro1, erls = er1, srls = sr1, calc = ca1,
   667 	    rules = rs1, errpatts = eps1, scr = sc1, ...})
   668 	  (Rls {preconds = pc2, erls = er2, srls = sr2, calc = ca2,
   669 	    rules = rs2, errpatts = eps2, ...})
   670     =
   671 	  (Rls {id = id, rew_ord = ro1, scr = sc1,
   672 	    preconds = union (op =) pc1 pc2,	    
   673 	    erls = merge_rls (merge_ids er1 er2) er1 er2,
   674 	    srls = merge_rls (merge_ids sr1 sr2) sr1 sr2,
   675 	    calc = union calc_eq ca1 ca2,
   676 		  rules = union eq_rule rs1 rs2,
   677       errpatts = union (op =) eps1 eps2} : rls)
   678   | merge_rls id
   679 	  (Seq {preconds = pc1, rew_ord = ro1, erls = er1, srls = sr1, calc = ca1,
   680 	    rules = rs1, errpatts = eps1, scr = sc1, ...})
   681 	  (Seq {preconds = pc2, erls = er2, srls = sr2, calc = ca2,
   682 	    rules = rs2, errpatts = eps2, ...})
   683     =
   684 	  (Seq {id = id, rew_ord = ro1, scr = sc1,
   685 	    preconds = union (op =) pc1 pc2,	    
   686 	    erls = merge_rls (merge_ids er1 er2) er1 er2,
   687 	    srls = merge_rls (merge_ids sr1 sr2) sr1 sr2,
   688 	    calc = union calc_eq ca1 ca2,
   689 		  rules = union eq_rule rs1 rs2,
   690       errpatts = union (op =) eps1 eps2} : rls)
   691   | merge_rls id _ _ = error ("merge_rls: \"" ^ id ^ 
   692     "\"; not for reverse-rewrite-rule-sets and not for mixed Rls -- Seq");
   693 
   694 fun remove_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   695 		     rules=rs, errpatts=eps, scr=sc}) r =
   696     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   697 	   rules = gen_rems eq_rule (rs, r),
   698 	   errpatts = eps(*gen_rems op= (eps, TODO)*),
   699 	 scr=sc}:rls)
   700   | remove_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   701 		     rules =rs, errpatts=eps, scr=sc}) r =
   702     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   703 	   rules = gen_rems eq_rule (rs, r),
   704 	   errpatts = eps(*gen_rems op= (eps, TODO)*),
   705 	 scr=sc}:rls)
   706   | remove_rls id (Rrls _) _ = error
   707                    ("remove_rls: not for reverse-rewrite-rule-set "^id);
   708 
   709 (* datastructure for KEStore_Elems, intermediate for thehier *)
   710 type rlss_elem = 
   711   (rls' *     (* identifier unique within Isac *)
   712   (theory' *  (* just for assignment in thehier, not appropriate for parsing etc *)
   713     rls))     (* ((#id o rep_rls) rls) = rls'   by coding discipline *)
   714 fun rls_eq ((id1, (_, _)), (id2, (_, _))) = id1 = id2
   715 
   716 fun insert_merge_rls (re as (id, (thyID, r1)) : rlss_elem) ys = 
   717   case get_index (fn y => if curry rls_eq re y then SOME y else NONE) ys of
   718     NONE => re :: ys
   719   | SOME (i, (_, (_, r2))) => 
   720       let
   721         val r12 = merge_rls id r1 r2
   722       in list_update ys i (id, (thyID, r12)) end
   723 
   724 fun merge_rlss (s1, s2) = fold insert_merge_rls s1 s2;
   725 
   726 
   727 fun memrls r (Rls {rules,...}) = gen_mem eqrule (r, rules)
   728   | memrls r (Seq {rules,...}) = gen_mem eqrule (r, rules)
   729   | memrls r _ = error ("memrls: incomplete impl. r= "^(rule2str r));
   730 
   731 fun assoc' ([], key) = error ("ME_Isa: '"^key^"' not known")
   732   | assoc' ((keyi, xi) :: pairs, key) =
   733       if key = keyi then SOME xi else assoc' (pairs, key);
   734 
   735 fun assoc_thy (thy:theory') =
   736     if thy = "e_domID" then (Thy_Info.get_theory "Script") (*lower bound of Knowledge*)
   737     else (Thy_Info.get_theory thy)
   738          handle _ => error ("ME_Isa: thy '" ^ thy ^ "' not in system");
   739 
   740 (*.overwrite an element in an association list and pair it with a thyID
   741    in order to create the thy_hierarchy;
   742    overwrites existing rls' even if they are defined in a different thy;
   743    this is related to assoc_rls, TODO.WN060120: assoc_rew_ord, assoc_calc;.*)
   744 (*WN060120 ...these are NOT compatible to "fun assoc_thm'" in that
   745    they do NOT handle overlays by re-using an identifier in different thys;
   746    "thyID.rlsID" would be a good solution, if the "." would be possible
   747    in scripts...
   748    actually a hack to get alltogether run again with minimal effort*)
   749 fun insthy thy' (rls', rls) = (rls', (thy', rls));
   750 fun overwritelthy thy (al, bl:(rls' * rls) list) =
   751     let val bl' = map (insthy ((get_thy o theory2theory') thy)) bl
   752     in overwritel (al, bl') end;
   753 
   754 fun assoc_rew_ord ro = ((the o assoc') (!rew_ord',ro))
   755   handle _ => error ("ME_Isa: rew_ord '"^ro^"' not in system");
   756 (*get the string for stac from rule*)
   757 
   758 fun subst2str (s:subst) =
   759     (strs2str o
   760      (map (linefeed o pair2str o
   761 	   (apsnd term2str) o
   762 	   (apfst term2str)))) s;
   763 fun subst2str' (s:subst) =
   764     (strs2str' o
   765      (map (pair2str o
   766 	   (apsnd term2str) o
   767 	   (apfst term2str)))) s;
   768 (*> subst2str' [(str2term "bdv", str2term "x"),
   769 		(str2term "bdv_2", str2term "y")];
   770 val it = "[(bdv, x)]" : string
   771 *)
   772 val env2str = subst2str;
   773 
   774 
   775 (*recursive defs:*)
   776 fun scr2str (Prog s) = "Prog " ^ term2str s
   777   | scr2str (Rfuns _)  = "Rfuns";
   778 
   779 
   780 fun maxthy thy1 thy2 = if Theory.subthy (thy1, thy2) then thy2 else thy1;
   781 
   782 
   783 (*.trace internal steps of isac's rewriter*)
   784 val trace_rewrite = Unsynchronized.ref false;
   785 (*.depth of recursion in traces of the rewriter, if trace_rewrite:=true.*)
   786 val depth = Unsynchronized.ref 99999;
   787 (*.no of rewrites exceeding this int -> NO rewrite.*)
   788 (*WN060829 still unused...*)
   789 val lim_rewrite = Unsynchronized.ref 99999;
   790 (*.no of derivation-elements exceeding this int -> SOME derivation-elements.*)
   791 val lim_deriv = Unsynchronized.ref 100;
   792 (*.switch for checking guhs unique before storing a pbl or met;
   793    set true at startup (done at begin of ROOT.ML)
   794    set false for editing IsacKnowledge (done at end of ROOT.ML).*)
   795 val check_guhs_unique = Unsynchronized.ref true;
   796 
   797 
   798 datatype lrd = (*elements of a path (=loc_) into an Isabelle term*)
   799 	 L     (*go left at $*)
   800        | R     (*go right at $*)
   801        | D;     (*go down at Abs*)
   802 type loc_ = lrd list;
   803 fun ldr2str L = "L"
   804   | ldr2str R = "R"
   805   | ldr2str D = "D";
   806 fun loc_2str (k:loc_) = (strs2str' o (map ldr2str)) k;
   807 
   808 
   809 (* the pattern for an item of a problems model or a methods guard *)
   810 type pat =
   811   (string *     (* field               *)
   812 	  (term *     (* description         *)
   813 	     term))   (* id | arbitrary term *);
   814 fun pat2str ((field, (dsc, id)) : pat) = 
   815   pair2str (field, pair2str (term2str dsc, term2str id))
   816 fun pats2str pats = (strs2str o (map pat2str)) pats
   817 
   818 (* types for problems models (TODO rename to specification models) *)
   819 type pbt_ =
   820   (string *   (* field "#Given",..*)(*deprecated due to 'type pat'*)
   821     (term *   (* description      *)
   822       term)); (* id | struct-var  *)
   823 val e_pbt_ = ("#Undef", (e_term, e_term)) : pbt_
   824 type pbt = 
   825   {guh : guh,         (* unique within this isac-knowledge *)
   826   mathauthors : string list, (* copyright *)
   827   init : pblID,       (* to start refinement with *)
   828   thy  : theory,      (* which allows to compile that pbt
   829                       TODO: search generalized for subthy (ref.p.69*)
   830                       (*^^^ WN050912 NOT used during application of the problem,
   831                       because applied terms may be from 'subthy' as well as from super;
   832                       thus we take 'maxthy'; see match_ags !*)
   833   cas : term option,  (* 'CAS-command'*)
   834   prls : rls,         (* for preds in where_*)
   835   where_ : term list, (* where - predicates*)
   836   ppc : pat list,     (* this is the model-pattern; 
   837                        it contains "#Given","#Where","#Find","#Relate"-patterns
   838                        for constraints on identifiers see "fun cpy_nam" *)
   839   met : metID list}   (* methods solving the pbt*)
   840 
   841 val e_pbt = {guh = "pbl_empty", mathauthors = [], init = e_pblID, thy = Thy_Info.get_theory "Pure",
   842   cas = NONE, prls = Erls, where_ = [], ppc = [], met = []} : pbt
   843 fun pbt2str
   844         ({cas = cas', guh = guh', init = init', mathauthors = ma', met = met', ppc = ppc',
   845           prls = prls', thy = thy', where_ = w'} : pbt) =
   846       "{cas = " ^ (termopt2str cas') ^  ", guh = \"" ^ guh'  ^ "\", init = "
   847         ^ (strs2str init') ^ ", mathauthors = " ^ (strs2str ma' |> quote) ^ ", met = "
   848         ^ (strslist2strs met') ^ ", ppc = " ^ pats2str ppc' ^ ", prls = "
   849         ^ (rls2str prls' |> quote) ^ ", thy = {" ^ (theory2str thy') ^ "}, where_ = "
   850         ^ (terms2str w') ^ "}" |> linefeed;
   851 fun pbts2str pbts = map pbt2str pbts |> list2str;
   852 
   853 val e_Ptyp = Ptyp ("e_pblID",[e_pbt],[])
   854 type ptyps = (pbt ptyp) list
   855 
   856 fun coll_pblguhs pbls =
   857     let fun node coll (Ptyp (_,[n],ns)) =
   858 	    [(#guh : pbt -> guh) n] @ (nodes coll ns)
   859 	and nodes coll [] = coll
   860 	  | nodes coll (n::ns) = (node coll n) @ (nodes coll ns);
   861     in nodes [] pbls end;
   862 fun check_pblguh_unique (guh:guh) (pbls: (pbt ptyp) list) =
   863     if member op = (coll_pblguhs pbls) guh
   864     then error ("check_guh_unique failed with '"^guh^"';\n"^
   865 		      "use 'sort_pblguhs()' for a list of guhs;\n"^
   866 		      "consider setting 'check_guhs_unique := false'")
   867     else ();
   868 
   869 fun insrt _ pbt [k] [] = [Ptyp (k, [pbt], [])]
   870   | insrt d pbt [k] ((Ptyp (k', [p], ps)) :: pys) =
   871       ((*writeln ("### insert 1: ks = " ^ strs2str [k] ^ "    k'= " ^ k');*)
   872       if k = k'
   873       then ((Ptyp (k', [pbt], ps)) :: pys)
   874       else  ((Ptyp (k', [p], ps)) :: (insrt d pbt [k] pys))
   875       )			 
   876   | insrt d pbt (k::ks) ((Ptyp (k', [p], ps))::pys) =
   877       ((*writeln ("### insert 2: ks = "^(strs2str (k::ks))^"    k'= "^k');*)
   878       if k = k'
   879       then ((Ptyp (k', [p], insrt d pbt ks ps)) :: pys)
   880       else 
   881         if length pys = 0
   882         then error ("insert: not found " ^ (strs2str (d : pblID)))
   883         else ((Ptyp (k', [p], ps)) :: (insrt d pbt (k :: ks) pys))
   884       );
   885 
   886 fun update_ptyps ID _ _ [] =
   887     error ("update_ptyps: " ^ strs2str' ID ^ " does not exist")
   888   | update_ptyps ID [i] data ((py as Ptyp (key, _, pys)) :: pyss) =
   889     if i = key
   890     then 
   891       if length pys = 0
   892       then ((Ptyp (key, [data], [])) :: pyss)
   893       else error ("update_ptyps: " ^ strs2str' ID ^ " has descendants")
   894     else py :: update_ptyps ID [i] data pyss
   895   | update_ptyps ID (i :: is) data ((py as Ptyp (key, d, pys)) :: pyss) =
   896     if i = key
   897     then ((Ptyp (key,  d, update_ptyps ID is data pys)) :: pyss)
   898     else (py :: (update_ptyps ID (i :: is) data pyss))
   899 
   900 (* this function only works wrt. the way Isabelle evaluates Theories and is not a general merge
   901   function for trees / ptyps *)
   902 fun merge_ptyps ([], pt) = pt
   903   | merge_ptyps (pt, []) = pt
   904   | merge_ptyps ((x' as Ptyp (k, x, ps)) :: xs, (xs' as Ptyp (k', y, ps') :: ys)) =
   905       if k = k'
   906       then Ptyp (k, y, merge_ptyps (ps, ps')) :: merge_ptyps (xs, ys)
   907       else x' :: merge_ptyps (xs, xs');
   908 fun merge_ptyps' pt1 pt2 = merge_ptyps (pt1, pt2)
   909 
   910 (* data for methods stored in 'methods'-database*)
   911 type met = 
   912      {guh        : guh,        (*unique within this isac-knowledge           *)
   913       mathauthors: string list,(*copyright                                   *)
   914       init       : pblID,      (*WN060721 introduced mistakenly--TODO.REMOVE!*)
   915       rew_ord'   : rew_ord',   (*for rules in Detail
   916 			                           TODO.WN0509 store fun itself, see 'type pbt'*)
   917       erls       : rls,        (*the eval_rls for cond. in rules FIXME "rls'
   918 				                         instead erls in "fun prep_met"              *)
   919       srls       : rls,        (*for evaluating list expressions in scr      *)
   920       prls       : rls,        (*for evaluating predicates in modelpattern   *)
   921       crls       : rls,        (*for check_elementwise, ie. formulae in calc.*)
   922       nrls       : rls,        (*canonical simplifier specific for this met  *)
   923       errpats    : errpat list,(*error patterns expected in this method      *)
   924       calc       : calc list,  (*Theory_Data in fun prep_met                 *)
   925       (*branch   : TransitiveB set in append_problem at generation ob pblobj
   926           FIXXXME.0308: set branch from met in Apply_Method ?                *)
   927       ppc        : pat list,   (*.items in given, find, relate;
   928 	      items (in "#Find") which need not occur in the arg-list of a SubProblem
   929         are 'copy-named' with an identifier "*'.'".
   930         copy-named items are 'generating' if they are NOT "*'''" ?WN120516??
   931         see ME/calchead.sml 'fun is_copy_named'.                              *)
   932       pre        : term list,  (*preconditions in where                       *)
   933       scr        : scr         (*prep_met gets progam or string "empty_script"*)
   934 	   };
   935 val e_met = {guh="met_empty",mathauthors=[],init=e_metID,
   936 	     rew_ord' = "e_rew_ord'": rew_ord',
   937 	      erls = e_rls, srls = e_rls, prls = e_rls,
   938 	      calc = [], crls = e_rls, errpats = [], nrls= e_rls,
   939 	      ppc = []: (string * (term * term)) list,
   940 	      pre = []: term list,
   941 	      scr = EmptyScr: scr}:met;
   942 
   943 
   944 val e_Mets = Ptyp ("e_metID",[e_met],[]);
   945 
   946 type mets = (met ptyp) list;
   947 
   948 fun coll_metguhs mets =
   949     let fun node coll (Ptyp (_,[n],ns)) =
   950 	    [(#guh : met -> guh) n] @ (nodes coll ns)
   951 	and nodes coll [] = coll
   952 	  | nodes coll (n::ns) = (node coll n) @ (nodes coll ns);
   953     in nodes [] mets end;
   954 
   955 fun check_metguh_unique (guh:guh) (mets: (met ptyp) list) =
   956     if member op = (coll_metguhs mets) guh
   957     then error ("check_guh_unique failed with '"^guh^"';\n"^
   958 		      "use 'sort_metguhs()' for a list of guhs;\n"^
   959 		      "consider setting 'check_guhs_unique := false'")
   960     else ();
   961 
   962 fun Html_default exist = (Html {guh = theID2guh exist, 
   963   coursedesign = ["isac team 2006"], mathauthors = [], html = ""})
   964 
   965 fun fill_parents (exist, [i]) thydata = Ptyp (i, [thydata], [])
   966   | fill_parents (exist, i :: is) thydata =
   967     Ptyp (i, [Html_default (exist @ [i])], [fill_parents (exist @ [i], is) thydata])
   968   | fill_parents _ _ = error "Html_default: avoid ML warning: Matches are not exhaustive"
   969 
   970 fun add_thydata (exist, is) thydata [] = [fill_parents (exist, is) thydata]
   971   | add_thydata (exist, [i]) data (pys as (py as Ptyp (key, _, _)) :: pyss) = 
   972     if i = key
   973     then pys (* preserve existing thydata *) 
   974     else py :: add_thydata (exist, [i]) data pyss
   975   | add_thydata (exist, iss as (i :: is)) data ((py as Ptyp (key, d, pys)) :: pyss) = 
   976     if i = key
   977     then       
   978       if length pys = 0
   979       then Ptyp (key, d, [fill_parents (exist @ [i], is) data]) :: pyss
   980       else Ptyp (key, d, add_thydata (exist @ [i], is) data pys) :: pyss
   981     else py :: add_thydata (exist, iss) data pyss
   982   | add_thydata _ _ _ = error "add_thydata: avoid ML warning: Matches are not exhaustive"
   983 
   984 fun update_hthm (Hthm {guh, coursedesign, mathauthors, thm, ...}) fillpats' =
   985   Hthm {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
   986     fillpats = fillpats', thm = thm}
   987   | update_hthm _ _ = raise ERROR "wrong data";
   988 
   989 (* for interface for dialog-authoring *)
   990 fun update_hrls (Hrls {guh, coursedesign, mathauthors, thy_rls = (thyID, rls)}) errpatIDs =
   991   let
   992     val rls' = 
   993       case rls of
   994         Rls {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...} =>
   995           Rls {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
   996             calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
   997       | Seq {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...} =>
   998             Seq {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
   999               calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
  1000       | Rrls {id, prepat, rew_ord, erls, calc, scr, ...} =>
  1001             Rrls {id = id, prepat = prepat, rew_ord = rew_ord, erls = erls, calc = calc,
  1002               scr = scr, errpatts = errpatIDs}
  1003       | Erls => Erls
  1004   in
  1005     Hrls {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
  1006       thy_rls = (thyID, rls')}
  1007   end
  1008   | update_hrls _ _ = raise ERROR "wrong data";
  1009 
  1010 fun app_py p f (d:pblID) (k(*:pblRD*)) = let
  1011     fun py_err _ =
  1012           error ("app_py: not found: " ^ (strs2str d));
  1013     fun app_py' _ [] = py_err ()
  1014       | app_py' [] _ = py_err ()
  1015       | app_py' [k0] ((p' as Ptyp (k', _, _  ))::ps) =
  1016           if k0 = k' then f p' else app_py' [k0] ps
  1017       | app_py' (k' as (k0::ks)) (Ptyp (k'', _, ps)::ps') =
  1018           if k0 = k'' then app_py' ks ps else app_py' k' ps';
  1019   in app_py' k p end;
  1020   
  1021 fun get_py p = let
  1022         fun extract_py (Ptyp (_, [py], _)) = py
  1023           | extract_py _ = error ("extract_py: Ptyp has wrong format.");
  1024       in app_py p extract_py end;
  1025 
  1026 fun (*KEStore_Elems.*)insert_fillpats th fis = (* for tests bypassing setup KEStore_Elems *)
  1027   let
  1028     fun update_elem th (theID, fillpats) =
  1029       let
  1030         val hthm = get_py th theID theID
  1031         val hthm' = update_hthm hthm fillpats
  1032           handle ERROR _ => error ("insert_fillpats: " ^ strs2str theID ^ "must address a theorem")
  1033       in update_ptyps theID theID hthm' end
  1034   in fold (update_elem th) fis end
  1035 
  1036 (* group the theories defined in Isac, compare Build_Thydata:
  1037   section "Get and group the theories defined in Isac" *) 
  1038 fun isabthys () = (*["Complex_Main", "Taylor", .., "Pure"]*)
  1039   let
  1040     val allthys = Theory.ancestors_of (Thy_Info.get_theory "Build_Thydata")
  1041   in
  1042     drop ((find_index (curry Theory.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), allthys)
  1043   end
  1044 fun knowthys () = (*["Isac", .., "Descript", "Delete"]*)
  1045   let
  1046     fun isacthys () = (* ["Isac", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
  1047       let
  1048         val allthys = filter_out (member Theory.eq_thy
  1049           [(*Thy_Info.get_theory "ProgLang",*) Thy_Info.get_theory "Interpret", 
  1050             Thy_Info.get_theory "xmlsrc", Thy_Info.get_theory "Frontend"]) 
  1051           (Theory.ancestors_of (Thy_Info.get_theory "Build_Thydata"))
  1052       in
  1053         take ((find_index (curry Theory.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
  1054         allthys)
  1055       end
  1056     val isacthys' = isacthys ()
  1057     val proglang_parent = Thy_Info.get_theory "ProgLang"
  1058   in
  1059     take ((find_index (curry Theory.eq_thy proglang_parent) isacthys'), isacthys')
  1060   end
  1061 fun progthys () = (*["Isac", .., "Descript", "Delete"]*)
  1062   let
  1063     fun isacthys () = (* ["Isac", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
  1064       let
  1065         val allthys = filter_out (member Theory.eq_thy
  1066           [(*Thy_Info.get_theory "ProgLang",*) Thy_Info.get_theory "Interpret", 
  1067             Thy_Info.get_theory "xmlsrc", Thy_Info.get_theory "Frontend"]) 
  1068           (Theory.ancestors_of (Thy_Info.get_theory "Build_Thydata"))
  1069       in
  1070         take ((find_index (curry Theory.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
  1071         allthys)
  1072       end
  1073     val isacthys' = isacthys ()
  1074     val proglang_parent = Thy_Info.get_theory "ProgLang"
  1075   in
  1076     drop ((find_index (curry Theory.eq_thy proglang_parent) isacthys') + 1(*ProgLang*), isacthys')
  1077   end
  1078 
  1079 fun partID thy = 
  1080   if member Theory.eq_thy (knowthys ()) thy then "IsacKnowledge"
  1081   else if member Theory.eq_thy (progthys ()) thy then "IsacScripts"
  1082   else if member Theory.eq_thy (isabthys ()) thy then "Isabelle"
  1083   else error ("closure of thys in Isac is broken by " ^ string_of_thy thy)
  1084 fun partID' (thy' : theory') = partID (Thy_Info.get_theory thy')
  1085 (*
  1086 end (*struct*)
  1087 *)