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