src/Tools/isac/ProgLang/rewrite.sml
author Walther Neuper <neuper@ist.tugraz.at>
Tue, 28 Sep 2010 09:06:56 +0200
branchisac-update-Isa09-2
changeset 38031 460c24a6a6ba
parent 38025 67a110289e4e
child 38036 02a9b2540eb7
permissions -rw-r--r--
tuned error and writeln

# raise error --> error
# writeln in atomtyp, atomty, atomt and xmlsrc
     1 (* isac's rewriter
     2    (c) Walther Neuper 2000
     3 
     4 use"ProgLang/rewrite.sml"; 
     5 use"rewrite.sml";
     6 *)
     7 
     8 
     9 exception NO_REWRITE;
    10 exception STOP_REW_SUB; (*WN050820 quick and dirty*)
    11 
    12 (*17.6.00: rewrite by going down the term with rew_sub*)
    13 (* val (thy, i, bdv, tless, rls, put_asm, thm, ct) =
    14        (thy, 1, []:(Term.term * Term.term) list, rew_ord, erls, bool,thm,term);
    15    *)
    16 fun rewrite__ thy i bdv tless rls put_asm thm ct =
    17   (let
    18     val (t',asms,lrd,rew) = 
    19 	rew_sub thy i bdv tless rls put_asm [(*root of the term*)]
    20 		(((inst_bdv bdv) o norm o #prop o rep_thm) thm) ct;
    21   in if rew then SOME (t', distinct asms)
    22      else NONE end)
    23 (* one rewrite (possibly conditional, ordered) EXOR exn EXOR go into subterms *)
    24 and rew_sub thy i bdv tless rls put_asm lrd r t = 
    25   ((*tracing ("@@@ rew_sub begin: t = "^(term2str t));*)
    26     let                  (* copy from Pure/thm.ML: fun rewritec *)
    27      val (lhs, rhs) = (HOLogic.dest_eq o HOLogic.dest_Trueprop
    28                        o Logic.strip_imp_concl) r;
    29      val r' = Envir.subst_term (Pattern.match thy (lhs, t) 
    30 					      (Vartab.empty, Vartab.empty)) r;
    31      val p' = map HOLogic.dest_Trueprop ((fst o Logic.strip_prems) 
    32                                              (Logic.count_prems r', [], r'));
    33      val t' = (snd o HOLogic.dest_eq o HOLogic.dest_Trueprop 
    34                o Logic.strip_imp_concl) r';
    35      (*val _= tracing("@@@ rew_sub match: t'= "^(term2str t'));*)
    36      val _= if ! trace_rewrite andalso i < ! depth andalso p' <> []
    37 	    then tracing((idt"#"(i+1))^" eval asms: "^(term2str r')) else();
    38      val (t'',p'') =                                   (*conditional rewriting*)
    39 	 let val (simpl_p', nofalse) = eval__true thy (i+1) p' bdv rls 	     
    40 	 in if nofalse
    41 	    then (if ! trace_rewrite andalso i < ! depth andalso p' <> []
    42 		  then tracing((idt"#"(i+1))^" asms accepted: "^(terms2str p')^
    43 			       "   stored: "^(terms2str simpl_p'))
    44 		  else(); (t',simpl_p'))             (* uncond.rew. from above*)
    45 	    else 
    46 		(if ! trace_rewrite andalso i < ! depth 
    47 		 then tracing((idt"#"(i+1))^" asms false: "^(terms2str p')) 
    48 		 else(); raise STOP_REW_SUB (*dont go into subterms of cond*))
    49 	 end
    50    in if perm lhs rhs andalso not (tless bdv (t',t))       (*ordered rewriting*)
    51 	then (if ! trace_rewrite andalso i < ! depth 
    52 	      then tracing((idt"#"i)^" not: \""^
    53 	      (term2str t)^"\" > \""^
    54 	      (term2str t')^"\"") else (); 
    55 	      raise NO_REWRITE )
    56 	else ((*tracing("##@ rew_sub: (t''= "^(term2str t'')^
    57 		      ", p'' ="^(terms2str p'')^", true)");*)
    58 	      (t'',p'',[],true))
    59    end
    60    ) handle _ (*NO_REWRITE WN050820 causes diff.behav. in tests + MATCH!*) => 
    61      ((*tracing ("@@@ rew_sub gosub: t = "^(term2str t));*)
    62       case t of
    63 	Const(s,T) => (Const(s,T),[],lrd,false)
    64       | Free(s,T) => (Free(s,T),[],lrd,false)
    65       | Var(n,T) => (Var(n,T),[],lrd,false)
    66       | Bound i => (Bound i,[],lrd,false)
    67       | Abs(s,T,body) => 
    68 	  let val (t', asms, lrd, rew) = 
    69 		  rew_sub thy i bdv tless rls put_asm (lrd@[D]) r body
    70 	  in (Abs(s,T,t'), asms, [], rew) end
    71       | t1 $ t2 => 
    72 	  let val (t2', asm2, lrd, rew2) = 
    73 		  rew_sub thy i bdv tless rls put_asm (lrd@[R]) r t2
    74 	  in if rew2 then (t1 $ t2', asm2, lrd, true)
    75 	     else let val (t1', asm1, lrd, rew1) = 
    76 	       rew_sub thy i bdv tless rls put_asm (lrd@[L]) r t1
    77 		  in if rew1 then (t1' $ t2, asm1, lrd, true)
    78 		     else (t1 $ t2,[], lrd, false) end
    79 	  end)
    80 (* simplify asumptions until one evaluates to false, store intermined's (x~=0)*)
    81 and eval__true thy i asms bdv rls =
    82   if asms = [HOLogic.true_const] orelse asms = [] then ([], true) 
    83   else if asms = [HOLogic.false_const] then ([], false)
    84   else let                            
    85       fun chk indets [] = (indets, true)(*return asms<>True until false*)
    86 	| chk indets (a::asms) =
    87 	  (case rewrite__set_ thy (i+1) false bdv rls a of
    88 	      NONE => (chk (indets @ [a]) asms)
    89 	    | SOME (t, a') =>
    90 	      if t = HOLogic.true_const 
    91 	      then (chk (indets @ a') asms)
    92 	      else if t = HOLogic.false_const then ([], false)
    93 	      (*asm false .. thm not applied ^^^; continue until False vvv*)
    94 	      else chk (indets @ [t] @ a') asms);
    95   in chk [] asms end
    96 (* rewrite with a rule set, which must not be the empty Erls *)
    97 and rewrite__set_ _ _ __ Erls t = 
    98     error("rewrite__set_ called with 'Erls' for '"^term2str t^"'")
    99   (* rewrite with a 'reverse rule set' based on ML code *)
   100   | rewrite__set_ thy i _ _ (rrls as Rrls _) t =
   101     let val _= if ! trace_rewrite andalso i < ! depth 
   102 	       then tracing ((idt"#"i)^" rls: "^(id_rls rrls)^" on: "^
   103 			     (term2str t)) else ()
   104 	val (t', asm, rew) = app_rev thy (i+1) rrls t
   105     in if rew then SOME (t', distinct asm)
   106        else NONE end
   107   (* rewrite with a rule set containing Thms or Calculations *)
   108   | rewrite__set_ thy i put_asm bdv rls ct =
   109 (* val (thy, i, put_asm, bdv, rls, ct) = (thy, 1, bool, [], rls, term);
   110    *)
   111   let
   112     datatype switch = Appl | Noap;
   113     fun rew_once ruls asm ct Noap [] = (ct,asm)
   114       | rew_once ruls asm ct Appl [] = 
   115 	(case rls of Rls _ => rew_once ruls asm ct Noap ruls
   116 		   | Seq _ => (ct,asm))
   117       | rew_once ruls asm ct apno (rul::thms) =
   118 (* val (ruls, asm, ct, apno, (rul::thms)) = (ruls, [], ct, Noap, ruls);
   119    val Thm (thmid, thm) = rul;
   120    *)
   121       case rul of
   122 	Thm (thmid, thm) =>
   123 	  (if !trace_rewrite andalso i < ! depth 
   124 	   then tracing((idt"#"(i+1))^" try thm: "^thmid) else ();
   125 	   case rewrite__ thy (i+1) bdv ((snd o #rew_ord o rep_rls) rls)
   126 	     ((#erls o rep_rls) rls) put_asm thm ct of
   127 	     NONE => rew_once ruls asm ct apno thms
   128 	   | SOME (ct',asm') => (if ! trace_rewrite andalso i < ! depth 
   129 	     then tracing((idt"="(i+1))^" rewrites to: "^
   130 			  (term2str ct')) else ();
   131 	       rew_once ruls (union (op =) asm asm') ct' Appl (rul::thms)))
   132       | Calc (cc as (op_,_)) => 
   133 	  (let val _= if !trace_rewrite andalso i < ! depth then
   134 		      tracing((idt"#"(i+1))^" try calc: "^op_^"'") else ();
   135 	     val ct = uminus_to_string ct
   136 	   in case get_calculation_ thy cc ct of
   137 	     NONE => rew_once ruls asm ct apno thms
   138 	   | SOME (thmid, thm') => 
   139 	       let 
   140 		 val pairopt = 
   141 		   rewrite__ thy (i+1) bdv ((snd o #rew_ord o rep_rls) rls)
   142 		   ((#erls o rep_rls) rls) put_asm thm' ct;
   143 		 val _ = if pairopt <> NONE then () 
   144 			 else error("rewrite_set_, rewrite_ \""^
   145 			 (string_of_thmI thm')^"\" "^(term2str ct)^" = NONE")
   146 		 val _ = if ! trace_rewrite andalso i < ! depth 
   147 			   then tracing((idt"="(i+1))^" calc. to: "^
   148 					(term2str ((fst o the) pairopt)))
   149 			 else()
   150 	       in rew_once ruls asm ((fst o the) pairopt) Appl (rul::thms) end
   151 	   end)
   152       | Cal1 (cc as (op_,_)) => 
   153 	  (let val _= if !trace_rewrite andalso i < ! depth then
   154 		      tracing((idt"#"(i+1))^" try cal1: "^op_^"'") else ();
   155 	     val ct = uminus_to_string ct
   156 	   in case get_calculation1_ thy cc ct of
   157 	     NONE => (ct, asm)
   158 	   | SOME (thmid, thm') =>
   159 	       let 
   160 		 val pairopt = 
   161 		   rewrite__ thy (i+1) bdv ((snd o #rew_ord o rep_rls) rls)
   162 		   ((#erls o rep_rls) rls) put_asm thm' ct;
   163 		 val _ = if pairopt <> NONE then () 
   164 			 else error("rewrite_set_, rewrite_ \""^
   165 			 (string_of_thmI thm')^"\" "^(term2str ct)^" = NONE")
   166 		 val _ = if ! trace_rewrite andalso i < ! depth 
   167 			   then tracing((idt"="(i+1))^" cal1. to: "^
   168 					(term2str ((fst o the) pairopt)))
   169 			 else()
   170 	       in the pairopt end
   171 	   end)
   172       | Rls_ rls' => 
   173 	(case rewrite__set_ thy (i+1) put_asm bdv rls' ct of
   174 	     SOME (t',asm') => rew_once ruls (union (op =) asm asm') t' Appl thms
   175 	   | NONE => rew_once ruls asm ct apno thms);
   176 
   177     val ruls = (#rules o rep_rls) rls;
   178     val _= if ! trace_rewrite andalso i < ! depth 
   179 	   then tracing ((idt"#"i)^" rls: "^(id_rls rls)^" on: "^
   180 			 (term2str ct)) else ()
   181     val (ct',asm') = rew_once ruls [] ct Noap ruls;
   182   in if ct = ct' then NONE else SOME (ct', distinct asm') end
   183 
   184 and app_rev thy i rrls t = 
   185     let (*.check a (precond, pattern) of a rev-set; stops with 1st true.*)
   186 	fun chk_prepat thy erls [] t = true
   187 	  | chk_prepat thy erls prepat t =
   188 	    let fun chk (pres, pat) =
   189 		    (let val subst: Type.tyenv * Envir.tenv = 
   190 			     Pattern.match thy (pat, t)
   191 					    (Vartab.empty, Vartab.empty)
   192 		     in snd (eval__true thy (i+1) 
   193 					(map (Envir.subst_term subst) pres)
   194 					[] erls)
   195 		     end)
   196 		    handle _ => false
   197 		fun scan_ f [] = false (*scan_ NEVER called by []*)
   198 		  | scan_ f (pp::pps) = if f pp then true
   199 					else scan_ f pps;
   200 	    in scan_ chk prepat end;
   201 
   202 	(*.apply the normal_form of a rev-set.*)
   203 	fun app_rev' thy (Rrls{erls,prepat,scr=Rfuns{normal_form,...},...}) t =
   204 	    if chk_prepat thy erls prepat t
   205 	    then ((*tracing("### app_rev': t = "^(term2str t));*)
   206                   normal_form t)
   207 	    else NONE;
   208 
   209 	val opt = app_rev' thy rrls t
   210     in case opt of
   211 	   SOME (t', asm) => (t', asm, true)
   212 	 | NONE => app_sub thy i rrls t
   213     end
   214 and app_sub thy i rrls t =
   215      ((*tracing("### app_sub: subterm = "^(term2str t));*)
   216       case t of
   217 	Const (s, T) => (Const(s, T), [], false)
   218       | Free (s, T) => (Free(s, T), [], false)
   219       | Var (n, T) => (Var(n, T), [], false)
   220       | Bound i => (Bound i, [], false)
   221       | Abs (s, T, body) => 
   222 	  let val (t', asm, rew) = app_rev thy i rrls body
   223 	  in (Abs(s, T, t'), asm, rew) end
   224       | t1 $ t2 => 
   225 	let val (t2', asm2, rew2) = app_rev thy i rrls t2
   226 	in if rew2 then (t1 $ t2', asm2, true)
   227 	   else let val (t1', asm1, rew1) = app_rev thy i rrls t1
   228 		in if rew1 then (t1' $ t2, asm1, true)
   229 		   else (t1 $ t2, [], false) end
   230 	end);
   231 
   232 
   233 
   234 (*.rewriting without argument [] for rew_ord.*)
   235 (*WN.11.6.03: shouldnt asm<>[] lead to false ????*)
   236 fun eval_true thy terms rls = (snd o (eval__true thy 1 terms [])) rls;
   237 
   238 
   239 (*.rewriting without internal argument [] for rew_ord.*)
   240 (* val (thy, rew_ord, erls, bool, thm, term) =
   241        (thy, (assoc_rew_ord ro), rls', false, (assoc_thm' thy thm'), f);
   242    val (thy, rew_ord, erls, bool, thm, term) =
   243        (thy, rew_ord, erls, false, thm, t'');
   244    *)
   245 fun rewrite_ thy rew_ord erls bool thm term = 
   246     rewrite__ thy 1 [] rew_ord erls bool thm term;
   247 fun rewrite_set_ thy bool rls term =
   248 (* val (thy, bool, rls, term) = (thy, false, srls, t);
   249    *)
   250     rewrite__set_ thy 1 bool [] rls term;
   251 
   252 
   253 fun subs'2subst thy (s:subs') = 
   254     (((map (apfst (term_of o the o (parse thy)))) 
   255      o (map (apsnd (term_of o the o (parse thy))))) s):subst;
   256 
   257 (*.variants of rewrite.*)
   258 (*FIXME 12.8.02: put_asm = true <==> rewrite_inst,
   259   thus the argument put_asm  IS NOT NECESSARY -- FIXME*)
   260 (* val (rew_ord,rls,put_asm,thm,ct)=
   261        (e_rew_ord,poly_erls,false,num_str d1_isolate_add2,t);
   262    *)
   263 fun rewrite_inst_ (thy:theory) rew_ord (rls:rls) (put_asm:bool) 
   264 		  (subst:(term * term) list) (thm:thm) (ct:term) =
   265     rewrite__ thy 1 subst rew_ord rls put_asm thm ct;
   266 
   267 fun rewrite_set_inst_ (thy:theory) 
   268   (put_asm:bool) (subst:(term * term) list) (rls:rls) (ct:term) =
   269   (*let 
   270     val subst = subs'2subst thy subs';
   271     val subrls = instantiate_rls subs' rls
   272   in*) rewrite__set_ thy 1 put_asm subst (*sub*)rls ct
   273   (*end*);
   274 
   275 (* given a list of equalities (lhs = rhs) and a term, 
   276    replace all occurrences of lhs in the term with rhs;
   277    thus the order or equalities matters: put variables in lhs first. *)
   278 fun rewrite_terms_ thy ord erls equs t =
   279     let (*val _=tracing("### rewrite_terms_ equs= '"^terms2str equs^"' ..."^
   280 		      term_detail2str (hd equs)^
   281 		      "### rewrite_terms_ t= '"^term2str t^"' ..."^
   282 		      term_detail2str t);*)
   283 	fun rew_ (t', asm') [] _ = (t', asm')
   284 	  (* 1st val (t', asm', rules as r::rs, t) = (e_term, [], equs, t);
   285 	     2nd val (t', asm', rules as r::rs, t) = (t'', [], rules, t'');
   286 	     rew_ (t', asm') (r::rs) t;
   287 	     *)
   288 	  | rew_ (t', asm') (rules as r::rs) t =
   289 	    let val _ = tracing("rew_ "^term2str t);
   290 		val (t'', asm'', lrd, rew) = 
   291 		    rew_sub thy 1 [] ord erls false [] (Trueprop $ r) t
   292 	    in if rew 
   293 	       then (tracing ("true  rew_ " ^ term2str t'');
   294 		   rew_ (t'', asm' @ asm'') rules t'')
   295 	       else (tracing ("false rew_ " ^ term2str t'');
   296 		   rew_ (t', asm') rs t')
   297 	    end
   298 	val (t'', asm'') = rew_ (e_term, []) equs t
   299     in if t'' = e_term 
   300        then NONE else SOME (t'', asm'')
   301     end;
   302 
   303 
   304 (*. search ct for adjacent numerals and calculate them by operator isa_fn .*)
   305 fun calculate_ thy isa_fn ct =
   306   let val ct = uminus_to_string ct
   307     in case get_calculation_ thy isa_fn ct of
   308 	   NONE => NONE
   309 	 | SOME (thmID, thm) => 
   310 	   (let val SOME (rew,_) = rewrite_ thy dummy_ord e_rls false thm ct
   311     in SOME (rew,(thmID, thm)) end)
   312 	   handle _ => error ("calculate_: "^thmID^" does not rewrite")
   313   end;
   314 (*
   315 > val thy = InsSort.thy;
   316 > val op_ = "le";      (* < *)
   317 > val ct = (the o (parse thy)) 
   318    "foldr ins [#2] (if #1 < #3 then #1 # ins [] #3 else [#3, #1])";
   319 > calculate_ thy op_ ct;
   320   SOME
   321     ("foldr ins [#2] (if True then #1 # ins [] #3 else [#3, #1])",
   322      "(#1 < #3) = True") : (cterm * thm) option  *)
   323 
   324 
   325 (* for test-printouts:
   326 val _ = tracing("in rew_sub  : "^( Syntax.string_of_term (thy2ctxt thy) t))
   327 val _ = tracing("in eval_true: prems= "^(commas (map (Syntax.string_of_term (thy2ctxt thy)) prems')))
   328 *)
   329 
   330 
   331 
   332 
   333 
   334 
   335 fun get_rls_scr rs' = ((#scr o rep_rls o #2 o the o assoc') (!ruleset',rs'))
   336   handle _ => error ("get_rls_scr: no script for "^rs');
   337 
   338 
   339 (*make_thm added to Pure/thm.ML*)
   340 fun mk_thm thy str = 
   341     let val t = (term_of o the o (parse thy)) str
   342 	val t' = case t of
   343 		     Const ("==>",_) $ _ $ _ => t
   344 		   | _ => Trueprop $ t
   345     in make_thm (cterm_of thy t') end;
   346 (*
   347   val str = "?r ^^^ 2 = ?r * ?r";
   348   val thm = realpow_twoI;
   349 
   350   val t1 = (#prop o rep_thm) (num_str thm);
   351   val t2 = Trueprop $ ((term_of o the o (parse thy)) str);
   352   t1 = t2;
   353 val it = true : bool      ... !!!
   354   val th1 = (num_str thm);
   355   val th2 = ((*num_str*) (mk_thm thy str)) handle e => print_exn e;
   356   th1 = th2;
   357 ML> val it = false : bool ... HIDDEN DIFFERENCES IRRELEVANT FOR ISAC ?!
   358 
   359 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   360   val str = "k ~= 0 ==> m * k / (n * k) = m / n";
   361   val thm = real_mult_div_cancel2;
   362 
   363   val t1 = (#prop o rep_thm) (num_str thm);
   364   val t2 = ((term_of o the o (parse thy)) str);
   365   t1 = t2;
   366 val it = false : bool     ... Var .. Free
   367   val th1 = (num_str thm);
   368   val th2 = ((*num_str*) (mk_thm thy str)) handle e => print_exn e;
   369   th1 = th2;
   370 ML> val it = false : bool ... PLUS HIDDEN DIFFERENCES IRRELEVANT FOR ISAC ?!
   371 *)
   372 
   373 
   374 (*prints subgoal etc. 
   375 ((goal thy);(topthm()) o ) str;                      *)
   376 (*assume rejects scheme variables 
   377   assume ((cterm_of thy) (Trueprop $ 
   378 		(term_of o the o (parse thy)) str)); *)
   379 
   380 
   381 (* outcommented 18.11.xx, xx < 02 -------
   382 fun rul2rul' (Thm (thmid, thm)) = Thm'(thmid, string_of_thmI thm)
   383   | rul2rul' (Calc op_)         = Calc' op_;
   384 fun rul'2rul thy (Thm'(thmid, ct')) = 
   385        Thm (thmid, mk_thm thy ct')
   386   | rul'2rul thy' (Calc' op_)        = Calc op_;
   387 
   388 
   389 fun rls2rls' (Rls{preconds=preconds,rew_ord=rew_ord,rules=rules}:rls) =
   390   Rls'{preconds'= map string_of_cterm preconds,
   391        rew_ord' = fst rew_ord,
   392        rules'   = map rul2rul' rules}:rlsdat';
   393 
   394 fun rls'2rls thy' (Rls'{preconds'=preconds,rew_ord'=rew_ord,
   395 		   rules'=rules}:rlsdat') =
   396   let val thy = the (assoc' (theory',thy'))
   397   in Rls{preconds = map (the o (parse thy)) preconds,
   398 	 rew_ord  = (rew_ord, the (assoc'(rew_ord',rew_ord))),
   399 	 rules    = map (rul'2rul thy) rules}:rls end;
   400 ------- *)
   401 
   402 (*.get the theorem associated with the xstring-identifier;
   403    if the identifier starts with "sym_" then swap lhs = rhs around =
   404    (ATTENTION: "RS sym" attaches a [.] -- remove it with string_of_thmI);
   405    identifiers starting with "#" come from Calc and
   406    get a hand-made theorem (containing numerals only).*)
   407 fun assoc_thm' (thy:theory) ((thmid, ct'):thm') =
   408     (case explode thmid of
   409 	"s"::"y"::"m"::"_"::id => 
   410 	if hd id = "#" 
   411 	then mk_thm thy ct'
   412 	else ((num_str o (PureThy.get_thm thy)) (implode id)) RS sym
   413       | id => 
   414 	if hd id = "#" 
   415 	then mk_thm thy ct'
   416 	else (num_str o (PureThy.get_thm thy)) thmid
   417 	     ) handle _ => 
   418 		      error ("assoc_thm': '"^thmid^"' not in '"^
   419 				   (theory2domID thy)^"' (and parents)");
   420 (*> assoc_thm' Isac.thy ("sym_#mult_2_3","6 = 2 * 3");
   421 val it = "6 = 2 * 3" : thm          
   422 
   423 > assoc_thm' Isac.thy ("add_0_left","");
   424 val it = "0 + ?z = ?z" : thm
   425 
   426 > assoc_thm' Isac.thy ("sym_real_add_zero_left","");
   427 val it = "?t = 0 + ?t"  [.] : thm
   428 
   429 > assoc_thm' HOL.thy ("sym_real_add_zero_left","");
   430 *** Unknown theorem(s) "add_0_left"
   431 *** assoc_thm': 'sym_real_add_zero_left' not in 'HOL.thy' (and parents)
   432  uncaught exception ERROR*)
   433 
   434 
   435 fun parse' (thy:theory') (ct:cterm') =
   436     case parse ((the o assoc')(!theory',thy)) ct of
   437 	NONE => NONE
   438       | SOME ct => SOME ((term2str (term_of ct)):cterm');
   439 
   440 
   441 (*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
   442   thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
   443 fun rewrite (thy':theory') (rew_ord:rew_ord') (rls:rls') 
   444     (put_asm:bool) (thm:thm') (ct:cterm') =
   445 (* val (rew_ord, rls, thm, ct) = (rew_ord', id_rls rls', thm', f);
   446    *)
   447     let val thy = (the o assoc')(!theory',thy');
   448     in
   449     case rewrite_ thy
   450 	((the o assoc')(!rew_ord',rew_ord))((#2 o the o assoc')(!ruleset',rls))
   451 	put_asm ((assoc_thm' thy) thm)
   452 	((term_of o the o (parse thy)) ct) of
   453 	NONE => NONE
   454       | SOME (t, ts) => SOME (term2str t, terms2str ts)
   455     end;
   456 
   457 (*
   458 val thy     = "RatArith.thy";
   459 val rew_ord = "dummy_ord"; 
   460 > val rls     = "eval_rls";
   461 val put_asm = true; 
   462 val thm     = ("square_equation_left","");
   463 val ct      = "sqrt(#9+#4*x)=sqrt x + sqrt(#-3+x)";
   464 
   465 val Zthy     = ((the o assoc')(!theory',thy));
   466 val Zrew_ord = ((the o assoc')(!rew_ord',rew_ord)); 
   467 val Zrls     = ((the o assoc')(!ruleset',rls));
   468 val Zput_asm = put_asm; 
   469 val Zthm     = ((the o (assoc'_thm' thy)) thm);
   470 val Zct      = ((the o (parse ((the o assoc')(!theory',thy)))) ct);
   471 
   472 rewrite_ Zthy Zrew_ord Zrls Zput_asm Zthm Zct;
   473 
   474  use"Isa99/interface_ME_ISA.sml";
   475 *)
   476 
   477 (*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
   478   thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
   479 fun rewrite_set (thy':theory') (put_asm:bool)
   480     (rls:rls') (ct:cterm') =
   481     let val thy = (the o assoc')(!theory',thy');
   482     in
   483     case rewrite_set_ thy put_asm ((#2 o the o assoc')(!ruleset',rls))
   484     ((term_of o the o (parse thy)) ct) of
   485 	NONE => NONE
   486       | SOME (t, ts) => SOME (term2str t, terms2str ts)
   487     end;
   488 
   489 (*evaluate list-expressions
   490   should work on term, and stand in Isa99/rewrite-parse.sml, 
   491   but there list_rls <- eval_binop is not yet defined*)
   492 (*fun eval_listexpr' ct = 
   493     let val rew = rewrite_set "ListC.thy" false "list_rls" ct;
   494     in case rew of 
   495 	   SOME (res,_) => res
   496 	 | NONE => ct end;-----------------30.9.02---*)
   497 fun eval_listexpr_ thy srls t =
   498 (* val (thy,            srls, t) = 
   499        ((assoc_thy th), sr,  (subst_atomic (upd_env_opt E (a,v)) t));
   500    *) 
   501     let val rew = rewrite_set_ thy false srls t;
   502     in case rew of 
   503 	   SOME (res,_) => res
   504 	 | NONE => t end;
   505 
   506 
   507 fun get_calculation' (thy:theory') op_ (ct:cterm') =
   508    case get_calculation_ ((the o assoc')(!theory',thy)) op_
   509     ((uminus_to_string o term_of o the o 
   510       (parse ((the o assoc')(!theory',thy)))) ct) of
   511 	NONE => NONE
   512       | SOME (thmid, thm) => 
   513 	    SOME ((thmid, string_of_thmI thm):thm');
   514 
   515 fun calculate (thy':theory') op_ (ct:cterm') =
   516     let val thy = (the o assoc')(!theory',thy');
   517     in
   518 	case calculate_ thy op_
   519 			((term_of o the o (parse thy)) ct) of
   520 	    NONE => NONE
   521 	  | SOME (ct,(thmID,thm)) => 
   522 	    SOME (term2str ct, 
   523 		  (thmID, string_of_thmI thm):thm')
   524     end;
   525 (*
   526 fun instantiate'' thy' subs ((thmid,ct'):thm') = 
   527   let val thmid_ = implode ("#"::(explode thmid))  (*see type thm'*)
   528   in (thmid_, (string_of_thmI o (read_instantiate subs)) 
   529       ((the o (assoc_thm' thy')) (thmid_,ct'))):thm' end;
   530 
   531 fun instantiate_rls' thy' subs (rls:rls') = 
   532     rls2rls' (instantiate_rls subs ((the o (assoc_rls thy')) rls)):rlsdat';
   533 
   534 ... problem with these functions: 
   535 > val thm = mk_thm thy "(bdv + a = b) = (bdv = b - a)";
   536 val thm = "(bdv + a = b) = (bdv = b - a)" : thm
   537 > show_types:=true; thm;    
   538 val it = "((bdv::'a) + (a::'a) = (b::'a)) = (bdv = b - a)" : thm
   539 ... and this doesn't match because of too general typing (?!)
   540     and read_insitantiate doesn't instantiate the types (?!)
   541 === solutions:
   542 (1) hard-coded type-instantiation ("'a", "RatArith.rat")
   543 (2) instantiate', instantiate ... no help by isabelle-users@ !!!
   544 === conclusion:
   545     rewrite_inst, rewrite_set_inst circumvent the problem,
   546     according functions out-commented with 'instantiate''
   547 *)
   548 
   549 (* instantiate''
   550 fun instantiate'' thy' subs ((thmid,ct'):thm') = 
   551   let 
   552     val thmid_ = implode ("#"::(explode thmid));  (*see type thm'*)
   553     val thy = (the o assoc')(!theory',thy');
   554     val typs = map (#T o rep_cterm o the o (parse thy)) 
   555       ((snd o split_list) subs);
   556     val ctyps = map 
   557       ((ctyp_of (sign_of thy)) o #T o rep_cterm o the o (parse thy)) 
   558       ((snd o split_list) subs);
   559 
   560 > val thy' = "RatArith.thy";
   561 > val subs = [("bdv","x::rat"),("zzz","z::nat")];
   562 > (the o (parse ((the o assoc')(!theory',thy')))) "x::rat";
   563 > (#T o rep_cterm o the o (parse ((the o assoc')(!theory',thy'))));
   564 
   565 > val ctyp = ((ctyp_of (sign_of thy)) o #T o rep_cterm o the o 
   566 	      (parse ((the o assoc')(!theory',thy')))) "x::rat";
   567 > val bdv = (the o (parse thy)) "bdv";
   568 > val x   = (the o (parse thy)) "x";
   569 > (instantiate ([(("'a",0),ctyp)],[(bdv,x)]) isolate_bdv_add)
   570       handle e => print_exn e;
   571 uncaught exception THM
   572   raised at: thm.ML:1085.18-1085.69
   573              thm.ML:1092.34
   574              goals.ML:536.61
   575 
   576 > val bdv = (the o (parse thy)) "bdv::nat";
   577 > val x   = (the o (parse thy)) "x::nat";
   578 > (instantiate ([(("'a",0),ctyp)],[(bdv,x)]) isolate_bdv_add)
   579       handle e => print_exn e;
   580 uncaught exception THM
   581   raised at: thm.ML:1085.18-1085.69
   582              thm.ML:1092.34
   583              goals.ML:536.61
   584 
   585 > (instantiate' [SOME ctyp] [] isolate_bdv_add)
   586       handle e => print_exn e;      
   587 uncaught exception TYPE
   588   raised at: drule.ML:613.13-615.44
   589              goals.ML:536.61
   590 
   591 > val repct = (rep_cterm o the o (parse ((the o assoc')(!theory',thy')))) "x::rat";
   592 *)
   593 
   594 (*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
   595   thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
   596 fun rewrite_inst (thy':theory') (rew_ord:rew_ord') (rls:rls') 
   597   (put_asm:bool) subs (thm:thm') (ct:cterm') =
   598   let
   599     val thy = (the o assoc')(!theory',thy');
   600     val thm = assoc_thm' thy thm; (*28.10.02*)
   601     (*val subthm = read_instantiate subs ((assoc_thm' thy) thm)*)
   602   in
   603     case rewrite_ thy
   604       ((the o assoc')(!rew_ord',rew_ord)) ((#2 o the o assoc')(!ruleset',rls))
   605       put_asm (*sub*)thm ((term_of o the o (parse thy)) ct) of
   606       NONE => NONE
   607     | SOME (ctm, ctms) => 
   608       SOME ((term2str ctm):cterm', (map term2str ctms):cterm' list)
   609   end;
   610 
   611 (*FIXME 12.8.02: put_asm = true <==> rewrite_inst, rewrite_set_inst
   612   thus the argument put_asm  IS NOT NECESSARY -- FIXME        ~~~~~*)
   613 fun rewrite_set_inst (thy':theory') (put_asm:bool)
   614   subs' (rls:rls') (ct:cterm') =
   615   let
   616     val thy = (the o assoc')(!theory',thy');
   617     val rls = assoc_rls rls
   618     val subst = subs'2subst thy subs'
   619     (*val subrls = instantiate_rls subs ((the o assoc')(!ruleset',rls))*)
   620   in case rewrite_set_inst_ thy put_asm subst (*sub*)rls
   621 			    ((term_of o the o (parse thy)) ct) of
   622 	 NONE => NONE
   623        | SOME (t, ts) => SOME (term2str t, terms2str ts)
   624   end;
   625 
   626 
   627 (*vor check_elementwise: SqRoot_eval_rls .. wie *_simplify ?! TODO *)
   628 fun eval_true' (thy':theory') (rls':rls') (Const ("True",_)) = true
   629 
   630   | eval_true' (thy':theory') (rls':rls') (t:term) =
   631 (* val thy'="Isac.thy"; val rls'="eval_rls"; val t=hd pres';
   632    *)
   633     let val ct' = term2str t;
   634     in case rewrite_set thy' false rls' ct' of
   635 	   SOME ("True",_) => true
   636 	 | _ => false 
   637     end;
   638 fun eval_true_ _ _ (Const ("True",_)) = true
   639   | eval_true_ (thy':theory') rls t =
   640     case rewrite_set_ (assoc_thy thy') false rls t of
   641 	   SOME (Const ("True",_),_) => true
   642 	 | _ => false;
   643 
   644 (*
   645 val test_rls = 
   646   Rls{preconds = [], rew_ord = ("sqrt_right",sqrt_right), 
   647       rules = [Calc ("matches",eval_matches "")
   648 	       ],
   649       scr = Script ((term_of o the o (parse thy)) 
   650       "empty_script")
   651       }:rls;      
   652 
   653 
   654 
   655   rewrite_set_ Isac.thy eval_rls false test_rls 
   656         ((the o (parse thy)) "matches (?a = ?b) (x = #0)");
   657   val xxx = (term_of o the o (parse thy)) 
   658 	       "matches (?a = ?b) (x = #0)";
   659   eval_matches """" xxx thy;
   660 SOME ("matches (?a = ?b) (x + #1 + #-1 * #2 = #0) = True",
   661      Const ("Trueprop","bool => prop") $ (Const # $ (# $ #) $ Const (#,#)))
   662 
   663 
   664 
   665   rewrite_set_ Isac.thy eval_rls false eval_rls 
   666         ((the o (parse thy)) "contains_root (sqrt #0)");
   667 val it = SOME ("True",[]) : (cterm * cterm list) option
   668     
   669 *)
   670 
   671 
   672 (*----------WN:16.5.03 stuff below considered illdesigned, thus coded from scratch in appl.sml fun check_elementwise
   673 datatype det = TRUE  | FALSE | INDET;(*FIXXME.WN:16.5.03
   674 				     introduced with quick-and-dirty code*)
   675 fun determine dts =
   676     let val false_indet = 
   677 	    filter_out ((curry op= TRUE) o (#1:det * term -> det)) dts
   678         val ts = map (#2: det * term -> term) dts
   679     in if nil = false_indet then (TRUE, ts)
   680        else if nil = filter ((curry op= FALSE) o (#1:det * term -> det))
   681 			    false_indet
   682        then (INDET, ts)
   683        else (FALSE, ts) end;
   684 (* val dts = [(INDET,e_term), (FALSE,HOLogic.false_const), 
   685 	      (INDET,e_term), (TRUE,HOLogic.true_const)];
   686   determine dts;
   687 val it =
   688   (FALSE,
   689    [Const ("empty","'a"),Const ("False","bool"),Const ("empty","'a"),
   690     Const ("True","bool")]) : det * term list*)
   691 
   692 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*)
   693 if cs = [HOLogic.true_const] orelse cs = [] then (TRUE, [])
   694     else if cs = [HOLogic.false_const] then (FALSE, cs)
   695     else
   696 	let fun eval t = 
   697 		let val taopt = rewrite__set_ thy 1 false [] rls t
   698 		in case taopt of
   699 		       SOME (t,_) =>
   700 		       if t = HOLogic.true_const then (TRUE, t)
   701 		       else if t = HOLogic.false_const then (FALSE, t)
   702 		       else (INDET, t)
   703 		     | NONE => (INDET, t) end
   704 	in (determine o (map eval)) cs end;
   705 WN.16.5.0-------------------------------------------------------------*)