src/HOL/Tools/inductive_codegen.ML
author wenzelm
Tue Apr 19 23:57:28 2011 +0200 (2011-04-19)
changeset 42411 ff997038e8eb
parent 42361 23f352990944
child 42427 5611f178a747
permissions -rw-r--r--
eliminated Codegen.mode in favour of explicit argument;
     1 (*  Title:      HOL/Tools/inductive_codegen.ML
     2     Author:     Stefan Berghofer, TU Muenchen
     3 
     4 Code generator for inductive predicates.
     5 *)
     6 
     7 signature INDUCTIVE_CODEGEN =
     8 sig
     9   val add : string option -> int option -> attribute
    10   val test_fn : (int * int * int -> term list option) Unsynchronized.ref  (* FIXME *)
    11   val test_term:
    12     Proof.context -> (term * term list) list -> int list -> term list option * Quickcheck.report option
    13   val setup : theory -> theory
    14   val quickcheck_setup : theory -> theory
    15 end;
    16 
    17 structure Inductive_Codegen : INDUCTIVE_CODEGEN =
    18 struct
    19 
    20 (**** theory data ****)
    21 
    22 fun merge_rules tabs =
    23   Symtab.join (fn _ => AList.merge (Thm.eq_thm_prop) (K true)) tabs;
    24 
    25 structure CodegenData = Theory_Data
    26 (
    27   type T =
    28     {intros : (thm * (string * int)) list Symtab.table,
    29      graph : unit Graph.T,
    30      eqns : (thm * string) list Symtab.table};
    31   val empty =
    32     {intros = Symtab.empty, graph = Graph.empty, eqns = Symtab.empty};
    33   val extend = I;
    34   fun merge
    35     ({intros = intros1, graph = graph1, eqns = eqns1},
    36       {intros = intros2, graph = graph2, eqns = eqns2}) : T =
    37     {intros = merge_rules (intros1, intros2),
    38      graph = Graph.merge (K true) (graph1, graph2),
    39      eqns = merge_rules (eqns1, eqns2)};
    40 );
    41 
    42 
    43 fun warn thm = warning ("Inductive_Codegen: Not a proper clause:\n" ^
    44   Display.string_of_thm_without_context thm);
    45 
    46 fun add_node x g = Graph.new_node (x, ()) g handle Graph.DUP _ => g;
    47 
    48 fun add optmod optnparms = Thm.declaration_attribute (fn thm => Context.mapping (fn thy =>
    49   let
    50     val {intros, graph, eqns} = CodegenData.get thy;
    51     fun thyname_of s = (case optmod of
    52       NONE => Codegen.thyname_of_const thy s | SOME s => s);
    53   in (case Option.map strip_comb (try HOLogic.dest_Trueprop (concl_of thm)) of
    54       SOME (Const (@{const_name HOL.eq}, _), [t, _]) =>
    55         (case head_of t of
    56           Const (s, _) =>
    57             CodegenData.put {intros = intros, graph = graph,
    58                eqns = eqns |> Symtab.map_default (s, [])
    59                  (AList.update Thm.eq_thm_prop (thm, thyname_of s))} thy
    60         | _ => (warn thm; thy))
    61     | SOME (Const (s, _), _) =>
    62         let
    63           val cs = fold Term.add_const_names (Thm.prems_of thm) [];
    64           val rules = Symtab.lookup_list intros s;
    65           val nparms =
    66             (case optnparms of
    67               SOME k => k
    68             | NONE =>
    69                 (case rules of
    70                   [] =>
    71                     (case try (Inductive.the_inductive (Proof_Context.init_global thy)) s of
    72                       SOME (_, {raw_induct, ...}) =>
    73                         length (Inductive.params_of raw_induct)
    74                     | NONE => 0)
    75                 | xs => snd (snd (List.last xs))))
    76         in CodegenData.put
    77           {intros = intros |>
    78            Symtab.update (s, (AList.update Thm.eq_thm_prop
    79              (thm, (thyname_of s, nparms)) rules)),
    80            graph = fold_rev (Graph.add_edge o pair s) cs (fold add_node (s :: cs) graph),
    81            eqns = eqns} thy
    82         end
    83     | _ => (warn thm; thy))
    84   end) I);
    85 
    86 fun get_clauses thy s =
    87   let val {intros, graph, ...} = CodegenData.get thy
    88   in case Symtab.lookup intros s of
    89       NONE => (case try (Inductive.the_inductive (Proof_Context.init_global thy)) s of
    90         NONE => NONE
    91       | SOME ({names, ...}, {intrs, raw_induct, ...}) =>
    92           SOME (names, Codegen.thyname_of_const thy s,
    93             length (Inductive.params_of raw_induct),
    94             Codegen.preprocess thy intrs))
    95     | SOME _ =>
    96         let
    97           val SOME names = find_first
    98             (fn xs => member (op =) xs s) (Graph.strong_conn graph);
    99           val intrs as (_, (thyname, nparms)) :: _ =
   100             maps (the o Symtab.lookup intros) names;
   101         in SOME (names, thyname, nparms, Codegen.preprocess thy (map fst (rev intrs))) end
   102   end;
   103 
   104 
   105 (**** check if a term contains only constructor functions ****)
   106 
   107 fun is_constrt thy =
   108   let
   109     val cnstrs = flat (maps
   110       (map (fn (_, (_, _, cs)) => map (apsnd length) cs) o #descr o snd)
   111       (Symtab.dest (Datatype_Data.get_all thy)));
   112     fun check t = (case strip_comb t of
   113         (Var _, []) => true
   114       | (Const (s, _), ts) => (case AList.lookup (op =) cnstrs s of
   115             NONE => false
   116           | SOME i => length ts = i andalso forall check ts)
   117       | _ => false)
   118   in check end;
   119 
   120 (**** check if a type is an equality type (i.e. doesn't contain fun) ****)
   121 
   122 fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
   123   | is_eqT _ = true;
   124 
   125 (**** mode inference ****)
   126 
   127 fun string_of_mode (iss, is) = space_implode " -> " (map
   128   (fn NONE => "X"
   129     | SOME js => enclose "[" "]" (commas (map string_of_int js)))
   130        (iss @ [SOME is]));
   131 
   132 fun print_modes modes = Codegen.message ("Inferred modes:\n" ^
   133   cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
   134     (fn (m, rnd) => string_of_mode m ^
   135        (if rnd then " (random)" else "")) ms)) modes));
   136 
   137 val term_vs = map (fst o fst o dest_Var) o OldTerm.term_vars;
   138 val terms_vs = distinct (op =) o maps term_vs;
   139 
   140 (** collect all Vars in a term (with duplicates!) **)
   141 fun term_vTs tm =
   142   fold_aterms (fn Var ((x, _), T) => cons (x, T) | _ => I) tm [];
   143 
   144 fun get_args _ _ [] = ([], [])
   145   | get_args is i (x::xs) = (if member (op =) is i then apfst else apsnd) (cons x)
   146       (get_args is (i+1) xs);
   147 
   148 fun merge xs [] = xs
   149   | merge [] ys = ys
   150   | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
   151       else y::merge (x::xs) ys;
   152 
   153 fun subsets i j = if i <= j then
   154        let val is = subsets (i+1) j
   155        in merge (map (fn ks => i::ks) is) is end
   156      else [[]];
   157 
   158 fun cprod ([], ys) = []
   159   | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
   160 
   161 fun cprods xss = List.foldr (map op :: o cprod) [[]] xss;
   162 
   163 datatype mode = Mode of ((int list option list * int list) * bool) * int list * mode option list;
   164 
   165 fun needs_random (Mode ((_, b), _, ms)) =
   166   b orelse exists (fn NONE => false | SOME m => needs_random m) ms;
   167 
   168 fun modes_of modes t =
   169   let
   170     val ks = 1 upto length (binder_types (fastype_of t));
   171     val default = [Mode ((([], ks), false), ks, [])];
   172     fun mk_modes name args = Option.map
   173      (maps (fn (m as ((iss, is), _)) =>
   174         let
   175           val (args1, args2) =
   176             if length args < length iss then
   177               error ("Too few arguments for inductive predicate " ^ name)
   178             else chop (length iss) args;
   179           val k = length args2;
   180           val prfx = 1 upto k
   181         in
   182           if not (is_prefix op = prfx is) then [] else
   183           let val is' = map (fn i => i - k) (List.drop (is, k))
   184           in map (fn x => Mode (m, is', x)) (cprods (map
   185             (fn (NONE, _) => [NONE]
   186               | (SOME js, arg) => map SOME (filter
   187                   (fn Mode (_, js', _) => js=js') (modes_of modes arg)))
   188                     (iss ~~ args1)))
   189           end
   190         end)) (AList.lookup op = modes name)
   191 
   192   in (case strip_comb t of
   193       (Const (@{const_name HOL.eq}, Type (_, [T, _])), _) =>
   194         [Mode ((([], [1]), false), [1], []), Mode ((([], [2]), false), [2], [])] @
   195         (if is_eqT T then [Mode ((([], [1, 2]), false), [1, 2], [])] else [])
   196     | (Const (name, _), args) => the_default default (mk_modes name args)
   197     | (Var ((name, _), _), args) => the (mk_modes name args)
   198     | (Free (name, _), args) => the (mk_modes name args)
   199     | _ => default)
   200   end;
   201 
   202 datatype indprem = Prem of term list * term * bool | Sidecond of term;
   203 
   204 fun missing_vars vs ts = subtract (fn (x, ((y, _), _)) => x = y) vs
   205   (fold Term.add_vars ts []);
   206 
   207 fun monomorphic_vars vs = null (fold (Term.add_tvarsT o snd) vs []);
   208 
   209 fun mode_ord p = int_ord (pairself (fn (Mode ((_, rnd), _, _), vs) =>
   210   length vs + (if null vs then 0 else 1) + (if rnd then 1 else 0)) p);
   211 
   212 fun select_mode_prem thy modes vs ps =
   213   sort (mode_ord o pairself (hd o snd))
   214     (filter_out (null o snd) (ps ~~ map
   215       (fn Prem (us, t, is_set) => sort mode_ord
   216           (List.mapPartial (fn m as Mode (_, is, _) =>
   217             let
   218               val (in_ts, out_ts) = get_args is 1 us;
   219               val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
   220               val vTs = maps term_vTs out_ts';
   221               val dupTs = map snd (duplicates (op =) vTs) @
   222                 map_filter (AList.lookup (op =) vTs) vs;
   223               val missing_vs = missing_vars vs (t :: in_ts @ in_ts')
   224             in
   225               if forall (is_eqT o fastype_of) in_ts' andalso forall is_eqT dupTs
   226                 andalso monomorphic_vars missing_vs
   227               then SOME (m, missing_vs)
   228               else NONE
   229             end)
   230               (if is_set then [Mode ((([], []), false), [], [])]
   231                else modes_of modes t handle Option =>
   232                  error ("Bad predicate: " ^ Syntax.string_of_term_global thy t)))
   233         | Sidecond t =>
   234             let val missing_vs = missing_vars vs [t]
   235             in
   236               if monomorphic_vars missing_vs
   237               then [(Mode ((([], []), false), [], []), missing_vs)]
   238               else []
   239             end)
   240               ps));
   241 
   242 fun use_random codegen_mode = member (op =) codegen_mode "random_ind";
   243 
   244 fun check_mode_clause thy codegen_mode arg_vs modes ((iss, is), rnd) (ts, ps) =
   245   let
   246     val modes' = modes @ map_filter
   247       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [(([], js), false)]))
   248         (arg_vs ~~ iss);
   249     fun check_mode_prems vs rnd [] = SOME (vs, rnd)
   250       | check_mode_prems vs rnd ps = (case select_mode_prem thy modes' vs ps of
   251           (x, (m, []) :: _) :: _ => check_mode_prems
   252             (case x of Prem (us, _, _) => union (op =) vs (terms_vs us) | _ => vs)
   253             (rnd orelse needs_random m)
   254             (filter_out (equal x) ps)
   255         | (_, (_, vs') :: _) :: _ =>
   256             if use_random codegen_mode then
   257               check_mode_prems (union (op =) vs (map (fst o fst) vs')) true ps
   258             else NONE
   259         | _ => NONE);
   260     val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (get_args is 1 ts));
   261     val in_vs = terms_vs in_ts;
   262   in
   263     if forall is_eqT (map snd (duplicates (op =) (maps term_vTs in_ts))) andalso
   264       forall (is_eqT o fastype_of) in_ts'
   265     then (case check_mode_prems (union (op =) arg_vs in_vs) rnd ps of
   266        NONE => NONE
   267      | SOME (vs, rnd') =>
   268          let val missing_vs = missing_vars vs ts
   269          in
   270            if null missing_vs orelse
   271              use_random codegen_mode andalso monomorphic_vars missing_vs
   272            then SOME (rnd' orelse not (null missing_vs))
   273            else NONE
   274          end)
   275     else NONE
   276   end;
   277 
   278 fun check_modes_pred thy codegen_mode arg_vs preds modes (p, ms) =
   279   let val SOME rs = AList.lookup (op =) preds p
   280   in (p, List.mapPartial (fn m as (m', _) =>
   281     let val xs = map (check_mode_clause thy codegen_mode arg_vs modes m) rs
   282     in case find_index is_none xs of
   283         ~1 => SOME (m', exists (fn SOME b => b) xs)
   284       | i => (Codegen.message ("Clause " ^ string_of_int (i+1) ^ " of " ^
   285         p ^ " violates mode " ^ string_of_mode m'); NONE)
   286     end) ms)
   287   end;
   288 
   289 fun fixp f (x : (string * ((int list option list * int list) * bool) list) list) =
   290   let val y = f x
   291   in if x = y then x else fixp f y end;
   292 
   293 fun infer_modes thy codegen_mode extra_modes arities arg_vs preds = fixp (fn modes =>
   294   map (check_modes_pred thy codegen_mode arg_vs preds (modes @ extra_modes)) modes)
   295     (map (fn (s, (ks, k)) => (s, map (rpair false) (cprod (cprods (map
   296       (fn NONE => [NONE]
   297         | SOME k' => map SOME (subsets 1 k')) ks),
   298       subsets 1 k)))) arities);
   299 
   300 (**** code generation ****)
   301 
   302 fun mk_eq (x::xs) =
   303   let fun mk_eqs _ [] = []
   304         | mk_eqs a (b::cs) = Codegen.str (a ^ " = " ^ b) :: mk_eqs b cs
   305   in mk_eqs x xs end;
   306 
   307 fun mk_tuple xs = Pretty.block (Codegen.str "(" ::
   308   flat (separate [Codegen.str ",", Pretty.brk 1] (map single xs)) @
   309   [Codegen.str ")"]);
   310 
   311 fun mk_v s (names, vs) =
   312   (case AList.lookup (op =) vs s of
   313     NONE => (s, (names, (s, [s])::vs))
   314   | SOME xs =>
   315       let val s' = Name.variant names s
   316       in (s', (s'::names, AList.update (op =) (s, s'::xs) vs)) end);
   317 
   318 fun distinct_v (Var ((s, 0), T)) nvs =
   319       let val (s', nvs') = mk_v s nvs
   320       in (Var ((s', 0), T), nvs') end
   321   | distinct_v (t $ u) nvs =
   322       let
   323         val (t', nvs') = distinct_v t nvs;
   324         val (u', nvs'') = distinct_v u nvs';
   325       in (t' $ u', nvs'') end
   326   | distinct_v t nvs = (t, nvs);
   327 
   328 fun is_exhaustive (Var _) = true
   329   | is_exhaustive (Const (@{const_name Pair}, _) $ t $ u) =
   330       is_exhaustive t andalso is_exhaustive u
   331   | is_exhaustive _ = false;
   332 
   333 fun compile_match nvs eq_ps out_ps success_p can_fail =
   334   let val eqs = flat (separate [Codegen.str " andalso", Pretty.brk 1]
   335     (map single (maps (mk_eq o snd) nvs @ eq_ps)));
   336   in
   337     Pretty.block
   338      ([Codegen.str "(fn ", mk_tuple out_ps, Codegen.str " =>", Pretty.brk 1] @
   339       (Pretty.block ((if null eqs then [] else Codegen.str "if " ::
   340          [Pretty.block eqs, Pretty.brk 1, Codegen.str "then "]) @
   341          (success_p ::
   342           (if null eqs then [] else [Pretty.brk 1, Codegen.str "else DSeq.empty"]))) ::
   343        (if can_fail then
   344           [Pretty.brk 1, Codegen.str "| _ => DSeq.empty)"]
   345         else [Codegen.str ")"])))
   346   end;
   347 
   348 fun modename module s (iss, is) gr =
   349   let val (id, gr') = if s = @{const_name HOL.eq} then (("", "equal"), gr)
   350     else Codegen.mk_const_id module s gr
   351   in (space_implode "__"
   352     (Codegen.mk_qual_id module id ::
   353       map (space_implode "_" o map string_of_int) (map_filter I iss @ [is])), gr')
   354   end;
   355 
   356 fun mk_funcomp brack s k p = (if brack then Codegen.parens else I)
   357   (Pretty.block [Pretty.block ((if k = 0 then [] else [Codegen.str "("]) @
   358     separate (Pretty.brk 1) (Codegen.str s :: replicate k (Codegen.str "|> ???")) @
   359     (if k = 0 then [] else [Codegen.str ")"])), Pretty.brk 1, p]);
   360 
   361 fun compile_expr thy codegen_mode defs dep module brack modes (NONE, t) gr =
   362       apfst single (Codegen.invoke_codegen thy codegen_mode defs dep module brack t gr)
   363   | compile_expr _ _ _ _ _ _ _ (SOME _, Var ((name, _), _)) gr =
   364       ([Codegen.str name], gr)
   365   | compile_expr thy codegen_mode defs dep module brack modes (SOME (Mode ((mode, _), _, ms)), t) gr =
   366       (case strip_comb t of
   367          (Const (name, _), args) =>
   368            if name = @{const_name HOL.eq} orelse AList.defined op = modes name then
   369              let
   370                val (args1, args2) = chop (length ms) args;
   371                val ((ps, mode_id), gr') = gr |> fold_map
   372                    (compile_expr thy codegen_mode defs dep module true modes) (ms ~~ args1)
   373                    ||>> modename module name mode;
   374                val (ps', gr'') = (case mode of
   375                    ([], []) => ([Codegen.str "()"], gr')
   376                  | _ => fold_map
   377                      (Codegen.invoke_codegen thy codegen_mode defs dep module true) args2 gr')
   378              in ((if brack andalso not (null ps andalso null ps') then
   379                single o Codegen.parens o Pretty.block else I)
   380                  (flat (separate [Pretty.brk 1]
   381                    ([Codegen.str mode_id] :: ps @ map single ps'))), gr')
   382              end
   383            else apfst (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   384              (Codegen.invoke_codegen thy codegen_mode defs dep module true t gr)
   385        | _ => apfst (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   386            (Codegen.invoke_codegen thy codegen_mode defs dep module true t gr));
   387 
   388 fun compile_clause thy codegen_mode defs dep module all_vs arg_vs modes (iss, is) (ts, ps) inp gr =
   389   let
   390     val modes' = modes @ map_filter
   391       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [(([], js), false)]))
   392         (arg_vs ~~ iss);
   393 
   394     fun check_constrt t (names, eqs) =
   395       if is_constrt thy t then (t, (names, eqs))
   396       else
   397         let val s = Name.variant names "x";
   398         in (Var ((s, 0), fastype_of t), (s::names, (s, t)::eqs)) end;
   399 
   400     fun compile_eq (s, t) gr =
   401       apfst (Pretty.block o cons (Codegen.str (s ^ " = ")) o single)
   402         (Codegen.invoke_codegen thy codegen_mode defs dep module false t gr);
   403 
   404     val (in_ts, out_ts) = get_args is 1 ts;
   405     val (in_ts', (all_vs', eqs)) = fold_map check_constrt in_ts (all_vs, []);
   406 
   407     fun compile_prems out_ts' vs names [] gr =
   408           let
   409             val (out_ps, gr2) =
   410               fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module false) out_ts gr;
   411             val (eq_ps, gr3) = fold_map compile_eq eqs gr2;
   412             val (out_ts'', (names', eqs')) = fold_map check_constrt out_ts' (names, []);
   413             val (out_ts''', nvs) =
   414               fold_map distinct_v out_ts'' (names', map (fn x => (x, [x])) vs);
   415             val (out_ps', gr4) =
   416               fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module false) out_ts''' gr3;
   417             val (eq_ps', gr5) = fold_map compile_eq eqs' gr4;
   418             val vs' = distinct (op =) (flat (vs :: map term_vs out_ts'));
   419             val missing_vs = missing_vars vs' out_ts;
   420             val final_p = Pretty.block
   421               [Codegen.str "DSeq.single", Pretty.brk 1, mk_tuple out_ps]
   422           in
   423             if null missing_vs then
   424               (compile_match (snd nvs) (eq_ps @ eq_ps') out_ps'
   425                  final_p (exists (not o is_exhaustive) out_ts'''), gr5)
   426             else
   427               let
   428                 val (pat_p, gr6) = Codegen.invoke_codegen thy codegen_mode defs dep module true
   429                   (HOLogic.mk_tuple (map Var missing_vs)) gr5;
   430                 val gen_p =
   431                   Codegen.mk_gen gr6 module true [] ""
   432                     (HOLogic.mk_tupleT (map snd missing_vs))
   433               in
   434                 (compile_match (snd nvs) eq_ps' out_ps'
   435                    (Pretty.block [Codegen.str "DSeq.generator ", gen_p,
   436                       Codegen.str " :->", Pretty.brk 1,
   437                       compile_match [] eq_ps [pat_p] final_p false])
   438                    (exists (not o is_exhaustive) out_ts'''),
   439                  gr6)
   440               end
   441           end
   442       | compile_prems out_ts vs names ps gr =
   443           let
   444             val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
   445             val (out_ts', (names', eqs)) = fold_map check_constrt out_ts (names, []);
   446             val (out_ts'', nvs) = fold_map distinct_v out_ts' (names', map (fn x => (x, [x])) vs);
   447             val (out_ps, gr0) =
   448               fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module false) out_ts'' gr;
   449             val (eq_ps, gr1) = fold_map compile_eq eqs gr0;
   450           in
   451             (case hd (select_mode_prem thy modes' vs' ps) of
   452                (p as Prem (us, t, is_set), (mode as Mode (_, js, _), []) :: _) =>
   453                  let
   454                    val ps' = filter_out (equal p) ps;
   455                    val (in_ts, out_ts''') = get_args js 1 us;
   456                    val (in_ps, gr2) =
   457                     fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module true) in_ts gr1;
   458                    val (ps, gr3) =
   459                      if not is_set then
   460                        apfst (fn ps => ps @
   461                            (if null in_ps then [] else [Pretty.brk 1]) @
   462                            separate (Pretty.brk 1) in_ps)
   463                          (compile_expr thy codegen_mode defs dep module false modes
   464                            (SOME mode, t) gr2)
   465                      else
   466                        apfst (fn p =>
   467                          Pretty.breaks [Codegen.str "DSeq.of_list", Codegen.str "(case", p,
   468                          Codegen.str "of", Codegen.str "Set", Codegen.str "xs", Codegen.str "=>",
   469                          Codegen.str "xs)"])
   470                          (*this is a very strong assumption about the generated code!*)
   471                            (Codegen.invoke_codegen thy codegen_mode defs dep module true t gr2);
   472                    val (rest, gr4) = compile_prems out_ts''' vs' (fst nvs) ps' gr3;
   473                  in
   474                    (compile_match (snd nvs) eq_ps out_ps
   475                       (Pretty.block (ps @
   476                          [Codegen.str " :->", Pretty.brk 1, rest]))
   477                       (exists (not o is_exhaustive) out_ts''), gr4)
   478                  end
   479              | (p as Sidecond t, [(_, [])]) =>
   480                  let
   481                    val ps' = filter_out (equal p) ps;
   482                    val (side_p, gr2) =
   483                     Codegen.invoke_codegen thy codegen_mode defs dep module true t gr1;
   484                    val (rest, gr3) = compile_prems [] vs' (fst nvs) ps' gr2;
   485                  in
   486                    (compile_match (snd nvs) eq_ps out_ps
   487                       (Pretty.block [Codegen.str "?? ", side_p,
   488                         Codegen.str " :->", Pretty.brk 1, rest])
   489                       (exists (not o is_exhaustive) out_ts''), gr3)
   490                  end
   491              | (_, (_, missing_vs) :: _) =>
   492                  let
   493                    val T = HOLogic.mk_tupleT (map snd missing_vs);
   494                    val (_, gr2) =
   495                     Codegen.invoke_tycodegen thy codegen_mode defs dep module false T gr1;
   496                    val gen_p = Codegen.mk_gen gr2 module true [] "" T;
   497                    val (rest, gr3) = compile_prems
   498                      [HOLogic.mk_tuple (map Var missing_vs)] vs' (fst nvs) ps gr2
   499                  in
   500                    (compile_match (snd nvs) eq_ps out_ps
   501                       (Pretty.block [Codegen.str "DSeq.generator", Pretty.brk 1,
   502                         gen_p, Codegen.str " :->", Pretty.brk 1, rest])
   503                       (exists (not o is_exhaustive) out_ts''), gr3)
   504                  end)
   505           end;
   506 
   507     val (prem_p, gr') = compile_prems in_ts' arg_vs all_vs' ps gr ;
   508   in
   509     (Pretty.block [Codegen.str "DSeq.single", Pretty.brk 1, inp,
   510        Codegen.str " :->", Pretty.brk 1, prem_p], gr')
   511   end;
   512 
   513 fun compile_pred thy codegen_mode defs dep module prfx all_vs arg_vs modes s cls mode gr =
   514   let
   515     val xs = map Codegen.str (Name.variant_list arg_vs
   516       (map (fn i => "x" ^ string_of_int i) (snd mode)));
   517     val ((cl_ps, mode_id), gr') = gr |>
   518       fold_map (fn cl => compile_clause thy codegen_mode defs
   519         dep module all_vs arg_vs modes mode cl (mk_tuple xs)) cls ||>>
   520       modename module s mode
   521   in
   522     (Pretty.block
   523       ([Pretty.block (separate (Pretty.brk 1)
   524          (Codegen.str (prfx ^ mode_id) ::
   525            map Codegen.str arg_vs @
   526            (case mode of ([], []) => [Codegen.str "()"] | _ => xs)) @
   527          [Codegen.str " ="]),
   528         Pretty.brk 1] @
   529        flat (separate [Codegen.str " ++", Pretty.brk 1] (map single cl_ps))), (gr', "and "))
   530   end;
   531 
   532 fun compile_preds thy codegen_mode defs dep module all_vs arg_vs modes preds gr =
   533   let val (prs, (gr', _)) = fold_map (fn (s, cls) =>
   534     fold_map (fn (mode, _) => fn (gr', prfx') => compile_pred thy codegen_mode defs
   535       dep module prfx' all_vs arg_vs modes s cls mode gr')
   536         (((the o AList.lookup (op =) modes) s))) preds (gr, "fun ")
   537   in
   538     (space_implode "\n\n" (map Codegen.string_of (flat prs)) ^ ";\n\n", gr')
   539   end;
   540 
   541 (**** processing of introduction rules ****)
   542 
   543 exception Modes of
   544   (string * ((int list option list * int list) * bool) list) list *
   545   (string * (int option list * int)) list;
   546 
   547 fun lookup_modes gr dep = apfst flat (apsnd flat (ListPair.unzip
   548   (map ((fn (SOME (Modes x), _, _) => x | _ => ([], [])) o Codegen.get_node gr)
   549     (Graph.all_preds (fst gr) [dep]))));
   550 
   551 fun print_arities arities = Codegen.message ("Arities:\n" ^
   552   cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
   553     space_implode " -> " (map
   554       (fn NONE => "X" | SOME k' => string_of_int k')
   555         (ks @ [SOME k]))) arities));
   556 
   557 fun prep_intrs intrs =
   558   map (Codegen.rename_term o #prop o rep_thm o Drule.export_without_context) intrs;
   559 
   560 fun constrain cs [] = []
   561   | constrain cs ((s, xs) :: ys) =
   562       (s,
   563         case AList.lookup (op =) cs (s : string) of
   564           NONE => xs
   565         | SOME xs' => inter (op = o apfst fst) xs' xs) :: constrain cs ys;
   566 
   567 fun mk_extra_defs thy codegen_mode defs gr dep names module ts =
   568   fold (fn name => fn gr =>
   569     if member (op =) names name then gr
   570     else
   571       (case get_clauses thy name of
   572         NONE => gr
   573       | SOME (names, thyname, nparms, intrs) =>
   574           mk_ind_def thy codegen_mode defs gr dep names
   575             (Codegen.if_library codegen_mode thyname module)
   576             [] (prep_intrs intrs) nparms))
   577     (fold Term.add_const_names ts []) gr
   578 
   579 and mk_ind_def thy codegen_mode defs gr dep names module modecs intrs nparms =
   580   Codegen.add_edge_acyclic (hd names, dep) gr handle
   581     Graph.CYCLES (xs :: _) =>
   582       error ("Inductive_Codegen: illegal cyclic dependencies:\n" ^ commas xs)
   583   | Graph.UNDEF _ =>
   584     let
   585       val _ $ u = Logic.strip_imp_concl (hd intrs);
   586       val args = List.take (snd (strip_comb u), nparms);
   587       val arg_vs = maps term_vs args;
   588 
   589       fun get_nparms s = if member (op =) names s then SOME nparms else
   590         Option.map #3 (get_clauses thy s);
   591 
   592       fun dest_prem (_ $ (Const (@{const_name Set.member}, _) $ t $ u)) =
   593             Prem ([t], Envir.beta_eta_contract u, true)
   594         | dest_prem (_ $ ((eq as Const (@{const_name HOL.eq}, _)) $ t $ u)) =
   595             Prem ([t, u], eq, false)
   596         | dest_prem (_ $ t) =
   597             (case strip_comb t of
   598               (v as Var _, ts) => if member (op =) args v then Prem (ts, v, false) else Sidecond t
   599             | (c as Const (s, _), ts) =>
   600                 (case get_nparms s of
   601                   NONE => Sidecond t
   602                 | SOME k =>
   603                     let val (ts1, ts2) = chop k ts
   604                     in Prem (ts2, list_comb (c, ts1), false) end)
   605             | _ => Sidecond t);
   606 
   607       fun add_clause intr (clauses, arities) =
   608         let
   609           val _ $ t = Logic.strip_imp_concl intr;
   610           val (Const (name, T), ts) = strip_comb t;
   611           val (ts1, ts2) = chop nparms ts;
   612           val prems = map dest_prem (Logic.strip_imp_prems intr);
   613           val (Ts, Us) = chop nparms (binder_types T)
   614         in
   615           (AList.update op = (name, these (AList.lookup op = clauses name) @
   616              [(ts2, prems)]) clauses,
   617            AList.update op = (name, (map (fn U => (case strip_type U of
   618                  (Rs as _ :: _, @{typ bool}) => SOME (length Rs)
   619                | _ => NONE)) Ts,
   620              length Us)) arities)
   621         end;
   622 
   623       val gr' = mk_extra_defs thy codegen_mode defs
   624         (Codegen.add_edge (hd names, dep)
   625           (Codegen.new_node (hd names, (NONE, "", "")) gr)) (hd names) names module intrs;
   626       val (extra_modes, extra_arities) = lookup_modes gr' (hd names);
   627       val (clauses, arities) = fold add_clause intrs ([], []);
   628       val modes = constrain modecs
   629         (infer_modes thy codegen_mode extra_modes arities arg_vs clauses);
   630       val _ = print_arities arities;
   631       val _ = print_modes modes;
   632       val (s, gr'') = compile_preds thy codegen_mode defs (hd names) module (terms_vs intrs)
   633         arg_vs (modes @ extra_modes) clauses gr';
   634     in
   635       (Codegen.map_node (hd names)
   636         (K (SOME (Modes (modes, arities)), module, s)) gr'')
   637     end;
   638 
   639 fun find_mode gr dep s u modes is = (case find_first (fn Mode (_, js, _) => is=js)
   640   (modes_of modes u handle Option => []) of
   641      NONE => Codegen.codegen_error gr dep
   642        ("No such mode for " ^ s ^ ": " ^ string_of_mode ([], is))
   643    | mode => mode);
   644 
   645 fun mk_ind_call thy codegen_mode defs dep module is_query s T ts names thyname k intrs gr =
   646   let
   647     val (ts1, ts2) = chop k ts;
   648     val u = list_comb (Const (s, T), ts1);
   649 
   650     fun mk_mode (Const (@{const_name dummy_pattern}, _)) ((ts, mode), i) = ((ts, mode), i + 1)
   651       | mk_mode t ((ts, mode), i) = ((ts @ [t], mode @ [i]), i + 1);
   652 
   653     val module' = Codegen.if_library codegen_mode thyname module;
   654     val gr1 = mk_extra_defs thy codegen_mode defs
   655       (mk_ind_def thy codegen_mode defs gr dep names module'
   656       [] (prep_intrs intrs) k) dep names module' [u];
   657     val (modes, _) = lookup_modes gr1 dep;
   658     val (ts', is) =
   659       if is_query then fst (fold mk_mode ts2 (([], []), 1))
   660       else (ts2, 1 upto length (binder_types T) - k);
   661     val mode = find_mode gr1 dep s u modes is;
   662     val _ = if is_query orelse not (needs_random (the mode)) then ()
   663       else warning ("Illegal use of random data generators in " ^ s);
   664     val (in_ps, gr2) =
   665       fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module true) ts' gr1;
   666     val (ps, gr3) = compile_expr thy codegen_mode defs dep module false modes (mode, u) gr2;
   667   in
   668     (Pretty.block (ps @ (if null in_ps then [] else [Pretty.brk 1]) @
   669        separate (Pretty.brk 1) in_ps), gr3)
   670   end;
   671 
   672 fun clause_of_eqn eqn =
   673   let
   674     val (t, u) = HOLogic.dest_eq (HOLogic.dest_Trueprop (concl_of eqn));
   675     val (Const (s, T), ts) = strip_comb t;
   676     val (Ts, U) = strip_type T
   677   in
   678     Codegen.rename_term (Logic.list_implies (prems_of eqn, HOLogic.mk_Trueprop
   679       (list_comb (Const (s ^ "_aux", Ts @ [U] ---> HOLogic.boolT), ts @ [u]))))
   680   end;
   681 
   682 fun mk_fun thy codegen_mode defs name eqns dep module module' gr =
   683   case try (Codegen.get_node gr) name of
   684     NONE =>
   685     let
   686       val clauses = map clause_of_eqn eqns;
   687       val pname = name ^ "_aux";
   688       val arity = length (snd (strip_comb (fst (HOLogic.dest_eq
   689         (HOLogic.dest_Trueprop (concl_of (hd eqns)))))));
   690       val mode = 1 upto arity;
   691       val ((fun_id, mode_id), gr') = gr |>
   692         Codegen.mk_const_id module' name ||>>
   693         modename module' pname ([], mode);
   694       val vars = map (fn i => Codegen.str ("x" ^ string_of_int i)) mode;
   695       val s = Codegen.string_of (Pretty.block
   696         [Codegen.mk_app false (Codegen.str ("fun " ^ snd fun_id)) vars, Codegen.str " =",
   697          Pretty.brk 1, Codegen.str "DSeq.hd", Pretty.brk 1,
   698          Codegen.parens (Pretty.block (separate (Pretty.brk 1) (Codegen.str mode_id ::
   699            vars)))]) ^ ";\n\n";
   700       val gr'' = mk_ind_def thy codegen_mode defs (Codegen.add_edge (name, dep)
   701         (Codegen.new_node (name, (NONE, module', s)) gr')) name [pname] module'
   702         [(pname, [([], mode)])] clauses 0;
   703       val (modes, _) = lookup_modes gr'' dep;
   704       val _ = find_mode gr'' dep pname (head_of (HOLogic.dest_Trueprop
   705         (Logic.strip_imp_concl (hd clauses)))) modes mode
   706     in (Codegen.mk_qual_id module fun_id, gr'') end
   707   | SOME _ =>
   708       (Codegen.mk_qual_id module (Codegen.get_const_id gr name), Codegen.add_edge (name, dep) gr);
   709 
   710 (* convert n-tuple to nested pairs *)
   711 
   712 fun conv_ntuple fs ts p =
   713   let
   714     val k = length fs;
   715     val xs = map_range (fn i => Codegen.str ("x" ^ string_of_int i)) (k + 1);
   716     val xs' = map (fn Bound i => nth xs (k - i)) ts;
   717     fun conv xs js =
   718       if member (op =) fs js then
   719         let
   720           val (p, xs') = conv xs (1::js);
   721           val (q, xs'') = conv xs' (2::js)
   722         in (mk_tuple [p, q], xs'') end
   723       else (hd xs, tl xs)
   724   in
   725     if k > 0 then
   726       Pretty.block
   727         [Codegen.str "DSeq.map (fn", Pretty.brk 1,
   728          mk_tuple xs', Codegen.str " =>", Pretty.brk 1, fst (conv xs []),
   729          Codegen.str ")", Pretty.brk 1, Codegen.parens p]
   730     else p
   731   end;
   732 
   733 fun inductive_codegen thy codegen_mode defs dep module brack t gr  = (case strip_comb t of
   734     (Const (@{const_name Collect}, _), [u]) =>
   735       let val (r, Ts, fs) = HOLogic.strip_psplits u
   736       in case strip_comb r of
   737           (Const (s, T), ts) =>
   738             (case (get_clauses thy s, Codegen.get_assoc_code thy (s, T)) of
   739               (SOME (names, thyname, k, intrs), NONE) =>
   740                 let
   741                   val (ts1, ts2) = chop k ts;
   742                   val ts2' = map
   743                     (fn Bound i => Term.dummy_pattern (nth Ts (length Ts - i - 1)) | t => t) ts2;
   744                   val (ots, its) = List.partition is_Bound ts2;
   745                   val closed = forall (not o Term.is_open)
   746                 in
   747                   if null (duplicates op = ots) andalso
   748                     closed ts1 andalso closed its
   749                   then
   750                     let val (call_p, gr') = mk_ind_call thy codegen_mode defs dep module true
   751                       s T (ts1 @ ts2') names thyname k intrs gr 
   752                     in SOME ((if brack then Codegen.parens else I) (Pretty.block
   753                       [Codegen.str "Set", Pretty.brk 1, Codegen.str "(DSeq.list_of", Pretty.brk 1,
   754                        Codegen.str "(", conv_ntuple fs ots call_p, Codegen.str "))"]),
   755                        (*this is a very strong assumption about the generated code!*)
   756                        gr')
   757                     end
   758                   else NONE
   759                 end
   760             | _ => NONE)
   761         | _ => NONE
   762       end
   763   | (Const (s, T), ts) =>
   764     (case Symtab.lookup (#eqns (CodegenData.get thy)) s of
   765       NONE =>
   766       (case (get_clauses thy s, Codegen.get_assoc_code thy (s, T)) of
   767         (SOME (names, thyname, k, intrs), NONE) =>
   768           if length ts < k then NONE else SOME
   769             (let val (call_p, gr') = mk_ind_call thy codegen_mode defs dep module false
   770                s T (map Term.no_dummy_patterns ts) names thyname k intrs gr
   771              in (mk_funcomp brack "?!"
   772                (length (binder_types T) - length ts) (Codegen.parens call_p), gr')
   773              end handle TERM _ => mk_ind_call thy codegen_mode defs dep module true
   774                s T ts names thyname k intrs gr )
   775       | _ => NONE)
   776     | SOME eqns =>
   777         let
   778           val (_, thyname) :: _ = eqns;
   779           val (id, gr') =
   780             mk_fun thy codegen_mode defs s (Codegen.preprocess thy (map fst (rev eqns)))
   781               dep module (Codegen.if_library codegen_mode thyname module) gr;
   782           val (ps, gr'') =
   783             fold_map (Codegen.invoke_codegen thy codegen_mode defs dep module true) ts gr';
   784         in SOME (Codegen.mk_app brack (Codegen.str id) ps, gr'')
   785         end)
   786   | _ => NONE);
   787 
   788 val setup =
   789   Codegen.add_codegen "inductive" inductive_codegen #>
   790   Attrib.setup @{binding code_ind}
   791     (Scan.lift (Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) --
   792       Scan.option (Args.$$$ "params" |-- Args.colon |-- Parse.nat) >> uncurry add))
   793     "introduction rules for executable predicates";
   794 
   795 (**** Quickcheck involving inductive predicates ****)
   796 
   797 val test_fn : (int * int * int -> term list option) Unsynchronized.ref =
   798   Unsynchronized.ref (fn _ => NONE);
   799 
   800 fun strip_imp p =
   801   let val (q, r) = HOLogic.dest_imp p
   802   in strip_imp r |>> cons q end
   803   handle TERM _ => ([], p);
   804 
   805 fun deepen bound f i =
   806   if i > bound then NONE
   807   else (case f i of
   808       NONE => deepen bound f (i + 1)
   809     | SOME x => SOME x);
   810 
   811 val (depth_bound, setup_depth_bound) = Attrib.config_int "ind_quickcheck_depth" (K 10);
   812 val (depth_start, setup_depth_start) = Attrib.config_int "ind_quickcheck_depth_start" (K 1);
   813 val (random_values, setup_random_values) = Attrib.config_int "ind_quickcheck_random" (K 5);
   814 val (size_offset, setup_size_offset) = Attrib.config_int "ind_quickcheck_size_offset" (K 0);
   815 
   816 fun test_term ctxt [(t, [])] =
   817   let
   818     val t' = list_abs_free (Term.add_frees t [], t)
   819     val thy = Proof_Context.theory_of ctxt;
   820     val (xs, p) = strip_abs t';
   821     val args' = map_index (fn (i, (_, T)) => ("arg" ^ string_of_int i, T)) xs;
   822     val args = map Free args';
   823     val (ps, q) = strip_imp p;
   824     val Ts = map snd xs;
   825     val T = Ts ---> HOLogic.boolT;
   826     val rl = Logic.list_implies
   827       (map (HOLogic.mk_Trueprop o curry subst_bounds (rev args)) ps @
   828        [HOLogic.mk_Trueprop (HOLogic.mk_not (subst_bounds (rev args, q)))],
   829        HOLogic.mk_Trueprop (list_comb (Free ("quickcheckp", T), args)));
   830     val (_, thy') = Inductive.add_inductive_global
   831       {quiet_mode=true, verbose=false, alt_name=Binding.empty, coind=false,
   832        no_elim=true, no_ind=false, skip_mono=false, fork_mono=false}
   833       [((Binding.name "quickcheckp", T), NoSyn)] []
   834       [(Attrib.empty_binding, rl)] [] (Theory.copy thy);
   835     val pred = HOLogic.mk_Trueprop (list_comb
   836       (Const (Sign.intern_const thy' "quickcheckp", T),
   837        map Term.dummy_pattern Ts));
   838     val (code, gr) =
   839       Codegen.generate_code_i thy' ["term_of", "test", "random_ind"] [] "Generated"
   840         [("testf", pred)];
   841     val s = "structure TestTerm =\nstruct\n\n" ^
   842       cat_lines (map snd code) ^
   843       "\nopen Generated;\n\n" ^ Codegen.string_of
   844         (Pretty.block [Codegen.str "val () = Inductive_Codegen.test_fn :=",
   845           Pretty.brk 1, Codegen.str "(fn p =>", Pretty.brk 1,
   846           Codegen.str "case Seq.pull (testf p) of", Pretty.brk 1,
   847           Codegen.str "SOME ", mk_tuple [mk_tuple (map (Codegen.str o fst) args'), Codegen.str "_"],
   848           Codegen.str " =>", Pretty.brk 1, Codegen.str "SOME ",
   849           Pretty.enum "," "[" "]"
   850             (map (fn (s, T) => Pretty.block
   851               [Codegen.mk_term_of gr "Generated" false T, Pretty.brk 1, Codegen.str s]) args'),
   852           Pretty.brk 1,
   853           Codegen.str "| NONE => NONE);"]) ^
   854       "\n\nend;\n";
   855     val test_fn' = NAMED_CRITICAL "codegen" (fn () =>
   856      (ML_Context.eval_text_in (SOME ctxt) false Position.none s; ! test_fn));
   857     val values = Config.get ctxt random_values;
   858     val bound = Config.get ctxt depth_bound;
   859     val start = Config.get ctxt depth_start;
   860     val offset = Config.get ctxt size_offset;
   861     fun test [k] = (deepen bound (fn i =>
   862       (Output.urgent_message ("Search depth: " ^ string_of_int i);
   863        test_fn' (i, values, k+offset))) start, NONE);
   864   in test end
   865   | test_term ctxt [(t, _)] = error "Option eval is not supported by tester SML_inductive"
   866   | test_term ctxt _ = error "Compilation of multiple instances is not supported by tester SML_inductive";
   867 
   868 val quickcheck_setup =
   869   setup_depth_bound #>
   870   setup_depth_start #>
   871   setup_random_values #>
   872   setup_size_offset #>
   873   Context.theory_map (Quickcheck.add_generator ("SML_inductive", test_term));
   874 
   875 end;