src/Tools/isac/calcelems.sml
author Walther Neuper <neuper@ist.tugraz.at>
Sat, 25 Sep 2010 16:49:33 +0200
branchisac-update-Isa09-2
changeset 38022 e6d356fc4d38
parent 38013 e4f42a63d665
child 38024 20231cdf39e7
permissions -rw-r--r--
rewrite_ returns assumptions without Trueprop (as was in Isabelle2002)

# added redirect_tracing to handle looping
# in src/../isac/* replaced all writeln with tracing
TODO: review the tracing except in ProgLang/calculate.sml, rewrite.sml
in particular in xmlsrc/*
     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 (*version typed weaker WN100910*)
   154 fun eq_thmI' ((thmid1, _), (thmid2, _)) =
   155     (strip_thy thmid1) = (strip_thy thmid2);
   156 
   157 
   158 val string_of_thm =  Thm.get_name_hint; (*FIXME.2009*)
   159 (*check for [.] as caused by "fun assoc_thm'"*)
   160 fun string_of_thmI thm =
   161     let val ct' = (de_quote o string_of_thm) thm
   162 	val (a, b) = split_nlast (5, explode ct')
   163     in case b of 
   164 	   [" ", " ","[", ".", "]"] => implode a
   165 	 | _ => ct'
   166     end;
   167 
   168 (*.id requested for all, Rls,Seq,Rrls.*)
   169 fun id_rls Erls = "e_rls" (*WN060714 quick and dirty: recursive defs!*)
   170   | id_rls (Rls {id,...}) = id
   171   | id_rls (Seq {id,...}) = id
   172   | id_rls (Rrls {id,...}) = id;
   173 val rls2str = id_rls;
   174 fun id_rule (Thm (id, _)) = id
   175   | id_rule (Calc (id, _)) = id
   176   | id_rule (Rls_ rls) = id_rls rls;
   177 
   178 fun get_rules (Rls {rules,...}) = rules
   179   | get_rules (Seq {rules,...}) = rules
   180   | get_rules (Rrls _) = [];
   181 
   182 fun rule2str Erule = "Erule"
   183   | rule2str (Thm (str, thm)) = "Thm (\""^str^"\","^(string_of_thmI thm)^")"
   184   | rule2str (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   185   | rule2str (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   186   | rule2str (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   187 fun rule2str' Erule = "Erule"
   188   | rule2str' (Thm (str, thm)) = "Thm (\""^str^"\",\"\")"
   189   | rule2str' (Calc (str,f))  = "Calc (\""^str^"\",fn)"
   190   | rule2str' (Cal1 (str,f))  = "Cal1 (\""^str^"\",fn)"
   191   | rule2str' (Rls_ rls) = "Rls_ (\""^id_rls rls^"\")";
   192 
   193 (*WN080102 compare eq_rule ?!?*)
   194 fun eqrule (Thm (id1,_), Thm (id2,_)) = id1 = id2
   195   | eqrule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   196   | eqrule (Cal1 (id1,_), Cal1 (id2,_)) = id1 = id2
   197   | eqrule (Rls_ _, Rls_ _) = false (*{id=id1}{id=id2} = id1 = id2 FIXXME*)
   198   | eqrule _ = false;
   199 
   200 
   201 type rrlsstate =      (*state for reverse rewriting*)
   202      (term *          (*the current formula: 
   203                         goes locate_gen -> next_tac via istate*)
   204       term *          (*the final formula*)
   205       rule list       (*of reverse rewrite set (#1#)*)
   206 	    list *    (*may be serveral, eg. in norm_rational*)
   207       (rule *         (*Thm (+ Thm generated from Calc) resulting in ...*)
   208        (term *        (*... rewrite with ...*)
   209 	term list))   (*... assumptions*)
   210 	  list);      (*derivation from given term to normalform
   211 		       in reverse order with sym_thm; 
   212                        (#1#) could be extracted from here #1*)
   213 val e_type = Type("empty",[]);
   214 val a_type = TFree("'a",[]);
   215 val e_term = Const("empty",e_type);
   216 val a_term = Free("empty",a_type);
   217 val e_rrlsstate = (e_term,e_term,[[e_rule]],[(e_rule,(e_term,[]))]):rrlsstate;
   218 
   219 
   220 
   221 
   222 (*22.2.02: ging auf Linux nicht (Stefan)
   223 val e_scr = Script ((term_of o the o (parse thy)) "e_script");*)
   224 val e_term = Const("empty", Type("'a", []));
   225 val e_scr = Script e_term;
   226 
   227 
   228 (*ad thm':
   229    there are two kinds of theorems ...
   230    (1) known by isabelle
   231    (2) not known, eg. calc_thm, instantiated rls
   232        the latter have a thmid "#..."
   233    and thus outside isa we ALWAYS transport both (thmid,string_of_thmI)
   234    and have a special assoc_thm / assoc_rls in this interface      *)
   235 type theory' = string; (* = domID ^".thy" *)
   236 type domID = string;   (* domID ^".thy" = theory' TODO.11.03replace by thyID*)
   237 type thyID = string;    (*WN.3.11.03 TODO: replace domID with thyID*)
   238 
   239 fun string_of_thy thy = Context.theory_name thy: theory';
   240 val theory2domID = string_of_thy;
   241 val theory2thyID = (get_thy o string_of_thy) : theory -> thyID;
   242 val theory2theory' = string_of_thy;
   243 val theory2str = string_of_thy; (*WN050903 ..most consistent naming*)
   244 val theory2str' = implode o (drop_last_n 4) o explode o string_of_thy;
   245 (*> theory2str' Isac.thy;
   246 al it = "Isac" : string
   247 *)
   248 
   249 fun thyID2theory' (thyID:thyID) =
   250     let val ss = explode thyID
   251 	val ext = implode (takelast (4, ss))
   252     in if ext = ".thy" then thyID : theory' (*disarm abuse of thyID*)
   253        else thyID ^ ".thy"
   254     end;
   255 (* thyID2theory' "Isac" (*ok*);
   256 val it = "Isac.thy" : theory'
   257  > thyID2theory' "Isac.thy" (*abuse, goes ok...*);
   258 val it = "Isac.thy" : theory'
   259 *)
   260 
   261 fun theory'2thyID (theory':theory') =
   262     let val ss = explode theory'
   263 	val ext = implode (takelast (4, ss))
   264     in if ext = ".thy" then ((implode o (drop_last_n 4)) ss) : thyID
   265        else theory' (*disarm abuse of theory'*)
   266     end;
   267 (* theory'2thyID "Isac.thy";
   268 val it = "Isac" : thyID
   269 > theory'2thyID "Isac";
   270 val it = "Isac" : thyID*)
   271 
   272 
   273 (*. WN0509 discussion:
   274 #############################################################################
   275 #   How to manage theorys in subproblems wrt. the requirement,              #
   276 #   that scripts should be re-usable ?                                      #
   277 #############################################################################
   278 
   279     eg. 'Script Solve_rat_equation' calls 'SubProblem (RatEq',..'
   280     which would not allow to 'solve (y'' = -M_b / EI, M_b)' by this script
   281     because Biegelinie.thy is subthy of RatEq.thy and thus Biegelinie.M_b 
   282     is unknown in RatEq.thy and M_b cannot be parsed into the scripts guard
   283     (see match_ags).
   284 
   285     Preliminary solution:
   286     # the thy in 'SubProblem (thy', pbl, arglist)' is not taken automatically,
   287     # instead the 'maxthy (rootthy pt) thy' is taken for each subpbl
   288     # however, a thy specified by the user in the rootpbl may lead to 
   289       errors in far-off subpbls (which are not yet reported properly !!!) 
   290       and interactively specifiying thys in subpbl is not very relevant.
   291 
   292     Other solutions possible:
   293     # always parse and type-check with theory "Isac"
   294       (rejected tue to the vague idea eg. to re-use equations for R in C etc.)
   295     # regard the subthy-relation in specifying thys of subpbls
   296     # specifically handle 'SubProblem (undefined, pbl, arglist)'
   297     # ???
   298 .*)
   299 (*WN0509 TODO "ProtoPure" ... would be more consistent 
   300   with assoc_thy <--> theory2theory' +FIXME assoc_thy "e_domID" -> Script.thy*)
   301 val e_domID = "e_domID":domID;
   302 
   303 (*the key into the hierarchy ob theory elements*)
   304 type theID = string list;
   305 val e_theID = ["e_theID"];
   306 val theID2str = strs2str;
   307 (*theID eg. is ["IsacKnowledge", "Test", "Rulesets", "ac_plus_times"]*)
   308 fun theID2thyID (theID:theID) =
   309     if length theID >= 3 then (last_elem o (drop_last_n 2)) theID : thyID
   310     else raise error ("theID2thyID called with "^ theID2str theID);
   311 
   312 (*the key into the hierarchy ob problems*)
   313 type pblID = string list; (* domID::...*)
   314 val e_pblID = ["e_pblID"]:pblID;
   315 val pblID2str = strs2str;
   316 
   317 (*the key into the hierarchy ob methods*)
   318 type metID = string list;
   319 val e_metID = ["e_metID"]:metID;
   320 val metID2str = strs2str;
   321 
   322 (*either theID or pblID or metID*)
   323 type kestoreID = string list;
   324 val e_kestoreID = ["e_kestoreID"];
   325 val kestoreID2str = strs2str;
   326 
   327 (*for distinction of contexts*)
   328 datatype ketype = Exp_ | Thy_ | Pbl_ | Met_;
   329 fun ketype2str Exp_ = "Exp_"
   330   | ketype2str Thy_ = "Thy_" 
   331   | ketype2str Pbl_ = "Pbl_" 
   332   | ketype2str Met_ = "Met_";
   333 fun ketype2str' Exp_ = "Example"
   334   | ketype2str' Thy_ = "Theory" 
   335   | ketype2str' Pbl_ = "Problem" 
   336   | ketype2str' Met_ = "Method";
   337 
   338 (*see 'How to manage theorys in subproblems' at 'type thyID'*)
   339 val theory'  = Unsynchronized.ref ([]:(theory' * theory) list);
   340 
   341 (*.all theories defined for Scripts, recorded in Scripts/Script.ML; 
   342    in order to distinguish them from general IsacKnowledge defined later on.*)
   343 val script_thys = Unsynchronized.ref ([] : (theory' * theory) list);
   344 
   345 
   346 (*rewrite orders, also stored in 'type met' and type 'and rls'
   347   The association list is required for 'rewrite.."rew_ord"..'
   348   WN0509 tests not well-organized: see smltest/Knowledge/termorder.sml*)
   349 val rew_ord' =
   350     Unsynchronized.ref
   351         ([]:(rew_ord' *        (*the key for the association list         *)
   352 	     (subst 	       (*the bound variables - they get high order*)
   353 	      -> (term * term) (*(t1, t2) to be compared                  *)
   354 	      -> bool))        (*if t1 <= t2 then true else false         *)
   355 		list);         (*association list                         *)
   356 rew_ord' := overwritel (!rew_ord', [("e_rew_ord", e_rew_ord),
   357 				    ("dummy_ord", dummy_ord)]);
   358 
   359 
   360 (*WN060120 a hack to get alltogether run again with minimal effort:
   361   theory' is inserted for creating thy_hierarchy; calls for assoc_rls
   362   need not be called*)
   363 val ruleset' = Unsynchronized.ref ([]:(rls' * (theory' * rls)) list);
   364 
   365 (*FIXME.040207 calclist': used by prep_rls, NOT in met*)
   366 val calclist'= Unsynchronized.ref ([]: calc list);
   367 
   368 (*.the hierarchy of thydata.*)
   369 
   370 (*.'a is for pbt | met.*)
   371 (*WN.24.4.03 -"- ... type parameters; afterwards naming inconsistent*)
   372 datatype 'a ptyp = 
   373 	 Ptyp of string *   (*element within pblID*)
   374 		 'a list *  (*several pbts with different domIDs/thy
   375 			      TODO: select by subthy (isaref.p.69)
   376 			      presently only _ONE_ elem*)
   377 		 ('a ptyp) list;   (*the children nodes*)
   378 
   379 (*.datatype for collecting thydata for hierarchy.*)
   380 (*WN060720 more consistent naming would be 'type thyelem' or 'thelem'*)
   381 (*WN0606 Htxt contains html which does not belong to the sml-kernel*)
   382 datatype thydata = Html of {guh: guh,
   383 			    coursedesign: authors,
   384 			    mathauthors: authors,
   385 			    html: string} (*html; for demos before database*)
   386 		 | Hthm of {guh: guh,
   387 			    coursedesign: authors,
   388 			    mathauthors: authors,
   389 			    thm: term}
   390 		 | Hrls of {guh: guh,
   391 			    coursedesign: authors,
   392 			    mathauthors: authors,
   393 			    (*like   vvvvvvvvvvvvv val ruleset'
   394 			     WN060711 redesign together !*)
   395 			    thy_rls: (thyID * rls)}
   396 		 | Hcal of {guh: guh,
   397 			    coursedesign: authors,
   398 			    mathauthors: authors,
   399 			    calc: calc}
   400 		 | Hord of {guh: guh,
   401 			    coursedesign: authors,
   402 			    mathauthors: authors,
   403 			    ord: (subst -> (term * term) -> bool)};
   404 val e_thydata = Html {guh="e_guh", coursedesign=[], mathauthors=[], html=""};
   405 
   406 type thehier = (thydata ptyp) list;
   407 val thehier = Unsynchronized.ref ([] : thehier);
   408 
   409 (*.an association list, gets the value once in Isac.ML.*)
   410 val isab_thm_thy = Unsynchronized.ref ([] : (thmID * (thyID * term)) list);
   411 
   412 
   413 type path = string;
   414 type filename = string;
   415 
   416 (*val xxx = fn: a b => (a,b);   ??? fun-definition ???*)
   417 local
   418     fun ii (_:term) = e_rrlsstate;
   419     fun no (_:term) = SOME (e_term,[e_term]);
   420     fun lo (_:rule list list) (_:term) (_:rule) = [(e_rule,(e_term,[e_term]))];
   421     fun ne (_:rule list list) (_:term) = SOME e_rule;
   422     fun fo (_:rule list list) (_:term) (_:term) = [(e_rule,(e_term,[e_term]))];
   423 in
   424 val e_rfuns = Rfuns {init_state=ii,normal_form=no,locate_rule=lo,
   425 		     next_rule=ne,attach_form=fo};
   426 end;
   427 
   428 val e_rls = 
   429   Rls{id = "e_rls",
   430       preconds = [], 
   431       rew_ord = ("dummy_ord", dummy_ord),
   432       erls = Erls,srls = Erls,
   433       calc = [],
   434       rules = [], scr = EmptyScr}:rls;
   435 val e_rrls = Rrls {id = "e_rrls",
   436 		   prepat = [],
   437 		   rew_ord = ("dummy_ord", dummy_ord),
   438 		   erls = Erls,
   439 		   calc = [],
   440 		   (*asm_thm=[],*)
   441 		   scr=e_rfuns}:rls;
   442 ruleset' := overwritel (!ruleset', [("e_rls",("Tools",e_rls)),
   443 				    ("e_rrls",("Tools",e_rrls))
   444 				    ]);
   445 
   446 fun rep_rls (Rls {id,preconds,rew_ord,erls,srls,calc,(*asm_thm,*)rules,scr}) =
   447   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   448    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   449   | rep_rls (Seq {id,preconds,rew_ord,erls,srls,calc,(*asm_thm,*)rules,scr}) =
   450   {id=id,preconds=preconds,rew_ord=rew_ord,erls=erls,srls=srls,calc=calc,
   451    (*asm_thm=asm_thm,*)rules=rules,scr=scr}
   452   | rep_rls Erls = rep_rls e_rls
   453   | rep_rls (Rrls {id,...})  = rep_rls e_rls
   454     (*raise error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id)*);
   455 (*| rep_rls (Seq {id,...})  = 
   456     raise error("rep_rls doesn't take apart reverse-rewrite-rule-sets: "^id);
   457 --1.7.03*)
   458 fun rep_rrls 
   459 	(Rrls {id,(*asm_thm,*) calc, erls, prepat, rew_ord, 
   460 	       scr=Rfuns
   461 		       {attach_form,init_state,locate_rule,
   462 			next_rule,normal_form}}) =
   463     {id=id,(*asm_thm=asm_thm,*) calc=calc, erls=erls, prepat=prepat, 
   464      rew_ord=rew_ord, attach_form=attach_form, init_state=init_state, 
   465      locate_rule=locate_rule, next_rule=next_rule, normal_form=normal_form}
   466   | rep_rrls (Rls {id,...}) = 
   467     raise error ("rep_rrls doesn't take apart (normal) rule-sets: "^id)
   468   | rep_rrls (Seq {id,...}) = 
   469     raise error ("rep_rrls doesn't take apart (normal) rule-sets: "^id);
   470 
   471 fun append_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   472 			rules =rs,scr=sc}) r =
   473     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   474 	 rules = rs @ r,scr=sc}:rls)
   475   | append_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   476 			rules =rs,scr=sc}) r =
   477     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   478 	 rules = rs @ r,scr=sc}:rls)
   479   | append_rls id (Rrls _) _ = 
   480     raise error ("append_rls: not for reverse-rewrite-rule-set "^id);
   481 
   482 (*. are _atomic_ rules equal ?.*)
   483 (*WN080102 compare eqrule ?!?*)
   484 fun eq_rule (Thm (thm1,_), Thm (thm2,_)) = thm1 = thm2
   485   | eq_rule (Calc (id1,_), Calc (id2,_)) = id1 = id2
   486   | eq_rule (Rls_ rls1, Rls_ rls2) = id_rls rls1 = id_rls rls2
   487   (*id_rls checks for Rls, Seq, Rrls*)
   488   | eq_rule _ = false;
   489 
   490 fun merge_rls _ Erls rls = rls
   491   | merge_rls _ rls Erls = rls
   492   | merge_rls id
   493 	(Rls {id=id1,preconds=pc1,rew_ord=ro1,erls=er1,srls=sr1,calc=ca1,
   494 	      (*asm_thm=at1,*)rules =rs1,scr=sc1}) 
   495 	(r2 as Rls {id=id2,preconds=pc2,rew_ord=ro2,erls=er2,srls=sr2,calc=ca2,
   496 	      (*asm_thm=at2,*)rules =rs2,scr=sc2}) =
   497 	(Rls {id=id,preconds=pc1 @ ((#preconds o rep_rls) r2),
   498 	      rew_ord=ro1,erls=merge_rls "" er1 er2(*er1*),
   499 	      srls=merge_rls ("merged_"^id1^"_"^((#id o rep_rls) r2)) sr1 
   500 			     ((#srls o rep_rls) r2),
   501 	      calc=ca1 @ ((#calc o rep_rls) r2),
   502 	      (*asm_thm=at1 @ ((#asm_thm o rep_rls) r2),*)
   503 	      rules = gen_union eq_rule rule2str (rs1, (#rules o rep_rls) r2),
   504 	      scr=sc1}:rls)
   505   | merge_rls id
   506 	(Seq {id=id1,preconds=pc1,rew_ord=ro1,erls=er1,srls=sr1,calc=ca1,
   507 	      (*asm_thm=at1,*)rules =rs1,scr=sc1}) 
   508 	(r2 as Seq {id=id2,preconds=pc2,rew_ord=ro2,erls=er2,srls=sr2,calc=ca2,
   509 	      (*asm_thm=at2,*)rules =rs2,scr=sc2}) =
   510 	(Seq {id=id,preconds=pc1 @ ((#preconds o rep_rls) r2),
   511 	      rew_ord=ro1,erls=merge_rls "" er1 er2(*er1*),
   512 	      srls=merge_rls ("merged_"^id1^"_"^((#id o rep_rls) r2)) sr1 
   513 			     ((#srls o rep_rls) r2),
   514 	      calc=ca1 @ ((#calc o rep_rls) r2),
   515 	      (*asm_thm=at1 @ ((#asm_thm o rep_rls) r2),*)
   516 	      rules = gen_union eq_rule rule2str (rs1, (#rules o rep_rls) r2),
   517 	      scr=sc1}:rls)
   518   | merge_rls _ _ _ = 
   519     raise error "merge_rls: not for reverse-rewrite-rule-sets\
   520 		\and not for mixed Rls -- Seq";
   521 fun remove_rls id (Rls {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   522 		     (*asm_thm=at,*)rules =rs,scr=sc}) r =
   523     (Rls{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   524 	 (*asm_thm=at,*)rules = gen_rems eq_rule (rs, r),
   525 	 scr=sc}:rls)
   526   | remove_rls id (Seq {id=_,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   527 		     (*asm_thm=at,*)rules =rs,scr=sc}) r =
   528     (Seq{id=id,preconds=pc,rew_ord=ro,erls=er,srls=sr,calc=ca,
   529 	 (*asm_thm=at,*)rules = gen_rems eq_rule (rs, r),
   530 	 scr=sc}:rls)
   531   | remove_rls id (Rrls _) _ = raise error 
   532                    ("remove_rls: not for reverse-rewrite-rule-set "^id);
   533 
   534 (*!!!> gen_rems (op=) ([1,2,3,4], [3,4,5]);
   535 val it = [1, 2] : int list*)
   536 
   537 (*elder version: migrated 3 calls in smtest to memrls
   538 fun mem_rls id rls = 
   539     case find_first ((curry op=) id) (map id_rule ((#rules o rep_rls) rls)) of
   540 	SOME _ => true | NONE => false;*)
   541 fun memrls r (Rls {rules,...}) = gen_mem eqrule (r, rules)
   542   | memrls r (Seq {rules,...}) = gen_mem eqrule (r, rules)
   543   | memrls r _ = raise error ("memrls: incomplete impl. r= "^(rule2str r));
   544 fun rls_get_thm rls (id: xstring) =
   545     case find_first (curry eq_rule e_rule) 
   546 		    ((#rules o rep_rls) rls) of
   547 	SOME thm => SOME thm | NONE => NONE;
   548 
   549 fun assoc' ([], key) = raise error ("ME_Isa: '"^key^"' not known")
   550   | assoc' ((keyi, xi) :: pairs, key) =
   551       if key = keyi then SOME xi else assoc' (pairs, key);
   552 
   553 (*100818 fun assoc_thy (thy:theory') = ((the o assoc')(!theory',thy))
   554   handle _ => raise error ("ME_Isa: thy '"^thy^"' not in system");*)
   555 fun assoc_thy (thy:theory') = (*FIXME100818 abolish*)
   556     (theory ((implode o (curry takelast 4) o explode) thy))
   557     handle _ => raise error ("ME_Isa: thy '" ^ thy ^ "' not in system");
   558     
   559 (*.associate an rls-identifier with an rls; related to 'fun assoc_rls';
   560    these are NOT compatible to "fun assoc_thm'" in that they do NOT handle
   561    overlays by re-using an identifier in different thys.*)
   562 fun assoc_rls (rls:rls') = ((#2 o the o assoc')(!ruleset',rls))
   563   handle _ => raise error ("ME_Isa: '"^rls^"' not in system");
   564 (*fun assoc_rls (rls:rls') = ((the o assoc')(!ruleset',rls))
   565   handle _ => raise error ("ME_Isa: '"^rls^"' not in system");*)
   566 
   567 (*.overwrite an element in an association list and pair it with a thyID
   568    in order to create the thy_hierarchy;
   569    overwrites existing rls' even if they are defined in a different thy;
   570    this is related to assoc_rls, TODO.WN060120: assoc_rew_ord, assoc_calc;.*)
   571 (*WN060120 ...these are NOT compatible to "fun assoc_thm'" in that 
   572    they do NOT handle overlays by re-using an identifier in different thys;
   573    "thyID.rlsID" would be a good solution, if the "." would be possible
   574    in scripts...
   575    actually a hack to get alltogether run again with minimal effort*)
   576 fun insthy thy' (rls', rls) = (rls', (thy', rls));
   577 fun overwritelthy thy (al, bl:(rls' * rls) list) =
   578     let val bl' = map (insthy ((get_thy o theory2theory') thy)) bl
   579     in overwritel (al, bl') end;
   580 
   581 fun assoc_rew_ord ro = ((the o assoc') (!rew_ord',ro))
   582   handle _ => raise error ("ME_Isa: rew_ord '"^ro^"' not in system");
   583 (*get the string for stac from rule*)
   584 fun assoc_calc ([], key) = raise error ("assoc_calc: '"^ key ^"' not found")
   585   | assoc_calc ((calc, (keyi, xi)) :: pairs, key) =
   586       if key = keyi then calc else assoc_calc (pairs, key);
   587 (*only used for !calclist'...*)
   588 fun assoc1 ([], key) = raise error ("assoc1 (for met.calc=): '"^ key 
   589 				    ^"' not found")
   590   | assoc1 ((all as (keyi, _)) :: pairs, key) =
   591       if key = keyi then all else assoc1 (pairs, key);
   592 
   593 (*TODO.WN080102 clarify usage of type cal and type calc..*)
   594 fun calID2calcID (calID : calID) = 
   595     let fun ass [] = raise error ("calID2calcID: "^calID^"not in calclist'")
   596 	  | ass ((calci, (cali, eval_fn))::ids) =
   597 	    if calID = cali then calci
   598 	    else ass ids
   599     in ass (!calclist') : calcID end;
   600 
   601 fun termopt2str (SOME t) = 
   602     "SOME " ^ (Syntax.string_of_term (thy2ctxt' "Isac") t)
   603   | termopt2str NONE = "NONE";
   604 (*fun term2str t = Syntax.string_of_term (thy2ctxt' "Isac") t; Isa2002*)
   605 (*Florian1009: 'val' would ensure static lookup, i.e. only at compile time;
   606   however, dynamic lookup is required, since "Isac" is not yet built here.*)
   607 fun term2str t = Print_Mode.setmp [] (Syntax.string_of_term
   608 (ProofContext.init_global (Thy_Info.get_theory "Isac"))) t;
   609 fun terms2str ts = (strs2str o (map term2str )) ts;
   610 (*terms2str [t1,t2] = "[\"1 + 2\",\"abc\"]";*)
   611 fun terms2str' ts = (strs2str' o (map term2str )) ts;
   612 (*terms2str' [t1,t2] = "[1 + 2,abc]";*)
   613 fun terms2strs ts = (map term2str) ts;
   614 (*terms2strs [t1,t2] = ["1 + 2", "abc"];*)
   615 
   616 un type2str typ = Syntax.string_of_typ (thy2ctxt' "Isac") typ;
   617 val string_of_typ = type2str;
   618 
   619 fun subst2str (s:subst) = 
   620     (strs2str o 
   621      (map (linefeed o pair2str o
   622 	   (apsnd term2str) o 
   623 	   (apfst term2str)))) s;
   624 fun subst2str' (s:subst) = 
   625     (strs2str' o 
   626      (map (pair2str o
   627 	   (apsnd term2str) o 
   628 	   (apfst term2str)))) s;
   629 (*> subst2str' [(str2term "bdv", str2term "x"),
   630 		(str2term "bdv_2", str2term "y")];
   631 val it = "[(bdv, x)]" : string
   632 *)
   633 val env2str = subst2str;
   634 
   635 
   636 (*recursive defs:*)
   637 fun scr2str (Script s) = "Script "^(term2str s)
   638   | scr2str (Rfuns _)  = "Rfuns";
   639 
   640 
   641 fun maxthy thy1 thy2 = if Theory.subthy (thy1, thy2) then thy2 else thy1;
   642 
   643 
   644 (*.trace internal steps of isac's rewriter*)
   645 val trace_rewrite = Unsynchronized.ref false;
   646 (*.depth of recursion in traces of the rewriter, if trace_rewrite:=true.*)
   647 val depth = Unsynchronized.ref 99999;
   648 (*.no of rewrites exceeding this int -> NO rewrite.*)
   649 (*WN060829 still unused...*)
   650 val lim_rewrite = Unsynchronized.ref 99999;
   651 (*.no of derivation-elements exceeding this int -> SOME derivation-elements.*)
   652 val lim_deriv = Unsynchronized.ref 100;
   653 (*.switch for checking guhs unique before storing a pbl or met;
   654    set true at startup (done at begin of ROOT.ML)
   655    set false for editing IsacKnowledge (done at end of ROOT.ML).*)
   656 val check_guhs_unique = Unsynchronized.ref false;
   657 
   658 
   659 datatype lrd = (*elements of a path (=loc_) into an Isabelle term*)
   660 	 L     (*go left at $*) 
   661        | R     (*go right at $*)
   662        | D;     (*go down at Abs*)
   663 type loc_ = lrd list;
   664 fun ldr2str L = "L"
   665   | ldr2str R = "R"
   666   | ldr2str D = "D";
   667 fun loc_2str (k:loc_) = (strs2str' o (map ldr2str)) k;
   668