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