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