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