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