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