src/Tools/isac/CalcElements/termC.sml
author Walther Neuper <walther.neuper@jku.at>
Wed, 15 Jan 2020 12:01:13 +0100
changeset 59768 82d0bd495525
parent 59767 c4acd312bd53
child 59770 82d51092c996
permissions -rw-r--r--
tuned
     1 (* Title: extends Isabelle/src/Pure/term.ML
     2    Author: Walther Neuper 1999, Mathias Lehnfeld
     3    (c) due to copyright terms
     4 *)
     5 infix contains_one_of
     6 
     7 (* TERM_C extends Isabelle's naming conventions: "C" indicates Isac add-ons to an Isabelle module *)
     8 signature TERM_C =
     9   sig
    10     datatype lrd = D | L | R
    11     type path
    12     val path2str: path -> string
    13     val at_location: path -> term -> term
    14     val go_up: path -> term -> term
    15 
    16     val contains_Var: term -> bool
    17     val dest_binop_typ: typ -> typ * typ * typ
    18     val dest_equals: term -> term * term
    19     val free2str: term -> string
    20     val ids2str: term -> string list
    21     val ins_concl: term -> term -> term
    22     val inst_abs: term -> term
    23     val inst_bdv: (term * term) list -> term -> term
    24  
    25     val term_of_num: typ -> int -> term
    26     val num_of_term: term -> int
    27     val int_of_str_opt: string -> int option
    28     val int_of_str: string -> int
    29     val isastr_of_int: int -> string
    30 
    31     val isalist2list: term -> term list
    32     val list2isalist: typ -> term list -> term
    33     val isapair2pair: term -> term * term (* rename to dest_pair, compare HOLogic.dest_string *)
    34  
    35     val is_atom: term -> bool
    36     val is_bdv: string -> bool
    37     val is_bdv_subst: term -> bool
    38     val guess_bdv_typ: term -> typ
    39     val is_equality: term -> bool
    40     val is_expliceq: term -> bool
    41     val is_f_x: term -> bool
    42     val is_list: term -> bool
    43     val is_num: term -> bool
    44     val is_num': string -> bool
    45 
    46     val mk_add: term -> term -> term
    47     val mk_free: typ -> string -> term
    48     val mk_equality: term * term -> term
    49     val mk_factroot: string -> typ -> int -> int -> term
    50     val mk_Free: string * typ -> term
    51     val mk_thmid: string -> string -> string -> string
    52     val mk_num_op_num: typ -> typ -> string * typ -> int -> int -> term
    53     val mk_num_op_var: term -> string -> typ -> typ -> int -> term
    54     val mk_var_op_num: term -> string -> typ -> typ -> int -> term
    55 
    56     val matches: theory -> term -> term -> bool
    57     val parse: theory -> string -> cterm option
    58     val parseN: theory -> string -> cterm option
    59     val parseNEW: Proof.context -> string -> term option
    60     val parseNEW': Proof.context -> string -> term
    61     val parseold: theory -> string -> cterm option
    62     val parse_patt: theory -> string -> term
    63     val perm: term -> term -> bool
    64 
    65     val str_of_free_opt: term -> string option
    66     val str_of_int: int -> string
    67     val str2term: string -> term
    68     val strip_imp_prems': term -> term option
    69     val subst_atomic_all: (term * term) list -> term -> bool * term
    70     val term_detail2str: term -> string
    71 
    72     val pairt: term -> term -> term
    73     val pairT: typ -> typ -> typ
    74     val raise_type_conflicts: term list -> unit
    75     val strip_trueprop: term -> term
    76 
    77     val num_str: thm -> thm
    78     val numbers_to_string: term -> term
    79     val uminus_to_string: term -> term
    80     val var2free: term -> term
    81     val vars: term -> term list  (* recognises numverals, should replace "fun vars_of" *)
    82     val vars_of: term -> term list
    83     val dest_list': term -> term list
    84 
    85 (* ---- for tests only: shifted from below to remove the Warning "unused" at fun.def. --------- *)
    86     val scala_of_term: term -> string
    87     val atomtyp(*<-- atom_typ TODO*): typ -> unit
    88     val atomty: term -> unit
    89     val atomw: term -> unit
    90     val atomwy: term -> unit
    91     val atomty_thy: Rule.thyID -> term -> unit
    92     val free2var: term -> term
    93     val contains_one_of: thm * (string * typ) list -> bool
    94     val contains_Const_typeless: term list -> term -> bool
    95 (*/-------------------------------------------------------- ! aktivate for Test_Isac BEGIN ---\* )
    96     val atomt: term -> unit
    97     val typ_a2real: term -> term
    98 ( *\--- ! aktivate for Test_Isac END ----------------------------------------------------------/*)
    99   end
   100 
   101 (**)
   102 structure TermC(**): TERM_C(**) =
   103 struct
   104 (**)
   105 
   106 datatype lrd = L (*t1 in "t1$t2"*)
   107              | R (*t2 in "t1$t2"*) | D; (*b in Abs(_,_,b*)
   108 type path = lrd list; 
   109 fun ldr2str L = "L"
   110   | ldr2str R = "R"
   111   | ldr2str D = "D";
   112 fun path2str k = (strs2str' o (map ldr2str)) k;
   113 (*go to a location in a term and fetch the resective sub-term*)
   114 fun at_location [] t = t
   115   | at_location (D :: p) (Abs(_, _, body)) = at_location (p : path) body
   116   | at_location (L :: p) (t1 $ _) = at_location p t1
   117   | at_location (R :: p) (_ $ t2) = at_location p t2
   118   | at_location l _ = error ("at_location: no " ^ path2str l);
   119 fun go_up l t =
   120   if length l > 1 then at_location (drop_last l) t else raise ERROR ("go_up [] " ^ Rule.term2str t)
   121 
   122 fun isastr_of_int i = if i >= 0 then string_of_int i else "-" ^ string_of_int (abs i)
   123 
   124 fun matches thy tm pa = 
   125     (Pattern.match thy (pa, tm) (Vartab.empty, Vartab.empty); true)
   126     handle Pattern.MATCH => false
   127 
   128 (** transform  typ / term to a String to be parsed by Scala after transport via libisabelle **)
   129 
   130 fun scala_of_typ (Type (s, typs)) =
   131     enclose "Type(" ")" (quote s ^ ", " ^
   132       (typs |> map scala_of_typ |> commas |> enclose "List(" ")"))
   133   | scala_of_typ (TFree (s, sort)) =
   134     enclose "TFree(" ")" (quote s ^ ", " ^ (sort |> map quote |> commas |> enclose "List(" ")"))
   135   | scala_of_typ (TVar ((s, i), sort)) =
   136     enclose "TVar(" ")" (
   137       enclose "(" ")," (quote s ^ "," ^ quote (string_of_int i)) ^ 
   138       (sort |> map quote |> commas |> enclose "List(" ")"))
   139 fun scala_of_term (Const (s, T)) =
   140     enclose "Const(" ")" (quote s ^ ", " ^ scala_of_typ T)
   141   | scala_of_term (Free (s, T)) =
   142     enclose "Free(" ")" (quote s ^ ", " ^ scala_of_typ T)
   143   | scala_of_term (Var ((s, i), T)) =
   144     enclose "TVar(" ")" (
   145       enclose "(" ")," (quote s ^ "," ^ quote (string_of_int i)) ^ 
   146       scala_of_typ T)
   147   | scala_of_term (Bound i) = enclose "Bound(" ")" (string_of_int i)
   148   | scala_of_term (Abs (s, T, t)) =
   149     enclose "Abs(" ")" (
   150       quote s ^ ", " ^
   151       scala_of_typ T ^ ", " ^
   152       scala_of_term t)
   153   | scala_of_term (t1 $ t2) =
   154     enclose "App(" ")" (scala_of_term t1 ^ ", " ^ scala_of_term t2)
   155 
   156 (* see structure's bare bones.
   157    for Isabelle standard output compare 2017 "structure ML_PP" *)
   158 fun atomtyp t =
   159   let
   160     fun ato n (Type (s, [])) = "\n*** " ^ indent n ^ "Type (" ^ s ^",[])"
   161       | ato n (Type (s, Ts)) = "\n*** " ^ indent n ^ "Type (" ^ s ^ ",[" ^ atol (n + 1) Ts
   162       | ato n (TFree (s, sort)) = "\n*** " ^ indent n ^ "TFree (" ^ s ^ "," ^ strs2str' sort
   163       | ato n (TVar ((s, i), sort)) =
   164         "\n*** " ^ indent n ^ "TVar ((" ^ s ^ "," ^ string_of_int i ^ strs2str' sort
   165     and atol n [] = "\n*** " ^ indent n ^ "]"
   166       | atol n (T :: Ts) = (ato n T ^ atol n Ts)
   167 in tracing (ato 0 t ^ "\n") end;
   168 
   169 local 
   170   fun ato (Const (a, _)) n = "\n*** " ^ indent n ^ "Const (" ^ a ^ ", _)"
   171 	  | ato (Free (a, _)) n = "\n*** " ^ indent n ^ "Free (" ^ a ^ ", _)"
   172 	  | ato (Var ((a, i), _)) n =
   173 	    "\n*** " ^ indent n ^ "Var (" ^ a ^ ", " ^ string_of_int i ^ "), _)"
   174 	  | ato (Bound i) n = "\n*** " ^ indent n ^ "Bound " ^ string_of_int i
   175 	  | ato (Abs (a, _, body)) n = "\n*** " ^ indent n ^ "Abs(" ^ a ^ ", _" ^ ato body (n+1)
   176 	  | ato (f $ t) n = (ato f n ^ ato t (n + 1))
   177 in
   178   fun atomw t = writeln ("\n*** -------------" ^ ato t 0 ^ "\n***");
   179   fun atomt t = tracing ("\n*** -------------" ^ ato t 0 ^ "\n***");
   180 end;
   181 
   182 fun term_detail2str t =
   183   let 
   184     fun ato (Const (a, T)) n = "\n*** " ^ indent n ^ "Const (" ^ a ^ ", " ^ Rule.string_of_typ T ^ ")"
   185       | ato (Free (a, T)) n = "\n*** " ^ indent n ^ "Free (" ^ a ^ ", " ^ Rule.string_of_typ T ^ ")"
   186       | ato (Var ((a, i), T)) n =
   187         "\n*** " ^ indent n ^ "Var ((" ^ a ^ ", " ^ string_of_int i ^ "), " ^ Rule.string_of_typ T ^ ")"
   188       | ato (Bound i) n = "\n*** " ^ indent n ^ "Bound " ^ string_of_int i
   189       | ato (Abs(a, T, body))  n = 
   190         "\n*** " ^ indent n ^ "Abs (" ^ a ^ ", " ^ Rule.string_of_typ T ^ ",.." ^ ato body (n + 1)
   191       | ato (f $ t) n = ato f n ^ ato t (n + 1)
   192   in "\n*** " ^ ato t 0 ^ "\n***" end;
   193 fun term_detail2str_thy thy t =
   194   let
   195     fun ato (Const (a, T)) n =
   196         "\n*** " ^ indent n ^ "Const (" ^ a ^ ", " ^ Rule.string_of_typ_thy thy T ^ ")"
   197   	  | ato (Free (a, T)) n =
   198   	     "\n*** " ^ indent n ^ "Free (" ^ a ^ ", " ^ Rule.string_of_typ_thy thy T ^ ")"
   199   	  | ato (Var ((a, i), T)) n =
   200   	    "\n*** " ^ indent n ^ "Var ((" ^ a ^ ", " ^ string_of_int i ^ "), " ^
   201   	    Rule.string_of_typ_thy thy T ^ ")"
   202   	  | ato (Bound i) n = 
   203   	    "\n*** " ^ indent n ^ "Bound " ^ string_of_int i
   204   	  | ato (Abs(a, T, body))  n = 
   205   	    "\n*** " ^ indent n ^ "Abs (" ^ a ^ ", " ^ Rule.string_of_typ_thy thy T ^ ",.." ^
   206   	    ato body (n + 1)
   207   	  | ato (f $ t) n = ato f n ^ ato t (n + 1)
   208   in "\n*** " ^ ato t 0 ^ "\n***" end;
   209 fun atomwy t = (writeln o term_detail2str) t;
   210 fun atomty t = (tracing o term_detail2str) t;
   211 fun atomty_thy thy t = (tracing o (term_detail2str_thy thy)) t;
   212 
   213 (* contains the term a VAR(("*",_),_) ? *)
   214 fun contains_Var (Abs(_,_,body)) = contains_Var body
   215   | contains_Var (f $ f') = contains_Var f orelse contains_Var f'
   216   | contains_Var (Var _) = true
   217   | contains_Var _ = false;
   218 
   219 fun str_of_int n = 
   220   if n < 0 then "-" ^ ((string_of_int o abs) n)
   221   else string_of_int n;
   222 val int_of_str = Value.parse_int;
   223 fun int_of_str_opt str = 
   224   let
   225     val ss = Symbol.explode str
   226     val ss' = case ss of "(" :: s => drop_last s | _ => ss
   227     val (sign, istr) = case ss' of "-" :: istr => (~1, istr) | _ => (1, ss')
   228   in
   229     case Library.read_int istr of (i, []) => SOME (sign * i) | _ => NONE
   230   end;
   231 fun is_num' str = case int_of_str_opt str of SOME _ => true | NONE => false;
   232 fun is_num (Free (s, _)) = if is_num' s then true else false | is_num _ = false;
   233 fun term_of_num ntyp n = Free (str_of_int n, ntyp);
   234 fun num_of_term (t as (Free (istr, _))) = 
   235     (case int_of_str_opt istr of SOME i => i | NONE => raise TERM ("num_of_term: NOT int ", [t]))
   236   | num_of_term t = raise TERM ("num_of_term: NOT Free ", [t])
   237 
   238 fun is_Free (Free _) = true | is_Free _ = false;
   239 fun is_fun_id (Const _) = true
   240   | is_fun_id (Free _) = true
   241   | is_fun_id _ = false;
   242 fun is_f_x (f $ x) = is_fun_id f andalso is_Free x
   243   | is_f_x _ = false;
   244 
   245 fun vars t =
   246   let
   247     fun scan vs (Const _) = vs
   248       | scan vs (t as Free (s, _)) = if is_num' s then vs else t :: vs
   249       | scan vs (t as Var _) = t :: vs
   250       | scan vs (Bound _) = vs 
   251       | scan vs (Abs (_, _, t)) = scan vs t
   252       | scan vs (t1 $ t2) = (scan vs t1) @ (scan vs t2)
   253   in (distinct o (scan [])) t end;
   254 (* bypass Isabelle's Pretty, which requires ctxt *)
   255 fun ids2str t =
   256   let
   257     fun scan vs (Const (s, _)) = if is_num' s then vs else s :: vs
   258       | scan vs (Free (s, _)) = if is_num' s then vs else s :: vs
   259       | scan vs (Var ((s, i), _)) = (s ^ "_" ^ string_of_int i) :: vs
   260       | scan vs (Bound _) = vs 
   261       | scan vs (Abs (s, _, t)) = scan (s :: vs) t
   262       | scan vs (t1 $ t2) = (scan vs t1) @ (scan vs t2)
   263   in (distinct o (scan [])) t end;
   264 fun is_bdv str = case Symbol.explode str of "b"::"d"::"v"::_ => true | _ => false;
   265 (* instantiate #prop thm with bound variables (as Free) *)
   266 fun inst_bdv [] t = t
   267   | inst_bdv (instl: (term*term) list) t =
   268     let
   269       fun subst (v as Var((s, _), T)) = 
   270           (case Symbol.explode s of
   271             "b"::"d"::"v"::_ => if_none (assoc(instl,Free(s,T))) (Free(s,T))
   272           | _ => v)
   273         | subst (Abs(a, T, body)) = Abs(a, T, subst body)
   274         | subst (f $ t') = subst f $ subst t'
   275         | subst t = if_none (assoc (instl, t)) t
   276     in  subst t  end;
   277 
   278 (* is a term a substitution for a bdv as found in programs and tactics *)
   279 fun is_bdv_subst (Const ("List.list.Cons", _) $
   280       (Const ("Product_Type.Pair", _) $ str $ _) $ _) = is_bdv (HOLogic.dest_string str)
   281   | is_bdv_subst _ = false;
   282 
   283 (* this shall be improved due to future requirements *)
   284 fun guess_bdv_typ t = t |> vars |> hd |> type_of
   285 
   286 fun free2str (Free (s, _)) = s
   287   | free2str t = error ("free2str not for " ^ Rule.term2str t);
   288 fun str_of_free_opt (Free (s, _)) = SOME s
   289   | str_of_free_opt _ = NONE
   290 
   291 (* compare Logic.unvarify_global, which rejects Free *)
   292 fun var2free (t as Const _) = t
   293   | var2free (t as Free _) = t
   294   | var2free (Var((s, _), T)) = Free (s,T)
   295   | var2free (t as Bound _) = t 
   296   | var2free (Abs(s, T, t)) = Abs(s, T, var2free t)
   297   | var2free (t1 $ t2) = (var2free t1) $ (var2free t2);
   298   
   299 (* Logic.varify does NOT take care of 'Free ("1", _)'*)
   300 fun free2var (t as Const _) = t
   301   | free2var (t as Free (s, T)) = if is_num' s then t else Var ((s, 0), T)
   302   | free2var (t as Var _) = t
   303   | free2var (t as Bound _) = t 
   304   | free2var (Abs (s, T, t)) = Abs (s, T, free2var t)
   305   | free2var (t1 $ t2) = (free2var t1) $ (free2var t2);
   306 
   307 fun mk_listT T = Type ("List.list", [T]);
   308 fun list_const T = Const ("List.list.Cons", [T, mk_listT T] ---> mk_listT T);
   309 fun list2isalist T [] = Const ("List.list.Nil", mk_listT T)
   310   | list2isalist T (t :: ts) = (list_const T) $ t $ (list2isalist T ts);
   311 
   312 fun isapair2pair (Const ("Product_Type.Pair",_) $ a $ b) = (a, b)
   313   | isapair2pair t = 
   314     error ("isapair2pair called with " ^ Rule.term2str t);
   315 fun isalist2list ls =
   316   let
   317     fun get es (Const("List.list.Cons", _) $ t $ ls) = get (t :: es) ls
   318       | get es (Const("List.list.Nil", _)) = es
   319       | get _ t = raise TERM ("isalist2list applied to NON-list: ", [t])
   320   in (rev o (get [])) ls end;
   321 
   322 fun is_list ((Const ("List.list.Cons", _)) $ _ $ _) = true
   323   | is_list _ = false;
   324 fun dest_binop_typ (Type ("fun", [range, Type ("fun", [arg2, arg1])])) = (arg1, arg2, range)
   325   | dest_binop_typ _ = raise ERROR "dest_binop_typ: not binary";
   326 fun dest_equals (Const("HOL.eq", _) $ t $ u)  =  (t, u) (* Pure/logic.ML: Const ("==", ..*)
   327   | dest_equals t = raise TERM ("dest_equals'", [t]);
   328 fun is_equality (Const("HOL.eq",_) $ _ $ _)  =  true  (* logic.ML: Const("=="*)
   329   | is_equality _ = false;
   330 fun mk_equality (t, u) = (Const("HOL.eq", [type_of t, type_of u] ---> HOLogic.boolT) $ t $ u); 
   331 fun is_expliceq (Const("HOL.eq",_) $ (Free _) $ _)  =  true
   332   | is_expliceq _ = false;
   333 fun strip_trueprop (Const ("HOL.Trueprop", _) $ t) = t
   334   | strip_trueprop t = t;
   335 
   336 (* (A1==>...An==>B) goes to (A1==>...An==>)   Pure/logic.ML: term -> term list*)
   337 fun strip_imp_prems' (Const ("Pure.imp", _) $ A $ t) = 
   338     let
   339       fun coll_prems As (Const("Pure.imp", _) $ A $ t) = 
   340           coll_prems (As $ (Logic.implies $ A)) t
   341         | coll_prems As _ = SOME As
   342     in coll_prems (Logic.implies $ A) t end
   343   | strip_imp_prems' _ = NONE;  (* *)
   344 
   345 (* (A1==>...An==>) (B) goes to (A1==>...An==>B), where B is lowest branch, 2002 Pure/thm.ML *)
   346 fun ins_concl (Const ("Pure.imp", _) $ A $ t) B = Logic.implies $ A $ (ins_concl t B)
   347   | ins_concl (Const ("Pure.imp", _) $ A    ) B = Logic.implies $ A $ B
   348   | ins_concl t B =  raise TERM ("ins_concl", [t, B]);
   349 
   350 fun vperm (Var _, Var _) = true  (* 2002 Pure/thm.ML *)
   351   | vperm (Abs (_, _, s), Abs (_, _, t)) = vperm (s, t)
   352   | vperm (t1 $ t2, u1 $ u2) = vperm (t1, u1) andalso vperm (t2, u2)
   353   | vperm (t, u) = (t = u);
   354 
   355 (*2002 cp from Pure/term.ML --- since 2009 in Pure/old_term.ML*)
   356 fun mem_term (_, []) = false
   357   | mem_term (t, t' :: ts) = t aconv t' orelse mem_term (t, ts);
   358 fun subset_term ([], _) = true
   359   | subset_term (x :: xs, ys) = mem_term (x, ys) andalso subset_term (xs, ys);
   360 fun eq_set_term (xs, ys) =
   361     xs = ys orelse (subset_term (xs, ys) andalso subset_term (ys, xs));
   362 (*a total, irreflexive ordering on index names*)
   363 fun xless ((a, i), (b, j): indexname) = i<j  orelse  (i = j andalso a < b);
   364 (*a partial ordering (not reflexive) for atomic terms*)
   365 fun atless (Const (a, _), Const (b, _)) = a < b
   366   | atless (Free (a, _), Free (b, _)) = a < b
   367   | atless (Var (v, _), Var (w, _)) = xless (v, w)
   368   | atless (Bound i, Bound j) =  i < j
   369   | atless _ = false;
   370 (*insert atomic term into partially sorted list, suppressing duplicates (?)*)
   371 fun insert_aterm (t,us) =
   372   let fun inserta [] = [t]
   373         | inserta (us as u::us') =
   374               if atless(t,u) then t::us
   375               else if t=u then us (*duplicate*)
   376               else u :: inserta us'
   377   in inserta us end;
   378 
   379 (* Accumulates the Vars in the term, suppressing duplicates *)
   380 fun add_term_vars (t, vars: term list) = case t of
   381     Var   _ => insert_aterm (t, vars)
   382   | Abs (_, _, body) => add_term_vars (body, vars)
   383   | f$t =>  add_term_vars (f, add_term_vars (t, vars))
   384   | _ => vars;
   385 fun term_vars t = add_term_vars (t, []);
   386 
   387 (*2002 Pure/thm.ML *)
   388 fun var_perm (t, u) = vperm (t, u) andalso eq_set_term (term_vars t, term_vars u);
   389 (*2002 fun decomp_simp, Pure/thm.ML *)
   390 fun perm lhs rhs = var_perm (lhs, rhs) andalso not (lhs aconv rhs) andalso not (is_Var lhs);
   391 
   392 
   393 fun pairT T1 T2 = Type ("*", [T1, T2]);
   394 fun PairT T1 T2 = ([T1, T2] ---> Type ("*", [T1, T2]));
   395 fun pairt t1 t2 = Const ("Product_Type.Pair", PairT (type_of t1) (type_of t2)) $ t1 $ t2;
   396 
   397 fun mk_factroot op_(*=thy.sqrt*) T fact root = 
   398   Const ("Groups.times_class.times", [T, T] ---> T) $ (term_of_num T fact) $
   399     (Const (op_, T --> T) $ term_of_num T root);
   400 fun mk_var_op_num v op_ optype ntyp n = Const (op_, optype) $ v $ Free (str_of_int  n, ntyp);
   401 fun mk_num_op_var v op_ optype ntyp n = Const (op_, optype) $ Free (str_of_int n, ntyp) $ v;
   402 fun mk_num_op_num T1 T2 (op_, Top) n1 n2 =
   403   Const (op_, Top) $ Free (str_of_int n1, T1) $ Free (str_of_int n2, T2);
   404 fun mk_thmid thmid n1 n2 = 
   405   thmid ^ (strip_thy n1) ^ "_" ^ (strip_thy n2);
   406 fun mk_add t1 t2 =
   407   let
   408     val (T1, T2) = (type_of t1, type_of t2)
   409   in
   410     if T1 <> T2 then raise TYPE ("mk_add gets ", [T1, T2], [t1,t2])
   411     else (Const ("Groups.plus_class.plus", [T1, T2] ---> T1) $ t1 $ t2)
   412   end;
   413 
   414 (** transform binary numeralsstrings **)
   415 (*Makarius 100308, hacked by WN*)
   416 val numbers_to_string =
   417   let
   418     fun dest_num t =
   419       (case try HOLogic.dest_number t of
   420         SOME (T, i) =>
   421           (*if T = @{typ int} orelse T = @{typ real} then WN*)
   422             SOME (Free (signed_string_of_int i, T))
   423           (*else NONE  WN*)
   424       | NONE => NONE);
   425     fun to_str (Abs (x, T, b)) = Abs (x, T, to_str b)
   426       | to_str (t as (u1 $ u2)) =
   427           (case dest_num t of
   428             SOME t' => t'
   429           | NONE => to_str u1 $ to_str u2)
   430       | to_str t = perhaps dest_num t;
   431   in to_str end
   432 val uminus_to_string =
   433   let
   434 	  fun dest_num t =
   435 	    case t of
   436 	      (Const ("Groups.uminus_class.uminus", _) $ Free (s, T)) => 
   437 	        (case int_of_str_opt s of
   438 	          SOME i => SOME (Free (signed_string_of_int (~1 * i), T))
   439 	        | NONE => NONE)
   440 	    | _ => NONE;
   441     fun to_str (Abs (x, T, b)) = Abs (x, T, to_str b)
   442       | to_str (t as (u1 $ u2)) =
   443           (case dest_num t of SOME t' => t' | NONE => to_str u1 $ to_str u2)
   444       | to_str t = perhaps dest_num t;
   445   in to_str end;
   446 fun num_str thm =
   447   let
   448     val (deriv, 
   449 	   {cert = cert, tags = tags, maxidx = maxidx, shyps = shyps, 
   450 	    hyps = hyps, tpairs = tpairs, prop = prop}) = Thm.rep_thm_G thm
   451     val prop' = numbers_to_string prop;
   452   in Thm.assbl_thm deriv cert tags maxidx shyps hyps tpairs prop' end;
   453 
   454 fun mk_Free (s,T) = Free (s, T);
   455 fun mk_free T s =  Free (s, T);
   456 
   457 (*Special case: one argument cp from Isabelle2002/src/Pure/term.ML*)
   458 fun subst_bound (arg, t) =
   459   let
   460     fun subst (t as Bound i, lev) =
   461         if i < lev then t (*var is locally bound*)
   462         else if i = lev then incr_boundvars lev arg
   463         else Bound (i - 1) (*loose: change it*)
   464       | subst (Abs(a, T, body), lev) = Abs (a, T, subst (body, lev + 1))
   465       | subst (f$t, lev) =  subst(f, lev)  $  subst(t, lev)
   466       | subst (t, _) = t
   467   in subst (t, 0)  end;
   468 
   469 (* instantiate let; necessary for scan_up1 *)
   470 fun inst_abs (Const sT) = Const sT
   471   | inst_abs (Free sT) = Free sT
   472   | inst_abs (Bound n) = Bound n
   473   | inst_abs (Var iT) = Var iT
   474   | inst_abs (Const ("HOL.Let",T1) $ e $ (Abs (v, T2, b))) = 
   475     let val b' = subst_bound (Free (v, T2), b); (*fun variant_abs: term.ML*)
   476     in Const ("HOL.Let", T1) $ inst_abs e $ (Abs (v, T2, inst_abs b')) end
   477   | inst_abs (t1 $ t2) = inst_abs t1 $ inst_abs t2
   478   | inst_abs t = t;
   479 
   480 (* for parse and parse_patt: fix all types to real *)
   481 fun T_a2real (Type (s, [])) = 
   482     if s = "'a" orelse s = "'b" orelse s = "'c" then HOLogic.realT else Type (s, [])
   483   | T_a2real (Type (s, Ts)) = Type (s, map T_a2real Ts)
   484   | T_a2real (TFree (s, srt)) = 
   485     if s = "'a" orelse s = "'b" orelse s = "'c" then HOLogic.realT else TFree (s, srt)
   486   | T_a2real (TVar (("DUMMY", _), _)) = HOLogic.realT
   487   | T_a2real (TVar ((s, i), srt)) = 
   488     if s = "'a" orelse s = "'b" orelse s = "'c" then HOLogic.realT else TVar ((s, i), srt)
   489 fun typ_a2real (Const( s, T)) = (Const( s, T_a2real T)) 
   490   | typ_a2real (Free( s, T)) = (Free( s, T_a2real T))
   491   | typ_a2real (Var( n, T)) = (Var( n, T_a2real T))
   492   | typ_a2real (Bound i) = (Bound i)
   493   | typ_a2real (Abs(s,T,t)) = Abs(s, T, typ_a2real t)
   494   | typ_a2real (t1 $ t2) = (typ_a2real t1) $ (typ_a2real t2);
   495 
   496 (* TODO clarify parse with Test_Isac *)
   497 fun parseold thy str = (* before 2002 *)
   498   (let val t = ((*typ_a2real o*) numbers_to_string) (Syntax.read_term_global thy str)
   499    in SOME (Thm.global_cterm_of thy t) end)
   500   handle _(*EXN? ..Inner syntax error Failed to parse term*) => NONE;
   501 fun parseN thy str = (* introduced 2002 *)
   502   (let val t = (*(typ_a2real o numbers_to_string)*) (Syntax.read_term_global thy str)
   503    in SOME (Thm.global_cterm_of thy t) end)
   504   handle _(*EXN? ..Inner syntax error Failed to parse term*) => NONE;
   505 fun parse thy str = (* introduced 2010 *)
   506   (let val t = (typ_a2real o numbers_to_string) (Syntax.read_term_global thy str)
   507    in SOME (Thm.global_cterm_of thy t) end)
   508   handle _(*EXN? ..Inner syntax error Failed to parse term*) => NONE;
   509 
   510 (*WN110317 parseNEW will replace parse after introduction of ctxt completed*)
   511 fun parseNEW ctxt str = SOME (Syntax.read_term ctxt str |> numbers_to_string)
   512    handle _ => NONE;
   513 fun parseNEW' ctxt str = 
   514   case parseNEW ctxt str of
   515     SOME t => t
   516   | NONE => raise TERM ("NO parseNEW' for " ^ str, [])
   517 
   518 (* parse term patterns; Var ("v",_), i.e. "?v", are required for instantiation
   519   WN130613 probably compare to 
   520   http://www.mail-archive.com/isabelle-dev@mailbroy.informatik.tu-muenchen.de/msg04249.html*)
   521 fun parse_patt thy str =
   522   (thy, str) |>> Rule.thy2ctxt 
   523              |-> Proof_Context.read_term_pattern
   524              |> numbers_to_string (*TODO drop*)
   525              |> typ_a2real;       (*TODO drop*)
   526 fun str2term str = parse_patt (Rule.Thy_Info_get_theory "Isac_Knowledge") str
   527 
   528 (* TODO decide with Test_Isac *)
   529 fun is_atom t = length (vars t) = 1
   530 fun is_atom (Const ("Float.Float",_) $ _) = true
   531   | is_atom (Const ("ComplexI.I'_'_",_)) = true
   532   | is_atom (Const ("Groups.times_class.times",_) $ t $ Const ("ComplexI.I'_'_",_)) = is_atom t
   533   | is_atom (Const ("Groups.plus_class.plus",_) $ t1 $ Const ("ComplexI.I'_'_",_)) = is_atom t1
   534   | is_atom (Const ("Groups.plus_class.plus",_) $ t1 $ 
   535 		   (Const ("Groups.times_class.times",_) $ t2 $ Const ("ComplexI.I'_'_",_))) = 
   536     is_atom t1 andalso is_atom t2
   537   | is_atom (Const _) = true
   538   | is_atom (Free _) = true
   539   | is_atom (Var _) = true
   540   | is_atom _ = false;
   541 
   542 (* from Pure/term.ML; reports if ALL Free's have found a substitution
   543    (required for evaluating the preconditions of _incomplete_ models) *)
   544 fun subst_atomic_all [] t = (false (*TODO may be 'true' for some terms ?*), t)
   545   | subst_atomic_all instl t =
   546     let
   547       fun subst (Abs (a, T, body)) = 
   548           let
   549             val (all, body') = subst body
   550           in (all, Abs(a, T, body')) end
   551         | subst (f$tt) = 
   552 	        let
   553 	          val (all1, f') = subst f
   554 	          val (all2, tt') = subst tt
   555 	        in (all1 andalso all2, f' $ tt') end
   556         | subst (t as Free _) = 
   557 	        if is_num t then (true, t) (*numerals cannot be subst*)
   558 	        else (case assoc (instl, t) of
   559 					  SOME t' => (true, t')
   560 				  | NONE => (false, t))
   561         | subst t = (true, if_none (assoc(instl,t)) t)
   562     in subst t end;
   563 
   564 fun op contains_one_of (thm, ids) =
   565   Term.exists_Const (fn id => member op= ids id) (Thm.prop_of thm)
   566 
   567 fun var_for vs (t as Const (str, _)) id = if id = strip_thy str then t :: vs else vs
   568   | var_for vs (t as Free (str, _)) id = if id = str then t :: vs else vs
   569   | var_for vs (t as Var (idn, _)) id = if id = Term.string_of_vname idn then t :: vs else vs
   570   | var_for vs (Bound _) _ = vs
   571   | var_for vs (Abs (_, _, t)) id = var_for vs t id
   572   | var_for vs (t1 $ t2) id = (var_for vs t1 id) @ (var_for vs t2 id)
   573 
   574 val poly_consts = (* TODO: adopt syntax-const from Isabelle*)
   575   ["Groups.plus_class.plus", "Groups.minus_class.minus",
   576   "Rings.divide_class.divide", "Groups.times_class.times",
   577   "Prog_Expr.pow"];
   578 (* treat Free, Const, Var as variables in polynomials *)
   579 fun vars_of t =
   580   let
   581     val var_ids = t |> ids2str |> subtract op = poly_consts |> map strip_thy |> sort string_ord
   582   in (map (var_for [] t) var_ids) |> flat |> distinct end
   583 
   584 (* this may decompose an object-language isa-list;
   585    use only, if description is not available, eg. not input ?WN:14.5.03 ??!?*)
   586 fun dest_list' t = if is_list t then isalist2list t  else [t];
   587 
   588 fun raise_type_conflicts ts =
   589   let
   590     val dups = duplicates (op =) (map (fst o dest_Free) ts)
   591     val confl = filter (fn Free (str, _) => member op = dups str) ts
   592   in
   593     if confl = []
   594     then ()
   595     else raise TYPE ("formalisation inconsistent w.r.t. type inference: ",
   596       map (snd o dest_Free)confl, confl)
   597   end
   598 
   599 (* expects t as Const *)
   600 fun contains_Const_typeless ts t = (t
   601   |> strip_comb |> fst
   602   |> member (fn (t1, t2) => fst (dest_Const t1) = fst (dest_Const t2)) ts
   603 ) handle TERM("dest_Const", _) => raise TERM ("contains_Const_typeless", [t])
   604 
   605 
   606 end