src/HOL/Tools/inductive_codegen.ML
author wenzelm
Mon Feb 26 23:18:24 2007 +0100 (2007-02-26)
changeset 22360 26ead7ed4f4b
parent 22271 51a80e238b29
child 22556 b067fdca022d
permissions -rw-r--r--
moved eq_thm etc. to structure Thm in Pure/more_thm.ML;
     1 (*  Title:      HOL/inductive_codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4 
     5 Code generator for inductive predicates.
     6 *)
     7 
     8 signature INDUCTIVE_CODEGEN =
     9 sig
    10   val add : string option -> int option -> attribute
    11   val setup : theory -> theory
    12 end;
    13 
    14 structure InductiveCodegen : INDUCTIVE_CODEGEN =
    15 struct
    16 
    17 open Codegen;
    18 
    19 (* read off parameters of inductive predicate from raw induction rule *)
    20 fun params_of induct =
    21   let
    22     val (_ $ t $ u :: _) =
    23       HOLogic.dest_conj (HOLogic.dest_Trueprop (concl_of induct));
    24     val (_, ts) = strip_comb t;
    25     val (_, us) = strip_comb u
    26   in
    27     List.take (ts, length ts - length us)
    28   end;
    29 
    30 (**** theory data ****)
    31 
    32 fun merge_rules tabs =
    33   Symtab.join (fn _ => fn (ths, ths') =>
    34     gen_merge_lists (Thm.eq_thm_prop o pairself fst) ths ths') tabs;
    35 
    36 structure CodegenData = TheoryDataFun
    37 (struct
    38   val name = "HOL/inductive_codegen";
    39   type T =
    40     {intros : (thm * (string * int)) list Symtab.table,
    41      graph : unit Graph.T,
    42      eqns : (thm * string) list Symtab.table};
    43   val empty =
    44     {intros = Symtab.empty, graph = Graph.empty, eqns = Symtab.empty};
    45   val copy = I;
    46   val extend = I;
    47   fun merge _ ({intros=intros1, graph=graph1, eqns=eqns1},
    48     {intros=intros2, graph=graph2, eqns=eqns2}) =
    49     {intros = merge_rules (intros1, intros2),
    50      graph = Graph.merge (K true) (graph1, graph2),
    51      eqns = merge_rules (eqns1, eqns2)};
    52   fun print _ _ = ();
    53 end);
    54 
    55 
    56 fun warn thm = warning ("InductiveCodegen: Not a proper clause:\n" ^
    57   string_of_thm thm);
    58 
    59 fun add_node (g, x) = Graph.new_node (x, ()) g handle Graph.DUP _ => g;
    60 
    61 fun add optmod optnparms = Thm.declaration_attribute (fn thm => Context.mapping (fn thy =>
    62   let
    63     val {intros, graph, eqns} = CodegenData.get thy;
    64     fun thyname_of s = (case optmod of
    65       NONE => thyname_of_const s thy | SOME s => s);
    66   in (case Option.map strip_comb (try HOLogic.dest_Trueprop (concl_of thm)) of
    67       SOME (Const ("op =", _), [t, _]) => (case head_of t of
    68         Const (s, _) =>
    69           CodegenData.put {intros = intros, graph = graph,
    70              eqns = eqns |> Symtab.update
    71                (s, Symtab.lookup_list eqns s @ [(thm, thyname_of s)])} thy
    72       | _ => (warn thm; thy))
    73     | SOME (Const (s, _), _) =>
    74         let
    75           val cs = foldr add_term_consts [] (prems_of thm);
    76           val rules = Symtab.lookup_list intros s;
    77           val nparms = (case optnparms of
    78             SOME k => k
    79           | NONE => (case rules of
    80              [] => (case try (InductivePackage.the_inductive (ProofContext.init thy)) s of
    81                  SOME (_, {raw_induct, ...}) => length (params_of raw_induct)
    82                | NONE => 0)
    83             | xs => snd (snd (snd (split_last xs)))))
    84         in CodegenData.put
    85           {intros = intros |>
    86            Symtab.update (s, rules @ [(thm, (thyname_of s, nparms))]),
    87            graph = foldr (uncurry (Graph.add_edge o pair s))
    88              (Library.foldl add_node (graph, s :: cs)) cs,
    89            eqns = eqns} thy
    90         end
    91     | _ => (warn thm; thy))
    92   end) I);
    93 
    94 fun get_clauses thy s =
    95   let val {intros, graph, ...} = CodegenData.get thy
    96   in case Symtab.lookup intros s of
    97       NONE => (case try (InductivePackage.the_inductive (ProofContext.init thy)) s of
    98         NONE => NONE
    99       | SOME ({names, ...}, {intrs, raw_induct, ...}) =>
   100           SOME (names, thyname_of_const s thy, length (params_of raw_induct),
   101             preprocess thy intrs))
   102     | SOME _ =>
   103         let
   104           val SOME names = find_first
   105             (fn xs => s mem xs) (Graph.strong_conn graph);
   106           val intrs = List.concat (map
   107             (fn s => the (Symtab.lookup intros s)) names);
   108           val (_, (_, (thyname, nparms))) = split_last intrs
   109         in SOME (names, thyname, nparms, preprocess thy (map fst intrs)) end
   110   end;
   111 
   112 
   113 (**** check if a term contains only constructor functions ****)
   114 
   115 fun is_constrt thy =
   116   let
   117     val cnstrs = List.concat (List.concat (map
   118       (map (fn (_, (_, _, cs)) => map (apsnd length) cs) o #descr o snd)
   119       (Symtab.dest (DatatypePackage.get_datatypes thy))));
   120     fun check t = (case strip_comb t of
   121         (Var _, []) => true
   122       | (Const (s, _), ts) => (case AList.lookup (op =) cnstrs s of
   123             NONE => false
   124           | SOME i => length ts = i andalso forall check ts)
   125       | _ => false)
   126   in check end;
   127 
   128 (**** check if a type is an equality type (i.e. doesn't contain fun) ****)
   129 
   130 fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
   131   | is_eqT _ = true;
   132 
   133 (**** mode inference ****)
   134 
   135 fun string_of_mode (iss, is) = space_implode " -> " (map
   136   (fn NONE => "X"
   137     | SOME js => enclose "[" "]" (commas (map string_of_int js)))
   138        (iss @ [SOME is]));
   139 
   140 fun print_modes modes = message ("Inferred modes:\n" ^
   141   space_implode "\n" (map (fn (s, ms) => s ^ ": " ^ commas (map
   142     string_of_mode ms)) modes));
   143 
   144 val term_vs = map (fst o fst o dest_Var) o term_vars;
   145 val terms_vs = distinct (op =) o List.concat o (map term_vs);
   146 
   147 (** collect all Vars in a term (with duplicates!) **)
   148 fun term_vTs tm =
   149   fold_aterms (fn Var ((x, _), T) => cons (x, T) | _ => I) tm [];
   150 
   151 fun get_args _ _ [] = ([], [])
   152   | get_args is i (x::xs) = (if i mem is then apfst else apsnd) (cons x)
   153       (get_args is (i+1) xs);
   154 
   155 fun merge xs [] = xs
   156   | merge [] ys = ys
   157   | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
   158       else y::merge (x::xs) ys;
   159 
   160 fun subsets i j = if i <= j then
   161        let val is = subsets (i+1) j
   162        in merge (map (fn ks => i::ks) is) is end
   163      else [[]];
   164 
   165 fun cprod ([], ys) = []
   166   | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
   167 
   168 fun cprods xss = foldr (map op :: o cprod) [[]] xss;
   169 
   170 datatype mode = Mode of (int list option list * int list) * int list * mode option list;
   171 
   172 fun modes_of modes t =
   173   let
   174     val ks = 1 upto length (binder_types (fastype_of t));
   175     val default = [Mode (([], ks), ks, [])];
   176     fun mk_modes name args = Option.map (List.concat o
   177       map (fn (m as (iss, is)) =>
   178         let
   179           val (args1, args2) =
   180             if length args < length iss then
   181               error ("Too few arguments for inductive predicate " ^ name)
   182             else chop (length iss) args;
   183           val k = length args2;
   184           val prfx = 1 upto k
   185         in
   186           if not (is_prefix op = prfx is) then [] else
   187           let val is' = map (fn i => i - k) (List.drop (is, k))
   188           in map (fn x => Mode (m, is', x)) (cprods (map
   189             (fn (NONE, _) => [NONE]
   190               | (SOME js, arg) => map SOME (List.filter
   191                   (fn Mode (_, js', _) => js=js') (modes_of modes arg)))
   192                     (iss ~~ args1)))
   193           end
   194         end)) (AList.lookup op = modes name)
   195 
   196   in (case strip_comb t of
   197       (Const ("op =", Type (_, [T, _])), _) =>
   198         [Mode (([], [1]), [1], []), Mode (([], [2]), [2], [])] @
   199         (if is_eqT T then [Mode (([], [1, 2]), [1, 2], [])] else [])
   200     | (Const (name, _), args) => the_default default (mk_modes name args)
   201     | (Var ((name, _), _), args) => the (mk_modes name args)
   202     | (Free (name, _), args) => the (mk_modes name args)
   203     | _ => default)
   204   end;
   205 
   206 datatype indprem = Prem of term list * term | Sidecond of term;
   207 
   208 fun select_mode_prem thy modes vs ps =
   209   find_first (is_some o snd) (ps ~~ map
   210     (fn Prem (us, t) => find_first (fn Mode (_, is, _) =>
   211           let
   212             val (in_ts, out_ts) = get_args is 1 us;
   213             val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
   214             val vTs = List.concat (map term_vTs out_ts');
   215             val dupTs = map snd (duplicates (op =) vTs) @
   216               List.mapPartial (AList.lookup (op =) vTs) vs;
   217           in
   218             terms_vs (in_ts @ in_ts') subset vs andalso
   219             forall (is_eqT o fastype_of) in_ts' andalso
   220             term_vs t subset vs andalso
   221             forall is_eqT dupTs
   222           end)
   223             (modes_of modes t handle Option => [Mode (([], []), [], [])])
   224       | Sidecond t => if term_vs t subset vs then SOME (Mode (([], []), [], []))
   225           else NONE) ps);
   226 
   227 fun check_mode_clause thy arg_vs modes (iss, is) (ts, ps) =
   228   let
   229     val modes' = modes @ List.mapPartial
   230       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
   231         (arg_vs ~~ iss);
   232     fun check_mode_prems vs [] = SOME vs
   233       | check_mode_prems vs ps = (case select_mode_prem thy modes' vs ps of
   234           NONE => NONE
   235         | SOME (x, _) => check_mode_prems
   236             (case x of Prem (us, _) => vs union terms_vs us | _ => vs)
   237             (filter_out (equal x) ps));
   238     val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (get_args is 1 ts));
   239     val in_vs = terms_vs in_ts;
   240     val concl_vs = terms_vs ts
   241   in
   242     forall is_eqT (map snd (duplicates (op =) (List.concat (map term_vTs in_ts)))) andalso
   243     forall (is_eqT o fastype_of) in_ts' andalso
   244     (case check_mode_prems (arg_vs union in_vs) ps of
   245        NONE => false
   246      | SOME vs => concl_vs subset vs)
   247   end;
   248 
   249 fun check_modes_pred thy arg_vs preds modes (p, ms) =
   250   let val SOME rs = AList.lookup (op =) preds p
   251   in (p, List.filter (fn m => case find_index
   252     (not o check_mode_clause thy arg_vs modes m) rs of
   253       ~1 => true
   254     | i => (message ("Clause " ^ string_of_int (i+1) ^ " of " ^
   255       p ^ " violates mode " ^ string_of_mode m); false)) ms)
   256   end;
   257 
   258 fun fixp f x =
   259   let val y = f x
   260   in if x = y then x else fixp f y end;
   261 
   262 fun infer_modes thy extra_modes arities arg_vs preds = fixp (fn modes =>
   263   map (check_modes_pred thy arg_vs preds (modes @ extra_modes)) modes)
   264     (map (fn (s, (ks, k)) => (s, cprod (cprods (map
   265       (fn NONE => [NONE]
   266         | SOME k' => map SOME (subsets 1 k')) ks),
   267       subsets 1 k))) arities);
   268 
   269 (**** code generation ****)
   270 
   271 fun mk_eq (x::xs) =
   272   let fun mk_eqs _ [] = []
   273         | mk_eqs a (b::cs) = Pretty.str (a ^ " = " ^ b) :: mk_eqs b cs
   274   in mk_eqs x xs end;
   275 
   276 fun mk_tuple xs = Pretty.block (Pretty.str "(" ::
   277   List.concat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   278   [Pretty.str ")"]);
   279 
   280 fun mk_v ((names, vs), s) = (case AList.lookup (op =) vs s of
   281       NONE => ((names, (s, [s])::vs), s)
   282     | SOME xs => let val s' = Name.variant names s in
   283         ((s'::names, AList.update (op =) (s, s'::xs) vs), s') end);
   284 
   285 fun distinct_v (nvs, Var ((s, 0), T)) =
   286       apsnd (Var o rpair T o rpair 0) (mk_v (nvs, s))
   287   | distinct_v (nvs, t $ u) =
   288       let
   289         val (nvs', t') = distinct_v (nvs, t);
   290         val (nvs'', u') = distinct_v (nvs', u);
   291       in (nvs'', t' $ u') end
   292   | distinct_v x = x;
   293 
   294 fun is_exhaustive (Var _) = true
   295   | is_exhaustive (Const ("Pair", _) $ t $ u) =
   296       is_exhaustive t andalso is_exhaustive u
   297   | is_exhaustive _ = false;
   298 
   299 fun compile_match nvs eq_ps out_ps success_p can_fail =
   300   let val eqs = List.concat (separate [Pretty.str " andalso", Pretty.brk 1]
   301     (map single (List.concat (map (mk_eq o snd) nvs) @ eq_ps)));
   302   in
   303     Pretty.block
   304      ([Pretty.str "(fn ", mk_tuple out_ps, Pretty.str " =>", Pretty.brk 1] @
   305       (Pretty.block ((if eqs=[] then [] else Pretty.str "if " ::
   306          [Pretty.block eqs, Pretty.brk 1, Pretty.str "then "]) @
   307          (success_p ::
   308           (if eqs=[] then [] else [Pretty.brk 1, Pretty.str "else Seq.empty"]))) ::
   309        (if can_fail then
   310           [Pretty.brk 1, Pretty.str "| _ => Seq.empty)"]
   311         else [Pretty.str ")"])))
   312   end;
   313 
   314 fun modename module s (iss, is) gr =
   315   let val (gr', id) = if s = "op =" then (gr, ("", "equal"))
   316     else mk_const_id module s gr
   317   in (gr', space_implode "__"
   318     (mk_qual_id module id ::
   319       map (space_implode "_" o map string_of_int) (List.mapPartial I iss @ [is])))
   320   end;
   321 
   322 fun mk_funcomp brack s k p = (if brack then parens else I)
   323   (Pretty.block [Pretty.block ((if k = 0 then [] else [Pretty.str "("]) @
   324     separate (Pretty.brk 1) (Pretty.str s :: replicate k (Pretty.str "|> ???")) @
   325     (if k = 0 then [] else [Pretty.str ")"])), Pretty.brk 1, p]);
   326 
   327 fun compile_expr thy defs dep module brack modes (gr, (NONE, t)) =
   328       apsnd single (invoke_codegen thy defs dep module brack (gr, t))
   329   | compile_expr _ _ _ _ _ _ (gr, (SOME _, Var ((name, _), _))) =
   330       (gr, [Pretty.str name])
   331   | compile_expr thy defs dep module brack modes (gr, (SOME (Mode (mode, _, ms)), t)) =
   332       (case strip_comb t of
   333          (Const (name, _), args) =>
   334            if name = "op =" orelse AList.defined op = modes name then
   335              let
   336                val (args1, args2) = chop (length ms) args;
   337                val (gr', (ps, mode_id)) = foldl_map
   338                    (compile_expr thy defs dep module true modes) (gr, ms ~~ args1) |>>>
   339                  modename module name mode;
   340                val (gr'', ps') = foldl_map
   341                  (invoke_codegen thy defs dep module true) (gr', args2)
   342              in (gr', (if brack andalso not (null ps andalso null ps') then
   343                single o parens o Pretty.block else I)
   344                  (List.concat (separate [Pretty.brk 1]
   345                    ([Pretty.str mode_id] :: ps @ map single ps'))))
   346              end
   347            else apsnd (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   348              (invoke_codegen thy defs dep module true (gr, t))
   349        | _ => apsnd (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   350            (invoke_codegen thy defs dep module true (gr, t)));
   351 
   352 fun compile_clause thy defs gr dep module all_vs arg_vs modes (iss, is) (ts, ps) inp =
   353   let
   354     val modes' = modes @ List.mapPartial
   355       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
   356         (arg_vs ~~ iss);
   357 
   358     fun check_constrt ((names, eqs), t) =
   359       if is_constrt thy t then ((names, eqs), t) else
   360         let val s = Name.variant names "x";
   361         in ((s::names, (s, t)::eqs), Var ((s, 0), fastype_of t)) end;
   362 
   363     fun compile_eq (gr, (s, t)) =
   364       apsnd (Pretty.block o cons (Pretty.str (s ^ " = ")) o single)
   365         (invoke_codegen thy defs dep module false (gr, t));
   366 
   367     val (in_ts, out_ts) = get_args is 1 ts;
   368     val ((all_vs', eqs), in_ts') =
   369       foldl_map check_constrt ((all_vs, []), in_ts);
   370 
   371     fun is_ind t = (case head_of t of
   372           Const (s, _) => s = "op =" orelse AList.defined (op =) modes s
   373         | Var ((s, _), _) => s mem arg_vs);
   374 
   375     fun compile_prems out_ts' vs names gr [] =
   376           let
   377             val (gr2, out_ps) = foldl_map
   378               (invoke_codegen thy defs dep module false) (gr, out_ts);
   379             val (gr3, eq_ps) = foldl_map compile_eq (gr2, eqs);
   380             val ((names', eqs'), out_ts'') =
   381               foldl_map check_constrt ((names, []), out_ts');
   382             val (nvs, out_ts''') = foldl_map distinct_v
   383               ((names', map (fn x => (x, [x])) vs), out_ts'');
   384             val (gr4, out_ps') = foldl_map
   385               (invoke_codegen thy defs dep module false) (gr3, out_ts''');
   386             val (gr5, eq_ps') = foldl_map compile_eq (gr4, eqs')
   387           in
   388             (gr5, compile_match (snd nvs) (eq_ps @ eq_ps') out_ps'
   389               (Pretty.block [Pretty.str "Seq.single", Pretty.brk 1, mk_tuple out_ps])
   390               (exists (not o is_exhaustive) out_ts'''))
   391           end
   392       | compile_prems out_ts vs names gr ps =
   393           let
   394             val vs' = distinct (op =) (List.concat (vs :: map term_vs out_ts));
   395             val SOME (p, mode as SOME (Mode (_, js, _))) =
   396               select_mode_prem thy modes' vs' ps;
   397             val ps' = filter_out (equal p) ps;
   398             val ((names', eqs), out_ts') =
   399               foldl_map check_constrt ((names, []), out_ts);
   400             val (nvs, out_ts'') = foldl_map distinct_v
   401               ((names', map (fn x => (x, [x])) vs), out_ts');
   402             val (gr0, out_ps) = foldl_map
   403               (invoke_codegen thy defs dep module false) (gr, out_ts'');
   404             val (gr1, eq_ps) = foldl_map compile_eq (gr0, eqs)
   405           in
   406             (case p of
   407                Prem (us, t) =>
   408                  let
   409                    val (in_ts, out_ts''') = get_args js 1 us;
   410                    val (gr2, in_ps) = foldl_map
   411                      (invoke_codegen thy defs dep module true) (gr1, in_ts);
   412                    val (gr3, ps) = if is_ind t then
   413                        apsnd (fn ps => ps @ Pretty.brk 1 ::
   414                            separate (Pretty.brk 1) in_ps)
   415                          (compile_expr thy defs dep module false modes
   416                            (gr2, (mode, t)))
   417                      else
   418                        apsnd (fn p => [Pretty.str "Seq.of_list", Pretty.brk 1, p])
   419                            (invoke_codegen thy defs dep module true (gr2, t));
   420                    val (gr4, rest) = compile_prems out_ts''' vs' (fst nvs) gr3 ps';
   421                  in
   422                    (gr4, compile_match (snd nvs) eq_ps out_ps
   423                       (Pretty.block (ps @
   424                          [Pretty.str " :->", Pretty.brk 1, rest]))
   425                       (exists (not o is_exhaustive) out_ts''))
   426                  end
   427              | Sidecond t =>
   428                  let
   429                    val (gr2, side_p) = invoke_codegen thy defs dep module true (gr1, t);
   430                    val (gr3, rest) = compile_prems [] vs' (fst nvs) gr2 ps';
   431                  in
   432                    (gr3, compile_match (snd nvs) eq_ps out_ps
   433                       (Pretty.block [Pretty.str "?? ", side_p,
   434                         Pretty.str " :->", Pretty.brk 1, rest])
   435                       (exists (not o is_exhaustive) out_ts''))
   436                  end)
   437           end;
   438 
   439     val (gr', prem_p) = compile_prems in_ts' arg_vs all_vs' gr ps;
   440   in
   441     (gr', Pretty.block [Pretty.str "Seq.single", Pretty.brk 1, inp,
   442        Pretty.str " :->", Pretty.brk 1, prem_p])
   443   end;
   444 
   445 fun compile_pred thy defs gr dep module prfx all_vs arg_vs modes s cls mode =
   446   let
   447     val xs = map Pretty.str (Name.variant_list arg_vs
   448       (map (fn i => "x" ^ string_of_int i) (snd mode)));
   449     val (gr', (cl_ps, mode_id)) =
   450       foldl_map (fn (gr, cl) => compile_clause thy defs
   451         gr dep module all_vs arg_vs modes mode cl (mk_tuple xs)) (gr, cls) |>>>
   452       modename module s mode
   453   in
   454     ((gr', "and "), Pretty.block
   455       ([Pretty.block (separate (Pretty.brk 1)
   456          (Pretty.str (prfx ^ mode_id) ::
   457            map Pretty.str arg_vs @ xs) @
   458          [Pretty.str " ="]),
   459         Pretty.brk 1] @
   460        List.concat (separate [Pretty.str " ++", Pretty.brk 1] (map single cl_ps))))
   461   end;
   462 
   463 fun compile_preds thy defs gr dep module all_vs arg_vs modes preds =
   464   let val ((gr', _), prs) = foldl_map (fn ((gr, prfx), (s, cls)) =>
   465     foldl_map (fn ((gr', prfx'), mode) => compile_pred thy defs gr'
   466       dep module prfx' all_vs arg_vs modes s cls mode)
   467         ((gr, prfx), ((the o AList.lookup (op =) modes) s))) ((gr, "fun "), preds)
   468   in
   469     (gr', space_implode "\n\n" (map Pretty.string_of (List.concat prs)) ^ ";\n\n")
   470   end;
   471 
   472 (**** processing of introduction rules ****)
   473 
   474 exception Modes of
   475   (string * (int list option list * int list) list) list *
   476   (string * (int option list * int)) list;
   477 
   478 fun lookup_modes gr dep = apfst List.concat (apsnd List.concat (ListPair.unzip
   479   (map ((fn (SOME (Modes x), _, _) => x | _ => ([], [])) o get_node gr)
   480     (Graph.all_preds (fst gr) [dep]))));
   481 
   482 fun print_arities arities = message ("Arities:\n" ^
   483   space_implode "\n" (map (fn (s, (ks, k)) => s ^ ": " ^
   484     space_implode " -> " (map
   485       (fn NONE => "X" | SOME k' => string_of_int k')
   486         (ks @ [SOME k]))) arities));
   487 
   488 fun prep_intrs intrs = map (rename_term o #prop o rep_thm o standard) intrs;
   489 
   490 fun constrain cs [] = []
   491   | constrain cs ((s, xs) :: ys) = (s, case AList.lookup (op =) cs s of
   492       NONE => xs
   493     | SOME xs' => xs inter xs') :: constrain cs ys;
   494 
   495 fun mk_extra_defs thy defs gr dep names module ts =
   496   Library.foldl (fn (gr, name) =>
   497     if name mem names then gr
   498     else (case get_clauses thy name of
   499         NONE => gr
   500       | SOME (names, thyname, nparms, intrs) =>
   501           mk_ind_def thy defs gr dep names (if_library thyname module)
   502             [] (prep_intrs intrs) nparms))
   503             (gr, foldr add_term_consts [] ts)
   504 
   505 and mk_ind_def thy defs gr dep names module modecs intrs nparms =
   506   add_edge (hd names, dep) gr handle Graph.UNDEF _ =>
   507     let
   508       val _ $ u = Logic.strip_imp_concl (hd intrs);
   509       val args = List.take (snd (strip_comb u), nparms);
   510       val arg_vs = List.concat (map term_vs args);
   511 
   512       fun get_nparms s = if s mem names then SOME nparms else
   513         Option.map #3 (get_clauses thy s);
   514 
   515       fun dest_prem (_ $ (Const ("op :", _) $ t $ u)) = Prem ([t], u)
   516         | dest_prem (_ $ ((eq as Const ("op =", _)) $ t $ u)) = Prem ([t, u], eq)
   517         | dest_prem (_ $ t) =
   518             (case strip_comb t of
   519                (v as Var _, ts) => Prem (ts, v)
   520              | (c as Const (s, _), ts) => (case get_nparms s of
   521                  NONE => Sidecond t
   522                | SOME k =>
   523                    let val (ts1, ts2) = chop k ts
   524                    in Prem (ts2, list_comb (c, ts1)) end)
   525              | _ => Sidecond t);
   526 
   527       fun add_clause intr (clauses, arities) =
   528         let
   529           val _ $ t = Logic.strip_imp_concl intr;
   530           val (Const (name, T), ts) = strip_comb t;
   531           val (ts1, ts2) = chop nparms ts;
   532           val prems = map dest_prem (Logic.strip_imp_prems intr);
   533           val (Ts, Us) = chop nparms (binder_types T)
   534         in
   535           (AList.update op = (name, these (AList.lookup op = clauses name) @
   536              [(ts2, prems)]) clauses,
   537            AList.update op = (name, (map (fn U => (case strip_type U of
   538                  (Rs as _ :: _, Type ("bool", [])) => SOME (length Rs)
   539                | _ => NONE)) Ts,
   540              length Us)) arities)
   541         end;
   542 
   543       val gr' = mk_extra_defs thy defs
   544         (add_edge (hd names, dep)
   545           (new_node (hd names, (NONE, "", "")) gr)) (hd names) names module intrs;
   546       val (extra_modes, extra_arities) = lookup_modes gr' (hd names);
   547       val (clauses, arities) = fold add_clause intrs ([], []);
   548       val modes = constrain modecs
   549         (infer_modes thy extra_modes arities arg_vs clauses);
   550       val _ = print_arities arities;
   551       val _ = print_modes modes;
   552       val (gr'', s) = compile_preds thy defs gr' (hd names) module (terms_vs intrs)
   553         arg_vs (modes @ extra_modes) clauses;
   554     in
   555       (map_node (hd names)
   556         (K (SOME (Modes (modes, arities)), module, s)) gr'')
   557     end;
   558 
   559 fun find_mode gr dep s u modes is = (case find_first (fn Mode (_, js, _) => is=js)
   560   (modes_of modes u handle Option => []) of
   561      NONE => codegen_error gr dep
   562        ("No such mode for " ^ s ^ ": " ^ string_of_mode ([], is))
   563    | mode => mode);
   564 
   565 fun mk_ind_call thy defs gr dep module is_query s T ts names thyname k intrs =
   566   let
   567     val (ts1, ts2) = chop k ts;
   568     val u = list_comb (Const (s, T), ts1);
   569 
   570     fun mk_mode (((ts, mode), i), Const ("dummy_pattern", _)) =
   571           ((ts, mode), i+1)
   572       | mk_mode (((ts, mode), i), t) = ((ts @ [t], mode @ [i]), i+1);
   573 
   574     val module' = if_library thyname module;
   575     val gr1 = mk_extra_defs thy defs
   576       (mk_ind_def thy defs gr dep names module'
   577       [] (prep_intrs intrs) k) dep names module' [u];
   578     val (modes, _) = lookup_modes gr1 dep;
   579     val (ts', is) = if is_query then
   580         fst (Library.foldl mk_mode ((([], []), 1), ts2))
   581       else (ts2, 1 upto length (binder_types T) - k);
   582     val mode = find_mode gr1 dep s u modes is;
   583     val (gr2, in_ps) = foldl_map
   584       (invoke_codegen thy defs dep module true) (gr1, ts');
   585     val (gr3, ps) =
   586       compile_expr thy defs dep module false modes (gr2, (mode, u))
   587   in
   588     (gr3, Pretty.block (ps @ (if null in_ps then [] else [Pretty.brk 1]) @
   589        separate (Pretty.brk 1) in_ps))
   590   end;
   591 
   592 fun clause_of_eqn eqn =
   593   let
   594     val (t, u) = HOLogic.dest_eq (HOLogic.dest_Trueprop (concl_of eqn));
   595     val (Const (s, T), ts) = strip_comb t;
   596     val (Ts, U) = strip_type T
   597   in
   598     rename_term (Logic.list_implies (prems_of eqn, HOLogic.mk_Trueprop
   599       (list_comb (Const (s ^ "_aux", Ts @ [U] ---> HOLogic.boolT), ts @ [u]))))
   600   end;
   601 
   602 fun mk_fun thy defs name eqns dep module module' gr =
   603   case try (get_node gr) name of
   604     NONE =>
   605     let
   606       val clauses = map clause_of_eqn eqns;
   607       val pname = name ^ "_aux";
   608       val arity = length (snd (strip_comb (fst (HOLogic.dest_eq
   609         (HOLogic.dest_Trueprop (concl_of (hd eqns)))))));
   610       val mode = 1 upto arity;
   611       val (gr', (fun_id, mode_id)) = gr |>
   612         mk_const_id module' name |>>>
   613         modename module' pname ([], mode);
   614       val vars = map (fn i => Pretty.str ("x" ^ string_of_int i)) mode;
   615       val s = Pretty.string_of (Pretty.block
   616         [mk_app false (Pretty.str ("fun " ^ snd fun_id)) vars, Pretty.str " =",
   617          Pretty.brk 1, Pretty.str "Seq.hd", Pretty.brk 1,
   618          parens (Pretty.block (separate (Pretty.brk 1) (Pretty.str mode_id ::
   619            vars)))]) ^ ";\n\n";
   620       val gr'' = mk_ind_def thy defs (add_edge (name, dep)
   621         (new_node (name, (NONE, module', s)) gr')) name [pname] module'
   622         [(pname, [([], mode)])] clauses 0;
   623       val (modes, _) = lookup_modes gr'' dep;
   624       val _ = find_mode gr'' dep pname (head_of (HOLogic.dest_Trueprop
   625         (Logic.strip_imp_concl (hd clauses)))) modes mode
   626     in (gr'', mk_qual_id module fun_id) end
   627   | SOME _ =>
   628       (add_edge (name, dep) gr, mk_qual_id module (get_const_id name gr));
   629 
   630 fun inductive_codegen thy defs gr dep module brack t = (case strip_comb t of
   631     (Const ("Collect", Type (_, [_, Type (_, [U])])), [u]) => (case strip_comb u of
   632         (Const (s, T), ts) => (case (get_clauses thy s, get_assoc_code thy s T) of
   633           (SOME (names, thyname, k, intrs), NONE) =>
   634             let val (gr', call_p) = mk_ind_call thy defs gr dep module true
   635               s T (ts @ [Term.dummy_pattern U]) names thyname k intrs
   636             in SOME (gr', (if brack then parens else I) (Pretty.block
   637               [Pretty.str "Seq.list_of", Pretty.brk 1, Pretty.str "(",
   638                call_p, Pretty.str ")"]))
   639             end
   640         | _ => NONE)
   641       | _ => NONE)
   642   | (Const (s, T), ts) => (case Symtab.lookup (#eqns (CodegenData.get thy)) s of
   643       NONE => (case (get_clauses thy s, get_assoc_code thy s T) of
   644         (SOME (names, thyname, k, intrs), NONE) =>
   645           if length ts < k then NONE else SOME
   646             (let val (gr', call_p) = mk_ind_call thy defs gr dep module false
   647                s T (map Term.no_dummy_patterns ts) names thyname k intrs
   648              in (gr', mk_funcomp brack "?!"
   649                (length (binder_types T) - length ts) (parens call_p))
   650              end handle TERM _ => mk_ind_call thy defs gr dep module true
   651                s T ts names thyname k intrs)
   652       | _ => NONE)
   653     | SOME eqns =>
   654         let
   655           val (_, (_, thyname)) = split_last eqns;
   656           val (gr', id) = mk_fun thy defs s (preprocess thy (map fst eqns))
   657             dep module (if_library thyname module) gr;
   658           val (gr'', ps) = foldl_map
   659             (invoke_codegen thy defs dep module true) (gr', ts);
   660         in SOME (gr'', mk_app brack (Pretty.str id) ps)
   661         end)
   662   | _ => NONE);
   663 
   664 val setup =
   665   add_codegen "inductive" inductive_codegen #>
   666   CodegenData.init #>
   667   add_attribute "ind" (Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) --
   668     Scan.option (Args.$$$ "params" |-- Args.colon |-- Args.nat) >> uncurry add);
   669 
   670 end;
   671 
   672 
   673 (**** combinators for code generated from inductive predicates ****)
   674 
   675 infix 5 :->;
   676 infix 3 ++;
   677 
   678 fun s :-> f = Seq.maps f s;
   679 
   680 fun s1 ++ s2 = Seq.append s1 s2;
   681 
   682 fun ?? b = if b then Seq.single () else Seq.empty;
   683 
   684 fun ??? f g = f o g;
   685 
   686 fun ?! s = is_some (Seq.pull s);
   687 
   688 fun equal__1 x = Seq.single x;
   689 
   690 val equal__2 = equal__1;
   691 
   692 fun equal__1_2 (x, y) = ?? (x = y);