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