src/Tools/isac/calcelems.sml
author Walther Neuper <neuper@ist.tugraz.at>
Mon, 04 Aug 2014 15:54:57 +0200
changeset 55489 c468e9311e5a
parent 55487 06883b595617
child 55491 0aab77a80b0b
permissions -rw-r--r--
in thehier replaced Threory.axioms_of by MutabelleExtra.thms_of

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