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