src/Tools/isac/calcelems.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Tue, 11 Aug 2015 15:39:27 +0200
changeset 59156 f323be267fa2
parent 59141 43c1e5222f0e
child 59172 a1d4bfe007da
permissions -rw-r--r--
PIDE-phase-2a: xml_to_* for operation_setup of all Math_Engine

cf. https://github.com/wneuper/libisabelle/commit/4ab04dd1a8bfe9d2d4d174c216d637b233ed42dc
phases described at https://intra.ist.tugraz.at/hg/isac/rev/232e68e6cad4.

Note: Communication isac-java <--> Isabelle/Isac by "isabelle tty"
was only partially prepared for asynchronous communication,
see https://intra.ist.tugraz.at/hg/isa/file/68ca125a58cb/src/Tools/isac/xmlsrc/interface-xml.sml#l5

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