src/Tools/isac/calcelems.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Fri, 23 Mar 2018 10:14:39 +0100
changeset 59411 3e241a6938ce
parent 59410 2cbb98890190
child 59413 081cfeaf2568
permissions -rw-r--r--
Celem: Test_Isac partially

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