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