src/HOL/Tools/Datatype/datatype_case.ML
author wenzelm
Sat Apr 16 15:25:25 2011 +0200 (2011-04-16)
changeset 42359 6ca5407863ed
parent 42290 b1f544c84040
child 42361 23f352990944
permissions -rw-r--r--
prefer local name spaces;
tuned signatures;
tuned;
haftmann@33968
     1
(*  Title:      HOL/Tools/Datatype/datatype_case.ML
berghofe@22779
     2
    Author:     Konrad Slind, Cambridge University Computer Laboratory
wenzelm@29266
     3
    Author:     Stefan Berghofer, TU Muenchen
berghofe@22779
     4
haftmann@33968
     5
Datatype package: nested case expressions on datatypes.
berghofe@22779
     6
*)
berghofe@22779
     7
berghofe@22779
     8
signature DATATYPE_CASE =
berghofe@22779
     9
sig
haftmann@33968
    10
  datatype config = Error | Warning | Quiet
haftmann@33968
    11
  type info = Datatype_Aux.info
haftmann@33968
    12
  val make_case: (string * typ -> info option) ->
bulwahn@32671
    13
    Proof.context -> config -> string list -> term -> (term * term) list ->
berghofe@22779
    14
    term * (term * (int * bool)) list
haftmann@33968
    15
  val dest_case: (string -> info option) -> bool ->
berghofe@22779
    16
    string list -> term -> (term * (term * term) list) option
haftmann@33968
    17
  val strip_case: (string -> info option) -> bool ->
berghofe@22779
    18
    term -> (term * (term * term) list) option
haftmann@33968
    19
  val case_tr: bool -> (theory -> string * typ -> info option) ->
haftmann@33968
    20
    Proof.context -> term list -> term
haftmann@33968
    21
  val case_tr': (theory -> string -> info option) ->
berghofe@22779
    22
    string -> Proof.context -> term list -> term
berghofe@22779
    23
end;
berghofe@22779
    24
haftmann@33968
    25
structure Datatype_Case : DATATYPE_CASE =
berghofe@22779
    26
struct
berghofe@22779
    27
bulwahn@32671
    28
datatype config = Error | Warning | Quiet;
haftmann@33968
    29
type info = Datatype_Aux.info;
bulwahn@32671
    30
berghofe@22779
    31
exception CASE_ERROR of string * int;
berghofe@22779
    32
berghofe@22779
    33
fun match_type thy pat ob = Sign.typ_match thy (pat, ob) Vartab.empty;
berghofe@22779
    34
berghofe@22779
    35
(*---------------------------------------------------------------------------
berghofe@22779
    36
 * Get information about datatypes
berghofe@22779
    37
 *---------------------------------------------------------------------------*)
berghofe@22779
    38
haftmann@32896
    39
fun ty_info tab sT =
wenzelm@42049
    40
  (case tab sT of
haftmann@33968
    41
    SOME ({descr, case_name, index, sorts, ...} : info) =>
berghofe@22779
    42
      let
berghofe@22779
    43
        val (_, (tname, dts, constrs)) = nth descr index;
haftmann@33968
    44
        val mk_ty = Datatype_Aux.typ_of_dtyp descr sorts;
wenzelm@35124
    45
        val T = Type (tname, map mk_ty dts);
berghofe@22779
    46
      in
berghofe@22779
    47
        SOME {case_name = case_name,
berghofe@22779
    48
          constructors = map (fn (cname, dts') =>
wenzelm@35845
    49
            Const (cname, Logic.varifyT_global (map mk_ty dts' ---> T))) constrs}
berghofe@22779
    50
      end
wenzelm@42049
    51
  | NONE => NONE);
berghofe@22779
    52
berghofe@22779
    53
berghofe@22779
    54
(*---------------------------------------------------------------------------
berghofe@22779
    55
 * Each pattern carries with it a tag (i,b) where
berghofe@22779
    56
 * i is the clause it came from and
berghofe@22779
    57
 * b=true indicates that clause was given by the user
berghofe@22779
    58
 * (or is an instantiation of a user supplied pattern)
berghofe@22779
    59
 * b=false --> i = ~1
berghofe@22779
    60
 *---------------------------------------------------------------------------*)
berghofe@22779
    61
wenzelm@29281
    62
fun pattern_subst theta (tm, x) = (subst_free theta tm, x);
berghofe@22779
    63
berghofe@22779
    64
fun row_of_pat x = fst (snd x);
berghofe@22779
    65
wenzelm@29281
    66
fun add_row_used ((prfx, pats), (tm, tag)) =
wenzelm@29281
    67
  fold Term.add_free_names (tm :: pats @ prfx);
berghofe@22779
    68
berghofe@22779
    69
(* try to preserve names given by user *)
berghofe@22779
    70
fun default_names names ts =
berghofe@22779
    71
  map (fn ("", Free (name', _)) => name' | (name, _) => name) (names ~~ ts);
berghofe@22779
    72
wenzelm@35124
    73
fun strip_constraints (Const (@{syntax_const "_constrain"}, _) $ t $ tT) =
berghofe@22779
    74
      strip_constraints t ||> cons tT
berghofe@22779
    75
  | strip_constraints t = (t, []);
berghofe@22779
    76
wenzelm@35124
    77
fun mk_fun_constrain tT t =
wenzelm@35124
    78
  Syntax.const @{syntax_const "_constrain"} $ t $
wenzelm@35363
    79
    (Syntax.const @{type_syntax fun} $ tT $ Syntax.const @{type_syntax dummy});
berghofe@22779
    80
berghofe@22779
    81
berghofe@22779
    82
(*---------------------------------------------------------------------------
berghofe@22779
    83
 * Produce an instance of a constructor, plus genvars for its arguments.
berghofe@22779
    84
 *---------------------------------------------------------------------------*)
berghofe@22779
    85
fun fresh_constr ty_match ty_inst colty used c =
berghofe@22779
    86
  let
berghofe@22779
    87
    val (_, Ty) = dest_Const c
berghofe@22779
    88
    val Ts = binder_types Ty;
berghofe@22779
    89
    val names = Name.variant_list used
wenzelm@35845
    90
      (Datatype_Prop.make_tnames (map Logic.unvarifyT_global Ts));
berghofe@22779
    91
    val ty = body_type Ty;
berghofe@22779
    92
    val ty_theta = ty_match ty colty handle Type.TYPE_MATCH =>
berghofe@22779
    93
      raise CASE_ERROR ("type mismatch", ~1)
berghofe@22779
    94
    val c' = ty_inst ty_theta c
berghofe@22779
    95
    val gvars = map (ty_inst ty_theta o Free) (names ~~ Ts)
wenzelm@42049
    96
  in (c', gvars) end;
berghofe@22779
    97
berghofe@22779
    98
berghofe@22779
    99
(*---------------------------------------------------------------------------
berghofe@22779
   100
 * Goes through a list of rows and picks out the ones beginning with a
berghofe@22779
   101
 * pattern with constructor = name.
berghofe@22779
   102
 *---------------------------------------------------------------------------*)
berghofe@22779
   103
fun mk_group (name, T) rows =
wenzelm@42049
   104
  let val k = length (binder_types T) in
wenzelm@42049
   105
    fold (fn (row as ((prfx, p :: rst), rhs as (_, (i, _)))) =>
wenzelm@42049
   106
      fn ((in_group, not_in_group), (names, cnstrts)) =>
wenzelm@42049
   107
        (case strip_comb p of
wenzelm@42049
   108
          (Const (name', _), args) =>
wenzelm@42049
   109
            if name = name' then
wenzelm@42049
   110
              if length args = k then
wenzelm@42049
   111
                let val (args', cnstrts') = split_list (map strip_constraints args)
wenzelm@42049
   112
                in
wenzelm@42049
   113
                  ((((prfx, args' @ rst), rhs) :: in_group, not_in_group),
wenzelm@42049
   114
                   (default_names names args', map2 append cnstrts cnstrts'))
wenzelm@42049
   115
                end
wenzelm@42049
   116
              else raise CASE_ERROR
wenzelm@42049
   117
                ("Wrong number of arguments for constructor " ^ name, i)
wenzelm@42049
   118
            else ((in_group, row :: not_in_group), (names, cnstrts))
wenzelm@42049
   119
        | _ => raise CASE_ERROR ("Not a constructor pattern", i)))
berghofe@22779
   120
    rows (([], []), (replicate k "", replicate k [])) |>> pairself rev
berghofe@22779
   121
  end;
berghofe@22779
   122
berghofe@22779
   123
(*---------------------------------------------------------------------------
berghofe@22779
   124
 * Partition the rows. Not efficient: we should use hashing.
berghofe@22779
   125
 *---------------------------------------------------------------------------*)
berghofe@22779
   126
fun partition _ _ _ _ _ _ _ [] = raise CASE_ERROR ("partition: no rows", ~1)
berghofe@22779
   127
  | partition ty_match ty_inst type_of used constructors colty res_ty
berghofe@22779
   128
        (rows as (((prfx, _ :: rstp), _) :: _)) =
berghofe@22779
   129
      let
berghofe@22779
   130
        fun part {constrs = [], rows = [], A} = rev A
berghofe@22779
   131
          | part {constrs = [], rows = (_, (_, (i, _))) :: _, A} =
berghofe@22779
   132
              raise CASE_ERROR ("Not a constructor pattern", i)
berghofe@22779
   133
          | part {constrs = c :: crst, rows, A} =
berghofe@22779
   134
              let
berghofe@22779
   135
                val ((in_group, not_in_group), (names, cnstrts)) =
berghofe@22779
   136
                  mk_group (dest_Const c) rows;
berghofe@22779
   137
                val used' = fold add_row_used in_group used;
berghofe@22779
   138
                val (c', gvars) = fresh_constr ty_match ty_inst colty used' c;
berghofe@22779
   139
                val in_group' =
berghofe@22779
   140
                  if null in_group  (* Constructor not given *)
berghofe@22779
   141
                  then
berghofe@22779
   142
                    let
berghofe@22779
   143
                      val Ts = map type_of rstp;
berghofe@22779
   144
                      val xs = Name.variant_list
wenzelm@29281
   145
                        (fold Term.add_free_names gvars used')
berghofe@22779
   146
                        (replicate (length rstp) "x")
berghofe@22779
   147
                    in
berghofe@22779
   148
                      [((prfx, gvars @ map Free (xs ~~ Ts)),
wenzelm@35140
   149
                        (Const (@{const_syntax undefined}, res_ty), (~1, false)))]
berghofe@22779
   150
                    end
berghofe@22779
   151
                  else in_group
berghofe@22779
   152
              in
berghofe@22779
   153
                part{constrs = crst,
berghofe@22779
   154
                  rows = not_in_group,
berghofe@22779
   155
                  A = {constructor = c',
berghofe@22779
   156
                    new_formals = gvars,
berghofe@22779
   157
                    names = names,
berghofe@22779
   158
                    constraints = cnstrts,
berghofe@22779
   159
                    group = in_group'} :: A}
berghofe@22779
   160
              end
wenzelm@42049
   161
      in part {constrs = constructors, rows = rows, A = []} end;
berghofe@22779
   162
berghofe@22779
   163
(*---------------------------------------------------------------------------
berghofe@22779
   164
 * Misc. routines used in mk_case
berghofe@22779
   165
 *---------------------------------------------------------------------------*)
berghofe@22779
   166
berghofe@22779
   167
fun mk_pat ((c, c'), l) =
berghofe@22779
   168
  let
berghofe@22779
   169
    val L = length (binder_types (fastype_of c))
berghofe@22779
   170
    fun build (prfx, tag, plist) =
berghofe@22779
   171
      let val (args, plist') = chop L plist
berghofe@22779
   172
      in (prfx, tag, list_comb (c', args) :: plist') end
berghofe@22779
   173
  in map build l end;
berghofe@22779
   174
berghofe@22779
   175
fun v_to_prfx (prfx, v::pats) = (v::prfx,pats)
berghofe@22779
   176
  | v_to_prfx _ = raise CASE_ERROR ("mk_case: v_to_prfx", ~1);
berghofe@22779
   177
berghofe@22779
   178
fun v_to_pats (v::prfx,tag, pats) = (prfx, tag, v::pats)
berghofe@22779
   179
  | v_to_pats _ = raise CASE_ERROR ("mk_case: v_to_pats", ~1);
berghofe@22779
   180
berghofe@22779
   181
berghofe@22779
   182
(*----------------------------------------------------------------------------
berghofe@22779
   183
 * Translation of pattern terms into nested case expressions.
berghofe@22779
   184
 *
berghofe@22779
   185
 * This performs the translation and also builds the full set of patterns.
berghofe@22779
   186
 * Thus it supports the construction of induction theorems even when an
berghofe@22779
   187
 * incomplete set of patterns is given.
berghofe@22779
   188
 *---------------------------------------------------------------------------*)
berghofe@22779
   189
berghofe@22779
   190
fun mk_case tab ctxt ty_match ty_inst type_of used range_ty =
berghofe@22779
   191
  let
berghofe@22779
   192
    val name = Name.variant used "a";
berghofe@22779
   193
    fun expand constructors used ty ((_, []), _) =
berghofe@22779
   194
          raise CASE_ERROR ("mk_case: expand_var_row", ~1)
berghofe@22779
   195
      | expand constructors used ty (row as ((prfx, p :: rst), rhs)) =
berghofe@22779
   196
          if is_Free p then
berghofe@22779
   197
            let
berghofe@22779
   198
              val used' = add_row_used row used;
berghofe@22779
   199
              fun expnd c =
berghofe@22779
   200
                let val capp =
berghofe@22779
   201
                  list_comb (fresh_constr ty_match ty_inst ty used' c)
berghofe@22779
   202
                in ((prfx, capp :: rst), pattern_subst [(p, capp)] rhs)
berghofe@22779
   203
                end
berghofe@22779
   204
            in map expnd constructors end
berghofe@22779
   205
          else [row]
berghofe@22779
   206
    fun mk {rows = [], ...} = raise CASE_ERROR ("no rows", ~1)
berghofe@22779
   207
      | mk {path = [], rows = ((prfx, []), (tm, tag)) :: _} =  (* Done *)
berghofe@22779
   208
          ([(prfx, tag, [])], tm)
berghofe@22779
   209
      | mk {path, rows as ((row as ((_, [Free _]), _)) :: _ :: _)} =
berghofe@22779
   210
          mk {path = path, rows = [row]}
berghofe@22779
   211
      | mk {path = u :: rstp, rows as ((_, _ :: _), _) :: _} =
wenzelm@42049
   212
          let val col0 = map (fn ((_, p :: _), (_, (i, _))) => (p, i)) rows in
wenzelm@42049
   213
            (case Option.map (apfst head_of) (find_first (not o is_Free o fst) col0) of
berghofe@22779
   214
              NONE =>
berghofe@22779
   215
                let
berghofe@22779
   216
                  val rows' = map (fn ((v, _), row) => row ||>
berghofe@22779
   217
                    pattern_subst [(v, u)] |>> v_to_prfx) (col0 ~~ rows);
berghofe@22779
   218
                  val (pref_patl, tm) = mk {path = rstp, rows = rows'}
berghofe@22779
   219
                in (map v_to_pats pref_patl, tm) end
wenzelm@42049
   220
            | SOME (Const (cname, cT), i) =>
wenzelm@42049
   221
                (case ty_info tab (cname, cT) of
wenzelm@42049
   222
                  NONE => raise CASE_ERROR ("Not a datatype constructor: " ^ cname, i)
wenzelm@42049
   223
                | SOME {case_name, constructors} =>
wenzelm@42049
   224
                  let
wenzelm@42049
   225
                    val pty = body_type cT;
wenzelm@42049
   226
                    val used' = fold Term.add_free_names rstp used;
wenzelm@42049
   227
                    val nrows = maps (expand constructors used' pty) rows;
wenzelm@42049
   228
                    val subproblems = partition ty_match ty_inst type_of used'
wenzelm@42049
   229
                      constructors pty range_ty nrows;
wenzelm@42049
   230
                    val constructors' = map #constructor subproblems
wenzelm@42049
   231
                    val news = map (fn {new_formals, group, ...} =>
wenzelm@42049
   232
                      {path = new_formals @ rstp, rows = group}) subproblems;
wenzelm@42049
   233
                    val (pat_rect, dtrees) = split_list (map mk news);
wenzelm@42049
   234
                    val case_functions = map2
wenzelm@42049
   235
                      (fn {new_formals, names, constraints, ...} =>
wenzelm@42049
   236
                         fold_rev (fn ((x as Free (_, T), s), cnstrts) => fn t =>
wenzelm@42049
   237
                           Abs (if s = "" then name else s, T,
wenzelm@42049
   238
                             abstract_over (x, t)) |>
wenzelm@42049
   239
                           fold mk_fun_constrain cnstrts)
wenzelm@42049
   240
                             (new_formals ~~ names ~~ constraints))
wenzelm@42049
   241
                      subproblems dtrees;
wenzelm@42049
   242
                    val types = map type_of (case_functions @ [u]);
wenzelm@42049
   243
                    val case_const = Const (case_name, types ---> range_ty)
wenzelm@42049
   244
                    val tree = list_comb (case_const, case_functions @ [u])
wenzelm@42049
   245
                    val pat_rect1 = maps mk_pat (constructors ~~ constructors' ~~ pat_rect)
wenzelm@42049
   246
                  in (pat_rect1, tree) end)
berghofe@22779
   247
            | SOME (t, i) => raise CASE_ERROR ("Not a datatype constructor: " ^
wenzelm@42049
   248
                Syntax.string_of_term ctxt t, i))
berghofe@22779
   249
          end
berghofe@22779
   250
      | mk _ = raise CASE_ERROR ("Malformed row matrix", ~1)
wenzelm@42049
   251
  in mk end;
berghofe@22779
   252
berghofe@22779
   253
fun case_error s = error ("Error in case expression:\n" ^ s);
berghofe@22779
   254
berghofe@22779
   255
(* Repeated variable occurrences in a pattern are not allowed. *)
berghofe@22779
   256
fun no_repeat_vars ctxt pat = fold_aterms
berghofe@22779
   257
  (fn x as Free (s, _) => (fn xs =>
berghofe@22779
   258
        if member op aconv xs x then
berghofe@22779
   259
          case_error (quote s ^ " occurs repeatedly in the pattern " ^
wenzelm@24920
   260
            quote (Syntax.string_of_term ctxt pat))
berghofe@22779
   261
        else x :: xs)
berghofe@22779
   262
    | _ => I) pat [];
berghofe@22779
   263
bulwahn@32671
   264
fun gen_make_case ty_match ty_inst type_of tab ctxt config used x clauses =
berghofe@22779
   265
  let
wenzelm@35124
   266
    fun string_of_clause (pat, rhs) =
wenzelm@35124
   267
      Syntax.string_of_term ctxt (Syntax.const @{syntax_const "_case1"} $ pat $ rhs);
berghofe@22779
   268
    val _ = map (no_repeat_vars ctxt o fst) clauses;
berghofe@22779
   269
    val rows = map_index (fn (i, (pat, rhs)) =>
berghofe@22779
   270
      (([], [pat]), (rhs, (i, true)))) clauses;
wenzelm@35124
   271
    val rangeT =
wenzelm@35124
   272
      (case distinct op = (map (type_of o snd) clauses) of
berghofe@22779
   273
        [] => case_error "no clauses given"
berghofe@22779
   274
      | [T] => T
berghofe@22779
   275
      | _ => case_error "all cases must have the same result type");
berghofe@22779
   276
    val used' = fold add_row_used rows used;
berghofe@22779
   277
    val (patts, case_tm) = mk_case tab ctxt ty_match ty_inst type_of
berghofe@22779
   278
        used' rangeT {path = [x], rows = rows}
berghofe@22779
   279
      handle CASE_ERROR (msg, i) => case_error (msg ^
berghofe@22779
   280
        (if i < 0 then ""
berghofe@22779
   281
         else "\nIn clause\n" ^ string_of_clause (nth clauses i)));
berghofe@22779
   282
    val patts1 = map
berghofe@22779
   283
      (fn (_, tag, [pat]) => (pat, tag)
berghofe@22779
   284
        | _ => case_error "error in pattern-match translation") patts;
wenzelm@35124
   285
    val patts2 = Library.sort (int_ord o pairself row_of_pat) patts1
berghofe@22779
   286
    val finals = map row_of_pat patts2
berghofe@22779
   287
    val originals = map (row_of_pat o #2) rows
wenzelm@35124
   288
    val _ =
wenzelm@42049
   289
      (case subtract (op =) finals originals of
wenzelm@42049
   290
        [] => ()
wenzelm@42049
   291
      | is =>
wenzelm@42049
   292
          (case config of Error => case_error | Warning => warning | Quiet => fn _ => {})
wenzelm@42049
   293
            ("The following clauses are redundant (covered by preceding clauses):\n" ^
wenzelm@42049
   294
             cat_lines (map (string_of_clause o nth clauses) is)));
berghofe@22779
   295
  in
berghofe@22779
   296
    (case_tm, patts2)
berghofe@22779
   297
  end;
berghofe@22779
   298
berghofe@22779
   299
fun make_case tab ctxt = gen_make_case
wenzelm@32035
   300
  (match_type (ProofContext.theory_of ctxt)) Envir.subst_term_types fastype_of tab ctxt;
berghofe@22779
   301
val make_case_untyped = gen_make_case (K (K Vartab.empty))
berghofe@22779
   302
  (K (Term.map_types (K dummyT))) (K dummyT);
berghofe@22779
   303
berghofe@22779
   304
berghofe@22779
   305
(* parse translation *)
berghofe@22779
   306
nipkow@24349
   307
fun case_tr err tab_of ctxt [t, u] =
wenzelm@42049
   308
      let
wenzelm@42049
   309
        val thy = ProofContext.theory_of ctxt;
wenzelm@42359
   310
        val intern_const_syntax = Consts.intern_syntax (ProofContext.consts_of ctxt);
wenzelm@35256
   311
wenzelm@42049
   312
        (* replace occurrences of dummy_pattern by distinct variables *)
wenzelm@42049
   313
        (* internalize constant names                                 *)
wenzelm@42049
   314
        fun prep_pat ((c as Const (@{syntax_const "_constrain"}, _)) $ t $ tT) used =
wenzelm@42049
   315
              let val (t', used') = prep_pat t used
wenzelm@42049
   316
              in (c $ t' $ tT, used') end
wenzelm@42049
   317
          | prep_pat (Const (@{const_syntax dummy_pattern}, T)) used =
wenzelm@42049
   318
              let val x = Name.variant used "x"
wenzelm@42049
   319
              in (Free (x, T), x :: used) end
wenzelm@42049
   320
          | prep_pat (Const (s, T)) used =
wenzelm@42049
   321
              (Const (intern_const_syntax s, T), used)
wenzelm@42049
   322
          | prep_pat (v as Free (s, T)) used =
wenzelm@42359
   323
              let val s' = ProofContext.intern_const ctxt s in
wenzelm@42049
   324
                if Sign.declared_const thy s' then
wenzelm@42049
   325
                  (Const (s', T), used)
wenzelm@42049
   326
                else (v, used)
wenzelm@42049
   327
              end
wenzelm@42049
   328
          | prep_pat (t $ u) used =
wenzelm@42049
   329
              let
wenzelm@42049
   330
                val (t', used') = prep_pat t used;
wenzelm@42359
   331
                val (u', used'') = prep_pat u used';
wenzelm@42049
   332
              in
wenzelm@42049
   333
                (t' $ u', used'')
wenzelm@42049
   334
              end
wenzelm@42049
   335
          | prep_pat t used = case_error ("Bad pattern: " ^ Syntax.string_of_term ctxt t);
wenzelm@42049
   336
        fun dest_case1 (t as Const (@{syntax_const "_case1"}, _) $ l $ r) =
wenzelm@42049
   337
              let val (l', cnstrts) = strip_constraints l
wenzelm@42049
   338
              in ((fst (prep_pat l' (Term.add_free_names t [])), r), cnstrts) end
wenzelm@42049
   339
          | dest_case1 t = case_error "dest_case1";
wenzelm@42049
   340
        fun dest_case2 (Const (@{syntax_const "_case2"}, _) $ t $ u) = t :: dest_case2 u
wenzelm@42049
   341
          | dest_case2 t = [t];
wenzelm@42057
   342
        val (cases, cnstrts) = split_list (map dest_case1 (dest_case2 u));
wenzelm@42049
   343
        val (case_tm, _) = make_case_untyped (tab_of thy) ctxt
wenzelm@42049
   344
          (if err then Error else Warning) []
wenzelm@42049
   345
          (fold (fn tT => fn t => Syntax.const @{syntax_const "_constrain"} $ t $ tT)
wenzelm@42049
   346
             (flat cnstrts) t) cases;
wenzelm@42049
   347
      in case_tm end
nipkow@24349
   348
  | case_tr _ _ _ ts = case_error "case_tr";
berghofe@22779
   349
berghofe@22779
   350
berghofe@22779
   351
(*---------------------------------------------------------------------------
berghofe@22779
   352
 * Pretty printing of nested case expressions
berghofe@22779
   353
 *---------------------------------------------------------------------------*)
berghofe@22779
   354
berghofe@22779
   355
(* destruct one level of pattern matching *)
berghofe@22779
   356
berghofe@22779
   357
fun gen_dest_case name_of type_of tab d used t =
wenzelm@42049
   358
  (case apfst name_of (strip_comb t) of
berghofe@22779
   359
    (SOME cname, ts as _ :: _) =>
berghofe@22779
   360
      let
berghofe@22779
   361
        val (fs, x) = split_last ts;
berghofe@22779
   362
        fun strip_abs i t =
berghofe@22779
   363
          let
berghofe@22779
   364
            val zs = strip_abs_vars t;
berghofe@22779
   365
            val _ = if length zs < i then raise CASE_ERROR ("", 0) else ();
berghofe@22779
   366
            val (xs, ys) = chop i zs;
berghofe@22779
   367
            val u = list_abs (ys, strip_abs_body t);
wenzelm@29270
   368
            val xs' = map Free (Name.variant_list (OldTerm.add_term_names (u, used))
berghofe@22779
   369
              (map fst xs) ~~ map snd xs)
berghofe@22779
   370
          in (xs', subst_bounds (rev xs', u)) end;
berghofe@22779
   371
        fun is_dependent i t =
berghofe@22779
   372
          let val k = length (strip_abs_vars t) - i
wenzelm@42049
   373
          in k < 0 orelse exists (fn j => j >= k) (loose_bnos (strip_abs_body t)) end;
berghofe@22779
   374
        fun count_cases (_, _, true) = I
berghofe@22779
   375
          | count_cases (c, (_, body), false) =
berghofe@22779
   376
              AList.map_default op aconv (body, []) (cons c);
wenzelm@35392
   377
        val is_undefined = name_of #> equal (SOME @{const_name undefined});
berghofe@22779
   378
        fun mk_case (c, (xs, body), _) = (list_comb (c, xs), body)
wenzelm@42049
   379
      in
wenzelm@42049
   380
        (case ty_info tab cname of
berghofe@22779
   381
          SOME {constructors, case_name} =>
berghofe@22779
   382
            if length fs = length constructors then
berghofe@22779
   383
              let
berghofe@22779
   384
                val cases = map (fn (Const (s, U), t) =>
berghofe@22779
   385
                  let
berghofe@22779
   386
                    val k = length (binder_types U);
berghofe@22779
   387
                    val p as (xs, _) = strip_abs k t
berghofe@22779
   388
                  in
berghofe@22779
   389
                    (Const (s, map type_of xs ---> type_of x),
berghofe@22779
   390
                     p, is_dependent k t)
berghofe@22779
   391
                  end) (constructors ~~ fs);
berghofe@22779
   392
                val cases' = sort (int_ord o swap o pairself (length o snd))
berghofe@22779
   393
                  (fold_rev count_cases cases []);
berghofe@22779
   394
                val R = type_of t;
wenzelm@35124
   395
                val dummy =
wenzelm@35392
   396
                  if d then Const (@{const_name dummy_pattern}, R)
wenzelm@42049
   397
                  else Free (Name.variant used "x", R);
berghofe@22779
   398
              in
wenzelm@42049
   399
                SOME (x,
wenzelm@42049
   400
                  map mk_case
wenzelm@42049
   401
                    (case find_first (is_undefined o fst) cases' of
wenzelm@42049
   402
                      SOME (_, cs) =>
wenzelm@42049
   403
                      if length cs = length constructors then [hd cases]
wenzelm@42049
   404
                      else filter_out (fn (_, (_, body), _) => is_undefined body) cases
wenzelm@42049
   405
                    | NONE => case cases' of
wenzelm@42049
   406
                      [] => cases
wenzelm@42049
   407
                    | (default, cs) :: _ =>
wenzelm@42049
   408
                      if length cs = 1 then cases
wenzelm@42049
   409
                      else if length cs = length constructors then
wenzelm@42049
   410
                        [hd cases, (dummy, ([], default), false)]
wenzelm@42049
   411
                      else
wenzelm@42049
   412
                        filter_out (fn (c, _, _) => member op aconv cs c) cases @
wenzelm@42049
   413
                        [(dummy, ([], default), false)]))
berghofe@22779
   414
              end handle CASE_ERROR _ => NONE
berghofe@22779
   415
            else NONE
wenzelm@42049
   416
        | _ => NONE)
berghofe@22779
   417
      end
wenzelm@42049
   418
  | _ => NONE);
berghofe@22779
   419
berghofe@22779
   420
val dest_case = gen_dest_case (try (dest_Const #> fst)) fastype_of;
wenzelm@42290
   421
val dest_case' = gen_dest_case (try (dest_Const #> fst #> Lexicon.unmark_const)) (K dummyT);
berghofe@22779
   422
berghofe@22779
   423
berghofe@22779
   424
(* destruct nested patterns *)
berghofe@22779
   425
haftmann@29623
   426
fun strip_case'' dest (pat, rhs) =
wenzelm@42049
   427
  (case dest (Term.add_free_names pat []) rhs of
berghofe@22779
   428
    SOME (exp as Free _, clauses) =>
wenzelm@29266
   429
      if member op aconv (OldTerm.term_frees pat) exp andalso
berghofe@22779
   430
        not (exists (fn (_, rhs') =>
wenzelm@29266
   431
          member op aconv (OldTerm.term_frees rhs') exp) clauses)
berghofe@22779
   432
      then
haftmann@29623
   433
        maps (strip_case'' dest) (map (fn (pat', rhs') =>
berghofe@22779
   434
          (subst_free [(exp, pat')] pat, rhs')) clauses)
berghofe@22779
   435
      else [(pat, rhs)]
wenzelm@42049
   436
  | _ => [(pat, rhs)]);
berghofe@22779
   437
wenzelm@35124
   438
fun gen_strip_case dest t =
wenzelm@42049
   439
  (case dest [] t of
berghofe@22779
   440
    SOME (x, clauses) =>
haftmann@29623
   441
      SOME (x, maps (strip_case'' dest) clauses)
wenzelm@42049
   442
  | NONE => NONE);
berghofe@22779
   443
berghofe@22779
   444
val strip_case = gen_strip_case oo dest_case;
berghofe@22779
   445
val strip_case' = gen_strip_case oo dest_case';
berghofe@22779
   446
berghofe@22779
   447
berghofe@22779
   448
(* print translation *)
berghofe@22779
   449
berghofe@22779
   450
fun case_tr' tab_of cname ctxt ts =
berghofe@22779
   451
  let
berghofe@22779
   452
    val thy = ProofContext.theory_of ctxt;
berghofe@22779
   453
    fun mk_clause (pat, rhs) =
wenzelm@42049
   454
      let val xs = Term.add_frees pat [] in
wenzelm@35124
   455
        Syntax.const @{syntax_const "_case1"} $
berghofe@22779
   456
          map_aterms
wenzelm@42284
   457
            (fn Free p => Syntax_Trans.mark_boundT p
wenzelm@42290
   458
              | Const (s, _) => Syntax.const (Lexicon.mark_const s)
berghofe@22779
   459
              | t => t) pat $
berghofe@22779
   460
          map_aterms
wenzelm@29266
   461
            (fn x as Free (s, T) =>
wenzelm@42284
   462
                  if member (op =) xs (s, T) then Syntax_Trans.mark_bound s else x
berghofe@22779
   463
              | t => t) rhs
wenzelm@42049
   464
      end;
wenzelm@35124
   465
  in
wenzelm@42049
   466
    (case strip_case' (tab_of thy) true (list_comb (Syntax.const cname, ts)) of
wenzelm@35124
   467
      SOME (x, clauses) =>
wenzelm@35124
   468
        Syntax.const @{syntax_const "_case_syntax"} $ x $
wenzelm@35124
   469
          foldr1 (fn (t, u) => Syntax.const @{syntax_const "_case2"} $ t $ u)
wenzelm@35124
   470
            (map mk_clause clauses)
wenzelm@42049
   471
    | NONE => raise Match)
berghofe@22779
   472
  end;
berghofe@22779
   473
berghofe@22779
   474
end;