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