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