src/Tools/isac/calcelems.sml
author Walther Neuper <neuper@ist.tugraz.at>
Sun, 21 Jul 2013 15:08:31 +0200
changeset 52065 41f6e90abf36
parent 48892 21eb57e95263
child 52070 77138c64f4f6
permissions -rw-r--r--
a bulky chunk of changes

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