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