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