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