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