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