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