src/Tools/isac/calcelems.sml
author Walther Neuper <neuper@ist.tugraz.at>
Mon, 20 Feb 2012 18:18:03 +0100
changeset 42376 9e59542132b3
parent 42372 10e8bfe8d913
child 42399 c5bb245afb58
permissions -rw-r--r--
Jan finished his work

ATTENTION: Test_Isac.thy indicates confusion in theory dependencies: NOT WORKING !!!
completed Partial_Fractions.thy (PFD), partial_fractions.sml:
all respective stuff moved here from Build_Inverse_Z_Transform.thy
pre-condition for PFD not fulfilled in order to bypass isac's weakness in 'solve'.
not completed:
transfer from Build_Inverse_Z_Transform.thy to Inverse_Z_Transform.thy
     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 the beginning of the code.
     6    author: Walther Neuper
     7    (c) isac-team 2003
     8 *)
     9 
    10 (*
    11 structure CalcElems =
    12 struct
    13 *)
    14 val linefeed = (curry op^) "\n";
    15 type authors = string list;
    16 
    17 type cterm' = string;
    18 val empty_cterm' = "empty_cterm'";
    19 type thmID = string;
    20 type thm' = thmID * cterm';(*WN060610 deprecated in favour of thm''*)
    21 type thm'' = thmID * term;
    22 type rls' = string;
    23 (*.a 'guh'='globally unique handle' is a string unique for each element
    24    of isac's KEStore and persistent over time
    25    (in particular under shifts within the respective hierarchy);
    26    specialty for thys:
    27    # guh NOT resistant agains shifts from one thy to another
    28    (which is the price for Isabelle's design: thy's overwrite ids of subthy's)
    29    # requirement for matchTheory: induce guh from tac + current thy
    30    (see 'fun thy_containing_thm', 'fun thy_containing_rls' etc.)
    31    TODO: introduce to pbl, met.*)
    32 type guh = string;
    33 val e_guh = "e_guh":guh;
    34 
    35 type xml = string;
    36 
    37 (*. eval function calling sml code during rewriting.*)
    38 type eval_fn = (string -> term -> theory -> (string * term) option);
    39 fun e_evalfn (_:'a) (_:term) (_:theory) = NONE:(string * term) option;
    40 (*. op in isa-term 'Const(op,_)' .*)
    41 type calID = string;
    42 type cal = (calID * eval_fn);
    43 (*. fun calculate_ fetches the evaluation-function via this list. *)
    44 type calcID = string;
    45 type calc = (calcID * cal);
    46 
    47 type subs' = (cterm' * cterm') list; (*16.11.00 for FE-KE*)
    48 type subst = (term * term) list; (*here for ets2str*)
    49 val e_subst = []:(term * term) list;
    50 
    51 (*TODO.WN060610 make use of "type rew_ord" total*)
    52 type rew_ord' = string;
    53 val e_rew_ord' = "e_rew_ord" : rew_ord';
    54 type rew_ord_ = subst -> Term.term * Term.term -> bool;
    55 fun dummy_ord (_:subst) (_:term,_:term) = true;
    56 val e_rew_ord_ = dummy_ord;
    57 type rew_ord = rew_ord' * rew_ord_;
    58 val e_rew_ord = dummy_ord; (* TODO.WN071231 clarify identifiers..e_rew_ordX*)
    59 val e_rew_ordX = (e_rew_ord', e_rew_ord_) : rew_ord;
    60 
    61 
    62 datatype rule =
    63   Erule                (*.the empty rule                     .*)
    64 | Thm of (string * Basic_Thm.thm)(*.a theorem, ie (identifier, Thm.thm).*)
    65 | Calc of string *     (*.sml-code manipulating a (sub)term  .*)
    66 	  (string -> term -> theory -> (string * term) option)
    67 | Cal1 of string *     (*.sml-code applied only to whole term
    68                           or left/right-hand-side of eqality .*)
    69 	  (string -> term -> theory -> (string * term) option)
    70 | Rls_ of rls          (*.ie. rule sets may be nested.*)
    71 and scr =
    72     EmptyScr
    73   | Script of term (*for met*)
    74   | Rfuns of {init_state : term ->
    75      (term *          (*the current formula:
    76                         goes locate_gen -> next_tac via istate*)
    77       term *          (*the final formula*)
    78       rule list       (*of reverse rewrite set (#1#)*)
    79 	    list *    (*may be serveral, eg. in norm_rational*)
    80       (rule *         (*Thm (+ Thm generated from Calc) resulting in ...*)
    81        (term *        (*... rewrite with ...*)
    82 	term list))   (*... assumptions*)
    83 	  list),      (*derivation from given term to normalform
    84 		       in reverse order with sym_thm;
    85                        (#1#) could be extracted from here #1*)
    86 
    87 	      normal_form: term -> (term * term list) option,
    88 	      locate_rule: rule list list -> term -> rule
    89 			   -> (rule * (term * term list)) list,
    90 	      next_rule  : rule list list -> term -> rule option,
    91 	      attach_form: rule list list -> term -> term
    92 			   -> (rule * (term * term list)) list}
    93 
    94 and rls =
    95     Erls                          (*for init e_rls*)
    96 
    97   | Rls of (*a confluent and terminating ruleset, in general         *)
    98     {id : string,          (*for trace_rewrite:=true                 *)
    99      preconds : term list, (*unused WN020820                         *)
   100      (*WN060616 for efficiency...
   101       bdvs    : false,       (*set in prep_rls for get_bdvs *)*)
   102      rew_ord  : rew_ord,   (*for rules*)
   103      erls     : rls,       (*for the conditions in rules             *)
   104      srls     : rls,       (*for evaluation of list_fns in script    *)
   105      calc     : calc list, (*for Calculate in scr, set by prep_rls   *)
   106      rules    : rule list,
   107      scr      : scr}       (*Script term: generating intermed.steps  *)
   108   | Seq of (*a sequence of rules to be tried only once               *)
   109     {id : string,          (*for trace_rewrite:=true                 *)
   110      preconds : term list, (*unused 20.8.02                          *)
   111      (*WN060616 for efficiency...
   112       bdvs    : false,       (*set in prep_rls for get_bdvs *)*)
   113      rew_ord  : rew_ord,   (*for rules                               *)
   114      erls     : rls,       (*for the conditions in rules             *)
   115      srls     : rls,       (*for evaluation of list_fns in script    *)
   116      calc     : calc list, (*for Calculate in scr, set by prep_rls   *)
   117      rules    : rule list,
   118      scr      : scr}  (*Script term  (how to restrict type ???)*)
   119   (*Rrls call SML-code and simulate an rls
   120     difference: there is always _ONE_ redex rewritten in 1 call,
   121     thus wrap Rrls by: Rls (Rls_ ...)*)
   122 
   123   | Rrls of (* for 'reverse rewriting' by SML-functions instead Script        *)
   124     {id : string,          (* for trace_rewrite := true                       *)
   125      prepat  : (term list *(* preconds, eval with subst from pattern;
   126                               if [HOLogic.true_const], match decides alone    *)
   127 		term )     (* pattern matched with current (sub)term          *)
   128 		   list,   (* meta-conjunction is or                          *)
   129      rew_ord  : rew_ord,   (* for rules                                       *)
   130      erls     : rls,       (* for the conditions in rules and preconds        *)
   131      calc     : calc list, (* for Calculate in scr, set automatic.in prep_rls *)
   132      scr      : scr};      (* Rfuns {...}  (how to restrict type ???)         *)
   133 (*1.8.02 ad (how to restrict type ???): scr should be usable indepentently
   134   from rls, and then contain both Script _AND_ Rfuns !!!*)
   135 
   136 fun thy2ctxt' thy' = ProofContext.init_global (Thy_Info.get_theory thy');(*FIXXXME thy-ctxt*)
   137 fun thy2ctxt thy = ProofContext.init_global thy;(*FIXXXME thy-ctxt*)
   138 
   139 fun Isac _ = ProofContext.theory_of (thy2ctxt' "Isac"); (*@{theory "Isac"}*)
   140 
   141 val e_rule = Thm ("refl", @{thm refl});
   142 fun id_of_thm (Thm (id, _)) = id
   143   | id_of_thm _ = error "id_of_thm";
   144 fun thm_of_thm (Thm (_, thm)) = thm
   145   | thm_of_thm _ = error "thm_of_thm";
   146 fun rep_thm_G' (Thm (thmid, thm)) = (thmid, thm);
   147 
   148 fun thmID_of_derivation_name dn = last_elem (space_explode "." dn);
   149 fun thyID_of_derivation_name dn = hd (space_explode "." dn);
   150 
   151 fun eq_thmI ((thmid1 : thmID, _ : thm), (thmid2 : thmID, _ : thm)) =
   152     (strip_thy thmid1) = (strip_thy thmid2);
   153 (*WN120201 weakened*)
   154 fun eq_thmI ((thmid1 : thmID, _ : thm), (thmid2 : thmID, _)) = thmid1 = thmid2;
   155 (*version typed weaker WN100910*)
   156 fun eq_thmI' ((thmid1, _), (thmid2, _)) =
   157     (thmID_of_derivation_name thmid1) = (thmID_of_derivation_name thmid2);
   158 
   159 
   160 val string_of_thm =  Thm.get_name_hint; (*FIXME.2009*)
   161 (*check for [.] as caused by "fun assoc_thm'"*)
   162 fun string_of_thmI thm =
   163     let val ct' = (de_quote o string_of_thm) thm
   164 	val (a, b) = split_nlast (5, Symbol.explode ct')
   165     in case b of
   166 	   [" ", " ","[", ".", "]"] => implode a
   167 	 | _ => ct'
   168     end;
   169 
   170 (*.id requested for all, Rls,Seq,Rrls.*)
   171 fun id_rls Erls = "e_rls" (*WN060714 quick and dirty: recursive defs!*)
   172   | id_rls (Rls {id,...}) = id
   173   | id_rls (Seq {id,...}) = id
   174   | id_rls (Rrls {id,...}) = id;
   175 val rls2str = id_rls;
   176 fun id_rule (Thm (id, _)) = id
   177   | id_rule (Calc (id, _)) = id
   178   | id_rule (Rls_ rls) = id_rls rls;
   179 
   180 fun get_rules (Rls {rules,...}) = rules
   181   | get_rules (Seq {rules,...}) = rules
   182   | get_rules (Rrls _) = [];
   183 
   184 fun rule2str Erule = "Erule"
   185   | rule2str (Thm (str, thm)) = "Thm (\""^str^"\","^(string_of_thmI thm)^")"
   186   | rule2str (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   187   | rule2str (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   188   | rule2str (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   189 fun rule2str' Erule = "Erule"
   190   | rule2str' (Thm (str, thm)) = "Thm (\""^str^"\",\"\")"
   191   | rule2str' (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   192   | rule2str' (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   193   | rule2str' (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   194 
   195 (*WN080102 compare eq_rule ?!?*)
   196 fun eqrule (Thm (id1,_), Thm (id2,_)) = id1 = id2
   197   | eqrule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   198   | eqrule (Cal1 (id1,_), Cal1 (id2,_)) = id1 = id2
   199   | eqrule (Rls_ _, Rls_ _) = false (*{id=id1}{id=id2} = id1 = id2 FIXXME*)
   200   | eqrule _ = false;
   201 
   202 
   203 type rrlsstate =      (*state for reverse rewriting*)
   204      (term *          (*the current formula:
   205                         goes locate_gen -> next_tac via istate*)
   206       term *          (*the final formula*)
   207       rule list       (*of reverse rewrite set (#1#)*)
   208 	    list *    (*may be serveral, eg. in norm_rational*)
   209       (rule *         (*Thm (+ Thm generated from Calc) resulting in ...*)
   210        (term *        (*... rewrite with ...*)
   211 	term list))   (*... assumptions*)
   212 	  list);      (*derivation from given term to normalform
   213 		       in reverse order with sym_thm;
   214                        (#1#) could be extracted from here #1*)
   215 val e_type = Type("empty",[]);
   216 val a_type = TFree("'a",[]);
   217 val e_term = Const("empty",e_type);
   218 val a_term = Free("empty",a_type);
   219 val e_rrlsstate = (e_term,e_term,[[e_rule]],[(e_rule,(e_term,[]))]):rrlsstate;
   220 
   221 
   222 
   223 
   224 (*22.2.02: ging auf Linux nicht (Stefan)
   225 val e_scr = Script ((term_of o the o (parse thy)) "e_script");*)
   226 val e_term = Const("empty", Type("'a", []));
   227 val e_scr = Script e_term;
   228 
   229 
   230 (*ad thm':
   231    there are two kinds of theorems ...
   232    (1) known by isabelle
   233    (2) not known, eg. calc_thm, instantiated rls
   234        the latter have a thmid "#..."
   235    and thus outside isa we ALWAYS transport both (thmid,string_of_thmI)
   236    and have a special assoc_thm / assoc_rls in this interface      *)
   237 type theory' = string; (* = domID ^".thy" WN.101011 ABOLISH !*)
   238 type domID = string;   (* domID ^".thy" = theory' WN.101011 replace by thyID*)
   239 type thyID = string;    (*WN.3.11.03 TODO: replace domID with thyID*)
   240 
   241 fun string_of_thy thy = Context.theory_name thy: theory';
   242 val theory2domID = string_of_thy;
   243 val theory2thyID = (get_thy o string_of_thy) : theory -> thyID;
   244 val theory2theory' = string_of_thy;
   245 val theory2str = string_of_thy; (*WN050903 ..most consistent naming*)
   246 val theory2str' = implode o (drop_last_n 4) o Symbol.explode o string_of_thy;
   247 (*> theory2str' (Thy_Info.get_theory "Isac");
   248 al it = "Isac" : string
   249 *)
   250 
   251 fun thyID2theory' (thyID:thyID) = thyID;
   252 (*
   253     let val ss = Symbol.explode thyID
   254 	val ext = implode (takelast (4, ss))
   255     in if ext = ".thy" then thyID : theory' (*disarm abuse of thyID*)
   256        else thyID ^ ".thy"
   257     end;
   258 *)
   259 (* thyID2theory' "Isac" (*ok*);
   260 val it = "Isac" : theory'
   261  > thyID2theory' "Isac" (*abuse, goes ok...*);
   262 val it = "Isac" : theory'
   263 *)
   264 
   265 fun theory'2thyID (theory':theory') = theory';
   266 (*
   267     let val ss = Symbol.explode theory'
   268 	val ext = implode (takelast (4, ss))
   269     in if ext = ".thy" then ((implode o (drop_last_n 4)) ss) : thyID
   270        else theory' (*disarm abuse of theory'*)
   271     end;
   272 *)
   273 (* theory'2thyID "Isac";
   274 val it = "Isac" : thyID
   275 > theory'2thyID "Isac";
   276 val it = "Isac" : thyID*)
   277 
   278 
   279 (*. WN0509 discussion:
   280 #############################################################################
   281 #   How to manage theorys in subproblems wrt. the requirement,              #
   282 #   that scripts should be re-usable ?                                      #
   283 #############################################################################
   284 
   285     eg. 'Script Solve_rat_equation' calls 'SubProblem (RatEq',..'
   286     which would not allow to 'solve (y'' = -M_b / EI, M_b)' by this script
   287     because Biegelinie.thy is subthy of RatEq.thy and thus Biegelinie.M_b
   288     is unknown in RatEq.thy and M_b cannot be parsed into the scripts guard
   289     (see match_ags).
   290 
   291     Preliminary solution:
   292     # the thy in 'SubProblem (thy', pbl, arglist)' is not taken automatically,
   293     # instead the 'maxthy (rootthy pt) thy' is taken for each subpbl
   294     # however, a thy specified by the user in the rootpbl may lead to
   295       errors in far-off subpbls (which are not yet reported properly !!!)
   296       and interactively specifiying thys in subpbl is not very relevant.
   297 
   298     Other solutions possible:
   299     # always parse and type-check with Thy_Info.get_theory "Isac"
   300       (rejected tue to the vague idea eg. to re-use equations for R in C etc.)
   301     # regard the subthy-relation in specifying thys of subpbls
   302     # specifically handle 'SubProblem (undefined, pbl, arglist)'
   303     # ???
   304 .*)
   305 (*WN0509 TODO "ProtoPure" ... would be more consistent
   306   with assoc_thy <--> theory2theory' +FIXME assoc_thy "e_domID" -> Script.thy*)
   307 val e_domID = "e_domID":domID;
   308 
   309 (*the key into the hierarchy ob theory elements*)
   310 type theID = string list;
   311 val e_theID = ["e_theID"];
   312 val theID2str = strs2str;
   313 (*theID eg. is ["IsacKnowledge", "Test", "Rulesets", "ac_plus_times"]*)
   314 fun theID2thyID (theID:theID) =
   315     if length theID >= 3 then (last_elem o (drop_last_n 2)) theID : thyID
   316     else error ("theID2thyID called with "^ theID2str theID);
   317 
   318 (*the key into the hierarchy ob problems*)
   319 type pblID = string list; (* domID::...*)
   320 val e_pblID = ["e_pblID"]:pblID;
   321 val pblID2str = strs2str;
   322 
   323 (*the key into the hierarchy ob methods*)
   324 type metID = string list;
   325 val e_metID = ["e_metID"]:metID;
   326 val metID2str = strs2str;
   327 
   328 (*either theID or pblID or metID*)
   329 type kestoreID = string list;
   330 val e_kestoreID = ["e_kestoreID"];
   331 val kestoreID2str = strs2str;
   332 
   333 (*for distinction of contexts*)
   334 datatype ketype = Exp_ | Thy_ | Pbl_ | Met_;
   335 fun ketype2str Exp_ = "Exp_"
   336   | ketype2str Thy_ = "Thy_"
   337   | ketype2str Pbl_ = "Pbl_"
   338   | ketype2str Met_ = "Met_";
   339 fun ketype2str' Exp_ = "Example"
   340   | ketype2str' Thy_ = "Theory"
   341   | ketype2str' Pbl_ = "Problem"
   342   | ketype2str' Met_ = "Method";
   343 
   344 (*see 'How to manage theorys in subproblems' at 'type thyID'*)
   345 val theory'  = Unsynchronized.ref ([]:(theory' * theory) list);
   346 
   347 (*.all theories defined for Scripts, recorded in Scripts/Script.ML;
   348    in order to distinguish them from general IsacKnowledge defined later on.*)
   349 val script_thys = Unsynchronized.ref ([] : (theory' * theory) list);
   350 
   351 
   352 (*rewrite orders, also stored in 'type met' and type 'and rls'
   353   The association list is required for 'rewrite.."rew_ord"..'
   354   WN0509 tests not well-organized: see smltest/Knowledge/termorder.sml*)
   355 val rew_ord' =
   356     Unsynchronized.ref
   357         ([]:(rew_ord' *        (*the key for the association list         *)
   358 	     (subst 	       (*the bound variables - they get high order*)
   359 	      -> (term * term) (*(t1, t2) to be compared                  *)
   360 	      -> bool))        (*if t1 <= t2 then true else false         *)
   361 		list);         (*association list                         *)
   362 
   363 rew_ord' := overwritel (!rew_ord', [("e_rew_ord", e_rew_ord),
   364 				    ("dummy_ord", dummy_ord)]);
   365 
   366 
   367 (*WN060120 a hack to get alltogether run again with minimal effort:
   368   theory' is inserted for creating thy_hierarchy; calls for assoc_rls
   369   need not be called*)
   370 val ruleset' = Unsynchronized.ref ([]:(rls' * (theory' * rls)) list);
   371 
   372 (*FIXME.040207 calclist': used by prep_rls, NOT in met*)
   373 val calclist'= Unsynchronized.ref ([]: calc list);
   374 
   375 (*.the hierarchy of thydata.*)
   376 
   377 (*.'a is for pbt | met.*)
   378 (*WN.24.4.03 -"- ... type parameters; afterwards naming inconsistent*)
   379 datatype 'a ptyp =
   380 	 Ptyp of string *   (*element within pblID*)
   381 		 'a list *  (*several pbts with different domIDs/thy
   382 			      TODO: select by subthy (isaref.p.69)
   383 			      presently only _ONE_ elem*)
   384 		 ('a ptyp) list;   (*the children nodes*)
   385 
   386 (*.datatype for collecting thydata for hierarchy.*)
   387 (*WN060720 more consistent naming would be 'type thyelem' or 'thelem'*)
   388 (*WN0606 Htxt contains html which does not belong to the sml-kernel*)
   389 datatype thydata = Html of {guh: guh,
   390 			    coursedesign: authors,
   391 			    mathauthors: authors,
   392 			    html: string} (*html; for demos before database*)
   393 		 | Hthm of {guh: guh,
   394 			    coursedesign: authors,
   395 			    mathauthors: authors,
   396 			    thm: term}
   397 		 | Hrls of {guh: guh,
   398 			    coursedesign: authors,
   399 			    mathauthors: authors,
   400 			    (*like   vvvvvvvvvvvvv val ruleset'
   401 			     WN060711 redesign together !*)
   402 			    thy_rls: (thyID * rls)}
   403 		 | Hcal of {guh: guh,
   404 			    coursedesign: authors,
   405 			    mathauthors: authors,
   406 			    calc: calc}
   407 		 | Hord of {guh: guh,
   408 			    coursedesign: authors,
   409 			    mathauthors: authors,
   410 			    ord: (subst -> (term * term) -> bool)};
   411 val e_thydata = Html {guh="e_guh", coursedesign=[], mathauthors=[], html=""};
   412 
   413 type thehier = (thydata ptyp) list;
   414 val thehier = Unsynchronized.ref ([] : thehier); (*WN101011 make argument, del*)
   415 
   416 (* an association list, gets the value once in Isac.ML.
   417    stores Isabelle's thms as terms for compatibility with Theory.axioms_of.
   418    WN1-1-28 make this data arguments and del ref ?*)
   419 val isab_thm_thy = Unsynchronized.ref ([] : (thmID * (thyID * term)) list);
   420 
   421 
   422 type path = string;
   423 type filename = string;
   424 
   425 (*val xxx = fn: a b => (a,b);   ??? fun-definition ???*)
   426 local
   427     fun ii (_:term) = e_rrlsstate;
   428     fun no (_:term) = SOME (e_term,[e_term]);
   429     fun lo (_:rule list list) (_:term) (_:rule) = [(e_rule,(e_term,[e_term]))];
   430     fun ne (_:rule list list) (_:term) = SOME e_rule;
   431     fun fo (_:rule list list) (_:term) (_:term) = [(e_rule,(e_term,[e_term]))];
   432 in
   433 val e_rfuns = Rfuns {init_state=ii,normal_form=no,locate_rule=lo,
   434 		     next_rule=ne,attach_form=fo};
   435 end;
   436 
   437 val e_rls =
   438   Rls{id = "e_rls",
   439       preconds = [],
   440       rew_ord = ("dummy_ord", dummy_ord),
   441       erls = Erls,srls = Erls,
   442       calc = [],
   443       rules = [], scr = EmptyScr}:rls;
   444 val e_rrls = Rrls {id = "e_rrls",
   445 		   prepat = [],
   446 		   rew_ord = ("dummy_ord", dummy_ord),
   447 		   erls = Erls,
   448 		   calc = [],
   449 		   (*asm_thm=[],*)
   450 		   scr=e_rfuns}:rls;
   451 ruleset' := overwritel (!ruleset', [("e_rls",("Tools",e_rls)),
   452 				    ("e_rrls",("Tools",e_rrls))
   453 				    ]);
   454 
   455 fun rep_rls (Rls {id,preconds,rew_ord,erls,srls,calc,(*asm_thm,*)rules,scr}) =
   456   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   457    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   458   | rep_rls (Seq {id,preconds,rew_ord,erls,srls,calc,(*asm_thm,*)rules,scr}) =
   459   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   460    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   461   | rep_rls Erls = rep_rls e_rls
   462   | rep_rls (Rrls {id,...})  = rep_rls e_rls
   463     (*error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id)*);
   464 (*| rep_rls (Seq {id,...})  =
   465     error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id);
   466 --1.7.03*)
   467 fun rep_rrls
   468 	(Rrls {id,(*asm_thm,*) calc, erls, prepat, rew_ord,
   469 	       scr=Rfuns
   470 		       {attach_form,init_state,locate_rule,
   471 			next_rule,normal_form}}) =
   472     {id=id,(*asm_thm=asm_thm,*) calc=calc, erls=erls, prepat=prepat,
   473      rew_ord=rew_ord, attach_form=attach_form, init_state=init_state,
   474      locate_rule=locate_rule, next_rule=next_rule, normal_form=normal_form}
   475   | rep_rrls (Rls {id,...}) =
   476     error ("rep_rrls doesn't take apart (normal) rule-sets: "^id)
   477   | rep_rrls (Seq {id,...}) =
   478     error ("rep_rrls doesn't take apart (normal) rule-sets: "^id);
   479 
   480 fun append_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   481 			rules =rs,scr=sc}) r =
   482     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   483 	 rules = rs @ r,scr=sc}:rls)
   484   | append_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   485 			rules =rs,scr=sc}) r =
   486     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   487 	 rules = rs @ r,scr=sc}:rls)
   488   | append_rls id (Rrls _) _ =
   489     error ("append_rls: not for reverse-rewrite-rule-set "^id);
   490 
   491 (*. are _atomic_ rules equal ?.*)
   492 (*WN080102 compare eqrule ?!?*)
   493 fun eq_rule (Thm (thm1,_), Thm (thm2,_)) = thm1 = thm2
   494   | eq_rule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   495   | eq_rule (Rls_ rls1, Rls_ rls2) = id_rls rls1 = id_rls rls2
   496   (*id_rls checks for Rls, Seq, Rrls*)
   497   | eq_rule _ = false;
   498 
   499 fun merge_rls _ Erls rls = rls
   500   | merge_rls _ rls Erls = rls
   501   | merge_rls id
   502 	(Rls {id=id1,preconds=pc1,rew_ord=ro1,erls=er1,srls=sr1,calc=ca1,
   503 	      (*asm_thm=at1,*)rules =rs1,scr=sc1})
   504 	(r2 as Rls {id=id2,preconds=pc2,rew_ord=ro2,erls=er2,srls=sr2,calc=ca2,
   505 	      (*asm_thm=at2,*)rules =rs2,scr=sc2}) =
   506 	(Rls {id=id,preconds=pc1 @ ((#preconds o rep_rls) r2),
   507 	      rew_ord=ro1,erls=merge_rls "" er1 er2(*er1*),
   508 	      srls=merge_rls ("merged_"^id1^"_"^((#id o rep_rls) r2)) sr1
   509 			     ((#srls o rep_rls) r2),
   510 	      calc=ca1 @ ((#calc o rep_rls) r2),
   511 	      (*asm_thm=at1 @ ((#asm_thm o rep_rls) r2),*)
   512 	      rules = gen_union eq_rule rule2str (rs1, (#rules o rep_rls) r2),
   513 	      scr=sc1}:rls)
   514   | merge_rls id
   515 	(Seq {id=id1,preconds=pc1,rew_ord=ro1,erls=er1,srls=sr1,calc=ca1,
   516 	      (*asm_thm=at1,*)rules =rs1,scr=sc1})
   517 	(r2 as Seq {id=id2,preconds=pc2,rew_ord=ro2,erls=er2,srls=sr2,calc=ca2,
   518 	      (*asm_thm=at2,*)rules =rs2,scr=sc2}) =
   519 	(Seq {id=id,preconds=pc1 @ ((#preconds o rep_rls) r2),
   520 	      rew_ord=ro1,erls=merge_rls "" er1 er2(*er1*),
   521 	      srls=merge_rls ("merged_"^id1^"_"^((#id o rep_rls) r2)) sr1
   522 			     ((#srls o rep_rls) r2),
   523 	      calc=ca1 @ ((#calc o rep_rls) r2),
   524 	      (*asm_thm=at1 @ ((#asm_thm o rep_rls) r2),*)
   525 	      rules = gen_union eq_rule rule2str (rs1, (#rules o rep_rls) r2),
   526 	      scr=sc1}:rls)
   527   | merge_rls _ _ _ =
   528     error "merge_rls: not for reverse-rewrite-rule-sets\
   529 		\and not for mixed Rls -- Seq";
   530 fun remove_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   531 		     (*asm_thm=at,*)rules =rs,scr=sc}) r =
   532     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   533 	 (*asm_thm=at,*)rules = gen_rems eq_rule (rs, r),
   534 	 scr=sc}:rls)
   535   | remove_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   536 		     (*asm_thm=at,*)rules =rs,scr=sc}) r =
   537     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   538 	 (*asm_thm=at,*)rules = gen_rems eq_rule (rs, r),
   539 	 scr=sc}:rls)
   540   | remove_rls id (Rrls _) _ = error
   541                    ("remove_rls: not for reverse-rewrite-rule-set "^id);
   542 
   543 (*!!!> gen_rems (op=) ([1,2,3,4], [3,4,5]);
   544 val it = [1, 2] : int list*)
   545 
   546 (*elder version: migrated 3 calls in smtest to memrls
   547 fun mem_rls id rls =
   548     case find_first ((curry op=) id) (map id_rule ((#rules o rep_rls) rls)) of
   549 	SOME _ => true | NONE => false;*)
   550 fun memrls r (Rls {rules,...}) = gen_mem eqrule (r, rules)
   551   | memrls r (Seq {rules,...}) = gen_mem eqrule (r, rules)
   552   | memrls r _ = error ("memrls: incomplete impl. r= "^(rule2str r));
   553 fun rls_get_thm rls (id: xstring) =
   554     case find_first (curry eq_rule e_rule)
   555 		    ((#rules o rep_rls) rls) of
   556 	SOME thm => SOME thm | NONE => NONE;
   557 
   558 fun assoc' ([], key) = error ("ME_Isa: '"^key^"' not known")
   559   | assoc' ((keyi, xi) :: pairs, key) =
   560       if key = keyi then SOME xi else assoc' (pairs, key);
   561 
   562 (*100818 fun assoc_thy (thy:theory') = ((the o assoc')(!theory',thy))
   563   handle _ => error ("ME_Isa: thy '"^thy^"' not in system");*)
   564 fun assoc_thy (thy:theory') =
   565     if thy = "e_domID" then (Thy_Info.get_theory "Script") (*lower bound of Knowledge*)
   566     else (Thy_Info.get_theory thy)
   567          handle _ => error ("ME_Isa: thy '" ^ thy ^ "' not in system");
   568 
   569 (*.associate an rls-identifier with an rls; related to 'fun assoc_rls'; WN111014?fun get_rls ?
   570    these are NOT compatible to "fun assoc_thm'" in that they do NOT handle
   571    overlays by re-using an identifier in different thys.*)
   572 fun assoc_rls (rls:rls') = ((#2 o the o assoc')(!ruleset',rls))
   573   handle _ => error ("ME_Isa: '"^rls^"' not in system");
   574 (*fun assoc_rls (rls:rls') = ((the o assoc')(!ruleset',rls))
   575   handle _ => error ("ME_Isa: '"^rls^"' not in system");*)
   576 
   577 (*.overwrite an element in an association list and pair it with a thyID
   578    in order to create the thy_hierarchy;
   579    overwrites existing rls' even if they are defined in a different thy;
   580    this is related to assoc_rls, TODO.WN060120: assoc_rew_ord, assoc_calc;.*)
   581 (*WN060120 ...these are NOT compatible to "fun assoc_thm'" in that
   582    they do NOT handle overlays by re-using an identifier in different thys;
   583    "thyID.rlsID" would be a good solution, if the "." would be possible
   584    in scripts...
   585    actually a hack to get alltogether run again with minimal effort*)
   586 fun insthy thy' (rls', rls) = (rls', (thy', rls));
   587 fun overwritelthy thy (al, bl:(rls' * rls) list) =
   588     let val bl' = map (insthy ((get_thy o theory2theory') thy)) bl
   589     in overwritel (al, bl') end;
   590 
   591 fun assoc_rew_ord ro = ((the o assoc') (!rew_ord',ro))
   592   handle _ => error ("ME_Isa: rew_ord '"^ro^"' not in system");
   593 (*get the string for stac from rule*)
   594 fun assoc_calc ([], key) = error ("assoc_calc: '"^ key ^"' not found")
   595   | assoc_calc ((calc, (keyi, xi)) :: pairs, key) =
   596       if key = keyi then calc else assoc_calc (pairs, key);
   597 (*only used for !calclist'...*)
   598 fun assoc1 ([], key) = error ("assoc1 (for met.calc=): '"^ key
   599 				    ^"' not found")
   600   | assoc1 ((all as (keyi, _)) :: pairs, key) =
   601       if key = keyi then all else assoc1 (pairs, key);
   602 
   603 (*TODO.WN080102 clarify usage of type cal and type calc..*)
   604 fun calID2calcID (calID : calID) =
   605     let fun ass [] = error ("calID2calcID: "^calID^"not in calclist'")
   606 	  | ass ((calci, (cali, eval_fn))::ids) =
   607 	    if calID = cali then calci
   608 	    else ass ids
   609     in ass (!calclist') : calcID end;
   610 
   611 fun term2str t = Print_Mode.setmp [] (Syntax.string_of_term
   612 (ProofContext.init_global (Thy_Info.get_theory "Isac"))) t;
   613 
   614 fun terms2str ts = (strs2str o (map term2str )) ts;
   615 (*terms2str [t1,t2] = "[\"1 + 2\",\"abc\"]";*)
   616 fun terms2str' ts = (strs2str' o (map term2str )) ts;
   617 (*terms2str' [t1,t2] = "[1 + 2,abc]";*)
   618 fun terms2strs ts = (map term2str) ts;
   619 (*terms2strs [t1,t2] = ["1 + 2", "abc"];*)
   620 
   621 fun termopt2str (SOME t) = "SOME " ^ term2str t
   622   | termopt2str NONE = "NONE";
   623 
   624 fun type2str typ =
   625   Print_Mode.setmp [] (Syntax.string_of_typ (thy2ctxt' "Isac")) typ;
   626 val string_of_typ = type2str;
   627 fun string_of_typ_thy thy typ =
   628   Print_Mode.setmp [] (Syntax.string_of_typ (thy2ctxt thy)) typ;
   629 
   630 fun subst2str (s:subst) =
   631     (strs2str o
   632      (map (linefeed o pair2str o
   633 	   (apsnd term2str) o
   634 	   (apfst term2str)))) s;
   635 fun subst2str' (s:subst) =
   636     (strs2str' o
   637      (map (pair2str o
   638 	   (apsnd term2str) o
   639 	   (apfst term2str)))) s;
   640 (*> subst2str' [(str2term "bdv", str2term "x"),
   641 		(str2term "bdv_2", str2term "y")];
   642 val it = "[(bdv, x)]" : string
   643 *)
   644 val env2str = subst2str;
   645 
   646 
   647 (*recursive defs:*)
   648 fun scr2str (Script s) = "Script "^(term2str s)
   649   | scr2str (Rfuns _)  = "Rfuns";
   650 
   651 
   652 fun maxthy thy1 thy2 = if Theory.subthy (thy1, thy2) then thy2 else thy1;
   653 
   654 
   655 (*.trace internal steps of isac's rewriter*)
   656 val trace_rewrite = Unsynchronized.ref false;
   657 (*.depth of recursion in traces of the rewriter, if trace_rewrite:=true.*)
   658 val depth = Unsynchronized.ref 99999;
   659 (*.no of rewrites exceeding this int -> NO rewrite.*)
   660 (*WN060829 still unused...*)
   661 val lim_rewrite = Unsynchronized.ref 99999;
   662 (*.no of derivation-elements exceeding this int -> SOME derivation-elements.*)
   663 val lim_deriv = Unsynchronized.ref 100;
   664 (*.switch for checking guhs unique before storing a pbl or met;
   665    set true at startup (done at begin of ROOT.ML)
   666    set false for editing IsacKnowledge (done at end of ROOT.ML).*)
   667 val check_guhs_unique = Unsynchronized.ref true;
   668 
   669 
   670 datatype lrd = (*elements of a path (=loc_) into an Isabelle term*)
   671 	 L     (*go left at $*)
   672        | R     (*go right at $*)
   673        | D;     (*go down at Abs*)
   674 type loc_ = lrd list;
   675 fun ldr2str L = "L"
   676   | ldr2str R = "R"
   677   | ldr2str D = "D";
   678 fun loc_2str (k:loc_) = (strs2str' o (map ldr2str)) k;
   679 
   680 (*
   681 end (*struct*)
   682 *)