src/HOL/Tools/Predicate_Compile/predicate_compile_core.ML
author bulwahn
Mon Mar 22 08:30:13 2010 +0100 (2010-03-22)
changeset 35889 c1f86c5d3827
parent 35888 d902054e7ac6
child 35891 3122bdd95275
permissions -rw-r--r--
avoiding fishing for split_asm rule in the predicate compiler
     1 (*  Title:      HOL/Tools/Predicate_Compile/predicate_compile_core.ML
     2     Author:     Lukas Bulwahn, TU Muenchen
     3 
     4 A compiler from predicates specified by intro/elim rules to equations.
     5 *)
     6 
     7 signature PREDICATE_COMPILE_CORE =
     8 sig
     9   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 thy (Const (f, _)) = is_constr thy f
  1031   | is_invertible_function thy _ = false
  1032 
  1033 fun non_invertible_subterms thy (t as Free _) = []
  1034   | non_invertible_subterms thy t = 
  1035   case (strip_comb t) of (f, args) =>
  1036     if is_invertible_function thy f then
  1037       maps (non_invertible_subterms thy) args
  1038     else
  1039       [t]
  1040 
  1041 fun collect_non_invertible_subterms thy (f as Free _) (names, eqs) = (f, (names, eqs))
  1042   | collect_non_invertible_subterms thy t (names, eqs) =
  1043     case (strip_comb t) of (f, args) =>
  1044       if is_invertible_function thy f then
  1045           let
  1046             val (args', (names', eqs')) =
  1047               fold_map (collect_non_invertible_subterms thy) args (names, eqs)
  1048           in
  1049             (list_comb (f, args'), (names', eqs'))
  1050           end
  1051         else
  1052           let
  1053             val s = Name.variant names "x"
  1054             val v = Free (s, fastype_of t)
  1055           in
  1056             (v, (s :: names, HOLogic.mk_eq (v, t) :: eqs))
  1057           end
  1058 (*
  1059   if is_constrt thy t then (t, (names, eqs)) else
  1060     let
  1061       val s = Name.variant names "x"
  1062       val v = Free (s, fastype_of t)
  1063     in (v, (s::names, HOLogic.mk_eq (v, t)::eqs)) end;
  1064 *)
  1065 
  1066 fun is_possible_output thy vs t =
  1067   forall
  1068     (fn t => is_eqT (fastype_of t) andalso forall (member (op =) vs) (term_vs t))
  1069       (non_invertible_subterms thy t)
  1070   andalso
  1071     (forall (is_eqT o snd)
  1072       (inter (fn ((f', _), f) => f = f') vs (Term.add_frees t [])))
  1073 
  1074 fun vars_of_destructable_term thy (Free (x, _)) = [x]
  1075   | vars_of_destructable_term thy t =
  1076   case (strip_comb t) of (f, args) =>
  1077     if is_invertible_function thy f then
  1078       maps (vars_of_destructable_term thy) args
  1079     else
  1080       []
  1081 
  1082 fun is_constructable thy vs t = forall (member (op =) vs) (term_vs t)
  1083 
  1084 fun missing_vars vs t = subtract (op =) vs (term_vs t)
  1085 
  1086 fun output_terms (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =
  1087     output_terms (t1, d1)  @ output_terms (t2, d2)
  1088   | output_terms (t1 $ t2, Mode_App (d1, d2)) =
  1089     output_terms (t1, d1)  @ output_terms (t2, d2)
  1090   | output_terms (t, Term Output) = [t]
  1091   | output_terms _ = []
  1092 
  1093 fun lookup_mode modes (Const (s, T)) =
  1094    (case (AList.lookup (op =) modes s) of
  1095       SOME ms => SOME (map (fn m => (Context m, [])) ms)
  1096     | NONE => NONE)
  1097   | lookup_mode modes (Free (x, _)) =
  1098     (case (AList.lookup (op =) modes x) of
  1099       SOME ms => SOME (map (fn m => (Context m , [])) ms)
  1100     | NONE => NONE)
  1101 
  1102 fun derivations_of thy modes vs (Const ("Pair", _) $ t1 $ t2) (Pair (m1, m2)) =
  1103     map_product
  1104       (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
  1105         (derivations_of thy modes vs t1 m1) (derivations_of thy modes vs t2 m2)
  1106   | derivations_of thy modes vs t (m as Fun _) =
  1107     (*let
  1108       val (p, args) = strip_comb t
  1109     in
  1110       (case lookup_mode modes p of
  1111         SOME ms => map_filter (fn (Context m, []) => let
  1112           val ms = strip_fun_mode m
  1113           val (argms, restms) = chop (length args) ms
  1114           val m' = fold_rev (curry Fun) restms Bool
  1115         in
  1116           if forall (fn m => eq_mode (Input, m)) argms andalso eq_mode (m', mode) then
  1117             SOME (fold (curry Mode_App) (map Term argms) (Context m), missing_vars vs t)
  1118           else NONE
  1119         end) ms
  1120       | NONE => (if is_all_input mode then [(Context mode, [])] else []))
  1121     end*)
  1122     (case try (all_derivations_of thy modes vs) t  of
  1123       SOME derivs =>
  1124         filter (fn (d, mvars) => eq_mode (mode_of d, m) andalso null (output_terms (t, d))) derivs
  1125     | NONE => (if is_all_input m then [(Context m, [])] else []))
  1126   | derivations_of thy modes vs t m =
  1127     if eq_mode (m, Input) then
  1128       [(Term Input, missing_vars vs t)]
  1129     else if eq_mode (m, Output) then
  1130       (if is_possible_output thy vs t then [(Term Output, [])] else [])
  1131     else []
  1132 and all_derivations_of thy modes vs (Const ("Pair", _) $ t1 $ t2) =
  1133   let
  1134     val derivs1 = all_derivations_of thy modes vs t1
  1135     val derivs2 = all_derivations_of thy modes vs t2
  1136   in
  1137     map_product
  1138       (fn (m1, mvars1) => fn (m2, mvars2) => (Mode_Pair (m1, m2), union (op =) mvars1 mvars2))
  1139         derivs1 derivs2
  1140   end
  1141   | all_derivations_of thy modes vs (t1 $ t2) =
  1142   let
  1143     val derivs1 = all_derivations_of thy modes vs t1
  1144   in
  1145     maps (fn (d1, mvars1) =>
  1146       case mode_of d1 of
  1147         Fun (m', _) => map (fn (d2, mvars2) =>
  1148           (Mode_App (d1, d2), union (op =) mvars1 mvars2)) (derivations_of thy modes vs t2 m')
  1149         | _ => raise Fail "Something went wrong") derivs1
  1150   end
  1151   | all_derivations_of thy modes vs (Const (s, T)) = the (lookup_mode modes (Const (s, T)))
  1152   | all_derivations_of thy modes vs (Free (x, T)) = the (lookup_mode modes (Free (x, T)))
  1153   | all_derivations_of _ modes vs _ = raise Fail "all_derivations_of"
  1154 
  1155 fun rev_option_ord ord (NONE, NONE) = EQUAL
  1156   | rev_option_ord ord (NONE, SOME _) = GREATER
  1157   | rev_option_ord ord (SOME _, NONE) = LESS
  1158   | rev_option_ord ord (SOME x, SOME y) = ord (x, y)
  1159 
  1160 fun term_of_prem (Prem t) = t
  1161   | term_of_prem (Negprem t) = t
  1162   | term_of_prem (Sidecond t) = t
  1163 
  1164 fun random_mode_in_deriv modes t deriv =
  1165   case try dest_Const (fst (strip_comb t)) of
  1166     SOME (s, _) =>
  1167       (case AList.lookup (op =) modes s of
  1168         SOME ms =>
  1169           (case AList.lookup (op =) (map (fn ((p, m), r) => (m, r)) ms) (head_mode_of deriv) of
  1170             SOME r => r
  1171           | NONE => false)
  1172       | NONE => false)
  1173   | NONE => false
  1174 
  1175 fun number_of_output_positions mode =
  1176   let
  1177     val args = strip_fun_mode mode
  1178     fun contains_output (Fun _) = false
  1179       | contains_output Input = false
  1180       | contains_output Output = true
  1181       | contains_output (Pair (m1, m2)) = contains_output m1 orelse contains_output m2
  1182   in
  1183     length (filter contains_output args)
  1184   end
  1185 
  1186 fun lex_ord ord1 ord2 (x, x') =
  1187   case ord1 (x, x') of
  1188     EQUAL => ord2 (x, x')
  1189   | ord => ord
  1190 
  1191 fun deriv_ord2' thy modes t1 t2 ((deriv1, mvars1), (deriv2, mvars2)) =
  1192   let
  1193     fun mvars_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1194       int_ord (length mvars1, length mvars2)
  1195     fun random_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1196       int_ord (if random_mode_in_deriv modes t1 deriv1 then 1 else 0,
  1197         if random_mode_in_deriv modes t1 deriv1 then 1 else 0)
  1198     fun output_mode_ord ((t1, deriv1, mvars1), (t2, deriv2, mvars2)) =
  1199       int_ord (number_of_output_positions (head_mode_of deriv1),
  1200         number_of_output_positions (head_mode_of deriv2))
  1201   in
  1202     lex_ord mvars_ord (lex_ord random_mode_ord output_mode_ord)
  1203       ((t1, deriv1, mvars1), (t2, deriv2, mvars2))
  1204   end
  1205 
  1206 fun deriv_ord2 thy modes t = deriv_ord2' thy modes t t
  1207 
  1208 fun deriv_ord ((deriv1, mvars1), (deriv2, mvars2)) =
  1209   int_ord (length mvars1, length mvars2)
  1210 
  1211 fun premise_ord thy modes ((prem1, a1), (prem2, a2)) =
  1212   rev_option_ord (deriv_ord2' thy modes (term_of_prem prem1) (term_of_prem prem2)) (a1, a2)
  1213 
  1214 fun print_mode_list modes =
  1215   tracing ("modes: " ^ (commas (map (fn (s, ms) => s ^ ": " ^
  1216     commas (map (fn (m, r) => string_of_mode m ^ (if r then " random " else " not ")) ms)) modes)))
  1217 
  1218 fun select_mode_prem (mode_analysis_options : mode_analysis_options) thy pol (modes, (pos_modes, neg_modes)) vs ps =
  1219   let
  1220     fun choose_mode_of_prem (Prem t) = partial_hd
  1221         (sort (deriv_ord2 thy modes t) (all_derivations_of thy pos_modes vs t))
  1222       | choose_mode_of_prem (Sidecond t) = SOME (Context Bool, missing_vars vs t)
  1223       | choose_mode_of_prem (Negprem t) = partial_hd
  1224           (sort (deriv_ord2 thy modes t) (filter (fn (d, missing_vars) => is_all_input (head_mode_of d))
  1225              (all_derivations_of thy neg_modes vs t)))
  1226       | choose_mode_of_prem p = raise Fail ("choose_mode_of_prem: " ^ string_of_prem thy p)
  1227   in
  1228     if #reorder_premises mode_analysis_options then
  1229       partial_hd (sort (premise_ord thy modes) (ps ~~ map choose_mode_of_prem ps))
  1230     else
  1231       SOME (hd ps, choose_mode_of_prem (hd ps))
  1232   end
  1233 
  1234 fun check_mode_clause' (mode_analysis_options : mode_analysis_options) thy param_vs (modes :
  1235   (string * ((bool * mode) * bool) list) list) ((pol, mode) : bool * mode) (ts, ps) =
  1236   let
  1237     val vTs = distinct (op =) (fold Term.add_frees (map term_of_prem ps) (fold Term.add_frees ts []))
  1238     val modes' = modes @ (param_vs ~~ map (fn x => [((true, x), false), ((false, x), false)]) (ho_arg_modes_of mode))
  1239     fun retrieve_modes_of_pol pol = map (fn (s, ms) =>
  1240       (s, map_filter (fn ((p, m), r) => if p = pol then SOME m else NONE | _ => NONE) ms))
  1241     val (pos_modes', neg_modes') =
  1242       if #infer_pos_and_neg_modes mode_analysis_options then
  1243         (retrieve_modes_of_pol pol modes', retrieve_modes_of_pol (not pol) modes')
  1244       else
  1245         let
  1246           val modes = map (fn (s, ms) => (s, map (fn ((p, m), r) => m) ms)) modes'
  1247         in (modes, modes) end
  1248     val (in_ts, out_ts) = split_mode mode ts
  1249     val in_vs = maps (vars_of_destructable_term thy) in_ts
  1250     val out_vs = terms_vs out_ts
  1251     fun known_vs_after p vs = (case p of
  1252         Prem t => union (op =) vs (term_vs t)
  1253       | Sidecond t => union (op =) vs (term_vs t)
  1254       | Negprem t => union (op =) vs (term_vs t)
  1255       | _ => raise Fail "I do not know")
  1256     fun check_mode_prems acc_ps rnd vs [] = SOME (acc_ps, vs, rnd)
  1257       | check_mode_prems acc_ps rnd vs ps =
  1258         (case
  1259           (select_mode_prem mode_analysis_options thy pol (modes', (pos_modes', neg_modes')) vs ps) of
  1260           SOME (p, SOME (deriv, [])) => check_mode_prems ((p, deriv) :: acc_ps) rnd
  1261             (known_vs_after p vs) (filter_out (equal p) ps)
  1262         | SOME (p, SOME (deriv, missing_vars)) =>
  1263           if #use_random mode_analysis_options andalso pol then
  1264             check_mode_prems ((p, deriv) :: (map
  1265               (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
  1266                 (distinct (op =) missing_vars))
  1267                 @ acc_ps) true (known_vs_after p vs) (filter_out (equal p) ps)
  1268           else NONE
  1269         | SOME (p, NONE) => NONE
  1270         | NONE => NONE)
  1271   in
  1272     case check_mode_prems [] false in_vs ps of
  1273       NONE => NONE
  1274     | SOME (acc_ps, vs, rnd) =>
  1275       if forall (is_constructable thy vs) (in_ts @ out_ts) then
  1276         SOME (ts, rev acc_ps, rnd)
  1277       else
  1278         if #use_random mode_analysis_options andalso pol then
  1279           let
  1280              val generators = map
  1281               (fn v => (Generator (v, the (AList.lookup (op =) vTs v)), Term Output))
  1282                 (subtract (op =) vs (terms_vs (in_ts @ out_ts)))
  1283           in
  1284             SOME (ts, rev (generators @ acc_ps), true)
  1285           end
  1286         else
  1287           NONE
  1288   end
  1289 
  1290 datatype result = Success of bool | Error of string
  1291 
  1292 fun check_modes_pred' mode_analysis_options options thy param_vs clauses modes (p, (ms : ((bool * mode) * bool) list)) =
  1293   let
  1294     fun split xs =
  1295       let
  1296         fun split' [] (ys, zs) = (rev ys, rev zs)
  1297           | split' ((m, Error z) :: xs) (ys, zs) = split' xs (ys, z :: zs)
  1298           | split' (((m : bool * mode), Success rnd) :: xs) (ys, zs) = split' xs ((m, rnd) :: ys, zs)
  1299        in
  1300          split' xs ([], [])
  1301        end
  1302     val rs = these (AList.lookup (op =) clauses p)
  1303     fun check_mode m =
  1304       let
  1305         val res = Output.cond_timeit false "work part of check_mode for one mode" (fn _ => 
  1306           map (check_mode_clause' mode_analysis_options thy param_vs modes m) rs)
  1307       in
  1308         Output.cond_timeit false "aux part of check_mode for one mode" (fn _ => 
  1309         case find_indices is_none res of
  1310           [] => Success (exists (fn SOME (_, _, true) => true | _ => false) res)
  1311         | is => (print_failed_mode options thy modes p m rs is; Error (error_of p m is)))
  1312       end
  1313     val _ = if show_mode_inference options then
  1314         tracing ("checking " ^ string_of_int (length ms) ^ " modes ...")
  1315       else ()
  1316     val res = Output.cond_timeit false "check_mode" (fn _ => map (fn (m, _) => (m, check_mode m)) ms)
  1317     val (ms', errors) = split res
  1318   in
  1319     ((p, (ms' : ((bool * mode) * bool) list)), errors)
  1320   end;
  1321 
  1322 fun get_modes_pred' mode_analysis_options thy param_vs clauses modes (p, ms) =
  1323   let
  1324     val rs = these (AList.lookup (op =) clauses p)
  1325   in
  1326     (p, map (fn (m, rnd) =>
  1327       (m, map
  1328         ((fn (ts, ps, rnd) => (ts, ps)) o the o
  1329           check_mode_clause' mode_analysis_options thy param_vs modes m) rs)) ms)
  1330   end;
  1331 
  1332 fun fixp f (x : (string * ((bool * mode) * bool) list) list) =
  1333   let val y = f x
  1334   in if x = y then x else fixp f y end;
  1335 
  1336 fun fixp_with_state f (x : (string * ((bool * mode) * bool) list) list, state) =
  1337   let
  1338     val (y, state') = f (x, state)
  1339   in
  1340     if x = y then (y, state') else fixp_with_state f (y, state')
  1341   end
  1342 
  1343 fun string_of_ext_mode ((pol, mode), rnd) =
  1344   string_of_mode mode ^ "(" ^ (if pol then "pos" else "neg") ^ ", "
  1345   ^ (if rnd then "rnd" else "nornd") ^ ")"
  1346 
  1347 fun print_extra_modes options modes =
  1348   if show_mode_inference options then
  1349     tracing ("Modes of inferred predicates: " ^
  1350       cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map string_of_ext_mode ms)) modes))
  1351   else ()
  1352 
  1353 fun infer_modes mode_analysis_options options compilation preds all_modes param_vs clauses thy =
  1354   let
  1355     val collect_errors = false
  1356     fun appair f (x1, x2) (y1, y2) = (f x1 y1, f x2 y2)
  1357     fun needs_random s (false, m) = ((false, m), false)
  1358       | needs_random s (true, m) = ((true, m), member (op =) (#needs_random (the_pred_data thy s)) m)
  1359     fun add_polarity_and_random_bit s b ms = map (fn m => needs_random s (b, m)) ms
  1360     val prednames = map fst preds
  1361     (* extramodes contains all modes of all constants, should we only use the necessary ones
  1362        - what is the impact on performance? *)
  1363     val extra_modes =
  1364       if #infer_pos_and_neg_modes mode_analysis_options then
  1365         let
  1366           val pos_extra_modes =
  1367             all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name)
  1368           val neg_extra_modes =
  1369             all_modes_of (negative_compilation_of compilation) thy
  1370             |> filter_out (fn (name, _) => member (op =) prednames name)
  1371         in
  1372           map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)
  1373                 @ add_polarity_and_random_bit s false (the (AList.lookup (op =) neg_extra_modes s))))
  1374             pos_extra_modes
  1375         end
  1376       else
  1377         map (fn (s, ms) => (s, (add_polarity_and_random_bit s true ms)))
  1378           (all_modes_of compilation thy |> filter_out (fn (name, _) => member (op =) prednames name))
  1379     val _ = print_extra_modes options extra_modes
  1380     val start_modes =
  1381       if #infer_pos_and_neg_modes mode_analysis_options then
  1382         map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms @
  1383           (map (fn m => ((false, m), false)) ms))) all_modes
  1384       else
  1385         map (fn (s, ms) => (s, map (fn m => ((true, m), false)) ms)) all_modes
  1386     fun iteration modes = map
  1387       (check_modes_pred' mode_analysis_options options thy param_vs clauses (modes @ extra_modes))
  1388         modes
  1389     val ((modes : (string * ((bool * mode) * bool) list) list), errors) =
  1390       Output.cond_timeit false "Fixpount computation of mode analysis" (fn () =>
  1391       if collect_errors then
  1392         fixp_with_state (fn (modes, errors) =>
  1393           let
  1394             val (modes', new_errors) = split_list (iteration modes)
  1395           in (modes', errors @ flat new_errors) end) (start_modes, [])
  1396         else
  1397           (fixp (fn modes => map fst (iteration modes)) start_modes, []))
  1398     val moded_clauses = map (get_modes_pred' mode_analysis_options thy param_vs clauses
  1399       (modes @ extra_modes)) modes
  1400     val thy' = fold (fn (s, ms) => if member (op =) (map fst preds) s then
  1401       set_needs_random s (map_filter (fn ((true, m), true) => SOME m | _ => NONE) ms) else I)
  1402       modes thy
  1403 
  1404   in
  1405     ((moded_clauses, errors), thy')
  1406   end;
  1407 
  1408 (* term construction *)
  1409 
  1410 fun mk_v (names, vs) s T = (case AList.lookup (op =) vs s of
  1411       NONE => (Free (s, T), (names, (s, [])::vs))
  1412     | SOME xs =>
  1413         let
  1414           val s' = Name.variant names s;
  1415           val v = Free (s', T)
  1416         in
  1417           (v, (s'::names, AList.update (op =) (s, v::xs) vs))
  1418         end);
  1419 
  1420 fun distinct_v (Free (s, T)) nvs = mk_v nvs s T
  1421   | distinct_v (t $ u) nvs =
  1422       let
  1423         val (t', nvs') = distinct_v t nvs;
  1424         val (u', nvs'') = distinct_v u nvs';
  1425       in (t' $ u', nvs'') end
  1426   | distinct_v x nvs = (x, nvs);
  1427 
  1428 (** specific rpred functions -- move them to the correct place in this file *)
  1429 
  1430 fun mk_Eval_of additional_arguments ((x, T), NONE) names = (x, names)
  1431   | mk_Eval_of additional_arguments ((x, T), SOME mode) names =
  1432   let
  1433     val Ts = binder_types T
  1434     fun mk_split_lambda [] t = lambda (Free (Name.variant names "x", HOLogic.unitT)) t
  1435       | mk_split_lambda [x] t = lambda x t
  1436       | mk_split_lambda xs t =
  1437       let
  1438         fun mk_split_lambda' (x::y::[]) t = HOLogic.mk_split (lambda x (lambda y t))
  1439           | mk_split_lambda' (x::xs) t = HOLogic.mk_split (lambda x (mk_split_lambda' xs t))
  1440       in
  1441         mk_split_lambda' xs t
  1442       end;
  1443     fun mk_arg (i, T) =
  1444       let
  1445         val vname = Name.variant names ("x" ^ string_of_int i)
  1446         val default = Free (vname, T)
  1447       in 
  1448         case AList.lookup (op =) mode i of
  1449           NONE => (([], [default]), [default])
  1450         | SOME NONE => (([default], []), [default])
  1451         | SOME (SOME pis) =>
  1452           case HOLogic.strip_tupleT T of
  1453             [] => error "pair mode but unit tuple" (*(([default], []), [default])*)
  1454           | [_] => error "pair mode but not a tuple" (*(([default], []), [default])*)
  1455           | Ts =>
  1456             let
  1457               val vnames = Name.variant_list names
  1458                 (map (fn j => "x" ^ string_of_int i ^ "p" ^ string_of_int j)
  1459                   (1 upto length Ts))
  1460               val args = map2 (curry Free) vnames Ts
  1461               fun split_args (i, arg) (ins, outs) =
  1462                 if member (op =) pis i then
  1463                   (arg::ins, outs)
  1464                 else
  1465                   (ins, arg::outs)
  1466               val (inargs, outargs) = fold_rev split_args ((1 upto length Ts) ~~ args) ([], [])
  1467               fun tuple args = if null args then [] else [HOLogic.mk_tuple args]
  1468             in ((tuple inargs, tuple outargs), args) end
  1469       end
  1470     val (inoutargs, args) = split_list (map mk_arg (1 upto (length Ts) ~~ Ts))
  1471     val (inargs, outargs) = pairself flat (split_list inoutargs)
  1472     val r = PredicateCompFuns.mk_Eval 
  1473       (list_comb (x, inargs @ additional_arguments), HOLogic.mk_tuple outargs)
  1474     val t = fold_rev mk_split_lambda args r
  1475   in
  1476     (t, names)
  1477   end;
  1478 
  1479 structure Comp_Mod =
  1480 struct
  1481 
  1482 datatype comp_modifiers = Comp_Modifiers of
  1483 {
  1484   compilation : compilation,
  1485   function_name_prefix : string,
  1486   compfuns : compilation_funs,
  1487   mk_random : typ -> term list -> term,
  1488   modify_funT : typ -> typ,
  1489   additional_arguments : string list -> term list,
  1490   wrap_compilation : compilation_funs -> string -> typ -> mode -> term list -> term -> term,
  1491   transform_additional_arguments : indprem -> term list -> term list
  1492 }
  1493 
  1494 fun dest_comp_modifiers (Comp_Modifiers c) = c
  1495 
  1496 val compilation = #compilation o dest_comp_modifiers
  1497 val function_name_prefix = #function_name_prefix o dest_comp_modifiers
  1498 val compfuns = #compfuns o dest_comp_modifiers
  1499 
  1500 val mk_random = #mk_random o dest_comp_modifiers
  1501 val funT_of' = funT_of o compfuns
  1502 val modify_funT = #modify_funT o dest_comp_modifiers
  1503 fun funT_of comp mode = modify_funT comp o funT_of' comp mode
  1504 
  1505 val additional_arguments = #additional_arguments o dest_comp_modifiers
  1506 val wrap_compilation = #wrap_compilation o dest_comp_modifiers
  1507 val transform_additional_arguments = #transform_additional_arguments o dest_comp_modifiers
  1508 
  1509 end;
  1510 
  1511 (* TODO: uses param_vs -- change necessary for compilation with new modes *)
  1512 fun compile_arg compilation_modifiers compfuns additional_arguments thy param_vs iss arg = 
  1513   let
  1514     fun map_params (t as Free (f, T)) =
  1515       if member (op =) param_vs f then
  1516         case (AList.lookup (op =) (param_vs ~~ iss) f) of
  1517           SOME is =>
  1518             let
  1519               val _ = error "compile_arg: A parameter in a input position -- do we have a test case?"
  1520               val T' = Comp_Mod.funT_of compilation_modifiers is T
  1521             in t(*fst (mk_Eval_of additional_arguments ((Free (f, T'), T), is) [])*) end
  1522         | NONE => t
  1523       else t
  1524       | map_params t = t
  1525     in map_aterms map_params arg end
  1526 
  1527 fun compile_match compilation_modifiers compfuns additional_arguments
  1528   param_vs iss thy eqs eqs' out_ts success_t =
  1529   let
  1530     val eqs'' = maps mk_eq eqs @ eqs'
  1531     val eqs'' =
  1532       map (compile_arg compilation_modifiers compfuns additional_arguments thy param_vs iss) eqs''
  1533     val names = fold Term.add_free_names (success_t :: eqs'' @ out_ts) [];
  1534     val name = Name.variant names "x";
  1535     val name' = Name.variant (name :: names) "y";
  1536     val T = HOLogic.mk_tupleT (map fastype_of out_ts);
  1537     val U = fastype_of success_t;
  1538     val U' = dest_predT compfuns U;
  1539     val v = Free (name, T);
  1540     val v' = Free (name', T);
  1541   in
  1542     lambda v (fst (Datatype.make_case
  1543       (ProofContext.init thy) Datatype_Case.Quiet [] v
  1544       [(HOLogic.mk_tuple out_ts,
  1545         if null eqs'' then success_t
  1546         else Const (@{const_name HOL.If}, HOLogic.boolT --> U --> U --> U) $
  1547           foldr1 HOLogic.mk_conj eqs'' $ success_t $
  1548             mk_bot compfuns U'),
  1549        (v', mk_bot compfuns U')]))
  1550   end;
  1551 
  1552 fun string_of_tderiv thy (t, deriv) = 
  1553   (case (t, deriv) of
  1554     (t1 $ t2, Mode_App (deriv1, deriv2)) =>
  1555       string_of_tderiv thy (t1, deriv1) ^ " $ " ^ string_of_tderiv thy (t2, deriv2)
  1556   | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (deriv1, deriv2)) =>
  1557     "(" ^ string_of_tderiv thy (t1, deriv1) ^ ", " ^ string_of_tderiv thy (t2, deriv2) ^ ")"
  1558   | (t, Term Input) => Syntax.string_of_term_global thy t ^ "[Input]"
  1559   | (t, Term Output) => Syntax.string_of_term_global thy t ^ "[Output]"
  1560   | (t, Context m) => Syntax.string_of_term_global thy t ^ "[" ^ string_of_mode m ^ "]")
  1561 
  1562 fun compile_expr compilation_modifiers compfuns thy pol (t, deriv) additional_arguments =
  1563   let
  1564     fun expr_of (t, deriv) =
  1565       (case (t, deriv) of
  1566         (t, Term Input) => SOME t
  1567       | (t, Term Output) => NONE
  1568       | (Const (name, T), Context mode) =>
  1569         SOME (Const (function_name_of (Comp_Mod.compilation compilation_modifiers) thy name
  1570           (pol, mode),
  1571           Comp_Mod.funT_of compilation_modifiers mode T))
  1572       | (Free (s, T), Context m) =>
  1573         SOME (Free (s, Comp_Mod.funT_of compilation_modifiers m T))
  1574       | (t, Context m) =>
  1575         let
  1576           val bs = map (pair "x") (binder_types (fastype_of t))
  1577           val bounds = map Bound (rev (0 upto (length bs) - 1))
  1578         in SOME (list_abs (bs, mk_if compfuns (list_comb (t, bounds)))) end
  1579       | (Const ("Pair", _) $ t1 $ t2, Mode_Pair (d1, d2)) =>
  1580         (case (expr_of (t1, d1), expr_of (t2, d2)) of
  1581           (NONE, NONE) => NONE
  1582         | (NONE, SOME t) => SOME t
  1583         | (SOME t, NONE) => SOME t
  1584         | (SOME t1, SOME t2) => SOME (HOLogic.mk_prod (t1, t2)))
  1585       | (t1 $ t2, Mode_App (deriv1, deriv2)) =>
  1586         (case (expr_of (t1, deriv1), expr_of (t2, deriv2)) of
  1587           (SOME t, NONE) => SOME t
  1588          | (SOME t, SOME u) => SOME (t $ u)
  1589          | _ => error "something went wrong here!"))
  1590   in
  1591     list_comb (the (expr_of (t, deriv)), additional_arguments)
  1592   end
  1593 
  1594 fun compile_clause compilation_modifiers compfuns thy all_vs param_vs additional_arguments
  1595   (pol, mode) inp (ts, moded_ps) =
  1596   let
  1597     val iss = ho_arg_modes_of mode
  1598     val compile_match = compile_match compilation_modifiers compfuns
  1599       additional_arguments param_vs iss thy
  1600     val (in_ts, out_ts) = split_mode mode ts;
  1601     val (in_ts', (all_vs', eqs)) =
  1602       fold_map (collect_non_invertible_subterms thy) in_ts (all_vs, []);
  1603     fun compile_prems out_ts' vs names [] =
  1604           let
  1605             val (out_ts'', (names', eqs')) =
  1606               fold_map (collect_non_invertible_subterms thy) out_ts' (names, []);
  1607             val (out_ts''', (names'', constr_vs)) = fold_map distinct_v
  1608               out_ts'' (names', map (rpair []) vs);
  1609           in
  1610             compile_match constr_vs (eqs @ eqs') out_ts'''
  1611               (mk_single compfuns (HOLogic.mk_tuple out_ts))
  1612           end
  1613       | compile_prems out_ts vs names ((p, deriv) :: ps) =
  1614           let
  1615             val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
  1616             val (out_ts', (names', eqs)) =
  1617               fold_map (collect_non_invertible_subterms thy) out_ts (names, [])
  1618             val (out_ts'', (names'', constr_vs')) = fold_map distinct_v
  1619               out_ts' ((names', map (rpair []) vs))
  1620             val mode = head_mode_of deriv
  1621             val additional_arguments' =
  1622               Comp_Mod.transform_additional_arguments compilation_modifiers p additional_arguments
  1623             val (compiled_clause, rest) = case p of
  1624                Prem t =>
  1625                  let
  1626                    val u =
  1627                      compile_expr compilation_modifiers compfuns thy
  1628                        pol (t, deriv) additional_arguments'
  1629                    val (_, out_ts''') = split_mode mode (snd (strip_comb t))
  1630                    val rest = compile_prems out_ts''' vs' names'' ps
  1631                  in
  1632                    (u, rest)
  1633                  end
  1634              | Negprem t =>
  1635                  let
  1636                    val u = mk_not compfuns
  1637                      (compile_expr compilation_modifiers compfuns thy
  1638                        (not pol) (t, deriv) additional_arguments')
  1639                    val (_, out_ts''') = split_mode mode (snd (strip_comb t))
  1640                    val rest = compile_prems out_ts''' vs' names'' ps
  1641                  in
  1642                    (u, rest)
  1643                  end
  1644              | Sidecond t =>
  1645                  let
  1646                    val t = compile_arg compilation_modifiers compfuns additional_arguments
  1647                      thy param_vs iss t
  1648                    val rest = compile_prems [] vs' names'' ps;
  1649                  in
  1650                    (mk_if compfuns t, rest)
  1651                  end
  1652              | Generator (v, T) =>
  1653                  let
  1654                    val u = Comp_Mod.mk_random compilation_modifiers T additional_arguments
  1655                    val rest = compile_prems [Free (v, T)]  vs' names'' ps;
  1656                  in
  1657                    (u, rest)
  1658                  end
  1659           in
  1660             compile_match constr_vs' eqs out_ts''
  1661               (mk_bind compfuns (compiled_clause, rest))
  1662           end
  1663     val prem_t = compile_prems in_ts' param_vs all_vs' moded_ps;
  1664   in
  1665     mk_bind compfuns (mk_single compfuns inp, prem_t)
  1666   end
  1667 
  1668 fun compile_pred compilation_modifiers thy all_vs param_vs s T (pol, mode) moded_cls =
  1669   let
  1670     val additional_arguments = Comp_Mod.additional_arguments compilation_modifiers
  1671       (all_vs @ param_vs)
  1672     val compfuns = Comp_Mod.compfuns compilation_modifiers
  1673     fun is_param_type (T as Type ("fun",[_ , T'])) =
  1674       is_some (try (dest_predT compfuns) T) orelse is_param_type T'
  1675       | is_param_type T = is_some (try (dest_predT compfuns) T)
  1676     val (inpTs, outTs) = split_map_modeT (fn m => fn T => (SOME (funT_of compfuns m T), NONE)) mode
  1677       (binder_types T)
  1678     val predT = mk_predT compfuns (HOLogic.mk_tupleT outTs)
  1679     val funT = Comp_Mod.funT_of compilation_modifiers mode T
  1680     
  1681     val (in_ts, _) = fold_map (fold_map_aterms_prodT (curry HOLogic.mk_prod)
  1682       (fn T => fn (param_vs, names) =>
  1683         if is_param_type T then                                                
  1684           (Free (hd param_vs, T), (tl param_vs, names))
  1685         else
  1686           let
  1687             val new = Name.variant names "x"
  1688           in (Free (new, T), (param_vs, new :: names)) end)) inpTs
  1689         (param_vs, (all_vs @ param_vs))
  1690     val in_ts' = map_filter (map_filter_prod
  1691       (fn t as Free (x, _) => if member (op =) param_vs x then NONE else SOME t | t => SOME t)) in_ts
  1692     val cl_ts =
  1693       map (compile_clause compilation_modifiers compfuns
  1694         thy all_vs param_vs additional_arguments (pol, mode) (HOLogic.mk_tuple in_ts')) moded_cls;
  1695     val compilation = Comp_Mod.wrap_compilation compilation_modifiers compfuns
  1696       s T mode additional_arguments
  1697       (if null cl_ts then
  1698         mk_bot compfuns (HOLogic.mk_tupleT outTs)
  1699       else foldr1 (mk_sup compfuns) cl_ts)
  1700     val fun_const =
  1701       Const (function_name_of (Comp_Mod.compilation compilation_modifiers) thy s (pol, mode), funT)
  1702   in
  1703     HOLogic.mk_Trueprop
  1704       (HOLogic.mk_eq (list_comb (fun_const, in_ts @ additional_arguments), compilation))
  1705   end;
  1706 
  1707 (* special setup for simpset *)                  
  1708 val HOL_basic_ss' = HOL_basic_ss addsimps (@{thms HOL.simp_thms} @ [@{thm Pair_eq}])
  1709   setSolver (mk_solver "all_tac_solver" (fn _ => fn _ => all_tac))
  1710   setSolver (mk_solver "True_solver" (fn _ => rtac @{thm TrueI}))
  1711 
  1712 (* Definition of executable functions and their intro and elim rules *)
  1713 
  1714 fun print_arities arities = tracing ("Arities:\n" ^
  1715   cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
  1716     space_implode " -> " (map
  1717       (fn NONE => "X" | SOME k' => string_of_int k')
  1718         (ks @ [SOME k]))) arities));
  1719 
  1720 fun split_lambda (x as Free _) t = lambda x t
  1721   | split_lambda (Const ("Pair", _) $ t1 $ t2) t =
  1722     HOLogic.mk_split (split_lambda t1 (split_lambda t2 t))
  1723   | split_lambda (Const ("Product_Type.Unity", _)) t = Abs ("x", HOLogic.unitT, t)
  1724   | split_lambda t _ = raise (TERM ("split_lambda", [t]))
  1725 
  1726 fun strip_split_abs (Const ("split", _) $ t) = strip_split_abs t
  1727   | strip_split_abs (Abs (_, _, t)) = strip_split_abs t
  1728   | strip_split_abs t = t
  1729 
  1730 fun mk_args is_eval (m as Pair (m1, m2), T as Type ("*", [T1, T2])) names =
  1731     if eq_mode (m, Input) orelse eq_mode (m, Output) then
  1732       let
  1733         val x = Name.variant names "x"
  1734       in
  1735         (Free (x, T), x :: names)
  1736       end
  1737     else
  1738       let
  1739         val (t1, names') = mk_args is_eval (m1, T1) names
  1740         val (t2, names'') = mk_args is_eval (m2, T2) names'
  1741       in
  1742         (HOLogic.mk_prod (t1, t2), names'')
  1743       end
  1744   | mk_args is_eval ((m as Fun _), T) names =
  1745     let
  1746       val funT = funT_of PredicateCompFuns.compfuns m T
  1747       val x = Name.variant names "x"
  1748       val (args, _) = fold_map (mk_args is_eval) (strip_fun_mode m ~~ binder_types T) (x :: names)
  1749       val (inargs, outargs) = split_map_mode (fn _ => fn t => (SOME t, NONE)) m args
  1750       val t = fold_rev split_lambda args (PredicateCompFuns.mk_Eval
  1751         (list_comb (Free (x, funT), inargs), HOLogic.mk_tuple outargs))
  1752     in
  1753       (if is_eval then t else Free (x, funT), x :: names)
  1754     end
  1755   | mk_args is_eval (_, T) names =
  1756     let
  1757       val x = Name.variant names "x"
  1758     in
  1759       (Free (x, T), x :: names)
  1760     end
  1761 
  1762 fun create_intro_elim_rule mode defthm mode_id funT pred thy =
  1763   let
  1764     val funtrm = Const (mode_id, funT)
  1765     val Ts = binder_types (fastype_of pred)
  1766     val (args, argnames) = fold_map (mk_args true) (strip_fun_mode mode ~~ Ts) []
  1767     fun strip_eval _ t =
  1768       let
  1769         val t' = strip_split_abs t
  1770         val (r, _) = PredicateCompFuns.dest_Eval t'
  1771       in (SOME (fst (strip_comb r)), NONE) end
  1772     val (inargs, outargs) = split_map_mode strip_eval mode args
  1773     val eval_hoargs = ho_args_of mode args
  1774     val hoargTs = ho_argsT_of mode Ts
  1775     val hoarg_names' =
  1776       Name.variant_list argnames ((map (fn i => "x" ^ string_of_int i)) (1 upto (length hoargTs)))
  1777     val hoargs' = map2 (curry Free) hoarg_names' hoargTs
  1778     val args' = replace_ho_args mode hoargs' args
  1779     val predpropI = HOLogic.mk_Trueprop (list_comb (pred, args'))
  1780     val predpropE = HOLogic.mk_Trueprop (list_comb (pred, args))
  1781     val param_eqs = map2 (HOLogic.mk_Trueprop oo (curry HOLogic.mk_eq)) eval_hoargs hoargs'
  1782     val funpropE = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
  1783                     if null outargs then Free("y", HOLogic.unitT) else HOLogic.mk_tuple outargs))
  1784     val funpropI = HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval (list_comb (funtrm, inargs),
  1785                      HOLogic.mk_tuple outargs))
  1786     val introtrm = Logic.list_implies (predpropI :: param_eqs, funpropI)
  1787     val simprules = [defthm, @{thm eval_pred},
  1788       @{thm "split_beta"}, @{thm "fst_conv"}, @{thm "snd_conv"}, @{thm pair_collapse}]
  1789     val unfolddef_tac = Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps simprules) 1
  1790     val introthm = Goal.prove (ProofContext.init thy)
  1791       (argnames @ hoarg_names' @ ["y"]) [] introtrm (fn _ => unfolddef_tac)
  1792     val P = HOLogic.mk_Trueprop (Free ("P", HOLogic.boolT));
  1793     val elimtrm = Logic.list_implies ([funpropE, Logic.mk_implies (predpropE, P)], P)
  1794     val elimthm = Goal.prove (ProofContext.init thy)
  1795       (argnames @ ["y", "P"]) [] elimtrm (fn _ => unfolddef_tac)
  1796     val opt_neg_introthm =
  1797       if is_all_input mode then
  1798         let
  1799           val neg_predpropI = HOLogic.mk_Trueprop (HOLogic.mk_not (list_comb (pred, args')))
  1800           val neg_funpropI =
  1801             HOLogic.mk_Trueprop (PredicateCompFuns.mk_Eval
  1802               (PredicateCompFuns.mk_not (list_comb (funtrm, inargs)), HOLogic.unit))
  1803           val neg_introtrm = Logic.list_implies (neg_predpropI :: param_eqs, neg_funpropI)
  1804           val tac =
  1805             Simplifier.asm_full_simp_tac (HOL_basic_ss addsimps
  1806               (@{thm if_False} :: @{thm Predicate.not_pred_eq} :: simprules)) 1
  1807             THEN rtac @{thm Predicate.singleI} 1
  1808         in SOME (Goal.prove (ProofContext.init thy) (argnames @ hoarg_names') []
  1809             neg_introtrm (fn _ => tac))
  1810         end
  1811       else NONE
  1812   in
  1813     ((introthm, elimthm), opt_neg_introthm)
  1814   end
  1815 
  1816 fun create_constname_of_mode options thy prefix name T mode = 
  1817   let
  1818     val system_proposal = prefix ^ (Long_Name.base_name name)
  1819       ^ "_" ^ ascii_string_of_mode mode
  1820     val name = the_default system_proposal (proposed_names options name mode)
  1821   in
  1822     Sign.full_bname thy name
  1823   end;
  1824 
  1825 fun create_definitions options preds (name, modes) thy =
  1826   let
  1827     val compfuns = PredicateCompFuns.compfuns
  1828     val T = AList.lookup (op =) preds name |> the
  1829     fun create_definition mode thy =
  1830       let
  1831         val mode_cname = create_constname_of_mode options thy "" name T mode
  1832         val mode_cbasename = Long_Name.base_name mode_cname
  1833         val funT = funT_of compfuns mode T
  1834         val (args, _) = fold_map (mk_args true) ((strip_fun_mode mode) ~~ (binder_types T)) []
  1835         fun strip_eval m t =
  1836           let
  1837             val t' = strip_split_abs t
  1838             val (r, _) = PredicateCompFuns.dest_Eval t'
  1839           in (SOME (fst (strip_comb r)), NONE) end
  1840         val (inargs, outargs) = split_map_mode strip_eval mode args
  1841         val predterm = fold_rev split_lambda inargs
  1842           (PredicateCompFuns.mk_Enum (split_lambda (HOLogic.mk_tuple outargs)
  1843             (list_comb (Const (name, T), args))))
  1844         val lhs = Const (mode_cname, funT)
  1845         val def = Logic.mk_equals (lhs, predterm)
  1846         val ([definition], thy') = thy |>
  1847           Sign.add_consts_i [(Binding.name mode_cbasename, funT, NoSyn)] |>
  1848           PureThy.add_defs false [((Binding.name (mode_cbasename ^ "_def"), def), [])]
  1849         val rules as ((intro, elim), _) =
  1850           create_intro_elim_rule mode definition mode_cname funT (Const (name, T)) thy'
  1851         in thy'
  1852           |> set_function_name Pred name mode mode_cname
  1853           |> add_predfun_data name mode (definition, rules)
  1854           |> PureThy.store_thm (Binding.name (mode_cbasename ^ "I"), intro) |> snd
  1855           |> PureThy.store_thm (Binding.name (mode_cbasename ^ "E"), elim)  |> snd
  1856           |> Theory.checkpoint
  1857         end;
  1858   in
  1859     thy |> defined_function_of Pred name |> fold create_definition modes
  1860   end;
  1861 
  1862 fun define_functions comp_modifiers compfuns options preds (name, modes) thy =
  1863   let
  1864     val T = AList.lookup (op =) preds name |> the
  1865     fun create_definition mode thy =
  1866       let
  1867         val function_name_prefix = Comp_Mod.function_name_prefix comp_modifiers
  1868         val mode_cname = create_constname_of_mode options thy function_name_prefix name T mode
  1869         val funT = Comp_Mod.funT_of comp_modifiers mode T
  1870       in
  1871         thy |> Sign.add_consts_i [(Binding.name (Long_Name.base_name mode_cname), funT, NoSyn)]
  1872         |> set_function_name (Comp_Mod.compilation comp_modifiers) name mode mode_cname
  1873       end;
  1874   in
  1875     thy
  1876     |> defined_function_of (Comp_Mod.compilation comp_modifiers) name
  1877     |> fold create_definition modes
  1878   end;
  1879 
  1880 (* Proving equivalence of term *)
  1881 
  1882 fun is_Type (Type _) = true
  1883   | is_Type _ = false
  1884 
  1885 (* returns true if t is an application of an datatype constructor *)
  1886 (* which then consequently would be splitted *)
  1887 (* else false *)
  1888 fun is_constructor thy t =
  1889   if (is_Type (fastype_of t)) then
  1890     (case Datatype.get_info thy ((fst o dest_Type o fastype_of) t) of
  1891       NONE => false
  1892     | SOME info => (let
  1893       val constr_consts = maps (fn (_, (_, _, constrs)) => map fst constrs) (#descr info)
  1894       val (c, _) = strip_comb t
  1895       in (case c of
  1896         Const (name, _) => name mem_string constr_consts
  1897         | _ => false) end))
  1898   else false
  1899 
  1900 (* MAJOR FIXME:  prove_params should be simple
  1901  - different form of introrule for parameters ? *)
  1902 
  1903 fun prove_param options ctxt nargs t deriv =
  1904   let
  1905     val  (f, args) = strip_comb (Envir.eta_contract t)
  1906     val mode = head_mode_of deriv
  1907     val param_derivations = param_derivations_of deriv
  1908     val ho_args = ho_args_of mode args
  1909     val f_tac = case f of
  1910       Const (name, T) => simp_tac (HOL_basic_ss addsimps 
  1911          [@{thm eval_pred}, predfun_definition_of ctxt name mode,
  1912          @{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
  1913          @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
  1914     | Free _ =>
  1915       Subgoal.FOCUS_PREMS (fn {context = ctxt, params = params, prems, asms, concl, schematics} =>
  1916         let
  1917           val prems' = maps dest_conjunct_prem (take nargs prems)
  1918         in
  1919           MetaSimplifier.rewrite_goal_tac
  1920             (map (fn th => th RS @{thm sym} RS @{thm eq_reflection}) prems') 1
  1921         end) ctxt 1
  1922     | Abs _ => raise Fail "prove_param: No valid parameter term"
  1923   in
  1924     REPEAT_DETERM (rtac @{thm ext} 1)
  1925     THEN print_tac options "prove_param"
  1926     THEN f_tac 
  1927     THEN print_tac options "after prove_param"
  1928     THEN (REPEAT_DETERM (atac 1))
  1929     THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
  1930     THEN REPEAT_DETERM (rtac @{thm refl} 1)
  1931   end
  1932 
  1933 fun prove_expr options ctxt nargs (premposition : int) (t, deriv) =
  1934   case strip_comb t of
  1935     (Const (name, T), args) =>
  1936       let
  1937         val mode = head_mode_of deriv
  1938         val introrule = predfun_intro_of ctxt name mode
  1939         val param_derivations = param_derivations_of deriv
  1940         val ho_args = ho_args_of mode args
  1941       in
  1942         print_tac options "before intro rule:"
  1943         THEN rtac introrule 1
  1944         THEN print_tac options "after intro rule"
  1945         (* for the right assumption in first position *)
  1946         THEN rotate_tac premposition 1
  1947         THEN atac 1
  1948         THEN print_tac options "parameter goal"
  1949         (* work with parameter arguments *)
  1950         THEN (EVERY (map2 (prove_param options ctxt nargs) ho_args param_derivations))
  1951         THEN (REPEAT_DETERM (atac 1))
  1952       end
  1953   | (Free _, _) =>
  1954     print_tac options "proving parameter call.."
  1955     THEN Subgoal.FOCUS_PREMS (fn {context = ctxt, params, prems, asms, concl, schematics} =>
  1956         let
  1957           val param_prem = nth prems premposition
  1958           val (param, _) = strip_comb (HOLogic.dest_Trueprop (prop_of param_prem))
  1959           val prems' = maps dest_conjunct_prem (take nargs prems)
  1960           fun param_rewrite prem =
  1961             param = snd (HOLogic.dest_eq (HOLogic.dest_Trueprop (prop_of prem)))
  1962           val SOME rew_eq = find_first param_rewrite prems'
  1963           val param_prem' = MetaSimplifier.rewrite_rule
  1964             (map (fn th => th RS @{thm eq_reflection})
  1965               [rew_eq RS @{thm sym}, @{thm split_beta}, @{thm fst_conv}, @{thm snd_conv}])
  1966             param_prem
  1967         in
  1968           rtac param_prem' 1
  1969         end) ctxt 1
  1970     THEN print_tac options "after prove parameter call"
  1971 
  1972 fun SOLVED tac st = FILTER (fn st' => nprems_of st' = nprems_of st - 1) tac st;
  1973 
  1974 fun SOLVEDALL tac st = FILTER (fn st' => nprems_of st' = 0) tac st
  1975 
  1976 fun check_format ctxt st =
  1977   let
  1978     val concl' = Logic.strip_assums_concl (hd (prems_of st))
  1979     val concl = HOLogic.dest_Trueprop concl'
  1980     val expr = fst (strip_comb (fst (PredicateCompFuns.dest_Eval concl)))
  1981     fun valid_expr (Const (@{const_name Predicate.bind}, _)) = true
  1982       | valid_expr (Const (@{const_name Predicate.single}, _)) = true
  1983       | valid_expr _ = false
  1984   in
  1985     if valid_expr expr then
  1986       ((*tracing "expression is valid";*) Seq.single st)
  1987     else
  1988       ((*tracing "expression is not valid";*) Seq.empty) (*error "check_format: wrong format"*)
  1989   end
  1990 
  1991 fun prove_match options ctxt out_ts =
  1992   let
  1993     val thy = ProofContext.theory_of ctxt
  1994     fun get_case_rewrite t =
  1995       if (is_constructor thy t) then let
  1996         val case_rewrites = (#case_rewrites (Datatype.the_info thy
  1997           ((fst o dest_Type o fastype_of) t)))
  1998         in case_rewrites @ maps get_case_rewrite (snd (strip_comb t)) end
  1999       else []
  2000     val simprules = @{thm "unit.cases"} :: @{thm "prod.cases"} :: maps get_case_rewrite out_ts
  2001   (* replace TRY by determining if it necessary - are there equations when calling compile match? *)
  2002   in
  2003      (* make this simpset better! *)
  2004     asm_full_simp_tac (HOL_basic_ss' addsimps simprules) 1
  2005     THEN print_tac options "after prove_match:"
  2006     THEN (DETERM (TRY (EqSubst.eqsubst_tac ctxt [0] [@{thm HOL.if_P}] 1
  2007            THEN (REPEAT_DETERM (rtac @{thm conjI} 1 THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1))))
  2008            THEN print_tac options "if condition to be solved:"
  2009            THEN (SOLVED (asm_simp_tac HOL_basic_ss' 1 THEN print_tac options "after if simp; in SOLVED:"))
  2010            THEN check_format thy
  2011            THEN print_tac options "after if simplification - a TRY block")))
  2012     THEN print_tac options "after if simplification"
  2013   end;
  2014 
  2015 (* corresponds to compile_fun -- maybe call that also compile_sidecond? *)
  2016 
  2017 fun prove_sidecond ctxt t =
  2018   let
  2019     val thy = ProofContext.theory_of ctxt
  2020     fun preds_of t nameTs = case strip_comb t of 
  2021       (f as Const (name, T), args) =>
  2022         if is_registered thy name then (name, T) :: nameTs
  2023           else fold preds_of args nameTs
  2024       | _ => nameTs
  2025     val preds = preds_of t []
  2026     val defs = map
  2027       (fn (pred, T) => predfun_definition_of ctxt pred
  2028         (all_input_of T))
  2029         preds
  2030   in 
  2031     (* remove not_False_eq_True when simpset in prove_match is better *)
  2032     simp_tac (HOL_basic_ss addsimps
  2033       (@{thms HOL.simp_thms} @ (@{thm not_False_eq_True} :: @{thm eval_pred} :: defs))) 1 
  2034     (* need better control here! *)
  2035   end
  2036 
  2037 fun prove_clause options ctxt nargs mode (_, clauses) (ts, moded_ps) =
  2038   let
  2039     val (in_ts, clause_out_ts) = split_mode mode ts;
  2040     fun prove_prems out_ts [] =
  2041       (prove_match options ctxt out_ts)
  2042       THEN print_tac options "before simplifying assumptions"
  2043       THEN asm_full_simp_tac HOL_basic_ss' 1
  2044       THEN print_tac options "before single intro rule"
  2045       THEN (rtac (if null clause_out_ts then @{thm singleI_unit} else @{thm singleI}) 1)
  2046     | prove_prems out_ts ((p, deriv) :: ps) =
  2047       let
  2048         val premposition = (find_index (equal p) clauses) + nargs
  2049         val mode = head_mode_of deriv
  2050         val rest_tac =
  2051           rtac @{thm bindI} 1
  2052           THEN (case p of Prem t =>
  2053             let
  2054               val (_, us) = strip_comb t
  2055               val (_, out_ts''') = split_mode mode us
  2056               val rec_tac = prove_prems out_ts''' ps
  2057             in
  2058               print_tac options "before clause:"
  2059               (*THEN asm_simp_tac HOL_basic_ss 1*)
  2060               THEN print_tac options "before prove_expr:"
  2061               THEN prove_expr options ctxt nargs premposition (t, deriv)
  2062               THEN print_tac options "after prove_expr:"
  2063               THEN rec_tac
  2064             end
  2065           | Negprem t =>
  2066             let
  2067               val (t, args) = strip_comb t
  2068               val (_, out_ts''') = split_mode mode args
  2069               val rec_tac = prove_prems out_ts''' ps
  2070               val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  2071               val neg_intro_rule =
  2072                 Option.map (fn name =>
  2073                   the (predfun_neg_intro_of ctxt name mode)) name
  2074               val param_derivations = param_derivations_of deriv
  2075               val params = ho_args_of mode args
  2076             in
  2077               print_tac options "before prove_neg_expr:"
  2078               THEN full_simp_tac (HOL_basic_ss addsimps
  2079                 [@{thm split_eta}, @{thm split_beta}, @{thm fst_conv},
  2080                  @{thm snd_conv}, @{thm pair_collapse}, @{thm Product_Type.split_conv}]) 1
  2081               THEN (if (is_some name) then
  2082                   print_tac options "before applying not introduction rule"
  2083                   THEN rotate_tac premposition 1
  2084                   THEN etac (the neg_intro_rule) 1
  2085                   THEN rotate_tac (~premposition) 1
  2086                   THEN print_tac options "after applying not introduction rule"
  2087                   THEN (EVERY (map2 (prove_param options ctxt nargs) params param_derivations))
  2088                   THEN (REPEAT_DETERM (atac 1))
  2089                 else
  2090                   rtac @{thm not_predI'} 1
  2091                   (* test: *)
  2092                   THEN dtac @{thm sym} 1
  2093                   THEN asm_full_simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1)
  2094                   THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  2095               THEN rec_tac
  2096             end
  2097           | Sidecond t =>
  2098            rtac @{thm if_predI} 1
  2099            THEN print_tac options "before sidecond:"
  2100            THEN prove_sidecond ctxt t
  2101            THEN print_tac options "after sidecond:"
  2102            THEN prove_prems [] ps)
  2103       in (prove_match options ctxt out_ts)
  2104           THEN rest_tac
  2105       end;
  2106     val prems_tac = prove_prems in_ts moded_ps
  2107   in
  2108     print_tac options "Proving clause..."
  2109     THEN rtac @{thm bindI} 1
  2110     THEN rtac @{thm singleI} 1
  2111     THEN prems_tac
  2112   end;
  2113 
  2114 fun select_sup 1 1 = []
  2115   | select_sup _ 1 = [rtac @{thm supI1}]
  2116   | select_sup n i = (rtac @{thm supI2})::(select_sup (n - 1) (i - 1));
  2117 
  2118 fun prove_one_direction options ctxt clauses preds pred mode moded_clauses =
  2119   let
  2120     val thy = ProofContext.theory_of ctxt
  2121     val T = the (AList.lookup (op =) preds pred)
  2122     val nargs = length (binder_types T)
  2123     val pred_case_rule = the_elim_of thy pred
  2124   in
  2125     REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"}))
  2126     THEN print_tac options "before applying elim rule"
  2127     THEN etac (predfun_elim_of ctxt pred mode) 1
  2128     THEN etac pred_case_rule 1
  2129     THEN print_tac options "after applying elim rule"
  2130     THEN (EVERY (map
  2131            (fn i => EVERY' (select_sup (length moded_clauses) i) i) 
  2132              (1 upto (length moded_clauses))))
  2133     THEN (EVERY (map2 (prove_clause options ctxt nargs mode) clauses moded_clauses))
  2134     THEN print_tac options "proved one direction"
  2135   end;
  2136 
  2137 (** Proof in the other direction **)
  2138 
  2139 fun prove_match2 options ctxt out_ts =
  2140   let
  2141     val thy = ProofContext.theory_of ctxt
  2142     fun split_term_tac (Free _) = all_tac
  2143       | split_term_tac t =
  2144         if (is_constructor thy t) then
  2145           let
  2146             val info = Datatype.the_info thy ((fst o dest_Type o fastype_of) t)
  2147             val num_of_constrs = length (#case_rewrites info)
  2148             val (_, ts) = strip_comb t
  2149           in
  2150             print_tac options ("Term " ^ (Syntax.string_of_term ctxt t) ^ 
  2151               "splitting with rules \n" ^ Display.string_of_thm ctxt (#split_asm info))
  2152             THEN TRY ((Splitter.split_asm_tac [#split_asm info] 1)
  2153               THEN (print_tac options "after splitting with split_asm rules")
  2154             (* THEN (Simplifier.asm_full_simp_tac HOL_basic_ss 1)
  2155               THEN (DETERM (TRY (etac @{thm Pair_inject} 1)))*)
  2156               THEN (REPEAT_DETERM_N (num_of_constrs - 1)
  2157                 (etac @{thm botE} 1 ORELSE etac @{thm botE} 2)))
  2158             THEN (assert_tac (Max_number_of_subgoals 2))
  2159             THEN (EVERY (map split_term_tac ts))
  2160           end
  2161       else all_tac
  2162   in
  2163     split_term_tac (HOLogic.mk_tuple out_ts)
  2164     THEN (DETERM (TRY ((Splitter.split_asm_tac [@{thm "split_if_asm"}] 1)
  2165     THEN (etac @{thm botE} 2))))
  2166   end
  2167 
  2168 (* VERY LARGE SIMILIRATIY to function prove_param 
  2169 -- join both functions
  2170 *)
  2171 (* TODO: remove function *)
  2172 
  2173 fun prove_param2 options ctxt t deriv =
  2174   let
  2175     val (f, args) = strip_comb (Envir.eta_contract t)
  2176     val mode = head_mode_of deriv
  2177     val param_derivations = param_derivations_of deriv
  2178     val ho_args = ho_args_of mode args
  2179     val f_tac = case f of
  2180         Const (name, T) => full_simp_tac (HOL_basic_ss addsimps 
  2181            (@{thm eval_pred}::(predfun_definition_of ctxt name mode)
  2182            :: @{thm "Product_Type.split_conv"}::[])) 1
  2183       | Free _ => all_tac
  2184       | _ => error "prove_param2: illegal parameter term"
  2185   in
  2186     print_tac options "before simplification in prove_args:"
  2187     THEN f_tac
  2188     THEN print_tac options "after simplification in prove_args"
  2189     THEN EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations)
  2190   end
  2191 
  2192 fun prove_expr2 options ctxt (t, deriv) = 
  2193   (case strip_comb t of
  2194       (Const (name, T), args) =>
  2195         let
  2196           val mode = head_mode_of deriv
  2197           val param_derivations = param_derivations_of deriv
  2198           val ho_args = ho_args_of mode args
  2199         in
  2200           etac @{thm bindE} 1
  2201           THEN (REPEAT_DETERM (CHANGED (rewtac @{thm "split_paired_all"})))
  2202           THEN print_tac options "prove_expr2-before"
  2203           THEN etac (predfun_elim_of ctxt name mode) 1
  2204           THEN print_tac options "prove_expr2"
  2205           THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
  2206           THEN print_tac options "finished prove_expr2"
  2207         end
  2208       | _ => etac @{thm bindE} 1)
  2209 
  2210 fun prove_sidecond2 options ctxt t = let
  2211   fun preds_of t nameTs = case strip_comb t of 
  2212     (f as Const (name, T), args) =>
  2213       if is_registered (ProofContext.theory_of ctxt) name then (name, T) :: nameTs
  2214         else fold preds_of args nameTs
  2215     | _ => nameTs
  2216   val preds = preds_of t []
  2217   val defs = map
  2218     (fn (pred, T) => predfun_definition_of ctxt pred 
  2219       (all_input_of T))
  2220       preds
  2221   in
  2222    (* only simplify the one assumption *)
  2223    full_simp_tac (HOL_basic_ss' addsimps @{thm eval_pred} :: defs) 1 
  2224    (* need better control here! *)
  2225    THEN print_tac options "after sidecond2 simplification"
  2226    end
  2227   
  2228 fun prove_clause2 options ctxt pred mode (ts, ps) i =
  2229   let
  2230     val pred_intro_rule = nth (intros_of (ProofContext.theory_of ctxt) pred) (i - 1)
  2231     val (in_ts, clause_out_ts) = split_mode mode ts;
  2232     fun prove_prems2 out_ts [] =
  2233       print_tac options "before prove_match2 - last call:"
  2234       THEN prove_match2 options ctxt out_ts
  2235       THEN print_tac options "after prove_match2 - last call:"
  2236       THEN (etac @{thm singleE} 1)
  2237       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  2238       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  2239       THEN (REPEAT_DETERM (etac @{thm Pair_inject} 1))
  2240       THEN (asm_full_simp_tac HOL_basic_ss' 1)
  2241       THEN SOLVED (print_tac options "state before applying intro rule:"
  2242       THEN (rtac pred_intro_rule 1)
  2243       (* How to handle equality correctly? *)
  2244       THEN (print_tac options "state before assumption matching")
  2245       THEN (REPEAT (atac 1 ORELSE 
  2246          (CHANGED (asm_full_simp_tac (HOL_basic_ss' addsimps
  2247            [@{thm split_eta}, @{thm "split_beta"}, @{thm "fst_conv"},
  2248              @{thm "snd_conv"}, @{thm pair_collapse}]) 1)
  2249           THEN print_tac options "state after simp_tac:"))))
  2250     | prove_prems2 out_ts ((p, deriv) :: ps) =
  2251       let
  2252         val mode = head_mode_of deriv
  2253         val rest_tac = (case p of
  2254           Prem t =>
  2255           let
  2256             val (_, us) = strip_comb t
  2257             val (_, out_ts''') = split_mode mode us
  2258             val rec_tac = prove_prems2 out_ts''' ps
  2259           in
  2260             (prove_expr2 options ctxt (t, deriv)) THEN rec_tac
  2261           end
  2262         | Negprem t =>
  2263           let
  2264             val (_, args) = strip_comb t
  2265             val (_, out_ts''') = split_mode mode args
  2266             val rec_tac = prove_prems2 out_ts''' ps
  2267             val name = (case strip_comb t of (Const (c, _), _) => SOME c | _ => NONE)
  2268             val param_derivations = param_derivations_of deriv
  2269             val ho_args = ho_args_of mode args
  2270           in
  2271             print_tac options "before neg prem 2"
  2272             THEN etac @{thm bindE} 1
  2273             THEN (if is_some name then
  2274                 full_simp_tac (HOL_basic_ss addsimps
  2275                   [predfun_definition_of ctxt (the name) mode]) 1
  2276                 THEN etac @{thm not_predE} 1
  2277                 THEN simp_tac (HOL_basic_ss addsimps [@{thm not_False_eq_True}]) 1
  2278                 THEN (EVERY (map2 (prove_param2 options ctxt) ho_args param_derivations))
  2279               else
  2280                 etac @{thm not_predE'} 1)
  2281             THEN rec_tac
  2282           end 
  2283         | Sidecond t =>
  2284           etac @{thm bindE} 1
  2285           THEN etac @{thm if_predE} 1
  2286           THEN prove_sidecond2 options ctxt t
  2287           THEN prove_prems2 [] ps)
  2288       in print_tac options "before prove_match2:"
  2289          THEN prove_match2 options ctxt out_ts
  2290          THEN print_tac options "after prove_match2:"
  2291          THEN rest_tac
  2292       end;
  2293     val prems_tac = prove_prems2 in_ts ps 
  2294   in
  2295     print_tac options "starting prove_clause2"
  2296     THEN etac @{thm bindE} 1
  2297     THEN (etac @{thm singleE'} 1)
  2298     THEN (TRY (etac @{thm Pair_inject} 1))
  2299     THEN print_tac options "after singleE':"
  2300     THEN prems_tac
  2301   end;
  2302  
  2303 fun prove_other_direction options ctxt pred mode moded_clauses =
  2304   let
  2305     fun prove_clause clause i =
  2306       (if i < length moded_clauses then etac @{thm supE} 1 else all_tac)
  2307       THEN (prove_clause2 options ctxt pred mode clause i)
  2308   in
  2309     (DETERM (TRY (rtac @{thm unit.induct} 1)))
  2310      THEN (REPEAT_DETERM (CHANGED (rewtac @{thm split_paired_all})))
  2311      THEN (rtac (predfun_intro_of ctxt pred mode) 1)
  2312      THEN (REPEAT_DETERM (rtac @{thm refl} 2))
  2313      THEN (if null moded_clauses then
  2314          etac @{thm botE} 1
  2315        else EVERY (map2 prove_clause moded_clauses (1 upto (length moded_clauses))))
  2316   end;
  2317 
  2318 (** proof procedure **)
  2319 
  2320 fun prove_pred options thy clauses preds pred (pol, mode) (moded_clauses, compiled_term) =
  2321   let
  2322     val ctxt = ProofContext.init thy
  2323     val clauses = case AList.lookup (op =) clauses pred of SOME rs => rs | NONE => []
  2324   in
  2325     Goal.prove ctxt (Term.add_free_names compiled_term []) [] compiled_term
  2326       (if not (skip_proof options) then
  2327         (fn _ =>
  2328         rtac @{thm pred_iffI} 1
  2329         THEN print_tac options "after pred_iffI"
  2330         THEN prove_one_direction options ctxt clauses preds pred mode moded_clauses
  2331         THEN print_tac options "proved one direction"
  2332         THEN prove_other_direction options ctxt pred mode moded_clauses
  2333         THEN print_tac options "proved other direction")
  2334       else (fn _ => Skip_Proof.cheat_tac thy))
  2335   end;
  2336 
  2337 (* composition of mode inference, definition, compilation and proof *)
  2338 
  2339 (** auxillary combinators for table of preds and modes **)
  2340 
  2341 fun map_preds_modes f preds_modes_table =
  2342   map (fn (pred, modes) =>
  2343     (pred, map (fn (mode, value) => (mode, f pred mode value)) modes)) preds_modes_table
  2344 
  2345 fun join_preds_modes table1 table2 =
  2346   map_preds_modes (fn pred => fn mode => fn value =>
  2347     (value, the (AList.lookup (op =) (the (AList.lookup (op =) table2 pred)) mode))) table1
  2348     
  2349 fun maps_modes preds_modes_table =
  2350   map (fn (pred, modes) =>
  2351     (pred, map (fn (mode, value) => value) modes)) preds_modes_table
  2352     
  2353 fun compile_preds comp_modifiers thy all_vs param_vs preds moded_clauses =
  2354   map_preds_modes (fn pred => compile_pred comp_modifiers thy all_vs param_vs pred
  2355       (the (AList.lookup (op =) preds pred))) moded_clauses
  2356 
  2357 fun prove options thy clauses preds moded_clauses compiled_terms =
  2358   map_preds_modes (prove_pred options thy clauses preds)
  2359     (join_preds_modes moded_clauses compiled_terms)
  2360 
  2361 fun prove_by_skip options thy _ _ _ compiled_terms =
  2362   map_preds_modes
  2363     (fn pred => fn mode => fn t => Drule.export_without_context (Skip_Proof.make_thm thy t))
  2364     compiled_terms
  2365 
  2366 (* preparation of introduction rules into special datastructures *)
  2367 
  2368 fun dest_prem thy params t =
  2369   (case strip_comb t of
  2370     (v as Free _, ts) => if member (op =) params v then Prem t else Sidecond t
  2371   | (c as Const (@{const_name Not}, _), [t]) => (case dest_prem thy params t of
  2372       Prem t => Negprem t
  2373     | Negprem _ => error ("Double negation not allowed in premise: " ^
  2374         Syntax.string_of_term_global thy (c $ t)) 
  2375     | Sidecond t => Sidecond (c $ t))
  2376   | (c as Const (s, _), ts) =>
  2377     if is_registered thy s then Prem t else Sidecond t
  2378   | _ => Sidecond t)
  2379 
  2380 fun prepare_intrs options compilation thy prednames intros =
  2381   let
  2382     val intrs = map prop_of intros
  2383     val preds = map (fn c => Const (c, Sign.the_const_type thy c)) prednames
  2384     val (preds, intrs) = unify_consts thy preds intrs
  2385     val ([preds, intrs], _) = fold_burrow (Variable.import_terms false) [preds, intrs]
  2386       (ProofContext.init thy)
  2387     val preds = map dest_Const preds
  2388     val all_vs = terms_vs intrs
  2389     val all_modes = 
  2390       map (fn (s, T) =>
  2391         (s,
  2392             (if member (op =) (no_higher_order_predicate options) s then
  2393                (all_smodes_of_typ T)
  2394             else (all_modes_of_typ T)))) preds
  2395     val params =
  2396       case intrs of
  2397         [] =>
  2398           let
  2399             val T = snd (hd preds)
  2400             val paramTs =
  2401               ho_argsT_of (hd (all_modes_of_typ T)) (binder_types T)
  2402             val param_names = Name.variant_list [] (map (fn i => "p" ^ string_of_int i)
  2403               (1 upto length paramTs))
  2404           in
  2405             map2 (curry Free) param_names paramTs
  2406           end
  2407       | (intr :: _) =>
  2408         let
  2409           val (p, args) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr)) 
  2410         in
  2411           ho_args_of (hd (the (AList.lookup (op =) all_modes (fst (dest_Const p))))) args
  2412         end
  2413     val param_vs = map (fst o dest_Free) params
  2414     fun add_clause intr clauses =
  2415       let
  2416         val (Const (name, T), ts) = strip_comb (HOLogic.dest_Trueprop (Logic.strip_imp_concl intr))
  2417         val prems = map (dest_prem thy params o HOLogic.dest_Trueprop) (Logic.strip_imp_prems intr)
  2418       in
  2419         AList.update op = (name, these (AList.lookup op = clauses name) @
  2420           [(ts, prems)]) clauses
  2421       end;
  2422     val clauses = fold add_clause intrs []
  2423   in
  2424     (preds, all_vs, param_vs, all_modes, clauses)
  2425   end;
  2426 
  2427 (* sanity check of introduction rules *)
  2428 (* TODO: rethink check with new modes *)
  2429 (*
  2430 fun check_format_of_intro_rule thy intro =
  2431   let
  2432     val concl = Logic.strip_imp_concl (prop_of intro)
  2433     val (p, args) = strip_comb (HOLogic.dest_Trueprop concl)
  2434     val params = fst (chop (nparams_of thy (fst (dest_Const p))) args)
  2435     fun check_arg arg = case HOLogic.strip_tupleT (fastype_of arg) of
  2436       (Ts as _ :: _ :: _) =>
  2437         if length (HOLogic.strip_tuple arg) = length Ts then
  2438           true
  2439         else
  2440           error ("Format of introduction rule is invalid: tuples must be expanded:"
  2441           ^ (Syntax.string_of_term_global thy arg) ^ " in " ^
  2442           (Display.string_of_thm_global thy intro)) 
  2443       | _ => true
  2444     val prems = Logic.strip_imp_prems (prop_of intro)
  2445     fun check_prem (Prem t) = forall check_arg args
  2446       | check_prem (Negprem t) = forall check_arg args
  2447       | check_prem _ = true
  2448   in
  2449     forall check_arg args andalso
  2450     forall (check_prem o dest_prem thy params o HOLogic.dest_Trueprop) prems
  2451   end
  2452 *)
  2453 (*
  2454 fun check_intros_elim_match thy prednames =
  2455   let
  2456     fun check predname =
  2457       let
  2458         val intros = intros_of thy predname
  2459         val elim = the_elim_of thy predname
  2460         val nparams = nparams_of thy predname
  2461         val elim' =
  2462           (Drule.export_without_context o Skip_Proof.make_thm thy)
  2463           (mk_casesrule (ProofContext.init thy) nparams intros)
  2464       in
  2465         if not (Thm.equiv_thm (elim, elim')) then
  2466           error "Introduction and elimination rules do not match!"
  2467         else true
  2468       end
  2469   in forall check prednames end
  2470 *)
  2471 
  2472 (* create code equation *)
  2473 
  2474 fun add_code_equations thy preds result_thmss =
  2475   let
  2476     val ctxt = ProofContext.init thy
  2477     fun add_code_equation (predname, T) (pred, result_thms) =
  2478       let
  2479         val full_mode = fold_rev (curry Fun) (map (K Input) (binder_types T)) Bool
  2480       in
  2481         if member (op =) (modes_of Pred thy predname) full_mode then
  2482           let
  2483             val Ts = binder_types T
  2484             val arg_names = Name.variant_list []
  2485               (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
  2486             val args = map2 (curry Free) arg_names Ts
  2487             val predfun = Const (function_name_of Pred thy predname (true, full_mode),
  2488               Ts ---> PredicateCompFuns.mk_predT @{typ unit})
  2489             val rhs = @{term Predicate.holds} $ (list_comb (predfun, args))
  2490             val eq_term = HOLogic.mk_Trueprop
  2491               (HOLogic.mk_eq (list_comb (Const (predname, T), args), rhs))
  2492             val def = predfun_definition_of ctxt predname full_mode
  2493             val tac = fn _ => Simplifier.simp_tac
  2494               (HOL_basic_ss addsimps [def, @{thm holds_eq}, @{thm eval_pred}]) 1
  2495             val eq = Goal.prove ctxt arg_names [] eq_term tac
  2496           in
  2497             (pred, result_thms @ [eq])
  2498           end
  2499         else
  2500           (pred, result_thms)
  2501       end
  2502   in
  2503     map2 add_code_equation preds result_thmss
  2504   end
  2505 
  2506 (** main function of predicate compiler **)
  2507 
  2508 datatype steps = Steps of
  2509   {
  2510   define_functions : options -> (string * typ) list -> string * (bool * mode) list -> theory -> theory,
  2511   (*infer_modes : options -> (string * typ) list -> (string * mode list) list
  2512     -> string list -> (string * (term list * indprem list) list) list
  2513     -> theory -> ((moded_clause list pred_mode_table * string list) * theory),*)
  2514   prove : options -> theory -> (string * (term list * indprem list) list) list -> (string * typ) list
  2515     -> moded_clause list pred_mode_table -> term pred_mode_table -> thm pred_mode_table,
  2516   add_code_equations : theory -> (string * typ) list
  2517     -> (string * thm list) list -> (string * thm list) list,
  2518   comp_modifiers : Comp_Mod.comp_modifiers,
  2519   use_random : bool,
  2520   qname : bstring
  2521   }
  2522 
  2523 fun add_equations_of steps mode_analysis_options options prednames thy =
  2524   let
  2525     fun dest_steps (Steps s) = s
  2526     val compilation = Comp_Mod.compilation (#comp_modifiers (dest_steps steps))
  2527     val _ = print_step options
  2528       ("Starting predicate compiler (compilation: " ^ string_of_compilation compilation
  2529         ^ ") for predicates " ^ commas prednames ^ "...")
  2530       (*val _ = check_intros_elim_match thy prednames*)
  2531       (*val _ = map (check_format_of_intro_rule thy) (maps (intros_of thy) prednames)*)
  2532     val _ =
  2533       if show_intermediate_results options then
  2534         tracing (commas (map (Display.string_of_thm_global thy) (maps (intros_of thy) prednames)))
  2535       else ()
  2536     val (preds, all_vs, param_vs, all_modes, clauses) =
  2537       prepare_intrs options compilation thy prednames (maps (intros_of thy) prednames)
  2538     val _ = print_step options "Infering modes..."
  2539     val ((moded_clauses, errors), thy') =
  2540       (*Output.cond_timeit true "Infering modes"
  2541       (fn _ =>*) infer_modes mode_analysis_options
  2542         options compilation preds all_modes param_vs clauses thy
  2543     val modes = map (fn (p, mps) => (p, map fst mps)) moded_clauses
  2544     val _ = check_expected_modes preds options modes
  2545     (*val _ = check_proposed_modes preds options modes (fst extra_modes) errors*)
  2546     val _ = print_modes options thy' modes
  2547     val _ = print_step options "Defining executable functions..."
  2548     val thy'' = fold (#define_functions (dest_steps steps) options preds) modes thy'
  2549       |> Theory.checkpoint
  2550     val _ = print_step options "Compiling equations..."
  2551     val compiled_terms =
  2552       compile_preds (#comp_modifiers (dest_steps steps)) thy'' all_vs param_vs preds moded_clauses
  2553     val _ = print_compiled_terms options thy'' compiled_terms
  2554     val _ = print_step options "Proving equations..."
  2555     val result_thms =
  2556       #prove (dest_steps steps) options thy'' clauses preds moded_clauses compiled_terms
  2557     val result_thms' = #add_code_equations (dest_steps steps) thy'' preds
  2558       (maps_modes result_thms)
  2559     val qname = #qname (dest_steps steps)
  2560     val attrib = fn thy => Attrib.attribute_i thy (Attrib.internal (K (Thm.declaration_attribute
  2561       (fn thm => Context.mapping (Code.add_eqn thm) I))))
  2562     val thy''' = fold (fn (name, result_thms) => fn thy => snd (PureThy.add_thmss
  2563       [((Binding.qualify true (Long_Name.base_name name) (Binding.name qname), result_thms),
  2564         [attrib thy ])] thy))
  2565       result_thms' thy'' |> Theory.checkpoint
  2566   in
  2567     thy'''
  2568   end
  2569 
  2570 fun extend' value_of edges_of key (G, visited) =
  2571   let
  2572     val (G', v) = case try (Graph.get_node G) key of
  2573         SOME v => (G, v)
  2574       | NONE => (Graph.new_node (key, value_of key) G, value_of key)
  2575     val (G'', visited') = fold (extend' value_of edges_of)
  2576       (subtract (op =) visited (edges_of (key, v)))
  2577       (G', key :: visited)
  2578   in
  2579     (fold (Graph.add_edge o (pair key)) (edges_of (key, v)) G'', visited')
  2580   end;
  2581 
  2582 fun extend value_of edges_of key G = fst (extend' value_of edges_of key (G, [])) 
  2583   
  2584 fun gen_add_equations steps options names thy =
  2585   let
  2586     fun dest_steps (Steps s) = s
  2587     val defined = defined_functions (Comp_Mod.compilation (#comp_modifiers (dest_steps steps)))
  2588     val thy' = thy
  2589       |> PredData.map (fold (extend (fetch_pred_data thy) (depending_preds_of thy)) names)
  2590       |> Theory.checkpoint;
  2591     fun strong_conn_of gr keys =
  2592       Graph.strong_conn (Graph.subgraph (member (op =) (Graph.all_succs gr keys)) gr)
  2593     val scc = strong_conn_of (PredData.get thy') names
  2594     
  2595     val thy'' = fold_rev
  2596       (fn preds => fn thy =>
  2597         if not (forall (defined thy) preds) then
  2598           let
  2599             val mode_analysis_options = {use_random = #use_random (dest_steps steps),
  2600               reorder_premises =
  2601                 not (no_topmost_reordering options andalso not (null (inter (op =) preds names))),
  2602               infer_pos_and_neg_modes = #use_random (dest_steps steps)}
  2603           in
  2604             add_equations_of steps mode_analysis_options options preds thy
  2605           end
  2606         else thy)
  2607       scc thy' |> Theory.checkpoint
  2608   in thy'' end
  2609 
  2610 val depth_limited_comp_modifiers = Comp_Mod.Comp_Modifiers
  2611   {
  2612   compilation = Depth_Limited,
  2613   function_name_prefix = "depth_limited_",
  2614   compfuns = PredicateCompFuns.compfuns,
  2615   mk_random = (fn _ => error "no random generation"),
  2616   additional_arguments = fn names =>
  2617     let
  2618       val depth_name = Name.variant names "depth"
  2619     in [Free (depth_name, @{typ code_numeral})] end,
  2620   modify_funT = (fn T => let val (Ts, U) = strip_type T
  2621   val Ts' = [@{typ code_numeral}] in (Ts @ Ts') ---> U end),
  2622   wrap_compilation =
  2623     fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  2624     let
  2625       val [depth] = additional_arguments
  2626       val (_, Ts) = split_modeT' mode (binder_types T)
  2627       val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
  2628       val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
  2629     in
  2630       if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
  2631         $ mk_bot compfuns (dest_predT compfuns T')
  2632         $ compilation
  2633     end,
  2634   transform_additional_arguments =
  2635     fn prem => fn additional_arguments =>
  2636     let
  2637       val [depth] = additional_arguments
  2638       val depth' =
  2639         Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
  2640           $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
  2641     in [depth'] end
  2642   }
  2643 
  2644 val random_comp_modifiers = Comp_Mod.Comp_Modifiers
  2645   {
  2646   compilation = Random,
  2647   function_name_prefix = "random_",
  2648   compfuns = PredicateCompFuns.compfuns,
  2649   mk_random = (fn T => fn additional_arguments =>
  2650   list_comb (Const(@{const_name Quickcheck.iter},
  2651   [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
  2652     PredicateCompFuns.mk_predT T), additional_arguments)),
  2653   modify_funT = (fn T =>
  2654     let
  2655       val (Ts, U) = strip_type T
  2656       val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ "code_numeral * code_numeral"}]
  2657     in (Ts @ Ts') ---> U end),
  2658   additional_arguments = (fn names =>
  2659     let
  2660       val [nrandom, size, seed] = Name.variant_list names ["nrandom", "size", "seed"]
  2661     in
  2662       [Free (nrandom, @{typ code_numeral}), Free (size, @{typ code_numeral}),
  2663         Free (seed, @{typ "code_numeral * code_numeral"})]
  2664     end),
  2665   wrap_compilation = K (K (K (K (K I))))
  2666     : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  2667   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2668   }
  2669 
  2670 val depth_limited_random_comp_modifiers = Comp_Mod.Comp_Modifiers
  2671   {
  2672   compilation = Depth_Limited_Random,
  2673   function_name_prefix = "depth_limited_random_",
  2674   compfuns = PredicateCompFuns.compfuns,
  2675   mk_random = (fn T => fn additional_arguments =>
  2676   list_comb (Const(@{const_name Quickcheck.iter},
  2677   [@{typ code_numeral}, @{typ code_numeral}, @{typ Random.seed}] ---> 
  2678     PredicateCompFuns.mk_predT T), tl additional_arguments)),
  2679   modify_funT = (fn T =>
  2680     let
  2681       val (Ts, U) = strip_type T
  2682       val Ts' = [@{typ code_numeral}, @{typ code_numeral}, @{typ code_numeral},
  2683         @{typ "code_numeral * code_numeral"}]
  2684     in (Ts @ Ts') ---> U end),
  2685   additional_arguments = (fn names =>
  2686     let
  2687       val [depth, nrandom, size, seed] = Name.variant_list names ["depth", "nrandom", "size", "seed"]
  2688     in
  2689       [Free (depth, @{typ code_numeral}), Free (nrandom, @{typ code_numeral}),
  2690         Free (size, @{typ code_numeral}), Free (seed, @{typ "code_numeral * code_numeral"})]
  2691     end),
  2692   wrap_compilation =
  2693   fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  2694     let
  2695       val depth = hd (additional_arguments)
  2696       val (_, Ts) = split_modeT' mode (binder_types T)
  2697       val T' = mk_predT compfuns (HOLogic.mk_tupleT Ts)
  2698       val if_const = Const (@{const_name "If"}, @{typ bool} --> T' --> T' --> T')
  2699     in
  2700       if_const $ HOLogic.mk_eq (depth, @{term "0 :: code_numeral"})
  2701         $ mk_bot compfuns (dest_predT compfuns T')
  2702         $ compilation
  2703     end,
  2704   transform_additional_arguments =
  2705     fn prem => fn additional_arguments =>
  2706     let
  2707       val [depth, nrandom, size, seed] = additional_arguments
  2708       val depth' =
  2709         Const (@{const_name Groups.minus}, @{typ "code_numeral => code_numeral => code_numeral"})
  2710           $ depth $ Const (@{const_name Groups.one}, @{typ "Code_Numeral.code_numeral"})
  2711     in [depth', nrandom, size, seed] end
  2712 }
  2713 
  2714 (* different instantiantions of the predicate compiler *)
  2715 
  2716 val predicate_comp_modifiers = Comp_Mod.Comp_Modifiers
  2717   {
  2718   compilation = Pred,
  2719   function_name_prefix = "",
  2720   compfuns = PredicateCompFuns.compfuns,
  2721   mk_random = (fn _ => error "no random generation"),
  2722   modify_funT = I,
  2723   additional_arguments = K [],
  2724   wrap_compilation = K (K (K (K (K I))))
  2725    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  2726   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2727   }
  2728 
  2729 val add_equations = gen_add_equations
  2730   (Steps {
  2731   define_functions =
  2732     fn options => fn preds => fn (s, modes) =>
  2733       create_definitions
  2734       options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2735   prove = prove,
  2736   add_code_equations = add_code_equations,
  2737   comp_modifiers = predicate_comp_modifiers,
  2738   use_random = false,
  2739   qname = "equation"})
  2740 
  2741 val annotated_comp_modifiers = Comp_Mod.Comp_Modifiers
  2742   {
  2743   compilation = Annotated,
  2744   function_name_prefix = "annotated_",
  2745   compfuns = PredicateCompFuns.compfuns,
  2746   mk_random = (fn _ => error "no random generation"),
  2747   modify_funT = I,
  2748   additional_arguments = K [],
  2749   wrap_compilation =
  2750     fn compfuns => fn s => fn T => fn mode => fn additional_arguments => fn compilation =>
  2751       mk_tracing ("calling predicate " ^ s ^
  2752         " with mode " ^ string_of_mode mode) compilation,
  2753   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2754   }
  2755 
  2756 val dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  2757   {
  2758   compilation = DSeq,
  2759   function_name_prefix = "dseq_",
  2760   compfuns = DSequence_CompFuns.compfuns,
  2761   mk_random = (fn _ => error "no random generation"),
  2762   modify_funT = I,
  2763   additional_arguments = K [],
  2764   wrap_compilation = K (K (K (K (K I))))
  2765    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  2766   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2767   }
  2768 
  2769 val pos_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  2770   {
  2771   compilation = Pos_Random_DSeq,
  2772   function_name_prefix = "random_dseq_",
  2773   compfuns = Random_Sequence_CompFuns.compfuns,
  2774   mk_random = (fn T => fn additional_arguments =>
  2775   let
  2776     val random = Const ("Quickcheck.random_class.random",
  2777       @{typ code_numeral} --> @{typ Random.seed} -->
  2778         HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed}))
  2779   in
  2780     Const ("Random_Sequence.Random", (@{typ code_numeral} --> @{typ Random.seed} -->
  2781       HOLogic.mk_prodT (HOLogic.mk_prodT (T, @{typ "unit => term"}), @{typ Random.seed})) -->
  2782       Random_Sequence_CompFuns.mk_random_dseqT T) $ random
  2783   end),
  2784 
  2785   modify_funT = I,
  2786   additional_arguments = K [],
  2787   wrap_compilation = K (K (K (K (K I))))
  2788    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  2789   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2790   }
  2791 
  2792 val neg_random_dseq_comp_modifiers = Comp_Mod.Comp_Modifiers
  2793   {
  2794   compilation = Neg_Random_DSeq,
  2795   function_name_prefix = "random_dseq_neg_",
  2796   compfuns = Random_Sequence_CompFuns.compfuns,
  2797   mk_random = (fn _ => error "no random generation"),
  2798   modify_funT = I,
  2799   additional_arguments = K [],
  2800   wrap_compilation = K (K (K (K (K I))))
  2801    : (compilation_funs -> string -> typ -> mode -> term list -> term -> term),
  2802   transform_additional_arguments = K I : (indprem -> term list -> term list)
  2803   }
  2804 
  2805 val add_depth_limited_equations = gen_add_equations
  2806   (Steps {
  2807   define_functions =
  2808     fn options => fn preds => fn (s, modes) =>
  2809     define_functions depth_limited_comp_modifiers PredicateCompFuns.compfuns
  2810     options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2811   prove = prove_by_skip,
  2812   add_code_equations = K (K I),
  2813   comp_modifiers = depth_limited_comp_modifiers,
  2814   use_random = false,
  2815   qname = "depth_limited_equation"})
  2816 
  2817 val add_annotated_equations = gen_add_equations
  2818   (Steps {
  2819   define_functions =
  2820     fn options => fn preds => fn (s, modes) =>
  2821       define_functions annotated_comp_modifiers PredicateCompFuns.compfuns options preds
  2822       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2823   prove = prove_by_skip,
  2824   add_code_equations = K (K I),
  2825   comp_modifiers = annotated_comp_modifiers,
  2826   use_random = false,
  2827   qname = "annotated_equation"})
  2828 
  2829 val add_random_equations = gen_add_equations
  2830   (Steps {
  2831   define_functions =
  2832     fn options => fn preds => fn (s, modes) =>
  2833       define_functions random_comp_modifiers PredicateCompFuns.compfuns options preds
  2834       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2835   comp_modifiers = random_comp_modifiers,
  2836   prove = prove_by_skip,
  2837   add_code_equations = K (K I),
  2838   use_random = true,
  2839   qname = "random_equation"})
  2840 
  2841 val add_depth_limited_random_equations = gen_add_equations
  2842   (Steps {
  2843   define_functions =
  2844     fn options => fn preds => fn (s, modes) =>
  2845       define_functions depth_limited_random_comp_modifiers PredicateCompFuns.compfuns options preds
  2846       (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2847   comp_modifiers = depth_limited_random_comp_modifiers,
  2848   prove = prove_by_skip,
  2849   add_code_equations = K (K I),
  2850   use_random = true,
  2851   qname = "depth_limited_random_equation"})
  2852 
  2853 val add_dseq_equations = gen_add_equations
  2854   (Steps {
  2855   define_functions =
  2856   fn options => fn preds => fn (s, modes) =>
  2857     define_functions dseq_comp_modifiers DSequence_CompFuns.compfuns
  2858     options preds (s, map_filter (fn (true, m) => SOME m | _ => NONE) modes),
  2859   prove = prove_by_skip,
  2860   add_code_equations = K (K I),
  2861   comp_modifiers = dseq_comp_modifiers,
  2862   use_random = false,
  2863   qname = "dseq_equation"})
  2864 
  2865 val add_random_dseq_equations = gen_add_equations
  2866   (Steps {
  2867   define_functions =
  2868     fn options => fn preds => fn (s, modes) =>
  2869     let
  2870       val pos_modes = map_filter (fn (true, m) => SOME m | _ => NONE) modes
  2871       val neg_modes = map_filter (fn (false, m) => SOME m | _ => NONE) modes
  2872     in define_functions pos_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
  2873       options preds (s, pos_modes)
  2874       #> define_functions neg_random_dseq_comp_modifiers Random_Sequence_CompFuns.compfuns
  2875       options preds (s, neg_modes)
  2876     end,
  2877   prove = prove_by_skip,
  2878   add_code_equations = K (K I),
  2879   comp_modifiers = pos_random_dseq_comp_modifiers,
  2880   use_random = true,
  2881   qname = "random_dseq_equation"})
  2882 
  2883 
  2884 (** user interface **)
  2885 
  2886 (* code_pred_intro attribute *)
  2887 
  2888 fun attrib f = Thm.declaration_attribute (fn thm => Context.mapping (f thm) I);
  2889 
  2890 val code_pred_intro_attrib = attrib add_intro;
  2891 
  2892 
  2893 (*FIXME
  2894 - Naming of auxiliary rules necessary?
  2895 *)
  2896 
  2897 val setup = PredData.put (Graph.empty) #>
  2898   Attrib.setup @{binding code_pred_intro} (Scan.succeed (attrib add_intro))
  2899     "adding alternative introduction rules for code generation of inductive predicates"
  2900 
  2901 (* TODO: make Theory_Data to Generic_Data & remove duplication of local theory and theory *)
  2902 fun generic_code_pred prep_const options raw_const lthy =
  2903   let
  2904     val thy = ProofContext.theory_of lthy
  2905     val const = prep_const thy raw_const
  2906     val lthy' = Local_Theory.theory (PredData.map
  2907         (extend (fetch_pred_data thy) (depending_preds_of thy) const)) lthy
  2908       |> Local_Theory.checkpoint
  2909     val thy' = ProofContext.theory_of lthy'
  2910     val preds = Graph.all_succs (PredData.get thy') [const] |> filter_out (has_elim thy')
  2911     fun mk_cases const =
  2912       let
  2913         val T = Sign.the_const_type thy const
  2914         val pred = Const (const, T)
  2915         val intros = intros_of thy' const
  2916       in mk_casesrule lthy' pred intros end  
  2917     val cases_rules = map mk_cases preds
  2918     val cases =
  2919       map (fn case_rule => Rule_Cases.Case {fixes = [],
  2920         assumes = [("", Logic.strip_imp_prems case_rule)],
  2921         binds = [], cases = []}) cases_rules
  2922     val case_env = map2 (fn p => fn c => (Long_Name.base_name p, SOME c)) preds cases
  2923     val lthy'' = lthy'
  2924       |> fold Variable.auto_fixes cases_rules 
  2925       |> ProofContext.add_cases true case_env
  2926     fun after_qed thms goal_ctxt =
  2927       let
  2928         val global_thms = ProofContext.export goal_ctxt
  2929           (ProofContext.init (ProofContext.theory_of goal_ctxt)) (map the_single thms)
  2930       in
  2931         goal_ctxt |> Local_Theory.theory (fold set_elim global_thms #>
  2932           ((case compilation options of
  2933              Pred => add_equations
  2934            | DSeq => add_dseq_equations
  2935            | Pos_Random_DSeq => add_random_dseq_equations
  2936            | Depth_Limited => add_depth_limited_equations
  2937            | Random => add_random_equations
  2938            | Depth_Limited_Random => add_depth_limited_random_equations
  2939            | compilation => error ("Compilation not supported")
  2940            ) options [const]))
  2941       end
  2942   in
  2943     Proof.theorem_i NONE after_qed (map (single o (rpair [])) cases_rules) lthy''
  2944   end;
  2945 
  2946 val code_pred = generic_code_pred (K I);
  2947 val code_pred_cmd = generic_code_pred Code.read_const
  2948 
  2949 (* transformation for code generation *)
  2950 
  2951 val eval_ref = Unsynchronized.ref (NONE : (unit -> term Predicate.pred) option);
  2952 val random_eval_ref =
  2953   Unsynchronized.ref (NONE : (unit -> int * int -> term Predicate.pred * (int * int)) option);
  2954 val dseq_eval_ref = Unsynchronized.ref (NONE : (unit -> term DSequence.dseq) option);
  2955 val random_dseq_eval_ref =
  2956   Unsynchronized.ref (NONE : (unit -> int -> int -> int * int -> term DSequence.dseq * (int * int)) option);
  2957 
  2958 (*FIXME turn this into an LCF-guarded preprocessor for comprehensions*)
  2959 fun analyze_compr thy compfuns param_user_modes (compilation, arguments) t_compr =
  2960   let
  2961     val all_modes_of = all_modes_of compilation
  2962     val split = case t_compr of (Const (@{const_name Collect}, _) $ t) => t
  2963       | _ => error ("Not a set comprehension: " ^ Syntax.string_of_term_global thy t_compr);
  2964     val (body, Ts, fp) = HOLogic.strip_psplits split;
  2965     val output_names = Name.variant_list (Term.add_free_names body [])
  2966       (map (fn i => "x" ^ string_of_int i) (1 upto length Ts))
  2967     val output_frees = map2 (curry Free) output_names (rev Ts)
  2968     val body = subst_bounds (output_frees, body)
  2969     val T_compr = HOLogic.mk_ptupleT fp Ts
  2970     val output_tuple = HOLogic.mk_ptuple fp T_compr (rev output_frees)
  2971     val (pred as Const (name, T), all_args) = strip_comb body
  2972   in
  2973     if defined_functions compilation thy name then
  2974       let
  2975         fun extract_mode (Const ("Pair", _) $ t1 $ t2) = Pair (extract_mode t1, extract_mode t2)
  2976           | extract_mode (Free (x, _)) = if member (op =) output_names x then Output else Input
  2977           | extract_mode _ = Input
  2978         val user_mode = fold_rev (curry Fun) (map extract_mode all_args) Bool
  2979         fun valid modes1 modes2 =
  2980           case int_ord (length modes1, length modes2) of
  2981             GREATER => error "Not enough mode annotations"
  2982           | LESS => error "Too many mode annotations"
  2983           | EQUAL => forall (fn (m, NONE) => true | (m, SOME m2) => eq_mode (m, m2))
  2984             (modes1 ~~ modes2)
  2985         fun mode_instance_of (m1, m2) =
  2986           let
  2987             fun instance_of (Fun _, Input) = true
  2988               | instance_of (Input, Input) = true
  2989               | instance_of (Output, Output) = true
  2990               | instance_of (Pair (m1, m2), Pair (m1', m2')) =
  2991                   instance_of  (m1, m1') andalso instance_of (m2, m2')
  2992               | instance_of (Pair (m1, m2), Input) =
  2993                   instance_of (m1, Input) andalso instance_of (m2, Input)
  2994               | instance_of (Pair (m1, m2), Output) =
  2995                   instance_of (m1, Output) andalso instance_of (m2, Output)
  2996               | instance_of _ = false
  2997           in forall instance_of (strip_fun_mode m1 ~~ strip_fun_mode m2) end
  2998         val derivs = all_derivations_of thy (all_modes_of thy) [] body
  2999           |> filter (fn (d, missing_vars) =>
  3000             let
  3001               val (p_mode :: modes) = collect_context_modes d
  3002             in
  3003               null missing_vars andalso
  3004               mode_instance_of (p_mode, user_mode) andalso
  3005               the_default true (Option.map (valid modes) param_user_modes)
  3006             end)
  3007           |> map fst
  3008         val deriv = case derivs of
  3009             [] => error ("No mode possible for comprehension "
  3010                     ^ Syntax.string_of_term_global thy t_compr)
  3011           | [d] => d
  3012           | d :: _ :: _ => (warning ("Multiple modes possible for comprehension "
  3013                     ^ Syntax.string_of_term_global thy t_compr); d);
  3014         val (_, outargs) = split_mode (head_mode_of deriv) all_args
  3015         val additional_arguments =
  3016           case compilation of
  3017             Pred => []
  3018           | Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
  3019             [@{term "(1, 1) :: code_numeral * code_numeral"}]
  3020           | Annotated => []
  3021           | Depth_Limited => [HOLogic.mk_number @{typ "code_numeral"} (hd arguments)]
  3022           | Depth_Limited_Random => map (HOLogic.mk_number @{typ "code_numeral"}) arguments @
  3023             [@{term "(1, 1) :: code_numeral * code_numeral"}]
  3024           | DSeq => []
  3025           | Pos_Random_DSeq => []
  3026         val comp_modifiers =
  3027           case compilation of
  3028             Pred => predicate_comp_modifiers
  3029           | Random => random_comp_modifiers
  3030           | Depth_Limited => depth_limited_comp_modifiers
  3031           | Depth_Limited_Random => depth_limited_random_comp_modifiers
  3032           (*| Annotated => annotated_comp_modifiers*)
  3033           | DSeq => dseq_comp_modifiers
  3034           | Pos_Random_DSeq => pos_random_dseq_comp_modifiers
  3035         val t_pred = compile_expr comp_modifiers compfuns thy true (body, deriv) additional_arguments;
  3036         val T_pred = dest_predT compfuns (fastype_of t_pred)
  3037         val arrange = split_lambda (HOLogic.mk_tuple outargs) output_tuple
  3038       in
  3039         if null outargs then t_pred else mk_map compfuns T_pred T_compr arrange t_pred
  3040       end
  3041     else
  3042       error "Evaluation with values is not possible because compilation with code_pred was not invoked"
  3043   end
  3044 
  3045 fun eval thy param_user_modes (options as (compilation, arguments)) k t_compr =
  3046   let
  3047     val compfuns =
  3048       case compilation of
  3049         Random => PredicateCompFuns.compfuns
  3050       | DSeq => DSequence_CompFuns.compfuns
  3051       | Pos_Random_DSeq => Random_Sequence_CompFuns.compfuns
  3052       | _ => PredicateCompFuns.compfuns
  3053     val t = analyze_compr thy compfuns param_user_modes options t_compr;
  3054     val T = dest_predT compfuns (fastype_of t);
  3055     val t' = mk_map compfuns T HOLogic.termT (HOLogic.term_of_const T) t;
  3056     val ts =
  3057       case compilation of
  3058        (* Random =>
  3059           fst (Predicate.yieldn k
  3060           (Code_Eval.eval NONE ("Predicate_Compile_Core.random_eval_ref", random_eval_ref)
  3061             (fn proc => fn g => fn s => g s |>> Predicate.map proc) thy t' []
  3062             |> Random_Engine.run))*)
  3063         Pos_Random_DSeq =>
  3064           let
  3065             val [nrandom, size, depth] = arguments
  3066           in
  3067             fst (DSequence.yieldn k
  3068               (Code_Eval.eval NONE ("Predicate_Compile_Core.random_dseq_eval_ref", random_dseq_eval_ref)
  3069                 (fn proc => fn g => fn nrandom => fn size => fn s => g nrandom size s |>> DSequence.map proc)
  3070                   thy t' [] nrandom size
  3071                 |> Random_Engine.run)
  3072               depth true)
  3073           end
  3074       | DSeq =>
  3075           fst (DSequence.yieldn k
  3076             (Code_Eval.eval NONE ("Predicate_Compile_Core.dseq_eval_ref", dseq_eval_ref)
  3077               DSequence.map thy t' []) (the_single arguments) true)
  3078       | _ =>
  3079           fst (Predicate.yieldn k
  3080             (Code_Eval.eval NONE ("Predicate_Compile_Core.eval_ref", eval_ref)
  3081               Predicate.map thy t' []))
  3082   in (T, ts) end;
  3083 
  3084 fun values ctxt param_user_modes (raw_expected, comp_options) k t_compr =
  3085   let
  3086     val thy = ProofContext.theory_of ctxt
  3087     val (T, ts) = eval thy param_user_modes comp_options k t_compr
  3088     val setT = HOLogic.mk_setT T
  3089     val elems = HOLogic.mk_set T ts
  3090     val cont = Free ("...", setT)
  3091     (* check expected values *)
  3092     val () =
  3093       case raw_expected of
  3094         NONE => ()
  3095       | SOME s =>
  3096         if eq_set (op =) (HOLogic.dest_set (Syntax.read_term ctxt s), ts) then ()
  3097         else
  3098           error ("expected and computed values do not match:\n" ^
  3099             "expected values: " ^ Syntax.string_of_term ctxt (Syntax.read_term ctxt s) ^ "\n" ^
  3100             "computed values: " ^ Syntax.string_of_term ctxt elems ^ "\n")
  3101   in
  3102     if k = ~1 orelse length ts < k then elems
  3103       else Const (@{const_abbrev Set.union}, setT --> setT --> setT) $ elems $ cont
  3104   end;
  3105 
  3106 fun values_cmd print_modes param_user_modes options k raw_t state =
  3107   let
  3108     val ctxt = Toplevel.context_of state
  3109     val t = Syntax.read_term ctxt raw_t
  3110     val t' = values ctxt param_user_modes options k t
  3111     val ty' = Term.type_of t'
  3112     val ctxt' = Variable.auto_fixes t' ctxt
  3113     val p = PrintMode.with_modes print_modes (fn () =>
  3114       Pretty.block [Pretty.quote (Syntax.pretty_term ctxt' t'), Pretty.fbrk,
  3115         Pretty.str "::", Pretty.brk 1, Pretty.quote (Syntax.pretty_typ ctxt' ty')]) ();
  3116   in Pretty.writeln p end;
  3117 
  3118 end;