src/Tools/isac/Interpret/rewtools.sml
author Walther Neuper <walther.neuper@jku.at>
Wed, 15 Apr 2020 13:47:56 +0200
changeset 59879 33449c96d99f
parent 59878 3163e63a5111
child 59880 f1f086029ee5
permissions -rw-r--r--
use "ThyC" for renaming identifiers
     1 (* 
     2    authors: Walther Neuper 2002, 2006
     3   (c) due to copyright terms
     4 
     5 tools for rewriting, reverse rewriting, context to thy concerning rewriting
     6 *)
     7 
     8 signature REWRITE_TOOLS =
     9 sig
    10   type deriv
    11   val contains_rule : Rule.rule -> Rule_Set.T -> bool
    12   val atomic_appl_tacs : theory -> string -> Rule_Set.T -> term -> Tactic.input -> Tactic.input list
    13   val thy_containing_rls : ThyC.id -> Rule_Set.id -> string * ThyC.id
    14   val thy_containing_cal : ThyC.id -> Exec_Def.prog_calcID -> string * string
    15   datatype contthy
    16   = ContNOrew of {applto: term, thm_rls: Celem.guh, thyID: ThyC.id}
    17      | ContNOrewInst of {applto: term, bdvs: UnparseC.subst, thm_rls: Celem.guh, thminst: term, thyID: ThyC.id}
    18      | ContRls of {applto: term, asms: term list, result: term, rls: Celem.guh, thyID: ThyC.id}
    19      | ContRlsInst of {applto: term, asms: term list, bdvs: UnparseC.subst, result: term, rls: Celem.guh, thyID: ThyC.id}
    20      | ContThm of {applat: term, applto: term, asmrls: Rule_Set.id, asms: (term * term) list,
    21        lhs: term * term, resasms: term list, result: term, reword: Rewrite_Ord.rew_ord', rhs: term * term,
    22        thm: Celem.guh, thyID: ThyC.id}
    23      | ContThmInst of {applat: term, applto: term, asmrls: Rule_Set.id, asms: (term * term) list,
    24        bdvs: UnparseC.subst, lhs: term * term, resasms: term list, result: term, reword: Rewrite_Ord.rew_ord',
    25        rhs: term * term, thm: Celem.guh, thminst: term, thyID: ThyC.id}
    26      | EContThy
    27   val guh2filename : Celem.guh -> Celem.filename
    28   val thms_of_rls : Rule_Set.T -> Rule.rule list
    29   val theID2filename : Celem.theID -> Celem.filename
    30   val no_thycontext : Celem.guh -> bool
    31   val subs_from : Istate.T -> 'a -> Celem.guh -> Selem.subs
    32   val guh2rewtac : Celem.guh -> Selem.subs -> Tactic.input
    33   val get_tac_checked : Ctree.ctree -> Pos.pos' -> Tactic.input
    34   val context_thy : Calc.T -> Tactic.input -> contthy
    35   val distinct_Thm : Rule.rule list -> Rule.rule list
    36   val eq_Thms : string list -> Rule.rule -> bool
    37   val make_deriv : theory -> Rule_Set.T -> Rule.rule list -> ((term * term) list -> term * term -> bool) ->
    38     term option -> term -> deriv
    39   val reverse_deriv : theory -> Rule_Set.T -> Rule.rule list -> ((term * term) list -> term * term -> bool) ->
    40     term option -> term -> (Rule.rule * (term * term list)) list
    41   val get_bdv_subst : term -> (term * term) list -> Selem.subs option * UnparseC.subst
    42   val thy_containing_thm : string -> string * string
    43   val guh2theID : Celem.guh -> Celem.theID
    44 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
    45   (*  NONE *)
    46 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
    47   val trtas2str : (term * Rule.rule * (term * term list)) list -> string
    48   val eq_Thm : Rule.rule * Rule.rule -> bool
    49   val deriv2str : (term * Rule.rule * (term * term list)) list -> string
    50   val deriv_of_thm'' : ThmC.T -> string
    51 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
    52 
    53 (*----- unused code, kept as hints to design ideas ---------------------------------------------*)
    54   val deri2str : (Rule.rule * (term * term list)) list -> string
    55   val sym_trm : term -> term
    56 end 
    57 (**)
    58 structure Rtools(**): REWRITE_TOOLS(**) =
    59 struct
    60 (**)
    61 
    62 (*** reverse rewriting ***)
    63 (*. a '_deriv'ation is constructed during 'reverse rewring' by an Rrls       *
    64  *  of for connecting a user-input formula with the current calc-state.	     *
    65  *# It is somewhat incompatible with the rest of the math-engine:	     *
    66  *  (1) it is not created by a script					     *
    67  *  (2) thus there cannot be another user-input within a derivation	     *
    68  *# It suffers particularily from the not-well-foundedness of the math-engine*
    69  *  (1) FIXME other branchtyptes than Transitive will change 'embed_deriv'   *
    70  *  (2) FIXME and eventually 'compare_step' (ie. the script interpreter)     *
    71  *  (3) FIXME and eventually 'lev_back'                                      *
    72  *# SOME improvements are evident FIXME.040215 '_deriv'ation:	             *
    73  *  (1) FIXME nest Rls_ in 'make_deriv'					     *
    74  *  (2) FIXME do the not-reversed part in 'make_deriv' by scripts -- thus    *
    75  *	user-input will become possible in this part of a derivation	     *
    76  *  (3) FIXME do (2) only if a derivation has been found -- for efficiency,  *
    77  *	while a non-derivable inform requires to step until End_Proof'	     *
    78  *  (4) FIXME find criteria on when _not_ to step until End_Proof'           *
    79  *  (5) FIXME 
    80 .*)
    81 type deriv =      (* derivation for insertin one level of nodes into the Ctree *) 
    82   ( term *        (* where the rule is applied to                              *)
    83     Rule.rule *   (* rule to be applied                                        *)
    84     ( term *      (* resulting from rule application                           *)
    85       term list)) (* assumptions resulting from rule application               *)
    86   list
    87 
    88 fun trta2str (t, r, (t', a)) =
    89   "\n(" ^ UnparseC.term t ^ ", " ^ Rule.to_string_short r ^ ", (" ^ UnparseC.term t' ^ ", " ^ UnparseC.terms a ^ "))"
    90 fun trtas2str trtas = (strs2str o (map trta2str)) trtas
    91 val deriv2str = trtas2str
    92 fun rta2str (r, (t, a)) =
    93   "\n(" ^ Rule.to_string_short r ^ ", (" ^ UnparseC.term t ^ ", " ^ UnparseC.terms a ^ "))"
    94 fun rtas2str rtas = (strs2str o (map rta2str)) rtas
    95 val deri2str = rtas2str
    96 
    97 (* WN100910 weaker than fun sym_thm for Theory.axioms_of in isa02 *)
    98 fun sym_trm trm =
    99   let
   100     val (lhs, rhs) = (TermC.dest_equals o TermC.strip_trueprop o Logic.strip_imp_concl) trm
   101     val trm' = case TermC.strip_imp_prems' trm of
   102 	      NONE => TermC.mk_equality (rhs, lhs)
   103 	    | SOME cs => TermC.ins_concl cs (TermC.mk_equality (rhs, lhs))
   104   in trm' end
   105 
   106 (* derive normalform of a rls, or derive until SOME goal,
   107    and record rules applied and rewrites.
   108 val it = fn
   109   : theory
   110     -> rls
   111     -> rule list
   112     -> rew_ord       : the order of this rls, which 1 theorem of is used 
   113                        for rewriting 1 single step (?14.4.03)
   114     -> term option   : 040214 ??? use for "derive until SOME goal" ??? 
   115     -> term 
   116     -> (term *       : to this term ...
   117         rule * 	     : ... this rule is applied yielding ...
   118         (term *      : ... this term ...
   119          term list)) : ... under these assumptions.
   120        list          :
   121 returns empty list for a normal form
   122 FIXME.WN040214: treats rules as in Rls, _not_ as in Seq
   123 
   124 WN060825 too complicated for the intended use by cancel_, common_nominator_
   125 and unreflectedly adapted to extension of rules by Rls_: returns Rls_("sym_simpl..
   126  -- replaced below *)
   127 fun make_deriv thy erls rs ro goal tt = 
   128   let 
   129     datatype switch = Appl | Noap (* unify with version in rewrite.sml *)
   130     fun rew_once _ rts t Noap [] = 
   131         (case goal of NONE => rts | SOME _ => error ("make_deriv: no derivation for " ^ UnparseC.term t))
   132       | rew_once lim rts t Appl [] = rew_once lim rts t Noap rs
   133         (*| Seq _ => rts) FIXXXXXME 14.3.03*)
   134       | rew_once lim rts t apno rs' =
   135         (case goal of 
   136           NONE => rew_or_calc lim rts t apno rs'
   137         | SOME g => if g = t then rts else rew_or_calc lim rts t apno rs')
   138     and rew_or_calc lim rts t apno (rrs' as (r :: rs')) =
   139       if lim < 0 
   140       then (tracing ("make_deriv exceeds " ^ int2str (! Celem.lim_deriv) ^ "with deriv =\n");
   141         tracing (deriv2str rts); rts)
   142       else
   143         (case r of
   144           Rule.Thm (thmid, tm) => 
   145             (if not (! Celem.trace_rewrite) then () else tracing ("### trying thm \"" ^ thmid ^ "\"");
   146             case Rewrite.rewrite_ thy ro erls true tm t of
   147               NONE => rew_once lim rts t apno rs'
   148             | SOME (t', a') =>
   149               (if ! Celem.trace_rewrite then tracing ("=== rewrites to: " ^ UnparseC.term t') else ();
   150               rew_once (lim - 1) (rts @ [(t, r, (t', a'))]) t' Appl rrs'))
   151         | Rule.Eval (c as (op_, _)) => 
   152           let 
   153             val _ = if not (! Celem.trace_rewrite) then () else tracing ("### trying calc. \"" ^ op_^"\"")
   154             val t = TermC.uminus_to_string t
   155           in 
   156             case Eval.adhoc_thm thy c t of
   157               NONE => rew_once lim rts t apno rs'
   158             | SOME (thmid, tm) => 
   159               (let
   160                 val (t', a') = case Rewrite.rewrite_ thy ro erls true tm t of
   161                   SOME ta => ta
   162                 | NONE => error "adhoc_thm: NONE"
   163                 val _ = if not (! Celem.trace_rewrite) then () else tracing("=== calc. to: " ^ UnparseC.term t')
   164                 val r' = Rule.Thm (thmid, tm)
   165               in rew_once (lim - 1) (rts @ [(t, r', (t', a'))]) t' Appl rrs' end) 
   166                 handle _ => error "derive_norm, Eval: no rewrite"
   167           end
   168       (*| Cal1 (cc as (op_,_)) => ... WN080222 see rewrite__set_: see 7df94616c1bd and earlier*)
   169         | Rule.Rls_ rls =>           (* WN060829: CREATES "sym_rlsID", see 7df94616c1bd and earlier*)
   170           (case Rewrite.rewrite_set_ thy true rls t of
   171             NONE => rew_once lim rts t apno rs'
   172           | SOME (t', a') => rew_once (lim - 1) (rts @ [(t, r, (t', a'))]) t' Appl rrs')
   173         | rule => error ("rew_once: uncovered case " ^ Rule.to_string rule))
   174     | rew_or_calc _ _ _ _ [] = error "rew_or_calc: called with []"
   175   in rew_once (! Celem.lim_deriv) [] tt Noap rs end
   176 
   177 (*version for reverse rewrite used before 040214*)
   178 fun rev_deriv (t, r, (_, a)) = (ThmC.make_sym_rule r, (t, a));
   179 fun reverse_deriv thy erls rs ro goal t =
   180     (rev o (map rev_deriv)) (make_deriv thy erls rs ro goal t)
   181 
   182 fun eq_Thm (Rule.Thm (id1, _), Rule.Thm (id2,_)) = id1 = id2
   183   | eq_Thm (Rule.Thm (_, _), _) = false
   184   | eq_Thm (Rule.Rls_ r1, Rule.Rls_ r2) = Rule_Set.id r1 = Rule_Set.id r2
   185   | eq_Thm (Rule.Rls_ _, _) = false
   186   | eq_Thm (r1, r2) = error ("eq_Thm: called with '" ^ Rule.to_string r1 ^ "' '" ^ Rule.to_string r2 ^ "'")
   187 fun distinct_Thm r = gen_distinct eq_Thm r
   188 
   189 fun eq_Thms thmIDs thm = (member op = thmIDs (Rule.thm_id thm))
   190   handle ERROR _ => false
   191 
   192 fun thy_containing_thm thmDeriv =
   193   let
   194     val isabthys' = map Context.theory_name (Celem.isabthys ());
   195   in
   196     if member op= isabthys' (ThyC.cut_id thmDeriv)
   197     then ("Isabelle", ThyC.cut_id thmDeriv)
   198     else ("IsacKnowledge", ThyC.cut_id thmDeriv)
   199   end
   200 
   201 (* which theory in ancestors of thy' contains a ruleset *)
   202 fun thy_containing_rls thy' rls' =
   203   let
   204     val thy = ThyC.get_theory thy'
   205   in
   206     case AList.lookup op= (KEStore_Elems.get_rlss thy) rls' of
   207       SOME (thy'', _) => (Celem.partID' thy'', thy'')
   208     | _ => error ("thy_containing_rls : rls '" ^ rls' ^ "' not in ancestors of thy '" ^ thy' ^ "'")
   209   end
   210 
   211 (* this function cannot work as long as the datastructure does not contain thy' *)
   212 fun thy_containing_cal thy' sop =
   213   let
   214     val thy = ThyC.get_theory thy'
   215   in
   216     case AList.lookup op= (KEStore_Elems.get_calcs thy) sop of
   217       SOME (_(*"Groups.plus_class.plus"*), _) => ("IsacKnowledge", "Base_Tools")
   218     | _ => error ("thy_containing_cal : rls '" ^ sop ^ "' not in ancestors of thy '" ^ thy' ^ "'")
   219   end
   220 
   221 (* packing return-values to matchTheory, contextToThy for xml-generation *)
   222 datatype contthy =  (*also an item from KEStore on Browser ...........#*)
   223 	EContThy   (* not from KEStore ..............................*)
   224   | ContThm of (* a theorem in contex ===========================*)
   225     {thyID   : ThyC.id,      (* for *2guh in sub-elems here        .*)
   226      thm     : Celem.guh,       (* theorem in the context             .*)
   227      applto  : term,	          (* applied to formula ...             .*)
   228      applat  : term,	          (* ...  with lhs inserted             .*)
   229      reword  : Rewrite_Ord.rew_ord',   (* order used for rewrite             .*)
   230      asms    : (term            (* asumption instantiated             .*)
   231    	   * term) list,            (* asumption evaluated                .*)
   232      lhs     : term             (* lhs of the theorem ...             #*)
   233    	   * term,                  (* ... instantiated                   .*)
   234      rhs     : term             (* rhs of the theorem ...             #*)
   235    	   * term,                  (* ... instantiated                   .*)
   236      result  : term,	          (* resulting from the rewrite         .*)
   237      resasms : term list,       (* ... with asms stored               .*)
   238      asmrls  : Rule_Set.id        (* ruleset for evaluating asms        .*)
   239    	}						 
   240   | ContThmInst of (* a theorem with bdvs in contex ============ *)
   241     {thyID   : ThyC.id,      (*for *2guh in sub-elems here         .*)
   242      thm     : Celem.guh,       (*theorem in the context              .*)
   243      bdvs    : UnparseC.subst,      (*bound variables to modify...        .*)
   244      thminst : term,            (*... theorem instantiated            .*)
   245      applto  : term,	          (*applied to formula ...              .*)
   246      applat  : term,	          (*...  with lhs inserted              .*)
   247      reword  : Rewrite_Ord.rew_ord',   (*order used for rewrite              .*)
   248      asms    : (term            (*asumption instantiated              .*)
   249    	   * term) list,            (*asumption evaluated                 .*)
   250      lhs     : term             (*lhs of the theorem ...              #*)
   251    	   * term,                  (*... instantiated                    .*)
   252      rhs     : term             (*rhs of the theorem ...              #*)
   253    	   * term,                  (*... instantiated                    .*)
   254      result  : term,	          (*resulting from the rewrite          .*)
   255      resasms : term list,       (*... with asms stored                .*)
   256      asmrls  : Rule_Set.id        (*ruleset for evaluating asms         .*)
   257     }						 
   258   | ContRls of (* a rule set in contex ========================= *)
   259     {thyID   : ThyC.id,      (*for *2guh in sub-elems here         .*)
   260      rls     : Celem.guh,       (*rule set in the context             .*)
   261      applto  : term,	          (*rewrite this formula                .*)
   262      result  : term,	          (*resulting from the rewrite          .*)
   263      asms    : term list        (*... with asms stored                .*)
   264    	}						 
   265   | ContRlsInst of (* a rule set with bdvs in contex =========== *)
   266 	{thyID   : ThyC.id,        (*for *2guh in sub-elems here         .*)
   267 	 rls     : Celem.guh,         (*rule set in the context             .*)
   268 	 bdvs    : UnparseC.subst,        (*for bound variables in thms         .*)
   269 	 applto  : term,	            (*rewrite this formula                .*)
   270 	 result  : term,	            (*resulting from the rewrite          .*)
   271 	 asms    : term list          (*... with asms stored                .*)
   272    	}						 
   273   | ContNOrew of (* no rewrite for thm or rls ================== *)
   274     {thyID   : ThyC.id,      (*for *2guh in sub-elems here         .*)
   275      thm_rls : Celem.guh,       (*thm or rls in the context           .*)
   276      applto  : term	            (*rewrite this formula                .*)
   277    	}						 
   278   | ContNOrewInst of (* no rewrite for some instantiation ====== *)
   279     {thyID   : ThyC.id,      (*for *2guh in sub-elems here         .*)
   280      thm_rls : Celem.guh,       (*thm or rls in the context           .*)
   281      bdvs    : UnparseC.subst,      (*for bound variables in thms         .*)
   282      thminst : term,            (*... theorem instantiated            .*)
   283      applto  : term	            (*rewrite this formula                .*)
   284    	}						 
   285 
   286 (*.check a rewrite-tac for bdv (RL always used *_Inst !) TODO.WN060718
   287    pass other tacs unchanged.*)
   288 fun get_tac_checked pt ((p, _) : Pos.pos') = Ctree.get_obj Ctree.g_tac pt p;
   289 
   290 (* create a derivation-name, eg. ("refl", _) --> "HOL.refl"*)
   291 fun deriv_of_thm'' (thmID, _) =
   292   thmID |> Global_Theory.get_thm (ThyC.Isac ()) |> Thm.get_name_hint
   293 
   294 (* get the formula f at ptp rewritten by the Rewrite_* already applied to f *)
   295 fun context_thy (pt, pos as (p,p_)) (tac as Tactic.Rewrite thm'') =
   296     let val thm_deriv = deriv_of_thm'' thm''
   297     in
   298     (case Applicable.applicable_in pos pt tac of
   299       Applicable.Appl (Tactic.Rewrite' (thy', ord', erls, _, _, f, (res,asm))) =>
   300         ContThm
   301          {thyID = ThyC.theory'2thyID thy',
   302           thm = Celem.thm2guh (thy_containing_thm thm_deriv) (ThmC.cut_id thm_deriv),
   303           applto = f, applat  = TermC.empty, reword  = ord',
   304           asms = [](*asms ~~ asms'*), lhs = (TermC.empty, TermC.empty)(*(lhs, lhs')*), rhs = (TermC.empty, TermC.empty)(*(rhs, rhs')*),
   305           result = res, resasms = asm, asmrls  = Rule_Set.id erls}
   306      | Applicable.Notappl _ =>
   307          let
   308            val pp = Ctree.par_pblobj pt p
   309            val thy' = Ctree.get_obj Ctree.g_domID pt pp
   310            val f = case p_ of
   311              Pos.Frm => Ctree.get_obj Ctree.g_form pt p
   312            | Pos.Res => (fst o (Ctree.get_obj Ctree.g_result pt)) p 
   313            | _ => error "context_thy: uncovered position"
   314          in
   315            ContNOrew
   316             {thyID   = ThyC.theory'2thyID thy',
   317              thm_rls = 
   318                Celem.thm2guh (thy_containing_thm thm_deriv) (ThmC.cut_id thm_deriv),
   319              applto  = f}
   320 		     end
   321      | _ => error "context_thy..Rewrite: uncovered case 2")
   322     end
   323   | context_thy (pt, pos as (p, p_)) (tac as Tactic.Rewrite_Inst (subs, (thmID, _))) =
   324     let val thm = Global_Theory.get_thm (ThyC.Isac ()) thmID
   325     in
   326 	  (case Applicable.applicable_in pos pt tac of
   327 	     Applicable.Appl (Tactic.Rewrite_Inst' (thy', ord', erls, _, subst, _, f, (res, asm))) =>
   328 	       let
   329            val thm_deriv = Thm.get_name_hint thm
   330            val thminst = TermC.inst_bdv subst ((Eval.norm o #prop o Thm.rep_thm) thm)
   331 	       in
   332 	         ContThmInst
   333 	          {thyID = ThyC.theory'2thyID thy',
   334 	           thm = 
   335 	             Celem.thm2guh (thy_containing_thm thm_deriv) (ThmC.cut_id thm_deriv),
   336 	           bdvs = subst, thminst = thminst, applto  = f, applat  = TermC.empty, reword  = ord',
   337 	           asms = [](*asms ~~ asms'*), lhs = (TermC.empty, TermC.empty)(*(lhs, lhs')*), rhs = (TermC.empty, TermC.empty)(*(rhs, rhs')*),
   338 	           result = res, resasms = asm, asmrls  = Rule_Set.id erls}
   339 	       end
   340      | Applicable.Notappl _ =>
   341          let
   342            val thm = Global_Theory.get_thm (ThyC.Isac ()(*WN141021 assoc_thy thy' ERROR*)) thmID
   343            val thm_deriv = Thm.get_name_hint thm
   344            val pp = Ctree.par_pblobj pt p
   345            val thy' = Ctree.get_obj Ctree.g_domID pt pp
   346            val subst = Selem.subs2subst (Celem.assoc_thy thy') subs
   347            val thminst = TermC.inst_bdv subst ((Eval.norm o #prop o Thm.rep_thm) thm)
   348            val f = case p_ of
   349                Pos.Frm => Ctree.get_obj Ctree.g_form pt p
   350              | Pos.Res => (fst o (Ctree.get_obj Ctree.g_result pt)) p 
   351              | _ => error "context_thy: uncovered case 3"
   352          in
   353            ContNOrewInst
   354             {thyID = ThyC.theory'2thyID thy',
   355              thm_rls = Celem.thm2guh (thy_containing_thm thm_deriv) (ThmC.cut_id thm_deriv),
   356              bdvs = subst, thminst = thminst, applto = f}
   357          end
   358       | _ => error "context_thy..Rewrite_Inst: uncovered case 4")
   359     end
   360   | context_thy (pt, p) (tac as Tactic.Rewrite_Set rls') =
   361     (case Applicable.applicable_in p pt tac of
   362        Applicable.Appl (Tactic.Rewrite_Set' (thy', _, _(*rls*), f, (res,asm))) =>
   363          ContRls
   364           {thyID = ThyC.theory'2thyID thy',
   365            rls = Celem.rls2guh (thy_containing_rls thy' rls') rls',
   366            applto = f, result = res, asms = asm}
   367      | _ => error ("context_thy Rewrite_Set: not for Applicable.Notappl"))
   368   | context_thy (pt,p) (tac as Tactic.Rewrite_Set_Inst (_(*subs*), rls')) = 
   369     (case Applicable.applicable_in p pt tac of
   370        Applicable.Appl (Tactic.Rewrite_Set_Inst' (thy', _, subst, _, f, (res,asm))) =>
   371          ContRlsInst
   372           {thyID = ThyC.theory'2thyID thy',
   373            rls = Celem.rls2guh (thy_containing_rls thy' rls') rls',
   374            bdvs = subst, applto = f, result = res, asms = asm}
   375      | _ => error ("context_thy Rewrite_Set_Inst: not for Applicable.Notappl"))
   376   | context_thy (_, p) tac =
   377       error ("context_thy: not for tac " ^ Tactic.input_to_string tac ^ " at " ^ Pos.pos'2str p)
   378 
   379 (* get all theorems in a rule set (recursivley containing rule sets) *)
   380 fun thm_of_rule Rule.Erule = []
   381   | thm_of_rule (thm as Rule.Thm _) = [thm]
   382   | thm_of_rule (Rule.Eval _) = []
   383   | thm_of_rule (Rule.Cal1 _) = []
   384   | thm_of_rule (Rule.Rls_ rls) = thms_of_rls rls
   385 and thms_of_rls Rule_Set.Empty = []
   386   | thms_of_rls (Rule_Def.Repeat {rules,...}) = (flat o (map  thm_of_rule)) rules
   387   | thms_of_rls (Rule_Set.Sequence {rules,...}) = (flat o (map  thm_of_rule)) rules
   388   | thms_of_rls (Rule_Set.Rrls _) = []
   389 
   390 (* check if a rule is contained in a rule-set (recursivley down in Rls_);
   391    this rule can even be a rule-set itself                             *)
   392 fun contains_rule r rls = 
   393   let 
   394     fun (*find (_, Rls_ rls) = finds (get_rules rls)
   395       | find r12 = equal r12
   396     and*) finds [] = false
   397     | finds (r1 :: rs) = if Rule.equal (r, r1) then true else finds rs
   398   in 
   399     finds (Rule_Set.get_rules rls) 
   400   end
   401 
   402 (* try if a rewrite-rule is applicable to a given formula; 
   403    in case of rule-sets (recursivley) collect all _atomic_ rewrites *) 
   404 fun try_rew thy ((_, ro) : Rewrite_Ord.rew_ord) erls (subst : UnparseC.subst) f (thm' as Rule.Thm (_, thm)) =
   405     if Auto_Prog.contains_bdv thm
   406     then case Rewrite.rewrite_inst_ thy ro erls false subst thm f of
   407 	    SOME _ => [Tactic.rule2tac thy subst thm']
   408 	  | NONE => []
   409     else (case Rewrite.rewrite_ thy ro erls false thm f of
   410 	    SOME _ => [Tactic.rule2tac thy [] thm']
   411 	  | NONE => [])
   412   | try_rew thy _ _ _ f (cal as Rule.Eval c) = 
   413     (case Eval.adhoc_thm thy c f of
   414 	    SOME _ => [Tactic.rule2tac thy [] cal]
   415     | NONE => [])
   416   | try_rew thy _ _ _ f (cal as Rule.Cal1 c) = 
   417     (case Eval.adhoc_thm thy c f of
   418 	      SOME _ => [Tactic.rule2tac thy [] cal]
   419       | NONE => [])
   420   | try_rew thy _ _ subst f (Rule.Rls_ rls) = filter_appl_rews thy subst f rls
   421   | try_rew _ _ _ _ _ _ = error "try_rew: uncovered case"
   422 and filter_appl_rews thy subst f (Rule_Def.Repeat {rew_ord = ro, erls, rules, ...}) = 
   423     gen_distinct Tactic.eq_tac (flat (map (try_rew thy ro erls subst f) rules))
   424   | filter_appl_rews thy subst f (Rule_Set.Sequence {rew_ord = ro, erls, rules,...}) = 
   425     gen_distinct Tactic.eq_tac (flat (map (try_rew thy ro erls subst f) rules))
   426   | filter_appl_rews _ _ _ (Rule_Set.Rrls _) = []
   427   | filter_appl_rews _ _ _ _ = error "filter_appl_rews: uncovered case"
   428 
   429 (* decide if a tactic is applicable to a given formula; 
   430    in case of Rewrite_Set* go down to _atomic_ rewrite-tactics *)
   431 fun atomic_appl_tacs thy _ _ f (Tactic.Calculate scrID) =
   432     try_rew thy Rewrite_Ord.e_rew_ordX Rule_Set.empty [] f (Rule.Eval (assoc_calc' thy scrID |> snd))
   433   | atomic_appl_tacs thy ro erls f (Tactic.Rewrite thm'') =
   434     try_rew thy (ro, Rewrite_Ord.assoc_rew_ord ro) erls [] f (Rule.Thm thm'')
   435   | atomic_appl_tacs thy ro erls f (Tactic.Rewrite_Inst (subs, thm'')) =
   436     try_rew thy (ro, Rewrite_Ord.assoc_rew_ord ro) erls (Selem.subs2subst thy subs) f (Rule.Thm thm'')
   437 
   438   | atomic_appl_tacs thy _ _ f (Tactic.Rewrite_Set rls') =
   439     filter_appl_rews thy [] f (assoc_rls rls')
   440   | atomic_appl_tacs thy _ _ f (Tactic.Rewrite_Set_Inst (subs, rls')) =
   441     filter_appl_rews thy (Selem.subs2subst thy subs) f (assoc_rls rls')
   442   | atomic_appl_tacs _ _ _ _ tac = 
   443     (tracing ("### atomic_appl_tacs: not impl. for tac = '" ^ Tactic.input_to_string tac ^ "'"); []);
   444 
   445 (* filenames not only for thydata, but also for thy's etc *)
   446 fun theID2filename theID = Celem.theID2guh theID ^ ".xml"
   447 
   448 fun guh2theID guh =
   449   let
   450     val guh' = Symbol.explode guh
   451     val part = implode (take_fromto 1 4 guh')
   452     val isa = implode (take_fromto 5 9 guh')
   453   in
   454     if not (member op = ["exp_", "thy_", "pbl_", "met_"] part)
   455     then raise ERROR ("guh '" ^ guh ^ "' does not begin with exp_ | thy_ | pbl_ | met_")
   456     else
   457       let
   458   	    val chap = case isa of
   459   		  "isab_" => "Isabelle"
   460   		| "scri_" => "IsacScripts"
   461   		| "isac_" => "IsacKnowledge"
   462   		| _ =>
   463   		  raise ERROR ("guh2theID: '" ^ guh ^ "' does not have isab_ | scri_ | isac_ at position 5..9")
   464         val rest = takerest (9, guh') 
   465         val thyID = takewhile [] (not o (curry op= "-")) rest
   466         val rest' = dropuntil (curry op = "-") rest
   467 	    in case implode rest' of
   468 		    "-part" => [chap] : Celem.theID
   469       | "" => [chap, implode thyID]
   470       | "-Theorems" => [chap, implode thyID, "Theorems"]
   471       | "-Rulesets" => [chap, implode thyID, "Rulesets"]
   472       | "-Operations" => [chap, implode thyID, "Operations"]
   473       | "-Orders" => [chap, implode thyID, "Orders"]
   474       | _ => 
   475 		    let val sect = implode (take_fromto 1 5 rest')
   476 		       val sect' = case sect of
   477 			       "-thm-" => "Theorems"
   478 			     | "-rls-" => "Rulesets"
   479 			     | "-cal-" => "Operations"
   480 			     | "-ord-" => "Orders"
   481 			     | _ =>
   482 			     raise ERROR ("guh2theID: '" ^ guh ^ "' has '" ^ sect ^ "' instead -thm- | -rls- | -cal- | -ord-")
   483 		    in
   484 		      [chap, implode thyID, sect', implode (takerest (5, rest'))]
   485 		    end
   486 	    end	
   487     end
   488 
   489 fun guh2filename guh = guh ^ ".xml";
   490 
   491 fun guh2rewtac guh [] =
   492     let
   493       val (_, thy, sect, xstr) = case guh2theID guh of
   494         [isa, thy, sect, xstr] => (isa, thy, sect, xstr)
   495       | _ => error "guh2rewtac: uncovered case"
   496     in case sect of
   497       "Theorems" => Tactic.Rewrite (xstr, ThmC.thm_from_thy (Celem.assoc_thy thy) xstr)
   498     | "Rulesets" => Tactic.Rewrite_Set xstr
   499     | _ => error ("guh2rewtac: not impl. for '"^xstr^"'") 
   500     end
   501   | guh2rewtac guh subs =
   502     let
   503       val (_, thy, sect, xstr) = case guh2theID guh of
   504         [isa, thy, sect, xstr] => (isa, thy, sect, xstr)
   505       | _ => error "guh2rewtac: uncovered case"
   506     in case sect of
   507       "Theorems" => 
   508         Tactic.Rewrite_Inst (subs, (xstr, ThmC.thm_from_thy (Celem.assoc_thy thy) xstr))
   509     | "Rulesets" => Tactic.Rewrite_Set_Inst (subs,  xstr)
   510     | str => error ("guh2rewtac: not impl. for '" ^ str ^ "'") 
   511     end
   512 
   513 (* the front-end may request a context for any element of the hierarchy *)
   514 fun no_thycontext guh = (guh2theID guh; false)
   515   handle ERROR _ => true;
   516 
   517 (* get the substitution of bound variables for matchTheory:
   518    # lookup the thm|rls' in the script
   519    # take the [(bdv, v_),..] from the respective Rewrite_(Set_)Inst
   520    # instantiate this subs with the istates env to [(bdv, x),..]
   521    # otherwise []
   522    WN060617 hack assuming that all scripts use only one bound variable
   523    and use 'v_' as the formal argument for this bound variable*)
   524 fun subs_from (Istate.Pstate (pst as {env, ...})) _ guh =
   525     let
   526       val (_, _, thyID, sect, xstr) = case guh2theID guh of
   527         theID as [isa, thyID, sect, xstr] => (theID, isa, thyID, sect, xstr)
   528       | _ => error "subs_from: uncovered case"
   529     in
   530       case sect of
   531         "Theorems" => 
   532           let val thm = Global_Theory.get_thm (Celem.assoc_thy (ThyC.thyID2theory' thyID)) xstr
   533           in
   534             if Auto_Prog.contains_bdv thm
   535             then
   536               let
   537                 val formal_arg = TermC.str2term "v_"      
   538                 val value = subst_atomic env formal_arg
   539               in ["(''bdv''," ^ UnparseC.term value ^ ")"] : Selem.subs end
   540             else []
   541 	        end
   542   	  | "Rulesets" => 
   543         let
   544           val rules = (Rule_Set.get_rules o assoc_rls) xstr
   545         in
   546           if Auto_Prog.contain_bdv rules
   547           then
   548             let
   549               val formal_arg = TermC.str2term "v_"
   550               val value = subst_atomic env formal_arg
   551             in ["(''bdv''," ^ UnparseC.term value ^ ")"] : Selem.subs end
   552           else []
   553         end
   554       | str => error ("subs_from: uncovered case with " ^ str)
   555     end
   556   | subs_from _ _  guh = error ("subs_from: uncovered case with " ^ guh)
   557 
   558 (* get a substitution for "bdv*" from the current program and environment.
   559     returns a substitution: sube for tac, subst for tac_, i.e. for rewriting *)
   560 fun get_bdv_subst prog env =
   561   let
   562     fun scan (Const _) = NONE
   563       | scan (Free _) = NONE
   564       | scan (Var _) = NONE
   565       | scan (Bound _) = NONE
   566       | scan (t as Const ("List.list.Cons", _) $ (Const ("Product_Type.Pair", _) $ _ $ _) $ _) =
   567         if TermC.is_bdv_subst t then SOME t else NONE
   568       | scan (Abs (_, _, body)) = scan body
   569       | scan (t1 $ t2) = case scan t1 of NONE => scan t2 | SOME subst => SOME subst
   570   in
   571     case scan prog of
   572       NONE => (NONE: Selem.subs option, []: UnparseC.subst)
   573     | SOME tm =>
   574         let val subst = subst_atomic env tm
   575         in (SOME (Selem.subst'_to_sube subst), Selem.subst'_to_subst subst) end
   576   end
   577 
   578 end