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