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