src/HOL/Tools/inductive_codegen.ML
author wenzelm
Sat May 17 15:31:42 2008 +0200 (2008-05-17)
changeset 26931 aa226d8405a8
parent 26928 ca87aff1ad2d
child 26939 1035c89b4c02
permissions -rw-r--r--
cat_lines;
     1 (*  Title:      HOL/Tools/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   Display.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   cat_lines (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 * bool | 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, is_set) => 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             (if is_set then [Mode (([], []), [], [])]
   212              else modes_of modes t handle Option =>
   213                error ("Bad predicate: " ^ Sign.string_of_term thy t))
   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 DSeq.empty"]))) ::
   299        (if can_fail then
   300           [Pretty.brk 1, Pretty.str "| _ => DSeq.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') = (case mode of
   331                    ([], []) => (gr', [Pretty.str "()"])
   332                  | _ => foldl_map
   333                      (invoke_codegen thy defs dep module true) (gr', args2))
   334              in (gr', (if brack andalso not (null ps andalso null ps') then
   335                single o parens o Pretty.block else I)
   336                  (List.concat (separate [Pretty.brk 1]
   337                    ([Pretty.str mode_id] :: ps @ map single ps'))))
   338              end
   339            else apsnd (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   340              (invoke_codegen thy defs dep module true (gr, t))
   341        | _ => apsnd (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
   342            (invoke_codegen thy defs dep module true (gr, t)));
   343 
   344 fun compile_clause thy defs gr dep module all_vs arg_vs modes (iss, is) (ts, ps) inp =
   345   let
   346     val modes' = modes @ List.mapPartial
   347       (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [([], js)]))
   348         (arg_vs ~~ iss);
   349 
   350     fun check_constrt ((names, eqs), t) =
   351       if is_constrt thy t then ((names, eqs), t) else
   352         let val s = Name.variant names "x";
   353         in ((s::names, (s, t)::eqs), Var ((s, 0), fastype_of t)) end;
   354 
   355     fun compile_eq (gr, (s, t)) =
   356       apsnd (Pretty.block o cons (Pretty.str (s ^ " = ")) o single)
   357         (invoke_codegen thy defs dep module false (gr, t));
   358 
   359     val (in_ts, out_ts) = get_args is 1 ts;
   360     val ((all_vs', eqs), in_ts') =
   361       foldl_map check_constrt ((all_vs, []), in_ts);
   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 "DSeq.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, is_set) =>
   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) =
   401                      if not is_set then
   402                        apsnd (fn ps => ps @
   403                            (if null in_ps then [] else [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 "DSeq.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 "DSeq.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 @
   448            (case mode of ([], []) => [Pretty.str "()"] | _ => xs)) @
   449          [Pretty.str " ="]),
   450         Pretty.brk 1] @
   451        List.concat (separate [Pretty.str " ++", Pretty.brk 1] (map single cl_ps))))
   452   end;
   453 
   454 fun compile_preds thy defs gr dep module all_vs arg_vs modes preds =
   455   let val ((gr', _), prs) = foldl_map (fn ((gr, prfx), (s, cls)) =>
   456     foldl_map (fn ((gr', prfx'), mode) => compile_pred thy defs gr'
   457       dep module prfx' all_vs arg_vs modes s cls mode)
   458         ((gr, prfx), ((the o AList.lookup (op =) modes) s))) ((gr, "fun "), preds)
   459   in
   460     (gr', space_implode "\n\n" (map Pretty.string_of (List.concat prs)) ^ ";\n\n")
   461   end;
   462 
   463 (**** processing of introduction rules ****)
   464 
   465 exception Modes of
   466   (string * (int list option list * int list) list) list *
   467   (string * (int option list * int)) list;
   468 
   469 fun lookup_modes gr dep = apfst List.concat (apsnd List.concat (ListPair.unzip
   470   (map ((fn (SOME (Modes x), _, _) => x | _ => ([], [])) o get_node gr)
   471     (Graph.all_preds (fst gr) [dep]))));
   472 
   473 fun print_arities arities = message ("Arities:\n" ^
   474   cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
   475     space_implode " -> " (map
   476       (fn NONE => "X" | SOME k' => string_of_int k')
   477         (ks @ [SOME k]))) arities));
   478 
   479 fun prep_intrs intrs = map (rename_term o #prop o rep_thm o standard) intrs;
   480 
   481 fun constrain cs [] = []
   482   | constrain cs ((s, xs) :: ys) = (s, case AList.lookup (op =) cs (s : string) of
   483       NONE => xs
   484     | SOME xs' => xs inter xs') :: constrain cs ys;
   485 
   486 fun mk_extra_defs thy defs gr dep names module ts =
   487   Library.foldl (fn (gr, name) =>
   488     if name mem names then gr
   489     else (case get_clauses thy name of
   490         NONE => gr
   491       | SOME (names, thyname, nparms, intrs) =>
   492           mk_ind_def thy defs gr dep names (if_library thyname module)
   493             [] (prep_intrs intrs) nparms))
   494             (gr, foldr add_term_consts [] ts)
   495 
   496 and mk_ind_def thy defs gr dep names module modecs intrs nparms =
   497   add_edge_acyclic (hd names, dep) gr handle
   498     Graph.CYCLES (xs :: _) =>
   499       error ("InductiveCodegen: illegal cyclic dependencies:\n" ^ commas xs)
   500   | Graph.UNDEF _ =>
   501     let
   502       val _ $ u = Logic.strip_imp_concl (hd intrs);
   503       val args = List.take (snd (strip_comb u), nparms);
   504       val arg_vs = List.concat (map term_vs args);
   505 
   506       fun get_nparms s = if s mem names then SOME nparms else
   507         Option.map #3 (get_clauses thy s);
   508 
   509       fun dest_prem (_ $ (Const ("op :", _) $ t $ u)) = Prem ([t], Envir.beta_eta_contract u, true)
   510         | dest_prem (_ $ ((eq as Const ("op =", _)) $ t $ u)) = Prem ([t, u], eq, false)
   511         | dest_prem (_ $ t) =
   512             (case strip_comb t of
   513                (v as Var _, ts) => if v mem args then Prem (ts, v, false) else Sidecond t
   514              | (c as Const (s, _), ts) => (case get_nparms s of
   515                  NONE => Sidecond t
   516                | SOME k =>
   517                    let val (ts1, ts2) = chop k ts
   518                    in Prem (ts2, list_comb (c, ts1), false) end)
   519              | _ => Sidecond t);
   520 
   521       fun add_clause intr (clauses, arities) =
   522         let
   523           val _ $ t = Logic.strip_imp_concl intr;
   524           val (Const (name, T), ts) = strip_comb t;
   525           val (ts1, ts2) = chop nparms ts;
   526           val prems = map dest_prem (Logic.strip_imp_prems intr);
   527           val (Ts, Us) = chop nparms (binder_types T)
   528         in
   529           (AList.update op = (name, these (AList.lookup op = clauses name) @
   530              [(ts2, prems)]) clauses,
   531            AList.update op = (name, (map (fn U => (case strip_type U of
   532                  (Rs as _ :: _, Type ("bool", [])) => SOME (length Rs)
   533                | _ => NONE)) Ts,
   534              length Us)) arities)
   535         end;
   536 
   537       val gr' = mk_extra_defs thy defs
   538         (add_edge (hd names, dep)
   539           (new_node (hd names, (NONE, "", "")) gr)) (hd names) names module intrs;
   540       val (extra_modes, extra_arities) = lookup_modes gr' (hd names);
   541       val (clauses, arities) = fold add_clause intrs ([], []);
   542       val modes = constrain modecs
   543         (infer_modes thy extra_modes arities arg_vs clauses);
   544       val _ = print_arities arities;
   545       val _ = print_modes modes;
   546       val (gr'', s) = compile_preds thy defs gr' (hd names) module (terms_vs intrs)
   547         arg_vs (modes @ extra_modes) clauses;
   548     in
   549       (map_node (hd names)
   550         (K (SOME (Modes (modes, arities)), module, s)) gr'')
   551     end;
   552 
   553 fun find_mode gr dep s u modes is = (case find_first (fn Mode (_, js, _) => is=js)
   554   (modes_of modes u handle Option => []) of
   555      NONE => codegen_error gr dep
   556        ("No such mode for " ^ s ^ ": " ^ string_of_mode ([], is))
   557    | mode => mode);
   558 
   559 fun mk_ind_call thy defs gr dep module is_query s T ts names thyname k intrs =
   560   let
   561     val (ts1, ts2) = chop k ts;
   562     val u = list_comb (Const (s, T), ts1);
   563 
   564     fun mk_mode (((ts, mode), i), Const ("dummy_pattern", _)) =
   565           ((ts, mode), i+1)
   566       | mk_mode (((ts, mode), i), t) = ((ts @ [t], mode @ [i]), i+1);
   567 
   568     val module' = if_library thyname module;
   569     val gr1 = mk_extra_defs thy defs
   570       (mk_ind_def thy defs gr dep names module'
   571       [] (prep_intrs intrs) k) dep names module' [u];
   572     val (modes, _) = lookup_modes gr1 dep;
   573     val (ts', is) = if is_query then
   574         fst (Library.foldl mk_mode ((([], []), 1), ts2))
   575       else (ts2, 1 upto length (binder_types T) - k);
   576     val mode = find_mode gr1 dep s u modes is;
   577     val (gr2, in_ps) = foldl_map
   578       (invoke_codegen thy defs dep module true) (gr1, ts');
   579     val (gr3, ps) =
   580       compile_expr thy defs dep module false modes (gr2, (mode, u))
   581   in
   582     (gr3, Pretty.block (ps @ (if null in_ps then [] else [Pretty.brk 1]) @
   583        separate (Pretty.brk 1) in_ps))
   584   end;
   585 
   586 fun clause_of_eqn eqn =
   587   let
   588     val (t, u) = HOLogic.dest_eq (HOLogic.dest_Trueprop (concl_of eqn));
   589     val (Const (s, T), ts) = strip_comb t;
   590     val (Ts, U) = strip_type T
   591   in
   592     rename_term (Logic.list_implies (prems_of eqn, HOLogic.mk_Trueprop
   593       (list_comb (Const (s ^ "_aux", Ts @ [U] ---> HOLogic.boolT), ts @ [u]))))
   594   end;
   595 
   596 fun mk_fun thy defs name eqns dep module module' gr =
   597   case try (get_node gr) name of
   598     NONE =>
   599     let
   600       val clauses = map clause_of_eqn eqns;
   601       val pname = name ^ "_aux";
   602       val arity = length (snd (strip_comb (fst (HOLogic.dest_eq
   603         (HOLogic.dest_Trueprop (concl_of (hd eqns)))))));
   604       val mode = 1 upto arity;
   605       val (gr', (fun_id, mode_id)) = gr |>
   606         mk_const_id module' name |>>>
   607         modename module' pname ([], mode);
   608       val vars = map (fn i => Pretty.str ("x" ^ string_of_int i)) mode;
   609       val s = Pretty.string_of (Pretty.block
   610         [mk_app false (Pretty.str ("fun " ^ snd fun_id)) vars, Pretty.str " =",
   611          Pretty.brk 1, Pretty.str "DSeq.hd", Pretty.brk 1,
   612          parens (Pretty.block (separate (Pretty.brk 1) (Pretty.str mode_id ::
   613            vars)))]) ^ ";\n\n";
   614       val gr'' = mk_ind_def thy defs (add_edge (name, dep)
   615         (new_node (name, (NONE, module', s)) gr')) name [pname] module'
   616         [(pname, [([], mode)])] clauses 0;
   617       val (modes, _) = lookup_modes gr'' dep;
   618       val _ = find_mode gr'' dep pname (head_of (HOLogic.dest_Trueprop
   619         (Logic.strip_imp_concl (hd clauses)))) modes mode
   620     in (gr'', mk_qual_id module fun_id) end
   621   | SOME _ =>
   622       (add_edge (name, dep) gr, mk_qual_id module (get_const_id name gr));
   623 
   624 (* convert n-tuple to nested pairs *)
   625 
   626 fun conv_ntuple fs ts p =
   627   let
   628     val k = length fs;
   629     val xs = map (fn i => Pretty.str ("x" ^ string_of_int i)) (0 upto k);
   630     val xs' = map (fn Bound i => nth xs (k - i)) ts;
   631     fun conv xs js =
   632       if js mem fs then
   633         let
   634           val (p, xs') = conv xs (1::js);
   635           val (q, xs'') = conv xs' (2::js)
   636         in (mk_tuple [p, q], xs'') end
   637       else (hd xs, tl xs)
   638   in
   639     if k > 0 then
   640       Pretty.block
   641         [Pretty.str "DSeq.map (fn", Pretty.brk 1,
   642          mk_tuple xs', Pretty.str " =>", Pretty.brk 1, fst (conv xs []),
   643          Pretty.str ")", Pretty.brk 1, parens p]
   644     else p
   645   end;
   646 
   647 fun inductive_codegen thy defs gr dep module brack t = (case strip_comb t of
   648     (Const ("Collect", _), [u]) =>
   649       let val (r, Ts, fs) = HOLogic.strip_split u
   650       in case strip_comb r of
   651           (Const (s, T), ts) =>
   652             (case (get_clauses thy s, get_assoc_code thy (s, T)) of
   653               (SOME (names, thyname, k, intrs), NONE) =>
   654                 let
   655                   val (ts1, ts2) = chop k ts;
   656                   val ts2' = map
   657                     (fn Bound i => Term.dummy_pattern (nth Ts i) | t => t) ts2;
   658                   val (ots, its) = List.partition is_Bound ts2;
   659                   val no_loose = forall (fn t => not (loose_bvar (t, 0)))
   660                 in
   661                   if null (duplicates op = ots) andalso
   662                     no_loose ts1 andalso no_loose its
   663                   then
   664                     let val (gr', call_p) = mk_ind_call thy defs gr dep module true
   665                       s T (ts1 @ ts2') names thyname k intrs
   666                     in SOME (gr', (if brack then parens else I) (Pretty.block
   667                       [Pretty.str "DSeq.list_of", Pretty.brk 1, Pretty.str "(",
   668                        conv_ntuple fs ots call_p, Pretty.str ")"]))
   669                     end
   670                   else NONE
   671                 end
   672             | _ => NONE)
   673         | _ => NONE
   674       end
   675   | (Const (s, T), ts) => (case Symtab.lookup (#eqns (CodegenData.get thy)) s of
   676       NONE => (case (get_clauses thy s, get_assoc_code thy (s, T)) of
   677         (SOME (names, thyname, k, intrs), NONE) =>
   678           if length ts < k then NONE else SOME
   679             (let val (gr', call_p) = mk_ind_call thy defs gr dep module false
   680                s T (map Term.no_dummy_patterns ts) names thyname k intrs
   681              in (gr', mk_funcomp brack "?!"
   682                (length (binder_types T) - length ts) (parens call_p))
   683              end handle TERM _ => mk_ind_call thy defs gr dep module true
   684                s T ts names thyname k intrs)
   685       | _ => NONE)
   686     | SOME eqns =>
   687         let
   688           val (_, thyname) :: _ = eqns;
   689           val (gr', id) = mk_fun thy defs s (preprocess thy (map fst (rev eqns)))
   690             dep module (if_library thyname module) gr;
   691           val (gr'', ps) = foldl_map
   692             (invoke_codegen thy defs dep module true) (gr', ts);
   693         in SOME (gr'', mk_app brack (Pretty.str id) ps)
   694         end)
   695   | _ => NONE);
   696 
   697 val setup =
   698   add_codegen "inductive" inductive_codegen #>
   699   Code.add_attribute ("ind", Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) --
   700     Scan.option (Args.$$$ "params" |-- Args.colon |-- Args.nat) >> uncurry add);
   701 
   702 end;