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