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