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