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