src/Tools/isac/CalcElements/calcelems.sml
author Walther Neuper <walther.neuper@jku.at>
Wed, 08 Apr 2020 12:32:51 +0200
changeset 59852 ea7e6679080e
parent 59851 4dd533681fef
child 59854 c20d08e01ad2
permissions -rw-r--r--
use new struct "Rule_Set" for renaming identifiers
     1 (* ~~/src/Tools/isac/calcelems.sml
     2    elements of calculations.
     3    they are partially held in association lists as ref's for
     4    switching language levels (meta-string, object-values).                                  
     5    in order to keep these ref's during re-evaluation of code,                       
     6    they are defined here at the beginning of the code.
     7    Author: Walther Neuper 2003
     8    (c) copyright due to lincense terms
     9 *)
    10 
    11 signature CALC_ELEMENT =
    12   sig
    13     type cas_elem
    14     type pbt
    15     type ptyps
    16     type metID
    17     type pblID
    18     type mets
    19     type met
    20     datatype 'a ptyp = Ptyp of string * 'a list * 'a ptyp list
    21 
    22     type authors
    23     type guh
    24 
    25     type fillpat
    26     datatype thydata
    27       = Hcal of {calc: Rule_Def.calc, coursedesign: authors, guh: guh, mathauthors: authors}
    28       | Hord of {coursedesign: authors, guh: guh, mathauthors: authors, ord: Rule.subst -> term * term -> bool}
    29       | Hrls of {coursedesign: authors, guh: guh, mathauthors: authors, thy_rls: Rule.thyID * Rule_Set.T}
    30       | Hthm of {coursedesign: authors, fillpats: fillpat list, guh: guh, mathauthors: authors, thm: thm}
    31       | Html of {coursedesign: authors, guh: guh, html: string, mathauthors: authors}
    32     type theID
    33     type spec
    34     val cas_eq: cas_elem * cas_elem -> bool
    35     val e_Ptyp: pbt ptyp
    36     val merge_ptyps: 'a ptyp list * 'a ptyp list -> 'a ptyp list
    37     val check_guhs_unique: bool Unsynchronized.ref
    38     val check_pblguh_unique: guh -> pbt ptyp list -> unit
    39     val insrt: pblID -> 'a -> string list -> 'a ptyp list -> 'a ptyp list
    40     val e_Mets: met ptyp
    41     val check_metguh_unique: guh -> met ptyp list -> unit
    42     val add_thydata: string list * string list -> thydata -> thydata ptyp list -> thydata ptyp list
    43     val get_py: 'a ptyp list -> pblID -> string list -> 'a
    44     val update_hthm: thydata -> fillpat list -> thydata
    45     val update_ptyps: string list -> string list -> 'a -> 'a ptyp list -> 'a ptyp list
    46     val part2guh: theID -> guh
    47     val spec2str: string * string list * string list -> string
    48     val linefeed: string -> string
    49     val pbts2str: pbt list -> string
    50     val thes2str: thydata list -> string
    51     val theID2str: string list -> string
    52     val the2str: thydata -> string
    53     val trace_calc: bool Unsynchronized.ref
    54     eqtype thmID
    55     type thm'
    56     val trace_rewrite: bool Unsynchronized.ref
    57     val depth: int Unsynchronized.ref
    58     val assoc_thy: Rule.theory' -> theory
    59     type thm''
    60     val metID2str: string list -> string
    61     val e_pblID: pblID
    62     val e_metID: metID
    63     val empty_spec: spec
    64     val e_spec: spec
    65     datatype ketype = Exp_ | Met_ | Pbl_ | Thy_
    66     type kestoreID
    67     val app_py: 'a ptyp list -> ('a ptyp -> 'b) -> pblID -> string list -> 'b
    68     val ketype2str: ketype -> string
    69     val coll_pblguhs: pbt ptyp list -> guh list
    70     val coll_metguhs: met ptyp list -> guh list
    71     type pat
    72     val pats2str: pat list -> string
    73     val maxthy: theory -> theory -> theory
    74     eqtype filename
    75     val lim_deriv: int Unsynchronized.ref
    76     val id_of_thm: Rule.rule -> string
    77     val isabthys: unit -> theory list
    78     val thyID_of_derivation_name: string -> string
    79     val partID': Rule.theory' -> string
    80     val thm2guh: string * Rule.thyID -> thmID -> guh
    81     val thmID_of_derivation_name: string -> string
    82     val rls2guh: string * Rule.thyID -> Rule_Set.identifier -> guh
    83     val theID2guh: theID -> guh
    84     eqtype fillpatID
    85     type pbt_ = string * (term * term)
    86     eqtype xml
    87     val cal2guh: string * Rule.thyID -> string -> guh
    88     val ketype2str': ketype -> string
    89     val str2ketype': string -> ketype
    90     val thmID_of_derivation_name': thm -> string
    91     eqtype filepath
    92     val theID2thyID: theID -> Rule.thyID
    93     val thy2guh: theID -> guh
    94     val thypart2guh: theID -> guh
    95     val ord2guh: string * Rule.theory' -> string -> string
    96     val update_hrls: thydata -> Rule.errpatID list -> thydata
    97     eqtype iterID
    98     eqtype calcID
    99     val thm''_of_thm: thm -> thm''
   100     val thm_of_thm: Rule.rule -> thm
   101 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
   102     val pats2str' : pat list -> string
   103     val insert_fillpats: thydata ptyp list -> (pblID * fillpat list) list -> thydata ptyp list ->
   104       thydata ptyp list
   105 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
   106     val knowthys: unit -> theory list
   107     val e_pbt: pbt
   108     val e_met: met
   109 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
   110 
   111 (*----- unused code, kept as hints to design ideas ---------------------------------------------*)
   112 val overwritelthy: theory -> (Rule_Set.identifier * (string * Rule_Set.T)) list * (Rule_Set.identifier * Rule_Set.T) list ->
   113   (Rule_Set.identifier * (string * Rule_Set.T)) list  end
   114 
   115 (**)
   116 structure Celem(**): CALC_ELEMENT(**) =
   117 struct
   118 (**)
   119 
   120 val linefeed = (curry op^) "\n"; (* ?\<longrightarrow> libraryC ?*)
   121 type authors = string list;
   122 
   123 type iterID = int;
   124 type calcID = int;
   125 
   126 (* TODO CLEANUP Thm:
   127 Thm (string, thm): (a) needs string to identify sym_thmID for handling in front-end;
   128                    (b) investigate if ""RS sym" attaches a [.]" still occurs: string_of_thmI
   129 thmID            : type for data from user input + program
   130 thmDeriv         : type for thy_hierarchy ONLY
   131 obsolete types   : thm' (SEE "ad thm'"), thm''. 
   132 revise funs      : id_of_thm, thm_of_thm, rep_thm_G', eq_thmI, eq_thmI', thm''_of_thm thm.
   133 activate         : thmID_of_derivation_name'
   134 *)
   135 type thmID = string;    (* identifier for a thm (the shortest possible identifier)       *)
   136 type thmDeriv = string; (* WN120524 deprecated
   137   thyID ^"."^ xxx ^"."^ thmID, see fun thmID_of_derivation_name 
   138   WN120524: dont use Thm.derivation_name, this is destroyed by num_str;
   139   Thm.get_name_hint survives num_str and seems perfectly reliable *)
   140 
   141 type thm' = thmID * Rule.cterm';(*WN060610 deprecated in favour of thm''; WN180324: used in TODO review:
   142 val thm'2xml : int -> Celem.thm' -> Celem.xml
   143 val assoc_thm': theory -> Celem.thm' -> thm
   144 | Calculate' of Rule.theory' * string * term * (term * Celem.thm')
   145 *)
   146 (* tricky combination of (string, term) for theorems in Isac:
   147   * case 1 general: frontend + lucin, e.g. applicable_in..Rewrite: (thmID, _) --> (thmID, thm)
   148     by Global_Theory.get_thm, special cases ("add_commute",..) see convert_metaview_to_thmid.
   149   * case 2 "sym_..": Global_Theory.get_thm..RS sym
   150   * case 3 ad-hoc thm "#..." mk_thm from ad-hoc term (numerals only) in calculate_:
   151     from applicable_in..Calculate: opstr --calculate_/adhoc_thm--> (thmID, thm)
   152 *)
   153 type thm'' = thmID * thm; (* only for transport via libisabelle isac-java <--- ME *)
   154 
   155 (*.a 'guh'='globally unique handle' is a string unique for each element
   156    of isac's KEStore and persistent over time
   157    (in particular under shifts within the respective hierarchy);
   158    specialty for thys:
   159    # guh NOT resistant agains shifts from one thy to another
   160    (which is the price for Isabelle's design: thy's overwrite ids of subthy's)
   161    # requirement for matchTheory: induce guh from tac + current thy
   162    (see 'fun thy_containing_thm', 'fun thy_containing_rls' etc.)
   163    TODO: introduce to pbl, met.*)
   164 type guh = string;
   165 
   166 type xml = string; (* rm together with old code replaced by XML.tree *)
   167 
   168 
   169 (* for (at least) 2 kinds of access:
   170   (1) given an errpatID, find the respective fillpats (e.g. in fun find_fill_pats)
   171   (2) given a thm, find respective fillpats *)
   172 type fillpatID = string
   173 type fillpat =
   174   fillpatID   (* DESIGN ?TODO: give an order w.r.t difficulty ? *)
   175   * term      (* the pattern with fill-in gaps                  *)
   176   * Rule.errpatID; (* which the fillpat would be a help for          
   177                  DESIGN ?TODO: list for several patterns ?      *)
   178 
   179 
   180 (*  WN0509 discussion:
   181 #############################################################################
   182 #   How to manage theorys in subproblems wrt. the requirement,              #
   183 #   that scripts should be re-usable ?                                      #
   184 #############################################################################
   185 
   186     eg. 'Program Solve_rat_equation' calls 'SubProblem (RatEq',..'
   187     which would not allow to 'solve (y'' = -M_b / EI, M_b)' by this script
   188     because Biegelinie.thy is subthy of RatEq.thy and thus Biegelinie.M_b
   189     is unknown in RatEq.thy and M_b cannot be parsed into the scripts guard
   190     (see match_ags).
   191 
   192     Preliminary solution:
   193     # the thy in 'SubProblem (thy', pbl, arglist)' is not taken automatically,
   194     # instead the 'maxthy (rootthy pt) thy' is taken for each subpbl
   195     # however, a thy specified by the user in the rootpbl may lead to
   196       errors in far-off subpbls (which are not yet reported properly !!!)
   197       and interactively specifiying thys in subpbl is not very relevant.
   198 
   199     Other solutions possible:
   200     # always parse and type-check with Thy_Info_get_theory "Isac_Knowledge"
   201       (rejected due to the vague idea eg. to re-use equations for R in C etc.)
   202     # regard the subthy-relation in specifying thys of subpbls
   203     # specifically handle 'SubProblem (undefined, pbl, arglist)'
   204     # ???
   205 *)
   206 
   207 fun id_of_thm (Rule.Thm (id, _)) = id  (* TODO re-arrange code for rule2str *)
   208   | id_of_thm _ = raise ERROR ("id_of_thm: uncovered case " (* ^ rule2str r *))
   209 fun thm_of_thm (Rule.Thm (_, thm)) = thm  (* TODO re-arrange code for rule2str *)
   210   | thm_of_thm _ = raise ERROR ("thm_of_thm: uncovered case " (* ^ rule2str r *))
   211 
   212 fun thmID_of_derivation_name dn = last_elem (space_explode "." dn);
   213 fun thmID_of_derivation_name' thm = (thmID_of_derivation_name o Thm.get_name_hint) thm
   214 fun thyID_of_derivation_name dn = hd (space_explode "." dn);
   215 fun thm''_of_thm thm = (thmID_of_derivation_name' thm, thm) : thm''
   216 
   217 
   218 
   219 (*the key into the hierarchy ob theory elements*)
   220 type theID = string list;
   221 val theID2str = strs2str; (*theID eg. is ["IsacKnowledge", "Test", "Rulesets", "ac_plus_times"]*)
   222 fun theID2thyID theID =
   223   if length theID >= 3 then (last_elem o (drop_last_n 2)) theID
   224   else error ("theID2thyID called with " ^ theID2str theID);
   225 
   226 (*the key into the hierarchy ob problems*)
   227 type pblID = string list; (* domID :: ...*)
   228 val e_pblID = ["e_pblID"];
   229 
   230 (*the key into the hierarchy ob methods*)
   231 type metID = string list;
   232 type spec = Rule.domID * pblID * metID;
   233 fun spec2str (dom, pbl, met) = 
   234   "(" ^ quote dom  ^ ", " ^ strs2str pbl ^ ", " ^ strs2str met ^ ")";
   235 val e_metID = ["e_metID"];
   236 val metID2str = strs2str;
   237 val empty_spec = (Rule.e_domID, e_pblID, e_metID);
   238 val e_spec = empty_spec;
   239 
   240 (* association list with cas-commands, for generating a complete calc-head *)
   241 type generate_fn = 
   242   (term list ->    (* the arguments of the cas-command, eg. (x+1=2, x) *)
   243     (term *        (* description of an element                        *)
   244       term list)   (* value of the element (always put into a list)    *)
   245   list)            (* of elements in the formalization                 *)
   246 type cas_elem = 
   247   (term *          (* cas-command, eg. 'solve'                         *)
   248     (spec *        (* theory, problem, method                          *)
   249     generate_fn))
   250 fun cas_eq ((t1, (_, _)) : cas_elem, (t2, (_, _)) : cas_elem) = t1 = t2
   251 
   252 (*either theID or pblID or metID*)
   253 type kestoreID = string list;
   254 
   255 (* for distinction of contexts WN130621: disambiguate with Isabelle's Context *)
   256 datatype ketype = Exp_ | Thy_ | Pbl_ | Met_;
   257 fun ketype2str Exp_ = "Exp_"
   258   | ketype2str Thy_ = "Thy_"
   259   | ketype2str Pbl_ = "Pbl_"
   260   | ketype2str Met_ = "Met_";
   261 fun ketype2str' Exp_ = "Example"
   262   | ketype2str' Thy_ = "Theory"
   263   | ketype2str' Pbl_ = "Problem"
   264   | ketype2str' Met_ = "Method";
   265 (* for conversion from XML *)
   266 fun str2ketype' "exp" = Exp_
   267   | str2ketype' "thy" = Thy_
   268   | str2ketype' "pbl" = Pbl_
   269   | str2ketype' "met" = Met_
   270   | str2ketype' str = raise ERROR ("str2ketype': WRONG arg = " ^ str)
   271 
   272 (* A tree for storing data defined in different theories 
   273   for access from the Interpreter and from dialogue authoring 
   274   using a string list as key.
   275   'a is for pbt | met | thydata; after WN030424 naming "pbt" became inappropriate *)
   276 datatype 'a ptyp =
   277 	Ptyp of string *  (* element of the key                                                        *)
   278 		'a list *       (* several pbts with different domIDs/thy TODO: select by subthy (isaref.p.69)
   279 			                 presently only _ONE_ elem FOR ALL KINDS OF CONTENT pbt | met | thydata    *)
   280 		('a ptyp) list; (* the children nodes                                                        *)
   281 
   282 (* datatype for collecting thydata for hierarchy *)
   283 (*WN060720 more consistent naming would be 'type thyelem' or 'thelem'*)
   284 datatype thydata =
   285   Html of {guh: guh, coursedesign: authors, mathauthors: authors, html: string}
   286 | Hthm of {guh: guh, coursedesign: authors, mathauthors: authors, fillpats: fillpat list,
   287    thm: thm} (* here no sym_thm, thus no thmID required *)
   288 | Hrls of {guh: guh, coursedesign: authors, mathauthors: authors, thy_rls: (Rule.thyID * Rule_Set.T)}
   289 | Hcal of {guh: guh, coursedesign: authors, mathauthors: authors, calc: Rule_Def.calc}
   290 | Hord of {guh: guh, coursedesign: authors, mathauthors: authors,
   291     ord: (Rule.subst -> (term * term) -> bool)};
   292 fun the2str (Html {guh, ...}) = guh
   293   | the2str (Hthm {guh, ...}) = guh
   294   | the2str (Hrls {guh, ...}) = guh
   295   | the2str (Hcal {guh, ...}) = guh
   296   | the2str (Hord {guh, ...}) = guh
   297 fun thes2str thes = map the2str thes |> list2str;
   298 
   299 (* notes on thehier concerning sym_thmID theorems (created in derivations, reverse rewriting)
   300      (a): thehier does not contain sym_thmID theorems
   301      (b): lookup for sym_thmID directly from Isabelle using sym_thm
   302           (within math-engine NO lookup in thehier -- within java in *.xml only!)
   303 TODO (c): export from thehier to xml
   304 TODO (c1)   creates one entry for "thmID" (and NONE for "sym_thmID") in the hierarchy
   305 TODO (c2)   creates 2 files "thy_*-thm-thmID.xml" and "thy_*-thm-sym_thmID.xml"
   306 TODO (d): 1 entry in the MiniBrowser's hierarchy (generated from xml)
   307           stands for both, "thmID" and "sym_thmID" 
   308 TODO (d1)   lookup from calctxt          
   309 TODO (d1)   lookup from from rule set in MiniBrowser *)
   310 type thehier = (thydata ptyp) list;
   311 (* required to determine sequence of main nodes of thehier in KEStore.thy *)
   312 fun part2guh [str] = (case str of
   313 	  "Isabelle" => "thy_isab_" ^ str ^ "-part" : guh
   314       | "IsacScripts" => "thy_scri_" ^ str ^ "-part"
   315       | "IsacKnowledge" => "thy_isac_" ^ str ^ "-part"
   316       | str => raise ERROR ("thy2guh: called with \""^ str ^"\""))
   317   | part2guh theID = raise ERROR ("part2guh called with theID = \"" ^ theID2str theID ^ "'");
   318 
   319 fun thy2guh [part, thyID] = (case part of
   320       "Isabelle" => "thy_isab_" ^ thyID
   321     | "IsacScripts" => "thy_scri_" ^ thyID
   322     | "IsacKnowledge" => "thy_isac_" ^ thyID
   323     | str => raise ERROR ("thy2guh: called with \"" ^ str ^ "\""))
   324   | thy2guh theID = raise ERROR ("thy2guh called with \"" ^ strs2str' theID ^ "\"");
   325 			
   326 fun thypart2guh ([part, thyID, thypart] : theID) = (case part of
   327       "Isabelle" => "thy_isab_" ^ thyID ^ "-" ^ thypart : guh
   328     | "IsacScripts" => "thy_scri_" ^ thyID ^ "-" ^ thypart
   329     | "IsacKnowledge" => "thy_isac_" ^ thyID ^ "-" ^ thypart
   330     | str => raise ERROR ("thypart2guh: called with '" ^ str ^ "'"))
   331   | thypart2guh strs = raise ERROR ("thypart2guh called with \"" ^ strs2str' strs ^ "\"");
   332 
   333   
   334 (* convert the data got via contextToThy to a globally unique handle.
   335    there is another way to get the guh: get out of the 'theID' in the hierarchy *)
   336 fun thm2guh (isa, thyID) thmID = case isa of
   337     "Isabelle" => "thy_isab_" ^ Rule.theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID : guh
   338   | "IsacKnowledge" => "thy_isac_" ^ Rule.theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
   339   | "IsacScripts" => "thy_scri_" ^ Rule.theory'2thyID thyID ^ "-thm-" ^ strip_thy thmID
   340   | _ => raise ERROR
   341     ("thm2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for thm = \"" ^ thmID ^ "\"");
   342 
   343 fun rls2guh (isa, thyID) rls' = case isa of
   344     "Isabelle" => "thy_isab_" ^ Rule.theory'2thyID thyID ^ "-rls-" ^ rls' : guh
   345   | "IsacKnowledge" => "thy_isac_" ^ Rule.theory'2thyID thyID ^ "-rls-" ^ rls'
   346   | "IsacScripts" => "thy_scri_" ^ Rule.theory'2thyID thyID ^ "-rls-" ^ rls'
   347   | _ => raise ERROR
   348     ("rls2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for rls = \"" ^ rls' ^ "\"");
   349 			  
   350 fun cal2guh (isa, thyID) calID = case isa of
   351     "Isabelle" => "thy_isab_" ^ Rule.theory'2thyID thyID ^ "-cal-" ^ calID : guh
   352   | "IsacKnowledge" => "thy_isac_" ^ Rule.theory'2thyID thyID ^ "-cal-" ^ calID
   353   | "IsacScripts" => "thy_scri_" ^ Rule.theory'2thyID thyID ^ "-cal-" ^ calID
   354   | _ => raise ERROR
   355     ("cal2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for cal = \"" ^ calID ^ "\"");
   356 			  
   357 fun ord2guh (isa, thyID) rew_ord' = case isa of
   358     "Isabelle" => "thy_isab_" ^ Rule.theory'2thyID thyID ^ "-ord-" ^ rew_ord' : guh
   359   | "IsacKnowledge" => "thy_isac_" ^ Rule.theory'2thyID thyID ^ "-ord-" ^ rew_ord'
   360   | "IsacScripts" => "thy_scri_" ^ Rule.theory'2thyID thyID ^ "-ord-" ^ rew_ord'
   361   | _ => raise ERROR
   362     ("ord2guh called with (isa, thyID) = (" ^ isa ^ ", " ^ thyID ^ ") for ord = \"" ^ rew_ord' ^ "\"");
   363 
   364 (* not only for thydata, but also for thy's etc *)
   365 (* TODO
   366 fun theID2guh theID = case length theID of
   367     0 => error ("theID2guh: called with theID = " ^ strs2str' theID)
   368   | 1 => part2guh theID
   369   | 2 => thy2guh theID
   370   | 3 => thypart2guh theID
   371   | 4 => 
   372     let val [isa, thyID, typ, elemID] = theID
   373     in case typ of
   374         "Theorems" => thm2guh (isa, thyID) elemID
   375       | "Rulesets" => rls2guh (isa, thyID) elemID
   376       | "Calculations" => cal2guh (isa, thyID) elemID
   377       | "Orders" => ord2guh (isa, thyID) elemID
   378       | "Theorems" => thy2guh [isa, thyID]
   379       | str => raise ERROR ("theID2guh: called with theID = " ^ strs2str' theID)
   380     end
   381   | n => raise ERROR ("theID2guh called with theID = " ^ strs2str' theID);
   382 *)
   383 (* not only for thydata, but also for thy's etc *)
   384 fun theID2guh [] = raise ERROR ("theID2guh: called with []")
   385   | theID2guh [str] = part2guh [str]
   386   | theID2guh [s1, s2] = thy2guh [s1, s2]
   387   | theID2guh [s1, s2, s3] = thypart2guh [s1, s2, s3]
   388   | theID2guh (strs as [isa, thyID, typ, elemID]) = (case typ of
   389       "Theorems" => thm2guh (isa, thyID) elemID
   390     | "Rulesets" => rls2guh (isa, thyID) elemID
   391     | "Calculations" => cal2guh (isa, thyID) elemID
   392     | "Orders" => ord2guh (isa, thyID) elemID
   393     | _ => raise ERROR ("theID2guh: called with theID = " ^ strs2str' strs))
   394   | theID2guh strs = raise ERROR ("theID2guh called with theID = " ^ strs2str' strs);
   395 
   396 type filepath = string;
   397 type filename = string;
   398 
   399 fun assoc_thy thy =
   400     if thy = "e_domID"
   401     then (Rule.Thy_Info_get_theory "Base_Tools") (*lower bound of Knowledge*)
   402     else (Rule.Thy_Info_get_theory thy) handle _ => error ("ME_Isa: thy \"" ^ thy ^ "\" not in system");
   403 
   404 (* overwrite an element in an association list and pair it with a thyID
   405    in order to create the thy_hierarchy;
   406    overwrites existing rls' even if they are defined in a different thy;
   407    this is related to assoc_rls, TODO.WN060120: assoc_rew_ord, assoc_calc *)
   408 (* WN060120 ...these are NOT compatible to "fun assoc_thm'" in that
   409    they do NOT handle overlays by re-using an identifier in different thys;
   410    "thyID.rlsID" would be a good solution, if the "." would be possible
   411    in scripts...
   412    actually a hack to get alltogether run again with minimal effort *)
   413 fun insthy thy' (rls', rls) = (rls', (thy', rls));
   414 fun overwritelthy thy (al, bl: (Rule_Set.identifier * Rule_Set.T) list) =
   415     let val bl' = map (insthy ((get_thy o Rule.theory2theory') thy)) bl
   416     in overwritel (al, bl') end;
   417 
   418 fun maxthy thy1 thy2 = if Context.subthy (thy1, thy2) then thy2 else thy1;
   419 
   420 
   421 (* trace internal steps of isac's numeral calculations *)
   422 val trace_calc = Unsynchronized.ref false;
   423 (* trace internal steps of isac's rewriter *)
   424 val trace_rewrite = Unsynchronized.ref false;
   425 (* depth of recursion in traces of the rewriter, if trace_rewrite:=true *)
   426 val depth = Unsynchronized.ref 99999;
   427 (* no of rewrites exceeding this int -> NO rewrite *)
   428 val lim_deriv = Unsynchronized.ref 100;
   429 (* switch for checking guhs unique before storing a pbl or met;
   430    set true at startup (done at begin of ROOT.ML)
   431    set false for editing IsacKnowledge (done at end of ROOT.ML) *)
   432 val check_guhs_unique = Unsynchronized.ref true;
   433 
   434 (* the pattern for an item of a problems model or a methods guard *)
   435 type pat =
   436   (string *     (* field               *)
   437 	  (term *     (* description         *)
   438 	     term))   (* id | arbitrary term *);
   439 fun pat2str ((field, (dsc, id)) : pat) = 
   440   pair2str (field, pair2str (Rule.term2str dsc, Rule.term2str id))
   441 fun pats2str pats = (strs2str o (map pat2str)) pats
   442 fun pat2str' ((field, (dsc, id)) : pat) = 
   443   pair2str (field, pair2str (Rule.term2str dsc, Rule.term2str id)) ^ "\n"
   444 fun pats2str' pats = (strs2str o (map pat2str')) pats
   445 
   446 (* types for problems models (TODO rename to specification models) *)
   447 type pbt_ =
   448   (string *   (* field "#Given",..*)(*deprecated due to 'type pat'*)
   449     (term *   (* description      *)
   450       term)); (* id | struct-var  *)
   451 type pbt = 
   452   {guh : guh,         (* unique within this isac-knowledge                               *)
   453   mathauthors : string list, (* copyright                                                *)
   454   init : pblID,       (* to start refinement with                                        *)
   455   thy  : theory,      (* which allows to compile that pbt
   456                         TODO: search generalized for subthy (ref.p.69*)
   457                         (*^^^ WN050912 NOT used during application of the problem,
   458                         because applied terms may be from 'subthy' as well as from super;
   459                         thus we take 'maxthy'; see match_ags !                           *)
   460   cas : term option,  (* 'CAS-command'                                                   *)
   461   met : metID list,   (* methods solving the pbt                                         *)
   462 (*TODO: abstract to ?pre_model?...*)
   463   prls : Rule_Set.T,    (* for preds in where_                                             *)
   464   where_ : term list, (* where - predicates                                              *)
   465   ppc : pat list      (* this is the model-pattern; 
   466                          it contains "#Given","#Where","#Find","#Relate"-patterns
   467                          for constraints on identifiers see "fun cpy_nam"                *)
   468 }   
   469 
   470 val e_pbt = {guh = "pbl_empty", mathauthors = [], init = e_pblID, thy = Thy_Info.get_theory "Pure",
   471   cas = NONE, prls = Rule_Set.Empty, where_ = [], ppc = [], met = []} : pbt
   472 fun pbt2str ({cas = cas', guh = guh', init = init', mathauthors = ma', met = met', ppc = ppc',
   473       prls = prls', thy = thy', where_ = w'} : pbt)
   474     = "{cas = " ^ (Rule.termopt2str cas') ^  ", guh = \"" ^ guh'  ^ "\", init = "
   475       ^ (strs2str init') ^ ", mathauthors = " ^ (strs2str ma' |> quote) ^ ", met = "
   476       ^ (strslist2strs met') ^ ", ppc = " ^ pats2str ppc' ^ ", prls = "
   477       ^ (Rule_Set.rls2str prls' |> quote) ^ ", thy = {" ^ (Rule.theory2str thy') ^ "}, where_ = "
   478       ^ (Rule.terms2str w') ^ "}" |> linefeed;
   479 fun pbts2str pbts = map pbt2str pbts |> list2str;
   480 
   481 val e_Ptyp = Ptyp ("e_pblID", [e_pbt], [])
   482 type ptyps = (pbt ptyp) list
   483 
   484 fun coll_pblguhs pbls =
   485   let
   486     fun node coll (Ptyp (_, [n], ns)) = [(#guh : pbt -> guh) n] @ (nodes coll ns)
   487       | node _ _ = raise ERROR "coll_pblguhs - node"
   488 	  and nodes coll [] = coll
   489       | nodes coll (n :: ns) = (node coll n) @ (nodes coll ns);
   490   in nodes [] pbls end;
   491 fun check_pblguh_unique guh pbls =
   492   if member op = (coll_pblguhs pbls) guh
   493   then error ("check_guh_unique failed with \""^ guh ^"\";\n"^
   494 	      "use \"sort_pblguhs()\" for a list of guhs;\n"^
   495 	      "consider setting \"check_guhs_unique := false\"")
   496   else ();
   497 
   498 fun insrt _ pbt [k] [] = [Ptyp (k, [pbt], [])]
   499   | insrt d pbt [k] ((Ptyp (k', [p], ps)) :: pys) =
   500     ((*writeln ("### insert 1: ks = " ^ strs2str [k] ^ "    k'= " ^ k');*)
   501     if k = k'
   502     then ((Ptyp (k', [pbt], ps)) :: pys)
   503     else  ((Ptyp (k', [p], ps)) :: (insrt d pbt [k] pys))
   504     )			 
   505   | insrt d pbt (k::ks) ((Ptyp (k', [p], ps)) :: pys) =
   506     ((*writeln ("### insert 2: ks = "^(strs2str (k::ks))^"    k'= "^k');*)
   507     if k = k'
   508     then ((Ptyp (k', [p], insrt d pbt ks ps)) :: pys)
   509     else 
   510       if length pys = 0
   511       then error ("insert: not found " ^ (strs2str (d : pblID)))
   512       else ((Ptyp (k', [p], ps)) :: (insrt d pbt (k :: ks) pys))
   513     )
   514   | insrt _ _ _ _ = raise ERROR "";
   515 
   516 fun update_ptyps ID _ _ [] =
   517     error ("update_ptyps: " ^ strs2str' ID ^ " does not exist")
   518   | update_ptyps ID [i] data ((py as Ptyp (key, _, pys)) :: pyss) =
   519     if i = key
   520     then 
   521       if length pys = 0
   522       then ((Ptyp (key, [data], [])) :: pyss)
   523       else error ("update_ptyps: " ^ strs2str' ID ^ " has descendants")
   524     else py :: update_ptyps ID [i] data pyss
   525   | update_ptyps ID (i :: is) data ((py as Ptyp (key, d, pys)) :: pyss) =
   526     if i = key
   527     then ((Ptyp (key,  d, update_ptyps ID is data pys)) :: pyss)
   528     else (py :: (update_ptyps ID (i :: is) data pyss))
   529   | update_ptyps _ _ _ _ = raise ERROR "update_ptyps called with undef pattern.";
   530 
   531 (* this function only works wrt. the way Isabelle evaluates Theories and is not a general merge
   532   function for trees / ptyps *)
   533 fun merge_ptyps ([], pt) = pt
   534   | merge_ptyps (pt, []) = pt
   535   | merge_ptyps ((x' as Ptyp (k, _, ps)) :: xs, (xs' as Ptyp (k', y, ps') :: ys)) =
   536       if k = k'
   537       then Ptyp (k, y, merge_ptyps (ps, ps')) :: merge_ptyps (xs, ys)
   538       else x' :: merge_ptyps (xs, xs');
   539 
   540 (* data for methods stored in 'methods'-database*)
   541 type met = 
   542      {guh        : guh,             (* unique within this isac-knowledge             *)
   543       mathauthors: string list,     (* copyright                                     *)
   544       init       : pblID,           (* WN060721 introduced mistakenly--TODO.REMOVE!  *)
   545       rew_ord'   : Rule_Def.rew_ord',  (* for rules in Detail                           
   546 			                                 TODO.WN0509 store fun itself, see 'type pbt'  *)
   547       erls       : Rule_Set.T,        (* the eval_rls for cond. in rules FIXME "rls'   
   548 				                               instead erls in "fun prep_met"                *)
   549       srls       : Rule_Set.T,        (* for evaluating list expressions in scr        *)
   550       crls       : Rule_Set.T,        (* for check_elementwise, ie. formulae in calc.  *)
   551       nrls       : Rule_Set.T,        (* canonical simplifier specific for this met    *)
   552       errpats    : Rule.errpat list,(* error patterns expected in this method        *)
   553       calc       : Rule_Def.calc list, (* Theory_Data in fun prep_met                   *)
   554       (*branch   : TransitiveB set in append_problem at generation ob pblobj         *)
   555       scr        : Rule.program,    (* progam, empty as @{thm refl} or Rfuns         *)
   556 (*TODO: abstract to ?pre_model?...*)
   557       prls       : Rule_Set.T,        (* for evaluating predicates in modelpattern     *)
   558       ppc        : pat list,        (* items in given, find, relate;
   559 	      items (in "#Find") which need not occur in the arg-list of a SubProblem
   560         are 'copy-named' with an identifier "*'.'".
   561         copy-named items are 'generating' if they are NOT "*'''" ?WN120516??
   562         see ME/calchead.sml 'fun is_copy_named'.                                     *)
   563       pre        : term list        (* preconditions in where                        *)
   564 	   };
   565 val e_met = {guh = "met_empty", mathauthors = [], init = e_metID, rew_ord' = "e_rew_ord'",
   566 	erls = Rule_Set.empty, srls = Rule_Set.empty, prls = Rule_Set.empty, calc = [], crls = Rule_Set.empty,
   567 	errpats = [], nrls = Rule_Set.empty, ppc = [], pre = [], scr = Rule.EmptyScr};
   568 val e_Mets = Ptyp ("e_metID", [e_met],[]);
   569 
   570 type mets = (met ptyp) list;
   571 fun coll_metguhs mets =
   572   let
   573     fun node coll (Ptyp (_, [n], ns)) = [(#guh : met -> guh) n] @ (nodes coll ns)
   574       | node _ _ = raise ERROR "coll_pblguhs - node"
   575   	and nodes coll [] = coll
   576   	  | nodes coll (n :: ns) = (node coll n) @ (nodes coll ns);
   577     in nodes [] mets end;
   578 fun check_metguh_unique (guh:guh) (mets: (met ptyp) list) =
   579     if member op = (coll_metguhs mets) guh
   580     then raise ERROR ("check_guh_unique failed with \"" ^ guh ^"\";\n"^
   581 		(*"use \"sort_metguhs()\" for a list of guhs;\n" ^        ...evaluates to [] ?!?*)
   582 		  "consider setting \"check_guhs_unique := false\"")
   583     else ();
   584 
   585 fun Html_default exist = (Html {guh = theID2guh exist, 
   586   coursedesign = ["isac team 2006"], mathauthors = [], html = ""})
   587 
   588 fun fill_parents (_, [i]) thydata = Ptyp (i, [thydata], [])
   589   | fill_parents (exist, i :: is) thydata =
   590     Ptyp (i, [Html_default (exist @ [i])], [fill_parents (exist @ [i], is) thydata])
   591   | fill_parents _ _ = raise ERROR "Html_default: avoid ML warning: Matches are not exhaustive"
   592 
   593 fun add_thydata (exist, is) thydata [] = [fill_parents (exist, is) thydata]
   594   | add_thydata (exist, [i]) data (pys as (py as Ptyp (key, _, _)) :: pyss) = 
   595     if i = key
   596     then pys (* preserve existing thydata *) 
   597     else py :: add_thydata (exist, [i]) data pyss
   598   | add_thydata (exist, iss as (i :: is)) data ((py as Ptyp (key, d, pys)) :: pyss) = 
   599     if i = key
   600     then       
   601       if length pys = 0
   602       then Ptyp (key, d, [fill_parents (exist @ [i], is) data]) :: pyss
   603       else Ptyp (key, d, add_thydata (exist @ [i], is) data pys) :: pyss
   604     else py :: add_thydata (exist, iss) data pyss
   605   | add_thydata _ _ _ = raise ERROR "add_thydata: avoid ML warning: Matches are not exhaustive"
   606 
   607 fun update_hthm (Hthm {guh, coursedesign, mathauthors, thm, ...}) fillpats' =
   608   Hthm {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
   609     fillpats = fillpats', thm = thm}
   610   | update_hthm _ _ = raise ERROR "update_hthm: wrong arguments";
   611 
   612 (* for dialog-authoring *)
   613 fun update_hrls (Hrls {guh, coursedesign, mathauthors, thy_rls = (thyID, rls)}) errpatIDs =
   614     let
   615       val rls' = 
   616         case rls of
   617           Rule_Def.Repeat {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...}
   618           => Rule_Def.Repeat {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
   619                calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
   620         | Rule_Set.Seqence {id, preconds, rew_ord, erls, srls, calc, rules, scr, ...}
   621           => Rule_Set.Seqence {id = id, preconds = preconds, rew_ord = rew_ord, erls = erls, srls = srls,
   622                calc = calc, rules = rules, scr = scr, errpatts = errpatIDs}
   623         | Rule_Set.Rrls {id, prepat, rew_ord, erls, calc, scr, ...}
   624           => Rule_Set.Rrls {id = id, prepat = prepat, rew_ord = rew_ord, erls = erls, calc = calc,
   625                scr = scr, errpatts = errpatIDs}
   626         | Erls => Erls
   627     in
   628       Hrls {guh = guh, coursedesign = coursedesign, mathauthors = mathauthors,
   629         thy_rls = (thyID, rls')}
   630     end
   631   | update_hrls _ _ = raise ERROR "update_hrls: wrong arguments";
   632 
   633 fun app_py p f (d:pblID) (k(*:pblRD*)) =
   634   let
   635     fun py_err _ = raise ERROR ("app_py: not found: " ^ strs2str d);
   636     fun app_py' _ [] = py_err ()
   637       | app_py' [] _ = py_err ()
   638       | app_py' [k0] ((p' as Ptyp (k', _, _  )) :: ps) =
   639         if k0 = k' then f p' else app_py' [k0] ps
   640       | app_py' (k' as (k0 :: ks)) (Ptyp (k'', _, ps) :: ps') =
   641         if k0 = k'' then app_py' ks ps else app_py' k' ps';
   642   in app_py' k p end;
   643 fun get_py p =
   644   let
   645     fun extract_py (Ptyp (_, [py], _)) = py
   646       | extract_py _ = raise ERROR ("extract_py: Ptyp has wrong format.");
   647   in app_py p extract_py end;
   648 
   649 fun (*KEStore_Elems.*)insert_fillpats th fis = (* for tests bypassing setup KEStore_Elems *)
   650   let
   651     fun update_elem th (theID, fillpats) =
   652       let
   653         val hthm = get_py th theID theID
   654         val hthm' = update_hthm hthm fillpats
   655           handle ERROR _ => error ("insert_fillpats: " ^ strs2str theID ^ "must address a theorem")
   656       in update_ptyps theID theID hthm' end
   657   in fold (update_elem th) fis end
   658 
   659 (* group the theories defined in Isac, compare Build_Thydata:
   660   section "Get and group the theories defined in Isac" *) 
   661 fun isabthys () = (*["Complex_Main", "Taylor", .., "Pure"]*)
   662   let
   663     val allthys = Theory.ancestors_of (Rule.Thy_Info_get_theory "Build_Thydata")
   664   in
   665     drop ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), allthys)
   666   end
   667 fun knowthys () = (*["Isac_Knowledge", .., "Descript"]*)
   668   let
   669     fun isacthys () = (* ["Isac_Knowledge", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
   670       let
   671         val allthys = filter_out (member Context.eq_thy
   672           [(*Thy_Info_get_theory "ProgLang",*) Rule.Thy_Info_get_theory "Interpret", 
   673             Rule.Thy_Info_get_theory "MathEngine", Rule.Thy_Info_get_theory "BridgeLibisabelle"]) 
   674           (Theory.ancestors_of (Rule.Thy_Info_get_theory "Build_Thydata"))
   675       in
   676         take ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
   677         allthys)
   678       end
   679     val isacthys' = isacthys ()
   680     val proglang_parent = Rule.Thy_Info_get_theory "ProgLang"
   681   in
   682     take ((find_index (curry Context.eq_thy proglang_parent) isacthys'), isacthys')
   683   end
   684 
   685 fun progthys () = (*["Isac_Knowledge", .., "Descript"]*)
   686   let
   687     fun isacthys () = (* ["Isac_Knowledge", .., "KEStore"] without Build_Isac thys: "Interpret" etc *)
   688       let                                                        
   689         val allthys = filter_out (member Context.eq_thy
   690           [(*Thy_Info_get_theory "ProgLang",*) Rule.Thy_Info_get_theory "Interpret", 
   691             Rule.Thy_Info_get_theory "MathEngine", Rule.Thy_Info_get_theory "BridgeLibisabelle"]) 
   692           (Theory.ancestors_of (Rule.Thy_Info_get_theory "Build_Thydata"))
   693       in
   694         take ((find_index (curry Context.eq_thy (Thy_Info.get_theory "Complex_Main")) allthys), 
   695         allthys)
   696       end
   697     val isacthys' = isacthys ()
   698     val proglang_parent = Rule.Thy_Info_get_theory "ProgLang"
   699   in
   700     drop ((find_index (curry Context.eq_thy proglang_parent) isacthys') + 1(*ProgLang*), isacthys')
   701   end
   702 
   703 fun partID thy = 
   704   if member Context.eq_thy (knowthys ()) thy then "IsacKnowledge"
   705   else if member Context.eq_thy (progthys ()) thy then "IsacScripts"
   706   else if member Context.eq_thy (isabthys ()) thy then "Isabelle"
   707   else error ("closure of thys in Isac is broken by " ^ Rule.string_of_thy thy)
   708 fun partID' thy' = partID (Rule.Thy_Info_get_theory thy')
   709 
   710 end (*struct*)
   711