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