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