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