src/HOL/Tools/inductive_codegen.ML
author haftmann
Fri Jan 22 16:56:51 2010 +0100 (2010-01-22)
changeset 34962 807f6ce0273d
parent 33963 977b94b64905
child 35021 c839a4c670c6
permissions -rw-r--r--
HOLogic.strip_psplits: types are ordered after syntactic appearance, not after corresponding de-Bruin index (closer correspondence to similar strip operations)
haftmann@24584
     1
(*  Title:      HOL/Tools/inductive_codegen.ML
wenzelm@11539
     2
    Author:     Stefan Berghofer, TU Muenchen
berghofe@11537
     3
wenzelm@11539
     4
Code generator for inductive predicates.
berghofe@11537
     5
*)
berghofe@11537
     6
berghofe@11537
     7
signature INDUCTIVE_CODEGEN =
berghofe@11537
     8
sig
berghofe@22271
     9
  val add : string option -> int option -> attribute
berghofe@33771
    10
  val test_fn : (int * int * int -> term list option) Unsynchronized.ref
berghofe@33771
    11
  val test_term: Proof.context -> term -> int -> term list option
wenzelm@18708
    12
  val setup : theory -> theory
berghofe@33771
    13
  val quickcheck_setup : theory -> theory
berghofe@11537
    14
end;
berghofe@11537
    15
berghofe@11537
    16
structure InductiveCodegen : INDUCTIVE_CODEGEN =
berghofe@11537
    17
struct
berghofe@11537
    18
berghofe@11537
    19
open Codegen;
berghofe@11537
    20
berghofe@12557
    21
(**** theory data ****)
berghofe@12557
    22
wenzelm@18930
    23
fun merge_rules tabs =
haftmann@22642
    24
  Symtab.join (fn _ => AList.merge (Thm.eq_thm_prop) (K true)) tabs;
wenzelm@18930
    25
wenzelm@33522
    26
structure CodegenData = Theory_Data
wenzelm@22846
    27
(
berghofe@15031
    28
  type T =
berghofe@22271
    29
    {intros : (thm * (string * int)) list Symtab.table,
berghofe@15031
    30
     graph : unit Graph.T,
berghofe@16645
    31
     eqns : (thm * string) list Symtab.table};
berghofe@15031
    32
  val empty =
berghofe@15031
    33
    {intros = Symtab.empty, graph = Graph.empty, eqns = Symtab.empty};
wenzelm@16424
    34
  val extend = I;
wenzelm@33522
    35
  fun merge ({intros=intros1, graph=graph1, eqns=eqns1},
wenzelm@33522
    36
    {intros=intros2, graph=graph2, eqns=eqns2}) : T =
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)};
wenzelm@22846
    40
);
berghofe@12557
    41
berghofe@12557
    42
berghofe@12557
    43
fun warn thm = warning ("InductiveCodegen: Not a proper clause:\n" ^
wenzelm@32091
    44
  Display.string_of_thm_without_context thm);
berghofe@11537
    45
wenzelm@33244
    46
fun add_node x g = Graph.new_node (x, ()) g handle Graph.DUP _ => g;
berghofe@14162
    47
berghofe@22271
    48
fun add optmod optnparms = Thm.declaration_attribute (fn thm => Context.mapping (fn thy =>
berghofe@16645
    49
  let
berghofe@16645
    50
    val {intros, graph, eqns} = CodegenData.get thy;
berghofe@16645
    51
    fun thyname_of s = (case optmod of
haftmann@27398
    52
      NONE => Codegen.thyname_of_const thy s | SOME s => s);
berghofe@22271
    53
  in (case Option.map strip_comb (try HOLogic.dest_Trueprop (concl_of thm)) of
berghofe@22271
    54
      SOME (Const ("op =", _), [t, _]) => (case head_of t of
berghofe@15031
    55
        Const (s, _) =>
wenzelm@18728
    56
          CodegenData.put {intros = intros, graph = graph,
haftmann@22642
    57
             eqns = eqns |> Symtab.map_default (s, [])
haftmann@22642
    58
               (AList.update Thm.eq_thm_prop (thm, thyname_of s))} thy
wenzelm@18728
    59
      | _ => (warn thm; thy))
berghofe@22271
    60
    | SOME (Const (s, _), _) =>
berghofe@22271
    61
        let
wenzelm@29287
    62
          val cs = fold Term.add_const_names (Thm.prems_of thm) [];
berghofe@22271
    63
          val rules = Symtab.lookup_list intros s;
berghofe@22271
    64
          val nparms = (case optnparms of
berghofe@22271
    65
            SOME k => k
berghofe@22271
    66
          | NONE => (case rules of
haftmann@31723
    67
             [] => (case try (Inductive.the_inductive (ProofContext.init thy)) s of
berghofe@22791
    68
                 SOME (_, {raw_induct, ...}) =>
haftmann@31723
    69
                   length (Inductive.params_of raw_induct)
berghofe@22271
    70
               | NONE => 0)
berghofe@22271
    71
            | xs => snd (snd (snd (split_last xs)))))
berghofe@22271
    72
        in CodegenData.put
berghofe@22271
    73
          {intros = intros |>
haftmann@22642
    74
           Symtab.update (s, (AList.update Thm.eq_thm_prop
haftmann@22642
    75
             (thm, (thyname_of s, nparms)) rules)),
wenzelm@33338
    76
           graph = fold_rev (Graph.add_edge o pair s) cs (fold add_node (s :: cs) graph),
berghofe@22271
    77
           eqns = eqns} thy
berghofe@22271
    78
        end
wenzelm@18728
    79
    | _ => (warn thm; thy))
wenzelm@20897
    80
  end) I);
berghofe@12557
    81
berghofe@12557
    82
fun get_clauses thy s =
berghofe@15031
    83
  let val {intros, graph, ...} = CodegenData.get thy
wenzelm@17412
    84
  in case Symtab.lookup intros s of
haftmann@31723
    85
      NONE => (case try (Inductive.the_inductive (ProofContext.init thy)) s of
skalberg@15531
    86
        NONE => NONE
berghofe@22271
    87
      | SOME ({names, ...}, {intrs, raw_induct, ...}) =>
haftmann@27398
    88
          SOME (names, Codegen.thyname_of_const thy s,
haftmann@31723
    89
            length (Inductive.params_of raw_induct),
berghofe@22661
    90
            preprocess thy intrs))
skalberg@15531
    91
    | SOME _ =>
berghofe@16645
    92
        let
berghofe@16645
    93
          val SOME names = find_first
haftmann@22642
    94
            (fn xs => member (op =) xs s) (Graph.strong_conn graph);
haftmann@22642
    95
          val intrs as (_, (thyname, nparms)) :: _ =
haftmann@22642
    96
            maps (the o Symtab.lookup intros) names;
haftmann@22642
    97
        in SOME (names, thyname, nparms, preprocess thy (map fst (rev intrs))) end
berghofe@14162
    98
  end;
berghofe@12557
    99
berghofe@12557
   100
berghofe@11537
   101
(**** check if a term contains only constructor functions ****)
berghofe@11537
   102
berghofe@11537
   103
fun is_constrt thy =
berghofe@11537
   104
  let
haftmann@31784
   105
    val cnstrs = flat (maps
berghofe@11537
   106
      (map (fn (_, (_, _, cs)) => map (apsnd length) cs) o #descr o snd)
haftmann@33963
   107
      (Symtab.dest (Datatype_Data.get_all thy)));
berghofe@11537
   108
    fun check t = (case strip_comb t of
berghofe@11537
   109
        (Var _, []) => true
haftmann@17521
   110
      | (Const (s, _), ts) => (case AList.lookup (op =) cnstrs s of
skalberg@15531
   111
            NONE => false
skalberg@15531
   112
          | SOME i => length ts = i andalso forall check ts)
berghofe@11537
   113
      | _ => false)
berghofe@11537
   114
  in check end;
berghofe@11537
   115
berghofe@11537
   116
(**** check if a type is an equality type (i.e. doesn't contain fun) ****)
berghofe@11537
   117
berghofe@11537
   118
fun is_eqT (Type (s, Ts)) = s <> "fun" andalso forall is_eqT Ts
berghofe@11537
   119
  | is_eqT _ = true;
berghofe@11537
   120
berghofe@11537
   121
(**** mode inference ****)
berghofe@11537
   122
berghofe@15204
   123
fun string_of_mode (iss, is) = space_implode " -> " (map
skalberg@15531
   124
  (fn NONE => "X"
skalberg@15531
   125
    | SOME js => enclose "[" "]" (commas (map string_of_int js)))
skalberg@15531
   126
       (iss @ [SOME is]));
berghofe@15204
   127
berghofe@15204
   128
fun print_modes modes = message ("Inferred modes:\n" ^
wenzelm@26931
   129
  cat_lines (map (fn (s, ms) => s ^ ": " ^ commas (map
berghofe@33771
   130
    (fn (m, rnd) => string_of_mode m ^
berghofe@33771
   131
       (if rnd then " (random)" else "")) ms)) modes));
berghofe@15204
   132
wenzelm@29265
   133
val term_vs = map (fst o fst o dest_Var) o OldTerm.term_vars;
wenzelm@32952
   134
val terms_vs = distinct (op =) o maps term_vs;
berghofe@11537
   135
berghofe@11537
   136
(** collect all Vars in a term (with duplicates!) **)
wenzelm@16861
   137
fun term_vTs tm =
wenzelm@16861
   138
  fold_aterms (fn Var ((x, _), T) => cons (x, T) | _ => I) tm [];
berghofe@11537
   139
berghofe@11537
   140
fun get_args _ _ [] = ([], [])
berghofe@11537
   141
  | get_args is i (x::xs) = (if i mem is then apfst else apsnd) (cons x)
berghofe@11537
   142
      (get_args is (i+1) xs);
berghofe@11537
   143
berghofe@11537
   144
fun merge xs [] = xs
berghofe@11537
   145
  | merge [] ys = ys
berghofe@11537
   146
  | merge (x::xs) (y::ys) = if length x >= length y then x::merge xs (y::ys)
berghofe@11537
   147
      else y::merge (x::xs) ys;
berghofe@11537
   148
berghofe@11537
   149
fun subsets i j = if i <= j then
berghofe@11537
   150
       let val is = subsets (i+1) j
berghofe@11537
   151
       in merge (map (fn ks => i::ks) is) is end
berghofe@11537
   152
     else [[]];
berghofe@11537
   153
berghofe@12557
   154
fun cprod ([], ys) = []
berghofe@12557
   155
  | cprod (x :: xs, ys) = map (pair x) ys @ cprod (xs, ys);
berghofe@12557
   156
wenzelm@30190
   157
fun cprods xss = List.foldr (map op :: o cprod) [[]] xss;
berghofe@12557
   158
berghofe@33771
   159
datatype mode = Mode of ((int list option list * int list) * bool) * int list * mode option list;
berghofe@33771
   160
berghofe@33771
   161
fun needs_random (Mode ((_, b), _, ms)) =
berghofe@33771
   162
  b orelse exists (fn NONE => false | SOME m => needs_random m) ms;
berghofe@12557
   163
berghofe@12557
   164
fun modes_of modes t =
berghofe@12557
   165
  let
berghofe@22271
   166
    val ks = 1 upto length (binder_types (fastype_of t));
berghofe@33771
   167
    val default = [Mode ((([], ks), false), ks, [])];
wenzelm@32952
   168
    fun mk_modes name args = Option.map
berghofe@33771
   169
     (maps (fn (m as ((iss, is), _)) =>
berghofe@22271
   170
        let
berghofe@22271
   171
          val (args1, args2) =
berghofe@22271
   172
            if length args < length iss then
berghofe@22271
   173
              error ("Too few arguments for inductive predicate " ^ name)
berghofe@22271
   174
            else chop (length iss) args;
berghofe@22271
   175
          val k = length args2;
berghofe@22271
   176
          val prfx = 1 upto k
berghofe@22271
   177
        in
berghofe@22271
   178
          if not (is_prefix op = prfx is) then [] else
berghofe@22271
   179
          let val is' = map (fn i => i - k) (List.drop (is, k))
berghofe@22271
   180
          in map (fn x => Mode (m, is', x)) (cprods (map
berghofe@22271
   181
            (fn (NONE, _) => [NONE]
wenzelm@33317
   182
              | (SOME js, arg) => map SOME (filter
berghofe@22271
   183
                  (fn Mode (_, js', _) => js=js') (modes_of modes arg)))
berghofe@22271
   184
                    (iss ~~ args1)))
berghofe@22271
   185
          end
berghofe@22271
   186
        end)) (AList.lookup op = modes name)
berghofe@12557
   187
berghofe@12557
   188
  in (case strip_comb t of
berghofe@14163
   189
      (Const ("op =", Type (_, [T, _])), _) =>
berghofe@33771
   190
        [Mode ((([], [1]), false), [1], []), Mode ((([], [2]), false), [2], [])] @
berghofe@33771
   191
        (if is_eqT T then [Mode ((([], [1, 2]), false), [1, 2], [])] else [])
berghofe@22271
   192
    | (Const (name, _), args) => the_default default (mk_modes name args)
berghofe@22271
   193
    | (Var ((name, _), _), args) => the (mk_modes name args)
berghofe@22271
   194
    | (Free (name, _), args) => the (mk_modes name args)
berghofe@22271
   195
    | _ => default)
berghofe@12557
   196
  end;
berghofe@12557
   197
berghofe@26806
   198
datatype indprem = Prem of term list * term * bool | Sidecond of term;
berghofe@12557
   199
berghofe@33771
   200
fun missing_vars vs ts = subtract (fn (x, ((y, _), _)) => x = y) vs
berghofe@33771
   201
  (fold Term.add_vars ts []);
berghofe@33771
   202
berghofe@33771
   203
fun monomorphic_vars vs = null (fold (Term.add_tvarsT o snd) vs []);
berghofe@33771
   204
berghofe@33771
   205
fun mode_ord p = int_ord (pairself (fn (Mode ((_, rnd), _, _), vs) =>
berghofe@33771
   206
  length vs + (if null vs then 0 else 1) + (if rnd then 1 else 0)) p);
berghofe@33771
   207
berghofe@11537
   208
fun select_mode_prem thy modes vs ps =
berghofe@33771
   209
  sort (mode_ord o pairself (hd o snd))
berghofe@33771
   210
    (filter_out (null o snd) (ps ~~ map
berghofe@33771
   211
      (fn Prem (us, t, is_set) => sort mode_ord
berghofe@33771
   212
          (List.mapPartial (fn m as Mode (_, is, _) =>
berghofe@33771
   213
            let
berghofe@33771
   214
              val (in_ts, out_ts) = get_args is 1 us;
berghofe@33771
   215
              val (out_ts', in_ts') = List.partition (is_constrt thy) out_ts;
berghofe@33771
   216
              val vTs = maps term_vTs out_ts';
berghofe@33771
   217
              val dupTs = map snd (duplicates (op =) vTs) @
berghofe@33771
   218
                map_filter (AList.lookup (op =) vTs) vs;
berghofe@33771
   219
              val missing_vs = missing_vars vs (t :: in_ts @ in_ts')
berghofe@33771
   220
            in
berghofe@33771
   221
              if forall (is_eqT o fastype_of) in_ts' andalso forall is_eqT dupTs
berghofe@33771
   222
                andalso monomorphic_vars missing_vs
berghofe@33771
   223
              then SOME (m, missing_vs)
berghofe@33771
   224
              else NONE
berghofe@33771
   225
            end)
berghofe@33771
   226
              (if is_set then [Mode ((([], []), false), [], [])]
berghofe@33771
   227
               else modes_of modes t handle Option =>
berghofe@33771
   228
                 error ("Bad predicate: " ^ Syntax.string_of_term_global thy t)))
berghofe@33771
   229
        | Sidecond t =>
berghofe@33771
   230
            let val missing_vs = missing_vars vs [t]
berghofe@33771
   231
            in
berghofe@33771
   232
              if monomorphic_vars missing_vs
berghofe@33771
   233
              then [(Mode ((([], []), false), [], []), missing_vs)]
berghofe@33771
   234
              else []
berghofe@33771
   235
            end)
berghofe@33771
   236
              ps));
berghofe@11537
   237
berghofe@33771
   238
fun use_random () = "random_ind" mem !Codegen.mode;
berghofe@33771
   239
berghofe@33771
   240
fun check_mode_clause thy arg_vs modes ((iss, is), rnd) (ts, ps) =
berghofe@11537
   241
  let
wenzelm@32952
   242
    val modes' = modes @ map_filter
berghofe@33771
   243
      (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [(([], js), false)]))
berghofe@12557
   244
        (arg_vs ~~ iss);
berghofe@33771
   245
    fun check_mode_prems vs rnd [] = SOME (vs, rnd)
berghofe@33771
   246
      | check_mode_prems vs rnd ps = (case select_mode_prem thy modes' vs ps of
berghofe@33771
   247
          (x, (m, []) :: _) :: _ => check_mode_prems
haftmann@33042
   248
            (case x of Prem (us, _, _) => union (op =) vs (terms_vs us) | _ => vs)
berghofe@33771
   249
            (rnd orelse needs_random m)
berghofe@33771
   250
            (filter_out (equal x) ps)
berghofe@33771
   251
        | (_, (_, vs') :: _) :: _ =>
berghofe@33771
   252
            if use_random () then
berghofe@33771
   253
              check_mode_prems (union (op =) vs (map (fst o fst) vs')) true ps
berghofe@33771
   254
            else NONE
berghofe@33771
   255
        | _ => NONE);
skalberg@15570
   256
    val (in_ts, in_ts') = List.partition (is_constrt thy) (fst (get_args is 1 ts));
berghofe@11537
   257
    val in_vs = terms_vs in_ts;
berghofe@11537
   258
  in
berghofe@33771
   259
    if forall is_eqT (map snd (duplicates (op =) (maps term_vTs in_ts))) andalso
berghofe@33771
   260
      forall (is_eqT o fastype_of) in_ts'
berghofe@33771
   261
    then (case check_mode_prems (union (op =) arg_vs in_vs) rnd ps of
berghofe@33771
   262
       NONE => NONE
berghofe@33771
   263
     | SOME (vs, rnd') =>
berghofe@33771
   264
         let val missing_vs = missing_vars vs ts
berghofe@33771
   265
         in
berghofe@33771
   266
           if null missing_vs orelse
berghofe@33771
   267
             use_random () andalso monomorphic_vars missing_vs
berghofe@33771
   268
           then SOME (rnd' orelse not (null missing_vs))
berghofe@33771
   269
           else NONE
berghofe@33771
   270
         end)
berghofe@33771
   271
    else NONE
berghofe@11537
   272
  end;
berghofe@11537
   273
berghofe@11537
   274
fun check_modes_pred thy arg_vs preds modes (p, ms) =
haftmann@17521
   275
  let val SOME rs = AList.lookup (op =) preds p
berghofe@33771
   276
  in (p, List.mapPartial (fn m as (m', _) =>
berghofe@33771
   277
    let val xs = map (check_mode_clause thy arg_vs modes m) rs
berghofe@33771
   278
    in case find_index is_none xs of
berghofe@33771
   279
        ~1 => SOME (m', exists (fn SOME b => b) xs)
berghofe@33771
   280
      | i => (message ("Clause " ^ string_of_int (i+1) ^ " of " ^
berghofe@33771
   281
        p ^ " violates mode " ^ string_of_mode m'); NONE)
berghofe@33771
   282
    end) ms)
berghofe@15204
   283
  end;
berghofe@11537
   284
berghofe@33771
   285
fun fixp f (x : (string * ((int list option list * int list) * bool) list) list) =
berghofe@11537
   286
  let val y = f x
berghofe@11537
   287
  in if x = y then x else fixp f y end;
berghofe@11537
   288
berghofe@22271
   289
fun infer_modes thy extra_modes arities arg_vs preds = fixp (fn modes =>
berghofe@11537
   290
  map (check_modes_pred thy arg_vs preds (modes @ extra_modes)) modes)
berghofe@33771
   291
    (map (fn (s, (ks, k)) => (s, map (rpair false) (cprod (cprods (map
skalberg@15531
   292
      (fn NONE => [NONE]
berghofe@22271
   293
        | SOME k' => map SOME (subsets 1 k')) ks),
berghofe@33771
   294
      subsets 1 k)))) arities);
berghofe@11537
   295
berghofe@11537
   296
(**** code generation ****)
berghofe@11537
   297
berghofe@11537
   298
fun mk_eq (x::xs) =
berghofe@11537
   299
  let fun mk_eqs _ [] = []
berghofe@26975
   300
        | mk_eqs a (b::cs) = str (a ^ " = " ^ b) :: mk_eqs b cs
berghofe@11537
   301
  in mk_eqs x xs end;
berghofe@11537
   302
berghofe@26975
   303
fun mk_tuple xs = Pretty.block (str "(" ::
wenzelm@32952
   304
  flat (separate [str ",", Pretty.brk 1] (map single xs)) @
berghofe@26975
   305
  [str ")"]);
berghofe@11537
   306
wenzelm@33244
   307
fun mk_v s (names, vs) =
wenzelm@33244
   308
  (case AList.lookup (op =) vs s of
wenzelm@33244
   309
    NONE => (s, (names, (s, [s])::vs))
wenzelm@33244
   310
  | SOME xs =>
wenzelm@33244
   311
      let val s' = Name.variant names s
wenzelm@33244
   312
      in (s', (s'::names, AList.update (op =) (s, s'::xs) vs)) end);
berghofe@11537
   313
wenzelm@33244
   314
fun distinct_v (Var ((s, 0), T)) nvs =
wenzelm@33244
   315
      let val (s', nvs') = mk_v s nvs
wenzelm@33244
   316
      in (Var ((s', 0), T), nvs') end
wenzelm@33244
   317
  | distinct_v (t $ u) nvs =
berghofe@11537
   318
      let
wenzelm@33244
   319
        val (t', nvs') = distinct_v t nvs;
wenzelm@33244
   320
        val (u', nvs'') = distinct_v u nvs';
wenzelm@33244
   321
      in (t' $ u', nvs'') end
wenzelm@33244
   322
  | distinct_v t nvs = (t, nvs);
berghofe@11537
   323
berghofe@15061
   324
fun is_exhaustive (Var _) = true
berghofe@15061
   325
  | is_exhaustive (Const ("Pair", _) $ t $ u) =
berghofe@15061
   326
      is_exhaustive t andalso is_exhaustive u
berghofe@15061
   327
  | is_exhaustive _ = false;
berghofe@15061
   328
berghofe@15061
   329
fun compile_match nvs eq_ps out_ps success_p can_fail =
wenzelm@32952
   330
  let val eqs = flat (separate [str " andalso", Pretty.brk 1]
wenzelm@32952
   331
    (map single (maps (mk_eq o snd) nvs @ eq_ps)));
berghofe@11537
   332
  in
berghofe@11537
   333
    Pretty.block
berghofe@26975
   334
     ([str "(fn ", mk_tuple out_ps, str " =>", Pretty.brk 1] @
berghofe@26975
   335
      (Pretty.block ((if eqs=[] then [] else str "if " ::
berghofe@26975
   336
         [Pretty.block eqs, Pretty.brk 1, str "then "]) @
berghofe@11537
   337
         (success_p ::
berghofe@26975
   338
          (if eqs=[] then [] else [Pretty.brk 1, str "else DSeq.empty"]))) ::
berghofe@15061
   339
       (if can_fail then
berghofe@26975
   340
          [Pretty.brk 1, str "| _ => DSeq.empty)"]
berghofe@26975
   341
        else [str ")"])))
berghofe@11537
   342
  end;
berghofe@11537
   343
berghofe@17144
   344
fun modename module s (iss, is) gr =
haftmann@28537
   345
  let val (id, gr') = if s = @{const_name "op ="} then (("", "equal"), gr)
berghofe@17144
   346
    else mk_const_id module s gr
haftmann@28537
   347
  in (space_implode "__"
berghofe@17144
   348
    (mk_qual_id module id ::
wenzelm@32952
   349
      map (space_implode "_" o map string_of_int) (map_filter I iss @ [is])), gr')
berghofe@17144
   350
  end;
berghofe@11537
   351
berghofe@22271
   352
fun mk_funcomp brack s k p = (if brack then parens else I)
berghofe@26975
   353
  (Pretty.block [Pretty.block ((if k = 0 then [] else [str "("]) @
berghofe@26975
   354
    separate (Pretty.brk 1) (str s :: replicate k (str "|> ???")) @
berghofe@26975
   355
    (if k = 0 then [] else [str ")"])), Pretty.brk 1, p]);
berghofe@22271
   356
haftmann@28537
   357
fun compile_expr thy defs dep module brack modes (NONE, t) gr =
haftmann@28537
   358
      apfst single (invoke_codegen thy defs dep module brack t gr)
haftmann@28537
   359
  | compile_expr _ _ _ _ _ _ (SOME _, Var ((name, _), _)) gr =
haftmann@28537
   360
      ([str name], gr)
berghofe@33771
   361
  | compile_expr thy defs dep module brack modes (SOME (Mode ((mode, _), _, ms)), t) gr =
berghofe@22271
   362
      (case strip_comb t of
berghofe@22271
   363
         (Const (name, _), args) =>
haftmann@28537
   364
           if name = @{const_name "op ="} orelse AList.defined op = modes name then
berghofe@22271
   365
             let
berghofe@22271
   366
               val (args1, args2) = chop (length ms) args;
haftmann@28537
   367
               val ((ps, mode_id), gr') = gr |> fold_map
haftmann@28537
   368
                   (compile_expr thy defs dep module true modes) (ms ~~ args1)
haftmann@28537
   369
                   ||>> modename module name mode;
haftmann@28537
   370
               val (ps', gr'') = (case mode of
haftmann@28537
   371
                   ([], []) => ([str "()"], gr')
haftmann@28537
   372
                 | _ => fold_map
haftmann@28537
   373
                     (invoke_codegen thy defs dep module true) args2 gr')
haftmann@28537
   374
             in ((if brack andalso not (null ps andalso null ps') then
berghofe@22271
   375
               single o parens o Pretty.block else I)
wenzelm@32952
   376
                 (flat (separate [Pretty.brk 1]
haftmann@28537
   377
                   ([str mode_id] :: ps @ map single ps'))), gr')
berghofe@22271
   378
             end
haftmann@28537
   379
           else apfst (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
haftmann@28537
   380
             (invoke_codegen thy defs dep module true t gr)
haftmann@28537
   381
       | _ => apfst (single o mk_funcomp brack "??" (length (binder_types (fastype_of t))))
haftmann@28537
   382
           (invoke_codegen thy defs dep module true t gr));
berghofe@12557
   383
haftmann@28537
   384
fun compile_clause thy defs dep module all_vs arg_vs modes (iss, is) (ts, ps) inp gr =
berghofe@11537
   385
  let
wenzelm@32952
   386
    val modes' = modes @ map_filter
berghofe@33771
   387
      (fn (_, NONE) => NONE | (v, SOME js) => SOME (v, [(([], js), false)]))
berghofe@12557
   388
        (arg_vs ~~ iss);
berghofe@12557
   389
wenzelm@33244
   390
    fun check_constrt t (names, eqs) =
wenzelm@33244
   391
      if is_constrt thy t then (t, (names, eqs))
wenzelm@33244
   392
      else
wenzelm@20071
   393
        let val s = Name.variant names "x";
wenzelm@33244
   394
        in (Var ((s, 0), fastype_of t), (s::names, (s, t)::eqs)) end;
berghofe@11537
   395
haftmann@28537
   396
    fun compile_eq (s, t) gr =
haftmann@28537
   397
      apfst (Pretty.block o cons (str (s ^ " = ")) o single)
haftmann@28537
   398
        (invoke_codegen thy defs dep module false t gr);
berghofe@15031
   399
berghofe@12557
   400
    val (in_ts, out_ts) = get_args is 1 ts;
wenzelm@33244
   401
    val (in_ts', (all_vs', eqs)) = fold_map check_constrt in_ts (all_vs, []);
berghofe@11537
   402
haftmann@28537
   403
    fun compile_prems out_ts' vs names [] gr =
berghofe@11537
   404
          let
wenzelm@33244
   405
            val (out_ps, gr2) =
wenzelm@33244
   406
              fold_map (invoke_codegen thy defs dep module false) out_ts gr;
haftmann@28537
   407
            val (eq_ps, gr3) = fold_map compile_eq eqs gr2;
wenzelm@33244
   408
            val (out_ts'', (names', eqs')) = fold_map check_constrt out_ts' (names, []);
wenzelm@33244
   409
            val (out_ts''', nvs) =
wenzelm@33244
   410
              fold_map distinct_v out_ts'' (names', map (fn x => (x, [x])) vs);
wenzelm@33244
   411
            val (out_ps', gr4) =
wenzelm@33244
   412
              fold_map (invoke_codegen thy defs dep module false) out_ts''' gr3;
haftmann@28537
   413
            val (eq_ps', gr5) = fold_map compile_eq eqs' gr4;
berghofe@33771
   414
            val vs' = distinct (op =) (flat (vs :: map term_vs out_ts'));
berghofe@33771
   415
            val missing_vs = missing_vars vs' out_ts;
berghofe@33771
   416
            val final_p = Pretty.block
berghofe@33771
   417
              [str "DSeq.single", Pretty.brk 1, mk_tuple out_ps]
berghofe@11537
   418
          in
berghofe@33771
   419
            if null missing_vs then
berghofe@33771
   420
              (compile_match (snd nvs) (eq_ps @ eq_ps') out_ps'
berghofe@33771
   421
                 final_p (exists (not o is_exhaustive) out_ts'''), gr5)
berghofe@33771
   422
            else
berghofe@33771
   423
              let
berghofe@33771
   424
                val (pat_p, gr6) = invoke_codegen thy defs dep module true
berghofe@33771
   425
                  (HOLogic.mk_tuple (map Var missing_vs)) gr5;
berghofe@33771
   426
                val gen_p = mk_gen gr6 module true [] ""
berghofe@33771
   427
                  (HOLogic.mk_tupleT (map snd missing_vs))
berghofe@33771
   428
              in
berghofe@33771
   429
                (compile_match (snd nvs) eq_ps' out_ps'
berghofe@33771
   430
                   (Pretty.block [str "DSeq.generator ", gen_p,
berghofe@33771
   431
                      str " :->", Pretty.brk 1,
berghofe@33771
   432
                      compile_match [] eq_ps [pat_p] final_p false])
berghofe@33771
   433
                   (exists (not o is_exhaustive) out_ts'''),
berghofe@33771
   434
                 gr6)
berghofe@33771
   435
              end
berghofe@11537
   436
          end
haftmann@28537
   437
      | compile_prems out_ts vs names ps gr =
berghofe@11537
   438
          let
haftmann@31852
   439
            val vs' = distinct (op =) (flat (vs :: map term_vs out_ts));
wenzelm@33244
   440
            val (out_ts', (names', eqs)) = fold_map check_constrt out_ts (names, []);
wenzelm@33244
   441
            val (out_ts'', nvs) = fold_map distinct_v out_ts' (names', map (fn x => (x, [x])) vs);
wenzelm@33244
   442
            val (out_ps, gr0) = fold_map (invoke_codegen thy defs dep module false) out_ts'' gr;
haftmann@28537
   443
            val (eq_ps, gr1) = fold_map compile_eq eqs gr0;
berghofe@11537
   444
          in
berghofe@33771
   445
            (case hd (select_mode_prem thy modes' vs' ps) of
berghofe@33771
   446
               (p as Prem (us, t, is_set), (mode as Mode (_, js, _), []) :: _) =>
berghofe@11537
   447
                 let
berghofe@33771
   448
                   val ps' = filter_out (equal p) ps;
berghofe@15031
   449
                   val (in_ts, out_ts''') = get_args js 1 us;
haftmann@28537
   450
                   val (in_ps, gr2) = fold_map
haftmann@28537
   451
                     (invoke_codegen thy defs dep module true) in_ts gr1;
haftmann@28537
   452
                   val (ps, gr3) =
berghofe@26806
   453
                     if not is_set then
haftmann@28537
   454
                       apfst (fn ps => ps @
berghofe@24129
   455
                           (if null in_ps then [] else [Pretty.brk 1]) @
berghofe@22271
   456
                           separate (Pretty.brk 1) in_ps)
berghofe@22271
   457
                         (compile_expr thy defs dep module false modes
berghofe@33771
   458
                           (SOME mode, t) gr2)
berghofe@26806
   459
                     else
haftmann@31852
   460
                       apfst (fn p => Pretty.breaks [str "DSeq.of_list", str "(case", p,
haftmann@31852
   461
                         str "of", str "Set", str "xs", str "=>", str "xs)"])
haftmann@31852
   462
                         (*this is a very strong assumption about the generated code!*)
haftmann@28537
   463
                           (invoke_codegen thy defs dep module true t gr2);
haftmann@28537
   464
                   val (rest, gr4) = compile_prems out_ts''' vs' (fst nvs) ps' gr3;
berghofe@11537
   465
                 in
haftmann@28537
   466
                   (compile_match (snd nvs) eq_ps out_ps
berghofe@12557
   467
                      (Pretty.block (ps @
berghofe@26975
   468
                         [str " :->", Pretty.brk 1, rest]))
haftmann@28537
   469
                      (exists (not o is_exhaustive) out_ts''), gr4)
berghofe@11537
   470
                 end
berghofe@33771
   471
             | (p as Sidecond t, [(_, [])]) =>
berghofe@11537
   472
                 let
berghofe@33771
   473
                   val ps' = filter_out (equal p) ps;
haftmann@28537
   474
                   val (side_p, gr2) = invoke_codegen thy defs dep module true t gr1;
haftmann@28537
   475
                   val (rest, gr3) = compile_prems [] vs' (fst nvs) ps' gr2;
berghofe@11537
   476
                 in
haftmann@28537
   477
                   (compile_match (snd nvs) eq_ps out_ps
berghofe@26975
   478
                      (Pretty.block [str "?? ", side_p,
berghofe@26975
   479
                        str " :->", Pretty.brk 1, rest])
haftmann@28537
   480
                      (exists (not o is_exhaustive) out_ts''), gr3)
berghofe@33771
   481
                 end
berghofe@33771
   482
             | (_, (_, missing_vs) :: _) =>
berghofe@33771
   483
                 let
berghofe@33771
   484
                   val T = HOLogic.mk_tupleT (map snd missing_vs);
berghofe@33771
   485
                   val (_, gr2) = invoke_tycodegen thy defs dep module false T gr1;
berghofe@33771
   486
                   val gen_p = mk_gen gr2 module true [] "" T;
berghofe@33771
   487
                   val (rest, gr3) = compile_prems
berghofe@33771
   488
                     [HOLogic.mk_tuple (map Var missing_vs)] vs' (fst nvs) ps gr2
berghofe@33771
   489
                 in
berghofe@33771
   490
                   (compile_match (snd nvs) eq_ps out_ps
berghofe@33771
   491
                      (Pretty.block [str "DSeq.generator", Pretty.brk 1,
berghofe@33771
   492
                        gen_p, str " :->", Pretty.brk 1, rest])
berghofe@33771
   493
                      (exists (not o is_exhaustive) out_ts''), gr3)
berghofe@11537
   494
                 end)
berghofe@11537
   495
          end;
berghofe@11537
   496
haftmann@28537
   497
    val (prem_p, gr') = compile_prems in_ts' arg_vs all_vs' ps gr ;
berghofe@11537
   498
  in
haftmann@28537
   499
    (Pretty.block [str "DSeq.single", Pretty.brk 1, inp,
haftmann@28537
   500
       str " :->", Pretty.brk 1, prem_p], gr')
berghofe@11537
   501
  end;
berghofe@11537
   502
haftmann@28537
   503
fun compile_pred thy defs dep module prfx all_vs arg_vs modes s cls mode gr =
berghofe@22271
   504
  let
berghofe@26975
   505
    val xs = map str (Name.variant_list arg_vs
berghofe@22271
   506
      (map (fn i => "x" ^ string_of_int i) (snd mode)));
haftmann@28537
   507
    val ((cl_ps, mode_id), gr') = gr |>
haftmann@28537
   508
      fold_map (fn cl => compile_clause thy defs
haftmann@28537
   509
        dep module all_vs arg_vs modes mode cl (mk_tuple xs)) cls ||>>
berghofe@22271
   510
      modename module s mode
berghofe@11537
   511
  in
haftmann@28537
   512
    (Pretty.block
berghofe@11537
   513
      ([Pretty.block (separate (Pretty.brk 1)
berghofe@26975
   514
         (str (prfx ^ mode_id) ::
berghofe@26975
   515
           map str arg_vs @
berghofe@26975
   516
           (case mode of ([], []) => [str "()"] | _ => xs)) @
berghofe@26975
   517
         [str " ="]),
berghofe@11537
   518
        Pretty.brk 1] @
wenzelm@32952
   519
       flat (separate [str " ++", Pretty.brk 1] (map single cl_ps))), (gr', "and "))
berghofe@11537
   520
  end;
berghofe@11537
   521
haftmann@28537
   522
fun compile_preds thy defs dep module all_vs arg_vs modes preds gr =
haftmann@28537
   523
  let val (prs, (gr', _)) = fold_map (fn (s, cls) =>
berghofe@33771
   524
    fold_map (fn (mode, _) => fn (gr', prfx') => compile_pred thy defs
haftmann@28537
   525
      dep module prfx' all_vs arg_vs modes s cls mode gr')
haftmann@28537
   526
        (((the o AList.lookup (op =) modes) s))) preds (gr, "fun ")
berghofe@11537
   527
  in
wenzelm@32952
   528
    (space_implode "\n\n" (map string_of (flat prs)) ^ ";\n\n", gr')
berghofe@11537
   529
  end;
berghofe@11537
   530
berghofe@11537
   531
(**** processing of introduction rules ****)
berghofe@11537
   532
berghofe@12557
   533
exception Modes of
berghofe@33771
   534
  (string * ((int list option list * int list) * bool) list) list *
berghofe@22271
   535
  (string * (int option list * int)) list;
berghofe@12557
   536
wenzelm@32952
   537
fun lookup_modes gr dep = apfst flat (apsnd flat (ListPair.unzip
berghofe@17144
   538
  (map ((fn (SOME (Modes x), _, _) => x | _ => ([], [])) o get_node gr)
berghofe@17144
   539
    (Graph.all_preds (fst gr) [dep]))));
berghofe@12557
   540
berghofe@22271
   541
fun print_arities arities = message ("Arities:\n" ^
wenzelm@26931
   542
  cat_lines (map (fn (s, (ks, k)) => s ^ ": " ^
berghofe@12557
   543
    space_implode " -> " (map
berghofe@22271
   544
      (fn NONE => "X" | SOME k' => string_of_int k')
berghofe@22271
   545
        (ks @ [SOME k]))) arities));
berghofe@11537
   546
wenzelm@32957
   547
fun prep_intrs intrs = map (rename_term o #prop o rep_thm o Drule.standard) intrs;
berghofe@15031
   548
berghofe@15031
   549
fun constrain cs [] = []
wenzelm@33244
   550
  | constrain cs ((s, xs) :: ys) =
wenzelm@33244
   551
      (s,
wenzelm@33244
   552
        case AList.lookup (op =) cs (s : string) of
wenzelm@33244
   553
          NONE => xs
berghofe@33771
   554
        | SOME xs' => inter (op = o apfst fst) xs' xs) :: constrain cs ys;
berghofe@15031
   555
berghofe@17144
   556
fun mk_extra_defs thy defs gr dep names module ts =
wenzelm@33244
   557
  fold (fn name => fn gr =>
berghofe@12557
   558
    if name mem names then gr
wenzelm@33244
   559
    else
wenzelm@33244
   560
      (case get_clauses thy name of
skalberg@15531
   561
        NONE => gr
berghofe@22271
   562
      | SOME (names, thyname, nparms, intrs) =>
berghofe@17144
   563
          mk_ind_def thy defs gr dep names (if_library thyname module)
berghofe@22271
   564
            [] (prep_intrs intrs) nparms))
wenzelm@33244
   565
    (fold Term.add_const_names ts []) gr
berghofe@12557
   566
berghofe@22271
   567
and mk_ind_def thy defs gr dep names module modecs intrs nparms =
berghofe@24129
   568
  add_edge_acyclic (hd names, dep) gr handle
berghofe@24129
   569
    Graph.CYCLES (xs :: _) =>
berghofe@24129
   570
      error ("InductiveCodegen: illegal cyclic dependencies:\n" ^ commas xs)
berghofe@24129
   571
  | Graph.UNDEF _ =>
berghofe@11537
   572
    let
berghofe@22271
   573
      val _ $ u = Logic.strip_imp_concl (hd intrs);
berghofe@22271
   574
      val args = List.take (snd (strip_comb u), nparms);
wenzelm@32952
   575
      val arg_vs = maps term_vs args;
berghofe@15031
   576
berghofe@22271
   577
      fun get_nparms s = if s mem names then SOME nparms else
berghofe@22271
   578
        Option.map #3 (get_clauses thy s);
berghofe@11537
   579
berghofe@26806
   580
      fun dest_prem (_ $ (Const ("op :", _) $ t $ u)) = Prem ([t], Envir.beta_eta_contract u, true)
berghofe@26806
   581
        | dest_prem (_ $ ((eq as Const ("op =", _)) $ t $ u)) = Prem ([t, u], eq, false)
berghofe@22271
   582
        | dest_prem (_ $ t) =
berghofe@22271
   583
            (case strip_comb t of
berghofe@26806
   584
               (v as Var _, ts) => if v mem args then Prem (ts, v, false) else Sidecond t
berghofe@22271
   585
             | (c as Const (s, _), ts) => (case get_nparms s of
berghofe@22271
   586
                 NONE => Sidecond t
berghofe@22271
   587
               | SOME k =>
berghofe@22271
   588
                   let val (ts1, ts2) = chop k ts
berghofe@26806
   589
                   in Prem (ts2, list_comb (c, ts1), false) end)
berghofe@22271
   590
             | _ => Sidecond t);
berghofe@22271
   591
berghofe@22271
   592
      fun add_clause intr (clauses, arities) =
berghofe@11537
   593
        let
berghofe@22271
   594
          val _ $ t = Logic.strip_imp_concl intr;
berghofe@22271
   595
          val (Const (name, T), ts) = strip_comb t;
berghofe@22271
   596
          val (ts1, ts2) = chop nparms ts;
berghofe@22271
   597
          val prems = map dest_prem (Logic.strip_imp_prems intr);
berghofe@22271
   598
          val (Ts, Us) = chop nparms (binder_types T)
berghofe@11537
   599
        in
berghofe@22271
   600
          (AList.update op = (name, these (AList.lookup op = clauses name) @
berghofe@22271
   601
             [(ts2, prems)]) clauses,
berghofe@22271
   602
           AList.update op = (name, (map (fn U => (case strip_type U of
berghofe@22271
   603
                 (Rs as _ :: _, Type ("bool", [])) => SOME (length Rs)
berghofe@22271
   604
               | _ => NONE)) Ts,
berghofe@22271
   605
             length Us)) arities)
berghofe@11537
   606
        end;
berghofe@11537
   607
berghofe@16645
   608
      val gr' = mk_extra_defs thy defs
berghofe@17144
   609
        (add_edge (hd names, dep)
berghofe@17144
   610
          (new_node (hd names, (NONE, "", "")) gr)) (hd names) names module intrs;
berghofe@22271
   611
      val (extra_modes, extra_arities) = lookup_modes gr' (hd names);
berghofe@22271
   612
      val (clauses, arities) = fold add_clause intrs ([], []);
berghofe@15031
   613
      val modes = constrain modecs
berghofe@22271
   614
        (infer_modes thy extra_modes arities arg_vs clauses);
berghofe@22271
   615
      val _ = print_arities arities;
berghofe@11537
   616
      val _ = print_modes modes;
haftmann@28537
   617
      val (s, gr'') = compile_preds thy defs (hd names) module (terms_vs intrs)
haftmann@28537
   618
        arg_vs (modes @ extra_modes) clauses gr';
berghofe@11537
   619
    in
berghofe@17144
   620
      (map_node (hd names)
berghofe@22271
   621
        (K (SOME (Modes (modes, arities)), module, s)) gr'')
berghofe@16645
   622
    end;
berghofe@11537
   623
berghofe@22271
   624
fun find_mode gr dep s u modes is = (case find_first (fn Mode (_, js, _) => is=js)
wenzelm@15660
   625
  (modes_of modes u handle Option => []) of
berghofe@17144
   626
     NONE => codegen_error gr dep
berghofe@17144
   627
       ("No such mode for " ^ s ^ ": " ^ string_of_mode ([], is))
berghofe@15031
   628
   | mode => mode);
berghofe@15031
   629
haftmann@28537
   630
fun mk_ind_call thy defs dep module is_query s T ts names thyname k intrs gr =
berghofe@22271
   631
  let
berghofe@22271
   632
    val (ts1, ts2) = chop k ts;
berghofe@22271
   633
    val u = list_comb (Const (s, T), ts1);
berghofe@22271
   634
wenzelm@33244
   635
    fun mk_mode (Const ("dummy_pattern", _)) ((ts, mode), i) = ((ts, mode), i + 1)
wenzelm@33244
   636
      | mk_mode t ((ts, mode), i) = ((ts @ [t], mode @ [i]), i + 1);
berghofe@11537
   637
berghofe@22271
   638
    val module' = if_library thyname module;
berghofe@22271
   639
    val gr1 = mk_extra_defs thy defs
berghofe@22271
   640
      (mk_ind_def thy defs gr dep names module'
berghofe@22271
   641
      [] (prep_intrs intrs) k) dep names module' [u];
berghofe@22271
   642
    val (modes, _) = lookup_modes gr1 dep;
wenzelm@33244
   643
    val (ts', is) =
wenzelm@33244
   644
      if is_query then fst (fold mk_mode ts2 (([], []), 1))
berghofe@22271
   645
      else (ts2, 1 upto length (binder_types T) - k);
berghofe@22271
   646
    val mode = find_mode gr1 dep s u modes is;
berghofe@33771
   647
    val _ = if is_query orelse not (needs_random (the mode)) then ()
berghofe@33771
   648
      else warning ("Illegal use of random data generators in " ^ s);
haftmann@28537
   649
    val (in_ps, gr2) = fold_map (invoke_codegen thy defs dep module true) ts' gr1;
haftmann@28537
   650
    val (ps, gr3) = compile_expr thy defs dep module false modes (mode, u) gr2;
berghofe@22271
   651
  in
haftmann@28537
   652
    (Pretty.block (ps @ (if null in_ps then [] else [Pretty.brk 1]) @
haftmann@28537
   653
       separate (Pretty.brk 1) in_ps), gr3)
berghofe@22271
   654
  end;
berghofe@15031
   655
berghofe@15031
   656
fun clause_of_eqn eqn =
berghofe@15031
   657
  let
berghofe@15031
   658
    val (t, u) = HOLogic.dest_eq (HOLogic.dest_Trueprop (concl_of eqn));
berghofe@15031
   659
    val (Const (s, T), ts) = strip_comb t;
berghofe@15031
   660
    val (Ts, U) = strip_type T
berghofe@15031
   661
  in
berghofe@22271
   662
    rename_term (Logic.list_implies (prems_of eqn, HOLogic.mk_Trueprop
berghofe@22271
   663
      (list_comb (Const (s ^ "_aux", Ts @ [U] ---> HOLogic.boolT), ts @ [u]))))
berghofe@15031
   664
  end;
berghofe@15031
   665
berghofe@17144
   666
fun mk_fun thy defs name eqns dep module module' gr =
berghofe@17144
   667
  case try (get_node gr) name of
berghofe@17144
   668
    NONE =>
berghofe@15031
   669
    let
berghofe@15031
   670
      val clauses = map clause_of_eqn eqns;
berghofe@17144
   671
      val pname = name ^ "_aux";
berghofe@15031
   672
      val arity = length (snd (strip_comb (fst (HOLogic.dest_eq
berghofe@15031
   673
        (HOLogic.dest_Trueprop (concl_of (hd eqns)))))));
berghofe@15031
   674
      val mode = 1 upto arity;
haftmann@28537
   675
      val ((fun_id, mode_id), gr') = gr |>
haftmann@28537
   676
        mk_const_id module' name ||>>
berghofe@17144
   677
        modename module' pname ([], mode);
berghofe@26975
   678
      val vars = map (fn i => str ("x" ^ string_of_int i)) mode;
berghofe@26975
   679
      val s = string_of (Pretty.block
berghofe@26975
   680
        [mk_app false (str ("fun " ^ snd fun_id)) vars, str " =",
berghofe@26975
   681
         Pretty.brk 1, str "DSeq.hd", Pretty.brk 1,
berghofe@26975
   682
         parens (Pretty.block (separate (Pretty.brk 1) (str mode_id ::
berghofe@22271
   683
           vars)))]) ^ ";\n\n";
berghofe@17144
   684
      val gr'' = mk_ind_def thy defs (add_edge (name, dep)
berghofe@17144
   685
        (new_node (name, (NONE, module', s)) gr')) name [pname] module'
berghofe@22271
   686
        [(pname, [([], mode)])] clauses 0;
berghofe@17144
   687
      val (modes, _) = lookup_modes gr'' dep;
berghofe@22271
   688
      val _ = find_mode gr'' dep pname (head_of (HOLogic.dest_Trueprop
berghofe@22271
   689
        (Logic.strip_imp_concl (hd clauses)))) modes mode
haftmann@28537
   690
    in (mk_qual_id module fun_id, gr'') end
berghofe@17144
   691
  | SOME _ =>
haftmann@28537
   692
      (mk_qual_id module (get_const_id gr name), add_edge (name, dep) gr);
berghofe@15031
   693
berghofe@23761
   694
(* convert n-tuple to nested pairs *)
berghofe@23761
   695
berghofe@23761
   696
fun conv_ntuple fs ts p =
berghofe@23761
   697
  let
berghofe@23761
   698
    val k = length fs;
haftmann@33063
   699
    val xs = map_range (fn i => str ("x" ^ string_of_int i)) (k + 1);
berghofe@23761
   700
    val xs' = map (fn Bound i => nth xs (k - i)) ts;
berghofe@23761
   701
    fun conv xs js =
berghofe@23761
   702
      if js mem fs then
berghofe@23761
   703
        let
berghofe@23761
   704
          val (p, xs') = conv xs (1::js);
berghofe@23761
   705
          val (q, xs'') = conv xs' (2::js)
berghofe@23761
   706
        in (mk_tuple [p, q], xs'') end
berghofe@23761
   707
      else (hd xs, tl xs)
berghofe@23761
   708
  in
berghofe@23761
   709
    if k > 0 then
berghofe@23761
   710
      Pretty.block
berghofe@26975
   711
        [str "DSeq.map (fn", Pretty.brk 1,
berghofe@26975
   712
         mk_tuple xs', str " =>", Pretty.brk 1, fst (conv xs []),
berghofe@26975
   713
         str ")", Pretty.brk 1, parens p]
berghofe@23761
   714
    else p
berghofe@23761
   715
  end;
berghofe@23761
   716
haftmann@28537
   717
fun inductive_codegen thy defs dep module brack t gr  = (case strip_comb t of
berghofe@23761
   718
    (Const ("Collect", _), [u]) =>
haftmann@32342
   719
      let val (r, Ts, fs) = HOLogic.strip_psplits u
berghofe@23761
   720
      in case strip_comb r of
berghofe@23761
   721
          (Const (s, T), ts) =>
berghofe@23761
   722
            (case (get_clauses thy s, get_assoc_code thy (s, T)) of
berghofe@23761
   723
              (SOME (names, thyname, k, intrs), NONE) =>
berghofe@23761
   724
                let
berghofe@23761
   725
                  val (ts1, ts2) = chop k ts;
berghofe@23761
   726
                  val ts2' = map
haftmann@34962
   727
                    (fn Bound i => Term.dummy_pattern (nth Ts (length Ts - i - 1)) | t => t) ts2;
berghofe@23761
   728
                  val (ots, its) = List.partition is_Bound ts2;
berghofe@23761
   729
                  val no_loose = forall (fn t => not (loose_bvar (t, 0)))
berghofe@23761
   730
                in
berghofe@23761
   731
                  if null (duplicates op = ots) andalso
berghofe@23761
   732
                    no_loose ts1 andalso no_loose its
berghofe@23761
   733
                  then
haftmann@28537
   734
                    let val (call_p, gr') = mk_ind_call thy defs dep module true
haftmann@28537
   735
                      s T (ts1 @ ts2') names thyname k intrs gr 
haftmann@28537
   736
                    in SOME ((if brack then parens else I) (Pretty.block
haftmann@31852
   737
                      [str "Set", Pretty.brk 1, str "(DSeq.list_of", Pretty.brk 1, str "(",
haftmann@31852
   738
                       conv_ntuple fs ots call_p, str "))"]),
haftmann@31852
   739
                       (*this is a very strong assumption about the generated code!*)
haftmann@31852
   740
                       gr')
berghofe@23761
   741
                    end
berghofe@23761
   742
                  else NONE
berghofe@23761
   743
                end
berghofe@23761
   744
            | _ => NONE)
berghofe@23761
   745
        | _ => NONE
berghofe@23761
   746
      end
berghofe@22271
   747
  | (Const (s, T), ts) => (case Symtab.lookup (#eqns (CodegenData.get thy)) s of
haftmann@22921
   748
      NONE => (case (get_clauses thy s, get_assoc_code thy (s, T)) of
berghofe@22271
   749
        (SOME (names, thyname, k, intrs), NONE) =>
berghofe@22271
   750
          if length ts < k then NONE else SOME
haftmann@28537
   751
            (let val (call_p, gr') = mk_ind_call thy defs dep module false
haftmann@28537
   752
               s T (map Term.no_dummy_patterns ts) names thyname k intrs gr
haftmann@28537
   753
             in (mk_funcomp brack "?!"
haftmann@28537
   754
               (length (binder_types T) - length ts) (parens call_p), gr')
haftmann@28537
   755
             end handle TERM _ => mk_ind_call thy defs dep module true
haftmann@28537
   756
               s T ts names thyname k intrs gr )
berghofe@22271
   757
      | _ => NONE)
berghofe@22271
   758
    | SOME eqns =>
berghofe@22271
   759
        let
haftmann@22642
   760
          val (_, thyname) :: _ = eqns;
haftmann@28537
   761
          val (id, gr') = mk_fun thy defs s (preprocess thy (map fst (rev eqns)))
berghofe@22271
   762
            dep module (if_library thyname module) gr;
haftmann@28537
   763
          val (ps, gr'') = fold_map
haftmann@28537
   764
            (invoke_codegen thy defs dep module true) ts gr';
haftmann@28537
   765
        in SOME (mk_app brack (str id) ps, gr'')
berghofe@22271
   766
        end)
berghofe@22271
   767
  | _ => NONE);
berghofe@11537
   768
berghofe@12557
   769
val setup =
wenzelm@18708
   770
  add_codegen "inductive" inductive_codegen #>
wenzelm@33244
   771
  Attrib.setup @{binding code_ind}
wenzelm@33244
   772
    (Scan.lift (Scan.option (Args.$$$ "target" |-- Args.colon |-- Args.name) --
wenzelm@33244
   773
      Scan.option (Args.$$$ "params" |-- Args.colon |-- OuterParse.nat) >> uncurry add))
haftmann@31998
   774
    "introduction rules for executable predicates";
berghofe@11537
   775
berghofe@33771
   776
(**** Quickcheck involving inductive predicates ****)
berghofe@33771
   777
berghofe@33771
   778
val test_fn : (int * int * int -> term list option) Unsynchronized.ref =
berghofe@33771
   779
  Unsynchronized.ref (fn _ => NONE);
berghofe@33771
   780
berghofe@33771
   781
fun strip_imp p =
berghofe@33771
   782
  let val (q, r) = HOLogic.dest_imp p
berghofe@33771
   783
  in strip_imp r |>> cons q end
berghofe@33771
   784
  handle TERM _ => ([], p);
berghofe@33771
   785
berghofe@33771
   786
fun deepen bound f i =
berghofe@33771
   787
  if i > bound then NONE
berghofe@33771
   788
  else (case f i of
berghofe@33771
   789
      NONE => deepen bound f (i + 1)
berghofe@33771
   790
    | SOME x => SOME x);
berghofe@33771
   791
berghofe@33771
   792
val depth_bound_value =
berghofe@33771
   793
  Config.declare false "ind_quickcheck_depth" (Config.Int 10);
berghofe@33771
   794
val depth_bound = Config.int depth_bound_value;
berghofe@33771
   795
berghofe@33771
   796
val depth_start_value =
berghofe@33771
   797
  Config.declare false "ind_quickcheck_depth_start" (Config.Int 1);
berghofe@33771
   798
val depth_start = Config.int depth_start_value;
berghofe@33771
   799
berghofe@33771
   800
val random_values_value =
berghofe@33771
   801
  Config.declare false "ind_quickcheck_random" (Config.Int 5);
berghofe@33771
   802
val random_values = Config.int random_values_value;
berghofe@33771
   803
berghofe@33771
   804
val size_offset_value =
berghofe@33771
   805
  Config.declare false "ind_quickcheck_size_offset" (Config.Int 0);
berghofe@33771
   806
val size_offset = Config.int size_offset_value;
berghofe@33771
   807
berghofe@33771
   808
fun test_term ctxt t =
berghofe@33771
   809
  let
berghofe@33771
   810
    val thy = ProofContext.theory_of ctxt;
berghofe@33771
   811
    val (xs, p) = strip_abs t;
berghofe@33771
   812
    val args' = map_index (fn (i, (_, T)) => ("arg" ^ string_of_int i, T)) xs;
berghofe@33771
   813
    val args = map Free args';
berghofe@33771
   814
    val (ps, q) = strip_imp p;
berghofe@33771
   815
    val Ts = map snd xs;
berghofe@33771
   816
    val T = Ts ---> HOLogic.boolT;
berghofe@33771
   817
    val rl = Logic.list_implies
berghofe@33771
   818
      (map (HOLogic.mk_Trueprop o curry subst_bounds (rev args)) ps @
berghofe@33771
   819
       [HOLogic.mk_Trueprop (HOLogic.mk_not (subst_bounds (rev args, q)))],
berghofe@33771
   820
       HOLogic.mk_Trueprop (list_comb (Free ("quickcheckp", T), args)));
berghofe@33771
   821
    val (_, thy') = Inductive.add_inductive_global
berghofe@33771
   822
      {quiet_mode=true, verbose=false, alt_name=Binding.empty, coind=false,
berghofe@33771
   823
       no_elim=true, no_ind=false, skip_mono=false, fork_mono=false}
berghofe@33771
   824
      [((Binding.name "quickcheckp", T), NoSyn)] []
berghofe@33771
   825
      [(Attrib.empty_binding, rl)] [] (Theory.copy thy);
berghofe@33771
   826
    val pred = HOLogic.mk_Trueprop (list_comb
berghofe@33771
   827
      (Const (Sign.intern_const thy' "quickcheckp", T),
berghofe@33771
   828
       map Term.dummy_pattern Ts));
berghofe@33771
   829
    val (code, gr) = setmp_CRITICAL mode ["term_of", "test", "random_ind"]
berghofe@33771
   830
      (generate_code_i thy' [] "Generated") [("testf", pred)];
berghofe@33771
   831
    val s = "structure TestTerm =\nstruct\n\n" ^
berghofe@33771
   832
      cat_lines (map snd code) ^
berghofe@33771
   833
      "\nopen Generated;\n\n" ^ string_of
berghofe@33771
   834
        (Pretty.block [str "val () = InductiveCodegen.test_fn :=",
berghofe@33771
   835
          Pretty.brk 1, str "(fn p =>", Pretty.brk 1,
berghofe@33771
   836
          str "case Seq.pull (testf p) of", Pretty.brk 1,
berghofe@33771
   837
          str "SOME ", mk_tuple [mk_tuple (map (str o fst) args'), str "_"],
berghofe@33771
   838
          str " =>", Pretty.brk 1, str "SOME ",
berghofe@33771
   839
          Pretty.block (str "[" ::
berghofe@33771
   840
            Pretty.commas (map (fn (s, T) => Pretty.block
berghofe@33771
   841
              [mk_term_of gr "Generated" false T, Pretty.brk 1, str s]) args') @
berghofe@33771
   842
            [str "]"]), Pretty.brk 1,
berghofe@33771
   843
          str "| NONE => NONE);"]) ^
berghofe@33771
   844
      "\n\nend;\n";
berghofe@33771
   845
    val _ = ML_Context.eval_in (SOME ctxt) false Position.none s;
berghofe@33771
   846
    val values = Config.get ctxt random_values;
berghofe@33771
   847
    val bound = Config.get ctxt depth_bound;
berghofe@33771
   848
    val start = Config.get ctxt depth_start;
berghofe@33771
   849
    val offset = Config.get ctxt size_offset;
berghofe@33771
   850
    val test_fn' = !test_fn;
berghofe@33771
   851
    fun test k = deepen bound (fn i =>
berghofe@33771
   852
      (priority ("Search depth: " ^ string_of_int i);
berghofe@33771
   853
       test_fn' (i, values, k+offset))) start;
berghofe@33771
   854
  in test end;
berghofe@33771
   855
berghofe@33771
   856
val quickcheck_setup =
berghofe@33771
   857
  Attrib.register_config depth_bound_value #>
berghofe@33771
   858
  Attrib.register_config depth_start_value #>
berghofe@33771
   859
  Attrib.register_config random_values_value #>
berghofe@33771
   860
  Attrib.register_config size_offset_value #>
berghofe@33771
   861
  Quickcheck.add_generator ("SML_inductive", test_term);
berghofe@33771
   862
berghofe@11537
   863
end;