src/Tools/isac/ProgLang/rewrite.sml
author Walther Neuper <wneuper@ist.tugraz.at>
Fri, 23 Feb 2018 07:29:36 +0100
changeset 59380 8b08d9296654
parent 59352 172b53399454
child 59381 cb7e75507c05
permissions -rw-r--r--
separate structure Rewrite : REWRITE
neuper@37906
     1
(* isac's rewriter
neuper@37906
     2
   (c) Walther Neuper 2000
neuper@37906
     3
*)
neuper@37906
     4
wneuper@59380
     5
signature REWRITE =
wneuper@59380
     6
  sig
wneuper@59380
     7
    val assoc_thm': theory -> thm' -> thm
wneuper@59380
     8
    val assoc_thm'': theory -> thmID -> thm
wneuper@59380
     9
    val calculate_: theory -> string * eval_fn -> term -> (term * (string * thm)) option
wneuper@59380
    10
    val eval__true: theory -> int -> term list -> (term * term) list -> rls -> term list * bool
wneuper@59380
    11
    val eval_listexpr_: theory -> rls -> term -> term
wneuper@59380
    12
    val eval_true: theory -> term list -> rls -> bool
wneuper@59380
    13
    val eval_true_: theory' -> rls -> term -> bool
wneuper@59380
    14
    val rew_sub: theory -> int -> (term * term) list -> ((term * term) list -> term * term -> bool) -> rls -> bool -> lrd list -> term -> term -> term * term list * lrd list * bool
wneuper@59380
    15
    val rewrite_: theory -> ((term * term) list -> term * term -> bool) -> rls -> bool -> thm -> term -> (term * term list) option
wneuper@59380
    16
    val rewrite_inst_: theory -> ((term * term) list -> term * term -> bool) -> rls -> bool -> (term * term) list -> thm -> term -> (term * term list) option
wneuper@59380
    17
    val rewrite_set_: theory -> bool -> rls -> term -> (term * term list) option
wneuper@59380
    18
    val rewrite_set_inst_: theory -> bool -> (term * term) list -> rls -> term -> (term * term list) option
wneuper@59380
    19
    val rewrite_terms_: theory -> ((term * term) list -> term * term -> bool) -> rls -> term list -> term -> (term * term list) option
wneuper@59380
    20
(* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
wneuper@59380
    21
  (* NONE *)
wneuper@59380
    22
(*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
wneuper@59380
    23
  (* NONE *)
wneuper@59380
    24
(* probably shift up ---------------
wneuper@59380
    25
    exception NO_REWRITE
wneuper@59380
    26
    exception STOP_REW_SUB
wneuper@59380
    27
    val adhoc_thm': theory' -> string * eval_fn -> cterm' -> thm' option
wneuper@59380
    28
    val app_rev: theory -> int -> rls -> term -> term * term list * bool
wneuper@59380
    29
    val app_sub: theory -> int -> rls -> term -> term * term list * bool
wneuper@59380
    30
    val calculate: theory' -> string * eval_fn -> cterm' -> (string * thm') option
wneuper@59380
    31
    val convert: 'a -> string -> string
wneuper@59380
    32
    val convert_metaview_to_thmid: theory -> string -> thm
wneuper@59380
    33
    val eval_true': theory' -> rls' -> term -> bool
wneuper@59380
    34
    val get_rls_scr: rls' -> scr
wneuper@59380
    35
    val mk_thm: theory -> string -> thm
wneuper@59380
    36
    val mk_thm'': theory -> term -> thm
wneuper@59380
    37
    val parse': theory' -> cterm' -> cterm' option
wneuper@59380
    38
    val rewrite: theory' -> rew_ord' -> rls' -> bool -> thm' -> cterm' -> (string * string) option
wneuper@59380
    39
    val rewrite__: theory -> int -> (term * term) list -> ((term * term) list -> term * term -> bool) -> rls -> bool -> thm -> term -> (term * term list) option
wneuper@59380
    40
    val rewrite__set_: theory -> int -> bool -> (term * term) list -> rls -> term -> (term * term list) option
wneuper@59380
    41
    val rewrite_inst: theory' -> rew_ord' -> rls' -> bool -> 'a -> thm' -> cterm' -> (cterm' * cterm' list) option
wneuper@59380
    42
    val rewrite_set: theory' -> bool -> rls' -> cterm' -> (string * string) option
wneuper@59380
    43
    val rewrite_set_inst: theory' -> bool -> subs' -> rls' -> cterm' -> (string * string) option
wneuper@59380
    44
    val subs'2subst: theory -> subs' -> subst
wneuper@59380
    45
    val trace: int -> string -> unit
wneuper@59380
    46
    val trace1: int -> string -> unit
wneuper@59380
    47
--------------------------------------*)
wneuper@59380
    48
( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
wneuper@59380
    49
  end
wneuper@59380
    50
wneuper@59380
    51
(**)
wneuper@59380
    52
structure Rewrite(**): REWRITE(**) =
wneuper@59380
    53
struct
wneuper@59380
    54
(**)
neuper@37906
    55
neuper@37906
    56
exception NO_REWRITE;
neuper@37906
    57
exception STOP_REW_SUB; (*WN050820 quick and dirty*)
neuper@37906
    58
neuper@52101
    59
fun trace i str = 
neuper@52101
    60
  if ! trace_rewrite andalso i < ! depth then tracing (idt "#" i ^ str) else ()
neuper@52101
    61
fun trace1 i str = 
neuper@52101
    62
  if ! trace_rewrite andalso i < ! depth then tracing (idt "#" (i + 1) ^ str) else ()
neuper@52101
    63
neuper@52084
    64
(* 
neuper@52084
    65
Synopsis rewriting (prep for reference manual):
neuper@52084
    66
----------------------------------------------
neuper@52084
    67
Rewriting uses theorems for transforming terms. However, not all kinds
neuper@52084
    68
of such transformations can be done by rewriting. Examples are
neuper@52084
    69
calculation with numerals or cancellation of fractions. 
neuper@52084
    70
neuper@52084
    71
Isac tries to present transformations like calculations or cancellation 
neuper@52084
    72
as simple rewrite steps for the naive user. However, some of such
neuper@52084
    73
transformations should be transparent to the user by single-stepping.
neuper@52084
    74
For instance, cancellation involves interesting CA algorithms like 
neuper@52084
    75
GCD of multivariate polynomials.
neuper@52084
    76
neuper@52084
    77
Thus Isac has two mechanisms for including SML code, "thm Calc" and "Rrls",
neuper@52084
    78
the former for steps which are not meant to be inspected by single-stepping
neuper@52084
    79
the latter meant for single-stepping and providing respective mechanisms.
neuper@52084
    80
neuper@52084
    81
(1) Inclusion by "thm Calc" for 1-step execution
neuper@52084
    82
TODO
neuper@52084
    83
neuper@52084
    84
(2) Inclusion by "Rrls" for multi-step execution
neuper@52084
    85
TODO
neuper@52084
    86
In multi-step execution "reverse rewriting" worked only as passive presentation
neuper@52084
    87
without any interaction. So the functions init_state, locate_rule etc are just dummies.
neuper@52084
    88
TODO
neuper@52084
    89
? multi-step execution did never work.
neuper@52084
    90
what worked is "reverse rewriting", 
neuper@52084
    91
i.e. presentation of intermediate steps *without* interaction
neuper@52084
    92
TODO
neuper@52084
    93
# type rule and scr | Rfuns
neuper@52084
    94
# type rrlsstate = (*state for reverse rewriting*) 
neuper@52084
    95
# type and rls | Rrls
neuper@52084
    96
all in calcelems.sml
neuper@52084
    97
TODO
neuper@52084
    98
*)
neuper@37906
    99
fun rewrite__ thy i bdv tless rls put_asm thm ct =
neuper@38022
   100
  (let
neuper@37906
   101
    val (t',asms,lrd,rew) = 
neuper@37906
   102
	rew_sub thy i bdv tless rls put_asm [(*root of the term*)]
wneuper@59187
   103
		(((inst_bdv bdv) o norm o #prop o Thm.rep_thm) thm) ct;
neuper@37906
   104
  in if rew then SOME (t', distinct asms)
neuper@37906
   105
     else NONE end)
neuper@38022
   106
(* one rewrite (possibly conditional, ordered) EXOR exn EXOR go into subterms *)
neuper@37906
   107
and rew_sub thy i bdv tless rls put_asm lrd r t = 
neuper@41928
   108
  ((*tracing ("@@@ rew_sub begin: t = "^(term2str t));
wneuper@59337
   109
   tracing ("@@@ rew_sub begin: bdv = "^(@{make_string} bdv));
neuper@41928
   110
   tracing ("@@@ rew_sub begin: r = "^(term2str r));*)
neuper@37906
   111
    let                  (* copy from Pure/thm.ML: fun rewritec *)
neuper@37906
   112
     val (lhs, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop
neuper@37906
   113
                       o Logic.strip_imp_concl) r;
wneuper@59339
   114
     (*?alternative Unify.matchers:
wneuper@59339
   115
       http://isabelle.in.tum.de/repos/isabelle/file/Isabelle2017/src/Pure/more_unify.ML*)
neuper@37906
   116
     val r' = Envir.subst_term (Pattern.match thy (lhs, t) 
neuper@37906
   117
					      (Vartab.empty, Vartab.empty)) r;
neuper@38022
   118
     val p' = map HOLogic.dest_Trueprop ((fst o Logic.strip_prems) 
neuper@38022
   119
                                             (Logic.count_prems r', [], r'));
neuper@37906
   120
     val t' = (snd o HOLogic.dest_eq o HOLogic.dest_Trueprop 
neuper@37906
   121
               o Logic.strip_imp_concl) r';
neuper@38015
   122
     (*val _= tracing("@@@ rew_sub match: t'= "^(term2str t'));*)
neuper@37906
   123
     val _= if ! trace_rewrite andalso i < ! depth andalso p' <> []
neuper@38015
   124
	    then tracing((idt"#"(i+1))^" eval asms: "^(term2str r')) else();
neuper@37976
   125
     val (t'',p'') =                                   (*conditional rewriting*)
neuper@37906
   126
	 let val (simpl_p', nofalse) = eval__true thy (i+1) p' bdv rls 	     
neuper@37906
   127
	 in if nofalse
neuper@37906
   128
	    then (if ! trace_rewrite andalso i < ! depth andalso p' <> []
neuper@38015
   129
		  then tracing((idt"#"(i+1))^" asms accepted: "^(terms2str p')^
neuper@37906
   130
			       "   stored: "^(terms2str simpl_p'))
neuper@38022
   131
		  else(); (t',simpl_p'))             (* uncond.rew. from above*)
neuper@37906
   132
	    else 
neuper@37906
   133
		(if ! trace_rewrite andalso i < ! depth 
neuper@38015
   134
		 then tracing((idt"#"(i+1))^" asms false: "^(terms2str p')) 
neuper@37906
   135
		 else(); raise STOP_REW_SUB (*dont go into subterms of cond*))
neuper@37906
   136
	 end
neuper@37976
   137
   in if perm lhs rhs andalso not (tless bdv (t',t))       (*ordered rewriting*)
neuper@37906
   138
	then (if ! trace_rewrite andalso i < ! depth 
neuper@38015
   139
	      then tracing((idt"#"i)^" not: \""^
neuper@37906
   140
	      (term2str t)^"\" > \""^
neuper@37906
   141
	      (term2str t')^"\"") else (); 
neuper@37906
   142
	      raise NO_REWRITE )
neuper@38015
   143
	else ((*tracing("##@ rew_sub: (t''= "^(term2str t'')^
neuper@37906
   144
		      ", p'' ="^(terms2str p'')^", true)");*)
neuper@37906
   145
	      (t'',p'',[],true))
neuper@37906
   146
   end
neuper@37906
   147
   ) handle _ (*NO_REWRITE WN050820 causes diff.behav. in tests + MATCH!*) => 
neuper@38015
   148
     ((*tracing ("@@@ rew_sub gosub: t = "^(term2str t));*)
neuper@37906
   149
      case t of
neuper@37906
   150
	Const(s,T) => (Const(s,T),[],lrd,false)
neuper@37906
   151
      | Free(s,T) => (Free(s,T),[],lrd,false)
neuper@37906
   152
      | Var(n,T) => (Var(n,T),[],lrd,false)
neuper@37906
   153
      | Bound i => (Bound i,[],lrd,false)
neuper@37906
   154
      | Abs(s,T,body) => 
neuper@37906
   155
	  let val (t', asms, lrd, rew) = 
neuper@37906
   156
		  rew_sub thy i bdv tless rls put_asm (lrd@[D]) r body
neuper@37906
   157
	  in (Abs(s,T,t'), asms, [], rew) end
neuper@37906
   158
      | t1 $ t2 => 
neuper@37906
   159
	  let val (t2', asm2, lrd, rew2) = 
neuper@37906
   160
		  rew_sub thy i bdv tless rls put_asm (lrd@[R]) r t2
neuper@37906
   161
	  in if rew2 then (t1 $ t2', asm2, lrd, true)
neuper@37906
   162
	     else let val (t1', asm1, lrd, rew1) = 
neuper@37906
   163
	       rew_sub thy i bdv tless rls put_asm (lrd@[L]) r t1
neuper@37906
   164
		  in if rew1 then (t1' $ t2, asm1, lrd, true)
neuper@37906
   165
		     else (t1 $ t2,[], lrd, false) end
neuper@37906
   166
	  end)
neuper@38022
   167
(* simplify asumptions until one evaluates to false, store intermined's (x~=0)*)
neuper@37906
   168
and eval__true thy i asms bdv rls =
neuper@48760
   169
  if asms = [@{term True}] orelse asms = [] then ([], true)
neuper@48760
   170
  (* this allows to check Rrls with prepat = ([@{term True}], pat) *)
neuper@52101
   171
  else if asms = [@{term False}] then ([], false) else
neuper@52085
   172
    let                            
neuper@37906
   173
      fun chk indets [] = (indets, true)(*return asms<>True until false*)
neuper@52085
   174
        | chk indets (a::asms) =
neuper@52101
   175
          (case rewrite__set_ thy (i + 1) false bdv rls a of
neuper@52085
   176
            NONE => (chk (indets @ [a]) asms)
neuper@52085
   177
          | SOME (t, a') =>
neuper@52085
   178
            if t = @{term True} then (chk (indets @ a') asms) 
neuper@52085
   179
            else if t = @{term False} then ([], false)
neuper@52085
   180
          (*asm false .. thm not applied ^^^; continue until False vvv*)
neuper@52085
   181
          else chk (indets @ [t] @ a') asms);
neuper@52085
   182
    in chk [] asms end
neuper@38022
   183
(* rewrite with a rule set, which must not be the empty Erls *)
neuper@37906
   184
and rewrite__set_ _ _ __ Erls t = 
neuper@52101
   185
    error ("rewrite__set_ called with 'Erls' for '" ^ term2str t ^ "'")
neuper@38036
   186
  (* rewrite with a 'reverse rule set' implemented by ML code *)
neuper@37906
   187
  | rewrite__set_ thy i _ _ (rrls as Rrls _) t =
neuper@52101
   188
    let
neuper@52101
   189
      val _= trace i (" rls: " ^ id_rls rrls ^ " on: " ^ term2str t)
neuper@52101
   190
	    val (t', asm, rew) = app_rev thy (i + 1) rrls t
neuper@52101
   191
    in if rew then SOME (t', distinct asm) else NONE end
neuper@38022
   192
  (* rewrite with a rule set containing Thms or Calculations *)
neuper@37906
   193
  | rewrite__set_ thy i put_asm bdv rls ct =
neuper@52101
   194
    let
neuper@52101
   195
      datatype switch = Appl | Noap;
wneuper@59263
   196
      fun rew_once ruls asm ct Noap [] = (ct, asm) (* unify with version in rewtools.sml *)
neuper@52101
   197
        | rew_once ruls asm ct Appl [] = 
neuper@52101
   198
          (case rls of Rls _ => rew_once ruls asm ct Noap ruls
neuper@52101
   199
          | Seq _ => (ct, asm))
neuper@52101
   200
        | rew_once ruls asm ct apno (rul::thms) =
neuper@52101
   201
          case rul of
neuper@52101
   202
            Thm (thmid, thm) =>
neuper@52101
   203
              (trace1 i (" try thm: " ^ thmid);
neuper@52101
   204
              case rewrite__ thy (i + 1) bdv ((snd o #rew_ord o rep_rls) rls)
neuper@52101
   205
                  ((#erls o rep_rls) rls) put_asm thm ct of
neuper@52101
   206
                NONE => rew_once ruls asm ct apno thms
neuper@52101
   207
              | SOME (ct',asm') => 
neuper@52101
   208
                (trace1 i (" rewrites to: " ^ term2str ct');
neuper@52101
   209
                rew_once ruls (union (op =) asm asm') ct' Appl (rul::thms)))
neuper@52101
   210
          | Calc (cc as (op_, _)) => 
neuper@52101
   211
            let val _= trace1 i (" try calc: " ^ op_ ^ "'")
neuper@52101
   212
              val ct = uminus_to_string ct
wneuper@59255
   213
            in case adhoc_thm thy cc ct of
neuper@52101
   214
                NONE => rew_once ruls asm ct apno thms
neuper@52101
   215
              | SOME (thmid, thm') => 
neuper@52101
   216
                let 
neuper@52101
   217
                  val pairopt = rewrite__ thy (i + 1) bdv ((snd o #rew_ord o rep_rls) rls)
neuper@52101
   218
                    ((#erls o rep_rls) rls) put_asm thm' ct;
neuper@52101
   219
                  val _ = if pairopt <> NONE then () else error ("rewrite_set_, rewrite_ \"" ^ 
neuper@52101
   220
                    string_of_thmI thm' ^ "\" " ^ term2str ct ^ " = NONE")
neuper@52101
   221
                  val _ = trace1 i (" calc. to: " ^ term2str ((fst o the) pairopt))
neuper@52101
   222
                in rew_once ruls asm ((fst o the) pairopt) Appl (rul :: thms) end
neuper@52101
   223
            end
neuper@52101
   224
          | Cal1 (cc as (op_, _)) => 
neuper@52101
   225
            let val _= trace1 i (" try cal1: " ^ op_ ^ "'");
neuper@52101
   226
              val ct = uminus_to_string ct
wneuper@59255
   227
            in case adhoc_thm1_ thy cc ct of
neuper@52101
   228
                NONE => (ct, asm)
neuper@52101
   229
              | SOME (thmid, thm') =>
neuper@52101
   230
                let 
neuper@52101
   231
                  val pairopt = rewrite__ thy (i + 1) bdv ((snd o #rew_ord o rep_rls) rls)
neuper@52101
   232
                    ((#erls o rep_rls) rls) put_asm thm' ct;
neuper@52101
   233
                  val _ = if pairopt <> NONE then () else error ("rewrite_set_, rewrite_ \"" ^
neuper@52101
   234
                     string_of_thmI thm' ^ "\" " ^ term2str ct ^ " = NONE")
neuper@52101
   235
                  val _ = trace1 i (" cal1. to: " ^ term2str ((fst o the) pairopt))
neuper@52101
   236
                in the pairopt end
neuper@52101
   237
            end
neuper@52101
   238
          | Rls_ rls' => 
neuper@52101
   239
            (case rewrite__set_ thy (i + 1) put_asm bdv rls' ct of
neuper@52101
   240
              SOME (t', asm') => rew_once ruls (union (op =) asm asm') t' Appl thms
neuper@52101
   241
            | NONE => rew_once ruls asm ct apno thms);
neuper@52101
   242
      val ruls = (#rules o rep_rls) rls;
neuper@52101
   243
      val _= trace i (" rls: " ^ id_rls rls ^ " on: " ^ term2str ct)
neuper@52101
   244
      val (ct', asm') = rew_once ruls [] ct Noap ruls;
neuper@52101
   245
	  in if ct = ct' then NONE else SOME (ct', distinct asm') end
neuper@37906
   246
neuper@52085
   247
(* apply an Rrls; if not applicable proceed with subterms *)
neuper@37906
   248
and app_rev thy i rrls t = 
neuper@52085
   249
  let (* check a (precond, pattern) of a rev-set; stops with 1st true *)
neuper@52085
   250
    fun chk_prepat thy erls [] t = true
neuper@52085
   251
      | chk_prepat thy erls prepat t =
neuper@52085
   252
        let
neuper@52085
   253
          fun chk (pres, pat) =
neuper@52085
   254
            (let 
neuper@52085
   255
              val subst: Type.tyenv * Envir.tenv =
neuper@52085
   256
                Pattern.match thy (pat, t) (Vartab.empty, Vartab.empty)
neuper@52085
   257
             in
neuper@52085
   258
              snd (eval__true thy (i + 1) (map (Envir.subst_term subst) pres) [] erls)
neuper@52085
   259
             end) handle _ => false
neuper@52085
   260
           fun scan_ f [] = false (*scan_ NEVER called by []*)
neuper@52085
   261
             | scan_ f (pp::pps) =
neuper@52085
   262
               if f pp then true else scan_ f pps;
neuper@52085
   263
        in scan_ chk prepat end;
neuper@52085
   264
    (* apply the normal_form of a rev-set *)
neuper@52101
   265
    fun app_rev' thy (Rrls {erls, prepat, scr = Rfuns {normal_form, ...}, ...}) t =
neuper@52105
   266
      if chk_prepat thy erls prepat t then normal_form t else NONE;
neuper@52085
   267
    val opt = app_rev' thy rrls t
neuper@52085
   268
  in
neuper@52085
   269
    case opt of
neuper@52085
   270
      SOME (t', asm) => (t', asm, true)
neuper@52085
   271
    | NONE => app_sub thy i rrls t
neuper@52085
   272
  end
neuper@37906
   273
neuper@52085
   274
(* apply an Rrls to subterms *)
neuper@37906
   275
and app_sub thy i rrls t =
neuper@52085
   276
  ((*tracing("### app_sub: subterm = "^(term2str t));*)
neuper@52085
   277
  case t of
neuper@52085
   278
    Const (s, T) => (Const(s, T), [], false)
neuper@52085
   279
  | Free (s, T) => (Free(s, T), [], false)
neuper@52085
   280
  | Var (n, T) => (Var(n, T), [], false)
neuper@52085
   281
  | Bound i => (Bound i, [], false)
neuper@52085
   282
  | Abs (s, T, body) => 
neuper@37906
   283
	  let val (t', asm, rew) = app_rev thy i rrls body
neuper@37906
   284
	  in (Abs(s, T, t'), asm, rew) end
neuper@52085
   285
  | t1 $ t2 => 
neuper@52085
   286
    let val (t2', asm2, rew2) = app_rev thy i rrls t2
neuper@52085
   287
    in
neuper@52085
   288
      if rew2 then (t1 $ t2', asm2, true)
neuper@52085
   289
      else
neuper@52085
   290
        let val (t1', asm1, rew1) = app_rev thy i rrls t1
neuper@52085
   291
        in if rew1 then (t1' $ t2, asm1, true)
neuper@52085
   292
           else (t1 $ t2, [], false)
neuper@52085
   293
        end
neuper@52085
   294
    end);
neuper@37906
   295
neuper@37906
   296
neuper@37906
   297
neuper@37906
   298
(*.rewriting without argument [] for rew_ord.*)
neuper@37906
   299
(*WN.11.6.03: shouldnt asm<>[] lead to false ????*)
neuper@37906
   300
fun eval_true thy terms rls = (snd o (eval__true thy 1 terms [])) rls;
neuper@37906
   301
neuper@52101
   302
(* rewriting without internal argument [] *)
neuper@52101
   303
fun rewrite_ thy rew_ord erls bool thm term = rewrite__ thy 1 [] rew_ord erls bool thm term;
neuper@52101
   304
fun rewrite_set_ thy bool rls term = rewrite__set_ thy 1 bool [] rls term;
neuper@37906
   305
neuper@37906
   306
fun subs'2subst thy (s:subs') = 
wneuper@59186
   307
    (((map (apfst (Thm.term_of o the o (parse thy)))) 
wneuper@59186
   308
     o (map (apsnd (Thm.term_of o the o (parse thy))))) s):subst;
neuper@37906
   309
neuper@37906
   310
(*.variants of rewrite.*)
neuper@37906
   311
(*FIXME 12.8.02: put_asm = true <==> rewrite_inst,
neuper@37906
   312
  thus the argument put_asm  IS NOT NECESSARY -- FIXME*)
neuper@37906
   313
(* val (rew_ord,rls,put_asm,thm,ct)=
neuper@37906
   314
       (e_rew_ord,poly_erls,false,num_str d1_isolate_add2,t);
neuper@37906
   315
   *)
neuper@37906
   316
fun rewrite_inst_ (thy:theory) rew_ord (rls:rls) (put_asm:bool) 
neuper@37906
   317
		  (subst:(term * term) list) (thm:thm) (ct:term) =
neuper@37906
   318
    rewrite__ thy 1 subst rew_ord rls put_asm thm ct;
neuper@37906
   319
neuper@37906
   320
fun rewrite_set_inst_ (thy:theory) 
neuper@37906
   321
  (put_asm:bool) (subst:(term * term) list) (rls:rls) (ct:term) =
neuper@37906
   322
  (*let 
neuper@37906
   323
    val subst = subs'2subst thy subs';
neuper@37906
   324
    val subrls = instantiate_rls subs' rls
neuper@37906
   325
  in*) rewrite__set_ thy 1 put_asm subst (*sub*)rls ct
neuper@37906
   326
  (*end*);
neuper@37906
   327
neuper@38025
   328
(* given a list of equalities (lhs = rhs) and a term, 
neuper@38025
   329
   replace all occurrences of lhs in the term with rhs;
neuper@38025
   330
   thus the order or equalities matters: put variables in lhs first. *)
neuper@38025
   331
fun rewrite_terms_ thy ord erls equs t =
neuper@42359
   332
  let
neuper@42359
   333
	  fun rew_ (t', asm') [] _ = (t', asm')
neuper@42359
   334
	    | rew_ (t', asm') (rules as r::rs) t =
neuper@42359
   335
	        let
neuper@42359
   336
	          val (t'', asm'', lrd, rew) = rew_sub thy 1 [] ord erls false [] (Trueprop $ r) t
neuper@42359
   337
	        in 
neuper@42359
   338
	          if rew 
neuper@42359
   339
	          then rew_ (t'', asm' @ asm'') rules t''
neuper@42359
   340
	          else rew_ (t', asm') rs t'
neuper@42359
   341
	        end
neuper@42359
   342
	  val (t'', asm'') = rew_ (e_term, []) equs t
neuper@42359
   343
    in if t'' = e_term then NONE else SOME (t'', asm'')
neuper@42359
   344
    end;
neuper@37906
   345
neuper@37906
   346
(*. search ct for adjacent numerals and calculate them by operator isa_fn .*)
neuper@37906
   347
fun calculate_ thy isa_fn ct =
neuper@37906
   348
  let val ct = uminus_to_string ct
wneuper@59255
   349
    in case adhoc_thm thy isa_fn ct of
neuper@37906
   350
	   NONE => NONE
neuper@37906
   351
	 | SOME (thmID, thm) => 
neuper@37906
   352
	   (let val SOME (rew,_) = rewrite_ thy dummy_ord e_rls false thm ct
neuper@37906
   353
    in SOME (rew,(thmID, thm)) end)
neuper@37906
   354
	   handle _ => error ("calculate_: "^thmID^" does not rewrite")
neuper@37906
   355
  end;
neuper@37906
   356
(*
neuper@37906
   357
> val thy = InsSort.thy;
neuper@37906
   358
> val op_ = "le";      (* < *)
neuper@37906
   359
> val ct = (the o (parse thy)) 
neuper@37906
   360
   "foldr ins [#2] (if #1 < #3 then #1 # ins [] #3 else [#3, #1])";
neuper@37906
   361
> calculate_ thy op_ ct;
neuper@37906
   362
  SOME
neuper@37906
   363
    ("foldr ins [#2] (if True then #1 # ins [] #3 else [#3, #1])",
neuper@37906
   364
     "(#1 < #3) = True") : (cterm * thm) option  *)
neuper@37906
   365
neuper@52121
   366
fun get_rls_scr rls' = ((#scr o rep_rls o assoc_rls) rls')
neuper@52121
   367
  handle _ => error ("get_rls_scr: no script for " ^ rls');
neuper@37906
   368
wneuper@59185
   369
(*Thm.make_thm added to Pure/thm.ML*)
wneuper@59250
   370
fun mk_thm'' thy t = 
wneuper@59250
   371
    let val t' = case t of
wneuper@59250
   372
		     Const ("==>",_) $ _ $ _ => t
wneuper@59250
   373
		   | _ => Trueprop $ t
wneuper@59250
   374
    in Thm.make_thm (Thm.global_cterm_of thy t') end;
neuper@37906
   375
fun mk_thm thy str = 
wneuper@59186
   376
    let val t = (Thm.term_of o the o (parse thy)) str
neuper@37906
   377
	val t' = case t of
neuper@37906
   378
		     Const ("==>",_) $ _ $ _ => t
neuper@37906
   379
		   | _ => Trueprop $ t
wneuper@59185
   380
    in Thm.make_thm (Thm.global_cterm_of thy t') end;
neuper@37906
   381
(*
neuper@37906
   382
  val str = "?r ^^^ 2 = ?r * ?r";
neuper@37906
   383
  val thm = realpow_twoI;
neuper@37906
   384
neuper@37906
   385
  val t1 = (#prop o rep_thm) (num_str thm);
wneuper@59186
   386
  val t2 = Trueprop $ ((Thm.term_of o the o (parse thy)) str);
neuper@37906
   387
  t1 = t2;
neuper@37906
   388
val it = true : bool      ... !!!
neuper@37906
   389
  val th1 = (num_str thm);
neuper@37906
   390
  val th2 = ((*num_str*) (mk_thm thy str)) handle e => print_exn e;
neuper@37906
   391
  th1 = th2;
neuper@37906
   392
ML> val it = false : bool ... HIDDEN DIFFERENCES IRRELEVANT FOR ISAC ?!
neuper@37906
   393
neuper@37906
   394
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
neuper@37906
   395
  val str = "k ~= 0 ==> m * k / (n * k) = m / n";
neuper@37906
   396
  val thm = real_mult_div_cancel2;
neuper@37906
   397
neuper@37906
   398
  val t1 = (#prop o rep_thm) (num_str thm);
wneuper@59186
   399
  val t2 = ((Thm.term_of o the o (parse thy)) str);
neuper@37906
   400
  t1 = t2;
neuper@37906
   401
val it = false : bool     ... Var .. Free
neuper@37906
   402
  val th1 = (num_str thm);
neuper@37906
   403
  val th2 = ((*num_str*) (mk_thm thy str)) handle e => print_exn e;
neuper@37906
   404
  th1 = th2;
neuper@37906
   405
ML> val it = false : bool ... PLUS HIDDEN DIFFERENCES IRRELEVANT FOR ISAC ?!
neuper@37906
   406
*)
neuper@37906
   407
neuper@37906
   408
neuper@37906
   409
(*prints subgoal etc. 
neuper@37906
   410
((goal thy);(topthm()) o ) str;                      *)
neuper@37906
   411
(*assume rejects scheme variables 
wneuper@59184
   412
  assume ((Thm.global_cterm_of thy) (Trueprop $ 
wneuper@59186
   413
		(Thm.term_of o the o (parse thy)) str)); *)
neuper@37906
   414
neuper@37906
   415
neuper@37906
   416
(* outcommented 18.11.xx, xx < 02 -------
neuper@37906
   417
fun rul2rul' (Thm (thmid, thm)) = Thm'(thmid, string_of_thmI thm)
neuper@37906
   418
  | rul2rul' (Calc op_)         = Calc' op_;
neuper@37906
   419
fun rul'2rul thy (Thm'(thmid, ct')) = 
neuper@37906
   420
       Thm (thmid, mk_thm thy ct')
neuper@37906
   421
  | rul'2rul thy' (Calc' op_)        = Calc op_;
neuper@37906
   422
neuper@37906
   423
neuper@37906
   424
fun rls2rls' (Rls{preconds=preconds,rew_ord=rew_ord,rules=rules}:rls) =
neuper@37906
   425
  Rls'{preconds'= map string_of_cterm preconds,
neuper@37906
   426
       rew_ord' = fst rew_ord,
neuper@37906
   427
       rules'   = map rul2rul' rules}:rlsdat';
neuper@37906
   428
neuper@37906
   429
fun rls'2rls thy' (Rls'{preconds'=preconds,rew_ord'=rew_ord,
neuper@37906
   430
		   rules'=rules}:rlsdat') =
neuper@38041
   431
  let val thy = assoc_thy thy';
neuper@37906
   432
  in Rls{preconds = map (the o (parse thy)) preconds,
neuper@37906
   433
	 rew_ord  = (rew_ord, the (assoc'(rew_ord',rew_ord))),
neuper@37906
   434
	 rules    = map (rul'2rul thy) rules}:rls end;
neuper@37906
   435
------- *)
neuper@37906
   436
wneuper@59108
   437
(* "metaview" as seen from programs and from user input (both are parsed like terms presently) *)
wneuper@59108
   438
fun convert_metaview_to_thmid thy thmid =
wneuper@59108
   439
  let val thmid' = case thmid of
wneuper@59108
   440
      "add_commute" => "add.commute"
wneuper@59108
   441
    | "mult_commute" => "mult.commute"
wneuper@59108
   442
    | "add_left_commute" => "add.left_commute"
wneuper@59108
   443
    | "mult_left_commute" => "mult.left_commute"
wneuper@59108
   444
    | "add_assoc" => "add.assoc"
wneuper@59108
   445
    | "mult_assoc" => "mult.assoc"
wneuper@59108
   446
    | _ => thmid
wneuper@59108
   447
  in (Global_Theory.get_thm thy) thmid' end;
wneuper@59108
   448
wneuper@59380
   449
(* FIXME: the other direction below is probably concerned with this fun:
wneuper@59380
   450
thmID_of_derivation_name' @{thm add.assoc} = "assoc"    TODO: repair this fun *);
wneuper@59108
   451
wneuper@59108
   452
fun convert thmid_to_metaview thmid =
wneuper@59108
   453
  case thmid of
wneuper@59108
   454
      "add.commute" => "add_commute"
wneuper@59108
   455
    | "mult.commute" => "mult_commute"
wneuper@59108
   456
    | "add.left_commute" => "add_left_commute"
wneuper@59108
   457
    | "mult.left_commute" => "mult_left_commute"
wneuper@59108
   458
    | "add.assoc" => "add_assoc"
wneuper@59108
   459
    | "mult.assoc" => "mult_assoc"
wneuper@59108
   460
    | _ => thmid;
wneuper@59108
   461
neuper@37906
   462
(*.get the theorem associated with the xstring-identifier;
neuper@37906
   463
   if the identifier starts with "sym_" then swap lhs = rhs around =
neuper@37906
   464
   (ATTENTION: "RS sym" attaches a [.] -- remove it with string_of_thmI);
neuper@37906
   465
   identifiers starting with "#" come from Calc and
neuper@37906
   466
   get a hand-made theorem (containing numerals only).*)
wneuper@59253
   467
fun assoc_thm'' (thy : theory) (thmid : thmID) =
wneuper@59253
   468
  case Symbol.explode thmid of
wneuper@59253
   469
    "s"::"y"::"m"::"_"::"#"::_ => error ("assoc_thm'' not impl.for " ^ thmid)
wneuper@59253
   470
  | "s"::"y"::"m"::"_"::id => ((num_str o (Global_Theory.get_thm thy)) (implode id)) RS sym
wneuper@59253
   471
  | "#"::_ => error ("assoc_thm'' not impl.for " ^ thmid)
wneuper@59253
   472
  | _ => thmid |> convert_metaview_to_thmid thy |> num_str
neuper@37906
   473
fun assoc_thm' (thy:theory) ((thmid, ct'):thm') =
neuper@55487
   474
  (case Symbol.explode thmid of
neuper@55487
   475
    "s"::"y"::"m"::"_"::id => 
neuper@55487
   476
      if hd id = "#" 
neuper@55487
   477
      then mk_thm thy ct'
neuper@55487
   478
      else ((num_str o (Global_Theory.get_thm thy)) (implode id)) RS sym
wneuper@59109
   479
  | id =>
neuper@55487
   480
    if hd id = "#" 
neuper@55487
   481
    then mk_thm thy ct'
wneuper@59109
   482
    else thmid |> convert_metaview_to_thmid thy |> num_str
wneuper@59109
   483
  ) handle _ (*TODO: fin exn behind ERROR: Undefined fact: "add_commute"*) => 
neuper@55487
   484
    error ("assoc_thm': \"" ^ thmid ^ "\" not in \"" ^ theory2domID thy ^ "\" (and parents)")
neuper@37906
   485
neuper@37906
   486
fun parse' (thy:theory') (ct:cterm') =
neuper@38041
   487
    case parse (assoc_thy thy) ct of
neuper@37906
   488
	NONE => NONE
wneuper@59186
   489
      | SOME ct => SOME ((term2str (Thm.term_of ct)):cterm');
neuper@37906
   490
neuper@37906
   491
neuper@37906
   492
(*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
neuper@37906
   493
  thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
neuper@52121
   494
fun rewrite (thy':theory') (rew_ord:rew_ord') (rls:rls') (put_asm:bool) (thm:thm') (ct:cterm') =
neuper@52121
   495
  let val thy = assoc_thy thy';
neuper@52121
   496
  in
neuper@52121
   497
    case rewrite_ thy ((the o assoc')(!rew_ord',rew_ord))(assoc_rls rls)
wneuper@59186
   498
      put_asm ((assoc_thm' thy) thm) ((Thm.term_of o the o (parse thy)) ct) of
neuper@52121
   499
      NONE => NONE
neuper@52121
   500
    | SOME (t, ts) => SOME (term2str t, terms2str ts)
neuper@52121
   501
  end;
neuper@37906
   502
neuper@37906
   503
(*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
neuper@37906
   504
  thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
neuper@52121
   505
fun rewrite_set (thy':theory') (put_asm:bool) (rls:rls') (ct:cterm') =
neuper@52121
   506
  let val thy = (assoc_thy thy');
neuper@52121
   507
  in
wneuper@59186
   508
    case rewrite_set_ thy put_asm (assoc_rls rls) ((Thm.term_of o the o (parse thy)) ct) of
neuper@52121
   509
      NONE => NONE
neuper@52121
   510
    | SOME (t, ts) => SOME (term2str t, terms2str ts)
neuper@52121
   511
  end;
neuper@37906
   512
neuper@37906
   513
fun eval_listexpr_ thy srls t =
neuper@52139
   514
  let val rew = rewrite_set_ thy false srls t;
neuper@52139
   515
  in case rew of SOME (res,_) => res | NONE => t end;
neuper@37906
   516
wneuper@59255
   517
fun adhoc_thm' (thy:theory') op_ (ct:cterm') =
wneuper@59255
   518
   case adhoc_thm (assoc_thy thy) op_
wneuper@59186
   519
    ((uminus_to_string o Thm.term_of o the o 
neuper@38041
   520
      (parse (assoc_thy thy))) ct) of
neuper@37906
   521
	NONE => NONE
neuper@37906
   522
      | SOME (thmid, thm) => 
neuper@37906
   523
	    SOME ((thmid, string_of_thmI thm):thm');
neuper@37906
   524
neuper@37906
   525
fun calculate (thy':theory') op_ (ct:cterm') =
neuper@38041
   526
    let val thy = (assoc_thy thy');
neuper@37906
   527
    in
neuper@37906
   528
	case calculate_ thy op_
wneuper@59186
   529
			((Thm.term_of o the o (parse thy)) ct) of
neuper@37906
   530
	    NONE => NONE
neuper@37906
   531
	  | SOME (ct,(thmID,thm)) => 
neuper@37906
   532
	    SOME (term2str ct, 
neuper@37906
   533
		  (thmID, string_of_thmI thm):thm')
neuper@37906
   534
    end;
neuper@37906
   535
neuper@37906
   536
(*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
neuper@37906
   537
  thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
neuper@37906
   538
fun rewrite_inst (thy':theory') (rew_ord:rew_ord') (rls:rls') 
neuper@37906
   539
  (put_asm:bool) subs (thm:thm') (ct:cterm') =
neuper@37906
   540
  let
neuper@38041
   541
    val thy = assoc_thy thy';
neuper@37906
   542
    val thm = assoc_thm' thy thm; (*28.10.02*)
neuper@37906
   543
    (*val subthm = read_instantiate subs ((assoc_thm' thy) thm)*)
neuper@37906
   544
  in
neuper@37906
   545
    case rewrite_ thy
neuper@52121
   546
      ((the o assoc')(!rew_ord',rew_ord)) (assoc_rls rls)
wneuper@59186
   547
      put_asm (*sub*)thm ((Thm.term_of o the o (parse thy)) ct) of
neuper@37906
   548
      NONE => NONE
neuper@37906
   549
    | SOME (ctm, ctms) => 
neuper@37906
   550
      SOME ((term2str ctm):cterm', (map term2str ctms):cterm' list)
neuper@37906
   551
  end;
neuper@37906
   552
neuper@37906
   553
(*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
neuper@37906
   554
  thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
neuper@37906
   555
fun rewrite_set_inst (thy':theory') (put_asm:bool)
neuper@37906
   556
  subs' (rls:rls') (ct:cterm') =
neuper@37906
   557
  let
neuper@38041
   558
    val thy = assoc_thy thy';
neuper@37906
   559
    val rls = assoc_rls rls
neuper@37906
   560
    val subst = subs'2subst thy subs'
neuper@37906
   561
  in case rewrite_set_inst_ thy put_asm subst (*sub*)rls
wneuper@59186
   562
			    ((Thm.term_of o the o (parse thy)) ct) of
neuper@37906
   563
	 NONE => NONE
neuper@37906
   564
       | SOME (t, ts) => SOME (term2str t, terms2str ts)
neuper@37906
   565
  end;
neuper@37906
   566
neuper@37906
   567
neuper@37906
   568
(*vor check_elementwise: SqRoot_eval_rls .. wie *_simplify ?! TODO *)
neuper@41928
   569
fun eval_true' (thy':theory') (rls':rls') (Const ("HOL.True",_)) = true
neuper@37906
   570
neuper@37906
   571
  | eval_true' (thy':theory') (rls':rls') (t:term) =
neuper@38050
   572
(* val thy'="Isac"; val rls'="eval_rls"; val t=hd pres';
neuper@37906
   573
   *)
neuper@37906
   574
    let val ct' = term2str t;
neuper@37906
   575
    in case rewrite_set thy' false rls' ct' of
neuper@41928
   576
	   SOME ("HOL.True",_) => true
neuper@37906
   577
	 | _ => false 
neuper@37906
   578
    end;
neuper@41928
   579
fun eval_true_ _ _ (Const ("HOL.True",_)) = true
neuper@37906
   580
  | eval_true_ (thy':theory') rls t =
neuper@37906
   581
    case rewrite_set_ (assoc_thy thy') false rls t of
neuper@41928
   582
	   SOME (Const ("HOL.True",_),_) => true
neuper@37906
   583
	 | _ => false;
neuper@37906
   584
neuper@37906
   585
(*
neuper@37906
   586
val test_rls = 
neuper@37906
   587
  Rls{preconds = [], rew_ord = ("sqrt_right",sqrt_right), 
neuper@37906
   588
      rules = [Calc ("matches",eval_matches "")
neuper@37906
   589
	       ],
wneuper@59186
   590
      scr = Prog ((Thm.term_of o the o (parse thy)) 
neuper@37906
   591
      "empty_script")
neuper@37906
   592
      }:rls;      
neuper@37906
   593
neuper@37906
   594
neuper@37906
   595
wneuper@59352
   596
  rewrite_set_ (Thy_Info_get_theory "Isac") eval_rls false test_rls 
neuper@37906
   597
        ((the o (parse thy)) "matches (?a = ?b) (x = #0)");
wneuper@59186
   598
  val xxx = (Thm.term_of o the o (parse thy)) 
neuper@37906
   599
	       "matches (?a = ?b) (x = #0)";
neuper@37906
   600
  eval_matches """" xxx thy;
neuper@37906
   601
SOME ("matches (?a = ?b) (x + #1 + #-1 * #2 = #0) = True",
neuper@41924
   602
     Const ("HOL.Trueprop","bool => prop") $ (Const # $ (# $ #) $ Const (#,#)))
neuper@37906
   603
neuper@37906
   604
neuper@37906
   605
wneuper@59352
   606
  rewrite_set_ (Thy_Info_get_theory "Isac") eval_rls false eval_rls 
neuper@37906
   607
        ((the o (parse thy)) "contains_root (sqrt #0)");
neuper@41928
   608
val it = SOME ("HOL.True",[]) : (cterm * cterm list) option
neuper@37906
   609
    
neuper@37906
   610
*)
neuper@37906
   611
neuper@37906
   612
neuper@37906
   613
(*----------WN:16.5.03 stuff below considered illdesigned, thus coded from scratch in appl.sml fun check_elementwise
neuper@37906
   614
datatype det = TRUE  | FALSE | INDET;(*FIXXME.WN:16.5.03
neuper@37906
   615
				     introduced with quick-and-dirty code*)
neuper@37906
   616
fun determine dts =
neuper@37906
   617
    let val false_indet = 
neuper@37906
   618
	    filter_out ((curry op= TRUE) o (#1:det * term -> det)) dts
neuper@37906
   619
        val ts = map (#2: det * term -> term) dts
neuper@37906
   620
    in if nil = false_indet then (TRUE, ts)
neuper@37906
   621
       else if nil = filter ((curry op= FALSE) o (#1:det * term -> det))
neuper@37906
   622
			    false_indet
neuper@37906
   623
       then (INDET, ts)
neuper@37906
   624
       else (FALSE, ts) end;
neuper@48760
   625
(* val dts = [(INDET,e_term), (FALSE,@{term False}), 
neuper@48760
   626
	      (INDET,e_term), (TRUE,@{term True})];
neuper@37906
   627
  determine dts;
neuper@37906
   628
val it =
neuper@37906
   629
  (FALSE,
neuper@41928
   630
   [Const ("empty","'a"),Const ("HOL.False","bool"),Const ("empty","'a"),
neuper@41928
   631
    Const ("HOL.True","bool")]) : det * term list*)
neuper@37906
   632
neuper@37906
   633
fun eval__indet_ thy cs rls = (*FIXXME.WN:16.5.03 pull into eval__true_, update check (check_elementwise), and regard eval_true_ + eval_true*)
neuper@48760
   634
if cs = [@{term True}] orelse cs = [] then (TRUE, [])
neuper@48760
   635
    else if cs = [@{term False}] then (FALSE, cs)
neuper@37906
   636
    else
neuper@37906
   637
	let fun eval t = 
neuper@37906
   638
		let val taopt = rewrite__set_ thy 1 false [] rls t
neuper@37906
   639
		in case taopt of
neuper@37906
   640
		       SOME (t,_) =>
neuper@48760
   641
		       if t = @{term True} then (TRUE, t)
neuper@48760
   642
		       else if t = @{term False} then (FALSE, t)
neuper@37906
   643
		       else (INDET, t)
neuper@37906
   644
		     | NONE => (INDET, t) end
neuper@37906
   645
	in (determine o (map eval)) cs end;
neuper@37906
   646
WN.16.5.0-------------------------------------------------------------*)
wneuper@59380
   647
wneuper@59380
   648
end