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