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