src/HOL/Tools/inductive_codegen.ML
author berghofe
Thu Dec 20 15:23:42 2001 +0100 (2001-12-20)
changeset 12562 323ce5a89695
parent 12557 bb2e4689347e
child 12565 9df4b3934487
permissions -rw-r--r--
Fixed bug in function add.
     1 (*  Title:      HOL/inductive_codegen.ML
     2     ID:         $Id$
     3     Author:     Stefan Berghofer, TU Muenchen
     4     License:    GPL (GNU GENERAL PUBLIC LICENSE)
     5 
     6 Code generator for inductive predicates.
     7 *)
     8 
     9 signature INDUCTIVE_CODEGEN =
    10 sig
    11   val add : theory attribute
    12   val setup : (theory -> theory) list
    13 end;
    14 
    15 structure InductiveCodegen : INDUCTIVE_CODEGEN =
    16 struct
    17 
    18 open Codegen;
    19 
    20 (**** theory data ****)
    21 
    22 structure CodegenArgs =
    23 struct
    24   val name = "HOL/inductive_codegen";
    25   type T = thm list Symtab.table;
    26   val empty = Symtab.empty;
    27   val copy = I;
    28   val prep_ext = I;
    29   val merge = Symtab.merge_multi eq_thm;
    30   fun print _ _ = ();
    31 end;
    32 
    33 structure CodegenData = TheoryDataFun(CodegenArgs);
    34 
    35 fun warn thm = warning ("InductiveCodegen: Not a proper clause:\n" ^
    36   string_of_thm thm);
    37 
    38 fun add (p as (thy, thm)) =
    39   let val tab = CodegenData.get thy;
    40   in (case concl_of thm of
    41       _ $ (Const ("op :", _) $ _ $ t) => (case head_of t of
    42         Const (s, _) => (CodegenData.put (Symtab.update ((s,
    43           if_none (Symtab.lookup (tab, s)) [] @ [thm]), tab)) thy, thm)
    44       | _ => (warn thm; p))
    45     | _ => (warn thm; p))
    46   end;
    47 
    48 fun get_clauses thy s =
    49   (case Symtab.lookup (CodegenData.get thy, s) of
    50      None => (case InductivePackage.get_inductive thy s of
    51        None => None
    52      | Some ({names, ...}, {intrs, ...}) => Some (names, intrs))
    53    | Some thms => Some ([s], thms));
    54 
    55 
    56 (**** improper tuples ****)
    57 
    58 fun prod_factors p (Const ("Pair", _) $ t $ u) =
    59       p :: prod_factors (1::p) t @ prod_factors (2::p) u
    60   | prod_factors p _ = [];
    61 
    62 fun split_prod p ps t = if p mem ps then (case t of
    63        Const ("Pair", _) $ t $ u =>
    64          split_prod (1::p) ps t @ split_prod (2::p) ps u
    65      | _ => error "Inconsistent use of products") else [t];
    66 
    67 datatype factors = FVar of int list list | FFix of int list list;
    68 
    69 exception Factors;
    70 
    71 fun mg_factor (FVar f) (FVar f') = FVar (f inter f')
    72   | mg_factor (FVar f) (FFix f') =
    73       if f' subset f then FFix f' else raise Factors
    74   | mg_factor (FFix f) (FVar f') =
    75       if f subset f' then FFix f else raise Factors
    76   | mg_factor (FFix f) (FFix f') =
    77       if f subset f' andalso f' subset f then FFix f else raise Factors;
    78 
    79 fun dest_factors (FVar f) = f
    80   | dest_factors (FFix f) = f;
    81 
    82 fun infer_factors sg extra_fs (fs, (optf, t)) =
    83   let fun err s = error (s ^ "\n" ^ Sign.string_of_term sg t)
    84   in (case (optf, strip_comb t) of
    85       (Some f, (Const (name, _), args)) =>
    86         (case assoc (extra_fs, name) of
    87            None => overwrite (fs, (name, if_none
    88              (apsome (mg_factor f) (assoc (fs, name))) f))
    89          | Some (fs', f') => (mg_factor f (FFix f');
    90              foldl (infer_factors sg extra_fs)
    91                (fs, map (apsome FFix) fs' ~~ args)))
    92     | (Some f, (Var ((name, _), _), [])) =>
    93         overwrite (fs, (name, if_none
    94           (apsome (mg_factor f) (assoc (fs, name))) f))
    95     | (None, _) => fs
    96     | _ => err "Illegal term")
    97       handle Factors => err "Product factor mismatch in"
    98   end;
    99 
   100 fun string_of_factors p ps = if p mem ps then
   101     "(" ^ string_of_factors (1::p) ps ^ ", " ^ string_of_factors (2::p) ps ^ ")"
   102   else "_";
   103 
   104 
   105 (**** check if a term contains only constructor functions ****)
   106 
   107 fun is_constrt thy =
   108   let
   109     val cnstrs = flat (flat (map
   110       (map (fn (_, (_, _, cs)) => map (apsnd length) cs) o #descr o snd)
   111       (Symtab.dest (DatatypePackage.get_datatypes thy))));
   112     fun check t = (case strip_comb t of
   113         (Var _, []) => true
   114       | (Const (s, _), ts) => (case assoc (cnstrs, s) of
   115             None => false
   116           | Some i => length ts = i andalso forall check ts)
   117       | _ => false)
   118   in check end;
   119 
   120 (**** check if a type is an equality type (i.e. doesn't contain fun) ****)
   121 
   122 fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
   123   | is_eqT _ = true;
   124 
   125 (**** mode inference ****)
   126 
   127 val term_vs = map (fst o fst o dest_Var) o term_vars;
   128 val terms_vs = distinct o flat o (map term_vs);
   129 
   130 (** collect all Vars in a term (with duplicates!) **)
   131 fun term_vTs t = map (apfst fst o dest_Var)
   132   (filter is_Var (foldl_aterms (op :: o Library.swap) ([], t)));
   133 
   134 fun known_args _ _ [] = []
   135   | known_args vs i (t::ts) = if term_vs t subset vs then i::known_args vs (i+1) ts
   136       else known_args vs (i+1) ts;
   137 
   138 fun get_args _ _ [] = ([], [])
   139   | get_args is i (x::xs) = (if i mem is then apfst else apsnd) (cons x)
   140       (get_args is (i+1) xs);
   141 
   142 fun merge xs [] = xs
   143   | merge [] ys = ys
   144   | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
   145       else y::merge (x::xs) ys;
   146 
   147 fun subsets i j = if i <= j then
   148        let val is = subsets (i+1) j
   149        in merge (map (fn ks => i::ks) is) is end
   150      else [[]];
   151 
   152 fun cprod ([], ys) = []
   153   | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
   154 
   155 fun cprods xss = foldr (map op :: o cprod) (xss, [[]]);
   156 
   157 datatype mode = Mode of (int list option list * int list) * mode option list;
   158 
   159 fun modes_of modes t =
   160   let
   161     fun mk_modes name args = flat
   162       (map (fn (m as (iss, is)) => map (Mode o pair m) (cprods (map
   163         (fn (None, _) => [None]
   164           | (Some js, arg) => map Some
   165               (filter (fn Mode ((_, js'), _) => js=js') (modes_of modes arg)))
   166                 (iss ~~ args)))) (the (assoc (modes, name))))
   167 
   168   in (case strip_comb t of
   169       (Const (name, _), args) => mk_modes name args
   170     | (Var ((name, _), _), args) => mk_modes name args)
   171   end;
   172 
   173 datatype indprem = Prem of term list * term | Sidecond of term;
   174 
   175 fun select_mode_prem thy modes vs ps =
   176   find_first (is_some o snd) (ps ~~ map
   177     (fn Prem (us, t) => find_first (fn Mode ((_, is), _) =>
   178           let
   179             val (_, out_ts) = get_args is 1 us;
   180             val vTs = flat (map term_vTs out_ts);
   181             val dupTs = map snd (duplicates vTs) @
   182               mapfilter (curry assoc vTs) vs;
   183           in
   184             is subset known_args vs 1 us andalso
   185             forall (is_constrt thy) (snd (get_args is 1 us)) andalso
   186             term_vs t subset vs andalso
   187             forall is_eqT dupTs
   188           end)
   189             (modes_of modes t)
   190       | Sidecond t => if term_vs t subset vs then Some (Mode (([], []), []))
   191           else None) ps);
   192 
   193 fun check_mode_clause thy arg_vs modes (iss, is) (ts, ps) =
   194   let
   195     val modes' = modes @ mapfilter
   196       (fn (_, None) => None | (v, Some js) => Some (v, [([], js)]))
   197         (arg_vs ~~ iss);
   198     fun check_mode_prems vs [] = Some vs
   199       | check_mode_prems vs ps = (case select_mode_prem thy modes' vs ps of
   200           None => None
   201         | Some (x, _) => check_mode_prems
   202             (case x of Prem (us, _) => vs union terms_vs us | _ => vs)
   203             (filter_out (equal x) ps));
   204     val (in_ts', _) = get_args is 1 ts;
   205     val in_ts = filter (is_constrt thy) in_ts';
   206     val in_vs = terms_vs in_ts;
   207     val concl_vs = terms_vs ts
   208   in
   209     forall is_eqT (map snd (duplicates (flat (map term_vTs in_ts')))) andalso
   210     (case check_mode_prems (arg_vs union in_vs) ps of
   211        None => false
   212      | Some vs => concl_vs subset vs)
   213   end;
   214 
   215 fun check_modes_pred thy arg_vs preds modes (p, ms) =
   216   let val Some rs = assoc (preds, p)
   217   in (p, filter (fn m => forall (check_mode_clause thy arg_vs modes m) rs) ms) end
   218 
   219 fun fixp f x =
   220   let val y = f x
   221   in if x = y then x else fixp f y end;
   222 
   223 fun infer_modes thy extra_modes factors arg_vs preds = fixp (fn modes =>
   224   map (check_modes_pred thy arg_vs preds (modes @ extra_modes)) modes)
   225     (map (fn (s, (fs, f)) => (s, cprod (cprods (map
   226       (fn None => [None]
   227         | Some f' => map Some (subsets 1 (length f' + 1))) fs),
   228       subsets 1 (length f + 1)))) factors);
   229 
   230 (**** code generation ****)
   231 
   232 fun mk_eq (x::xs) =
   233   let fun mk_eqs _ [] = []
   234         | mk_eqs a (b::cs) = Pretty.str (a ^ " = " ^ b) :: mk_eqs b cs
   235   in mk_eqs x xs end;
   236 
   237 fun mk_tuple xs = Pretty.block (Pretty.str "(" ::
   238   flat (separate [Pretty.str ",", Pretty.brk 1] (map single xs)) @
   239   [Pretty.str ")"]);
   240 
   241 fun mk_v ((names, vs), s) = (case assoc (vs, s) of
   242       None => ((names, (s, [s])::vs), s)
   243     | Some xs => let val s' = variant names s in
   244         ((s'::names, overwrite (vs, (s, s'::xs))), s') end);
   245 
   246 fun distinct_v (nvs, Var ((s, 0), T)) =
   247       apsnd (Var o rpair T o rpair 0) (mk_v (nvs, s))
   248   | distinct_v (nvs, t $ u) =
   249       let
   250         val (nvs', t') = distinct_v (nvs, t);
   251         val (nvs'', u') = distinct_v (nvs', u);
   252       in (nvs'', t' $ u') end
   253   | distinct_v x = x;
   254 
   255 fun compile_match nvs eq_ps out_ps success_p fail_p =
   256   let val eqs = flat (separate [Pretty.str " andalso", Pretty.brk 1]
   257     (map single (flat (map (mk_eq o snd) nvs) @ eq_ps)));
   258   in
   259     Pretty.block
   260      ([Pretty.str "(fn ", mk_tuple out_ps, Pretty.str " =>", Pretty.brk 1] @
   261       (Pretty.block ((if eqs=[] then [] else Pretty.str "if " ::
   262          [Pretty.block eqs, Pretty.brk 1, Pretty.str "then "]) @
   263          (success_p ::
   264           (if eqs=[] then [] else [Pretty.brk 1, Pretty.str "else ", fail_p]))) ::
   265        [Pretty.brk 1, Pretty.str "| _ => ", fail_p, Pretty.str ")"]))
   266   end;
   267 
   268 fun modename thy s (iss, is) = space_implode "__"
   269   (mk_const_id (sign_of thy) s ::
   270     map (space_implode "_" o map string_of_int) (mapfilter I iss @ [is]));
   271 
   272 fun compile_expr thy dep brack (gr, (None, t)) =
   273       apsnd single (invoke_codegen thy dep brack (gr, t))
   274   | compile_expr _ _ _ (gr, (Some _, Var ((name, _), _))) =
   275       (gr, [Pretty.str name])
   276   | compile_expr thy dep brack (gr, (Some (Mode (mode, ms)), t)) =
   277       let
   278         val (Const (name, _), args) = strip_comb t;
   279         val (gr', ps) = foldl_map
   280           (compile_expr thy dep true) (gr, ms ~~ args);
   281       in (gr', (if brack andalso not (null ps) then
   282         single o parens o Pretty.block else I)
   283           (flat (separate [Pretty.brk 1]
   284             ([Pretty.str (modename thy name mode)] :: ps))))
   285       end;
   286 
   287 fun compile_clause thy gr dep all_vs arg_vs modes (iss, is) (ts, ps) =
   288   let
   289     val modes' = modes @ mapfilter
   290       (fn (_, None) => None | (v, Some js) => Some (v, [([], js)]))
   291         (arg_vs ~~ iss);
   292 
   293     fun check_constrt ((names, eqs), t) =
   294       if is_constrt thy t then ((names, eqs), t) else
   295         let val s = variant names "x";
   296         in ((s::names, (s, t)::eqs), Var ((s, 0), fastype_of t)) end;
   297 
   298     val (in_ts, out_ts) = get_args is 1 ts;
   299     val ((all_vs', eqs), in_ts') =
   300       foldl_map check_constrt ((all_vs, []), in_ts);
   301 
   302     fun compile_prems out_ts' vs names gr [] =
   303           let
   304             val (gr2, out_ps) = foldl_map
   305               (invoke_codegen thy dep false) (gr, out_ts);
   306             val (gr3, eq_ps) = foldl_map (fn (gr, (s, t)) =>
   307               apsnd (Pretty.block o cons (Pretty.str (s ^ " = ")) o single)
   308                 (invoke_codegen thy dep false (gr, t))) (gr2, eqs);
   309             val (nvs, out_ts'') = foldl_map distinct_v
   310               ((names, map (fn x => (x, [x])) vs), out_ts');
   311             val (gr4, out_ps') = foldl_map
   312               (invoke_codegen thy dep false) (gr3, out_ts'');
   313           in
   314             (gr4, compile_match (snd nvs) eq_ps out_ps'
   315               (Pretty.block [Pretty.str "Seq.single", Pretty.brk 1, mk_tuple out_ps])
   316               (Pretty.str "Seq.empty"))
   317           end
   318       | compile_prems out_ts vs names gr ps =
   319           let
   320             val vs' = distinct (flat (vs :: map term_vs out_ts));
   321             val Some (p, mode as Some (Mode ((_, js), _))) =
   322               select_mode_prem thy modes' (arg_vs union vs') ps;
   323             val ps' = filter_out (equal p) ps;
   324           in
   325             (case p of
   326                Prem (us, t) =>
   327                  let
   328                    val (in_ts, out_ts') = get_args js 1 us;
   329                    val (gr1, in_ps) = foldl_map
   330                      (invoke_codegen thy dep false) (gr, in_ts);
   331                    val (nvs, out_ts'') = foldl_map distinct_v
   332                      ((names, map (fn x => (x, [x])) vs), out_ts);
   333                    val (gr2, out_ps) = foldl_map
   334                      (invoke_codegen thy dep false) (gr1, out_ts'');
   335                    val (gr3, ps) = compile_expr thy dep false (gr2, (mode, t));
   336                    val (gr4, rest) = compile_prems out_ts' vs' (fst nvs) gr3 ps';
   337                  in
   338                    (gr4, compile_match (snd nvs) [] out_ps
   339                       (Pretty.block (ps @
   340                          [Pretty.brk 1, mk_tuple in_ps,
   341                           Pretty.str " :->", Pretty.brk 1, rest]))
   342                       (Pretty.str "Seq.empty"))
   343                  end
   344              | Sidecond t =>
   345                  let
   346                    val (gr1, side_p) = invoke_codegen thy dep true (gr, t);
   347                    val (nvs, out_ts') = foldl_map distinct_v
   348                      ((names, map (fn x => (x, [x])) vs), out_ts);
   349                    val (gr2, out_ps) = foldl_map
   350                      (invoke_codegen thy dep false) (gr1, out_ts')
   351                    val (gr3, rest) = compile_prems [] vs' (fst nvs) gr2 ps';
   352                  in
   353                    (gr3, compile_match (snd nvs) [] out_ps
   354                       (Pretty.block [Pretty.str "?? ", side_p,
   355                         Pretty.str " :->", Pretty.brk 1, rest])
   356                       (Pretty.str "Seq.empty"))
   357                  end)
   358           end;
   359 
   360     val (gr', prem_p) = compile_prems in_ts' [] all_vs' gr ps;
   361   in
   362     (gr', Pretty.block [Pretty.str "Seq.single inp :->", Pretty.brk 1, prem_p])
   363   end;
   364 
   365 fun compile_pred thy gr dep prfx all_vs arg_vs modes s cls mode =
   366   let val (gr', cl_ps) = foldl_map (fn (gr, cl) =>
   367     compile_clause thy gr dep all_vs arg_vs modes mode cl) (gr, cls)
   368   in
   369     ((gr', "and "), Pretty.block
   370       ([Pretty.block (separate (Pretty.brk 1)
   371          (Pretty.str (prfx ^ modename thy s mode) :: map Pretty.str arg_vs) @
   372          [Pretty.str " inp ="]),
   373         Pretty.brk 1] @
   374        flat (separate [Pretty.str " ++", Pretty.brk 1] (map single cl_ps))))
   375   end;
   376 
   377 fun compile_preds thy gr dep all_vs arg_vs modes preds =
   378   let val ((gr', _), prs) = foldl_map (fn ((gr, prfx), (s, cls)) =>
   379     foldl_map (fn ((gr', prfx'), mode) =>
   380       compile_pred thy gr' dep prfx' all_vs arg_vs modes s cls mode)
   381         ((gr, prfx), the (assoc (modes, s)))) ((gr, "fun "), preds)
   382   in
   383     (gr', space_implode "\n\n" (map Pretty.string_of (flat prs)) ^ ";\n\n")
   384   end;
   385 
   386 (**** processing of introduction rules ****)
   387 
   388 exception Modes of
   389   (string * (int list option list * int list) list) list *
   390   (string * (int list list option list * int list list)) list;
   391 
   392 fun lookup_modes gr dep = apfst flat (apsnd flat (ListPair.unzip
   393   (map ((fn (Some (Modes x), _) => x | _ => ([], [])) o Graph.get_node gr)
   394     (Graph.all_preds gr [dep]))));
   395 
   396 fun string_of_mode (iss, is) = space_implode " -> " (map
   397   (fn None => "X"
   398     | Some js => enclose "[" "]" (commas (map string_of_int js)))
   399        (iss @ [Some is]));
   400 
   401 fun print_modes modes = message ("Inferred modes:\n" ^
   402   space_implode "\n" (map (fn (s, ms) => s ^ ": " ^ commas (map
   403     string_of_mode ms)) modes));
   404 
   405 fun print_factors factors = message ("Factors:\n" ^
   406   space_implode "\n" (map (fn (s, (fs, f)) => s ^ ": " ^
   407     space_implode " -> " (map
   408       (fn None => "X" | Some f' => string_of_factors [] f')
   409         (fs @ [Some f]))) factors));
   410 
   411 fun mk_extra_defs thy gr dep names ts =
   412   foldl (fn (gr, name) =>
   413     if name mem names then gr
   414     else (case get_clauses thy name of
   415         None => gr
   416       | Some (names, intrs) =>
   417           mk_ind_def thy gr dep names intrs))
   418             (gr, foldr add_term_consts (ts, []))
   419 
   420 and mk_ind_def thy gr dep names intrs =
   421   let val ids = map (mk_const_id (sign_of thy)) names
   422   in Graph.add_edge (hd ids, dep) gr handle Graph.UNDEF _ =>
   423     let
   424       fun dest_prem factors (_ $ (Const ("op :", _) $ t $ u)) =
   425             (case head_of u of
   426                Const (name, _) => Prem (split_prod []
   427                  (the (assoc (factors, name))) t, u)
   428              | Var ((name, _), _) => Prem (split_prod []
   429                  (the (assoc (factors, name))) t, u))
   430         | dest_prem factors (_ $ ((eq as Const ("op =", _)) $ t $ u)) =
   431             Prem ([t, u], eq)
   432         | dest_prem factors (_ $ t) = Sidecond t;
   433 
   434       fun add_clause factors (clauses, intr) =
   435         let
   436           val _ $ (_ $ t $ u) = Logic.strip_imp_concl intr;
   437           val Const (name, _) = head_of u;
   438           val prems = map (dest_prem factors) (Logic.strip_imp_prems intr);
   439         in
   440           (overwrite (clauses, (name, if_none (assoc (clauses, name)) [] @
   441              [(split_prod [] (the (assoc (factors, name))) t, prems)])))
   442         end;
   443 
   444       fun add_prod_factors extra_fs (fs, _ $ (Const ("op :", _) $ t $ u)) =
   445             infer_factors (sign_of thy) extra_fs
   446               (fs, (Some (FVar (prod_factors [] t)), u))
   447         | add_prod_factors _ (fs, _) = fs;
   448 
   449       val intrs' = map (rename_term o #prop o rep_thm o standard) intrs;
   450       val _ $ (_ $ _ $ u) = Logic.strip_imp_concl (hd intrs');
   451       val (_, args) = strip_comb u;
   452       val arg_vs = flat (map term_vs args);
   453       val gr' = mk_extra_defs thy
   454         (Graph.add_edge (hd ids, dep)
   455           (Graph.new_node (hd ids, (None, "")) gr)) (hd ids) names intrs';
   456       val (extra_modes', extra_factors) = lookup_modes gr' (hd ids);
   457       val extra_modes =
   458         ("op =", [([], [1]), ([], [2]), ([], [1, 2])]) :: extra_modes';
   459       val fs = map (apsnd dest_factors)
   460         (foldl (add_prod_factors extra_factors) ([], flat (map (fn t =>
   461           Logic.strip_imp_concl t :: Logic.strip_imp_prems t) intrs')));
   462       val _ = (case map fst fs \\ names \\ arg_vs of
   463           [] => ()
   464         | xs => error ("Non-inductive sets: " ^ commas_quote xs));
   465       val factors = mapfilter (fn (name, f) =>
   466         if name mem arg_vs then None
   467         else Some (name, (map (curry assoc fs) arg_vs, f))) fs;
   468       val clauses =
   469         foldl (add_clause (fs @ map (apsnd snd) extra_factors)) ([], intrs');
   470       val modes = infer_modes thy extra_modes factors arg_vs clauses;
   471       val _ = print_factors factors;
   472       val _ = print_modes modes;
   473       val (gr'', s) = compile_preds thy gr' (hd ids) (terms_vs intrs') arg_vs
   474         (modes @ extra_modes) clauses;
   475     in
   476       (Graph.map_node (hd ids) (K (Some (Modes (modes, factors)), s)) gr'')
   477     end      
   478   end;
   479 
   480 fun mk_ind_call thy gr dep t u is_query = (case head_of u of
   481   Const (s, _) => (case get_clauses thy s of
   482        None => None
   483      | Some (names, intrs) =>
   484          let
   485           fun mk_mode (((ts, mode), i), Var _) = ((ts, mode), i+1)
   486             | mk_mode (((ts, mode), i), Free _) = ((ts, mode), i+1)
   487             | mk_mode (((ts, mode), i), t) = ((ts @ [t], mode @ [i]), i+1);
   488 
   489            val gr1 = mk_extra_defs thy
   490              (mk_ind_def thy gr dep names intrs) dep names [u];
   491            val (modes, factors) = lookup_modes gr1 dep;
   492            val ts = split_prod [] (snd (the (assoc (factors, s)))) t;
   493            val (ts', is) = if is_query then
   494                fst (foldl mk_mode ((([], []), 1), ts))
   495              else (ts, 1 upto length ts);
   496            val mode = (case find_first (fn Mode ((_, js), _) => is=js)
   497                   (modes_of modes u) of
   498                 None => error ("No such mode for " ^ s ^ ": " ^
   499                   string_of_mode ([], is))
   500               | mode => mode);
   501            val (gr2, in_ps) = foldl_map
   502              (invoke_codegen thy dep false) (gr1, ts');
   503            val (gr3, ps) = compile_expr thy dep false (gr2, (mode, u))
   504          in
   505            Some (gr3, Pretty.block
   506              (ps @ [Pretty.brk 1, mk_tuple in_ps]))
   507          end)
   508   | _ => None);
   509 
   510 fun inductive_codegen thy gr dep brack (Const ("op :", _) $ t $ u) =
   511       (case mk_ind_call thy gr dep t u false of
   512          None => None
   513        | Some (gr', call_p) => Some (gr', (if brack then parens else I)
   514            (Pretty.block [Pretty.str "?! (", call_p, Pretty.str ")"])))
   515   | inductive_codegen thy gr dep brack (Free ("query", _) $ (Const ("op :", _) $ t $ u)) =
   516       mk_ind_call thy gr dep t u true
   517   | inductive_codegen thy gr dep brack _ = None;
   518 
   519 val setup =
   520   [add_codegen "inductive" inductive_codegen,
   521    CodegenData.init,
   522    add_attribute "ind" add];
   523 
   524 end;
   525 
   526 
   527 (**** combinators for code generated from inductive predicates ****)
   528 
   529 infix 5 :->;
   530 infix 3 ++;
   531 
   532 fun s :-> f = Seq.flat (Seq.map f s);
   533 
   534 fun s1 ++ s2 = Seq.append (s1, s2);
   535 
   536 fun ?? b = if b then Seq.single () else Seq.empty;
   537 
   538 fun ?! s = is_some (Seq.pull s);    
   539 
   540 fun op__61__1 x = Seq.single x;
   541 
   542 val op__61__2 = op__61__1;
   543 
   544 fun op__61__1_2 (x, y) = ?? (x = y);