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