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