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