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