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