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