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