src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author bulwahn
Mon Mar 29 17:30:54 2010 +0200 (2010-03-29)
changeset 36037 b1b21a8f6362
parent 36035 d82682936c52
child 36038 385f706eff24
permissions -rw-r--r--
correcting alternative functions with tuples
     1 (*  Title:      HOL/Tools/Predicate_Compile/predicate_compile_core.ML
     2     Author:     Lukas Bulwahn, TU Muenchen
     3 
     4 A compiler from predicates specified by intro/elim rules to equations.
     5 *)
     6 
     7 signature PREDICATE_COMPILE_CORE =
     8 sig
     9   val setup : theory -> theory
    10   val code_pred : Predicate_Compile_Aux.options -> string -> Proof.context -> Proof.state
    11   val code_pred_cmd : Predicate_Compile_Aux.options -> string -> Proof.context -> Proof.state
    12   val values_cmd : string list -> Predicate_Compile_Aux.mode option list option
    13     -> ((string option * bool) * (Predicate_Compile_Aux.compilation * int list))
    14     -> int -> string -> Toplevel.state -> unit
    15   val register_predicate : (string * thm list * thm) -> theory -> theory
    16   val register_intros : string * thm list -> theory -> theory
    17   val is_registered : theory -> string -> bool
    18   val function_name_of : Predicate_Compile_Aux.compilation -> theory
    19     -> string -> Predicate_Compile_Aux.mode -> string
    20   val predfun_intro_of: Proof.context -> string -> Predicate_Compile_Aux.mode -> thm
    21   val predfun_elim_of: Proof.context -> string -> Predicate_Compile_Aux.mode -> thm
    22   val all_preds_of : theory -> string list
    23   val modes_of: Predicate_Compile_Aux.compilation
    24     -> theory -> string -> Predicate_Compile_Aux.mode list
    25   val all_modes_of : Predicate_Compile_Aux.compilation
    26     -> theory -> (string * Predicate_Compile_Aux.mode list) list
    27   val all_random_modes_of : theory -> (string * Predicate_Compile_Aux.mode list) list
    28   val intros_of : theory -> string -> thm list
    29   val add_intro : thm -> theory -> theory
    30   val set_elim : thm -> theory -> theory
    31   val register_alternative_function : string -> Predicate_Compile_Aux.mode -> string -> theory -> theory
    32   val alternative_function_of : theory -> string -> Predicate_Compile_Aux.mode -> string option
    33   val preprocess_intro : theory -> thm -> thm
    34   val print_stored_rules : theory -> unit
    35   val print_all_modes : Predicate_Compile_Aux.compilation -> theory -> unit
    36   val mk_casesrule : Proof.context -> term -> thm list -> term
    37   
    38   val eval_ref : (unit -> term Predicate.pred) option Unsynchronized.ref
    39   val random_eval_ref : (unit -> int * int -> term Predicate.pred * (int * int))
    40     option Unsynchronized.ref
    41   val dseq_eval_ref : (unit -> term DSequence.dseq) option Unsynchronized.ref
    42   val random_dseq_eval_ref : (unit -> int -> int -> int * int -> term DSequence.dseq * (int * int))
    43     option Unsynchronized.ref
    44   val new_random_dseq_eval_ref :
    45     (unit -> int -> int -> int * int -> int -> term Lazy_Sequence.lazy_sequence)
    46       option Unsynchronized.ref
    47   val new_random_dseq_stats_eval_ref :
    48     (unit -> int -> int -> int * int -> int -> (term * int) Lazy_Sequence.lazy_sequence)
    49       option Unsynchronized.ref
    50   val code_pred_intro_attrib : attribute
    51   
    52   (* used by Quickcheck_Generator *) 
    53   (* temporary for testing of the compilation *)
    54   
    55   datatype compilation_funs = CompilationFuns of {
    56     mk_predT : typ -> typ,
    57     dest_predT : typ -> typ,
    58     mk_bot : typ -> term,
    59     mk_single : term -> term,
    60     mk_bind : term * term -> term,
    61     mk_sup : term * term -> term,
    62     mk_if : term -> term,
    63     mk_not : term -> term,
    64     mk_map : typ -> typ -> term -> term -> term
    65   };
    66   
    67   val pred_compfuns : compilation_funs
    68   val randompred_compfuns : compilation_funs
    69   val new_randompred_compfuns : compilation_funs
    70   val add_equations : Predicate_Compile_Aux.options -> string list -> theory -> theory
    71   val add_depth_limited_random_equations : Predicate_Compile_Aux.options -> string list -> theory -> theory
    72   val add_random_dseq_equations : Predicate_Compile_Aux.options -> string list -> theory -> theory
    73   val add_new_random_dseq_equations : Predicate_Compile_Aux.options -> string list -> theory -> theory
    74   val mk_tracing : string -> term -> term
    75 end;
    76 
    77 structure Predicate_Compile_Core : PREDICATE_COMPILE_CORE =
    78 struct
    79 
    80 open Predicate_Compile_Aux;
    81 
    82 (** auxiliary **)
    83 
    84 (* debug stuff *)
    85 
    86 fun print_tac options s = 
    87   if show_proof_trace options then Tactical.print_tac s else Seq.single;
    88 
    89 fun assert b = if not b then raise Fail "Assertion failed" else warning "Assertion holds"
    90 
    91 datatype assertion = Max_number_of_subgoals of int
    92 fun assert_tac (Max_number_of_subgoals i) st =
    93   if (nprems_of st <= i) then Seq.single st
    94   else raise Fail ("assert_tac: Numbers of subgoals mismatch at goal state :"
    95     ^ "\n" ^ Pretty.string_of (Pretty.chunks
    96       (Goal_Display.pretty_goals_without_context (! Goal_Display.goals_limit) st)));
    97 
    98 (** fundamentals **)
    99 
   100 (* syntactic operations *)
   101 
   102 fun mk_eq (x, xs) =
   103   let fun mk_eqs _ [] = []
   104         | mk_eqs a (b::cs) =
   105             HOLogic.mk_eq (Free (a, fastype_of b), b) :: mk_eqs a cs
   106   in mk_eqs x xs end;
   107 
   108 fun mk_scomp (t, u) =
   109   let
   110     val T = fastype_of t
   111     val U = fastype_of u
   112     val [A] = binder_types T
   113     val D = body_type U                   
   114   in 
   115     Const (@{const_name "scomp"}, T --> U --> A --> D) $ t $ u
   116   end;
   117 
   118 fun dest_funT (Type ("fun",[S, T])) = (S, T)
   119   | dest_funT T = raise TYPE ("dest_funT", [T], [])
   120  
   121 fun mk_fun_comp (t, u) =
   122   let
   123     val (_, B) = dest_funT (fastype_of t)
   124     val (C, A) = dest_funT (fastype_of u)
   125   in
   126     Const(@{const_name "Fun.comp"}, (A --> B) --> (C --> A) --> C --> B) $ t $ u
   127   end;
   128 
   129 fun dest_randomT (Type ("fun", [@{typ Random.seed},
   130   Type ("*", [Type ("*", [T, @{typ "unit => Code_Evaluation.term"}]) ,@{typ Random.seed}])])) = T
   131   | dest_randomT T = raise TYPE ("dest_randomT", [T], [])
   132 
   133 fun mk_tracing s t =
   134   Const(@{const_name Code_Evaluation.tracing},
   135     @{typ String.literal} --> (fastype_of t) --> (fastype_of t)) $ (HOLogic.mk_literal s) $ t
   136 
   137 val strip_intro_concl = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of)
   138 
   139 (* derivation trees for modes of premises *)
   140 
   141 datatype mode_derivation = Mode_App of mode_derivation * mode_derivation | Context of mode
   142   | Mode_Pair of mode_derivation * mode_derivation | Term of mode
   143 
   144 fun string_of_derivation (Mode_App (m1, m2)) =
   145   "App (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
   146   | string_of_derivation (Mode_Pair (m1, m2)) =
   147   "Pair (" ^ string_of_derivation m1 ^ ", " ^ string_of_derivation m2 ^ ")"
   148   | string_of_derivation (Term m) = "Term (" ^ string_of_mode m ^ ")"
   149   | string_of_derivation (Context m) = "Context (" ^ string_of_mode m ^ ")"
   150 
   151 fun strip_mode_derivation deriv =
   152   let
   153     fun strip (Mode_App (deriv1, deriv2)) ds = strip deriv1 (deriv2 :: ds)
   154       | strip deriv ds = (deriv, ds)
   155   in
   156     strip deriv []
   157   end
   158 
   159 fun mode_of (Context m) = m
   160   | mode_of (Term m) = m
   161   | mode_of (Mode_App (d1, d2)) =
   162     (case mode_of d1 of Fun (m, m') =>
   163         (if eq_mode (m, mode_of d2) then m' else raise Fail "mode_of")
   164       | _ => raise Fail "mode_of2")
   165   | mode_of (Mode_Pair (d1, d2)) =
   166     Pair (mode_of d1, mode_of d2)
   167 
   168 fun head_mode_of deriv = mode_of (fst (strip_mode_derivation deriv))
   169 
   170 fun param_derivations_of deriv =
   171   let
   172     val (_, argument_derivs) = strip_mode_derivation deriv
   173     fun param_derivation (Mode_Pair (m1, m2)) =
   174         param_derivation m1 @ param_derivation m2
   175       | param_derivation (Term _) = []
   176       | param_derivation m = [m]
   177   in
   178     maps param_derivation argument_derivs
   179   end
   180 
   181 fun collect_context_modes (Mode_App (m1, m2)) =
   182       collect_context_modes m1 @ collect_context_modes m2
   183   | collect_context_modes (Mode_Pair (m1, m2)) =
   184       collect_context_modes m1 @ collect_context_modes m2
   185   | collect_context_modes (Context m) = [m]
   186   | collect_context_modes (Term _) = []
   187 
   188 (* representation of inferred clauses with modes *)
   189 
   190 type moded_clause = term list * (indprem * mode_derivation) list
   191 
   192 type 'a pred_mode_table = (string * ((bool * mode) * 'a) list) list
   193 
   194 (* book-keeping *)
   195 
   196 datatype predfun_data = PredfunData of {
   197   definition : thm,
   198   intro : thm,
   199   elim : thm,
   200   neg_intro : thm option
   201 };
   202 
   203 fun rep_predfun_data (PredfunData data) = data;
   204 
   205 fun mk_predfun_data (definition, ((intro, elim), neg_intro)) =
   206   PredfunData {definition = definition, intro = intro, elim = elim, neg_intro = neg_intro}
   207 
   208 datatype pred_data = PredData of {
   209   intros : thm list,
   210   elim : thm option,
   211   function_names : (compilation * (mode * string) list) list,
   212   predfun_data : (mode * predfun_data) list,
   213   needs_random : mode list
   214 };
   215 
   216 fun rep_pred_data (PredData data) = data;
   217 
   218 fun mk_pred_data ((intros, elim), (function_names, (predfun_data, needs_random))) =
   219   PredData {intros = intros, elim = elim,
   220     function_names = function_names, predfun_data = predfun_data, needs_random = needs_random}
   221 
   222 fun map_pred_data f (PredData {intros, elim, function_names, predfun_data, needs_random}) =
   223   mk_pred_data (f ((intros, elim), (function_names, (predfun_data, needs_random))))
   224 
   225 fun eq_option eq (NONE, NONE) = true
   226   | eq_option eq (SOME x, SOME y) = eq (x, y)
   227   | eq_option eq _ = false
   228 
   229 fun eq_pred_data (PredData d1, PredData d2) = 
   230   eq_list Thm.eq_thm (#intros d1, #intros d2) andalso
   231   eq_option Thm.eq_thm (#elim d1, #elim d2)
   232 
   233 structure PredData = Theory_Data
   234 (
   235   type T = pred_data Graph.T;
   236   val empty = Graph.empty;
   237   val extend = I;
   238   val merge = Graph.merge eq_pred_data;
   239 );
   240 
   241 (* queries *)
   242 
   243 fun lookup_pred_data thy name =
   244   Option.map rep_pred_data (try (Graph.get_node (PredData.get thy)) name)
   245 
   246 fun the_pred_data thy name = case lookup_pred_data thy name
   247  of NONE => error ("No such predicate " ^ quote name)  
   248   | SOME data => data;
   249 
   250 val is_registered = is_some oo lookup_pred_data
   251 
   252 val all_preds_of = Graph.keys o PredData.get
   253 
   254 fun intros_of thy = map (Thm.transfer thy) o #intros o the_pred_data thy
   255 
   256 fun the_elim_of thy name = case #elim (the_pred_data thy name)
   257  of NONE => error ("No elimination rule for predicate " ^ quote name)
   258   | SOME thm => Thm.transfer thy thm
   259   
   260 val has_elim = is_some o #elim oo the_pred_data;
   261 
   262 fun function_names_of compilation thy name =
   263   case AList.lookup (op =) (#function_names (the_pred_data thy name)) compilation of
   264     NONE => error ("No " ^ string_of_compilation compilation
   265       ^ "functions defined for predicate " ^ quote name)
   266   | SOME fun_names => fun_names
   267 
   268 fun function_name_of compilation thy name mode =
   269   case AList.lookup eq_mode
   270     (function_names_of compilation thy name) mode of
   271     NONE => error ("No " ^ string_of_compilation compilation
   272       ^ " function defined for mode " ^ string_of_mode mode ^ " of predicate " ^ quote name)
   273   | SOME function_name => function_name
   274 
   275 fun modes_of compilation thy name = map fst (function_names_of compilation thy name)
   276 
   277 fun all_modes_of compilation thy =
   278   map_filter (fn name => Option.map (pair name) (try (modes_of compilation thy) name))
   279     (all_preds_of thy)
   280 
   281 val all_random_modes_of = all_modes_of Random
   282 
   283 fun defined_functions compilation thy name =
   284   AList.defined (op =) (#function_names (the_pred_data thy name)) compilation
   285 
   286 fun lookup_predfun_data thy name mode =
   287   Option.map rep_predfun_data
   288     (AList.lookup (op =) (#predfun_data (the_pred_data thy name)) mode)
   289 
   290 fun the_predfun_data thy name mode =
   291   case lookup_predfun_data thy name mode of
   292     NONE => error ("No function defined for mode " ^ string_of_mode mode ^
   293       " of predicate " ^ name)
   294   | SOME data => data;
   295 
   296 val predfun_definition_of = #definition ooo the_predfun_data o ProofContext.theory_of
   297 
   298 val predfun_intro_of = #intro ooo the_predfun_data o ProofContext.theory_of
   299 
   300 val predfun_elim_of = #elim ooo the_predfun_data o ProofContext.theory_of
   301 
   302 val predfun_neg_intro_of = #neg_intro ooo the_predfun_data o ProofContext.theory_of
   303 
   304 (* diagnostic display functions *)
   305 
   306 fun print_modes options thy modes =
   307   if show_modes options then
   308     tracing ("Inferred modes:\n" ^
   309       cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
   310         (fn (p, m) => string_of_mode m ^ (if p then "pos" else "neg")) ms)) modes))
   311   else ()
   312 
   313 fun print_pred_mode_table string_of_entry thy pred_mode_table =
   314   let
   315     fun print_mode pred ((pol, mode), entry) =  "mode : " ^ string_of_mode mode
   316       ^ string_of_entry pred mode entry
   317     fun print_pred (pred, modes) =
   318       "predicate " ^ pred ^ ": " ^ cat_lines (map (print_mode pred) modes)
   319     val _ = tracing (cat_lines (map print_pred pred_mode_table))
   320   in () end;
   321 
   322 fun string_of_prem thy (Prem t) =
   323     (Syntax.string_of_term_global thy t) ^ "(premise)"
   324   | string_of_prem thy (Negprem t) =
   325     (Syntax.string_of_term_global thy (HOLogic.mk_not t)) ^ "(negative premise)"
   326   | string_of_prem thy (Sidecond t) =
   327     (Syntax.string_of_term_global thy t) ^ "(sidecondition)"
   328   | string_of_prem thy _ = raise Fail "string_of_prem: unexpected input"
   329 
   330 fun string_of_clause thy pred (ts, prems) =
   331   (space_implode " --> "
   332   (map (string_of_prem thy) prems)) ^ " --> " ^ pred ^ " "
   333    ^ (space_implode " " (map (Syntax.string_of_term_global thy) ts))
   334 
   335 fun print_compiled_terms options thy =
   336   if show_compilation options then
   337     print_pred_mode_table (fn _ => fn _ => Syntax.string_of_term_global thy) thy
   338   else K ()
   339 
   340 fun print_stored_rules thy =
   341   let
   342     val preds = (Graph.keys o PredData.get) thy
   343     fun print pred () = let
   344       val _ = writeln ("predicate: " ^ pred)
   345       val _ = writeln ("introrules: ")
   346       val _ = fold (fn thm => fn u => writeln (Display.string_of_thm_global thy thm))
   347         (rev (intros_of thy pred)) ()
   348     in
   349       if (has_elim thy pred) then
   350         writeln ("elimrule: " ^ Display.string_of_thm_global thy (the_elim_of thy pred))
   351       else
   352         writeln ("no elimrule defined")
   353     end
   354   in
   355     fold print preds ()
   356   end;
   357 
   358 fun print_all_modes compilation thy =
   359   let
   360     val _ = writeln ("Inferred modes:")
   361     fun print (pred, modes) u =
   362       let
   363         val _ = writeln ("predicate: " ^ pred)
   364         val _ = writeln ("modes: " ^ (commas (map string_of_mode modes)))
   365       in u end
   366   in
   367     fold print (all_modes_of compilation thy) ()
   368   end
   369 
   370 (* validity checks *)
   371 (* EXPECTED MODE and PROPOSED_MODE are largely the same; define a clear semantics for those! *)
   372 
   373 fun check_expected_modes preds options modes =
   374   case expected_modes options of
   375     SOME (s, ms) => (case AList.lookup (op =) modes s of
   376       SOME modes =>
   377         let
   378           val modes' = map snd modes
   379         in
   380           if not (eq_set eq_mode (ms, modes')) then
   381             error ("expected modes were not inferred:\n"
   382             ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
   383             ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms))
   384           else ()
   385         end
   386       | NONE => ())
   387   | NONE => ()
   388 
   389 fun check_proposed_modes preds options modes extra_modes errors =
   390   case proposed_modes options of
   391     SOME (s, ms) => (case AList.lookup (op =) modes s of
   392       SOME inferred_ms =>
   393         let
   394           val preds_without_modes = map fst (filter (null o snd) (modes @ extra_modes))
   395           val modes' = map snd inferred_ms
   396         in
   397           if not (eq_set eq_mode (ms, modes')) then
   398             error ("expected modes were not inferred:\n"
   399             ^ "  inferred modes for " ^ s ^ ": " ^ commas (map string_of_mode modes')  ^ "\n"
   400             ^ "  expected modes for " ^ s ^ ": " ^ commas (map string_of_mode ms) ^ "\n"
   401             ^ "For the following clauses, the following modes could not be inferred: " ^ "\n"
   402             ^ cat_lines errors ^
   403             (if not (null preds_without_modes) then
   404               "\n" ^ "No mode inferred for the predicates " ^ commas preds_without_modes
   405             else ""))
   406           else ()
   407         end
   408       | NONE => ())
   409   | NONE => ()
   410 
   411 (* importing introduction rules *)
   412 
   413 fun unify_consts thy cs intr_ts =
   414   (let
   415      val add_term_consts_2 = fold_aterms (fn Const c => insert (op =) c | _ => I);
   416      fun varify (t, (i, ts)) =
   417        let val t' = map_types (Logic.incr_tvar (i + 1)) (#2 (Type.varify_global [] t))
   418        in (maxidx_of_term t', t'::ts) end;
   419      val (i, cs') = List.foldr varify (~1, []) cs;
   420      val (i', intr_ts') = List.foldr varify (i, []) intr_ts;
   421      val rec_consts = fold add_term_consts_2 cs' [];
   422      val intr_consts = fold add_term_consts_2 intr_ts' [];
   423      fun unify (cname, cT) =
   424        let val consts = map snd (filter (fn c => fst c = cname) intr_consts)
   425        in fold (Sign.typ_unify thy) ((replicate (length consts) cT) ~~ consts) end;
   426      val (env, _) = fold unify rec_consts (Vartab.empty, i');
   427      val subst = map_types (Envir.norm_type env)
   428    in (map subst cs', map subst intr_ts')
   429    end) handle Type.TUNIFY =>
   430      (warning "Occurrences of recursive constant have non-unifiable types"; (cs, intr_ts));
   431 
   432 fun import_intros inp_pred [] ctxt =
   433   let
   434     val ([outp_pred], ctxt') = Variable.import_terms true [inp_pred] ctxt
   435     val T = fastype_of outp_pred
   436     (* TODO: put in a function for this next line! *)
   437     val paramTs = ho_argsT_of (hd (all_modes_of_typ T)) (binder_types T)
   438     val (param_names, ctxt'') = Variable.variant_fixes
   439       (map (fn i => "p" ^ (string_of_int i)) (1 upto (length paramTs))) ctxt'
   440     val params = map2 (curry Free) param_names paramTs
   441   in
   442     (((outp_pred, params), []), ctxt')
   443   end
   444   | import_intros inp_pred (th :: ths) ctxt =
   445     let
   446       val ((_, [th']), ctxt') = Variable.import true [th] ctxt
   447       val thy = ProofContext.theory_of ctxt'
   448       val (pred, args) = strip_intro_concl th'
   449       val T = fastype_of pred
   450       val ho_args = ho_args_of (hd (all_modes_of_typ T)) args
   451       fun subst_of (pred', pred) =
   452         let
   453           val subst = Sign.typ_match thy (fastype_of pred', fastype_of pred) Vartab.empty
   454         in map (fn (indexname, (s, T)) => ((indexname, s), T)) (Vartab.dest subst) end
   455       fun instantiate_typ th =
   456         let
   457           val (pred', _) = strip_intro_concl th
   458           val _ = if not (fst (dest_Const pred) = fst (dest_Const pred')) then
   459             raise Fail "Trying to instantiate another predicate" else ()
   460         in Thm.certify_instantiate (subst_of (pred', pred), []) th end;
   461       fun instantiate_ho_args th =
   462         let
   463           val (_, args') = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl o prop_of) th
   464           val ho_args' = map dest_Var (ho_args_of (hd (all_modes_of_typ T)) args')
   465         in Thm.certify_instantiate ([], ho_args' ~~ ho_args) th end
   466       val outp_pred =
   467         Term_Subst.instantiate (subst_of (inp_pred, pred), []) inp_pred
   468       val ((_, ths'), ctxt1) =
   469         Variable.import false (map (instantiate_typ #> instantiate_ho_args) ths) ctxt'
   470     in
   471       (((outp_pred, ho_args), th' :: ths'), ctxt1)
   472     end
   473 
   474 (* generation of case rules from user-given introduction rules *)
   475 
   476 fun mk_args2 (Type ("*", [T1, T2])) st =
   477     let
   478       val (t1, st') = mk_args2 T1 st
   479       val (t2, st'') = mk_args2 T2 st'
   480     in
   481       (HOLogic.mk_prod (t1, t2), st'')
   482     end
   483   (*| mk_args2 (T as Type ("fun", _)) (params, ctxt) = 
   484     let
   485       val (S, U) = strip_type T
   486     in
   487       if U = HOLogic.boolT then
   488         (hd params, (tl params, ctxt))
   489       else
   490         let
   491           val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
   492         in
   493           (Free (x, T), (params, ctxt'))
   494         end
   495     end*)
   496   | mk_args2 T (params, ctxt) =
   497     let
   498       val ([x], ctxt') = Variable.variant_fixes ["x"] ctxt
   499     in
   500       (Free (x, T), (params, ctxt'))
   501     end
   502 
   503 fun mk_casesrule ctxt pred introrules =
   504   let
   505     (* TODO: can be simplified if parameters are not treated specially ? *)
   506     val (((pred, params), intros_th), ctxt1) = import_intros pred introrules ctxt
   507     (* TODO: distinct required ? -- test case with more than one parameter! *)
   508     val params = distinct (op aconv) params
   509     val intros = map prop_of intros_th
   510     val ([propname], ctxt2) = Variable.variant_fixes ["thesis"] ctxt1
   511     val prop = HOLogic.mk_Trueprop (Free (propname, HOLogic.boolT))
   512     val argsT = binder_types (fastype_of pred)
   513     (* TODO: can be simplified if parameters are not treated specially ? <-- see uncommented code! *)
   514     val (argvs, _) = fold_map mk_args2 argsT (params, ctxt2)
   515     fun mk_case intro =
   516       let
   517         val (_, args) = (strip_comb o HOLogic.dest_Trueprop o Logic.strip_imp_concl) intro
   518         val prems = Logic.strip_imp_prems intro
   519         val eqprems =
   520           map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) argvs args
   521         val frees = map Free (fold Term.add_frees (args @ prems) [])
   522       in fold Logic.all frees (Logic.list_implies (eqprems @ prems, prop)) end
   523     val assm = HOLogic.mk_Trueprop (list_comb (pred, argvs))
   524     val cases = map mk_case intros
   525   in Logic.list_implies (assm :: cases, prop) end;
   526 
   527 fun dest_conjunct_prem th =
   528   case HOLogic.dest_Trueprop (prop_of th) of
   529     (Const ("op &", _) $ t $ t') =>
   530       dest_conjunct_prem (th RS @{thm conjunct1})
   531         @ dest_conjunct_prem (th RS @{thm conjunct2})
   532     | _ => [th]
   533 
   534 fun prove_casesrule ctxt (pred, (pre_cases_rule, nparams)) cases_rule =
   535   let
   536     val thy = ProofContext.theory_of ctxt
   537     val nargs = length (binder_types (fastype_of pred))
   538     fun PEEK f dependent_tactic st = dependent_tactic (f st) st
   539     fun meta_eq_of th = th RS @{thm eq_reflection}
   540     val tuple_rew_rules = map meta_eq_of [@{thm fst_conv}, @{thm snd_conv}, @{thm Pair_eq}]
   541     fun instantiate i n {context = ctxt, params = p, prems = prems,
   542       asms = a, concl = cl, schematics = s}  =
   543       let
   544         val (cases, (eqs, prems)) = apsnd (chop (nargs - nparams)) (chop n prems)
   545         val case_th = MetaSimplifier.simplify true
   546         (@{thm Predicate.eq_is_eq} :: map meta_eq_of eqs)
   547           (nth cases (i - 1))
   548         val prems' = maps (dest_conjunct_prem o MetaSimplifier.simplify true tuple_rew_rules) prems
   549         val pats = map (swap o HOLogic.dest_eq o HOLogic.dest_Trueprop) (take nargs (prems_of case_th))
   550         val (_, tenv) = fold (Pattern.match thy) pats (Vartab.empty, Vartab.empty)
   551         fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t)
   552         val inst = map (pairself (cterm_of thy) o term_pair_of) (Vartab.dest tenv)
   553         val thesis = Thm.instantiate ([], inst) case_th OF (replicate nargs @{thm refl}) OF prems'
   554       in
   555         (rtac thesis 1)
   556       end
   557     val tac =
   558       etac pre_cases_rule 1
   559       THEN
   560       (PEEK nprems_of
   561         (fn n =>
   562           ALLGOALS (fn i =>
   563             MetaSimplifier.rewrite_goal_tac [@{thm split_paired_all}] i
   564             THEN (SUBPROOF (instantiate i n) ctxt i))))
   565   in
   566     Goal.prove ctxt (Term.add_free_names cases_rule []) [] cases_rule (fn _ => tac)
   567   end
   568 
   569 (** preprocessing rules **)
   570 
   571 fun imp_prems_conv cv ct =
   572   case Thm.term_of ct of
   573     Const ("==>", _) $ _ $ _ => Conv.combination_conv (Conv.arg_conv cv) (imp_prems_conv cv) ct
   574   | _ => Conv.all_conv ct
   575 
   576 fun Trueprop_conv cv ct =
   577   case Thm.term_of ct of
   578     Const ("Trueprop", _) $ _ => Conv.arg_conv cv ct  
   579   | _ => raise Fail "Trueprop_conv"
   580 
   581 fun preprocess_intro thy rule =
   582   Conv.fconv_rule
   583     (imp_prems_conv
   584       (Trueprop_conv (Conv.try_conv (Conv.rewr_conv (Thm.symmetric @{thm Predicate.eq_is_eq})))))
   585     (Thm.transfer thy rule)
   586 
   587 fun preprocess_elim thy elimrule =
   588   let
   589     fun replace_eqs (Const ("Trueprop", _) $ (Const ("op =", T) $ lhs $ rhs)) =
   590        HOLogic.mk_Trueprop (Const (@{const_name Predicate.eq}, T) $ lhs $ rhs)
   591      | replace_eqs t = t
   592     val ctxt = ProofContext.init thy
   593     val ((_, [elimrule]), ctxt') = Variable.import false [elimrule] ctxt
   594     val prems = Thm.prems_of elimrule
   595     val nargs = length (snd (strip_comb (HOLogic.dest_Trueprop (hd prems))))
   596     fun preprocess_case t =
   597       let
   598        val params = Logic.strip_params t
   599        val (assums1, assums2) = chop nargs (Logic.strip_assums_hyp t)
   600        val assums_hyp' = assums1 @ (map replace_eqs assums2)
   601       in
   602        list_all (params, Logic.list_implies (assums_hyp', Logic.strip_assums_concl t))
   603       end
   604     val cases' = map preprocess_case (tl prems)
   605     val elimrule' = Logic.list_implies ((hd prems) :: cases', Thm.concl_of elimrule)
   606     val bigeq = (Thm.symmetric (Conv.implies_concl_conv
   607       (MetaSimplifier.rewrite true [@{thm Predicate.eq_is_eq}])
   608         (cterm_of thy elimrule')))
   609     val tac = (fn _ => Skip_Proof.cheat_tac thy)
   610     val eq = Goal.prove ctxt' [] [] (Logic.mk_equals ((Thm.prop_of elimrule), elimrule')) tac
   611   in
   612     Thm.equal_elim eq elimrule |> singleton (Variable.export ctxt' ctxt)
   613   end;
   614 
   615 fun expand_tuples_elim th = th
   616 
   617 val no_compilation = ([], ([], []))
   618 
   619 fun fetch_pred_data thy name =
   620   case try (Inductive.the_inductive (ProofContext.init thy)) name of
   621     SOME (info as (_, result)) => 
   622       let
   623         fun is_intro_of intro =
   624           let
   625             val (const, _) = strip_comb (HOLogic.dest_Trueprop (concl_of intro))
   626           in (fst (dest_Const const) = name) end;      
   627         val intros =
   628           (map (expand_tuples thy #> preprocess_intro thy) (filter is_intro_of (#intrs result)))
   629         val index = find_index (fn s => s = name) (#names (fst info))
   630         val pre_elim = nth (#elims result) index
   631         val pred = nth (#preds result) index
   632         val nparams = length (Inductive.params_of (#raw_induct result))
   633         val ctxt = ProofContext.init thy
   634         val elim_t = mk_casesrule ctxt pred intros
   635         val elim =
   636           prove_casesrule ctxt (pred, (pre_elim, nparams)) elim_t
   637       in
   638         mk_pred_data ((intros, SOME elim), no_compilation)
   639       end
   640   | NONE => error ("No such predicate: " ^ quote name)
   641 
   642 fun add_predfun_data name mode data =
   643   let
   644     val add = (apsnd o apsnd o apfst) (cons (mode, mk_predfun_data data))
   645   in PredData.map (Graph.map_node name (map_pred_data add)) end
   646 
   647 fun is_inductive_predicate thy name =
   648   is_some (try (Inductive.the_inductive (ProofContext.init thy)) name)
   649 
   650 fun depending_preds_of thy (key, value) =
   651   let
   652     val intros = (#intros o rep_pred_data) value
   653   in
   654     fold Term.add_const_names (map Thm.prop_of intros) []
   655       |> filter (fn c => (not (c = key)) andalso
   656         (is_inductive_predicate thy c orelse is_registered thy c))
   657   end;
   658 
   659 fun add_intro thm thy =
   660   let
   661     val (name, T) = dest_Const (fst (strip_intro_concl thm))
   662     fun cons_intro gr =
   663      case try (Graph.get_node gr) name of
   664        SOME pred_data => Graph.map_node name (map_pred_data
   665          (apfst (fn (intros, elim) => (intros @ [thm], elim)))) gr
   666      | NONE => Graph.new_node (name, mk_pred_data (([thm], NONE), no_compilation)) gr
   667   in PredData.map cons_intro thy end
   668 
   669 fun set_elim thm =
   670   let
   671     val (name, _) = dest_Const (fst 
   672       (strip_comb (HOLogic.dest_Trueprop (hd (prems_of thm)))))
   673     fun set (intros, _) = (intros, SOME thm)
   674   in PredData.map (Graph.map_node name (map_pred_data (apfst set))) end
   675 
   676 fun register_predicate (constname, pre_intros, pre_elim) thy =
   677   let
   678     val intros = map (preprocess_intro thy) pre_intros
   679     val elim = preprocess_elim thy pre_elim
   680   in
   681     if not (member (op =) (Graph.keys (PredData.get thy)) constname) then
   682       PredData.map
   683         (Graph.new_node (constname,
   684           mk_pred_data ((intros, SOME elim), no_compilation))) thy
   685     else thy
   686   end
   687 
   688 fun register_intros (constname, pre_intros) thy =
   689   let
   690     val T = Sign.the_const_type thy constname
   691     fun constname_of_intro intr = fst (dest_Const (fst (strip_intro_concl intr)))
   692     val _ = if not (forall (fn intr => constname_of_intro intr = constname) pre_intros) then
   693       error ("register_intros: Introduction rules of different constants are used\n" ^
   694         "expected rules for " ^ constname ^ ", but received rules for " ^
   695           commas (map constname_of_intro pre_intros))
   696       else ()
   697     val pred = Const (constname, T)
   698     val pre_elim = 
   699       (Drule.export_without_context o Skip_Proof.make_thm thy)
   700       (mk_casesrule (ProofContext.init thy) pred pre_intros)
   701   in register_predicate (constname, pre_intros, pre_elim) thy end
   702 
   703 fun defined_function_of compilation pred =
   704   let
   705     val set = (apsnd o apfst) (cons (compilation, []))
   706   in
   707     PredData.map (Graph.map_node pred (map_pred_data set))
   708   end
   709 
   710 fun set_function_name compilation pred mode name =
   711   let
   712     val set = (apsnd o apfst)
   713       (AList.map_default (op =) (compilation, [(mode, name)]) (cons (mode, name)))
   714   in
   715     PredData.map (Graph.map_node pred (map_pred_data set))
   716   end
   717 
   718 fun set_needs_random name modes =
   719   let
   720     val set = (apsnd o apsnd o apsnd) (K modes)
   721   in
   722     PredData.map (Graph.map_node name (map_pred_data set))
   723   end
   724 
   725 (* registration of alternative function names *)
   726 
   727 structure Alt_Names_Data = Theory_Data
   728 (
   729   type T = (mode * string) list Symtab.table;
   730   val empty = Symtab.empty;
   731   val extend = I;
   732   val merge = Symtab.merge (op =);
   733 );
   734 
   735 fun register_alternative_function pred_name mode fun_name =
   736   Alt_Names_Data.map (Symtab.insert_list (op =) (pred_name, (mode, fun_name)))
   737 
   738 fun alternative_function_of thy pred_name mode =
   739   AList.lookup eq_mode (Symtab.lookup_list (Alt_Names_Data.get thy) pred_name) mode
   740 
   741 (* datastructures and setup for generic compilation *)
   742 
   743 datatype compilation_funs = CompilationFuns of {
   744   mk_predT : typ -> typ,
   745   dest_predT : typ -> typ,
   746   mk_bot : typ -> term,
   747   mk_single : term -> term,
   748   mk_bind : term * term -> term,
   749   mk_sup : term * term -> term,
   750   mk_if : term -> term,
   751   mk_not : term -> term,
   752   mk_map : typ -> typ -> term -> term -> term
   753 };
   754 
   755 fun mk_predT (CompilationFuns funs) = #mk_predT funs
   756 fun dest_predT (CompilationFuns funs) = #dest_predT funs
   757 fun mk_bot (CompilationFuns funs) = #mk_bot funs
   758 fun mk_single (CompilationFuns funs) = #mk_single funs
   759 fun mk_bind (CompilationFuns funs) = #mk_bind funs
   760 fun mk_sup (CompilationFuns funs) = #mk_sup funs
   761 fun mk_if (CompilationFuns funs) = #mk_if funs
   762 fun mk_not (CompilationFuns funs) = #mk_not funs
   763 fun mk_map (CompilationFuns funs) = #mk_map funs
   764 
   765 structure PredicateCompFuns =
   766 struct
   767 
   768 fun mk_predT T = Type (@{type_name Predicate.pred}, [T])
   769 
   770 fun dest_predT (Type (@{type_name Predicate.pred}, [T])) = T
   771   | dest_predT T = raise TYPE ("dest_predT", [T], []);
   772 
   773 fun mk_bot T = Const (@{const_name Orderings.bot}, mk_predT T);
   774 
   775 fun mk_single t =
   776   let val T = fastype_of t
   777   in Const(@{const_name Predicate.single}, T --> mk_predT T) $ t end;
   778 
   779 fun mk_bind (x, f) =
   780   let val T as Type ("fun", [_, U]) = fastype_of f
   781   in
   782     Const (@{const_name Predicate.bind}, fastype_of x --> T --> U) $ x $ f
   783   end;
   784 
   785 val mk_sup = HOLogic.mk_binop @{const_name sup};
   786 
   787 fun mk_if cond = Const (@{const_name Predicate.if_pred},
   788   HOLogic.boolT --> mk_predT HOLogic.unitT) $ cond;
   789 
   790 fun mk_not t =
   791   let
   792     val T = mk_predT HOLogic.unitT
   793   in Const (@{const_name Predicate.not_pred}, T --> T) $ t end
   794 
   795 fun mk_Enum f =
   796   let val T as Type ("fun", [T', _]) = fastype_of f
   797   in
   798     Const (@{const_name Predicate.Pred}, T --> mk_predT T') $ f    
   799   end;
   800 
   801 fun mk_Eval (f, x) =
   802   let
   803     val T = fastype_of x
   804   in
   805     Const (@{const_name Predicate.eval}, mk_predT T --> T --> HOLogic.boolT) $ f $ x
   806   end;
   807 
   808 fun dest_Eval (Const (@{const_name Predicate.eval}, _) $ f $ x) = (f, x)
   809 
   810 fun mk_map T1 T2 tf tp = Const (@{const_name Predicate.map},
   811   (T1 --> T2) --> mk_predT T1 --> mk_predT T2) $ tf $ tp;
   812 
   813 val compfuns = CompilationFuns {mk_predT = mk_predT, dest_predT = dest_predT, mk_bot = mk_bot,
   814   mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if, mk_not = mk_not,
   815   mk_map = mk_map};
   816 
   817 end;
   818 
   819 structure RandomPredCompFuns =
   820 struct
   821 
   822 fun mk_randompredT T =
   823   @{typ Random.seed} --> HOLogic.mk_prodT (PredicateCompFuns.mk_predT T, @{typ Random.seed})
   824 
   825 fun dest_randompredT (Type ("fun", [@{typ Random.seed}, Type (@{type_name "*"},
   826   [Type (@{type_name "Predicate.pred"}, [T]), @{typ Random.seed}])])) = T
   827   | dest_randompredT T = raise TYPE ("dest_randompredT", [T], []);
   828 
   829 fun mk_bot T = Const(@{const_name Quickcheck.empty}, mk_randompredT T)
   830 
   831 fun mk_single t =
   832   let               
   833     val T = fastype_of t
   834   in
   835     Const (@{const_name Quickcheck.single}, T --> mk_randompredT T) $ t
   836   end;
   837 
   838 fun mk_bind (x, f) =
   839   let
   840     val T as (Type ("fun", [_, U])) = fastype_of f
   841   in
   842     Const (@{const_name Quickcheck.bind}, fastype_of x --> T --> U) $ x $ f
   843   end
   844 
   845 val mk_sup = HOLogic.mk_binop @{const_name Quickcheck.union}
   846 
   847 fun mk_if cond = Const (@{const_name Quickcheck.if_randompred},
   848   HOLogic.boolT --> mk_randompredT HOLogic.unitT) $ cond;
   849 
   850 fun mk_not t =
   851   let
   852     val T = mk_randompredT HOLogic.unitT
   853   in Const (@{const_name Quickcheck.not_randompred}, T --> T) $ t end
   854 
   855 fun mk_map T1 T2 tf tp = Const (@{const_name Quickcheck.map},
   856   (T1 --> T2) --> mk_randompredT T1 --> mk_randompredT T2) $ tf $ tp
   857 
   858 val compfuns = CompilationFuns {mk_predT = mk_randompredT, dest_predT = dest_randompredT,
   859     mk_bot = mk_bot, mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if,
   860     mk_not = mk_not, mk_map = mk_map};
   861 
   862 end;
   863 
   864 structure DSequence_CompFuns =
   865 struct
   866 
   867 fun mk_dseqT T = Type ("fun", [@{typ code_numeral}, Type ("fun", [@{typ bool},
   868   Type (@{type_name Option.option}, [Type  (@{type_name Lazy_Sequence.lazy_sequence}, [T])])])])
   869 
   870 fun dest_dseqT (Type ("fun", [@{typ code_numeral}, Type ("fun", [@{typ bool},
   871   Type (@{type_name Option.option}, [Type (@{type_name Lazy_Sequence.lazy_sequence}, [T])])])])) = T
   872   | dest_dseqT T = raise TYPE ("dest_dseqT", [T], []);
   873 
   874 fun mk_bot T = Const (@{const_name DSequence.empty}, mk_dseqT T);
   875 
   876 fun mk_single t =
   877   let val T = fastype_of t
   878   in Const(@{const_name DSequence.single}, T --> mk_dseqT T) $ t end;
   879 
   880 fun mk_bind (x, f) =
   881   let val T as Type ("fun", [_, U]) = fastype_of f
   882   in
   883     Const (@{const_name DSequence.bind}, fastype_of x --> T --> U) $ x $ f
   884   end;
   885 
   886 val mk_sup = HOLogic.mk_binop @{const_name DSequence.union};
   887 
   888 fun mk_if cond = Const (@{const_name DSequence.if_seq},
   889   HOLogic.boolT --> mk_dseqT HOLogic.unitT) $ cond;
   890 
   891 fun mk_not t = let val T = mk_dseqT HOLogic.unitT
   892   in Const (@{const_name DSequence.not_seq}, T --> T) $ t end
   893 
   894 fun mk_map T1 T2 tf tp = Const (@{const_name DSequence.map},
   895   (T1 --> T2) --> mk_dseqT T1 --> mk_dseqT T2) $ tf $ tp
   896 
   897 val compfuns = CompilationFuns {mk_predT = mk_dseqT, dest_predT = dest_dseqT,
   898     mk_bot = mk_bot, mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if,
   899     mk_not = mk_not, mk_map = mk_map}
   900 
   901 end;
   902 
   903 structure New_Pos_Random_Sequence_CompFuns =
   904 struct
   905 
   906 fun mk_pos_random_dseqT T =
   907   @{typ code_numeral} --> @{typ code_numeral} --> @{typ Random.seed} -->
   908     @{typ code_numeral} --> Type (@{type_name Lazy_Sequence.lazy_sequence}, [T])
   909 
   910 fun dest_pos_random_dseqT (Type ("fun", [@{typ code_numeral}, Type ("fun", [@{typ code_numeral},
   911     Type ("fun", [@{typ Random.seed}, Type ("fun", [@{typ code_numeral},
   912     Type (@{type_name Lazy_Sequence.lazy_sequence}, [T])])])])])) = T
   913   | dest_pos_random_dseqT T = raise TYPE ("dest_random_dseqT", [T], []);
   914 
   915 fun mk_bot T = Const (@{const_name New_Random_Sequence.pos_empty}, mk_pos_random_dseqT T);
   916 
   917 fun mk_single t =
   918   let
   919     val T = fastype_of t
   920   in Const(@{const_name New_Random_Sequence.pos_single}, T --> mk_pos_random_dseqT T) $ t end;
   921 
   922 fun mk_bind (x, f) =
   923   let
   924     val T as Type ("fun", [_, U]) = fastype_of f
   925   in
   926     Const (@{const_name New_Random_Sequence.pos_bind}, fastype_of x --> T --> U) $ x $ f
   927   end;
   928 
   929 val mk_sup = HOLogic.mk_binop @{const_name New_Random_Sequence.pos_union};
   930 
   931 fun mk_if cond = Const (@{const_name New_Random_Sequence.pos_if_random_dseq},
   932   HOLogic.boolT --> mk_pos_random_dseqT HOLogic.unitT) $ cond;
   933 
   934 fun mk_not t =
   935   let
   936     val pT = mk_pos_random_dseqT HOLogic.unitT
   937     val nT = @{typ code_numeral} --> @{typ code_numeral} --> @{typ Random.seed} -->
   938       @{typ code_numeral} --> Type (@{type_name Lazy_Sequence.lazy_sequence},
   939         [Type (@{type_name Option.option}, [@{typ unit}])])
   940 
   941   in Const (@{const_name New_Random_Sequence.pos_not_random_dseq}, nT --> pT) $ t end
   942 
   943 fun mk_map T1 T2 tf tp = Const (@{const_name New_Random_Sequence.pos_map},
   944   (T1 --> T2) --> mk_pos_random_dseqT T1 --> mk_pos_random_dseqT T2) $ tf $ tp
   945 
   946 val compfuns = CompilationFuns {mk_predT = mk_pos_random_dseqT, dest_predT = dest_pos_random_dseqT,
   947     mk_bot = mk_bot, mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if,
   948     mk_not = mk_not, mk_map = mk_map}
   949 
   950 end;
   951 
   952 structure New_Neg_Random_Sequence_CompFuns =
   953 struct
   954 
   955 fun mk_neg_random_dseqT T =
   956    @{typ code_numeral} --> @{typ code_numeral} --> @{typ Random.seed} -->
   957     @{typ code_numeral} --> 
   958     Type (@{type_name Lazy_Sequence.lazy_sequence}, [Type (@{type_name Option.option}, [T])])
   959 
   960 fun dest_neg_random_dseqT (Type ("fun", [@{typ code_numeral}, Type ("fun", [@{typ code_numeral},
   961     Type ("fun", [@{typ Random.seed}, Type ("fun", [@{typ code_numeral},
   962       Type (@{type_name Lazy_Sequence.lazy_sequence},
   963         [Type (@{type_name Option.option}, [T])])])])])])) = T
   964   | dest_neg_random_dseqT T = raise TYPE ("dest_random_dseqT", [T], []);
   965 
   966 fun mk_bot T = Const (@{const_name New_Random_Sequence.neg_empty}, mk_neg_random_dseqT T);
   967 
   968 fun mk_single t =
   969   let
   970     val T = fastype_of t
   971   in Const(@{const_name New_Random_Sequence.neg_single}, T --> mk_neg_random_dseqT T) $ t end;
   972 
   973 fun mk_bind (x, f) =
   974   let
   975     val T as Type ("fun", [_, U]) = fastype_of f
   976   in
   977     Const (@{const_name New_Random_Sequence.neg_bind}, fastype_of x --> T --> U) $ x $ f
   978   end;
   979 
   980 val mk_sup = HOLogic.mk_binop @{const_name New_Random_Sequence.neg_union};
   981 
   982 fun mk_if cond = Const (@{const_name New_Random_Sequence.neg_if_random_dseq},
   983   HOLogic.boolT --> mk_neg_random_dseqT HOLogic.unitT) $ cond;
   984 
   985 fun mk_not t =
   986   let
   987     val nT = mk_neg_random_dseqT HOLogic.unitT
   988     val pT = @{typ code_numeral} --> @{typ code_numeral} --> @{typ Random.seed} -->
   989     @{typ code_numeral} --> Type (@{type_name Lazy_Sequence.lazy_sequence}, [@{typ unit}])
   990   in Const (@{const_name New_Random_Sequence.neg_not_random_dseq}, pT --> nT) $ t end
   991 
   992 fun mk_map T1 T2 tf tp = Const (@{const_name New_Random_Sequence.neg_map},
   993   (T1 --> T2) --> mk_neg_random_dseqT T1 --> mk_neg_random_dseqT T2) $ tf $ tp
   994 
   995 val compfuns = CompilationFuns {mk_predT = mk_neg_random_dseqT, dest_predT = dest_neg_random_dseqT,
   996     mk_bot = mk_bot, mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if,
   997     mk_not = mk_not, mk_map = mk_map}
   998 
   999 end;
  1000 
  1001 structure Random_Sequence_CompFuns =
  1002 struct
  1003 
  1004 fun mk_random_dseqT T =
  1005   @{typ code_numeral} --> @{typ code_numeral} --> @{typ Random.seed} -->
  1006     HOLogic.mk_prodT (DSequence_CompFuns.mk_dseqT T, @{typ Random.seed})
  1007 
  1008 fun dest_random_dseqT (Type ("fun", [@{typ code_numeral}, Type ("fun", [@{typ code_numeral},
  1009   Type ("fun", [@{typ Random.seed},
  1010   Type (@{type_name "*"}, [T, @{typ Random.seed}])])])])) = DSequence_CompFuns.dest_dseqT T
  1011   | dest_random_dseqT T = raise TYPE ("dest_random_dseqT", [T], []);
  1012 
  1013 fun mk_bot T = Const (@{const_name Random_Sequence.empty}, mk_random_dseqT T);
  1014 
  1015 fun mk_single t =
  1016   let
  1017     val T = fastype_of t
  1018   in Const(@{const_name Random_Sequence.single}, T --> mk_random_dseqT T) $ t end;
  1019 
  1020 fun mk_bind (x, f) =
  1021   let
  1022     val T as Type ("fun", [_, U]) = fastype_of f
  1023   in
  1024     Const (@{const_name Random_Sequence.bind}, fastype_of x --> T --> U) $ x $ f
  1025   end;
  1026 
  1027 val mk_sup = HOLogic.mk_binop @{const_name Random_Sequence.union};
  1028 
  1029 fun mk_if cond = Const (@{const_name Random_Sequence.if_random_dseq},
  1030   HOLogic.boolT --> mk_random_dseqT HOLogic.unitT) $ cond;
  1031 
  1032 fun mk_not t =
  1033   let
  1034     val T = mk_random_dseqT HOLogic.unitT
  1035   in Const (@{const_name Random_Sequence.not_random_dseq}, T --> T) $ t end
  1036 
  1037 fun mk_map T1 T2 tf tp = Const (@{const_name Random_Sequence.map},
  1038   (T1 --> T2) --> mk_random_dseqT T1 --> mk_random_dseqT T2) $ tf $ tp
  1039 
  1040 val compfuns = CompilationFuns {mk_predT = mk_random_dseqT, dest_predT = dest_random_dseqT,
  1041     mk_bot = mk_bot, mk_single = mk_single, mk_bind = mk_bind, mk_sup = mk_sup, mk_if = mk_if,
  1042     mk_not = mk_not, mk_map = mk_map}
  1043 
  1044 end;
  1045 
  1046 (* for external use with interactive mode *)
  1047 val pred_compfuns = PredicateCompFuns.compfuns
  1048 val randompred_compfuns = Random_Sequence_CompFuns.compfuns;
  1049 val new_randompred_compfuns = New_Pos_Random_Sequence_CompFuns.compfuns
  1050 
  1051 (* compilation modifiers *)
  1052 
  1053 (* function types and names of different compilations *)
  1054 
  1055 fun funT_of compfuns mode T =
  1056   let
  1057     val Ts = binder_types T
  1058     val (inTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode Ts
  1059   in
  1060     inTs ---> (mk_predT compfuns (HOLogic.mk_tupleT outTs))
  1061   end;
  1062 
  1063 structure Comp_Mod =
  1064 struct
  1065 
  1066 datatype comp_modifiers = Comp_Modifiers of
  1067 {
  1068   compilation : compilation,
  1069   function_name_prefix : string,
  1070   compfuns : compilation_funs,
  1071   mk_random : typ -> term list -> term,
  1072   modify_funT : typ -> typ,
  1073   additional_arguments : string list -> term list,
  1074   wrap_compilation : compilation_funs -> string -> typ -> mode -> term list -> term -> term,
  1075   transform_additional_arguments : indprem -> term list -> term list
  1076 }
  1077 
  1078 fun dest_comp_modifiers (Comp_Modifiers c) = c
  1079 
  1080 val compilation = #compilation o dest_comp_modifiers
  1081 val function_name_prefix = #function_name_prefix o dest_comp_modifiers
  1082 val compfuns = #compfuns o dest_comp_modifiers
  1083 
  1084 val mk_random = #mk_random o dest_comp_modifiers
  1085 val funT_of' = funT_of o compfuns
  1086 val modify_funT = #modify_funT o dest_comp_modifiers
  1087 fun funT_of comp mode = modify_funT comp o funT_of' comp mode
  1088 
  1089 val additional_arguments = #additional_arguments o dest_comp_modifiers
  1090 val wrap_compilation = #wrap_compilation o dest_comp_modifiers
  1091 val transform_additional_arguments = #transform_additional_arguments o dest_comp_modifiers
  1092 
  1093 end;
  1094 
  1095 val depth_limited_comp_modifiers = Comp_Mod.Comp_Modifiers
  1096   {
  1097   compilation = Depth_Limited,
  1098   function_name_prefix = "depth_limited_",
  1099   compfuns = PredicateCompFuns.compfuns,
  1100   mk_random = (fn _ => error "no random generation"),
  1101   additional_arguments = fn names =>
  1102     let
  1103       val depth_name = Name.variant names "depth"
  1104     in [Free (depth_name, @{typ code_numeral})] end,
  1105   modify_funT = (fn T => let val (Ts, U) = strip_type T
  1106   val Ts' = [@{typ code_numeral}] in (Ts @ Ts') ---> U end),
  1107   wrap_compilation =
  1108     fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  1109     let
  1110       val [depth] = additional_arguments
  1111       val (_, Ts) = split_modeT' mode (binder_types T)
  1112       val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
  1113       val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
  1114     in
  1115       if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
  1116         $ mk_bot compfuns (dest_predT compfuns T')
  1117         $ compilation
  1118     end,
  1119   transform_additional_arguments =
  1120     fn prem => fn additional_arguments =>
  1121     let
  1122       val [depth] = additional_arguments
  1123       val depth' =
  1124         Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
  1125           $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
  1126     in [depth'] end
  1127   }
  1128 
  1129 val random_comp_modifiers = Comp_Mod.Comp_Modifiers
  1130   {
  1131   compilation = Random,
  1132   function_name_prefix = "random_",
  1133   compfuns = PredicateCompFuns.compfuns,
  1134   mk_random = (fn T => fn additional_arguments =>
  1135   list_comb (Const(@{const_name Quickcheck.iter},
  1136   [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
  1137     PredicateCompFuns.mk_predT T), additional_arguments)),
  1138   modify_funT = (fn T =>
  1139     let
  1140       val (Ts, U) = strip_type T
  1141       val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ "code_numeral * code_numeral"}]
  1142     in (Ts @ Ts') ---> U end),
  1143   additional_arguments = (fn names =>
  1144     let
  1145       val [nrandom, size, seed] = Name.variant_list names ["nrandom", "size", "seed"]
  1146     in
  1147       [Free (nrandom, @{typ code_numeral}), Free (size, @{typ code_numeral}),
  1148         Free (seed, @{typ "code_numeral * code_numeral"})]
  1149     end),
  1150   wrap_compilation = K (K (K (K (K I))))
  1151     : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1152   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1153   }
  1154 
  1155 val depth_limited_random_comp_modifiers = Comp_Mod.Comp_Modifiers
  1156   {
  1157   compilation = Depth_Limited_Random,
  1158   function_name_prefix = "depth_limited_random_",
  1159   compfuns = PredicateCompFuns.compfuns,
  1160   mk_random = (fn T => fn additional_arguments =>
  1161   list_comb (Const(@{const_name Quickcheck.iter},
  1162   [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
  1163     PredicateCompFuns.mk_predT T), tl additional_arguments)),
  1164   modify_funT = (fn T =>
  1165     let
  1166       val (Ts, U) = strip_type T
  1167       val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ code_numeral},
  1168         @{typ "code_numeral * code_numeral"}]
  1169     in (Ts @ Ts') ---> U end),
  1170   additional_arguments = (fn names =>
  1171     let
  1172       val [depth, nrandom, size, seed] = Name.variant_list names ["depth", "nrandom", "size", "seed"]
  1173     in
  1174       [Free (depth, @{typ code_numeral}), Free (nrandom, @{typ code_numeral}),
  1175         Free (size, @{typ code_numeral}), Free (seed, @{typ "code_numeral * code_numeral"})]
  1176     end),
  1177   wrap_compilation =
  1178   fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  1179     let
  1180       val depth = hd (additional_arguments)
  1181       val (_, Ts) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE))
  1182         mode (binder_types T)
  1183       val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
  1184       val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
  1185     in
  1186       if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
  1187         $ mk_bot compfuns (dest_predT compfuns T')
  1188         $ compilation
  1189     end,
  1190   transform_additional_arguments =
  1191     fn prem => fn additional_arguments =>
  1192     let
  1193       val [depth, nrandom, size, seed] = additional_arguments
  1194       val depth' =
  1195         Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
  1196           $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
  1197     in [depth', nrandom, size, seed] end
  1198 }
  1199 
  1200 val predicate_comp_modifiers = Comp_Mod.Comp_Modifiers
  1201   {
  1202   compilation = Pred,
  1203   function_name_prefix = "",
  1204   compfuns = PredicateCompFuns.compfuns,
  1205   mk_random = (fn _ => error "no random generation"),
  1206   modify_funT = I,
  1207   additional_arguments = K [],
  1208   wrap_compilation = K (K (K (K (K I))))
  1209    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1210   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1211   }
  1212 
  1213 val annotated_comp_modifiers = Comp_Mod.Comp_Modifiers
  1214   {
  1215   compilation = Annotated,
  1216   function_name_prefix = "annotated_",
  1217   compfuns = PredicateCompFuns.compfuns,
  1218   mk_random = (fn _ => error "no random generation"),
  1219   modify_funT = I,
  1220   additional_arguments = K [],
  1221   wrap_compilation =
  1222     fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  1223       mk_tracing ("calling predicate " ^ s ^
  1224         " with mode " ^ string_of_mode mode) compilation,
  1225   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1226   }
  1227 
  1228 val dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  1229   {
  1230   compilation = DSeq,
  1231   function_name_prefix = "dseq_",
  1232   compfuns = DSequence_CompFuns.compfuns,
  1233   mk_random = (fn _ => error "no random generation"),
  1234   modify_funT = I,
  1235   additional_arguments = K [],
  1236   wrap_compilation = K (K (K (K (K I))))
  1237    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1238   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1239   }
  1240 
  1241 val pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  1242   {
  1243   compilation = Pos_Random_DSeq,
  1244   function_name_prefix = "random_dseq_",
  1245   compfuns = Random_Sequence_CompFuns.compfuns,
  1246   mk_random = (fn T => fn additional_arguments =>
  1247   let
  1248     val random = Const ("Quickcheck.random_class.random",
  1249       @{typ code_numeral} --> @{typ Random.seed} -->
  1250         HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
  1251   in
  1252     Const ("Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
  1253       HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
  1254       Random_Sequence_CompFuns.mk_random_dseqT T) $ random
  1255   end),
  1256 
  1257   modify_funT = I,
  1258   additional_arguments = K [],
  1259   wrap_compilation = K (K (K (K (K I))))
  1260    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1261   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1262   }
  1263 
  1264 val neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  1265   {
  1266   compilation = Neg_Random_DSeq,
  1267   function_name_prefix = "random_dseq_neg_",
  1268   compfuns = Random_Sequence_CompFuns.compfuns,
  1269   mk_random = (fn _ => error "no random generation"),
  1270   modify_funT = I,
  1271   additional_arguments = K [],
  1272   wrap_compilation = K (K (K (K (K I))))
  1273    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1274   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1275   }
  1276 
  1277 
  1278 val new_pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  1279   {
  1280   compilation = New_Pos_Random_DSeq,
  1281   function_name_prefix = "new_random_dseq_",
  1282   compfuns = New_Pos_Random_Sequence_CompFuns.compfuns,
  1283   mk_random = (fn T => fn additional_arguments =>
  1284   let
  1285     val random = Const ("Quickcheck.random_class.random",
  1286       @{typ code_numeral} --> @{typ Random.seed} -->
  1287         HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
  1288   in
  1289     Const ("New_Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
  1290       HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
  1291       New_Pos_Random_Sequence_CompFuns.mk_pos_random_dseqT T) $ random
  1292   end),
  1293   modify_funT = I,
  1294   additional_arguments = K [],
  1295   wrap_compilation = K (K (K (K (K I))))
  1296    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1297   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1298   }
  1299 
  1300 val new_neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  1301   {
  1302   compilation = New_Neg_Random_DSeq,
  1303   function_name_prefix = "new_random_dseq_neg_",
  1304   compfuns = New_Neg_Random_Sequence_CompFuns.compfuns,
  1305   mk_random = (fn _ => error "no random generation"),
  1306   modify_funT = I,
  1307   additional_arguments = K [],
  1308   wrap_compilation = K (K (K (K (K I))))
  1309    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  1310   transform_additional_arguments = K I : (indprem -> term list -> term list)
  1311   }
  1312 
  1313 fun negative_comp_modifiers_of comp_modifiers =
  1314     (case Comp_Mod.compilation comp_modifiers of
  1315       Pos_Random_DSeq => neg_random_dseq_comp_modifiers
  1316     | Neg_Random_DSeq => pos_random_dseq_comp_modifiers
  1317     | New_Pos_Random_DSeq => new_neg_random_dseq_comp_modifiers
  1318     | New_Neg_Random_DSeq => new_pos_random_dseq_comp_modifiers
  1319     | c => comp_modifiers)
  1320 
  1321 (** mode analysis **)
  1322 
  1323 type mode_analysis_options = {use_random : bool, reorder_premises : bool, infer_pos_and_neg_modes : bool}
  1324 
  1325 fun is_constrt thy =
  1326   let
  1327     val cnstrs = flat (maps
  1328       (map (fn (_, (Tname, _, cs)) => map (apsnd (rpair Tname o length)) cs) o #descr o snd)
  1329       (Symtab.dest (Datatype.get_all thy)));
  1330     fun check t = (case strip_comb t of
  1331         (Free _, []) => true
  1332       | (Const (s, T), ts) => (case (AList.lookup (op =) cnstrs s, body_type T) of
  1333             (SOME (i, Tname), Type (Tname', _)) =>
  1334               length ts = i andalso Tname = Tname' andalso forall check ts
  1335           | _ => false)
  1336       | _ => false)
  1337   in check end;
  1338 
  1339 (*** check if a type is an equality type (i.e. doesn't contain fun)
  1340   FIXME this is only an approximation ***)
  1341 fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
  1342   | is_eqT _ = true;
  1343 
  1344 fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
  1345 val terms_vs = distinct (op =) o maps term_vs;
  1346 
  1347 (** collect all Frees in a term (with duplicates!) **)
  1348 fun term_vTs tm =
  1349   fold_aterms (fn Free xT => cons xT | _ => I) tm [];
  1350 
  1351 fun subsets i j =
  1352   if i <= j then
  1353     let
  1354       fun merge xs [] = xs
  1355         | merge [] ys = ys
  1356         | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
  1357             else y::merge (x::xs) ys;
  1358       val is = subsets (i+1) j
  1359     in merge (map (fn ks => i::ks) is) is end
  1360   else [[]];
  1361 
  1362 fun print_failed_mode options thy modes p (pol, m) rs is =
  1363   if show_mode_inference options then
  1364     let
  1365       val _ = tracing ("Clauses " ^ commas (map (fn i => string_of_int (i + 1)) is) ^ " of " ^
  1366         p ^ " violates mode " ^ string_of_mode m)
  1367     in () end
  1368   else ()
  1369 
  1370 fun error_of p (pol, m) is =
  1371   "  Clauses " ^ commas (map (fn i => string_of_int (i + 1)) is) ^ " of " ^
  1372         p ^ " violates mode " ^ string_of_mode m
  1373 
  1374 fun is_all_input mode =
  1375   let
  1376     fun is_all_input' (Fun _) = true
  1377       | is_all_input' (Pair (m1, m2)) = is_all_input' m1 andalso is_all_input' m2
  1378       | is_all_input' Input = true
  1379       | is_all_input' Output = false
  1380   in
  1381     forall is_all_input' (strip_fun_mode mode)
  1382   end
  1383 
  1384 fun all_input_of T =
  1385   let
  1386     val (Ts, U) = strip_type T
  1387     fun input_of (Type ("*", [T1, T2])) = Pair (input_of T1, input_of T2)
  1388       | input_of _ = Input
  1389   in
  1390     if U = HOLogic.boolT then
  1391       fold_rev (curry Fun) (map input_of Ts) Bool
  1392     else
  1393       raise Fail "all_input_of: not a predicate"
  1394   end
  1395 
  1396 fun partial_hd [] = NONE
  1397   | partial_hd (x :: xs) = SOME x
  1398 
  1399 fun term_vs tm = fold_aterms (fn Free (x, T) => cons x | _ => I) tm [];
  1400 val terms_vs = distinct (op =) o maps term_vs;
  1401 
  1402 fun input_mode T =
  1403   let
  1404     val (Ts, U) = strip_type T
  1405   in
  1406     fold_rev (curry Fun) (map (K Input) Ts) Input
  1407   end
  1408 
  1409 fun output_mode T =
  1410   let
  1411     val (Ts, U) = strip_type T
  1412   in
  1413     fold_rev (curry Fun) (map (K Output) Ts) Output
  1414   end
  1415 
  1416 fun is_invertible_function ctxt (Const (f, _)) = is_constr ctxt f
  1417   | is_invertible_function ctxt _ = false
  1418 
  1419 fun non_invertible_subterms ctxt (t as Free _) = []
  1420   | non_invertible_subterms ctxt t = 
  1421   let
  1422     val (f, args) = strip_comb t
  1423   in
  1424     if is_invertible_function ctxt f then
  1425       maps (non_invertible_subterms ctxt) args
  1426     else
  1427       [t]
  1428   end
  1429 
  1430 fun collect_non_invertible_subterms ctxt (f as Free _) (names, eqs) = (f, (names, eqs))
  1431   | collect_non_invertible_subterms ctxt t (names, eqs) =
  1432     case (strip_comb t) of (f, args) =>
  1433       if is_invertible_function ctxt f then
  1434           let
  1435             val (args', (names', eqs')) =
  1436               fold_map (collect_non_invertible_subterms ctxt) args (names, eqs)
  1437           in
  1438             (list_comb (f, args'), (names', eqs'))
  1439           end
  1440         else
  1441           let
  1442             val s = Name.variant names "x"
  1443             val v = Free (s, fastype_of t)
  1444           in
  1445             (v, (s :: names, HOLogic.mk_eq (v, t) :: eqs))
  1446           end
  1447 (*
  1448   if is_constrt thy t then (t, (names, eqs)) else
  1449     let
  1450       val s = Name.variant names "x"
  1451       val v = Free (s, fastype_of t)
  1452     in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
  1453 *)
  1454 
  1455 fun is_possible_output thy vs t =
  1456   forall
  1457     (fn t => is_eqT (fastype_of t) andalso forall (member (op =) vs) (term_vs t))
  1458       (non_invertible_subterms (ProofContext.init thy) t)
  1459   andalso
  1460     (forall (is_eqT o snd)
  1461       (inter (fn ((f', _), f) => f = f') vs (Term.add_frees t [])))
  1462 
  1463 fun vars_of_destructable_term ctxt (Free (x, _)) = [x]
  1464   | vars_of_destructable_term ctxt t =
  1465   let
  1466     val (f, args) = strip_comb t
  1467   in
  1468     if is_invertible_function ctxt f then
  1469       maps (vars_of_destructable_term ctxt) args
  1470     else
  1471       []
  1472   end
  1473 
  1474 fun is_constructable thy vs t = forall (member (op =) vs) (term_vs t)
  1475 
  1476 fun missing_vars vs t = subtract (op =) vs (term_vs t)
  1477 
  1478 fun output_terms (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =
  1479     output_terms (t1, d1)  @ output_terms (t2, d2)
  1480   | output_terms (t1 $ t2, Mode_App (d1, d2)) =
  1481     output_terms (t1, d1)  @ output_terms (t2, d2)
  1482   | output_terms (t, Term Output) = [t]
  1483   | output_terms _ = []
  1484 
  1485 fun lookup_mode modes (Const (s, T)) =
  1486    (case (AList.lookup (op =) modes s) of
  1487       SOME ms => SOME (map (fn m => (Context m, [])) ms)
  1488     | NONE => NONE)
  1489   | lookup_mode modes (Free (x, _)) =
  1490     (case (AList.lookup (op =) modes x) of
  1491       SOME ms => SOME (map (fn m => (Context m , [])) ms)
  1492     | NONE => NONE)
  1493 
  1494 fun derivations_of (thy : theory) modes vs (Const ("Pair", _) $ t1 $ t2) (Pair (m1, m2)) =
  1495     map_product
  1496       (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
  1497         (derivations_of thy modes vs t1 m1) (derivations_of thy modes vs t2 m2)
  1498   | derivations_of thy modes vs t (m as Fun _) =
  1499     (*let
  1500       val (p, args) = strip_comb t
  1501     in
  1502       (case lookup_mode modes p of
  1503         SOME ms => map_filter (fn (Context m, []) => let
  1504           val ms = strip_fun_mode m
  1505           val (argms, restms) = chop (length args) ms
  1506           val m' = fold_rev (curry Fun) restms Bool
  1507         in
  1508           if forall (fn m => eq_mode (Input, m)) argms andalso eq_mode (m', mode) then
  1509             SOME (fold (curry Mode_App) (map Term argms) (Context m), missing_vars vs t)
  1510           else NONE
  1511         end) ms
  1512       | NONE => (if is_all_input mode then [(Context mode, [])] else []))
  1513     end*)
  1514     (case try (all_derivations_of thy modes vs) t  of
  1515       SOME derivs =>
  1516         filter (fn (d, mvars) => eq_mode (mode_of d, m) andalso null (output_terms (t, d))) derivs
  1517     | NONE => (if is_all_input m then [(Context m, [])] else []))
  1518   | derivations_of thy modes vs t m =
  1519     if eq_mode (m, Input) then
  1520       [(Term Input, missing_vars vs t)]
  1521     else if eq_mode (m, Output) then
  1522       (if is_possible_output thy vs t then [(Term Output, [])] else [])
  1523     else []
  1524 and all_derivations_of thy modes vs (Const ("Pair", _) $ t1 $ t2) =
  1525   let
  1526     val derivs1 = all_derivations_of thy modes vs t1
  1527     val derivs2 = all_derivations_of thy modes vs t2
  1528   in
  1529     map_product
  1530       (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
  1531         derivs1 derivs2
  1532   end
  1533   | all_derivations_of thy modes vs (t1 $ t2) =
  1534   let
  1535     val derivs1 = all_derivations_of thy modes vs t1
  1536   in
  1537     maps (fn (d1, mvars1) =>
  1538       case mode_of d1 of
  1539         Fun (m', _) => map (fn (d2, mvars2) =>
  1540           (Mode_App (d1, d2), union (op =) mvars1 mvars2)) (derivations_of thy modes vs t2 m')
  1541         | _ => raise Fail "Something went wrong") derivs1
  1542   end
  1543   | all_derivations_of thy modes vs (Const (s, T)) = the (lookup_mode modes (Const (s, T)))
  1544   | all_derivations_of thy modes vs (Free (x, T)) = the (lookup_mode modes (Free (x, T)))
  1545   | all_derivations_of _ modes vs _ = raise Fail "all_derivations_of"
  1546 
  1547 fun rev_option_ord ord (NONE, NONE) = EQUAL
  1548   | rev_option_ord ord (NONE, SOME _) = GREATER
  1549   | rev_option_ord ord (SOME _, NONE) = LESS
  1550   | rev_option_ord ord (SOME x, SOME y) = ord (x, y)
  1551 
  1552 fun term_of_prem (Prem t) = t
  1553   | term_of_prem (Negprem t) = t
  1554   | term_of_prem (Sidecond t) = t
  1555 
  1556 fun random_mode_in_deriv modes t deriv =
  1557   case try dest_Const (fst (strip_comb t)) of
  1558     SOME (s, _) =>
  1559       (case AList.lookup (op =) modes s of
  1560         SOME ms =>
  1561           (case AList.lookup (op =) (map (fn ((p, m), r) => (m, r)) ms) (head_mode_of deriv) of
  1562             SOME r => r
  1563           | NONE => false)
  1564       | NONE => false)
  1565   | NONE => false
  1566 
  1567 fun number_of_output_positions mode =
  1568   let
  1569     val args = strip_fun_mode mode
  1570     fun contains_output (Fun _) = false
  1571       | contains_output Input = false
  1572       | contains_output Output = true
  1573       | contains_output (Pair (m1, m2)) = contains_output m1 orelse contains_output m2
  1574   in
  1575     length (filter contains_output args)
  1576   end
  1577 
  1578 fun lex_ord ord1 ord2 (x, x') =
  1579   case ord1 (x, x') of
  1580     EQUAL => ord2 (x, x')
  1581   | ord => ord
  1582 
  1583 fun deriv_ord2' thy pred modes t1 t2 ((deriv1, mvars1), (deriv2, mvars2)) =
  1584   let
  1585     (* prefer modes without requirement for generating random values *)
  1586     fun mvars_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1587       int_ord (length mvars1, length mvars2)
  1588     (* prefer non-random modes *)
  1589     fun random_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1590       int_ord (if random_mode_in_deriv modes t1 deriv1 then 1 else 0,
  1591         if random_mode_in_deriv modes t1 deriv1 then 1 else 0)
  1592     (* prefer modes with more input and less output *)
  1593     fun output_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1594       int_ord (number_of_output_positions (head_mode_of deriv1),
  1595         number_of_output_positions (head_mode_of deriv2))
  1596     (* prefer recursive calls *)
  1597     fun is_rec_premise t =
  1598       case fst (strip_comb t) of Const (c, T) => c = pred | _ => false
  1599     fun recursive_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1600       int_ord (if is_rec_premise t1 then 0 else 1,
  1601         if is_rec_premise t2 then 0 else 1)
  1602     val ord = lex_ord mvars_ord (lex_ord random_mode_ord (lex_ord output_mode_ord recursive_ord))
  1603   in
  1604     ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2))
  1605   end
  1606 
  1607 fun deriv_ord2 thy pred modes t = deriv_ord2' thy pred modes t t
  1608 
  1609 fun deriv_ord ((deriv1, mvars1), (deriv2, mvars2)) =
  1610   int_ord (length mvars1, length mvars2)
  1611 
  1612 fun premise_ord thy pred modes ((prem1, a1), (prem2, a2)) =
  1613   rev_option_ord (deriv_ord2' thy pred modes (term_of_prem prem1) (term_of_prem prem2)) (a1, a2)
  1614 
  1615 fun print_mode_list modes =
  1616   tracing ("modes: " ^ (commas (map (fn (s, ms) => s ^ ": " ^
  1617     commas (map (fn (m, r) => string_of_mode m ^ (if r then " random " else " not ")) ms)) modes)))
  1618 
  1619 fun select_mode_prem (mode_analysis_options : mode_analysis_options) (thy : theory) pred
  1620   pol (modes, (pos_modes, neg_modes)) vs ps =
  1621   let
  1622     fun choose_mode_of_prem (Prem t) = partial_hd
  1623         (sort (deriv_ord2 thy pred modes t) (all_derivations_of thy pos_modes vs t))
  1624       | choose_mode_of_prem (Sidecond t) = SOME (Context Bool, missing_vars vs t)
  1625       | choose_mode_of_prem (Negprem t) = partial_hd
  1626           (sort (deriv_ord2 thy pred modes t) (filter (fn (d, missing_vars) => is_all_input (head_mode_of d))
  1627              (all_derivations_of thy neg_modes vs t)))
  1628       | choose_mode_of_prem p = raise Fail ("choose_mode_of_prem: " ^ string_of_prem thy p)
  1629   in
  1630     if #reorder_premises mode_analysis_options then
  1631       partial_hd (sort (premise_ord thy pred modes) (ps ~~ map choose_mode_of_prem ps))
  1632     else
  1633       SOME (hd ps, choose_mode_of_prem (hd ps))
  1634   end
  1635 
  1636 fun check_mode_clause' (mode_analysis_options : mode_analysis_options) thy pred param_vs (modes :
  1637   (string * ((bool * mode) * bool) list) list) ((pol, mode) : bool * mode) (ts, ps) =
  1638   let
  1639     val vTs = distinct (op =) (fold Term.add_frees (map term_of_prem ps) (fold Term.add_frees ts []))
  1640     val modes' = modes @ (param_vs ~~ map (fn x => [((true, x), false), ((false, x), false)]) (ho_arg_modes_of mode))
  1641     fun retrieve_modes_of_pol pol = map (fn (s, ms) =>
  1642       (s, map_filter (fn ((p, m), r) => if p = pol then SOME m else NONE | _ => NONE) ms))
  1643     val (pos_modes', neg_modes') =
  1644       if #infer_pos_and_neg_modes mode_analysis_options then
  1645         (retrieve_modes_of_pol pol modes', retrieve_modes_of_pol (not pol) modes')
  1646       else
  1647         let
  1648           val modes = map (fn (s, ms) => (s, map (fn ((p, m), r) => m) ms)) modes'
  1649         in (modes, modes) end
  1650     val (in_ts, out_ts) = split_mode mode ts
  1651     val in_vs = maps (vars_of_destructable_term (ProofContext.init thy)) in_ts
  1652     val out_vs = terms_vs out_ts
  1653     fun known_vs_after p vs = (case p of
  1654         Prem t => union (op =) vs (term_vs t)
  1655       | Sidecond t => union (op =) vs (term_vs t)
  1656       | Negprem t => union (op =) vs (term_vs t)
  1657       | _ => raise Fail "I do not know")
  1658     fun check_mode_prems acc_ps rnd vs [] = SOME (acc_ps, vs, rnd)
  1659       | check_mode_prems acc_ps rnd vs ps =
  1660         (case
  1661           (select_mode_prem mode_analysis_options thy pred pol (modes', (pos_modes', neg_modes')) vs ps) of
  1662           SOME (p, SOME (deriv, [])) => check_mode_prems ((p, deriv) :: acc_ps) rnd
  1663             (known_vs_after p vs) (filter_out (equal p) ps)
  1664         | SOME (p, SOME (deriv, missing_vars)) =>
  1665           if #use_random mode_analysis_options andalso pol then
  1666             check_mode_prems ((p, deriv) :: (map
  1667               (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
  1668                 (distinct (op =) missing_vars))
  1669                 @ acc_ps) true (known_vs_after p vs) (filter_out (equal p) ps)
  1670           else NONE
  1671         | SOME (p, NONE) => NONE
  1672         | NONE => NONE)
  1673   in
  1674     case check_mode_prems [] false in_vs ps of
  1675       NONE => NONE
  1676     | SOME (acc_ps, vs, rnd) =>
  1677       if forall (is_constructable thy vs) (in_ts @ out_ts) then
  1678         SOME (ts, rev acc_ps, rnd)
  1679       else
  1680         if #use_random mode_analysis_options andalso pol then
  1681           let
  1682              val generators = map
  1683               (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
  1684                 (subtract (op =) vs (terms_vs (in_ts @ out_ts)))
  1685           in
  1686             SOME (ts, rev (generators @ acc_ps), true)
  1687           end
  1688         else
  1689           NONE
  1690   end
  1691 
  1692 datatype result = Success of bool | Error of string
  1693 
  1694 fun check_modes_pred' mode_analysis_options options thy param_vs clauses modes (p, (ms : ((bool * mode) * bool) list)) =
  1695   let
  1696     fun split xs =
  1697       let
  1698         fun split' [] (ys, zs) = (rev ys, rev zs)
  1699           | split' ((m, Error z) :: xs) (ys, zs) = split' xs (ys, z :: zs)
  1700           | split' (((m : bool * mode), Success rnd) :: xs) (ys, zs) = split' xs ((m, rnd) :: ys, zs)
  1701        in
  1702          split' xs ([], [])
  1703        end
  1704     val rs = these (AList.lookup (op =) clauses p)
  1705     fun check_mode m =
  1706       let
  1707         val res = Output.cond_timeit false "work part of check_mode for one mode" (fn _ => 
  1708           map (check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)
  1709       in
  1710         Output.cond_timeit false "aux part of check_mode for one mode" (fn _ => 
  1711         case find_indices is_none res of
  1712           [] => Success (exists (fn SOME (_, _, true) => true | _ => false) res)
  1713         | is => (print_failed_mode options thy modes p m rs is; Error (error_of p m is)))
  1714       end
  1715     val _ = if show_mode_inference options then
  1716         tracing ("checking " ^ string_of_int (length ms) ^ " modes ...")
  1717       else ()
  1718     val res = Output.cond_timeit false "check_mode" (fn _ => map (fn (m, _) => (m, check_mode m)) ms)
  1719     val (ms', errors) = split res
  1720   in
  1721     ((p, (ms' : ((bool * mode) * bool) list)), errors)
  1722   end;
  1723 
  1724 fun get_modes_pred' mode_analysis_options thy param_vs clauses modes (p, ms) =
  1725   let
  1726     val rs = these (AList.lookup (op =) clauses p)
  1727   in
  1728     (p, map (fn (m, rnd) =>
  1729       (m, map
  1730         ((fn (ts, ps, rnd) => (ts, ps)) o the o
  1731           check_mode_clause' mode_analysis_options thy p param_vs modes m) rs)) ms)
  1732   end;
  1733 
  1734 fun fixp f (x : (string * ((bool * mode) * bool) list) list) =
  1735   let val y = f x
  1736   in if x = y then x else fixp f y end;
  1737 
  1738 fun fixp_with_state f (x : (string * ((bool * mode) * bool) list) list, state) =
  1739   let
  1740     val (y, state') = f (x, state)
  1741   in
  1742     if x = y then (y, state') else fixp_with_state f (y, state')
  1743   end
  1744 
  1745 fun string_of_ext_mode ((pol, mode), rnd) =
  1746   string_of_mode mode ^ "(" ^ (if pol then "pos" else "neg") ^ ", "
  1747   ^ (if rnd then "rnd" else "nornd") ^ ")"
  1748 
  1749 fun print_extra_modes options modes =
  1750   if show_mode_inference options then
  1751     tracing ("Modes of inferred predicates: " ^
  1752       cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map string_of_ext_mode ms)) modes))
  1753   else ()
  1754 
  1755 fun infer_modes mode_analysis_options options compilation preds all_modes param_vs clauses thy =
  1756   let
  1757     val collect_errors = false
  1758     fun appair f (x1, x2) (y1, y2) = (f x1 y1, f x2 y2)
  1759     fun needs_random s (false, m) = ((false, m), false)
  1760       | needs_random s (true, m) = ((true, m), member (op =) (#needs_random (the_pred_data thy s)) m)
  1761     fun add_polarity_and_random_bit s b ms = map (fn m => needs_random s (b, m)) ms
  1762     val prednames = map fst preds
  1763     (* extramodes contains all modes of all constants, should we only use the necessary ones
  1764        - what is the impact on performance? *)
  1765     val extra_modes =
  1766       if #infer_pos_and_neg_modes mode_analysis_options then
  1767         let
  1768           val pos_extra_modes =
  1769             all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name)
  1770           val neg_extra_modes =
  1771             all_modes_of (negative_compilation_of compilation) thy
  1772             |> filter_out (fn (name, _) => member (op =) prednames name)
  1773         in
  1774           map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)
  1775                 @ add_polarity_and_random_bit s false (the (AList.lookup (op =) neg_extra_modes s))))
  1776             pos_extra_modes
  1777         end
  1778       else
  1779         map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)))
  1780           (all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name))
  1781     val _ = print_extra_modes options extra_modes
  1782     val start_modes =
  1783       if #infer_pos_and_neg_modes mode_analysis_options then
  1784         map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms @
  1785           (map (fn m => ((false, m), false)) ms))) all_modes
  1786       else
  1787         map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms)) all_modes
  1788     fun iteration modes = map
  1789       (check_modes_pred' mode_analysis_options options thy param_vs clauses
  1790         (modes @ extra_modes)) modes
  1791     val ((modes : (string * ((bool * mode) * bool) list) list), errors) =
  1792       Output.cond_timeit false "Fixpount computation of mode analysis" (fn () =>
  1793       if collect_errors then
  1794         fixp_with_state (fn (modes, errors) =>
  1795           let
  1796             val (modes', new_errors) = split_list (iteration modes)
  1797           in (modes', errors @ flat new_errors) end) (start_modes, [])
  1798         else
  1799           (fixp (fn modes => map fst (iteration modes)) start_modes, []))
  1800     val moded_clauses = map (get_modes_pred' mode_analysis_options thy param_vs clauses
  1801       (modes @ extra_modes)) modes
  1802     val thy' = fold (fn (s, ms) => if member (op =) (map fst preds) s then
  1803       set_needs_random s (map_filter (fn ((true, m), true) => SOME m | _ => NONE) ms) else I)
  1804       modes thy
  1805 
  1806   in
  1807     ((moded_clauses, errors), thy')
  1808   end;
  1809 
  1810 (* term construction *)
  1811 
  1812 fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
  1813       NONE => (Free (s, T), (names, (s, [])::vs))
  1814     | SOME xs =>
  1815         let
  1816           val s' = Name.variant names s;
  1817           val v = Free (s', T)
  1818         in
  1819           (v, (s'::names, AList.update (op =) (s, v::xs) vs))
  1820         end);
  1821 
  1822 fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
  1823   | distinct_v (t $ u) nvs =
  1824       let
  1825         val (t', nvs') = distinct_v t nvs;
  1826         val (u', nvs'') = distinct_v u nvs';
  1827       in (t' $ u', nvs'') end
  1828   | distinct_v x nvs = (x, nvs);
  1829 
  1830 (** specific rpred functions -- move them to the correct place in this file *)
  1831 
  1832 fun mk_Eval_of additional_arguments ((x, T), NONE) names = (x, names)
  1833   | mk_Eval_of additional_arguments ((x, T), SOME mode) names =
  1834   let
  1835     val Ts = binder_types T
  1836     fun mk_split_lambda [] t = lambda (Free (Name.variant names "x", HOLogic.unitT)) t
  1837       | mk_split_lambda [x] t = lambda x t
  1838       | mk_split_lambda xs t =
  1839       let
  1840         fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
  1841           | mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
  1842       in
  1843         mk_split_lambda' xs t
  1844       end;
  1845     fun mk_arg (i, T) =
  1846       let
  1847         val vname = Name.variant names ("x" ^ string_of_int i)
  1848         val default = Free (vname, T)
  1849       in 
  1850         case AList.lookup (op =) mode i of
  1851           NONE => (([], [default]), [default])
  1852         | SOME NONE => (([default], []), [default])
  1853         | SOME (SOME pis) =>
  1854           case HOLogic.strip_tupleT T of
  1855             [] => error "pair mode but unit tuple" (*(([default], []), [default])*)
  1856           | [_] => error "pair mode but not a tuple" (*(([default], []), [default])*)
  1857           | Ts =>
  1858             let
  1859               val vnames = Name.variant_list names
  1860                 (map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
  1861                   (1 upto length Ts))
  1862               val args = map2 (curry Free) vnames Ts
  1863               fun split_args (i, arg) (ins, outs) =
  1864                 if member (op =) pis i then
  1865                   (arg::ins, outs)
  1866                 else
  1867                   (ins, arg::outs)
  1868               val (inargs, outargs) = fold_rev split_args ((1 upto length Ts) ~~ args) ([], [])
  1869               fun tuple args = if null args then [] else [HOLogic.mk_tuple args]
  1870             in ((tuple inargs, tuple outargs), args) end
  1871       end
  1872     val (inoutargs, args) = split_list (map mk_arg (1 upto (length Ts) ~~ Ts))
  1873     val (inargs, outargs) = pairself flat (split_list inoutargs)
  1874     val r = PredicateCompFuns.mk_Eval 
  1875       (list_comb (x, inargs @ additional_arguments), HOLogic.mk_tuple outargs)
  1876     val t = fold_rev mk_split_lambda args r
  1877   in
  1878     (t, names)
  1879   end;
  1880 
  1881 (* TODO: uses param_vs -- change necessary for compilation with new modes *)
  1882 fun compile_arg compilation_modifiers additional_arguments ctxt param_vs iss arg = 
  1883   let
  1884     fun map_params (t as Free (f, T)) =
  1885       if member (op =) param_vs f then
  1886         case (AList.lookup (op =) (param_vs ~~ iss) f) of
  1887           SOME is =>
  1888             let
  1889               val _ = error "compile_arg: A parameter in a input position -- do we have a test case?"
  1890               val T' = Comp_Mod.funT_of compilation_modifiers is T
  1891             in t(*fst (mk_Eval_of additional_arguments ((Free (f, T'), T), is) [])*) end
  1892         | NONE => t
  1893       else t
  1894       | map_params t = t
  1895     in map_aterms map_params arg end
  1896 
  1897 fun compile_match compilation_modifiers additional_arguments
  1898   param_vs iss ctxt eqs eqs' out_ts success_t =
  1899   let
  1900     val compfuns = Comp_Mod.compfuns compilation_modifiers
  1901     val eqs'' = maps mk_eq eqs @ eqs'
  1902     val eqs'' =
  1903       map (compile_arg compilation_modifiers additional_arguments ctxt param_vs iss) eqs''
  1904     val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
  1905     val name = Name.variant names "x";
  1906     val name' = Name.variant (name :: names) "y";
  1907     val T = HOLogic.mk_tupleT (map fastype_of out_ts);
  1908     val U = fastype_of success_t;
  1909     val U' = dest_predT compfuns U;
  1910     val v = Free (name, T);
  1911     val v' = Free (name', T);
  1912   in
  1913     lambda v (fst (Datatype.make_case ctxt Datatype_Case.Quiet [] v
  1914       [(HOLogic.mk_tuple out_ts,
  1915         if null eqs'' then success_t
  1916         else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
  1917           foldr1 HOLogic.mk_conj eqs'' $ success_t $
  1918             mk_bot compfuns U'),
  1919        (v', mk_bot compfuns U')]))
  1920   end;
  1921 
  1922 fun string_of_tderiv ctxt (t, deriv) = 
  1923   (case (t, deriv) of
  1924     (t1 $ t2, Mode_App (deriv1, deriv2)) =>
  1925       string_of_tderiv ctxt (t1, deriv1) ^ " $ " ^ string_of_tderiv ctxt (t2, deriv2)
  1926   | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (deriv1, deriv2)) =>
  1927     "(" ^ string_of_tderiv ctxt (t1, deriv1) ^ ", " ^ string_of_tderiv ctxt (t2, deriv2) ^ ")"
  1928   | (t, Term Input) => Syntax.string_of_term ctxt t ^ "[Input]"
  1929   | (t, Term Output) => Syntax.string_of_term ctxt t ^ "[Output]"
  1930   | (t, Context m) => Syntax.string_of_term ctxt t ^ "[" ^ string_of_mode m ^ "]")
  1931 
  1932 fun compile_expr compilation_modifiers ctxt (t, deriv) additional_arguments =
  1933   let
  1934     val compfuns = Comp_Mod.compfuns compilation_modifiers
  1935     fun expr_of (t, deriv) =
  1936       (case (t, deriv) of
  1937         (t, Term Input) => SOME t
  1938       | (t, Term Output) => NONE
  1939       | (Const (name, T), Context mode) =>
  1940         (case alternative_function_of (ProofContext.theory_of ctxt) name mode of
  1941           SOME alt_function_name =>
  1942             let
  1943               val (inpTs, outpTs) = split_map_modeT (fn _ => fn T => (SOME T, NONE))
  1944                 mode (binder_types T)
  1945               val bs = map (pair "x") inpTs
  1946               val bounds = map Bound (rev (0 upto (length bs) - 1))
  1947               val f = Const (alt_function_name, inpTs ---> HOLogic.mk_tupleT outpTs)
  1948             in SOME (list_abs (bs, mk_single compfuns (list_comb (f, bounds)))) end
  1949         | NONE =>
  1950           SOME (Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
  1951             (ProofContext.theory_of ctxt) name mode,
  1952             Comp_Mod.funT_of compilation_modifiers mode T)))
  1953       | (Free (s, T), Context m) =>
  1954         SOME (Free (s, Comp_Mod.funT_of compilation_modifiers m T))
  1955       | (t, Context m) =>
  1956         let
  1957           val bs = map (pair "x") (binder_types (fastype_of t))
  1958           val bounds = map Bound (rev (0 upto (length bs) - 1))
  1959         in SOME (list_abs (bs, mk_if compfuns (list_comb (t, bounds)))) end
  1960       | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =>
  1961         (case (expr_of (t1, d1), expr_of (t2, d2)) of
  1962           (NONE, NONE) => NONE
  1963         | (NONE, SOME t) => SOME t
  1964         | (SOME t, NONE) => SOME t
  1965         | (SOME t1, SOME t2) => SOME (HOLogic.mk_prod (t1, t2)))
  1966       | (t1 $ t2, Mode_App (deriv1, deriv2)) =>
  1967         (case (expr_of (t1, deriv1), expr_of (t2, deriv2)) of
  1968           (SOME t, NONE) => SOME t
  1969          | (SOME t, SOME u) => SOME (t $ u)
  1970          | _ => error "something went wrong here!"))
  1971   in
  1972     list_comb (the (expr_of (t, deriv)), additional_arguments)
  1973   end
  1974 
  1975 fun compile_clause compilation_modifiers ctxt all_vs param_vs additional_arguments
  1976   mode inp (ts, moded_ps) =
  1977   let
  1978     val compfuns = Comp_Mod.compfuns compilation_modifiers
  1979     val iss = ho_arg_modes_of mode
  1980     val compile_match = compile_match compilation_modifiers
  1981       additional_arguments param_vs iss ctxt
  1982     val (in_ts, out_ts) = split_mode mode ts;
  1983     val (in_ts', (all_vs', eqs)) =
  1984       fold_map (collect_non_invertible_subterms ctxt) in_ts (all_vs, []);
  1985     fun compile_prems out_ts' vs names [] =
  1986           let
  1987             val (out_ts'', (names', eqs')) =
  1988               fold_map (collect_non_invertible_subterms ctxt) out_ts' (names, []);
  1989             val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
  1990               out_ts'' (names', map (rpair []) vs);
  1991           in
  1992             compile_match constr_vs (eqs @ eqs') out_ts'''
  1993               (mk_single compfuns (HOLogic.mk_tuple out_ts))
  1994           end
  1995       | compile_prems out_ts vs names ((p, deriv) :: ps) =
  1996           let
  1997             val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
  1998             val (out_ts', (names', eqs)) =
  1999               fold_map (collect_non_invertible_subterms ctxt) out_ts (names, [])
  2000             val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
  2001               out_ts' ((names', map (rpair []) vs))
  2002             val mode = head_mode_of deriv
  2003             val additional_arguments' =
  2004               Comp_Mod.transform_additional_arguments compilation_modifiers p additional_arguments
  2005             val (compiled_clause, rest) = case p of
  2006                Prem t =>
  2007                  let
  2008                    val u =
  2009                      compile_expr compilation_modifiers ctxt (t, deriv) additional_arguments'
  2010                    val (_, out_ts''') = split_mode mode (snd (strip_comb t))
  2011                    val rest = compile_prems out_ts''' vs' names'' ps
  2012                  in
  2013                    (u, rest)
  2014                  end
  2015              | Negprem t =>
  2016                  let
  2017                    val neg_compilation_modifiers =
  2018                      negative_comp_modifiers_of compilation_modifiers
  2019                    val u = mk_not compfuns
  2020                      (compile_expr neg_compilation_modifiers ctxt (t, deriv) additional_arguments')
  2021                    val (_, out_ts''') = split_mode mode (snd (strip_comb t))
  2022                    val rest = compile_prems out_ts''' vs' names'' ps
  2023                  in
  2024                    (u, rest)
  2025                  end
  2026              | Sidecond t =>
  2027                  let
  2028                    val t = compile_arg compilation_modifiers additional_arguments
  2029                      ctxt param_vs iss t
  2030                    val rest = compile_prems [] vs' names'' ps;
  2031                  in
  2032                    (mk_if compfuns t, rest)
  2033                  end
  2034              | Generator (v, T) =>
  2035                  let
  2036                    val u = Comp_Mod.mk_random compilation_modifiers T additional_arguments
  2037                    val rest = compile_prems [Free (v, T)]  vs' names'' ps;
  2038                  in
  2039                    (u, rest)
  2040                  end
  2041           in
  2042             compile_match constr_vs' eqs out_ts''
  2043               (mk_bind compfuns (compiled_clause, rest))
  2044           end
  2045     val prem_t = compile_prems in_ts' param_vs all_vs' moded_ps;
  2046   in
  2047     mk_bind compfuns (mk_single compfuns inp, prem_t)
  2048   end
  2049 
  2050 fun compile_pred compilation_modifiers thy all_vs param_vs s T (pol, mode) moded_cls =
  2051   let
  2052     val ctxt = ProofContext.init thy
  2053     val compilation_modifiers = if pol then compilation_modifiers else
  2054       negative_comp_modifiers_of compilation_modifiers
  2055     val additional_arguments = Comp_Mod.additional_arguments compilation_modifiers
  2056       (all_vs @ param_vs)
  2057     val compfuns = Comp_Mod.compfuns compilation_modifiers
  2058     fun is_param_type (T as Type ("fun",[_ , T'])) =
  2059       is_some (try (dest_predT compfuns) T) orelse is_param_type T'
  2060       | is_param_type T = is_some (try (dest_predT compfuns) T)
  2061     val (inpTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode
  2062       (binder_types T)
  2063     val predT = mk_predT compfuns (HOLogic.mk_tupleT outTs)
  2064     val funT = Comp_Mod.funT_of compilation_modifiers mode T
  2065     
  2066     val (in_ts, _) = fold_map (fold_map_aterms_prodT (curry HOLogic.mk_prod)
  2067       (fn T => fn (param_vs, names) =>
  2068         if is_param_type T then
  2069           (Free (hd param_vs, T), (tl param_vs, names))
  2070         else
  2071           let
  2072             val new = Name.variant names "x"
  2073           in (Free (new, T), (param_vs, new :: names)) end)) inpTs
  2074         (param_vs, (all_vs @ param_vs))
  2075     val in_ts' = map_filter (map_filter_prod
  2076       (fn t as Free (x, _) => if member (op =) param_vs x then NONE else SOME t | t => SOME t)) in_ts
  2077     val cl_ts =
  2078       map (compile_clause compilation_modifiers
  2079         ctxt all_vs param_vs additional_arguments mode (HOLogic.mk_tuple in_ts')) moded_cls;
  2080     val compilation = Comp_Mod.wrap_compilation compilation_modifiers compfuns
  2081       s T mode additional_arguments
  2082       (if null cl_ts then
  2083         mk_bot compfuns (HOLogic.mk_tupleT outTs)
  2084       else foldr1 (mk_sup compfuns) cl_ts)
  2085     val fun_const =
  2086       Const (function_name_of (Comp_Mod.compilation compilation_modifiers)
  2087       (ProofContext.theory_of ctxt) s mode, funT)
  2088   in
  2089     HOLogic.mk_Trueprop
  2090       (HOLogic.mk_eq (list_comb (fun_const, in_ts @ additional_arguments), compilation))
  2091   end;
  2092 
  2093 (* special setup for simpset *)                  
  2094 val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms HOL.simp_thms} @ [@{thm Pair_eq}])
  2095   setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
  2096   setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
  2097 
  2098 (* Definition of executable functions and their intro and elim rules *)
  2099 
  2100 fun print_arities arities = tracing ("Arities:\n" ^
  2101   cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
  2102     space_implode " -> " (map
  2103       (fn NONE => "X" | SOME k' => string_of_int k')
  2104         (ks @ [SOME k]))) arities));
  2105 
  2106 fun split_lambda (x as Free _) t = lambda x t
  2107   | split_lambda (Const ("Pair", _) $ t1 $ t2) t =
  2108     HOLogic.mk_split (split_lambda t1 (split_lambda t2 t))
  2109   | split_lambda (Const ("Product_Type.Unity", _)) t = Abs ("x", HOLogic.unitT, t)
  2110   | split_lambda t _ = raise (TERM ("split_lambda", [t]))
  2111 
  2112 fun strip_split_abs (Const ("split", _) $ t) = strip_split_abs t
  2113   | strip_split_abs (Abs (_, _, t)) = strip_split_abs t
  2114   | strip_split_abs t = t
  2115 
  2116 fun mk_args is_eval (m as Pair (m1, m2), T as Type ("*", [T1, T2])) names =
  2117     if eq_mode (m, Input) orelse eq_mode (m, Output) then
  2118       let
  2119         val x = Name.variant names "x"
  2120       in
  2121         (Free (x, T), x :: names)
  2122       end
  2123     else
  2124       let
  2125         val (t1, names') = mk_args is_eval (m1, T1) names
  2126         val (t2, names'') = mk_args is_eval (m2, T2) names'
  2127       in
  2128         (HOLogic.mk_prod (t1, t2), names'')
  2129       end
  2130   | mk_args is_eval ((m as Fun _), T) names =
  2131     let
  2132       val funT = funT_of PredicateCompFuns.compfuns m T
  2133       val x = Name.variant names "x"
  2134       val (args, _) = fold_map (mk_args is_eval) (strip_fun_mode m ~~ binder_types T) (x :: names)
  2135       val (inargs, outargs) = split_map_mode (fn _ => fn t => (SOME t, NONE)) m args
  2136       val t = fold_rev split_lambda args (PredicateCompFuns.mk_Eval
  2137         (list_comb (Free (x, funT), inargs), HOLogic.mk_tuple outargs))
  2138     in
  2139       (if is_eval then t else Free (x, funT), x :: names)
  2140     end
  2141   | mk_args is_eval (_, T) names =
  2142     let
  2143       val x = Name.variant names "x"
  2144     in
  2145       (Free (x, T), x :: names)
  2146     end
  2147 
  2148 fun create_intro_elim_rule mode defthm mode_id funT pred thy =
  2149   let
  2150     val funtrm = Const (mode_id, funT)
  2151     val Ts = binder_types (fastype_of pred)
  2152     val (args, argnames) = fold_map (mk_args true) (strip_fun_mode mode ~~ Ts) []
  2153     fun strip_eval _ t =
  2154       let
  2155         val t' = strip_split_abs t
  2156         val (r, _) = PredicateCompFuns.dest_Eval t'
  2157       in (SOME (fst (strip_comb r)), NONE) end
  2158     val (inargs, outargs) = split_map_mode strip_eval mode args
  2159     val eval_hoargs = ho_args_of mode args
  2160     val hoargTs = ho_argsT_of mode Ts
  2161     val hoarg_names' =
  2162       Name.variant_list argnames ((map (fn i => "x" ^ string_of_int i)) (1 upto (length hoargTs)))
  2163     val hoargs' = map2 (curry Free) hoarg_names' hoargTs
  2164     val args' = replace_ho_args mode hoargs' args
  2165     val predpropI = HOLogic.mk_Trueprop (list_comb (pred, args'))
  2166     val predpropE = HOLogic.mk_Trueprop (list_comb (pred, args))
  2167     val param_eqs = map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) eval_hoargs hoargs'
  2168     val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
  2169                     if null outargs then Free("y", HOLogic.unitT) else HOLogic.mk_tuple outargs))
  2170     val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
  2171                      HOLogic.mk_tuple outargs))
  2172     val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
  2173     val simprules = [defthm, @{thm eval_pred},
  2174       @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
  2175     val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
  2176     val introthm = Goal.prove (ProofContext.init thy)
  2177       (argnames @ hoarg_names' @ ["y"]) [] introtrm (fn _ => unfolddef_tac)
  2178     val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
  2179     val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
  2180     val elimthm = Goal.prove (ProofContext.init thy)
  2181       (argnames @ ["y", "P"]) [] elimtrm (fn _ => unfolddef_tac)
  2182     val opt_neg_introthm =
  2183       if is_all_input mode then
  2184         let
  2185           val neg_predpropI = HOLogic.mk_Trueprop (HOLogic.mk_not (list_comb (pred, args')))
  2186           val neg_funpropI =
  2187             HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval
  2188               (PredicateCompFuns.mk_not (list_comb (funtrm, inargs)), HOLogic.unit))
  2189           val neg_introtrm = Logic.list_implies (neg_predpropI :: param_eqs, neg_funpropI)
  2190           val tac =
  2191             Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps
  2192               (@{thm if_False} :: @{thm Predicate.not_pred_eq} :: simprules)) 1
  2193             THEN rtac @{thm Predicate.singleI} 1
  2194         in SOME (Goal.prove (ProofContext.init thy) (argnames @ hoarg_names') []
  2195             neg_introtrm (fn _ => tac))
  2196         end
  2197       else NONE
  2198   in
  2199     ((introthm, elimthm), opt_neg_introthm)
  2200   end
  2201 
  2202 fun create_constname_of_mode options thy prefix name T mode = 
  2203   let
  2204     val system_proposal = prefix ^ (Long_Name.base_name name)
  2205       ^ "_" ^ ascii_string_of_mode mode
  2206     val name = the_default system_proposal (proposed_names options name mode)
  2207   in
  2208     Sign.full_bname thy name
  2209   end;
  2210 
  2211 fun create_definitions options preds (name, modes) thy =
  2212   let
  2213     val compfuns = PredicateCompFuns.compfuns
  2214     val T = AList.lookup (op =) preds name |> the
  2215     fun create_definition mode thy =
  2216       let
  2217         val mode_cname = create_constname_of_mode options thy "" name T mode
  2218         val mode_cbasename = Long_Name.base_name mode_cname
  2219         val funT = funT_of compfuns mode T
  2220         val (args, _) = fold_map (mk_args true) ((strip_fun_mode mode) ~~ (binder_types T)) []
  2221         fun strip_eval m t =
  2222           let
  2223             val t' = strip_split_abs t
  2224             val (r, _) = PredicateCompFuns.dest_Eval t'
  2225           in (SOME (fst (strip_comb r)), NONE) end
  2226         val (inargs, outargs) = split_map_mode strip_eval mode args
  2227         val predterm = fold_rev split_lambda inargs
  2228           (PredicateCompFuns.mk_Enum (split_lambda (HOLogic.mk_tuple outargs)
  2229             (list_comb (Const (name, T), args))))
  2230         val lhs = Const (mode_cname, funT)
  2231         val def = Logic.mk_equals (lhs, predterm)
  2232         val ([definition], thy') = thy |>
  2233           Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
  2234           PureThy.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
  2235         val rules as ((intro, elim), _) =
  2236           create_intro_elim_rule mode definition mode_cname funT (Const (name, T)) thy'
  2237         in thy'
  2238           |> set_function_name Pred name mode mode_cname
  2239           |> add_predfun_data name mode (definition, rules)
  2240           |> PureThy.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
  2241           |> PureThy.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
  2242           |> Theory.checkpoint
  2243         end;
  2244   in
  2245     thy |> defined_function_of Pred name |> fold create_definition modes
  2246   end;
  2247 
  2248 fun define_functions comp_modifiers compfuns options preds (name, modes) thy =
  2249   let
  2250     val T = AList.lookup (op =) preds name |> the
  2251     fun create_definition mode thy =
  2252       let
  2253         val function_name_prefix = Comp_Mod.function_name_prefix comp_modifiers
  2254         val mode_cname = create_constname_of_mode options thy function_name_prefix name T mode
  2255         val funT = Comp_Mod.funT_of comp_modifiers mode T
  2256       in
  2257         thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
  2258         |> set_function_name (Comp_Mod.compilation comp_modifiers) name mode mode_cname
  2259       end;
  2260   in
  2261     thy
  2262     |> defined_function_of (Comp_Mod.compilation comp_modifiers) name
  2263     |> fold create_definition modes
  2264   end;
  2265 
  2266 (* Proving equivalence of term *)
  2267 
  2268 fun is_Type (Type _) = true
  2269   | is_Type _ = false
  2270 
  2271 (* returns true if t is an application of an datatype constructor *)
  2272 (* which then consequently would be splitted *)
  2273 (* else false *)
  2274 fun is_constructor thy t =
  2275   if (is_Type (fastype_of t)) then
  2276     (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
  2277       NONE => false
  2278     | SOME info => (let
  2279       val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
  2280       val (c, _) = strip_comb t
  2281       in (case c of
  2282         Const (name, _) => name mem_string constr_consts
  2283         | _ => false) end))
  2284   else false
  2285 
  2286 (* MAJOR FIXME:  prove_params should be simple
  2287  - different form of introrule for parameters ? *)
  2288 
  2289 fun prove_param options ctxt nargs t deriv =
  2290   let
  2291     val  (f, args) = strip_comb (Envir.eta_contract t)
  2292     val mode = head_mode_of deriv
  2293     val param_derivations = param_derivations_of deriv
  2294     val ho_args = ho_args_of mode args
  2295     val f_tac = case f of
  2296       Const (name, T) => simp_tac (HOL_basic_ss addsimps 
  2297          [@{thm eval_pred}, predfun_definition_of ctxt name mode,
  2298          @{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
  2299          @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
  2300     | Free _ =>
  2301       Subgoal.FOCUS_PREMS (fn {context = ctxt, params = params, prems, asms, concl, schematics} =>
  2302         let
  2303           val prems' = maps dest_conjunct_prem (take nargs prems)
  2304         in
  2305           MetaSimplifier.rewrite_goal_tac
  2306             (map (fn th => th RS @{thm sym} RS @{thm eq_reflection}) prems') 1
  2307         end) ctxt 1
  2308     | Abs _ => raise Fail "prove_param: No valid parameter term"
  2309   in
  2310     REPEAT_DETERM (rtac @{thm ext} 1)
  2311     THEN print_tac options "prove_param"
  2312     THEN f_tac 
  2313     THEN print_tac options "after prove_param"
  2314     THEN (REPEAT_DETERM (atac 1))
  2315     THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
  2316     THEN REPEAT_DETERM (rtac @{thm refl} 1)
  2317   end
  2318 
  2319 fun prove_expr options ctxt nargs (premposition : int) (t, deriv) =
  2320   case strip_comb t of
  2321     (Const (name, T), args) =>
  2322       let
  2323         val mode = head_mode_of deriv
  2324         val introrule = predfun_intro_of ctxt name mode
  2325         val param_derivations = param_derivations_of deriv
  2326         val ho_args = ho_args_of mode args
  2327       in
  2328         print_tac options "before intro rule:"
  2329         THEN rtac introrule 1
  2330         THEN print_tac options "after intro rule"
  2331         (* for the right assumption in first position *)
  2332         THEN rotate_tac premposition 1
  2333         THEN atac 1
  2334         THEN print_tac options "parameter goal"
  2335         (* work with parameter arguments *)
  2336         THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
  2337         THEN (REPEAT_DETERM (atac 1))
  2338       end
  2339   | (Free _, _) =>
  2340     print_tac options "proving parameter call.."
  2341     THEN Subgoal.FOCUS_PREMS (fn {context = ctxt, params, prems, asms, concl, schematics} =>
  2342         let
  2343           val param_prem = nth prems premposition
  2344           val (param, _) = strip_comb (HOLogic.dest_Trueprop (prop_of param_prem))
  2345           val prems' = maps dest_conjunct_prem (take nargs prems)
  2346           fun param_rewrite prem =
  2347             param = snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of prem)))
  2348           val SOME rew_eq = find_first param_rewrite prems'
  2349           val param_prem' = MetaSimplifier.rewrite_rule
  2350             (map (fn th => th RS @{thm eq_reflection})
  2351               [rew_eq RS @{thm sym}, @{thm split_beta}, @{thm fst_conv}, @{thm snd_conv}])
  2352             param_prem
  2353         in
  2354           rtac param_prem' 1
  2355         end) ctxt 1
  2356     THEN print_tac options "after prove parameter call"
  2357 
  2358 fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st;
  2359 
  2360 fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
  2361 
  2362 fun check_format ctxt st =
  2363   let
  2364     val concl' = Logic.strip_assums_concl (hd (prems_of st))
  2365     val concl = HOLogic.dest_Trueprop concl'
  2366     val expr = fst (strip_comb (fst (PredicateCompFuns.dest_Eval concl)))
  2367     fun valid_expr (Const (@{const_name Predicate.bind}, _)) = true
  2368       | valid_expr (Const (@{const_name Predicate.single}, _)) = true
  2369       | valid_expr _ = false
  2370   in
  2371     if valid_expr expr then
  2372       ((*tracing "expression is valid";*) Seq.single st)
  2373     else
  2374       ((*tracing "expression is not valid";*) Seq.empty) (*error "check_format: wrong format"*)
  2375   end
  2376 
  2377 fun prove_match options ctxt out_ts =
  2378   let
  2379     val thy = ProofContext.theory_of ctxt
  2380     fun get_case_rewrite t =
  2381       if (is_constructor thy t) then let
  2382         val case_rewrites = (#case_rewrites (Datatype.the_info thy
  2383           ((fst o dest_Type o fastype_of) t)))
  2384         in case_rewrites @ maps get_case_rewrite (snd (strip_comb t)) end
  2385       else []
  2386     val simprules = @{thm "unit.cases"} :: @{thm "prod.cases"} :: maps get_case_rewrite out_ts
  2387   (* replace TRY by determining if it necessary - are there equations when calling compile match? *)
  2388   in
  2389      (* make this simpset better! *)
  2390     asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
  2391     THEN print_tac options "after prove_match:"
  2392     THEN (DETERM (TRY (EqSubst.eqsubst_tac ctxt [0] [@{thm HOL.if_P}] 1
  2393            THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1))))
  2394            THEN print_tac options "if condition to be solved:"
  2395            THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1 THEN print_tac options "after if simp; in SOLVED:"))
  2396            THEN check_format thy
  2397            THEN print_tac options "after if simplification - a TRY block")))
  2398     THEN print_tac options "after if simplification"
  2399   end;
  2400 
  2401 (* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
  2402 
  2403 fun prove_sidecond ctxt t =
  2404   let
  2405     val thy = ProofContext.theory_of ctxt
  2406     fun preds_of t nameTs = case strip_comb t of 
  2407       (f as Const (name, T), args) =>
  2408         if is_registered thy name then (name, T) :: nameTs
  2409           else fold preds_of args nameTs
  2410       | _ => nameTs
  2411     val preds = preds_of t []
  2412     val defs = map
  2413       (fn (pred, T) => predfun_definition_of ctxt pred
  2414         (all_input_of T))
  2415         preds
  2416   in 
  2417     (* remove not_False_eq_True when simpset in prove_match is better *)
  2418     simp_tac (HOL_basic_ss addsimps
  2419       (@{thms HOL.simp_thms} @ (@{thm not_False_eq_True} :: @{thm eval_pred} :: defs))) 1 
  2420     (* need better control here! *)
  2421   end
  2422 
  2423 fun prove_clause options ctxt nargs mode (_, clauses) (ts, moded_ps) =
  2424   let
  2425     val (in_ts, clause_out_ts) = split_mode mode ts;
  2426     fun prove_prems out_ts [] =
  2427       (prove_match options ctxt out_ts)
  2428       THEN print_tac options "before simplifying assumptions"
  2429       THEN asm_full_simp_tac HOL_basic_ss' 1
  2430       THEN print_tac options "before single intro rule"
  2431       THEN (rtac (if null clause_out_ts then @{thm singleI_unit} else @{thm singleI}) 1)
  2432     | prove_prems out_ts ((p, deriv) :: ps) =
  2433       let
  2434         val premposition = (find_index (equal p) clauses) + nargs
  2435         val mode = head_mode_of deriv
  2436         val rest_tac =
  2437           rtac @{thm bindI} 1
  2438           THEN (case p of Prem t =>
  2439             let
  2440               val (_, us) = strip_comb t
  2441               val (_, out_ts''') = split_mode mode us
  2442               val rec_tac = prove_prems out_ts''' ps
  2443             in
  2444               print_tac options "before clause:"
  2445               (*THEN asm_simp_tac HOL_basic_ss 1*)
  2446               THEN print_tac options "before prove_expr:"
  2447               THEN prove_expr options ctxt nargs premposition (t, deriv)
  2448               THEN print_tac options "after prove_expr:"
  2449               THEN rec_tac
  2450             end
  2451           | Negprem t =>
  2452             let
  2453               val (t, args) = strip_comb t
  2454               val (_, out_ts''') = split_mode mode args
  2455               val rec_tac = prove_prems out_ts''' ps
  2456               val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  2457               val neg_intro_rule =
  2458                 Option.map (fn name =>
  2459                   the (predfun_neg_intro_of ctxt name mode)) name
  2460               val param_derivations = param_derivations_of deriv
  2461               val params = ho_args_of mode args
  2462             in
  2463               print_tac options "before prove_neg_expr:"
  2464               THEN full_simp_tac (HOL_basic_ss addsimps
  2465                 [@{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
  2466                  @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
  2467               THEN (if (is_some name) then
  2468                   print_tac options "before applying not introduction rule"
  2469                   THEN rotate_tac premposition 1
  2470                   THEN etac (the neg_intro_rule) 1
  2471                   THEN rotate_tac (~premposition) 1
  2472                   THEN print_tac options "after applying not introduction rule"
  2473                   THEN (EVERY (map2 (prove_param options ctxt nargs) params param_derivations))
  2474                   THEN (REPEAT_DETERM (atac 1))
  2475                 else
  2476                   rtac @{thm not_predI'} 1
  2477                   (* test: *)
  2478                   THEN dtac @{thm sym} 1
  2479                   THEN asm_full_simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1)
  2480                   THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  2481               THEN rec_tac
  2482             end
  2483           | Sidecond t =>
  2484            rtac @{thm if_predI} 1
  2485            THEN print_tac options "before sidecond:"
  2486            THEN prove_sidecond ctxt t
  2487            THEN print_tac options "after sidecond:"
  2488            THEN prove_prems [] ps)
  2489       in (prove_match options ctxt out_ts)
  2490           THEN rest_tac
  2491       end;
  2492     val prems_tac = prove_prems in_ts moded_ps
  2493   in
  2494     print_tac options "Proving clause..."
  2495     THEN rtac @{thm bindI} 1
  2496     THEN rtac @{thm singleI} 1
  2497     THEN prems_tac
  2498   end;
  2499 
  2500 fun select_sup 1 1 = []
  2501   | select_sup _ 1 = [rtac @{thm supI1}]
  2502   | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
  2503 
  2504 fun prove_one_direction options ctxt clauses preds pred mode moded_clauses =
  2505   let
  2506     val thy = ProofContext.theory_of ctxt
  2507     val T = the (AList.lookup (op =) preds pred)
  2508     val nargs = length (binder_types T)
  2509     val pred_case_rule = the_elim_of thy pred
  2510   in
  2511     REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"}))
  2512     THEN print_tac options "before applying elim rule"
  2513     THEN etac (predfun_elim_of ctxt pred mode) 1
  2514     THEN etac pred_case_rule 1
  2515     THEN print_tac options "after applying elim rule"
  2516     THEN (EVERY (map
  2517            (fn i => EVERY' (select_sup (length moded_clauses) i) i) 
  2518              (1 upto (length moded_clauses))))
  2519     THEN (EVERY (map2 (prove_clause options ctxt nargs mode) clauses moded_clauses))
  2520     THEN print_tac options "proved one direction"
  2521   end;
  2522 
  2523 (** Proof in the other direction **)
  2524 
  2525 fun prove_match2 options ctxt out_ts =
  2526   let
  2527     val thy = ProofContext.theory_of ctxt
  2528     fun split_term_tac (Free _) = all_tac
  2529       | split_term_tac t =
  2530         if (is_constructor thy t) then
  2531           let
  2532             val info = Datatype.the_info thy ((fst o dest_Type o fastype_of) t)
  2533             val num_of_constrs = length (#case_rewrites info)
  2534             val (_, ts) = strip_comb t
  2535           in
  2536             print_tac options ("Term " ^ (Syntax.string_of_term ctxt t) ^ 
  2537               "splitting with rules \n" ^ Display.string_of_thm ctxt (#split_asm info))
  2538             THEN TRY ((Splitter.split_asm_tac [#split_asm info] 1)
  2539               THEN (print_tac options "after splitting with split_asm rules")
  2540             (* THEN (Simplifier.asm_full_simp_tac HOL_basic_ss 1)
  2541               THEN (DETERM (TRY (etac @{thm Pair_inject} 1)))*)
  2542               THEN (REPEAT_DETERM_N (num_of_constrs - 1)
  2543                 (etac @{thm botE} 1 ORELSE etac @{thm botE} 2)))
  2544             THEN (assert_tac (Max_number_of_subgoals 2))
  2545             THEN (EVERY (map split_term_tac ts))
  2546           end
  2547       else all_tac
  2548   in
  2549     split_term_tac (HOLogic.mk_tuple out_ts)
  2550     THEN (DETERM (TRY ((Splitter.split_asm_tac [@{thm "split_if_asm"}] 1)
  2551     THEN (etac @{thm botE} 2))))
  2552   end
  2553 
  2554 (* VERY LARGE SIMILIRATIY to function prove_param 
  2555 -- join both functions
  2556 *)
  2557 (* TODO: remove function *)
  2558 
  2559 fun prove_param2 options ctxt t deriv =
  2560   let
  2561     val (f, args) = strip_comb (Envir.eta_contract t)
  2562     val mode = head_mode_of deriv
  2563     val param_derivations = param_derivations_of deriv
  2564     val ho_args = ho_args_of mode args
  2565     val f_tac = case f of
  2566         Const (name, T) => full_simp_tac (HOL_basic_ss addsimps 
  2567            (@{thm eval_pred}::(predfun_definition_of ctxt name mode)
  2568            :: @{thm "Product_Type.split_conv"}::[])) 1
  2569       | Free _ => all_tac
  2570       | _ => error "prove_param2: illegal parameter term"
  2571   in
  2572     print_tac options "before simplification in prove_args:"
  2573     THEN f_tac
  2574     THEN print_tac options "after simplification in prove_args"
  2575     THEN EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations)
  2576   end
  2577 
  2578 fun prove_expr2 options ctxt (t, deriv) = 
  2579   (case strip_comb t of
  2580       (Const (name, T), args) =>
  2581         let
  2582           val mode = head_mode_of deriv
  2583           val param_derivations = param_derivations_of deriv
  2584           val ho_args = ho_args_of mode args
  2585         in
  2586           etac @{thm bindE} 1
  2587           THEN (REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"})))
  2588           THEN print_tac options "prove_expr2-before"
  2589           THEN etac (predfun_elim_of ctxt name mode) 1
  2590           THEN print_tac options "prove_expr2"
  2591           THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
  2592           THEN print_tac options "finished prove_expr2"
  2593         end
  2594       | _ => etac @{thm bindE} 1)
  2595 
  2596 fun prove_sidecond2 options ctxt t = let
  2597   fun preds_of t nameTs = case strip_comb t of 
  2598     (f as Const (name, T), args) =>
  2599       if is_registered (ProofContext.theory_of ctxt) name then (name, T) :: nameTs
  2600         else fold preds_of args nameTs
  2601     | _ => nameTs
  2602   val preds = preds_of t []
  2603   val defs = map
  2604     (fn (pred, T) => predfun_definition_of ctxt pred 
  2605       (all_input_of T))
  2606       preds
  2607   in
  2608    (* only simplify the one assumption *)
  2609    full_simp_tac (HOL_basic_ss' addsimps @{thm eval_pred} :: defs) 1 
  2610    (* need better control here! *)
  2611    THEN print_tac options "after sidecond2 simplification"
  2612    end
  2613   
  2614 fun prove_clause2 options ctxt pred mode (ts, ps) i =
  2615   let
  2616     val pred_intro_rule = nth (intros_of (ProofContext.theory_of ctxt) pred) (i - 1)
  2617     val (in_ts, clause_out_ts) = split_mode mode ts;
  2618     fun prove_prems2 out_ts [] =
  2619       print_tac options "before prove_match2 - last call:"
  2620       THEN prove_match2 options ctxt out_ts
  2621       THEN print_tac options "after prove_match2 - last call:"
  2622       THEN (etac @{thm singleE} 1)
  2623       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  2624       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  2625       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  2626       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  2627       THEN SOLVED (print_tac options "state before applying intro rule:"
  2628       THEN (rtac pred_intro_rule 1)
  2629       (* How to handle equality correctly? *)
  2630       THEN (print_tac options "state before assumption matching")
  2631       THEN (REPEAT (atac 1 ORELSE 
  2632          (CHANGED (asm_full_simp_tac (HOL_basic_ss' addsimps
  2633            [@{thm split_eta}, @{thm "split_beta"}, @{thm "fst_conv"},
  2634              @{thm "snd_conv"}, @{thm pair_collapse}]) 1)
  2635           THEN print_tac options "state after simp_tac:"))))
  2636     | prove_prems2 out_ts ((p, deriv) :: ps) =
  2637       let
  2638         val mode = head_mode_of deriv
  2639         val rest_tac = (case p of
  2640           Prem t =>
  2641           let
  2642             val (_, us) = strip_comb t
  2643             val (_, out_ts''') = split_mode mode us
  2644             val rec_tac = prove_prems2 out_ts''' ps
  2645           in
  2646             (prove_expr2 options ctxt (t, deriv)) THEN rec_tac
  2647           end
  2648         | Negprem t =>
  2649           let
  2650             val (_, args) = strip_comb t
  2651             val (_, out_ts''') = split_mode mode args
  2652             val rec_tac = prove_prems2 out_ts''' ps
  2653             val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  2654             val param_derivations = param_derivations_of deriv
  2655             val ho_args = ho_args_of mode args
  2656           in
  2657             print_tac options "before neg prem 2"
  2658             THEN etac @{thm bindE} 1
  2659             THEN (if is_some name then
  2660                 full_simp_tac (HOL_basic_ss addsimps
  2661                   [predfun_definition_of ctxt (the name) mode]) 1
  2662                 THEN etac @{thm not_predE} 1
  2663                 THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  2664                 THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
  2665               else
  2666                 etac @{thm not_predE'} 1)
  2667             THEN rec_tac
  2668           end 
  2669         | Sidecond t =>
  2670           etac @{thm bindE} 1
  2671           THEN etac @{thm if_predE} 1
  2672           THEN prove_sidecond2 options ctxt t
  2673           THEN prove_prems2 [] ps)
  2674       in print_tac options "before prove_match2:"
  2675          THEN prove_match2 options ctxt out_ts
  2676          THEN print_tac options "after prove_match2:"
  2677          THEN rest_tac
  2678       end;
  2679     val prems_tac = prove_prems2 in_ts ps 
  2680   in
  2681     print_tac options "starting prove_clause2"
  2682     THEN etac @{thm bindE} 1
  2683     THEN (etac @{thm singleE'} 1)
  2684     THEN (TRY (etac @{thm Pair_inject} 1))
  2685     THEN print_tac options "after singleE':"
  2686     THEN prems_tac
  2687   end;
  2688  
  2689 fun prove_other_direction options ctxt pred mode moded_clauses =
  2690   let
  2691     fun prove_clause clause i =
  2692       (if i < length moded_clauses then etac @{thm supE} 1 else all_tac)
  2693       THEN (prove_clause2 options ctxt pred mode clause i)
  2694   in
  2695     (DETERM (TRY (rtac @{thm unit.induct} 1)))
  2696      THEN (REPEAT_DETERM (CHANGED (rewtac @{thm split_paired_all})))
  2697      THEN (rtac (predfun_intro_of ctxt pred mode) 1)
  2698      THEN (REPEAT_DETERM (rtac @{thm refl} 2))
  2699      THEN (if null moded_clauses then
  2700          etac @{thm botE} 1
  2701        else EVERY (map2 prove_clause moded_clauses (1 upto (length moded_clauses))))
  2702   end;
  2703 
  2704 (** proof procedure **)
  2705 
  2706 fun prove_pred options thy clauses preds pred (pol, mode) (moded_clauses, compiled_term) =
  2707   let
  2708     val ctxt = ProofContext.init thy
  2709     val clauses = case AList.lookup (op =) clauses pred of SOME rs => rs | NONE => []
  2710   in
  2711     Goal.prove ctxt (Term.add_free_names compiled_term []) [] compiled_term
  2712       (if not (skip_proof options) then
  2713         (fn _ =>
  2714         rtac @{thm pred_iffI} 1
  2715         THEN print_tac options "after pred_iffI"
  2716         THEN prove_one_direction options ctxt clauses preds pred mode moded_clauses
  2717         THEN print_tac options "proved one direction"
  2718         THEN prove_other_direction options ctxt pred mode moded_clauses
  2719         THEN print_tac options "proved other direction")
  2720       else (fn _ => Skip_Proof.cheat_tac thy))
  2721   end;
  2722 
  2723 (* composition of mode inference, definition, compilation and proof *)
  2724 
  2725 (** auxillary combinators for table of preds and modes **)
  2726 
  2727 fun map_preds_modes f preds_modes_table =
  2728   map (fn (pred, modes) =>
  2729     (pred, map (fn (mode, value) => (mode, f pred mode value)) modes)) preds_modes_table
  2730 
  2731 fun join_preds_modes table1 table2 =
  2732   map_preds_modes (fn pred => fn mode => fn value =>
  2733     (value, the (AList.lookup (op =) (the (AList.lookup (op =) table2 pred)) mode))) table1
  2734     
  2735 fun maps_modes preds_modes_table =
  2736   map (fn (pred, modes) =>
  2737     (pred, map (fn (mode, value) => value) modes)) preds_modes_table
  2738     
  2739 fun compile_preds comp_modifiers thy all_vs param_vs preds moded_clauses =
  2740   map_preds_modes (fn pred => compile_pred comp_modifiers thy all_vs param_vs pred
  2741       (the (AList.lookup (op =) preds pred))) moded_clauses
  2742 
  2743 fun prove options thy clauses preds moded_clauses compiled_terms =
  2744   map_preds_modes (prove_pred options thy clauses preds)
  2745     (join_preds_modes moded_clauses compiled_terms)
  2746 
  2747 fun prove_by_skip options thy _ _ _ compiled_terms =
  2748   map_preds_modes
  2749     (fn pred => fn mode => fn t => Drule.export_without_context (Skip_Proof.make_thm thy t))
  2750     compiled_terms
  2751 
  2752 (* preparation of introduction rules into special datastructures *)
  2753 
  2754 fun dest_prem thy params t =
  2755   (case strip_comb t of
  2756     (v as Free _, ts) => if member (op =) params v then Prem t else Sidecond t
  2757   | (c as Const (@{const_name Not}, _), [t]) => (case dest_prem thy params t of
  2758       Prem t => Negprem t
  2759     | Negprem _ => error ("Double negation not allowed in premise: " ^
  2760         Syntax.string_of_term_global thy (c $ t)) 
  2761     | Sidecond t => Sidecond (c $ t))
  2762   | (c as Const (s, _), ts) =>
  2763     if is_registered thy s then Prem t else Sidecond t
  2764   | _ => Sidecond t)
  2765 
  2766 fun prepare_intrs options compilation thy prednames intros =
  2767   let
  2768     val intrs = map prop_of intros
  2769     val preds = map (fn c => Const (c, Sign.the_const_type thy c)) prednames
  2770     val (preds, intrs) = unify_consts thy preds intrs
  2771     val ([preds, intrs], _) = fold_burrow (Variable.import_terms false) [preds, intrs]
  2772       (ProofContext.init thy)
  2773     val preds = map dest_Const preds
  2774     val all_vs = terms_vs intrs
  2775     val all_modes = 
  2776       map (fn (s, T) =>
  2777         (s,
  2778             (if member (op =) (no_higher_order_predicate options) s then
  2779                (all_smodes_of_typ T)
  2780             else (all_modes_of_typ T)))) preds
  2781     val params =
  2782       case intrs of
  2783         [] =>
  2784           let
  2785             val T = snd (hd preds)
  2786             val paramTs =
  2787               ho_argsT_of (hd (all_modes_of_typ T)) (binder_types T)
  2788             val param_names = Name.variant_list [] (map (fn i => "p" ^ string_of_int i)
  2789               (1 upto length paramTs))
  2790           in
  2791             map2 (curry Free) param_names paramTs
  2792           end
  2793       | (intr :: _) =>
  2794         let
  2795           val (p, args) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr)) 
  2796         in
  2797           ho_args_of (hd (the (AList.lookup (op =) all_modes (fst (dest_Const p))))) args
  2798         end
  2799     val param_vs = map (fst o dest_Free) params
  2800     fun add_clause intr clauses =
  2801       let
  2802         val (Const (name, T), ts) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr))
  2803         val prems = map (dest_prem thy params o HOLogic.dest_Trueprop) (Logic.strip_imp_prems intr)
  2804       in
  2805         AList.update op = (name, these (AList.lookup op = clauses name) @
  2806           [(ts, prems)]) clauses
  2807       end;
  2808     val clauses = fold add_clause intrs []
  2809   in
  2810     (preds, all_vs, param_vs, all_modes, clauses)
  2811   end;
  2812 
  2813 (* sanity check of introduction rules *)
  2814 (* TODO: rethink check with new modes *)
  2815 (*
  2816 fun check_format_of_intro_rule thy intro =
  2817   let
  2818     val concl = Logic.strip_imp_concl (prop_of intro)
  2819     val (p, args) = strip_comb (HOLogic.dest_Trueprop concl)
  2820     val params = fst (chop (nparams_of thy (fst (dest_Const p))) args)
  2821     fun check_arg arg = case HOLogic.strip_tupleT (fastype_of arg) of
  2822       (Ts as _ :: _ :: _) =>
  2823         if length (HOLogic.strip_tuple arg) = length Ts then
  2824           true
  2825         else
  2826           error ("Format of introduction rule is invalid: tuples must be expanded:"
  2827           ^ (Syntax.string_of_term_global thy arg) ^ " in " ^
  2828           (Display.string_of_thm_global thy intro)) 
  2829       | _ => true
  2830     val prems = Logic.strip_imp_prems (prop_of intro)
  2831     fun check_prem (Prem t) = forall check_arg args
  2832       | check_prem (Negprem t) = forall check_arg args
  2833       | check_prem _ = true
  2834   in
  2835     forall check_arg args andalso
  2836     forall (check_prem o dest_prem thy params o HOLogic.dest_Trueprop) prems
  2837   end
  2838 *)
  2839 (*
  2840 fun check_intros_elim_match thy prednames =
  2841   let
  2842     fun check predname =
  2843       let
  2844         val intros = intros_of thy predname
  2845         val elim = the_elim_of thy predname
  2846         val nparams = nparams_of thy predname
  2847         val elim' =
  2848           (Drule.export_without_context o Skip_Proof.make_thm thy)
  2849           (mk_casesrule (ProofContext.init thy) nparams intros)
  2850       in
  2851         if not (Thm.equiv_thm (elim, elim')) then
  2852           error "Introduction and elimination rules do not match!"
  2853         else true
  2854       end
  2855   in forall check prednames end
  2856 *)
  2857 
  2858 (* create code equation *)
  2859 
  2860 fun add_code_equations thy preds result_thmss =
  2861   let
  2862     val ctxt = ProofContext.init thy
  2863     fun add_code_equation (predname, T) (pred, result_thms) =
  2864       let
  2865         val full_mode = fold_rev (curry Fun) (map (K Input) (binder_types T)) Bool
  2866       in
  2867         if member (op =) (modes_of Pred thy predname) full_mode then
  2868           let
  2869             val Ts = binder_types T
  2870             val arg_names = Name.variant_list []
  2871               (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
  2872             val args = map2 (curry Free) arg_names Ts
  2873             val predfun = Const (function_name_of Pred thy predname full_mode,
  2874               Ts ---> PredicateCompFuns.mk_predT @{typ unit})
  2875             val rhs = @{term Predicate.holds} $ (list_comb (predfun, args))
  2876             val eq_term = HOLogic.mk_Trueprop
  2877               (HOLogic.mk_eq (list_comb (Const (predname, T), args), rhs))
  2878             val def = predfun_definition_of ctxt predname full_mode
  2879             val tac = fn _ => Simplifier.simp_tac
  2880               (HOL_basic_ss addsimps [def, @{thm holds_eq}, @{thm eval_pred}]) 1
  2881             val eq = Goal.prove ctxt arg_names [] eq_term tac
  2882           in
  2883             (pred, result_thms @ [eq])
  2884           end
  2885         else
  2886           (pred, result_thms)
  2887       end
  2888   in
  2889     map2 add_code_equation preds result_thmss
  2890   end
  2891 
  2892 (** main function of predicate compiler **)
  2893 
  2894 datatype steps = Steps of
  2895   {
  2896   define_functions : options -> (string * typ) list -> string * (bool * mode) list -> theory -> theory,
  2897   (*infer_modes : options -> (string * typ) list -> (string * mode list) list
  2898     -> string list -> (string * (term list * indprem list) list) list
  2899     -> theory -> ((moded_clause list pred_mode_table * string list) * theory),*)
  2900   prove : options -> theory -> (string * (term list * indprem list) list) list -> (string * typ) list
  2901     -> moded_clause list pred_mode_table -> term pred_mode_table -> thm pred_mode_table,
  2902   add_code_equations : theory -> (string * typ) list
  2903     -> (string * thm list) list -> (string * thm list) list,
  2904   comp_modifiers : Comp_Mod.comp_modifiers,
  2905   use_random : bool,
  2906   qname : bstring
  2907   }
  2908 
  2909 fun add_equations_of steps mode_analysis_options options prednames thy =
  2910   let
  2911     fun dest_steps (Steps s) = s
  2912     val compilation = Comp_Mod.compilation (#comp_modifiers (dest_steps steps))
  2913     val _ = print_step options
  2914       ("Starting predicate compiler (compilation: " ^ string_of_compilation compilation
  2915         ^ ") for predicates " ^ commas prednames ^ "...")
  2916       (*val _ = check_intros_elim_match thy prednames*)
  2917       (*val _ = map (check_format_of_intro_rule thy) (maps (intros_of thy) prednames)*)
  2918     val _ =
  2919       if show_intermediate_results options then
  2920         tracing (commas (map (Display.string_of_thm_global thy) (maps (intros_of thy) prednames)))
  2921       else ()
  2922     val (preds, all_vs, param_vs, all_modes, clauses) =
  2923       prepare_intrs options compilation thy prednames (maps (intros_of thy) prednames)
  2924     val _ = print_step options "Infering modes..."
  2925     val ((moded_clauses, errors), thy') =
  2926       (*Output.cond_timeit true "Infering modes"
  2927       (fn _ =>*) infer_modes mode_analysis_options
  2928         options compilation preds all_modes param_vs clauses thy
  2929     val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
  2930     val _ = check_expected_modes preds options modes
  2931     (*val _ = check_proposed_modes preds options modes (fst extra_modes) errors*)
  2932     val _ = print_modes options thy' modes
  2933     val _ = print_step options "Defining executable functions..."
  2934     val thy'' = fold (#define_functions (dest_steps steps) options preds) modes thy'
  2935       |> Theory.checkpoint
  2936     val _ = print_step options "Compiling equations..."
  2937     val compiled_terms =
  2938       compile_preds (#comp_modifiers (dest_steps steps)) thy'' all_vs param_vs preds moded_clauses
  2939     val _ = print_compiled_terms options thy'' compiled_terms
  2940     val _ = print_step options "Proving equations..."
  2941     val result_thms =
  2942       #prove (dest_steps steps) options thy'' clauses preds moded_clauses compiled_terms
  2943     val result_thms' = #add_code_equations (dest_steps steps) thy'' preds
  2944       (maps_modes result_thms)
  2945     val qname = #qname (dest_steps steps)
  2946     val attrib = fn thy => Attrib.attribute_i thy (Attrib.internal (K (Thm.declaration_attribute
  2947       (fn thm => Context.mapping (Code.add_eqn thm) I))))
  2948     val thy''' = fold (fn (name, result_thms) => fn thy => snd (PureThy.add_thmss
  2949       [((Binding.qualify true (Long_Name.base_name name) (Binding.name qname), result_thms),
  2950         [attrib thy ])] thy))
  2951       result_thms' thy'' |> Theory.checkpoint
  2952   in
  2953     thy'''
  2954   end
  2955 
  2956 fun extend' value_of edges_of key (G, visited) =
  2957   let
  2958     val (G', v) = case try (Graph.get_node G) key of
  2959         SOME v => (G, v)
  2960       | NONE => (Graph.new_node (key, value_of key) G, value_of key)
  2961     val (G'', visited') = fold (extend' value_of edges_of)
  2962       (subtract (op =) visited (edges_of (key, v)))
  2963       (G', key :: visited)
  2964   in
  2965     (fold (Graph.add_edge o (pair key)) (edges_of (key, v)) G'', visited')
  2966   end;
  2967 
  2968 fun extend value_of edges_of key G = fst (extend' value_of edges_of key (G, [])) 
  2969   
  2970 fun gen_add_equations steps options names thy =
  2971   let
  2972     fun dest_steps (Steps s) = s
  2973     val defined = defined_functions (Comp_Mod.compilation (#comp_modifiers (dest_steps steps)))
  2974     val thy' = thy
  2975       |> PredData.map (fold (extend (fetch_pred_data thy) (depending_preds_of thy)) names)
  2976       |> Theory.checkpoint;
  2977     fun strong_conn_of gr keys =
  2978       Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
  2979     val scc = strong_conn_of (PredData.get thy') names
  2980     
  2981     val thy'' = fold_rev
  2982       (fn preds => fn thy =>
  2983         if not (forall (defined thy) preds) then
  2984           let
  2985             val mode_analysis_options = {use_random = #use_random (dest_steps steps),
  2986               reorder_premises =
  2987                 not (no_topmost_reordering options andalso not (null (inter (op =) preds names))),
  2988               infer_pos_and_neg_modes = #use_random (dest_steps steps)}
  2989           in
  2990             add_equations_of steps mode_analysis_options options preds thy
  2991           end
  2992         else thy)
  2993       scc thy' |> Theory.checkpoint
  2994   in thy'' end
  2995 
  2996 val add_equations = gen_add_equations
  2997   (Steps {
  2998   define_functions =
  2999     fn options => fn preds => fn (s, modes) =>
  3000       create_definitions
  3001       options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3002   prove = prove,
  3003   add_code_equations = add_code_equations,
  3004   comp_modifiers = predicate_comp_modifiers,
  3005   use_random = false,
  3006   qname = "equation"})
  3007 
  3008 val add_depth_limited_equations = gen_add_equations
  3009   (Steps {
  3010   define_functions =
  3011     fn options => fn preds => fn (s, modes) =>
  3012     define_functions depth_limited_comp_modifiers PredicateCompFuns.compfuns
  3013     options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3014   prove = prove_by_skip,
  3015   add_code_equations = K (K I),
  3016   comp_modifiers = depth_limited_comp_modifiers,
  3017   use_random = false,
  3018   qname = "depth_limited_equation"})
  3019 
  3020 val add_annotated_equations = gen_add_equations
  3021   (Steps {
  3022   define_functions =
  3023     fn options => fn preds => fn (s, modes) =>
  3024       define_functions annotated_comp_modifiers PredicateCompFuns.compfuns options preds
  3025       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3026   prove = prove_by_skip,
  3027   add_code_equations = K (K I),
  3028   comp_modifiers = annotated_comp_modifiers,
  3029   use_random = false,
  3030   qname = "annotated_equation"})
  3031 
  3032 val add_random_equations = gen_add_equations
  3033   (Steps {
  3034   define_functions =
  3035     fn options => fn preds => fn (s, modes) =>
  3036       define_functions random_comp_modifiers PredicateCompFuns.compfuns options preds
  3037       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3038   comp_modifiers = random_comp_modifiers,
  3039   prove = prove_by_skip,
  3040   add_code_equations = K (K I),
  3041   use_random = true,
  3042   qname = "random_equation"})
  3043 
  3044 val add_depth_limited_random_equations = gen_add_equations
  3045   (Steps {
  3046   define_functions =
  3047     fn options => fn preds => fn (s, modes) =>
  3048       define_functions depth_limited_random_comp_modifiers PredicateCompFuns.compfuns options preds
  3049       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3050   comp_modifiers = depth_limited_random_comp_modifiers,
  3051   prove = prove_by_skip,
  3052   add_code_equations = K (K I),
  3053   use_random = true,
  3054   qname = "depth_limited_random_equation"})
  3055 
  3056 val add_dseq_equations = gen_add_equations
  3057   (Steps {
  3058   define_functions =
  3059   fn options => fn preds => fn (s, modes) =>
  3060     define_functions dseq_comp_modifiers DSequence_CompFuns.compfuns
  3061     options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  3062   prove = prove_by_skip,
  3063   add_code_equations = K (K I),
  3064   comp_modifiers = dseq_comp_modifiers,
  3065   use_random = false,
  3066   qname = "dseq_equation"})
  3067 
  3068 val add_random_dseq_equations = gen_add_equations
  3069   (Steps {
  3070   define_functions =
  3071     fn options => fn preds => fn (s, modes) =>
  3072     let
  3073       val pos_modes = map_filter (fn (true, m) => SOME m | _ => NONE) modes
  3074       val neg_modes = map_filter (fn (false, m) => SOME m | _ => NONE) modes
  3075     in define_functions pos_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
  3076       options preds (s, pos_modes)
  3077       #> define_functions neg_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
  3078       options preds (s, neg_modes)
  3079     end,
  3080   prove = prove_by_skip,
  3081   add_code_equations = K (K I),
  3082   comp_modifiers = pos_random_dseq_comp_modifiers,
  3083   use_random = true,
  3084   qname = "random_dseq_equation"})
  3085 
  3086 val add_new_random_dseq_equations = gen_add_equations
  3087   (Steps {
  3088   define_functions =
  3089     fn options => fn preds => fn (s, modes) =>
  3090     let
  3091       val pos_modes = map_filter (fn (true, m) => SOME m | _ => NONE) modes
  3092       val neg_modes = map_filter (fn (false, m) => SOME m | _ => NONE) modes
  3093     in define_functions new_pos_random_dseq_comp_modifiers New_Pos_Random_Sequence_CompFuns.compfuns
  3094       options preds (s, pos_modes)
  3095       #> define_functions new_neg_random_dseq_comp_modifiers New_Neg_Random_Sequence_CompFuns.compfuns
  3096       options preds (s, neg_modes)
  3097     end,
  3098   prove = prove_by_skip,
  3099   add_code_equations = K (K I),
  3100   comp_modifiers = new_pos_random_dseq_comp_modifiers,
  3101   use_random = true,
  3102   qname = "new_random_dseq_equation"})
  3103 
  3104 (** user interface **)
  3105 
  3106 (* code_pred_intro attribute *)
  3107 
  3108 fun attrib f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
  3109 
  3110 val code_pred_intro_attrib = attrib add_intro;
  3111 
  3112 
  3113 (*FIXME
  3114 - Naming of auxiliary rules necessary?
  3115 *)
  3116 
  3117 val setup = PredData.put (Graph.empty) #>
  3118   Attrib.setup @{binding code_pred_intro} (Scan.succeed (attrib add_intro))
  3119     "adding alternative introduction rules for code generation of inductive predicates"
  3120 
  3121 (* TODO: make Theory_Data to Generic_Data & remove duplication of local theory and theory *)
  3122 fun generic_code_pred prep_const options raw_const lthy =
  3123   let
  3124     val thy = ProofContext.theory_of lthy
  3125     val const = prep_const thy raw_const
  3126     val lthy' = Local_Theory.theory (PredData.map
  3127         (extend (fetch_pred_data thy) (depending_preds_of thy) const)) lthy
  3128     val thy' = ProofContext.theory_of lthy'
  3129     val preds = Graph.all_succs (PredData.get thy') [const] |> filter_out (has_elim thy')
  3130     fun mk_cases const =
  3131       let
  3132         val T = Sign.the_const_type thy const
  3133         val pred = Const (const, T)
  3134         val intros = intros_of thy' const
  3135       in mk_casesrule lthy' pred intros end  
  3136     val cases_rules = map mk_cases preds
  3137     val cases =
  3138       map (fn case_rule => Rule_Cases.Case {fixes = [],
  3139         assumes = [("", Logic.strip_imp_prems case_rule)],
  3140         binds = [], cases = []}) cases_rules
  3141     val case_env = map2 (fn p => fn c => (Long_Name.base_name p, SOME c)) preds cases
  3142     val lthy'' = lthy'
  3143       |> fold Variable.auto_fixes cases_rules 
  3144       |> ProofContext.add_cases true case_env
  3145     fun after_qed thms goal_ctxt =
  3146       let
  3147         val global_thms = ProofContext.export goal_ctxt
  3148           (ProofContext.init (ProofContext.theory_of goal_ctxt)) (map the_single thms)
  3149       in
  3150         goal_ctxt |> Local_Theory.theory (fold set_elim global_thms #>
  3151           ((case compilation options of
  3152              Pred => add_equations
  3153            | DSeq => add_dseq_equations
  3154            | Pos_Random_DSeq => add_random_dseq_equations
  3155            | Depth_Limited => add_depth_limited_equations
  3156            | Random => add_random_equations
  3157            | Depth_Limited_Random => add_depth_limited_random_equations
  3158            | New_Pos_Random_DSeq => add_new_random_dseq_equations
  3159            | compilation => error ("Compilation not supported")
  3160            ) options [const]))
  3161       end
  3162   in
  3163     Proof.theorem_i NONE after_qed (map (single o (rpair [])) cases_rules) lthy''
  3164   end;
  3165 
  3166 val code_pred = generic_code_pred (K I);
  3167 val code_pred_cmd = generic_code_pred Code.read_const
  3168 
  3169 (* transformation for code generation *)
  3170 
  3171 val eval_ref = Unsynchronized.ref (NONE : (unit -> term Predicate.pred) option);
  3172 val random_eval_ref =
  3173   Unsynchronized.ref (NONE : (unit -> int * int -> term Predicate.pred * (int * int)) option);
  3174 val dseq_eval_ref = Unsynchronized.ref (NONE : (unit -> term DSequence.dseq) option);
  3175 val random_dseq_eval_ref =
  3176   Unsynchronized.ref (NONE : (unit -> int -> int -> int * int -> term DSequence.dseq * (int * int)) option);
  3177 val new_random_dseq_eval_ref =
  3178   Unsynchronized.ref (NONE : (unit -> int -> int -> int * int -> int -> term Lazy_Sequence.lazy_sequence) option)
  3179 val new_random_dseq_stats_eval_ref =
  3180     Unsynchronized.ref (NONE :
  3181       (unit -> int -> int -> int * int -> int -> (term * int) Lazy_Sequence.lazy_sequence) option)
  3182 
  3183 (*FIXME turn this into an LCF-guarded preprocessor for comprehensions*)
  3184 fun analyze_compr thy compfuns param_user_modes (compilation, arguments) t_compr =
  3185   let
  3186     val all_modes_of = all_modes_of compilation
  3187     val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
  3188       | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term_global thy t_compr);
  3189     val (body, Ts, fp) = HOLogic.strip_psplits split;
  3190     val output_names = Name.variant_list (Term.add_free_names body [])
  3191       (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
  3192     val output_frees = map2 (curry Free) output_names (rev Ts)
  3193     val body = subst_bounds (output_frees, body)
  3194     val T_compr = HOLogic.mk_ptupleT fp Ts
  3195     val output_tuple = HOLogic.mk_ptuple fp T_compr (rev output_frees)
  3196     val (pred as Const (name, T), all_args) =
  3197       case strip_comb body of
  3198         (Const (name, T), all_args) => (Const (name, T), all_args)
  3199       | (head, _) => error ("Not a constant: " ^ Syntax.string_of_term_global thy head)
  3200   in
  3201     if defined_functions compilation thy name then
  3202       let
  3203         fun extract_mode (Const ("Pair", _) $ t1 $ t2) = Pair (extract_mode t1, extract_mode t2)
  3204           | extract_mode (Free (x, _)) = if member (op =) output_names x then Output else Input
  3205           | extract_mode _ = Input
  3206         val user_mode = fold_rev (curry Fun) (map extract_mode all_args) Bool
  3207         fun valid modes1 modes2 =
  3208           case int_ord (length modes1, length modes2) of
  3209             GREATER => error "Not enough mode annotations"
  3210           | LESS => error "Too many mode annotations"
  3211           | EQUAL => forall (fn (m, NONE) => true | (m, SOME m2) => eq_mode (m, m2))
  3212             (modes1 ~~ modes2)
  3213         fun mode_instance_of (m1, m2) =
  3214           let
  3215             fun instance_of (Fun _, Input) = true
  3216               | instance_of (Input, Input) = true
  3217               | instance_of (Output, Output) = true
  3218               | instance_of (Pair (m1, m2), Pair (m1', m2')) =
  3219                   instance_of  (m1, m1') andalso instance_of (m2, m2')
  3220               | instance_of (Pair (m1, m2), Input) =
  3221                   instance_of (m1, Input) andalso instance_of (m2, Input)
  3222               | instance_of (Pair (m1, m2), Output) =
  3223                   instance_of (m1, Output) andalso instance_of (m2, Output)
  3224               | instance_of _ = false
  3225           in forall instance_of (strip_fun_mode m1 ~~ strip_fun_mode m2) end
  3226         val derivs = all_derivations_of thy (all_modes_of thy) [] body
  3227           |> filter (fn (d, missing_vars) =>
  3228             let
  3229               val (p_mode :: modes) = collect_context_modes d
  3230             in
  3231               null missing_vars andalso
  3232               mode_instance_of (p_mode, user_mode) andalso
  3233               the_default true (Option.map (valid modes) param_user_modes)
  3234             end)
  3235           |> map fst
  3236         val deriv = case derivs of
  3237             [] => error ("No mode possible for comprehension "
  3238                     ^ Syntax.string_of_term_global thy t_compr)
  3239           | [d] => d
  3240           | d :: _ :: _ => (warning ("Multiple modes possible for comprehension "
  3241                     ^ Syntax.string_of_term_global thy t_compr); d);
  3242         val (_, outargs) = split_mode (head_mode_of deriv) all_args
  3243         val additional_arguments =
  3244           case compilation of
  3245             Pred => []
  3246           | Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
  3247             [@{term "(1, 1) :: code_numeral * code_numeral"}]
  3248           | Annotated => []
  3249           | Depth_Limited => [HOLogic.mk_number @{typ "code_numeral"} (hd arguments)]
  3250           | Depth_Limited_Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
  3251             [@{term "(1, 1) :: code_numeral * code_numeral"}]
  3252           | DSeq => []
  3253           | Pos_Random_DSeq => []
  3254           | New_Pos_Random_DSeq => []
  3255         val comp_modifiers =
  3256           case compilation of
  3257             Pred => predicate_comp_modifiers
  3258           | Random => random_comp_modifiers
  3259           | Depth_Limited => depth_limited_comp_modifiers
  3260           | Depth_Limited_Random => depth_limited_random_comp_modifiers
  3261           (*| Annotated => annotated_comp_modifiers*)
  3262           | DSeq => dseq_comp_modifiers
  3263           | Pos_Random_DSeq => pos_random_dseq_comp_modifiers
  3264           | New_Pos_Random_DSeq => new_pos_random_dseq_comp_modifiers
  3265         val t_pred = compile_expr comp_modifiers (ProofContext.init thy)
  3266           (body, deriv) additional_arguments;
  3267         val T_pred = dest_predT compfuns (fastype_of t_pred)
  3268         val arrange = split_lambda (HOLogic.mk_tuple outargs) output_tuple
  3269       in
  3270         if null outargs then t_pred else mk_map compfuns T_pred T_compr arrange t_pred
  3271       end
  3272     else
  3273       error "Evaluation with values is not possible because compilation with code_pred was not invoked"
  3274   end
  3275 
  3276 fun eval thy stats param_user_modes (options as (compilation, arguments)) k t_compr =
  3277   let
  3278     fun count xs x =
  3279       let
  3280         fun count' i [] = i
  3281           | count' i (x' :: xs) = if x = x' then count' (i + 1) xs else count' i xs
  3282       in count' 0 xs end
  3283     fun accumulate xs = map (fn x => (x, count xs x)) (sort int_ord (distinct (op =) xs))
  3284     val compfuns =
  3285       case compilation of
  3286         Random => PredicateCompFuns.compfuns
  3287       | DSeq => DSequence_CompFuns.compfuns
  3288       | Pos_Random_DSeq => Random_Sequence_CompFuns.compfuns
  3289       | New_Pos_Random_DSeq => New_Pos_Random_Sequence_CompFuns.compfuns
  3290       | _ => PredicateCompFuns.compfuns
  3291     val t = analyze_compr thy compfuns param_user_modes options t_compr;
  3292     val T = dest_predT compfuns (fastype_of t);
  3293     val t' =
  3294       if stats andalso compilation = New_Pos_Random_DSeq then
  3295         mk_map compfuns T (HOLogic.mk_prodT (HOLogic.termT, @{typ code_numeral}))
  3296           (absdummy (T, HOLogic.mk_prod (HOLogic.term_of_const T $ Bound 0,
  3297             @{term Code_Numeral.of_nat} $ (HOLogic.size_const T $ Bound 0)))) t
  3298       else
  3299         mk_map compfuns T HOLogic.termT (HOLogic.term_of_const T) t
  3300     val (ts, statistics) =
  3301       case compilation of
  3302        (* Random =>
  3303           fst (Predicate.yieldn k
  3304           (Code_Eval.eval NONE ("Predicate_Compile_Core.random_eval_ref", random_eval_ref)
  3305             (fn proc => fn g => fn s => g s |>> Predicate.map proc) thy t' []
  3306             |> Random_Engine.run))*)
  3307         Pos_Random_DSeq =>
  3308           let
  3309             val [nrandom, size, depth] = arguments
  3310           in
  3311             rpair NONE (fst (DSequence.yieldn k
  3312               (Code_Eval.eval NONE ("Predicate_Compile_Core.random_dseq_eval_ref", random_dseq_eval_ref)
  3313                 (fn proc => fn g => fn nrandom => fn size => fn s => g nrandom size s |>> DSequence.map proc)
  3314                   thy t' [] nrandom size
  3315                 |> Random_Engine.run)
  3316               depth true))
  3317           end
  3318       | DSeq =>
  3319           rpair NONE (fst (DSequence.yieldn k
  3320             (Code_Eval.eval NONE ("Predicate_Compile_Core.dseq_eval_ref", dseq_eval_ref)
  3321               DSequence.map thy t' []) (the_single arguments) true))
  3322       | New_Pos_Random_DSeq =>
  3323           let
  3324             val [nrandom, size, depth] = arguments
  3325             val seed = Random_Engine.next_seed ()
  3326           in
  3327             if stats then
  3328               apsnd (SOME o accumulate) (split_list
  3329               (fst (Lazy_Sequence.yieldn k
  3330                 (Code_Eval.eval NONE
  3331                   ("Predicate_Compile_Core.new_random_dseq_stats_eval_ref", new_random_dseq_stats_eval_ref)
  3332                   (fn proc => fn g => fn nrandom => fn size => fn s => fn depth => g nrandom size s depth
  3333                     |> Lazy_Sequence.map (apfst proc))
  3334                     thy t' [] nrandom size seed depth))))
  3335             else rpair NONE
  3336               (fst (Lazy_Sequence.yieldn k
  3337                 (Code_Eval.eval NONE
  3338                   ("Predicate_Compile_Core.new_random_dseq_eval_ref", new_random_dseq_eval_ref)
  3339                   (fn proc => fn g => fn nrandom => fn size => fn s => fn depth => g nrandom size s depth
  3340                     |> Lazy_Sequence.map proc)
  3341                     thy t' [] nrandom size seed depth)))
  3342           end
  3343       | _ =>
  3344           rpair NONE (fst (Predicate.yieldn k
  3345             (Code_Eval.eval NONE ("Predicate_Compile_Core.eval_ref", eval_ref)
  3346               Predicate.map thy t' [])))
  3347   in ((T, ts), statistics) end;
  3348 
  3349 fun values ctxt param_user_modes ((raw_expected, stats), comp_options) k t_compr =
  3350   let
  3351     val thy = ProofContext.theory_of ctxt
  3352     val ((T, ts), statistics) = eval thy stats param_user_modes comp_options k t_compr
  3353     val setT = HOLogic.mk_setT T
  3354     val elems = HOLogic.mk_set T ts
  3355     val cont = Free ("...", setT)
  3356     (* check expected values *)
  3357     val () =
  3358       case raw_expected of
  3359         NONE => ()
  3360       | SOME s =>
  3361         if eq_set (op =) (HOLogic.dest_set (Syntax.read_term ctxt s), ts) then ()
  3362         else
  3363           error ("expected and computed values do not match:\n" ^
  3364             "expected values: " ^ Syntax.string_of_term ctxt (Syntax.read_term ctxt s) ^ "\n" ^
  3365             "computed values: " ^ Syntax.string_of_term ctxt elems ^ "\n")
  3366   in
  3367     (if k = ~1 orelse length ts < k then elems
  3368     else Const (@{const_abbrev Set.union}, setT --> setT --> setT) $ elems $ cont, statistics)
  3369   end;
  3370 
  3371 fun values_cmd print_modes param_user_modes options k raw_t state =
  3372   let
  3373     val ctxt = Toplevel.context_of state
  3374     val t = Syntax.read_term ctxt raw_t
  3375     val (t', stats) = values ctxt param_user_modes options k t
  3376     val ty' = Term.type_of t'
  3377     val ctxt' = Variable.auto_fixes t' ctxt
  3378     val pretty_stat =
  3379       case stats of
  3380           NONE => []
  3381         | SOME xs =>
  3382           let
  3383             val total = fold (curry (op +)) (map snd xs) 0
  3384             fun pretty_entry (s, n) =
  3385               [Pretty.str "size", Pretty.brk 1,
  3386                Pretty.str (string_of_int s), Pretty.str ":", Pretty.brk 1,
  3387                Pretty.str (string_of_int n), Pretty.fbrk]
  3388           in
  3389             [Pretty.fbrk, Pretty.str "Statistics:", Pretty.fbrk,
  3390              Pretty.str "total:", Pretty.brk 1, Pretty.str (string_of_int total), Pretty.fbrk]
  3391              @ maps pretty_entry xs
  3392           end
  3393     val p = PrintMode.with_modes print_modes (fn () =>
  3394       Pretty.block ([Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
  3395         Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]
  3396         @ pretty_stat)) ();
  3397   in Pretty.writeln p end;
  3398 
  3399 end;