src/Tools/isac/MathEngBasic/rewrite.sml
author wenzelm
Sun, 18 Apr 2021 23:37:59 +0200
changeset 60223 740ebee5948b
parent 60203 eb278178c278
child 60261 1790e1073acc
permissions -rw-r--r--
conditional compilation via system option "isac_test" and antiquotation \<^isac_test>CARTOUCHE:
option is provided in session ROOT, or interactively via $ISABELLE_HOME_USER/etc/preferences (i.e. Isabelle/jEdit plugin preferences);
     1 (* isac's rewriter
     2    (c) Walther Neuper 2000
     3 *)
     4 
     5 signature REWRITE =
     6 sig
     7   val calculate_: theory -> string * Eval_Def.eval_fn -> term -> (term * (string * thm)) option
     8   val eval__true: theory -> int -> term list -> (term * term) list -> Rule_Set.T -> term list * bool
     9   val eval_prog_expr: theory -> Rule_Set.T -> term -> term
    10   val eval_true_: theory -> Rule_Set.T -> term -> bool
    11   val eval_true: theory -> term list -> Rule_Set.T -> bool
    12   val rew_sub: theory -> int -> (term * term) list -> Rule_Def.rew_ord_
    13     -> Rule_Set.T -> bool -> TermC.path -> term -> term -> term * term list * TermC.path * bool
    14   val rewrite_: theory -> Rule_Def.rew_ord_ -> Rule_Set.T -> bool -> thm ->
    15     term -> (term * term list) option
    16   val rewrite_inst_: theory -> Rule_Def.rew_ord_ -> Rule_Set.T -> bool
    17     -> (term * term) list -> thm -> term -> (term * term list) option
    18   val rewrite_set_: theory -> bool -> Rule_Set.T -> term -> (term * term list) option
    19   val rewrite_set_inst_: theory -> bool -> (term * term) list -> Rule_Set.T -> term -> (term * term list) option
    20   val rewrite_terms_: theory -> Rule_Def.rew_ord_ -> Rule_Set.T -> term list
    21     -> term -> (term * term list) option
    22 
    23   val trace_on: bool Unsynchronized.ref
    24   val depth: int Unsynchronized.ref
    25   val lim_deriv: int Unsynchronized.ref
    26 
    27 \<^isac_test>\<open>
    28   val rewrite__: theory -> int -> (term * term) list -> Rule_Def.rew_ord_ ->
    29     Rule_Set.T -> bool -> thm -> term -> (term * term list) option
    30   val rewrite__set_: theory -> int -> bool -> (term * term) list -> Rule_Set.T -> term -> (term * term list) option
    31   val app_rev: theory -> int -> Rule_Set.T -> term -> term * term list * bool
    32   val app_sub: theory -> int -> Rule_Set.T -> term -> term * term list * bool
    33   val trace1: int -> string -> unit
    34 \<close>
    35 end
    36 
    37 (**)
    38 structure Rewrite(**): REWRITE(**) =
    39 struct
    40 (**)
    41 
    42 exception NO_REWRITE;
    43 exception STOP_REW_SUB; (*WN050820 quick and dirty*)
    44 
    45 val trace_on = Unsynchronized.ref false;
    46 (* depth of recursion in traces of the rewriter, if trace_on:=true *)
    47 val depth = Unsynchronized.ref 99999;
    48 (* no of rewrites exceeding this int -> NO rewrite *)
    49 val lim_deriv = Unsynchronized.ref 100;
    50 
    51 fun trace i str = 
    52   if ! trace_on andalso i < ! depth then tracing (idt "#" i ^ str) else ()
    53 fun trace1 i str = 
    54   if ! trace_on andalso i < ! depth then tracing (idt "#" (i + 1) ^ str) else ()
    55 
    56 fun rewrite__ thy i bdv tless rls put_asm thm ct =
    57   let
    58     val (t', asms, _ (*lrd*), rew) = rew_sub thy i bdv tless rls put_asm ([(*root of the term*)]: TermC.path)
    59 		  (TermC.inst_bdv bdv (Eval.norm (Thm.prop_of thm))) ct
    60   in if rew then SOME (t', distinct op = asms) else NONE end
    61   (* one rewrite (possibly conditional, ordered) EXOR exn EXOR go into subterms *)
    62 and rew_sub thy i bdv tless rls put_asm lrd r t = 
    63   (let
    64     val (lhs, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop o Logic.strip_imp_concl) r
    65     (*?alternative Unify.matchers:
    66       http://isabelle.in.tum.de/repos/isabelle/file/Isabelle2017/src/Pure/more_unify.ML*)
    67     val r' = Envir.subst_term (Pattern.match thy (lhs, t) (Vartab.empty, Vartab.empty)) r
    68     val p' = map HOLogic.dest_Trueprop ((fst o Logic.strip_prems) (Logic.count_prems r', [], r'))
    69     val t' = (snd o HOLogic.dest_eq o HOLogic.dest_Trueprop o Logic.strip_imp_concl) r'
    70     val _ = if ! trace_on andalso i < ! depth andalso p' <> []
    71 	    then tracing (idt "#" (i + 1) ^ " eval asms: " ^ UnparseC.term_in_thy thy r') else ()
    72     val (t'', p'') =                                                     (*conditional rewriting*)
    73       let
    74         val (simpl_p', nofalse) = eval__true thy (i + 1) p' bdv rls 	     
    75 	    in
    76 	      if nofalse
    77         then
    78           (if ! trace_on andalso i < ! depth andalso p' <> []
    79           then tracing (idt "#" (i + 1) ^ " asms accepted: " ^ UnparseC.terms_in_thy thy p' ^
    80   	        "   stored: " ^ UnparseC.terms_in_thy thy simpl_p')
    81   	      else();
    82           (t',simpl_p'))                                               (* uncond.rew. from above*)
    83         else 
    84           (if ! trace_on andalso i < ! depth 
    85           then tracing (idt "#" (i + 1) ^ " asms false: " ^ UnparseC.terms_in_thy thy p')
    86           else();
    87           raise STOP_REW_SUB (* don't go into subterms of cond *))
    88 	    end
    89     in
    90       if TermC.perm lhs rhs andalso not (tless bdv (t', t))                        (*ordered rewriting*)
    91       then (if ! trace_on andalso i < ! depth 
    92   	    then tracing (idt"#"i ^ " not: \"" ^ UnparseC.term_in_thy thy t ^ "\" > \"" ^ UnparseC.term_in_thy thy t' ^ "\"")
    93   	    else (); 
    94   	    raise NO_REWRITE)
    95   	  else (t'', p'', [], true)
    96     end
    97     ) handle _ (*TODO Pattern.MATCH when tests are ready: ERROR 364ce4699452 *) => 
    98       (case t of
    99         Const(s,T) => (Const(s,T),[],lrd,false)
   100       | Free(s,T) => (Free(s,T),[],lrd,false)
   101       | Var(n,T) => (Var(n,T),[],lrd,false)
   102       | Bound i => (Bound i,[],lrd,false)
   103       | Abs(s,T,body) => 
   104         let val (t', asms, _ (*lrd*), rew) =  rew_sub thy i bdv tless rls put_asm (lrd @ [TermC.D]) r body
   105     	   in (Abs(s, T, t'), asms, [], rew) end
   106       | t1 $ t2 => 
   107     	   let val (t2', asm2, lrd, rew2) = rew_sub thy i bdv tless rls put_asm (lrd @ [TermC.R]) r t2
   108     	   in
   109     	    if rew2 then (t1 $ t2', asm2, lrd, true)
   110     	    else
   111     	      let val (t1', asm1, lrd, rew1) = rew_sub thy i bdv tless rls put_asm (lrd @ [TermC.L]) r t1
   112     	      in if rew1 then (t1' $ t2, asm1, lrd, true) else (t1 $ t2,[], lrd, false) end
   113   end)
   114 and eval__true thy i asms bdv rls =         (* simplify asumptions until one evaluates to false *)
   115   if asms = [@{term True}] orelse asms = [] then ([], true)
   116   else (* this allows to check Rrls with prepat = ([@{term True}], pat) *)
   117     if asms = [@{term False}] then ([], false)
   118     else
   119       let                            
   120         fun chk indets [] = (indets, true) (*return asms<>True until false*)
   121           | chk indets (a :: asms) =
   122             (case rewrite__set_ thy (i + 1) false bdv rls a of
   123               NONE => (chk (indets @ [a]) asms)
   124             | SOME (t, a') =>
   125               if t = @{term True} then (chk (indets @ a') asms) 
   126               else if t = @{term False} then ([], false)
   127             (*asm false .. thm not applied ^^^; continue until False vvv*)
   128             else chk (indets @ [t] @ a') asms);
   129       in chk [] asms end
   130 and rewrite__set_ thy _ __ Rule_Set.Empty t =                             (* rewrite with a rule set *)
   131     raise ERROR ("rewrite__set_ called with 'Erls' for '" ^ UnparseC.term_in_thy thy t ^ "'")
   132   | rewrite__set_ thy i _ _ (rrls as Rule_Set.Rrls _) t =      (* rewrite with a 'reverse rule set' *)
   133     let
   134       val _= trace i (" rls: " ^ Rule_Set.id rrls ^ " on: " ^ UnparseC.term_in_thy thy t)
   135 	    val (t', asm, rew) = app_rev thy (i + 1) rrls t                   
   136     in if rew then SOME (t', distinct op = asm) else NONE end
   137   | rewrite__set_ thy i put_asm bdv rls ct =          (* Rls, Seq containing Thms or Eval, Cal1 *)
   138     let
   139       (* attention with cp to test/..: unbound thy, i, bdv, rls; TODO1803? pull out to rewrite__*)
   140       datatype switch = Appl | Noap;
   141       fun rew_once _ asm ct Noap [] = (ct, asm)         (* ?TODO unify with Prog_Expr.rew_once? *)
   142         | rew_once ruls asm ct Appl [] = 
   143           (case rls of Rule_Def.Repeat _ => rew_once ruls asm ct Noap ruls
   144           | Rule_Set.Sequence _ => (ct, asm)
   145           | rls => raise ERROR ("rew_once not appl. to \"" ^ Rule_Set.id rls ^ "\""))
   146         | rew_once ruls asm ct apno (rul :: thms) =
   147           case rul of
   148             Rule.Thm (thmid, thm) =>
   149               (trace1 i (" try thm: \"" ^ thmid ^ "\"");
   150               case rewrite__ thy (i + 1) bdv ((snd o #rew_ord o Rule_Set.rep) rls)
   151                   ((#erls o Rule_Set.rep) rls) put_asm thm ct of
   152                 NONE => rew_once ruls asm ct apno thms
   153               | SOME (ct', asm') => 
   154                 (trace1 i (" rewrites to: \"" ^ UnparseC.term_in_thy thy ct' ^ "\"");
   155                 rew_once ruls (union (op =) asm asm') ct' Appl (rul :: thms)))
   156                 (* once again try the same rule, e.g. associativity against "()"*)
   157           | Rule.Eval (cc as (op_, _)) => 
   158             let val _= trace1 i (" try calc: \"" ^ op_ ^ "\"")
   159               val ct = TermC.uminus_to_string ct (*WN190312: superfluous?*)
   160             in case Eval.adhoc_thm thy cc ct of
   161                 NONE => rew_once ruls asm ct apno thms
   162               | SOME (_, thm') => 
   163                 let 
   164                   val pairopt = rewrite__ thy (i + 1) bdv ((snd o #rew_ord o Rule_Set.rep) rls)
   165                     ((#erls o Rule_Set.rep) rls) put_asm thm' ct;
   166                   val _ = if pairopt <> NONE then () else raise ERROR ("rewrite_set_, rewrite_ \"" ^ 
   167                     ThmC.string_of_thm thm' ^ "\" " ^ UnparseC.term_in_thy thy ct ^ " = NONE")
   168                   val _ = trace1 i (" calc. to: " ^ UnparseC.term_in_thy thy ((fst o the) pairopt))
   169                 in rew_once ruls asm ((fst o the) pairopt) Appl (rul :: thms) end
   170             end
   171           | Rule.Cal1 (cc as (op_, _)) => 
   172             let val _= trace1 i (" try cal1: " ^ op_ ^ "'");
   173               val ct = TermC.uminus_to_string ct
   174             in case Eval.adhoc_thm1_ thy cc ct of
   175                 NONE => (ct, asm)
   176               | SOME (_, thm') =>
   177                 let 
   178                   val pairopt = rewrite__ thy (i + 1) bdv ((snd o #rew_ord o Rule_Set.rep) rls)
   179                     ((#erls o Rule_Set.rep) rls) put_asm thm' ct;
   180                   val _ = if pairopt <> NONE then () else raise ERROR ("rewrite_set_, rewrite_ \"" ^
   181                      ThmC.string_of_thm thm' ^ "\" " ^ UnparseC.term_in_thy thy ct ^ " = NONE")
   182                   val _ = trace1 i (" cal1. to: " ^ UnparseC.term_in_thy thy ((fst o the) pairopt))
   183                 in the pairopt end
   184             end
   185           | Rule.Rls_ rls' => 
   186             (case rewrite__set_ thy (i + 1) put_asm bdv rls' ct of
   187               SOME (t', asm') => rew_once ruls (union (op =) asm asm') t' Appl thms
   188             | NONE => rew_once ruls asm ct apno thms)
   189           | r => raise ERROR ("rew_once not appl. to \"" ^ Rule.to_string r ^ "\"");
   190       val ruls = (#rules o Rule_Set.rep) rls;
   191       val _ = trace i (" rls: " ^ Rule_Set.id rls ^ " on: " ^ UnparseC.term_in_thy thy ct)
   192       val (ct', asm') = rew_once ruls [] ct Noap ruls;
   193 	  in if ct = ct' then NONE else SOME (ct', distinct op =  asm') end
   194 (*-------------------------------------------------------------*)
   195 and app_rev thy i rrls t =            (* apply an Rrls; if not applicable proceed with subterms *)
   196   let (* check a (precond, pattern) of a rev-set; stops with 1st true *)
   197     fun chk_prepat _ _ [] _ = true
   198       | chk_prepat thy erls prepat t =
   199         let
   200           fun chk (pres, pat) =
   201             (let 
   202               val subst: Type.tyenv * Envir.tenv =
   203                 Pattern.match thy (pat, t) (Vartab.empty, Vartab.empty)
   204              in
   205               snd (eval__true thy (i + 1) (map (Envir.subst_term subst) pres) [] erls)
   206              end) handle _ (*TODO Pattern.MATCH*) => false
   207            fun scan_ _ [] = false
   208              | scan_ f (pp :: pps) =
   209                if f pp then true else scan_ f pps;
   210         in scan_ chk prepat end;
   211     (* apply the normal_form of a rev-set *)
   212     fun app_rev' thy (Rule_Set.Rrls {erls, prepat, scr = Rule.Rfuns {normal_form, ...}, ...}) t =
   213       if chk_prepat thy erls prepat t then normal_form t else NONE
   214       | app_rev' _ r _ = raise ERROR ("app_rev' not appl. to \"" ^ Rule_Set.id r ^ "\"");
   215     val opt = app_rev' thy rrls t
   216   in
   217     case opt of
   218       SOME (t', asm) => (t', asm, true)
   219     | NONE => app_sub thy i rrls t
   220   end
   221 and app_sub thy i rrls t =                                         (* apply an Rrls to subterms *)
   222   case t of
   223     Const (s, T) => (Const(s, T), [], false)
   224   | Free (s, T) => (Free(s, T), [], false)
   225   | Var (n, T) => (Var(n, T), [], false)
   226   | Bound i => (Bound i, [], false)
   227   | Abs (s, T, body) => 
   228 	  let val (t', asm, rew) = app_rev thy i rrls body
   229 	  in (Abs(s, T, t'), asm, rew) end
   230   | t1 $ t2 => 
   231     let val (t2', asm2, rew2) = app_rev thy i rrls t2
   232     in
   233       if rew2 then (t1 $ t2', asm2, true)
   234       else
   235         let val (t1', asm1, rew1) = app_rev thy i rrls t1
   236         in if rew1 then (t1' $ t2, asm1, true)
   237            else (t1 $ t2, [], false)
   238         end
   239     end;
   240 
   241 (* rewriting without argument [] for rew_ord;  WN110603: shouldnt asm<>[] lead to false? *)
   242 fun eval_true thy terms rls = (snd o (eval__true thy 1 terms [])) rls;
   243 
   244 (* rewriting without internal argument [] *)
   245 fun rewrite_ thy rew_ord erls bool thm term = rewrite__ thy 1 [] rew_ord erls bool thm term;
   246 fun rewrite_set_ thy bool rls term = rewrite__set_ thy 1 bool [] rls term;
   247 
   248 (* variants of rewrite; TODO del. put_asm *)
   249 fun rewrite_inst_  thy rew_ord rls put_asm subst thm ct =
   250   rewrite__ thy 1 subst rew_ord rls put_asm thm ct;
   251 fun rewrite_set_inst_ thy put_asm subst rls ct = rewrite__set_ thy 1 put_asm subst rls ct;
   252 
   253 (* given a list of equalities (lhs = rhs) and a term, 
   254    replace all occurrences of lhs in the term with rhs;
   255    thus the order or equalities matters: put variables in lhs first. *)
   256 fun rewrite_terms_ thy ord erls equs t =
   257   let
   258 	  fun rew_ (t', asm') [] _ = (t', asm')
   259 	    | rew_ (t', asm') (rules as r::rs) t =
   260 	        let
   261 	          val (t'', asm'', _(*lrd*), rew) = rew_sub thy 1 [] ord erls false [] (HOLogic.Trueprop $ r) t
   262 	        in 
   263 	          if rew 
   264 	          then rew_ (t'', asm' @ asm'') rules t''
   265 	          else rew_ (t', asm') rs t'
   266 	        end
   267 	  val (t'', asm'') = rew_ (TermC.empty, []) equs t
   268     in if t'' = TermC.empty then NONE else SOME (t'', asm'')
   269     end;
   270 
   271 (* search ct for adjacent numerals and calculate them by operator isa_fn *)
   272 fun calculate_ thy isa_fn ct =
   273   let val ct = TermC.uminus_to_string ct
   274     in case Eval.adhoc_thm thy isa_fn ct of
   275 	   NONE => NONE
   276 	 | SOME (thmID, thm) =>
   277 	   (let val rew = case rewrite_ thy Rewrite_Ord.dummy_ord Rule_Set.empty false thm ct of
   278          SOME (rew, _) => rew
   279        | NONE => raise ERROR ""
   280      in SOME (rew, (thmID, thm)) end)
   281 	   handle _ (*TODO Pattern.MATCH ?del?*)=> raise ERROR ("calculate_: " ^ thmID ^ " does not rewrite")
   282   end;
   283 
   284 fun eval_prog_expr thy srls t =
   285   let val rew = rewrite_set_ thy false srls t;
   286   in case rew of SOME (res,_) => res | NONE => t end;
   287 
   288 fun eval_true_ _ _ (Const ("HOL.True",_)) = true
   289   | eval_true_ thy rls t =
   290     case rewrite_set_ thy false rls t of
   291 	   SOME (Const ("HOL.True",_),_) => true
   292 	 | _ => false;
   293 
   294 end