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