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