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