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