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