src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author wenzelm
Tue Sep 29 16:24:36 2009 +0200 (2009-09-29)
changeset 32740 9dd0a2f83429
parent 32674 b629fbcc5313
child 32950 5d5e123443b3
child 33106 7a1636c3ffc9
permissions -rw-r--r--
explicit indication of Unsynchronized.ref;
     1 (* Author: Lukas Bulwahn, TU Muenchen
     2 
     3 (Prototype of) A compiler from predicates specified by intro/elim rules
     4 to equations.
     5 *)
     6 
     7 signature PREDICATE_COMPILE_CORE =
     8 sig
     9   val setup: theory -> theory
    10   val code_pred: bool -> string -> Proof.context -> Proof.state
    11   val code_pred_cmd: bool -> string -> Proof.context -> Proof.state
    12   type smode = (int * int list option) list
    13   type mode = smode option list * smode
    14   datatype tmode = Mode of mode * smode * tmode option list;
    15   (*val add_equations_of: bool -> string list -> theory -> theory *)
    16   val register_predicate : (thm list * thm * int) -> theory -> theory
    17   val register_intros : thm list -> theory -> theory
    18   val is_registered : theory -> string -> bool
    19  (* val fetch_pred_data : theory -> string -> (thm list * thm * int)  *)
    20   val predfun_intro_of: theory -> string -> mode -> thm
    21   val predfun_elim_of: theory -> string -> mode -> thm
    22   val strip_intro_concl: int -> term -> term * (term list * term list)
    23   val predfun_name_of: theory -> string -> mode -> string
    24   val all_preds_of : theory -> string list
    25   val modes_of: theory -> string -> mode list
    26   val sizelim_modes_of: theory -> string -> mode list
    27   val sizelim_function_name_of : theory -> string -> mode -> string
    28   val generator_modes_of: theory -> string -> mode list
    29   val generator_name_of : theory -> string -> mode -> string
    30   val string_of_mode : mode -> string
    31   val intros_of: theory -> string -> thm list
    32   val nparams_of: theory -> string -> int
    33   val add_intro: thm -> theory -> theory
    34   val set_elim: thm -> theory -> theory
    35   val set_nparams : string -> int -> theory -> theory
    36   val print_stored_rules: theory -> unit
    37   val print_all_modes: theory -> unit
    38   val do_proofs: bool Unsynchronized.ref
    39   val mk_casesrule : Proof.context -> int -> thm list -> term
    40   val analyze_compr: theory -> term -> term
    41   val eval_ref: (unit -> term Predicate.pred) option Unsynchronized.ref
    42   val add_equations : string list -> theory -> theory
    43   val code_pred_intros_attrib : attribute
    44   (* used by Quickcheck_Generator *) 
    45   (*val funT_of : mode -> typ -> typ
    46   val mk_if_pred : term -> term
    47   val mk_Eval : term * term -> term*)
    48   val mk_tupleT : typ list -> typ
    49 (*  val mk_predT :  typ -> typ *)
    50   (* temporary for testing of the compilation *)
    51   datatype indprem = Prem of term list * term | Negprem of term list * term | Sidecond of term |
    52     GeneratorPrem of term list * term | Generator of (string * typ);
    53  (* val prepare_intrs: theory -> string list ->
    54     (string * typ) list * int * string list * string list * (string * mode list) list *
    55     (string * (term list * indprem list) list) list * (string * (int option list * int)) list*)
    56   datatype compilation_funs = CompilationFuns of {
    57     mk_predT : typ -> typ,
    58     dest_predT : typ -> typ,
    59     mk_bot : typ -> term,
    60     mk_single : term -> term,
    61     mk_bind : term * term -> term,
    62     mk_sup : term * term -> term,
    63     mk_if : term -> term,
    64     mk_not : term -> term,
    65     mk_map : typ -> typ -> term -> term -> term,
    66     lift_pred : term -> term
    67   };  
    68   type moded_clause = term list * (indprem * tmode) list
    69   type 'a pred_mode_table = (string * (mode * 'a) list) list
    70   val infer_modes : theory -> (string * mode list) list
    71     -> (string * mode list) list
    72     -> string list
    73     -> (string * (term list * indprem list) list) list
    74     -> (moded_clause list) pred_mode_table
    75   val infer_modes_with_generator : theory -> (string * mode list) list
    76     -> (string * mode list) list
    77     -> string list
    78     -> (string * (term list * indprem list) list) list
    79     -> (moded_clause list) pred_mode_table  
    80   (*val compile_preds : theory -> compilation_funs -> string list -> string list
    81     -> (string * typ) list -> (moded_clause list) pred_mode_table -> term pred_mode_table
    82   val rpred_create_definitions :(string * typ) list -> string * mode list
    83     -> theory -> theory 
    84   val split_smode : int list -> term list -> (term list * term list) *)
    85   val print_moded_clauses :
    86     theory -> (moded_clause list) pred_mode_table -> unit
    87   val print_compiled_terms : theory -> term pred_mode_table -> unit
    88   (*val rpred_prove_preds : theory -> term pred_mode_table -> thm pred_mode_table*)
    89   val pred_compfuns : compilation_funs
    90   val rpred_compfuns : compilation_funs
    91   val dest_funT : typ -> typ * typ
    92  (* val depending_preds_of : theory -> thm list -> string list *)
    93   val add_quickcheck_equations : string list -> theory -> theory
    94   val add_sizelim_equations : string list -> theory -> theory
    95   val is_inductive_predicate : theory -> string -> bool
    96   val terms_vs : term list -> string list
    97   val subsets : int -> int -> int list list
    98   val check_mode_clause : bool -> theory -> string list ->
    99     (string * mode list) list -> (string * mode list) list -> mode -> (term list * indprem list)
   100       -> (term list * (indprem * tmode) list) option
   101   val string_of_moded_prem : theory -> (indprem * tmode) -> string
   102   val all_modes_of : theory -> (string * mode list) list
   103   val all_generator_modes_of : theory -> (string * mode list) list
   104   val compile_clause : compilation_funs -> term option -> (term list -> term) ->
   105     theory -> string list -> string list -> mode -> term -> moded_clause -> term
   106   val preprocess_intro : theory -> thm -> thm
   107   val is_constrt : theory -> term -> bool
   108   val is_predT : typ -> bool
   109   val guess_nparams : typ -> int
   110   val cprods_subset : 'a list list -> 'a list list
   111 end;
   112 
   113 structure Predicate_Compile_Core : PREDICATE_COMPILE_CORE =
   114 struct
   115 
   116 open Predicate_Compile_Aux;
   117 (** auxiliary **)
   118 
   119 (* debug stuff *)
   120 
   121 fun tracing s = (if ! Toplevel.debug then Output.tracing s else ());
   122 
   123 fun print_tac s = Seq.single; (*Tactical.print_tac s;*) (* (if ! Toplevel.debug then Tactical.print_tac s else Seq.single); *)
   124 fun debug_tac msg = Seq.single; (* (fn st => (Output.tracing msg; Seq.single st)); *)
   125 
   126 val do_proofs = Unsynchronized.ref true;
   127 
   128 (* reference to preprocessing of InductiveSet package *)
   129 
   130 val ind_set_codegen_preproc = (fn thy => I) (*Inductive_Set.codegen_preproc;*)
   131 
   132 (** fundamentals **)
   133 
   134 (* syntactic operations *)
   135 
   136 fun mk_eq (x, xs) =
   137   let fun mk_eqs _ [] = []
   138         | mk_eqs a (b::cs) =
   139             HOLogic.mk_eq (Free (a, fastype_of b), b) :: mk_eqs a cs
   140   in mk_eqs x xs end;
   141 
   142 fun mk_tupleT [] = HOLogic.unitT
   143   | mk_tupleT Ts = foldr1 HOLogic.mk_prodT Ts;
   144 
   145 fun dest_tupleT (Type (@{type_name Product_Type.unit}, [])) = []
   146   | dest_tupleT (Type (@{type_name "*"}, [T1, T2])) = T1 :: (dest_tupleT T2)
   147   | dest_tupleT t = [t]
   148 
   149 fun mk_tuple [] = HOLogic.unit
   150   | mk_tuple ts = foldr1 HOLogic.mk_prod ts;
   151 
   152 fun dest_tuple (Const (@{const_name Product_Type.Unity}, _)) = []
   153   | dest_tuple (Const (@{const_name Pair}, _) $ t1 $ t2) = t1 :: (dest_tuple t2)
   154   | dest_tuple t = [t]
   155 
   156 fun mk_scomp (t, u) =
   157   let
   158     val T = fastype_of t
   159     val U = fastype_of u
   160     val [A] = binder_types T
   161     val D = body_type U 
   162   in 
   163     Const (@{const_name "scomp"}, T --> U --> A --> D) $ t $ u
   164   end;
   165 
   166 fun dest_funT (Type ("fun",[S, T])) = (S, T)
   167   | dest_funT T = raise TYPE ("dest_funT", [T], [])
   168  
   169 fun mk_fun_comp (t, u) =
   170   let
   171     val (_, B) = dest_funT (fastype_of t)
   172     val (C, A) = dest_funT (fastype_of u)
   173   in
   174     Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
   175   end;
   176 
   177 fun dest_randomT (Type ("fun", [@{typ Random.seed},
   178   Type ("*", [Type ("*", [T, @{typ "unit => Code_Evaluation.term"}]) ,@{typ Random.seed}])])) = T
   179   | dest_randomT T = raise TYPE ("dest_randomT", [T], [])
   180 
   181 (* destruction of intro rules *)
   182 
   183 (* FIXME: look for other place where this functionality was used before *)
   184 fun strip_intro_concl nparams intro = let
   185   val _ $ u = Logic.strip_imp_concl intro
   186   val (pred, all_args) = strip_comb u
   187   val (params, args) = chop nparams all_args
   188 in (pred, (params, args)) end
   189 
   190 (** data structures **)
   191 
   192 type smode = (int * int list option) list
   193 type mode = smode option list * smode;
   194 datatype tmode = Mode of mode * smode * tmode option list;
   195 
   196 fun gen_split_smode (mk_tuple, strip_tuple) smode ts =
   197   let
   198     fun split_tuple' _ _ [] = ([], [])
   199     | split_tuple' is i (t::ts) =
   200       (if i mem is then apfst else apsnd) (cons t)
   201         (split_tuple' is (i+1) ts)
   202     fun split_tuple is t = split_tuple' is 1 (strip_tuple t)
   203     fun split_smode' _ _ [] = ([], [])
   204       | split_smode' smode i (t::ts) =
   205         (if i mem (map fst smode) then
   206           case (the (AList.lookup (op =) smode i)) of
   207             NONE => apfst (cons t)
   208             | SOME is =>
   209               let
   210                 val (ts1, ts2) = split_tuple is t
   211                 fun cons_tuple ts = if null ts then I else cons (mk_tuple ts)
   212                 in (apfst (cons_tuple ts1)) o (apsnd (cons_tuple ts2)) end
   213           else apsnd (cons t))
   214         (split_smode' smode (i+1) ts)
   215   in split_smode' smode 1 ts end
   216 
   217 val split_smode = gen_split_smode (HOLogic.mk_tuple, HOLogic.strip_tuple)   
   218 val split_smodeT = gen_split_smode (HOLogic.mk_tupleT, HOLogic.strip_tupleT)
   219 
   220 fun gen_split_mode split_smode (iss, is) ts =
   221   let
   222     val (t1, t2) = chop (length iss) ts 
   223   in (t1, split_smode is t2) end
   224 
   225 val split_mode = gen_split_mode split_smode
   226 val split_modeT = gen_split_mode split_smodeT
   227 
   228 fun string_of_smode js =
   229     commas (map
   230       (fn (i, is) =>
   231         string_of_int i ^ (case is of NONE => ""
   232     | SOME is => "p" ^ enclose "[" "]" (commas (map string_of_int is)))) js)
   233 
   234 fun string_of_mode (iss, is) = space_implode " -> " (map
   235   (fn NONE => "X"
   236     | SOME js => enclose "[" "]" (string_of_smode js))
   237        (iss @ [SOME is]));
   238 
   239 fun string_of_tmode (Mode (predmode, termmode, param_modes)) =
   240   "predmode: " ^ (string_of_mode predmode) ^ 
   241   (if null param_modes then "" else
   242     "; " ^ "params: " ^ commas (map (the_default "NONE" o Option.map string_of_tmode) param_modes))
   243 
   244 (* generation of case rules from user-given introduction rules *)
   245 
   246 fun mk_casesrule ctxt nparams introrules =
   247   let
   248     val ((_, intros_th), ctxt1) = Variable.import false introrules ctxt
   249     val intros = map prop_of intros_th
   250     val (pred, (params, args)) = strip_intro_concl nparams (hd intros)
   251     val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
   252     val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
   253     val (argnames, ctxt3) = Variable.variant_fixes
   254       (map (fn i => "a" ^ string_of_int i) (1 upto (length args))) ctxt2
   255     val argvs = map2 (curry Free) argnames (map fastype_of args)
   256     fun mk_case intro =
   257       let
   258         val (_, (_, args)) = strip_intro_concl nparams intro
   259         val prems = Logic.strip_imp_prems intro
   260         val eqprems = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (argvs ~~ args)
   261         val frees = (fold o fold_aterms)
   262           (fn t as Free _ =>
   263               if member (op aconv) params t then I else insert (op aconv) t
   264            | _ => I) (args @ prems) []
   265       in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
   266     val assm = HOLogic.mk_Trueprop (list_comb (pred, params @ argvs))
   267     val cases = map mk_case intros
   268   in Logic.list_implies (assm :: cases, prop) end;
   269     
   270 
   271 datatype indprem = Prem of term list * term | Negprem of term list * term | Sidecond of term |
   272   GeneratorPrem of term list * term | Generator of (string * typ);
   273 
   274 type moded_clause = term list * (indprem * tmode) list
   275 type 'a pred_mode_table = (string * (mode * 'a) list) list
   276 
   277 datatype predfun_data = PredfunData of {
   278   name : string,
   279   definition : thm,
   280   intro : thm,
   281   elim : thm
   282 };
   283 
   284 fun rep_predfun_data (PredfunData data) = data;
   285 fun mk_predfun_data (name, definition, intro, elim) =
   286   PredfunData {name = name, definition = definition, intro = intro, elim = elim}
   287 
   288 datatype function_data = FunctionData of {
   289   name : string,
   290   equation : thm option (* is not used at all? *)
   291 };
   292 
   293 fun rep_function_data (FunctionData data) = data;
   294 fun mk_function_data (name, equation) =
   295   FunctionData {name = name, equation = equation}
   296 
   297 datatype pred_data = PredData of {
   298   intros : thm list,
   299   elim : thm option,
   300   nparams : int,
   301   functions : (mode * predfun_data) list,
   302   generators : (mode * function_data) list,
   303   sizelim_functions : (mode * function_data) list 
   304 };
   305 
   306 fun rep_pred_data (PredData data) = data;
   307 fun mk_pred_data ((intros, elim, nparams), (functions, generators, sizelim_functions)) =
   308   PredData {intros = intros, elim = elim, nparams = nparams,
   309     functions = functions, generators = generators, sizelim_functions = sizelim_functions}
   310 fun map_pred_data f (PredData {intros, elim, nparams, functions, generators, sizelim_functions}) =
   311   mk_pred_data (f ((intros, elim, nparams), (functions, generators, sizelim_functions)))
   312   
   313 fun eq_option eq (NONE, NONE) = true
   314   | eq_option eq (SOME x, SOME y) = eq (x, y)
   315   | eq_option eq _ = false
   316   
   317 fun eq_pred_data (PredData d1, PredData d2) = 
   318   eq_list (Thm.eq_thm) (#intros d1, #intros d2) andalso
   319   eq_option (Thm.eq_thm) (#elim d1, #elim d2) andalso
   320   #nparams d1 = #nparams d2
   321   
   322 structure PredData = TheoryDataFun
   323 (
   324   type T = pred_data Graph.T;
   325   val empty = Graph.empty;
   326   val copy = I;
   327   val extend = I;
   328   fun merge _ = Graph.merge eq_pred_data;
   329 );
   330 
   331 (* queries *)
   332 
   333 fun lookup_pred_data thy name =
   334   Option.map rep_pred_data (try (Graph.get_node (PredData.get thy)) name)
   335 
   336 fun the_pred_data thy name = case lookup_pred_data thy name
   337  of NONE => error ("No such predicate " ^ quote name)  
   338   | SOME data => data;
   339 
   340 val is_registered = is_some oo lookup_pred_data 
   341 
   342 val all_preds_of = Graph.keys o PredData.get
   343 
   344 fun intros_of thy = map (Thm.transfer thy) o #intros o the_pred_data thy
   345 
   346 fun the_elim_of thy name = case #elim (the_pred_data thy name)
   347  of NONE => error ("No elimination rule for predicate " ^ quote name)
   348   | SOME thm => Thm.transfer thy thm 
   349   
   350 val has_elim = is_some o #elim oo the_pred_data;
   351 
   352 val nparams_of = #nparams oo the_pred_data
   353 
   354 val modes_of = (map fst) o #functions oo the_pred_data
   355 
   356 val sizelim_modes_of = (map fst) o #sizelim_functions oo the_pred_data
   357 
   358 val rpred_modes_of = (map fst) o #generators oo the_pred_data
   359   
   360 fun all_modes_of thy = map (fn name => (name, modes_of thy name)) (all_preds_of thy) 
   361 
   362 val is_compiled = not o null o #functions oo the_pred_data
   363 
   364 fun lookup_predfun_data thy name mode =
   365   Option.map rep_predfun_data (AList.lookup (op =)
   366   (#functions (the_pred_data thy name)) mode)
   367 
   368 fun the_predfun_data thy name mode = case lookup_predfun_data thy name mode
   369   of NONE => error ("No function defined for mode " ^ string_of_mode mode ^ " of predicate " ^ name)
   370    | SOME data => data;
   371 
   372 val predfun_name_of = #name ooo the_predfun_data
   373 
   374 val predfun_definition_of = #definition ooo the_predfun_data
   375 
   376 val predfun_intro_of = #intro ooo the_predfun_data
   377 
   378 val predfun_elim_of = #elim ooo the_predfun_data
   379 
   380 fun lookup_generator_data thy name mode = 
   381   Option.map rep_function_data (AList.lookup (op =)
   382   (#generators (the_pred_data thy name)) mode)
   383   
   384 fun the_generator_data thy name mode = case lookup_generator_data thy name mode
   385   of NONE => error ("No generator defined for mode " ^ string_of_mode mode ^ " of predicate " ^ name)
   386    | SOME data => data
   387 
   388 val generator_name_of = #name ooo the_generator_data
   389 
   390 val generator_modes_of = (map fst) o #generators oo the_pred_data
   391 
   392 fun all_generator_modes_of thy =
   393   map (fn name => (name, generator_modes_of thy name)) (all_preds_of thy) 
   394 
   395 fun lookup_sizelim_function_data thy name mode =
   396   Option.map rep_function_data (AList.lookup (op =)
   397   (#sizelim_functions (the_pred_data thy name)) mode)
   398 
   399 fun the_sizelim_function_data thy name mode = case lookup_sizelim_function_data thy name mode
   400   of NONE => error ("No size-limited function defined for mode " ^ string_of_mode mode
   401     ^ " of predicate " ^ name)
   402    | SOME data => data
   403 
   404 val sizelim_function_name_of = #name ooo the_sizelim_function_data
   405 
   406 (*val generator_modes_of = (map fst) o #generators oo the_pred_data*)
   407      
   408 (* diagnostic display functions *)
   409 
   410 fun print_modes modes = Output.tracing ("Inferred modes:\n" ^
   411   cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
   412     string_of_mode ms)) modes));
   413 
   414 fun print_pred_mode_table string_of_entry thy pred_mode_table =
   415   let
   416     fun print_mode pred (mode, entry) =  "mode : " ^ (string_of_mode mode)
   417       ^ (string_of_entry pred mode entry)  
   418     fun print_pred (pred, modes) =
   419       "predicate " ^ pred ^ ": " ^ cat_lines (map (print_mode pred) modes)
   420     val _ = Output.tracing (cat_lines (map print_pred pred_mode_table))
   421   in () end;
   422 
   423 fun string_of_moded_prem thy (Prem (ts, p), tmode) =
   424     (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
   425     "(" ^ (string_of_tmode tmode) ^ ")"
   426   | string_of_moded_prem thy (GeneratorPrem (ts, p), Mode (predmode, is, _)) =
   427     (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
   428     "(generator_mode: " ^ (string_of_mode predmode) ^ ")"
   429   | string_of_moded_prem thy (Generator (v, T), _) =
   430     "Generator for " ^ v ^ " of Type " ^ (Syntax.string_of_typ_global thy T)
   431   | string_of_moded_prem thy (Negprem (ts, p), Mode (_, is, _)) =
   432     (Syntax.string_of_term_global thy (list_comb (p, ts))) ^
   433     "(negative mode: " ^ string_of_smode is ^ ")"
   434   | string_of_moded_prem thy (Sidecond t, Mode (_, is, _)) =
   435     (Syntax.string_of_term_global thy t) ^
   436     "(sidecond mode: " ^ string_of_smode is ^ ")"    
   437   | string_of_moded_prem _ _ = error "string_of_moded_prem: unimplemented"
   438      
   439 fun print_moded_clauses thy =
   440   let        
   441     fun string_of_clause pred mode clauses =
   442       cat_lines (map (fn (ts, prems) => (space_implode " --> "
   443         (map (string_of_moded_prem thy) prems)) ^ " --> " ^ pred ^ " "
   444         ^ (space_implode " " (map (Syntax.string_of_term_global thy) ts))) clauses)
   445   in print_pred_mode_table string_of_clause thy end;
   446 
   447 fun print_compiled_terms thy =
   448   print_pred_mode_table (fn _ => fn _ => Syntax.string_of_term_global thy) thy
   449     
   450 fun print_stored_rules thy =
   451   let
   452     val preds = (Graph.keys o PredData.get) thy
   453     fun print pred () = let
   454       val _ = writeln ("predicate: " ^ pred)
   455       val _ = writeln ("number of parameters: " ^ string_of_int (nparams_of thy pred))
   456       val _ = writeln ("introrules: ")
   457       val _ = fold (fn thm => fn u => writeln (Display.string_of_thm_global thy thm))
   458         (rev (intros_of thy pred)) ()
   459     in
   460       if (has_elim thy pred) then
   461         writeln ("elimrule: " ^ Display.string_of_thm_global thy (the_elim_of thy pred))
   462       else
   463         writeln ("no elimrule defined")
   464     end
   465   in
   466     fold print preds ()
   467   end;
   468 
   469 fun print_all_modes thy =
   470   let
   471     val _ = writeln ("Inferred modes:")
   472     fun print (pred, modes) u =
   473       let
   474         val _ = writeln ("predicate: " ^ pred)
   475         val _ = writeln ("modes: " ^ (commas (map string_of_mode modes)))
   476       in u end  
   477   in
   478     fold print (all_modes_of thy) ()
   479   end
   480   
   481 (** preprocessing rules **)  
   482 
   483 fun imp_prems_conv cv ct =
   484   case Thm.term_of ct of
   485     Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
   486   | _ => Conv.all_conv ct
   487 
   488 fun Trueprop_conv cv ct =
   489   case Thm.term_of ct of
   490     Const ("Trueprop", _) $ _ => Conv.arg_conv cv ct  
   491   | _ => error "Trueprop_conv"
   492 
   493 fun preprocess_intro thy rule =
   494   Conv.fconv_rule
   495     (imp_prems_conv
   496       (Trueprop_conv (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
   497     (Thm.transfer thy rule)
   498 
   499 fun preprocess_elim thy nparams elimrule =
   500   let
   501     val _ = Output.tracing ("Preprocessing elimination rule "
   502       ^ (Display.string_of_thm_global thy elimrule))
   503     fun replace_eqs (Const ("Trueprop", _) $ (Const ("op =", T) $ lhs $ rhs)) =
   504        HOLogic.mk_Trueprop (Const (@{const_name Predicate.eq}, T) $ lhs $ rhs)
   505      | replace_eqs t = t
   506     val prems = Thm.prems_of elimrule
   507     val nargs = length (snd (strip_comb (HOLogic.dest_Trueprop (hd prems)))) - nparams
   508     fun preprocess_case t =
   509      let
   510        val params = Logic.strip_params t
   511        val (assums1, assums2) = chop nargs (Logic.strip_assums_hyp t)
   512        val assums_hyp' = assums1 @ (map replace_eqs assums2)
   513      in
   514        list_all (params, Logic.list_implies (assums_hyp', Logic.strip_assums_concl t))
   515      end
   516     val cases' = map preprocess_case (tl prems)
   517     val elimrule' = Logic.list_implies ((hd prems) :: cases', Thm.concl_of elimrule)
   518     (*val _ =  Output.tracing ("elimrule': "^ (Syntax.string_of_term_global thy elimrule'))*)
   519     val bigeq = (Thm.symmetric (Conv.implies_concl_conv
   520       (MetaSimplifier.rewrite true [@{thm Predicate.eq_is_eq}])
   521         (cterm_of thy elimrule')))
   522     (*
   523     val _ = Output.tracing ("bigeq:" ^ (Display.string_of_thm_global thy bigeq))   
   524     val res = 
   525     Thm.equal_elim bigeq elimrule
   526     *)
   527     (*
   528     val t = (fn {...} => mycheat_tac thy 1)
   529     val eq = Goal.prove (ProofContext.init thy) [] [] (Logic.mk_equals ((Thm.prop_of elimrule), elimrule')) t
   530     *)
   531     val _ = Output.tracing "Preprocessed elimination rule"
   532   in
   533     Thm.equal_elim bigeq elimrule
   534   end;
   535 
   536 (* special case: predicate with no introduction rule *)
   537 fun noclause thy predname elim = let
   538   val T = (Logic.unvarifyT o Sign.the_const_type thy) predname
   539   val Ts = binder_types T
   540   val names = Name.variant_list []
   541         (map (fn i => "x" ^ (string_of_int i)) (1 upto (length Ts)))
   542   val vs = map2 (curry Free) names Ts
   543   val clausehd = HOLogic.mk_Trueprop (list_comb (Const (predname, T), vs))
   544   val intro_t = Logic.mk_implies (@{prop False}, clausehd)
   545   val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT))
   546   val elim_t = Logic.list_implies ([clausehd, Logic.mk_implies (@{prop False}, P)], P)
   547   val intro = Goal.prove (ProofContext.init thy) names [] intro_t
   548         (fn {...} => etac @{thm FalseE} 1)
   549   val elim = Goal.prove (ProofContext.init thy) ("P" :: names) [] elim_t
   550         (fn {...} => etac elim 1) 
   551 in
   552   ([intro], elim)
   553 end
   554 
   555 fun fetch_pred_data thy name =
   556   case try (Inductive.the_inductive (ProofContext.init thy)) name of
   557     SOME (info as (_, result)) => 
   558       let
   559         fun is_intro_of intro =
   560           let
   561             val (const, _) = strip_comb (HOLogic.dest_Trueprop (concl_of intro))
   562           in (fst (dest_Const const) = name) end;      
   563         val intros = ind_set_codegen_preproc thy ((map (preprocess_intro thy))
   564           (filter is_intro_of (#intrs result)))
   565         val pre_elim = nth (#elims result) (find_index (fn s => s = name) (#names (fst info)))
   566         val nparams = length (Inductive.params_of (#raw_induct result))
   567         val elim = singleton (ind_set_codegen_preproc thy) (preprocess_elim thy nparams pre_elim)
   568         val (intros, elim) = if null intros then noclause thy name elim else (intros, elim)
   569       in
   570         mk_pred_data ((intros, SOME elim, nparams), ([], [], []))
   571       end                                                                    
   572   | NONE => error ("No such predicate: " ^ quote name)
   573   
   574 (* updaters *)
   575 
   576 fun apfst3 f (x, y, z) =  (f x, y, z)
   577 fun apsnd3 f (x, y, z) =  (x, f y, z)
   578 fun aptrd3 f (x, y, z) =  (x, y, f z)
   579 
   580 fun add_predfun name mode data =
   581   let
   582     val add = (apsnd o apfst3 o cons) (mode, mk_predfun_data data)
   583   in PredData.map (Graph.map_node name (map_pred_data add)) end
   584 
   585 fun is_inductive_predicate thy name =
   586   is_some (try (Inductive.the_inductive (ProofContext.init thy)) name)
   587 
   588 fun depending_preds_of thy (key, value) =
   589   let
   590     val intros = (#intros o rep_pred_data) value
   591   in
   592     fold Term.add_const_names (map Thm.prop_of intros) []
   593       |> filter (fn c => (not (c = key)) andalso (is_inductive_predicate thy c orelse is_registered thy c))
   594   end;
   595 
   596 
   597 (* code dependency graph *)
   598 (*
   599 fun dependencies_of thy name =
   600   let
   601     val (intros, elim, nparams) = fetch_pred_data thy name 
   602     val data = mk_pred_data ((intros, SOME elim, nparams), ([], [], []))
   603     val keys = depending_preds_of thy intros
   604   in
   605     (data, keys)
   606   end;
   607 *)
   608 (* guessing number of parameters *)
   609 fun find_indexes pred xs =
   610   let
   611     fun find is n [] = is
   612       | find is n (x :: xs) = find (if pred x then (n :: is) else is) (n + 1) xs;
   613   in rev (find [] 0 xs) end;
   614 
   615 fun guess_nparams T =
   616   let
   617     val argTs = binder_types T
   618     val nparams = fold (curry Int.max)
   619       (map (fn x => x + 1) (find_indexes is_predT argTs)) 0
   620   in nparams end;
   621 
   622 fun add_intro thm thy = let
   623    val (name, T) = dest_Const (fst (strip_intro_concl 0 (prop_of thm)))
   624    fun cons_intro gr =
   625      case try (Graph.get_node gr) name of
   626        SOME pred_data => Graph.map_node name (map_pred_data
   627          (apfst (fn (intro, elim, nparams) => (thm::intro, elim, nparams)))) gr
   628      | NONE =>
   629        let
   630          val nparams = the_default (guess_nparams T)  (try (#nparams o rep_pred_data o (fetch_pred_data thy)) name)
   631        in Graph.new_node (name, mk_pred_data (([thm], NONE, nparams), ([], [], []))) gr end;
   632   in PredData.map cons_intro thy end
   633 
   634 fun set_elim thm = let
   635     val (name, _) = dest_Const (fst 
   636       (strip_comb (HOLogic.dest_Trueprop (hd (prems_of thm)))))
   637     fun set (intros, _, nparams) = (intros, SOME thm, nparams)  
   638   in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
   639 
   640 fun set_nparams name nparams = let
   641     fun set (intros, elim, _ ) = (intros, elim, nparams) 
   642   in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
   643     
   644 fun register_predicate (pre_intros, pre_elim, nparams) thy =
   645   let
   646     val (name, _) = dest_Const (fst (strip_intro_concl nparams (prop_of (hd pre_intros))))
   647     (* preprocessing *)
   648     val intros = ind_set_codegen_preproc thy (map (preprocess_intro thy) pre_intros)
   649     val elim = singleton (ind_set_codegen_preproc thy) (preprocess_elim thy nparams pre_elim)
   650   in
   651     if not (member (op =) (Graph.keys (PredData.get thy)) name) then
   652       PredData.map
   653         (Graph.new_node (name, mk_pred_data ((intros, SOME elim, nparams), ([], [], [])))) thy
   654     else thy
   655   end
   656 
   657 fun register_intros pre_intros thy =
   658   let
   659     val (c, T) = dest_Const (fst (strip_intro_concl 0 (prop_of (hd pre_intros))))
   660     val _ = Output.tracing ("Registering introduction rules of " ^ c)
   661     val _ = Output.tracing (commas (map (Display.string_of_thm_global thy) pre_intros))
   662     val nparams = guess_nparams T
   663     val pre_elim = 
   664       (Drule.standard o (setmp quick_and_dirty true (SkipProof.make_thm thy)))
   665       (mk_casesrule (ProofContext.init thy) nparams pre_intros)
   666   in register_predicate (pre_intros, pre_elim, nparams) thy end
   667 
   668 fun set_generator_name pred mode name = 
   669   let
   670     val set = (apsnd o apsnd3 o cons) (mode, mk_function_data (name, NONE))
   671   in
   672     PredData.map (Graph.map_node pred (map_pred_data set))
   673   end
   674 
   675 fun set_sizelim_function_name pred mode name = 
   676   let
   677     val set = (apsnd o aptrd3 o cons) (mode, mk_function_data (name, NONE))
   678   in
   679     PredData.map (Graph.map_node pred (map_pred_data set))
   680   end
   681 
   682 (** data structures for generic compilation for different monads **)
   683 
   684 (* maybe rename functions more generic:
   685   mk_predT -> mk_monadT; dest_predT -> dest_monadT
   686   mk_single -> mk_return (?)
   687 *)
   688 datatype compilation_funs = CompilationFuns of {
   689   mk_predT : typ -> typ,
   690   dest_predT : typ -> typ,
   691   mk_bot : typ -> term,
   692   mk_single : term -> term,
   693   mk_bind : term * term -> term,
   694   mk_sup : term * term -> term,
   695   mk_if : term -> term,
   696   mk_not : term -> term,
   697 (*  funT_of : mode -> typ -> typ, *)
   698 (*  mk_fun_of : theory -> (string * typ) -> mode -> term, *) 
   699   mk_map : typ -> typ -> term -> term -> term,
   700   lift_pred : term -> term
   701 };
   702 
   703 fun mk_predT (CompilationFuns funs) = #mk_predT funs
   704 fun dest_predT (CompilationFuns funs) = #dest_predT funs
   705 fun mk_bot (CompilationFuns funs) = #mk_bot funs
   706 fun mk_single (CompilationFuns funs) = #mk_single funs
   707 fun mk_bind (CompilationFuns funs) = #mk_bind funs
   708 fun mk_sup (CompilationFuns funs) = #mk_sup funs
   709 fun mk_if (CompilationFuns funs) = #mk_if funs
   710 fun mk_not (CompilationFuns funs) = #mk_not funs
   711 (*fun funT_of (CompilationFuns funs) = #funT_of funs*)
   712 (*fun mk_fun_of (CompilationFuns funs) = #mk_fun_of funs*)
   713 fun mk_map (CompilationFuns funs) = #mk_map funs
   714 fun lift_pred (CompilationFuns funs) = #lift_pred funs
   715 
   716 fun funT_of compfuns (iss, is) T =
   717   let
   718     val Ts = binder_types T
   719     val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
   720     val paramTs' = map2 (fn NONE => I | SOME is => funT_of compfuns ([], is)) iss paramTs
   721   in
   722     (paramTs' @ inargTs) ---> (mk_predT compfuns (mk_tupleT outargTs))
   723   end;
   724 
   725 fun mk_fun_of compfuns thy (name, T) mode = 
   726   Const (predfun_name_of thy name mode, funT_of compfuns mode T)
   727 
   728 
   729 structure PredicateCompFuns =
   730 struct
   731 
   732 fun mk_predT T = Type (@{type_name "Predicate.pred"}, [T])
   733 
   734 fun dest_predT (Type (@{type_name "Predicate.pred"}, [T])) = T
   735   | dest_predT T = raise TYPE ("dest_predT", [T], []);
   736 
   737 fun mk_bot T = Const (@{const_name Orderings.bot}, mk_predT T);
   738 
   739 fun mk_single t =
   740   let val T = fastype_of t
   741   in Const(@{const_name Predicate.single}, T --> mk_predT T) $ t end;
   742 
   743 fun mk_bind (x, f) =
   744   let val T as Type ("fun", [_, U]) = fastype_of f
   745   in
   746     Const (@{const_name Predicate.bind}, fastype_of x --> T --> U) $ x $ f
   747   end;
   748 
   749 val mk_sup = HOLogic.mk_binop @{const_name sup};
   750 
   751 fun mk_if cond = Const (@{const_name Predicate.if_pred},
   752   HOLogic.boolT --> mk_predT HOLogic.unitT) $ cond;
   753 
   754 fun mk_not t = let val T = mk_predT HOLogic.unitT
   755   in Const (@{const_name Predicate.not_pred}, T --> T) $ t end
   756 
   757 fun mk_Enum f =
   758   let val T as Type ("fun", [T', _]) = fastype_of f
   759   in
   760     Const (@{const_name Predicate.Pred}, T --> mk_predT T') $ f    
   761   end;
   762 
   763 fun mk_Eval (f, x) =
   764   let
   765     val T = fastype_of x
   766   in
   767     Const (@{const_name Predicate.eval}, mk_predT T --> T --> HOLogic.boolT) $ f $ x
   768   end;
   769 
   770 fun mk_map T1 T2 tf tp = Const (@{const_name Predicate.map},
   771   (T1 --> T2) --> mk_predT T1 --> mk_predT T2) $ tf $ tp;
   772 
   773 val lift_pred = I
   774 
   775 val compfuns = CompilationFuns {mk_predT = mk_predT, dest_predT = dest_predT, mk_bot = mk_bot,
   776   mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if, mk_not = mk_not,
   777   mk_map = mk_map, lift_pred = lift_pred};
   778 
   779 end;
   780 
   781 structure RPredCompFuns =
   782 struct
   783 
   784 fun mk_rpredT T =
   785   @{typ "Random.seed"} --> HOLogic.mk_prodT (PredicateCompFuns.mk_predT T, @{typ "Random.seed"})
   786 
   787 fun dest_rpredT (Type ("fun", [_,
   788   Type (@{type_name "*"}, [Type (@{type_name "Predicate.pred"}, [T]), _])])) = T
   789   | dest_rpredT T = raise TYPE ("dest_rpredT", [T], []); 
   790 
   791 fun mk_bot T = Const(@{const_name RPred.bot}, mk_rpredT T)
   792 
   793 fun mk_single t =
   794   let
   795     val T = fastype_of t
   796   in
   797     Const (@{const_name RPred.return}, T --> mk_rpredT T) $ t
   798   end;
   799 
   800 fun mk_bind (x, f) =
   801   let
   802     val T as (Type ("fun", [_, U])) = fastype_of f
   803   in
   804     Const (@{const_name RPred.bind}, fastype_of x --> T --> U) $ x $ f
   805   end
   806 
   807 val mk_sup = HOLogic.mk_binop @{const_name RPred.supp}
   808 
   809 fun mk_if cond = Const (@{const_name RPred.if_rpred},
   810   HOLogic.boolT --> mk_rpredT HOLogic.unitT) $ cond;
   811 
   812 fun mk_not t = error "Negation is not defined for RPred"
   813 
   814 fun mk_map t = error "FIXME" (*FIXME*)
   815 
   816 fun lift_pred t =
   817   let
   818     val T = PredicateCompFuns.dest_predT (fastype_of t)
   819     val lift_predT = PredicateCompFuns.mk_predT T --> mk_rpredT T 
   820   in
   821     Const (@{const_name "RPred.lift_pred"}, lift_predT) $ t  
   822   end;
   823 
   824 val compfuns = CompilationFuns {mk_predT = mk_rpredT, dest_predT = dest_rpredT, mk_bot = mk_bot,
   825     mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if, mk_not = mk_not,
   826     mk_map = mk_map, lift_pred = lift_pred};
   827 
   828 end;
   829 (* for external use with interactive mode *)
   830 val pred_compfuns = PredicateCompFuns.compfuns
   831 val rpred_compfuns = RPredCompFuns.compfuns;
   832 
   833 fun lift_random random =
   834   let
   835     val T = dest_randomT (fastype_of random)
   836   in
   837     Const (@{const_name lift_random}, (@{typ Random.seed} -->
   838       HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) --> 
   839       RPredCompFuns.mk_rpredT T) $ random
   840   end;
   841 
   842 fun sizelim_funT_of compfuns (iss, is) T =
   843   let
   844     val Ts = binder_types T
   845     val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
   846     val paramTs' = map2 (fn SOME is => sizelim_funT_of PredicateCompFuns.compfuns ([], is) | NONE => I) iss paramTs 
   847   in
   848     (paramTs' @ inargTs @ [@{typ "code_numeral"}]) ---> (mk_predT compfuns (mk_tupleT outargTs))
   849   end;  
   850 
   851 fun mk_sizelim_fun_of compfuns thy (name, T) mode =
   852   Const (sizelim_function_name_of thy name mode, sizelim_funT_of compfuns mode T)
   853   
   854 fun mk_generator_of compfuns thy (name, T) mode = 
   855   Const (generator_name_of thy name mode, sizelim_funT_of compfuns mode T)
   856 
   857 (* Mode analysis *)
   858 
   859 (*** check if a term contains only constructor functions ***)
   860 fun is_constrt thy =
   861   let
   862     val cnstrs = flat (maps
   863       (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
   864       (Symtab.dest (Datatype.get_all thy)));
   865     fun check t = (case strip_comb t of
   866         (Free _, []) => true
   867       | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
   868             (SOME (i, Tname), Type (Tname', _)) => length ts = i andalso Tname = Tname' andalso forall check ts
   869           | _ => false)
   870       | _ => false)
   871   in check end;
   872 
   873 (*** check if a type is an equality type (i.e. doesn't contain fun)
   874   FIXME this is only an approximation ***)
   875 fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
   876   | is_eqT _ = true;
   877 
   878 fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
   879 val terms_vs = distinct (op =) o maps term_vs;
   880 
   881 (** collect all Frees in a term (with duplicates!) **)
   882 fun term_vTs tm =
   883   fold_aterms (fn Free xT => cons xT | _ => I) tm [];
   884 
   885 (*FIXME this function should not be named merge... make it local instead*)
   886 fun merge xs [] = xs
   887   | merge [] ys = ys
   888   | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
   889       else y::merge (x::xs) ys;
   890 
   891 fun subsets i j = if i <= j then
   892        let val is = subsets (i+1) j
   893        in merge (map (fn ks => i::ks) is) is end
   894      else [[]];
   895      
   896 (* FIXME: should be in library - cprod = map_prod I *)
   897 fun cprod ([], ys) = []
   898   | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
   899 
   900 fun cprods xss = foldr (map op :: o cprod) [[]] xss;
   901 
   902 fun cprods_subset [] = [[]]
   903   | cprods_subset (xs :: xss) =
   904   let
   905     val yss = (cprods_subset xss)
   906   in maps (fn ys => map (fn x => cons x ys) xs) yss @ yss end
   907   
   908 (*TODO: cleanup function and put together with modes_of_term *)
   909 (*
   910 fun modes_of_param default modes t = let
   911     val (vs, t') = strip_abs t
   912     val b = length vs
   913     fun mk_modes name args = Option.map (maps (fn (m as (iss, is)) =>
   914         let
   915           val (args1, args2) =
   916             if length args < length iss then
   917               error ("Too few arguments for inductive predicate " ^ name)
   918             else chop (length iss) args;
   919           val k = length args2;
   920           val perm = map (fn i => (find_index_eq (Bound (b - i)) args2) + 1)
   921             (1 upto b)  
   922           val partial_mode = (1 upto k) \\ perm
   923         in
   924           if not (partial_mode subset is) then [] else
   925           let
   926             val is' = 
   927             (fold_index (fn (i, j) => if j mem is then cons (i + 1) else I) perm [])
   928             |> fold (fn i => if i > k then cons (i - k + b) else I) is
   929               
   930            val res = map (fn x => Mode (m, is', x)) (cprods (map
   931             (fn (NONE, _) => [NONE]
   932               | (SOME js, arg) => map SOME (filter
   933                   (fn Mode (_, js', _) => js=js') (modes_of_term modes arg)))
   934                     (iss ~~ args1)))
   935           in res end
   936         end)) (AList.lookup op = modes name)
   937   in case strip_comb t' of
   938     (Const (name, _), args) => the_default default (mk_modes name args)
   939     | (Var ((name, _), _), args) => the (mk_modes name args)
   940     | (Free (name, _), args) => the (mk_modes name args)
   941     | _ => default end
   942   
   943 and
   944 *)
   945 fun modes_of_term modes t =
   946   let
   947     val ks = map_index (fn (i, T) => (i, NONE)) (binder_types (fastype_of t));
   948     val default = [Mode (([], ks), ks, [])];
   949     fun mk_modes name args = Option.map (maps (fn (m as (iss, is)) =>
   950         let
   951           val (args1, args2) =
   952             if length args < length iss then
   953               error ("Too few arguments for inductive predicate " ^ name)
   954             else chop (length iss) args;
   955           val k = length args2;
   956           val prfx = map (rpair NONE) (1 upto k)
   957         in
   958           if not (is_prefix op = prfx is) then [] else
   959           let val is' = List.drop (is, k)
   960           in map (fn x => Mode (m, is', x)) (cprods (map
   961             (fn (NONE, _) => [NONE]
   962               | (SOME js, arg) => map SOME (filter
   963                   (fn Mode (_, js', _) => js=js') (modes_of_term modes arg)))
   964                     (iss ~~ args1)))
   965           end
   966         end)) (AList.lookup op = modes name)
   967 
   968   in
   969     case strip_comb (Envir.eta_contract t) of
   970       (Const (name, _), args) => the_default default (mk_modes name args)
   971     | (Var ((name, _), _), args) => the (mk_modes name args)
   972     | (Free (name, _), args) => the (mk_modes name args)
   973     | (Abs _, []) => error "Abs at param position" (* modes_of_param default modes t *)
   974     | _ => default
   975   end
   976   
   977 fun select_mode_prem thy modes vs ps =
   978   find_first (is_some o snd) (ps ~~ map
   979     (fn Prem (us, t) => find_first (fn Mode (_, is, _) =>
   980           let
   981             val (in_ts, out_ts) = split_smode is us;
   982             val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
   983             val vTs = maps term_vTs out_ts';
   984             val dupTs = map snd (duplicates (op =) vTs) @
   985               List.mapPartial (AList.lookup (op =) vTs) vs;
   986           in
   987             terms_vs (in_ts @ in_ts') subset vs andalso
   988             forall (is_eqT o fastype_of) in_ts' andalso
   989             term_vs t subset vs andalso
   990             forall is_eqT dupTs
   991           end)
   992             (modes_of_term modes t handle Option =>
   993                error ("Bad predicate: " ^ Syntax.string_of_term_global thy t))
   994       | Negprem (us, t) => find_first (fn Mode (_, is, _) =>
   995             length us = length is andalso
   996             terms_vs us subset vs andalso
   997             term_vs t subset vs)
   998             (modes_of_term modes t handle Option =>
   999                error ("Bad predicate: " ^ Syntax.string_of_term_global thy t))
  1000       | Sidecond t => if term_vs t subset vs then SOME (Mode (([], []), [], []))
  1001           else NONE
  1002       ) ps);
  1003 
  1004 fun fold_prem f (Prem (args, _)) = fold f args
  1005   | fold_prem f (Negprem (args, _)) = fold f args
  1006   | fold_prem f (Sidecond t) = f t
  1007 
  1008 fun all_subsets [] = [[]]
  1009   | all_subsets (x::xs) = let val xss' = all_subsets xs in xss' @ (map (cons x) xss') end
  1010 
  1011 fun generator vTs v = 
  1012   let
  1013     val T = the (AList.lookup (op =) vTs v)
  1014   in
  1015     (Generator (v, T), Mode (([], []), [], []))
  1016   end;
  1017 
  1018 fun gen_prem (Prem (us, t)) = GeneratorPrem (us, t)
  1019   | gen_prem (Negprem (us, t)) = error "it is a negated prem"
  1020   | gen_prem (Sidecond t) = error "it is a sidecond"
  1021   | gen_prem _ = error "gen_prem : invalid input for gen_prem"
  1022 
  1023 fun param_gen_prem param_vs (p as Prem (us, t as Free (v, _))) =
  1024   if member (op =) param_vs v then
  1025     GeneratorPrem (us, t)
  1026   else p  
  1027   | param_gen_prem param_vs p = p
  1028   
  1029 fun check_mode_clause with_generator thy param_vs modes gen_modes (iss, is) (ts, ps) =
  1030   let
  1031     (*
  1032   val _ = Output.tracing ("param_vs:" ^ commas param_vs)
  1033   val _ = Output.tracing ("iss:" ^
  1034     commas (map (fn is => case is of SOME is => string_of_smode is | NONE => "NONE") iss))
  1035     *)
  1036     val modes' = modes @ List.mapPartial
  1037       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
  1038         (param_vs ~~ iss);
  1039     val gen_modes' = gen_modes @ List.mapPartial
  1040       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
  1041         (param_vs ~~ iss);  
  1042     val vTs = distinct (op =) ((fold o fold_prem) Term.add_frees ps (fold Term.add_frees ts []))
  1043     val prem_vs = distinct (op =) ((fold o fold_prem) Term.add_free_names ps [])
  1044     fun check_mode_prems acc_ps vs [] = SOME (acc_ps, vs)
  1045       | check_mode_prems acc_ps vs ps = (case select_mode_prem thy modes' vs ps of
  1046           NONE =>
  1047             (if with_generator then
  1048               (case select_mode_prem thy gen_modes' vs ps of
  1049                 SOME (p as Prem _, SOME mode) => check_mode_prems ((gen_prem p, mode) :: acc_ps) 
  1050                   (case p of Prem (us, _) => vs union terms_vs us | _ => vs)
  1051                   (filter_out (equal p) ps)
  1052               | _ =>
  1053                   let 
  1054                     val all_generator_vs = all_subsets (prem_vs \\ vs) |> sort (int_ord o (pairself length))
  1055                   in
  1056                     case (find_first (fn generator_vs => is_some
  1057                       (select_mode_prem thy modes' (vs union generator_vs) ps)) all_generator_vs) of
  1058                       SOME generator_vs => check_mode_prems ((map (generator vTs) generator_vs) @ acc_ps)
  1059                         (vs union generator_vs) ps
  1060                     | NONE => let
  1061                     val _ = Output.tracing ("ps:" ^ (commas
  1062                     (map (fn p => string_of_moded_prem thy (p, Mode (([], []), [], []))) ps)))
  1063                   in (*error "mode analysis failed"*)NONE end
  1064                   end)
  1065             else
  1066               NONE)
  1067         | SOME (p, SOME mode) => check_mode_prems ((if with_generator then param_gen_prem param_vs p else p, mode) :: acc_ps) 
  1068             (case p of Prem (us, _) => vs union terms_vs us | _ => vs)
  1069             (filter_out (equal p) ps))
  1070     val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (split_smode is ts));
  1071     val in_vs = terms_vs in_ts;
  1072     val concl_vs = terms_vs ts
  1073   in
  1074     if forall is_eqT (map snd (duplicates (op =) (maps term_vTs in_ts))) andalso
  1075     forall (is_eqT o fastype_of) in_ts' then
  1076       case check_mode_prems [] (param_vs union in_vs) ps of
  1077          NONE => NONE
  1078        | SOME (acc_ps, vs) =>
  1079          if with_generator then
  1080            SOME (ts, (rev acc_ps) @ (map (generator vTs) (concl_vs \\ vs))) 
  1081          else
  1082            if concl_vs subset vs then SOME (ts, rev acc_ps) else NONE
  1083     else NONE
  1084   end;
  1085 
  1086 fun check_modes_pred with_generator thy param_vs clauses modes gen_modes (p, ms) =
  1087   let val SOME rs = AList.lookup (op =) clauses p
  1088   in (p, List.filter (fn m => case find_index
  1089     (is_none o check_mode_clause with_generator thy param_vs modes gen_modes m) rs of
  1090       ~1 => true
  1091     | i => (Output.tracing ("Clause " ^ string_of_int (i + 1) ^ " of " ^
  1092       p ^ " violates mode " ^ string_of_mode m);
  1093         Output.tracing (commas (map (Syntax.string_of_term_global thy) (fst (nth rs i)))); false)) ms)
  1094   end;
  1095 
  1096 fun get_modes_pred with_generator thy param_vs clauses modes gen_modes (p, ms) =
  1097   let
  1098     val SOME rs = AList.lookup (op =) clauses p 
  1099   in
  1100     (p, map (fn m =>
  1101       (m, map (the o check_mode_clause with_generator thy param_vs modes gen_modes m) rs)) ms)
  1102   end;
  1103   
  1104 fun fixp f (x : (string * mode list) list) =
  1105   let val y = f x
  1106   in if x = y then x else fixp f y end;
  1107 
  1108 fun infer_modes thy extra_modes all_modes param_vs clauses =
  1109   let
  1110     val modes =
  1111       fixp (fn modes =>
  1112         map (check_modes_pred false thy param_vs clauses (modes @ extra_modes) []) modes)
  1113           all_modes
  1114   in
  1115     map (get_modes_pred false thy param_vs clauses (modes @ extra_modes) []) modes
  1116   end;
  1117 
  1118 fun remove_from rem [] = []
  1119   | remove_from rem ((k, vs) :: xs) =
  1120     (case AList.lookup (op =) rem k of
  1121       NONE => (k, vs)
  1122     | SOME vs' => (k, vs \\ vs'))
  1123     :: remove_from rem xs
  1124     
  1125 fun infer_modes_with_generator thy extra_modes all_modes param_vs clauses =
  1126   let
  1127     val prednames = map fst clauses
  1128     val extra_modes = all_modes_of thy
  1129     val gen_modes = all_generator_modes_of thy
  1130       |> filter_out (fn (name, _) => member (op =) prednames name)
  1131     val starting_modes = remove_from extra_modes all_modes 
  1132     val modes =
  1133       fixp (fn modes =>
  1134         map (check_modes_pred true thy param_vs clauses extra_modes (gen_modes @ modes)) modes)
  1135          starting_modes 
  1136   in
  1137     map (get_modes_pred true thy param_vs clauses extra_modes (gen_modes @ modes)) modes
  1138   end;
  1139 
  1140 (* term construction *)
  1141 
  1142 fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
  1143       NONE => (Free (s, T), (names, (s, [])::vs))
  1144     | SOME xs =>
  1145         let
  1146           val s' = Name.variant names s;
  1147           val v = Free (s', T)
  1148         in
  1149           (v, (s'::names, AList.update (op =) (s, v::xs) vs))
  1150         end);
  1151 
  1152 fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
  1153   | distinct_v (t $ u) nvs =
  1154       let
  1155         val (t', nvs') = distinct_v t nvs;
  1156         val (u', nvs'') = distinct_v u nvs';
  1157       in (t' $ u', nvs'') end
  1158   | distinct_v x nvs = (x, nvs);
  1159 
  1160 fun compile_match thy compfuns eqs eqs' out_ts success_t =
  1161   let
  1162     val eqs'' = maps mk_eq eqs @ eqs'
  1163     val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
  1164     val name = Name.variant names "x";
  1165     val name' = Name.variant (name :: names) "y";
  1166     val T = mk_tupleT (map fastype_of out_ts);
  1167     val U = fastype_of success_t;
  1168     val U' = dest_predT compfuns U;
  1169     val v = Free (name, T);
  1170     val v' = Free (name', T);
  1171   in
  1172     lambda v (fst (Datatype.make_case
  1173       (ProofContext.init thy) DatatypeCase.Quiet [] v
  1174       [(mk_tuple out_ts,
  1175         if null eqs'' then success_t
  1176         else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
  1177           foldr1 HOLogic.mk_conj eqs'' $ success_t $
  1178             mk_bot compfuns U'),
  1179        (v', mk_bot compfuns U')]))
  1180   end;
  1181 
  1182 (*FIXME function can be removed*)
  1183 fun mk_funcomp f t =
  1184   let
  1185     val names = Term.add_free_names t [];
  1186     val Ts = binder_types (fastype_of t);
  1187     val vs = map Free
  1188       (Name.variant_list names (replicate (length Ts) "x") ~~ Ts)
  1189   in
  1190     fold_rev lambda vs (f (list_comb (t, vs)))
  1191   end;
  1192 (*
  1193 fun compile_param_ext thy compfuns modes (NONE, t) = t
  1194   | compile_param_ext thy compfuns modes (m as SOME (Mode ((iss, is'), is, ms)), t) =
  1195       let
  1196         val (vs, u) = strip_abs t
  1197         val (ivs, ovs) = split_mode is vs    
  1198         val (f, args) = strip_comb u
  1199         val (params, args') = chop (length ms) args
  1200         val (inargs, outargs) = split_mode is' args'
  1201         val b = length vs
  1202         val perm = map (fn i => (find_index_eq (Bound (b - i)) args') + 1) (1 upto b)
  1203         val outp_perm =
  1204           snd (split_mode is perm)
  1205           |> map (fn i => i - length (filter (fn x => x < i) is'))
  1206         val names = [] -- TODO
  1207         val out_names = Name.variant_list names (replicate (length outargs) "x")
  1208         val f' = case f of
  1209             Const (name, T) =>
  1210               if AList.defined op = modes name then
  1211                 mk_predfun_of thy compfuns (name, T) (iss, is')
  1212               else error "compile param: Not an inductive predicate with correct mode"
  1213           | Free (name, T) => Free (name, param_funT_of compfuns T (SOME is'))
  1214         val outTs = dest_tupleT (dest_predT compfuns (body_type (fastype_of f')))
  1215         val out_vs = map Free (out_names ~~ outTs)
  1216         val params' = map (compile_param thy modes) (ms ~~ params)
  1217         val f_app = list_comb (f', params' @ inargs)
  1218         val single_t = (mk_single compfuns (mk_tuple (map (fn i => nth out_vs (i - 1)) outp_perm)))
  1219         val match_t = compile_match thy compfuns [] [] out_vs single_t
  1220       in list_abs (ivs,
  1221         mk_bind compfuns (f_app, match_t))
  1222       end
  1223   | compile_param_ext _ _ _ _ = error "compile params"
  1224 *)
  1225 
  1226 fun compile_param neg_in_sizelim size thy compfuns (NONE, t) = t
  1227   | compile_param neg_in_sizelim size thy compfuns (m as SOME (Mode ((iss, is'), is, ms)), t) =
  1228    let
  1229      val (f, args) = strip_comb (Envir.eta_contract t)
  1230      val (params, args') = chop (length ms) args
  1231      val params' = map (compile_param neg_in_sizelim size thy compfuns) (ms ~~ params)
  1232      val mk_fun_of = case size of NONE => mk_fun_of | SOME _ => mk_sizelim_fun_of
  1233      val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of
  1234      val f' =
  1235        case f of
  1236          Const (name, T) =>
  1237            mk_fun_of compfuns thy (name, T) (iss, is')
  1238        | Free (name, T) =>
  1239          case neg_in_sizelim of
  1240            SOME _ =>  Free (name, sizelim_funT_of compfuns (iss, is') T)
  1241          | NONE => Free (name, funT_of compfuns (iss, is') T)
  1242            
  1243        | _ => error ("PredicateCompiler: illegal parameter term")
  1244    in
  1245      (case neg_in_sizelim of SOME size_t =>
  1246        (fn t =>
  1247        let
  1248          val Ts = fst (split_last (binder_types (fastype_of t)))
  1249          val names = map (fn i => "x" ^ string_of_int i) (1 upto length Ts)
  1250        in
  1251          list_abs (names ~~ Ts, list_comb (t, (map Bound ((length Ts) - 1 downto 0)) @ [size_t]))
  1252        end)
  1253      | NONE => I)
  1254      (list_comb (f', params' @ args'))
  1255    end
  1256 
  1257 fun compile_expr neg_in_sizelim size thy ((Mode (mode, is, ms)), t) =
  1258   case strip_comb t of
  1259     (Const (name, T), params) =>
  1260        let
  1261          val params' = map (compile_param neg_in_sizelim size thy PredicateCompFuns.compfuns) (ms ~~ params)
  1262          val mk_fun_of = case size of NONE => mk_fun_of | SOME _ => mk_sizelim_fun_of
  1263        in
  1264          list_comb (mk_fun_of PredicateCompFuns.compfuns thy (name, T) mode, params')
  1265        end
  1266   | (Free (name, T), args) =>
  1267        let 
  1268          val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of 
  1269        in
  1270          list_comb (Free (name, funT_of PredicateCompFuns.compfuns ([], is) T), args)
  1271        end;
  1272        
  1273 fun compile_gen_expr size thy compfuns ((Mode (mode, is, ms)), t) inargs =
  1274   case strip_comb t of
  1275     (Const (name, T), params) =>
  1276       let
  1277         val params' = map (compile_param NONE size thy PredicateCompFuns.compfuns) (ms ~~ params)
  1278       in
  1279         list_comb (mk_generator_of compfuns thy (name, T) mode, params' @ inargs)
  1280       end
  1281     | (Free (name, T), params) =>
  1282     lift_pred compfuns
  1283     (list_comb (Free (name, sizelim_funT_of PredicateCompFuns.compfuns ([], is) T), params @ inargs))
  1284       
  1285           
  1286 (** specific rpred functions -- move them to the correct place in this file *)
  1287 
  1288 fun mk_Eval_of size ((x, T), NONE) names = (x, names)
  1289   | mk_Eval_of size ((x, T), SOME mode) names =
  1290 	let
  1291     val Ts = binder_types T
  1292     (*val argnames = Name.variant_list names
  1293         (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts)));
  1294     val args = map Free (argnames ~~ Ts)
  1295     val (inargs, outargs) = split_smode mode args*)
  1296 		fun mk_split_lambda [] t = lambda (Free (Name.variant names "x", HOLogic.unitT)) t
  1297 			| mk_split_lambda [x] t = lambda x t
  1298 			| mk_split_lambda xs t =
  1299 			let
  1300 				fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
  1301 					| mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
  1302 			in
  1303 				mk_split_lambda' xs t
  1304 			end;
  1305   	fun mk_arg (i, T) =
  1306 		  let
  1307 	  	  val vname = Name.variant names ("x" ^ string_of_int i)
  1308 		    val default = Free (vname, T)
  1309 		  in 
  1310 		    case AList.lookup (op =) mode i of
  1311 		      NONE => (([], [default]), [default])
  1312 			  | SOME NONE => (([default], []), [default])
  1313 			  | SOME (SOME pis) =>
  1314 				  case HOLogic.strip_tupleT T of
  1315 						[] => error "pair mode but unit tuple" (*(([default], []), [default])*)
  1316 					| [_] => error "pair mode but not a tuple" (*(([default], []), [default])*)
  1317 					| Ts =>
  1318 					  let
  1319 							val vnames = Name.variant_list names
  1320 								(map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
  1321 									(1 upto length Ts))
  1322 							val args = map Free (vnames ~~ Ts)
  1323 							fun split_args (i, arg) (ins, outs) =
  1324 							  if member (op =) pis i then
  1325 							    (arg::ins, outs)
  1326 								else
  1327 								  (ins, arg::outs)
  1328 							val (inargs, outargs) = fold_rev split_args ((1 upto length Ts) ~~ args) ([], [])
  1329 							fun tuple args = if null args then [] else [HOLogic.mk_tuple args]
  1330 						in ((tuple inargs, tuple outargs), args) end
  1331 			end
  1332 		val (inoutargs, args) = split_list (map mk_arg (1 upto (length Ts) ~~ Ts))
  1333     val (inargs, outargs) = pairself flat (split_list inoutargs)
  1334     val size_t = case size of NONE => [] | SOME size_t => [size_t]
  1335 		val r = PredicateCompFuns.mk_Eval (list_comb (x, inargs @ size_t), mk_tuple outargs)
  1336     val t = fold_rev mk_split_lambda args r
  1337   in
  1338     (t, names)
  1339   end;
  1340 
  1341 fun compile_arg size thy param_vs iss arg = 
  1342   let
  1343     val funT_of = case size of NONE => funT_of | SOME _ => sizelim_funT_of
  1344     fun map_params (t as Free (f, T)) =
  1345       if member (op =) param_vs f then
  1346         case (the (AList.lookup (op =) (param_vs ~~ iss) f)) of
  1347           SOME is => let val T' = funT_of PredicateCompFuns.compfuns ([], is) T
  1348             in fst (mk_Eval_of size ((Free (f, T'), T), SOME is) []) end
  1349         | NONE => t
  1350       else t
  1351       | map_params t = t
  1352     in map_aterms map_params arg end
  1353   
  1354 fun compile_clause compfuns size final_term thy all_vs param_vs (iss, is) inp (ts, moded_ps) =
  1355   let
  1356     fun check_constrt t (names, eqs) =
  1357       if is_constrt thy t then (t, (names, eqs)) else
  1358         let
  1359           val s = Name.variant names "x";
  1360           val v = Free (s, fastype_of t)
  1361         in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
  1362 
  1363     val (in_ts, out_ts) = split_smode is ts;
  1364     val (in_ts', (all_vs', eqs)) =
  1365       fold_map check_constrt in_ts (all_vs, []);
  1366 
  1367     fun compile_prems out_ts' vs names [] =
  1368           let
  1369             val (out_ts'', (names', eqs')) =
  1370               fold_map check_constrt out_ts' (names, []);
  1371             val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
  1372               out_ts'' (names', map (rpair []) vs);
  1373           in
  1374           (* termify code:
  1375             compile_match thy compfuns constr_vs (eqs @ eqs') out_ts'''
  1376               (mk_single compfuns (mk_tuple (map mk_valtermify_term out_ts)))
  1377            *)
  1378             compile_match thy compfuns constr_vs (eqs @ eqs') out_ts'''
  1379               (final_term out_ts)
  1380           end
  1381       | compile_prems out_ts vs names ((p, mode as Mode ((_, is), _, _)) :: ps) =
  1382           let
  1383             val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
  1384             val (out_ts', (names', eqs)) =
  1385               fold_map check_constrt out_ts (names, [])
  1386             val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
  1387               out_ts' ((names', map (rpair []) vs))
  1388             val (compiled_clause, rest) = case p of
  1389                Prem (us, t) =>
  1390                  let
  1391                    val (in_ts, out_ts''') = split_smode is us;
  1392                    val in_ts = map (compile_arg size thy param_vs iss) in_ts
  1393                    val args = case size of
  1394                      NONE => in_ts
  1395                    | SOME size_t => in_ts @ [size_t]
  1396                    val u = lift_pred compfuns
  1397                      (list_comb (compile_expr NONE size thy (mode, t), args))                     
  1398                    val rest = compile_prems out_ts''' vs' names'' ps
  1399                  in
  1400                    (u, rest)
  1401                  end
  1402              | Negprem (us, t) =>
  1403                  let
  1404                    val (in_ts, out_ts''') = split_smode is us
  1405                    val u = lift_pred compfuns
  1406                      (mk_not PredicateCompFuns.compfuns (list_comb (compile_expr size NONE thy (mode, t), in_ts)))
  1407                    val rest = compile_prems out_ts''' vs' names'' ps
  1408                  in
  1409                    (u, rest)
  1410                  end
  1411              | Sidecond t =>
  1412                  let
  1413                    val rest = compile_prems [] vs' names'' ps;
  1414                  in
  1415                    (mk_if compfuns t, rest)
  1416                  end
  1417              | GeneratorPrem (us, t) =>
  1418                  let
  1419                    val (in_ts, out_ts''') = split_smode is us;
  1420                    val args = case size of
  1421                      NONE => in_ts
  1422                    | SOME size_t => in_ts @ [size_t]
  1423                    val u = compile_gen_expr size thy compfuns (mode, t) args
  1424                    val rest = compile_prems out_ts''' vs' names'' ps
  1425                  in
  1426                    (u, rest)
  1427                  end
  1428              | Generator (v, T) =>
  1429                  let
  1430                    val u = lift_random (HOLogic.mk_random T (the size))
  1431                    val rest = compile_prems [Free (v, T)]  vs' names'' ps;
  1432                  in
  1433                    (u, rest)
  1434                  end
  1435           in
  1436             compile_match thy compfuns constr_vs' eqs out_ts'' 
  1437               (mk_bind compfuns (compiled_clause, rest))
  1438           end
  1439     val prem_t = compile_prems in_ts' param_vs all_vs' moded_ps;
  1440   in
  1441     mk_bind compfuns (mk_single compfuns inp, prem_t)
  1442   end
  1443 
  1444 fun compile_pred compfuns mk_fun_of use_size thy all_vs param_vs s T mode moded_cls =
  1445   let
  1446 	  val (Ts1, Ts2) = chop (length (fst mode)) (binder_types T)
  1447     val (Us1, Us2) = split_smodeT (snd mode) Ts2
  1448     val funT_of = if use_size then sizelim_funT_of else funT_of
  1449     val Ts1' = map2 (fn NONE => I | SOME is => funT_of PredicateCompFuns.compfuns ([], is)) (fst mode) Ts1
  1450     val size_name = Name.variant (all_vs @ param_vs) "size"
  1451   	fun mk_input_term (i, NONE) =
  1452 		    [Free (Name.variant (all_vs @ param_vs) ("x" ^ string_of_int i), nth Ts2 (i - 1))]
  1453 		  | mk_input_term (i, SOME pis) = case HOLogic.strip_tupleT (nth Ts2 (i - 1)) of
  1454 						   [] => error "strange unit input"
  1455 					   | [T] => [Free (Name.variant (all_vs @ param_vs) ("x" ^ string_of_int i), nth Ts2 (i - 1))]
  1456 						 | Ts => let
  1457 							 val vnames = Name.variant_list (all_vs @ param_vs)
  1458 								(map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
  1459 									pis)
  1460 						 in if null pis then []
  1461 						   else [HOLogic.mk_tuple (map Free (vnames ~~ map (fn j => nth Ts (j - 1)) pis))] end
  1462 		val in_ts = maps mk_input_term (snd mode)
  1463     val params = map2 (fn s => fn T => Free (s, T)) param_vs Ts1'
  1464     val size = Free (size_name, @{typ "code_numeral"})
  1465     val decr_size =
  1466       if use_size then
  1467         SOME (Const ("HOL.minus_class.minus", @{typ "code_numeral => code_numeral => code_numeral"})
  1468           $ size $ Const ("HOL.one_class.one", @{typ "Code_Numeral.code_numeral"}))
  1469       else
  1470         NONE
  1471     val cl_ts =
  1472       map (compile_clause compfuns decr_size (fn out_ts => mk_single compfuns (mk_tuple out_ts))
  1473         thy all_vs param_vs mode (mk_tuple in_ts)) moded_cls;
  1474     val t = foldr1 (mk_sup compfuns) cl_ts
  1475     val T' = mk_predT compfuns (mk_tupleT Us2)
  1476     val size_t = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
  1477       $ HOLogic.mk_eq (size, @{term "0 :: code_numeral"})
  1478       $ mk_bot compfuns (dest_predT compfuns T') $ t
  1479     val fun_const = mk_fun_of compfuns thy (s, T) mode
  1480     val eq = if use_size then
  1481       (list_comb (fun_const, params @ in_ts @ [size]), size_t)
  1482     else
  1483       (list_comb (fun_const, params @ in_ts), t)
  1484   in
  1485     HOLogic.mk_Trueprop (HOLogic.mk_eq eq)
  1486   end;
  1487   
  1488 (* special setup for simpset *)                  
  1489 val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms "HOL.simp_thms"} @ [@{thm Pair_eq}])
  1490   setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
  1491 	setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
  1492 
  1493 (* Definition of executable functions and their intro and elim rules *)
  1494 
  1495 fun print_arities arities = tracing ("Arities:\n" ^
  1496   cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
  1497     space_implode " -> " (map
  1498       (fn NONE => "X" | SOME k' => string_of_int k')
  1499         (ks @ [SOME k]))) arities));
  1500 
  1501 fun create_intro_elim_rule (mode as (iss, is)) defthm mode_id funT pred thy =
  1502 let
  1503   val Ts = binder_types (fastype_of pred)
  1504   val funtrm = Const (mode_id, funT)
  1505   val (Ts1, Ts2) = chop (length iss) Ts;
  1506   val Ts1' = map2 (fn NONE => I | SOME is => funT_of (PredicateCompFuns.compfuns) ([], is)) iss Ts1
  1507 	val param_names = Name.variant_list []
  1508     (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts1)));
  1509   val params = map Free (param_names ~~ Ts1')
  1510 	fun mk_args (i, T) argnames =
  1511     let
  1512 		  val vname = Name.variant (param_names @ argnames) ("x" ^ string_of_int (length Ts1' + i))
  1513 		  val default = (Free (vname, T), vname :: argnames)
  1514 	  in
  1515   	  case AList.lookup (op =) is i of
  1516 						 NONE => default
  1517 					 | SOME NONE => default
  1518         	 | SOME (SOME pis) =>
  1519 					   case HOLogic.strip_tupleT T of
  1520 						   [] => default
  1521 					   | [_] => default
  1522 						 | Ts => 
  1523 						let
  1524 							val vnames = Name.variant_list (param_names @ argnames)
  1525 								(map (fn j => "x" ^ string_of_int (length Ts1' + i) ^ "p" ^ string_of_int j)
  1526 									(1 upto (length Ts)))
  1527 						 in (HOLogic.mk_tuple (map Free (vnames ~~ Ts)), vnames  @ argnames) end
  1528 		end
  1529 	val (args, argnames) = fold_map mk_args (1 upto (length Ts2) ~~ Ts2) []
  1530   val (inargs, outargs) = split_smode is args
  1531   val param_names' = Name.variant_list (param_names @ argnames)
  1532     (map (fn i => "p" ^ string_of_int i) (1 upto (length iss)))
  1533   val param_vs = map Free (param_names' ~~ Ts1)
  1534   val (params', names) = fold_map (mk_Eval_of NONE) ((params ~~ Ts1) ~~ iss) []
  1535   val predpropI = HOLogic.mk_Trueprop (list_comb (pred, param_vs @ args))
  1536   val predpropE = HOLogic.mk_Trueprop (list_comb (pred, params' @ args))
  1537   val param_eqs = map (HOLogic.mk_Trueprop o HOLogic.mk_eq) (param_vs ~~ params')
  1538   val funargs = params @ inargs
  1539   val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, funargs),
  1540                   if null outargs then Free("y", HOLogic.unitT) else mk_tuple outargs))
  1541   val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, funargs),
  1542                    mk_tuple outargs))
  1543   val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
  1544   val simprules = [defthm, @{thm eval_pred},
  1545 	  @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
  1546   val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
  1547   val introthm = Goal.prove (ProofContext.init thy) (argnames @ param_names @ param_names' @ ["y"]) [] introtrm (fn {...} => unfolddef_tac)
  1548   val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
  1549   val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
  1550   val elimthm = Goal.prove (ProofContext.init thy) (argnames @ param_names @ param_names' @ ["y", "P"]) [] elimtrm (fn {...} => unfolddef_tac)
  1551 in
  1552   (introthm, elimthm)
  1553 end;
  1554 
  1555 fun create_constname_of_mode thy prefix name mode = 
  1556   let
  1557     fun string_of_mode mode = if null mode then "0"
  1558       else space_implode "_" (map (fn (i, NONE) => string_of_int i | (i, SOME pis) => string_of_int i ^ "p"
  1559         ^ space_implode "p" (map string_of_int pis)) mode)
  1560     val HOmode = space_implode "_and_"
  1561       (fold (fn NONE => I | SOME mode => cons (string_of_mode mode)) (fst mode) [])
  1562   in
  1563     (Sign.full_bname thy (prefix ^ (Long_Name.base_name name))) ^
  1564       (if HOmode = "" then "_" else "_for_" ^ HOmode ^ "_yields_") ^ (string_of_mode (snd mode))
  1565   end;
  1566 
  1567 fun split_tupleT is T =
  1568 	let
  1569 		fun split_tuple' _ _ [] = ([], [])
  1570 			| split_tuple' is i (T::Ts) =
  1571 			(if i mem is then apfst else apsnd) (cons T)
  1572 				(split_tuple' is (i+1) Ts)
  1573 	in
  1574 	  split_tuple' is 1 (HOLogic.strip_tupleT T)
  1575   end
  1576 	
  1577 fun mk_arg xin xout pis T =
  1578   let
  1579 	  val n = length (HOLogic.strip_tupleT T)
  1580 		val ni = length pis
  1581 	  fun mk_proj i j t =
  1582 		  (if i = j then I else HOLogic.mk_fst)
  1583 			  (funpow (i - 1) HOLogic.mk_snd t)
  1584 	  fun mk_arg' i (si, so) = if i mem pis then
  1585 		    (mk_proj si ni xin, (si+1, so))
  1586 		  else
  1587 			  (mk_proj so (n - ni) xout, (si, so+1))
  1588 	  val (args, _) = fold_map mk_arg' (1 upto n) (1, 1)
  1589 	in
  1590 	  HOLogic.mk_tuple args
  1591 	end
  1592 
  1593 fun create_definitions preds (name, modes) thy =
  1594   let
  1595     val compfuns = PredicateCompFuns.compfuns
  1596     val T = AList.lookup (op =) preds name |> the
  1597     fun create_definition (mode as (iss, is)) thy = let
  1598       val mode_cname = create_constname_of_mode thy "" name mode
  1599       val mode_cbasename = Long_Name.base_name mode_cname
  1600       val Ts = binder_types T
  1601       val (Ts1, Ts2) = chop (length iss) Ts
  1602       val (Us1, Us2) =  split_smodeT is Ts2
  1603       val Ts1' = map2 (fn NONE => I | SOME is => funT_of compfuns ([], is)) iss Ts1
  1604       val funT = (Ts1' @ Us1) ---> (mk_predT compfuns (mk_tupleT Us2))
  1605       val names = Name.variant_list []
  1606         (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts)));
  1607 			(* old *)
  1608 			(*
  1609 		  val xs = map Free (names ~~ (Ts1' @ Ts2))
  1610       val (xparams, xargs) = chop (length iss) xs
  1611       val (xins, xouts) = split_smode is xargs
  1612 			*)
  1613 			(* new *)
  1614 			val param_names = Name.variant_list []
  1615 			  (map (fn i => "x" ^ string_of_int i) (1 upto (length Ts1')))
  1616 		  val xparams = map Free (param_names ~~ Ts1')
  1617       fun mk_vars (i, T) names =
  1618 			  let
  1619 				  val vname = Name.variant names ("x" ^ string_of_int (length Ts1' + i))
  1620 				in
  1621 					case AList.lookup (op =) is i of
  1622 						 NONE => ((([], [Free (vname, T)]), Free (vname, T)), vname :: names)
  1623 					 | SOME NONE => ((([Free (vname, T)], []), Free (vname, T)), vname :: names)
  1624         	 | SOME (SOME pis) =>
  1625 					   let
  1626 						   val (Tins, Touts) = split_tupleT pis T
  1627 							 val name_in = Name.variant names ("x" ^ string_of_int (length Ts1' + i) ^ "in")
  1628 							 val name_out = Name.variant names ("x" ^ string_of_int (length Ts1' + i) ^ "out")
  1629 						   val xin = Free (name_in, HOLogic.mk_tupleT Tins)
  1630 							 val xout = Free (name_out, HOLogic.mk_tupleT Touts)
  1631 							 val xarg = mk_arg xin xout pis T
  1632 						 in (((if null Tins then [] else [xin], if null Touts then [] else [xout]), xarg), name_in :: name_out :: names) end
  1633 						 end
  1634    	  val (xinoutargs, names) = fold_map mk_vars ((1 upto (length Ts2)) ~~ Ts2) param_names
  1635       val (xinout, xargs) = split_list xinoutargs
  1636 			val (xins, xouts) = pairself flat (split_list xinout)
  1637 			val (xparams', names') = fold_map (mk_Eval_of NONE) ((xparams ~~ Ts1) ~~ iss) names
  1638       fun mk_split_lambda [] t = lambda (Free (Name.variant names' "x", HOLogic.unitT)) t
  1639         | mk_split_lambda [x] t = lambda x t
  1640         | mk_split_lambda xs t =
  1641         let
  1642           fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
  1643             | mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
  1644         in
  1645           mk_split_lambda' xs t
  1646         end;
  1647       val predterm = PredicateCompFuns.mk_Enum (mk_split_lambda xouts
  1648         (list_comb (Const (name, T), xparams' @ xargs)))
  1649       val lhs = list_comb (Const (mode_cname, funT), xparams @ xins)
  1650       val def = Logic.mk_equals (lhs, predterm)
  1651       val ([definition], thy') = thy |>
  1652         Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
  1653         PureThy.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
  1654       val (intro, elim) =
  1655         create_intro_elim_rule mode definition mode_cname funT (Const (name, T)) thy'
  1656       in thy'
  1657 			  |> add_predfun name mode (mode_cname, definition, intro, elim)
  1658         |> PureThy.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
  1659         |> PureThy.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
  1660         |> Theory.checkpoint
  1661       end;
  1662   in
  1663     fold create_definition modes thy
  1664   end;
  1665 
  1666 fun sizelim_create_definitions preds (name, modes) thy =
  1667   let
  1668     val T = AList.lookup (op =) preds name |> the
  1669     fun create_definition mode thy =
  1670       let
  1671         val mode_cname = create_constname_of_mode thy "sizelim_" name mode
  1672         val funT = sizelim_funT_of PredicateCompFuns.compfuns mode T
  1673       in
  1674         thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
  1675         |> set_sizelim_function_name name mode mode_cname 
  1676       end;
  1677   in
  1678     fold create_definition modes thy
  1679   end;
  1680 
  1681 fun generator_funT_of (iss, is) T =
  1682   let
  1683     val Ts = binder_types T
  1684     val (paramTs, (inargTs, outargTs)) = split_modeT (iss, is) Ts
  1685     val paramTs' = map2 (fn SOME is => sizelim_funT_of PredicateCompFuns.compfuns ([], is) | NONE => I) iss paramTs 
  1686   in
  1687     (paramTs' @ inargTs @ [@{typ "code_numeral"}]) ---> (mk_predT RPredCompFuns.compfuns (mk_tupleT outargTs))
  1688   end
  1689 
  1690 fun rpred_create_definitions preds (name, modes) thy =
  1691   let
  1692     val T = AList.lookup (op =) preds name |> the
  1693     fun create_definition mode thy =
  1694       let
  1695         val mode_cname = create_constname_of_mode thy "gen_" name mode
  1696         val funT = generator_funT_of mode T
  1697       in
  1698         thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
  1699         |> set_generator_name name mode mode_cname 
  1700       end;
  1701   in
  1702     fold create_definition modes thy
  1703   end;
  1704   
  1705 (* Proving equivalence of term *)
  1706 
  1707 fun is_Type (Type _) = true
  1708   | is_Type _ = false
  1709 
  1710 (* returns true if t is an application of an datatype constructor *)
  1711 (* which then consequently would be splitted *)
  1712 (* else false *)
  1713 fun is_constructor thy t =
  1714   if (is_Type (fastype_of t)) then
  1715     (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
  1716       NONE => false
  1717     | SOME info => (let
  1718       val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
  1719       val (c, _) = strip_comb t
  1720       in (case c of
  1721         Const (name, _) => name mem_string constr_consts
  1722         | _ => false) end))
  1723   else false
  1724 
  1725 (* MAJOR FIXME:  prove_params should be simple
  1726  - different form of introrule for parameters ? *)
  1727 fun prove_param thy (NONE, t) = TRY (rtac @{thm refl} 1)
  1728   | prove_param thy (m as SOME (Mode (mode, is, ms)), t) =
  1729   let
  1730     val  (f, args) = strip_comb (Envir.eta_contract t)
  1731     val (params, _) = chop (length ms) args
  1732     val f_tac = case f of
  1733       Const (name, T) => simp_tac (HOL_basic_ss addsimps 
  1734          ([@{thm eval_pred}, (predfun_definition_of thy name mode),
  1735          @{thm "split_eta"}, @{thm "split_beta"}, @{thm "fst_conv"},
  1736 				 @{thm "snd_conv"}, @{thm pair_collapse}, @{thm "Product_Type.split_conv"}])) 1
  1737     | Free _ => TRY (rtac @{thm refl} 1)
  1738     | Abs _ => error "prove_param: No valid parameter term"
  1739   in
  1740     REPEAT_DETERM (etac @{thm thin_rl} 1)
  1741     THEN REPEAT_DETERM (rtac @{thm ext} 1)
  1742     THEN print_tac "prove_param"
  1743     THEN f_tac
  1744     THEN print_tac "after simplification in prove_args"
  1745     THEN (EVERY (map (prove_param thy) (ms ~~ params)))
  1746     THEN (REPEAT_DETERM (atac 1))
  1747   end
  1748 
  1749 fun prove_expr thy (Mode (mode, is, ms), t, us) (premposition : int) =
  1750   case strip_comb t of
  1751     (Const (name, T), args) =>  
  1752       let
  1753         val introrule = predfun_intro_of thy name mode
  1754         val (args1, args2) = chop (length ms) args
  1755       in
  1756         rtac @{thm bindI} 1
  1757         THEN print_tac "before intro rule:"
  1758         (* for the right assumption in first position *)
  1759         THEN rotate_tac premposition 1
  1760         THEN debug_tac (Display.string_of_thm (ProofContext.init thy) introrule)
  1761         THEN rtac introrule 1
  1762         THEN print_tac "after intro rule"
  1763         (* work with parameter arguments *)
  1764         THEN (atac 1)
  1765         THEN (print_tac "parameter goal")
  1766         THEN (EVERY (map (prove_param thy) (ms ~~ args1)))
  1767         THEN (REPEAT_DETERM (atac 1))
  1768       end
  1769   | _ => rtac @{thm bindI} 1
  1770 	  THEN asm_full_simp_tac
  1771 		  (HOL_basic_ss' addsimps [@{thm "split_eta"}, @{thm "split_beta"}, @{thm "fst_conv"},
  1772 				 @{thm "snd_conv"}, @{thm pair_collapse}]) 1
  1773 	  THEN (atac 1)
  1774 	  THEN print_tac "after prove parameter call"
  1775 		
  1776 
  1777 fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st; 
  1778 
  1779 fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
  1780 
  1781 fun prove_match thy (out_ts : term list) = let
  1782   fun get_case_rewrite t =
  1783     if (is_constructor thy t) then let
  1784       val case_rewrites = (#case_rewrites (Datatype.the_info thy
  1785         ((fst o dest_Type o fastype_of) t)))
  1786       in case_rewrites @ (flat (map get_case_rewrite (snd (strip_comb t)))) end
  1787     else []
  1788   val simprules = @{thm "unit.cases"} :: @{thm "prod.cases"} :: (flat (map get_case_rewrite out_ts))
  1789 (* replace TRY by determining if it necessary - are there equations when calling compile match? *)
  1790 in
  1791    (* make this simpset better! *)
  1792   asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
  1793   THEN print_tac "after prove_match:"
  1794   THEN (DETERM (TRY (EqSubst.eqsubst_tac (ProofContext.init thy) [0] [@{thm "HOL.if_P"}] 1
  1795          THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss 1))))
  1796          THEN (SOLVED (asm_simp_tac HOL_basic_ss 1)))))
  1797   THEN print_tac "after if simplification"
  1798 end;
  1799 
  1800 (* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
  1801 
  1802 fun prove_sidecond thy modes t =
  1803   let
  1804     fun preds_of t nameTs = case strip_comb t of 
  1805       (f as Const (name, T), args) =>
  1806         if AList.defined (op =) modes name then (name, T) :: nameTs
  1807           else fold preds_of args nameTs
  1808       | _ => nameTs
  1809     val preds = preds_of t []
  1810     val defs = map
  1811       (fn (pred, T) => predfun_definition_of thy pred
  1812         ([], map (rpair NONE) (1 upto (length (binder_types T)))))
  1813         preds
  1814   in 
  1815     (* remove not_False_eq_True when simpset in prove_match is better *)
  1816     simp_tac (HOL_basic_ss addsimps
  1817       (@{thms "HOL.simp_thms"} @ (@{thm not_False_eq_True} :: @{thm eval_pred} :: defs))) 1 
  1818     (* need better control here! *)
  1819   end
  1820 
  1821 fun prove_clause thy nargs modes (iss, is) (_, clauses) (ts, moded_ps) =
  1822   let
  1823     val (in_ts, clause_out_ts) = split_smode is ts;
  1824     fun prove_prems out_ts [] =
  1825       (prove_match thy out_ts)
  1826 			THEN print_tac "before simplifying assumptions"
  1827       THEN asm_full_simp_tac HOL_basic_ss' 1
  1828 			THEN print_tac "before single intro rule"
  1829       THEN (rtac (if null clause_out_ts then @{thm singleI_unit} else @{thm singleI}) 1)
  1830     | prove_prems out_ts ((p, mode as Mode ((iss, is), _, param_modes)) :: ps) =
  1831       let
  1832         val premposition = (find_index (equal p) clauses) + nargs
  1833         val rest_tac = (case p of Prem (us, t) =>
  1834             let
  1835               val (_, out_ts''') = split_smode is us
  1836               val rec_tac = prove_prems out_ts''' ps
  1837             in
  1838               print_tac "before clause:"
  1839               THEN asm_simp_tac HOL_basic_ss 1
  1840               THEN print_tac "before prove_expr:"
  1841               THEN prove_expr thy (mode, t, us) premposition
  1842               THEN print_tac "after prove_expr:"
  1843               THEN rec_tac
  1844             end
  1845           | Negprem (us, t) =>
  1846             let
  1847               val (_, out_ts''') = split_smode is us
  1848               val rec_tac = prove_prems out_ts''' ps
  1849               val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  1850               val (_, params) = strip_comb t
  1851             in
  1852               rtac @{thm bindI} 1
  1853               THEN (if (is_some name) then
  1854                   simp_tac (HOL_basic_ss addsimps [predfun_definition_of thy (the name) (iss, is)]) 1
  1855                   THEN rtac @{thm not_predI} 1
  1856                   THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  1857                   THEN (REPEAT_DETERM (atac 1))
  1858                   (* FIXME: work with parameter arguments *)
  1859                   THEN (EVERY (map (prove_param thy) (param_modes ~~ params)))
  1860                 else
  1861                   rtac @{thm not_predI'} 1)
  1862                   THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  1863               THEN rec_tac
  1864             end
  1865           | Sidecond t =>
  1866            rtac @{thm bindI} 1
  1867            THEN rtac @{thm if_predI} 1
  1868            THEN print_tac "before sidecond:"
  1869            THEN prove_sidecond thy modes t
  1870            THEN print_tac "after sidecond:"
  1871            THEN prove_prems [] ps)
  1872       in (prove_match thy out_ts)
  1873           THEN rest_tac
  1874       end;
  1875     val prems_tac = prove_prems in_ts moded_ps
  1876   in
  1877     rtac @{thm bindI} 1
  1878     THEN rtac @{thm singleI} 1
  1879     THEN prems_tac
  1880   end;
  1881 
  1882 fun select_sup 1 1 = []
  1883   | select_sup _ 1 = [rtac @{thm supI1}]
  1884   | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
  1885 
  1886 fun prove_one_direction thy clauses preds modes pred mode moded_clauses =
  1887   let
  1888     val T = the (AList.lookup (op =) preds pred)
  1889     val nargs = length (binder_types T) - nparams_of thy pred
  1890     val pred_case_rule = the_elim_of thy pred
  1891   in
  1892     REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"}))
  1893 		THEN print_tac "before applying elim rule"
  1894     THEN etac (predfun_elim_of thy pred mode) 1
  1895     THEN etac pred_case_rule 1
  1896     THEN (EVERY (map
  1897            (fn i => EVERY' (select_sup (length moded_clauses) i) i) 
  1898              (1 upto (length moded_clauses))))
  1899     THEN (EVERY (map2 (prove_clause thy nargs modes mode) clauses moded_clauses))
  1900     THEN print_tac "proved one direction"
  1901   end;
  1902 
  1903 (** Proof in the other direction **)
  1904 
  1905 fun prove_match2 thy out_ts = let
  1906   fun split_term_tac (Free _) = all_tac
  1907     | split_term_tac t =
  1908       if (is_constructor thy t) then let
  1909         val info = Datatype.the_info thy ((fst o dest_Type o fastype_of) t)
  1910         val num_of_constrs = length (#case_rewrites info)
  1911         (* special treatment of pairs -- because of fishing *)
  1912         val split_rules = case (fst o dest_Type o fastype_of) t of
  1913           "*" => [@{thm prod.split_asm}] 
  1914           | _ => PureThy.get_thms thy (((fst o dest_Type o fastype_of) t) ^ ".split_asm")
  1915         val (_, ts) = strip_comb t
  1916       in
  1917         (Splitter.split_asm_tac split_rules 1)
  1918 (*        THEN (Simplifier.asm_full_simp_tac HOL_basic_ss 1)
  1919           THEN (DETERM (TRY (etac @{thm Pair_inject} 1))) *)
  1920         THEN (REPEAT_DETERM_N (num_of_constrs - 1) (etac @{thm botE} 1 ORELSE etac @{thm botE} 2))
  1921         THEN (EVERY (map split_term_tac ts))
  1922       end
  1923     else all_tac
  1924   in
  1925     split_term_tac (mk_tuple out_ts)
  1926     THEN (DETERM (TRY ((Splitter.split_asm_tac [@{thm "split_if_asm"}] 1) THEN (etac @{thm botE} 2))))
  1927   end
  1928 
  1929 (* VERY LARGE SIMILIRATIY to function prove_param 
  1930 -- join both functions
  1931 *)
  1932 (* TODO: remove function *)
  1933 
  1934 fun prove_param2 thy (NONE, t) = all_tac 
  1935   | prove_param2 thy (m as SOME (Mode (mode, is, ms)), t) = let
  1936     val  (f, args) = strip_comb (Envir.eta_contract t)
  1937     val (params, _) = chop (length ms) args
  1938     val f_tac = case f of
  1939         Const (name, T) => full_simp_tac (HOL_basic_ss addsimps 
  1940            (@{thm eval_pred}::(predfun_definition_of thy name mode)
  1941            :: @{thm "Product_Type.split_conv"}::[])) 1
  1942       | Free _ => all_tac
  1943       | _ => error "prove_param2: illegal parameter term"
  1944   in  
  1945     print_tac "before simplification in prove_args:"
  1946     THEN f_tac
  1947     THEN print_tac "after simplification in prove_args"
  1948     THEN (EVERY (map (prove_param2 thy) (ms ~~ params)))
  1949   end
  1950 
  1951 
  1952 fun prove_expr2 thy (Mode (mode, is, ms), t) = 
  1953   (case strip_comb t of
  1954     (Const (name, T), args) =>
  1955       etac @{thm bindE} 1
  1956       THEN (REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"})))
  1957       THEN print_tac "prove_expr2-before"
  1958       THEN (debug_tac (Syntax.string_of_term_global thy
  1959         (prop_of (predfun_elim_of thy name mode))))
  1960       THEN (etac (predfun_elim_of thy name mode) 1)
  1961       THEN print_tac "prove_expr2"
  1962       THEN (EVERY (map (prove_param2 thy) (ms ~~ args)))
  1963       THEN print_tac "finished prove_expr2"      
  1964     | _ => etac @{thm bindE} 1)
  1965     
  1966 (* FIXME: what is this for? *)
  1967 (* replace defined by has_mode thy pred *)
  1968 (* TODO: rewrite function *)
  1969 fun prove_sidecond2 thy modes t = let
  1970   fun preds_of t nameTs = case strip_comb t of 
  1971     (f as Const (name, T), args) =>
  1972       if AList.defined (op =) modes name then (name, T) :: nameTs
  1973         else fold preds_of args nameTs
  1974     | _ => nameTs
  1975   val preds = preds_of t []
  1976   val defs = map
  1977     (fn (pred, T) => predfun_definition_of thy pred 
  1978       ([], map (rpair NONE) (1 upto (length (binder_types T)))))
  1979       preds
  1980   in
  1981    (* only simplify the one assumption *)
  1982    full_simp_tac (HOL_basic_ss' addsimps @{thm eval_pred} :: defs) 1 
  1983    (* need better control here! *)
  1984    THEN print_tac "after sidecond2 simplification"
  1985    end
  1986   
  1987 fun prove_clause2 thy modes pred (iss, is) (ts, ps) i =
  1988   let
  1989     val pred_intro_rule = nth (intros_of thy pred) (i - 1)
  1990     val (in_ts, clause_out_ts) = split_smode is ts;
  1991     fun prove_prems2 out_ts [] =
  1992       print_tac "before prove_match2 - last call:"
  1993       THEN prove_match2 thy out_ts
  1994       THEN print_tac "after prove_match2 - last call:"
  1995       THEN (etac @{thm singleE} 1)
  1996       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  1997       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  1998       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  1999       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  2000       THEN SOLVED (print_tac "state before applying intro rule:"
  2001       THEN (rtac pred_intro_rule 1)
  2002       (* How to handle equality correctly? *)
  2003       THEN (print_tac "state before assumption matching")
  2004       THEN (REPEAT (atac 1 ORELSE 
  2005          (CHANGED (asm_full_simp_tac (HOL_basic_ss' addsimps
  2006 					 [@{thm split_eta}, @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]) 1)
  2007           THEN print_tac "state after simp_tac:"))))
  2008     | prove_prems2 out_ts ((p, mode as Mode ((iss, is), _, param_modes)) :: ps) =
  2009       let
  2010         val rest_tac = (case p of
  2011           Prem (us, t) =>
  2012           let
  2013             val (_, out_ts''') = split_smode is us
  2014             val rec_tac = prove_prems2 out_ts''' ps
  2015           in
  2016             (prove_expr2 thy (mode, t)) THEN rec_tac
  2017           end
  2018         | Negprem (us, t) =>
  2019           let
  2020             val (_, out_ts''') = split_smode is us
  2021             val rec_tac = prove_prems2 out_ts''' ps
  2022             val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  2023             val (_, params) = strip_comb t
  2024           in
  2025             print_tac "before neg prem 2"
  2026             THEN etac @{thm bindE} 1
  2027             THEN (if is_some name then
  2028                 full_simp_tac (HOL_basic_ss addsimps [predfun_definition_of thy (the name) (iss, is)]) 1 
  2029                 THEN etac @{thm not_predE} 1
  2030                 THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  2031                 THEN (EVERY (map (prove_param2 thy) (param_modes ~~ params)))
  2032               else
  2033                 etac @{thm not_predE'} 1)
  2034             THEN rec_tac
  2035           end 
  2036         | Sidecond t =>
  2037           etac @{thm bindE} 1
  2038           THEN etac @{thm if_predE} 1
  2039           THEN prove_sidecond2 thy modes t 
  2040           THEN prove_prems2 [] ps)
  2041       in print_tac "before prove_match2:"
  2042          THEN prove_match2 thy out_ts
  2043          THEN print_tac "after prove_match2:"
  2044          THEN rest_tac
  2045       end;
  2046     val prems_tac = prove_prems2 in_ts ps 
  2047   in
  2048     print_tac "starting prove_clause2"
  2049     THEN etac @{thm bindE} 1
  2050     THEN (etac @{thm singleE'} 1)
  2051     THEN (TRY (etac @{thm Pair_inject} 1))
  2052     THEN print_tac "after singleE':"
  2053     THEN prems_tac
  2054   end;
  2055  
  2056 fun prove_other_direction thy modes pred mode moded_clauses =
  2057   let
  2058     fun prove_clause clause i =
  2059       (if i < length moded_clauses then etac @{thm supE} 1 else all_tac)
  2060       THEN (prove_clause2 thy modes pred mode clause i)
  2061   in
  2062     (DETERM (TRY (rtac @{thm unit.induct} 1)))
  2063      THEN (REPEAT_DETERM (CHANGED (rewtac @{thm split_paired_all})))
  2064      THEN (rtac (predfun_intro_of thy pred mode) 1)
  2065      THEN (REPEAT_DETERM (rtac @{thm refl} 2))
  2066      THEN (EVERY (map2 prove_clause moded_clauses (1 upto (length moded_clauses))))
  2067   end;
  2068 
  2069 (** proof procedure **)
  2070 
  2071 fun prove_pred thy clauses preds modes pred mode (moded_clauses, compiled_term) =
  2072   let
  2073     val ctxt = ProofContext.init thy
  2074     val clauses = the (AList.lookup (op =) clauses pred)
  2075   in
  2076     Goal.prove ctxt (Term.add_free_names compiled_term []) [] compiled_term
  2077       (if !do_proofs then
  2078         (fn _ =>
  2079         rtac @{thm pred_iffI} 1
  2080 				THEN print_tac "after pred_iffI"
  2081         THEN prove_one_direction thy clauses preds modes pred mode moded_clauses
  2082         THEN print_tac "proved one direction"
  2083         THEN prove_other_direction thy modes pred mode moded_clauses
  2084         THEN print_tac "proved other direction")
  2085       else (fn _ => setmp quick_and_dirty true SkipProof.cheat_tac thy))
  2086   end;
  2087 
  2088 (* composition of mode inference, definition, compilation and proof *)
  2089 
  2090 (** auxillary combinators for table of preds and modes **)
  2091 
  2092 fun map_preds_modes f preds_modes_table =
  2093   map (fn (pred, modes) =>
  2094     (pred, map (fn (mode, value) => (mode, f pred mode value)) modes)) preds_modes_table
  2095 
  2096 fun join_preds_modes table1 table2 =
  2097   map_preds_modes (fn pred => fn mode => fn value =>
  2098     (value, the (AList.lookup (op =) (the (AList.lookup (op =) table2 pred)) mode))) table1
  2099     
  2100 fun maps_modes preds_modes_table =
  2101   map (fn (pred, modes) =>
  2102     (pred, map (fn (mode, value) => value) modes)) preds_modes_table  
  2103     
  2104 fun compile_preds compfuns mk_fun_of use_size thy all_vs param_vs preds moded_clauses =
  2105   map_preds_modes (fn pred => compile_pred compfuns mk_fun_of use_size thy all_vs param_vs pred
  2106       (the (AList.lookup (op =) preds pred))) moded_clauses  
  2107   
  2108 fun prove thy clauses preds modes moded_clauses compiled_terms =
  2109   map_preds_modes (prove_pred thy clauses preds modes)
  2110     (join_preds_modes moded_clauses compiled_terms)
  2111 
  2112 fun prove_by_skip thy _ _ _ _ compiled_terms =
  2113   map_preds_modes (fn pred => fn mode => fn t => Drule.standard (setmp quick_and_dirty true (SkipProof.make_thm thy) t))
  2114     compiled_terms
  2115     
  2116 fun prepare_intrs thy prednames =
  2117   let
  2118     val intrs = maps (intros_of thy) prednames
  2119       |> map (Logic.unvarify o prop_of)
  2120     val nparams = nparams_of thy (hd prednames)
  2121     val extra_modes = all_modes_of thy |> filter_out (fn (name, _) => member (op =) prednames name)
  2122     val preds = distinct (op =) (map (dest_Const o fst o (strip_intro_concl nparams)) intrs)
  2123     val _ $ u = Logic.strip_imp_concl (hd intrs);
  2124     val params = List.take (snd (strip_comb u), nparams);
  2125     val param_vs = maps term_vs params
  2126     val all_vs = terms_vs intrs
  2127     fun dest_prem t =
  2128       (case strip_comb t of
  2129         (v as Free _, ts) => if v mem params then Prem (ts, v) else Sidecond t
  2130       | (c as Const (@{const_name Not}, _), [t]) => (case dest_prem t of          
  2131           Prem (ts, t) => Negprem (ts, t)
  2132         | Negprem _ => error ("Double negation not allowed in premise: " ^ (Syntax.string_of_term_global thy (c $ t))) 
  2133         | Sidecond t => Sidecond (c $ t))
  2134       | (c as Const (s, _), ts) =>
  2135         if is_registered thy s then
  2136           let val (ts1, ts2) = chop (nparams_of thy s) ts
  2137           in Prem (ts2, list_comb (c, ts1)) end
  2138         else Sidecond t
  2139       | _ => Sidecond t)
  2140     fun add_clause intr (clauses, arities) =
  2141     let
  2142       val _ $ t = Logic.strip_imp_concl intr;
  2143       val (Const (name, T), ts) = strip_comb t;
  2144       val (ts1, ts2) = chop nparams ts;
  2145       val prems = map (dest_prem o HOLogic.dest_Trueprop) (Logic.strip_imp_prems intr);
  2146       val (Ts, Us) = chop nparams (binder_types T)
  2147     in
  2148       (AList.update op = (name, these (AList.lookup op = clauses name) @
  2149         [(ts2, prems)]) clauses,
  2150        AList.update op = (name, (map (fn U => (case strip_type U of
  2151                  (Rs as _ :: _, Type ("bool", [])) => SOME (length Rs)
  2152                | _ => NONE)) Ts,
  2153              length Us)) arities)
  2154     end;
  2155     val (clauses, arities) = fold add_clause intrs ([], []);
  2156     fun modes_of_arities arities =
  2157       (map (fn (s, (ks, k)) => (s, cprod (cprods (map
  2158             (fn NONE => [NONE]
  2159               | SOME k' => map SOME (map (map (rpair NONE)) (subsets 1 k'))) ks),
  2160        map (map (rpair NONE)) (subsets 1 k)))) arities)
  2161     fun modes_of_typ T =
  2162       let
  2163         val (Ts, Us) = chop nparams (binder_types T)
  2164         fun all_smodes_of_typs Ts = cprods_subset (
  2165           map_index (fn (i, U) =>
  2166             case HOLogic.strip_tupleT U of
  2167               [] => [(i + 1, NONE)]
  2168             | [U] => [(i + 1, NONE)]
  2169             | Us =>  (i + 1, NONE) ::
  2170               (map (pair (i + 1) o SOME) ((subsets 1 (length Us)) \\ [[], 1 upto (length Us)])))
  2171           Ts)
  2172       in
  2173         cprod (cprods (map (fn T => case strip_type T of
  2174           (Rs as _ :: _, Type ("bool", [])) => map SOME (all_smodes_of_typs Rs) | _ => [NONE]) Ts),
  2175            all_smodes_of_typs Us)
  2176       end
  2177     val all_modes = map (fn (s, T) => (s, modes_of_typ T)) preds
  2178   in (preds, nparams, all_vs, param_vs, extra_modes, clauses, all_modes) end;
  2179 
  2180 (** main function of predicate compiler **)
  2181 
  2182 fun add_equations_of steps prednames thy =
  2183   let
  2184     val _ = Output.tracing ("Starting predicate compiler for predicates " ^ commas prednames ^ "...")
  2185     val _ = Output.tracing (commas (map (Display.string_of_thm_global thy) (maps (intros_of thy) prednames)))
  2186     val (preds, nparams, all_vs, param_vs, extra_modes, clauses, all_modes) =
  2187       prepare_intrs thy prednames
  2188     val _ = Output.tracing "Infering modes..."
  2189     val moded_clauses = #infer_modes steps thy extra_modes all_modes param_vs clauses 
  2190     val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
  2191     val _ = print_modes modes
  2192     val _ = print_moded_clauses thy moded_clauses
  2193     val _ = Output.tracing "Defining executable functions..."
  2194     val thy' = fold (#create_definitions steps preds) modes thy
  2195       |> Theory.checkpoint
  2196     val _ = Output.tracing "Compiling equations..."
  2197     val compiled_terms =
  2198       (#compile_preds steps) thy' all_vs param_vs preds moded_clauses
  2199     val _ = print_compiled_terms thy' compiled_terms
  2200     val _ = Output.tracing "Proving equations..."
  2201     val result_thms = #prove steps thy' clauses preds (extra_modes @ modes)
  2202       moded_clauses compiled_terms
  2203     val qname = #qname steps
  2204     (* val attrib = gn thy => Attrib.attribute_i thy Code.add_eqn_attrib *)
  2205     val attrib = fn thy => Attrib.attribute_i thy (Attrib.internal (K (Thm.declaration_attribute
  2206       (fn thm => Context.mapping (Code.add_eqn thm) I))))
  2207     val thy'' = fold (fn (name, result_thms) => fn thy => snd (PureThy.add_thmss
  2208       [((Binding.qualify true (Long_Name.base_name name) (Binding.name qname), result_thms),
  2209         [attrib thy ])] thy))
  2210       (maps_modes result_thms) thy'
  2211       |> Theory.checkpoint
  2212   in
  2213     thy''
  2214   end
  2215 
  2216 fun extend' value_of edges_of key (G, visited) =
  2217   let
  2218     val (G', v) = case try (Graph.get_node G) key of
  2219         SOME v => (G, v)
  2220       | NONE => (Graph.new_node (key, value_of key) G, value_of key)
  2221     val (G'', visited') = fold (extend' value_of edges_of) (edges_of (key, v) \\ visited)
  2222       (G', key :: visited) 
  2223   in
  2224     (fold (Graph.add_edge o (pair key)) (edges_of (key, v)) G'', visited')
  2225   end;
  2226 
  2227 fun extend value_of edges_of key G = fst (extend' value_of edges_of key (G, [])) 
  2228   
  2229 fun gen_add_equations steps names thy =
  2230   let
  2231     val thy' = PredData.map (fold (extend (fetch_pred_data thy) (depending_preds_of thy)) names) thy
  2232       |> Theory.checkpoint;
  2233     fun strong_conn_of gr keys =
  2234       Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
  2235     val scc = strong_conn_of (PredData.get thy') names
  2236     val thy'' = fold_rev
  2237       (fn preds => fn thy =>
  2238         if #are_not_defined steps thy preds then add_equations_of steps preds thy else thy)
  2239       scc thy' |> Theory.checkpoint
  2240   in thy'' end
  2241 
  2242 (* different instantiantions of the predicate compiler *)
  2243 
  2244 val add_equations = gen_add_equations
  2245   {infer_modes = infer_modes,
  2246   create_definitions = create_definitions,
  2247   compile_preds = compile_preds PredicateCompFuns.compfuns mk_fun_of false,
  2248   prove = prove,
  2249   are_not_defined = fn thy => forall (null o modes_of thy),
  2250   qname = "equation"}
  2251 
  2252 val add_sizelim_equations = gen_add_equations
  2253   {infer_modes = infer_modes,
  2254   create_definitions = sizelim_create_definitions,
  2255   compile_preds = compile_preds PredicateCompFuns.compfuns mk_sizelim_fun_of true,
  2256   prove = prove_by_skip,
  2257   are_not_defined = fn thy => forall (null o sizelim_modes_of thy),
  2258   qname = "sizelim_equation"
  2259   }
  2260 
  2261 val add_quickcheck_equations = gen_add_equations
  2262   {infer_modes = infer_modes_with_generator,
  2263   create_definitions = rpred_create_definitions,
  2264   compile_preds = compile_preds RPredCompFuns.compfuns mk_generator_of true,
  2265   prove = prove_by_skip,
  2266   are_not_defined = fn thy => forall (null o rpred_modes_of thy),
  2267   qname = "rpred_equation"}
  2268 
  2269 (** user interface **)
  2270 
  2271 (* code_pred_intro attribute *)
  2272 
  2273 fun attrib f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
  2274 
  2275 val code_pred_intros_attrib = attrib add_intro;
  2276 
  2277 
  2278 (*FIXME
  2279 - Naming of auxiliary rules necessary?
  2280 - add default code equations P x y z = P_i_i_i x y z
  2281 *)
  2282 
  2283 val setup = PredData.put (Graph.empty) #>
  2284   Attrib.setup @{binding code_pred_intros} (Scan.succeed (attrib add_intro))
  2285     "adding alternative introduction rules for code generation of inductive predicates"
  2286 (*  Attrib.setup @{binding code_ind_cases} (Scan.succeed add_elim_attrib)
  2287     "adding alternative elimination rules for code generation of inductive predicates";
  2288     *)
  2289   (*FIXME name discrepancy in attribs and ML code*)
  2290   (*FIXME intros should be better named intro*)
  2291   (*FIXME why distinguished attribute for cases?*)
  2292 
  2293 (* TODO: make TheoryDataFun to GenericDataFun & remove duplication of local theory and theory *)
  2294 fun generic_code_pred prep_const rpred raw_const lthy =
  2295   let
  2296     val thy = ProofContext.theory_of lthy
  2297     val const = prep_const thy raw_const
  2298     val lthy' = LocalTheory.theory (PredData.map
  2299         (extend (fetch_pred_data thy) (depending_preds_of thy) const)) lthy
  2300       |> LocalTheory.checkpoint
  2301     val thy' = ProofContext.theory_of lthy'
  2302     val preds = Graph.all_preds (PredData.get thy') [const] |> filter_out (has_elim thy')
  2303     fun mk_cases const =
  2304       let
  2305         val nparams = nparams_of thy' const
  2306         val intros = intros_of thy' const
  2307       in mk_casesrule lthy' nparams intros end  
  2308     val cases_rules = map mk_cases preds
  2309     val cases =
  2310       map (fn case_rule => RuleCases.Case {fixes = [],
  2311         assumes = [("", Logic.strip_imp_prems case_rule)],
  2312         binds = [], cases = []}) cases_rules
  2313     val case_env = map2 (fn p => fn c => (Long_Name.base_name p, SOME c)) preds cases
  2314     val lthy'' = lthy'
  2315       |> fold Variable.auto_fixes cases_rules 
  2316       |> ProofContext.add_cases true case_env
  2317     fun after_qed thms goal_ctxt =
  2318       let
  2319         val global_thms = ProofContext.export goal_ctxt
  2320           (ProofContext.init (ProofContext.theory_of goal_ctxt)) (map the_single thms)
  2321       in
  2322         goal_ctxt |> LocalTheory.theory (fold set_elim global_thms #>
  2323           (if rpred then
  2324             (add_equations [const] #>
  2325              add_sizelim_equations [const] #> add_quickcheck_equations [const])
  2326         else add_equations [const]))
  2327       end  
  2328   in
  2329     Proof.theorem_i NONE after_qed (map (single o (rpair [])) cases_rules) lthy''
  2330   end;
  2331 
  2332 val code_pred = generic_code_pred (K I);
  2333 val code_pred_cmd = generic_code_pred Code.read_const
  2334 
  2335 (* transformation for code generation *)
  2336 
  2337 val eval_ref = Unsynchronized.ref (NONE : (unit -> term Predicate.pred) option);
  2338 
  2339 (*FIXME turn this into an LCF-guarded preprocessor for comprehensions*)
  2340 fun analyze_compr thy t_compr =
  2341   let
  2342     val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
  2343       | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term_global thy t_compr);
  2344     val (body, Ts, fp) = HOLogic.strip_psplits split;
  2345     val (pred as Const (name, T), all_args) = strip_comb body;
  2346     val (params, args) = chop (nparams_of thy name) all_args;
  2347     val user_mode = map_filter I (map_index
  2348       (fn (i, t) => case t of Bound j => if j < length Ts then NONE
  2349         else SOME (i+1) | _ => SOME (i+1)) args); (*FIXME dangling bounds should not occur*)
  2350     val user_mode' = map (rpair NONE) user_mode
  2351     val modes = filter (fn Mode (_, is, _) => is = user_mode')
  2352       (modes_of_term (all_modes_of thy) (list_comb (pred, params)));
  2353     val m = case modes
  2354      of [] => error ("No mode possible for comprehension "
  2355                 ^ Syntax.string_of_term_global thy t_compr)
  2356       | [m] => m
  2357       | m :: _ :: _ => (warning ("Multiple modes possible for comprehension "
  2358                 ^ Syntax.string_of_term_global thy t_compr); m);
  2359     val (inargs, outargs) = split_smode user_mode' args;
  2360     val t_pred = list_comb (compile_expr NONE NONE thy (m, list_comb (pred, params)), inargs);
  2361     val t_eval = if null outargs then t_pred else
  2362       let
  2363         val outargs_bounds = map (fn Bound i => i) outargs;
  2364         val outargsTs = map (nth Ts) outargs_bounds;
  2365         val T_pred = HOLogic.mk_tupleT outargsTs;
  2366         val T_compr = HOLogic.mk_ptupleT fp Ts;
  2367         val arrange_bounds = map_index I outargs_bounds
  2368           |> sort (prod_ord (K EQUAL) int_ord)
  2369           |> map fst;
  2370         val arrange = funpow (length outargs_bounds - 1) HOLogic.mk_split
  2371           (Term.list_abs (map (pair "") outargsTs,
  2372             HOLogic.mk_ptuple fp T_compr (map Bound arrange_bounds)))
  2373       in mk_map PredicateCompFuns.compfuns T_pred T_compr arrange t_pred end
  2374   in t_eval end;
  2375 
  2376 fun eval thy t_compr =
  2377   let
  2378     val t = analyze_compr thy t_compr;
  2379     val T = dest_predT PredicateCompFuns.compfuns (fastype_of t);
  2380     val t' = mk_map PredicateCompFuns.compfuns T HOLogic.termT (HOLogic.term_of_const T) t;
  2381   in (T, Code_ML.eval NONE ("Predicate_Compile_Core.eval_ref", eval_ref) Predicate.map thy t' []) end;
  2382 
  2383 fun values ctxt k t_compr =
  2384   let
  2385     val thy = ProofContext.theory_of ctxt;
  2386     val (T, t) = eval thy t_compr;
  2387     val setT = HOLogic.mk_setT T;
  2388     val (ts, _) = Predicate.yieldn k t;
  2389     val elemsT = HOLogic.mk_set T ts;
  2390   in if k = ~1 orelse length ts < k then elemsT
  2391     else Const (@{const_name Set.union}, setT --> setT --> setT) $ elemsT $ t_compr
  2392   end;
  2393   (*
  2394 fun random_values ctxt k t = 
  2395   let
  2396     val thy = ProofContext.theory_of ctxt
  2397     val _ = 
  2398   in
  2399   end;
  2400   *)
  2401 fun values_cmd modes k raw_t state =
  2402   let
  2403     val ctxt = Toplevel.context_of state;
  2404     val t = Syntax.read_term ctxt raw_t;
  2405     val t' = values ctxt k t;
  2406     val ty' = Term.type_of t';
  2407     val ctxt' = Variable.auto_fixes t' ctxt;
  2408     val p = PrintMode.with_modes modes (fn () =>
  2409       Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
  2410         Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
  2411   in Pretty.writeln p end;
  2412 
  2413 
  2414 local structure P = OuterParse in
  2415 
  2416 val opt_modes = Scan.optional (P.$$$ "(" |-- P.!!! (Scan.repeat1 P.xname --| P.$$$ ")")) [];
  2417 
  2418 val _ = OuterSyntax.improper_command "values" "enumerate and print comprehensions" OuterKeyword.diag
  2419   (opt_modes -- Scan.optional P.nat ~1 -- P.term
  2420     >> (fn ((modes, k), t) => Toplevel.no_timing o Toplevel.keep
  2421         (values_cmd modes k t)));
  2422 
  2423 end;
  2424 
  2425 end;