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