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