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