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