Persistent patterns, save and load to a file.
[ocaml-bitstring.git] / pa_bitmatch.ml
index 9a25da8..9ea15c3 100644 (file)
@@ -15,7 +15,7 @@
  * License along with this library; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  *
- * $Id: pa_bitmatch.ml,v 1.11 2008-04-25 14:57:11 rjones Exp $
+ * $Id$
  *)
 
 open Printf
@@ -24,6 +24,9 @@ open Camlp4.PreCast
 open Syntax
 open Ast
 
+open Bitmatch
+module P = Bitmatch_persistent
+
 (* If this is true then we emit some debugging code which can
  * be useful to tell what is happening during matches.  You
  * also need to do 'Bitmatch.debug := true' in your main program.
@@ -32,6 +35,9 @@ open Ast
  *)
 let debug = false
 
+(* Hashtable storing named persistent patterns. *)
+let pattern_hash : (string, P.pattern) Hashtbl.t = Hashtbl.create 13
+
 (* Work out if an expression is an integer constant.
  *
  * Returns [Some i] if so (where i is the integer value), else [None].
@@ -68,21 +74,6 @@ let rec expr_is_constant = function
      | _ -> None)
   | _ -> None                          (* Anything else is not constant. *)
 
-(* Field.  In bitmatch (patterns) the type is [patt field].  In
- * BITSTRING (constructor) the type is [expr field].
- *)
-type 'a field = {
-  field : 'a;                          (* field ('a is either patt or expr) *)
-  flen : expr;                         (* length in bits, may be non-const *)
-  endian : endian;                     (* endianness *)
-  signed : bool;                       (* true if signed, false if unsigned *)
-  t : t;                               (* type *)
-  _loc : Loc.t;                                (* location in source code *)
-  printer : 'a -> string;              (* turn the field into a string *)
-}
-and endian = BigEndian | LittleEndian | NativeEndian
-and t = Int | String | Bitstring
-
 (* Generate a fresh, unique symbol each time called. *)
 let gensym =
   let i = ref 1000 in
@@ -91,133 +82,99 @@ let gensym =
     sprintf "__pabitmatch_%s_%d" name i
 
 (* Deal with the qualifiers which appear for a field of both types. *)
-let parse_field _loc field flen qs printer =
-  let endian, signed, t =
+let parse_field _loc field qs =
+  let endian_set, signed_set, type_set, field =
     match qs with
-    | None -> (None, None, None)
+    | None -> (false, false, false, field)
     | Some qs ->
        List.fold_left (
-         fun (endian, signed, t) q ->
-           match q with
-           | "bigendian" ->
-               if endian <> None then
+         fun (endian_set, signed_set, type_set, field) qual_expr ->
+           match qual_expr with
+           | "bigendian", None ->
+               if endian_set then
                  Loc.raise _loc (Failure "an endian flag has been set already")
                else (
-                 let endian = Some BigEndian in
-                 (endian, signed, t)
+                 let field = P.set_endian field BigEndian in
+                 (true, signed_set, type_set, field)
                )
-           | "littleendian" ->
-               if endian <> None then
+           | "littleendian", None ->
+               if endian_set then
                  Loc.raise _loc (Failure "an endian flag has been set already")
                else (
-                 let endian = Some LittleEndian in
-                 (endian, signed, t)
+                 let field = P.set_endian field LittleEndian in
+                 (true, signed_set, type_set, field)
                )
-           | "nativeendian" ->
-               if endian <> None then
+           | "nativeendian", None ->
+               if endian_set then
                  Loc.raise _loc (Failure "an endian flag has been set already")
                else (
-                 let endian = Some NativeEndian in
-                 (endian, signed, t)
+                 let field = P.set_endian field NativeEndian in
+                 (true, signed_set, type_set, field)
                )
-           | "signed" ->
-               if signed <> None then
+           | "endian", Some expr ->
+               if endian_set then
+                 Loc.raise _loc (Failure "an endian flag has been set already")
+               else (
+                 let field = P.set_endian_expr field expr in
+                 (true, signed_set, type_set, field)
+               )
+           | "signed", None ->
+               if signed_set then
                  Loc.raise _loc (Failure "a signed flag has been set already")
                else (
-                 let signed = Some true in
-                 (endian, signed, t)
+                 let field = P.set_signed field true in
+                 (endian_set, true, type_set, field)
                )
-           | "unsigned" ->
-               if signed <> None then
+           | "unsigned", None ->
+               if signed_set then
                  Loc.raise _loc (Failure "a signed flag has been set already")
                else (
-                 let signed = Some false in
-                 (endian, signed, t)
+                 let field = P.set_signed field false in
+                 (endian_set, true, type_set, field)
                )
-           | "int" ->
-               if t <> None then
+           | "int", None ->
+               if type_set then
                  Loc.raise _loc (Failure "a type flag has been set already")
                else (
-                 let t = Some Int in
-                 (endian, signed, t)
+                 let field = P.set_type_int field in
+                 (endian_set, signed_set, true, field)
                )
-           | "string" ->
-               if t <> None then
+           | "string", None ->
+               if type_set then
                  Loc.raise _loc (Failure "a type flag has been set already")
                else (
-                 let t = Some String in
-                 (endian, signed, t)
+                 let field = P.set_type_string field in
+                 (endian_set, signed_set, true, field)
                )
-           | "bitstring" ->
-               if t <> None then
+           | "bitstring", None ->
+               if type_set then
                  Loc.raise _loc (Failure "a type flag has been set already")
                else (
-                 let t = Some Bitstring in
-                 (endian, signed, t)
+                 let field = P.set_type_bitstring field in
+                 (endian_set, signed_set, true, field)
                )
-           | s ->
-               Loc.raise _loc (Failure (s ^ ": unknown qualifier"))
-       ) (None, None, None) qs in
+           | s, Some _ ->
+               Loc.raise _loc (Failure (s ^ ": unknown qualifier, or qualifier should not be followed by an expression"))
+           | s, None ->
+               Loc.raise _loc (Failure (s ^ ": unknown qualifier, or qualifier should be followed by an expression"))
+       ) (false, false, false, field) qs in
 
   (* If type is set to string or bitstring then endianness and
    * signedness qualifiers are meaningless and must not be set.
    *)
-  if (t = Some Bitstring || t = Some String)
-    && (endian <> None || signed <> None) then
+  let () =
+    let t = P.get_type field in
+    if (t = P.Bitstring || t = P.String) && (endian_set || signed_set) then
       Loc.raise _loc (
        Failure "string types and endian or signed qualifiers cannot be mixed"
-      );
-
-  (* Default endianness, signedness, type. *)
-  let endian = match endian with None -> BigEndian | Some e -> e in
-  let signed = match signed with None -> false | Some s -> s in
-  let t = match t with None -> Int | Some t -> t in
-
-  {
-    field = field;
-    flen = flen;
-    endian = endian;
-    signed = signed;
-    t = t;
-    _loc = _loc;
-    printer = printer;
-  }
-
-let string_of_endian = function
-  | BigEndian -> "bigendian"
-  | LittleEndian -> "littleendian"
-  | NativeEndian -> "nativeendian"
-
-let string_of_t = function
-  | Int -> "int"
-  | String -> "string"
-  | Bitstring -> "bitstring"
-
-let patt_printer = function
-  | <:patt< $lid:id$ >> -> id
-  | _ -> "[pattern]"
-
-let expr_printer = function
-  | <:expr< $lid:id$ >> -> id
-  | _ -> "[expression]"
-
-let string_of_field { field = field; flen = flen;
-                     endian = endian; signed = signed; t = t;
-                     _loc = _loc;
-                     printer = printer} =
-  let flen =
-    match expr_is_constant flen with
-    | Some i -> string_of_int i
-    | None -> "[non-const-len]" in
-  let endian = string_of_endian endian in
-  let signed = if signed then "signed" else "unsigned" in
-  let t = string_of_t t in
-  let loc_fname = Loc.file_name _loc in
-  let loc_line = Loc.start_line _loc in
-  let loc_char = Loc.start_off _loc - Loc.start_bol _loc in
+      ) in
+
+  (* Default endianness, signedness, type if not set already. *)
+  let field = if endian_set then field else P.set_endian field BigEndian in
+  let field = if signed_set then field else P.set_signed field false in
+  let field = if type_set then field else P.set_type_int field in
 
-  sprintf "%s : %s : %s, %s, %s @ (%S, %d, %d)"
-    (printer field) flen t endian signed loc_fname loc_line loc_char
+  field
 
 (* Generate the code for a constructor, ie. 'BITSTRING ...'. *)
 let output_constructor _loc fields =
@@ -239,54 +196,96 @@ let output_constructor _loc fields =
 
   (* Convert each field to a simple bitstring-generating expression. *)
   let fields = List.map (
-    fun {field=fexpr; flen=flen; endian=endian; signed=signed;
-        t=t; _loc=_loc} ->
+    fun field ->
+      let fexpr = P.get_expr field in
+      let flen = P.get_length field in
+      let endian = P.get_endian field in
+      let signed = P.get_signed field in
+      let t = P.get_type field in
+      let _loc = P.get_location field in
+
       (* Is flen an integer constant?  If so, what is it?  This
        * is very simple-minded and only detects simple constants.
        *)
       let flen_is_const = expr_is_constant flen in
 
-      let name_of_int_construct_const = function
-         (* XXX As an enhancement we should allow a 64-bit-only
-          * mode which lets us use 'int' up to 63 bits and won't
-          * compile on 32-bit platforms.
-          *)
+      (* Choose the right constructor function. *)
+      let int_construct_const = function
          (* XXX The meaning of signed/unsigned breaks down at
           * 31, 32, 63 and 64 bits.
           *)
-       | (1, _, _) -> "construct_bit"
-       | ((2|3|4|5|6|7|8), _, false) -> "construct_char_unsigned"
-       | ((2|3|4|5|6|7|8), _, true) -> "construct_char_signed"
-       | (i, BigEndian, false) when i <= 31 -> "construct_int_be_unsigned"
-       | (i, BigEndian, true) when i <= 31 -> "construct_int_be_signed"
-       | (i, LittleEndian, false) when i <= 31 -> "construct_int_le_unsigned"
-       | (i, LittleEndian, true) when i <= 31 -> "construct_int_le_signed"
-       | (i, NativeEndian, false) when i <= 31 -> "construct_int_ne_unsigned"
-       | (i, NativeEndian, true) when i <= 31 -> "construct_int_ne_signed"
-       | (32, BigEndian, false) -> "construct_int32_be_unsigned"
-       | (32, BigEndian, true) -> "construct_int32_be_signed"
-       | (32, LittleEndian, false) -> "construct_int32_le_unsigned"
-       | (32, LittleEndian, true) -> "construct_int32_le_signed"
-       | (32, NativeEndian, false) -> "construct_int32_ne_unsigned"
-       | (32, NativeEndian, true) -> "construct_int32_ne_signed"
-       | (_, BigEndian, false) -> "construct_int64_be_unsigned"
-       | (_, BigEndian, true) -> "construct_int64_be_signed"
-       | (_, LittleEndian, false) -> "construct_int64_le_unsigned"
-       | (_, LittleEndian, true) -> "construct_int64_le_signed"
-       | (_, NativeEndian, false) -> "construct_int64_ne_unsigned"
-       | (_, NativeEndian, true) -> "construct_int64_ne_signed"
+       | (1, _, _) ->
+           <:expr<Bitmatch.construct_bit>>
+       | ((2|3|4|5|6|7|8), _, false) ->
+           <:expr<Bitmatch.construct_char_unsigned>>
+       | ((2|3|4|5|6|7|8), _, true) ->
+           <:expr<Bitmatch.construct_char_signed>>
+       | (i, P.ConstantEndian BigEndian, false) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_be_unsigned>>
+       | (i, P.ConstantEndian BigEndian, true) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_be_signed>>
+       | (i, P.ConstantEndian LittleEndian, false) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_le_unsigned>>
+       | (i, P.ConstantEndian LittleEndian, true) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_le_signed>>
+       | (i, P.ConstantEndian NativeEndian, false) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_ne_unsigned>>
+       | (i, P.ConstantEndian NativeEndian, true) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_ne_signed>>
+       | (i, P.EndianExpr expr, false) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_ee_unsigned $expr$>>
+       | (i, P.EndianExpr expr, true) when i <= 31 ->
+           <:expr<Bitmatch.construct_int_ee_signed $expr$>>
+       | (32, P.ConstantEndian BigEndian, false) ->
+           <:expr<Bitmatch.construct_int32_be_unsigned>>
+       | (32, P.ConstantEndian BigEndian, true) ->
+           <:expr<Bitmatch.construct_int32_be_signed>>
+       | (32, P.ConstantEndian LittleEndian, false) ->
+           <:expr<Bitmatch.construct_int32_le_unsigned>>
+       | (32, P.ConstantEndian LittleEndian, true) ->
+           <:expr<Bitmatch.construct_int32_le_signed>>
+       | (32, P.ConstantEndian NativeEndian, false) ->
+           <:expr<Bitmatch.construct_int32_ne_unsigned>>
+       | (32, P.ConstantEndian NativeEndian, true) ->
+           <:expr<Bitmatch.construct_int32_ne_signed>>
+       | (32, P.EndianExpr expr, false) ->
+           <:expr<Bitmatch.construct_int32_ee_unsigned $expr$>>
+       | (32, P.EndianExpr expr, true) ->
+           <:expr<Bitmatch.construct_int32_ee_signed $expr$>>
+       | (_, P.ConstantEndian BigEndian, false) ->
+           <:expr<Bitmatch.construct_int64_be_unsigned>>
+       | (_, P.ConstantEndian BigEndian, true) ->
+           <:expr<Bitmatch.construct_int64_be_signed>>
+       | (_, P.ConstantEndian LittleEndian, false) ->
+           <:expr<Bitmatch.construct_int64_le_unsigned>>
+       | (_, P.ConstantEndian LittleEndian, true) ->
+           <:expr<Bitmatch.construct_int64_le_signed>>
+       | (_, P.ConstantEndian NativeEndian, false) ->
+           <:expr<Bitmatch.construct_int64_ne_unsigned>>
+       | (_, P.ConstantEndian NativeEndian, true) ->
+           <:expr<Bitmatch.construct_int64_ne_signed>>
+       | (_, P.EndianExpr expr, false) ->
+           <:expr<Bitmatch.construct_int64_ee_unsigned $expr$>>
+       | (_, P.EndianExpr expr, true) ->
+           <:expr<Bitmatch.construct_int64_ee_signed $expr$>>
       in
-      let name_of_int_construct = function
-         (* XXX As an enhancement we should allow users to
-          * specify that a field length can fit into a char/int/int32
-          * (of course, this would have to be checked at runtime).
-          *)
-       | (BigEndian, false) -> "construct_int64_be_unsigned"
-       | (BigEndian, true) -> "construct_int64_be_signed"
-       | (LittleEndian, false) -> "construct_int64_le_unsigned"
-       | (LittleEndian, true) -> "construct_int64_le_signed"
-       | (NativeEndian, false) -> "construct_int64_ne_unsigned"
-       | (NativeEndian, true) -> "construct_int64_ne_signed"
+      let int_construct = function
+       | (P.ConstantEndian BigEndian, false) ->
+           <:expr<Bitmatch.construct_int64_be_unsigned>>
+       | (P.ConstantEndian BigEndian, true) ->
+           <:expr<Bitmatch.construct_int64_be_signed>>
+       | (P.ConstantEndian LittleEndian, false) ->
+           <:expr<Bitmatch.construct_int64_le_unsigned>>
+       | (P.ConstantEndian LittleEndian, true) ->
+           <:expr<Bitmatch.construct_int64_le_signed>>
+       | (P.ConstantEndian NativeEndian, false) ->
+           <:expr<Bitmatch.construct_int64_ne_unsigned>>
+       | (P.ConstantEndian NativeEndian, true) ->
+           <:expr<Bitmatch.construct_int64_ne_signed>>
+       | (P.EndianExpr expr, false) ->
+           <:expr<Bitmatch.construct_int64_ee_unsigned $expr$>>
+       | (P.EndianExpr expr, true) ->
+           <:expr<Bitmatch.construct_int64_ee_signed $expr$>>
       in
 
       let expr =
@@ -297,17 +296,15 @@ let output_constructor _loc fields =
         * because that's a lot simpler w.r.t. types.  It might
         * be better to move them here. XXX
         *)
-       | Int, Some i when i > 0 && i <= 64 ->
-           let construct_func =
-             name_of_int_construct_const (i,endian,signed) in
+       | P.Int, Some i when i > 0 && i <= 64 ->
+           let construct_fn = int_construct_const (i,endian,signed) in
            exn_used := true;
 
            <:expr<
-             Bitmatch.$lid:construct_func$ $lid:buffer$ $fexpr$ $flen$
-               $lid:exn$
+             $construct_fn$ $lid:buffer$ $fexpr$ $`int:i$ $lid:exn$
            >>
 
-       | Int, Some _ ->
+       | P.Int, Some _ ->
            Loc.raise _loc (Failure "length of int field must be [1..64]")
 
        (* Int field, non-constant length.  We need to perform a runtime
@@ -317,14 +314,13 @@ let output_constructor _loc fields =
         * because that's a lot simpler w.r.t. types.  It might
         * be better to move them here. XXX
         *)
-       | Int, None ->
-           let construct_func = name_of_int_construct (endian,signed) in
+       | P.Int, None ->
+           let construct_fn = int_construct (endian,signed) in
            exn_used := true;
 
            <:expr<
              if $flen$ >= 1 && $flen$ <= 64 then
-               Bitmatch.$lid:construct_func$ $lid:buffer$ $fexpr$ $flen$
-                 $lid:exn$
+               $construct_fn$ $lid:buffer$ $fexpr$ $flen$ $lid:exn$
              else
                raise (Bitmatch.Construct_failure
                         ("length of int field must be [1..64]",
@@ -333,11 +329,12 @@ let output_constructor _loc fields =
            >>
 
         (* String, constant length > 0, must be a multiple of 8. *)
-       | String, Some i when i > 0 && i land 7 = 0 ->
+       | P.String, Some i when i > 0 && i land 7 = 0 ->
            let bs = gensym "bs" in
+           let j = i lsr 3 in
            <:expr<
              let $lid:bs$ = $fexpr$ in
-             if String.length $lid:bs$ = ($flen$ lsr 3) then
+             if String.length $lid:bs$ = $`int:j$ then
                Bitmatch.construct_string $lid:buffer$ $lid:bs$
              else
                raise (Bitmatch.Construct_failure
@@ -349,20 +346,20 @@ let output_constructor _loc fields =
        (* String, constant length -1, means variable length string
         * with no checks.
         *)
-       | String, Some (-1) ->
+       | P.String, Some (-1) ->
            <:expr< Bitmatch.construct_string $lid:buffer$ $fexpr$ >>
 
        (* String, constant length = 0 is probably an error, and so is
         * any other value.
         *)
-       | String, Some _ ->
+       | P.String, Some _ ->
            Loc.raise _loc (Failure "length of string must be > 0 and a multiple of 8, or the special value -1")
 
        (* String, non-constant length.
         * We check at runtime that the length is > 0, a multiple of 8,
         * and matches the declared length.
         *)
-       | String, None ->
+       | P.String, None ->
            let bslen = gensym "bslen" in
            let bs = gensym "bs" in
            <:expr<
@@ -390,11 +387,11 @@ let output_constructor _loc fields =
            >>
 
         (* Bitstring, constant length > 0. *)
-       | Bitstring, Some i when i > 0 ->
+       | P.Bitstring, Some i when i > 0 ->
            let bs = gensym "bs" in
            <:expr<
              let $lid:bs$ = $fexpr$ in
-             if Bitmatch.bitstring_length $lid:bs$ = $flen$ then
+             if Bitmatch.bitstring_length $lid:bs$ = $`int:i$ then
                Bitmatch.construct_bitstring $lid:buffer$ $lid:bs$
              else
                raise (Bitmatch.Construct_failure
@@ -406,13 +403,13 @@ let output_constructor _loc fields =
        (* Bitstring, constant length -1, means variable length bitstring
         * with no checks.
         *)
-       | Bitstring, Some (-1) ->
+       | P.Bitstring, Some (-1) ->
            <:expr< Bitmatch.construct_bitstring $lid:buffer$ $fexpr$ >>
 
        (* Bitstring, constant length = 0 is probably an error, and so is
         * any other value.
         *)
-       | Bitstring, Some _ ->
+       | P.Bitstring, Some _ ->
            Loc.raise _loc
              (Failure
                 "length of bitstring must be > 0 or the special value -1")
@@ -421,7 +418,7 @@ let output_constructor _loc fields =
         * We check at runtime that the length is > 0 and matches
         * the declared length.
         *)
-       | Bitstring, None ->
+       | P.Bitstring, None ->
            let bslen = gensym "bslen" in
            let bs = gensym "bs" in
            <:expr<
@@ -496,100 +493,136 @@ let output_bitmatch _loc bs cases =
   let rec output_field_extraction inner = function
     | [] -> inner
     | field :: fields ->
-       let {field=fpatt; flen=flen; endian=endian; signed=signed;
-            t=t; _loc=_loc}
-           = field in
+       let fpatt = P.get_patt field in
+       let flen = P.get_length field in
+       let endian = P.get_endian field in
+       let signed = P.get_signed field in
+       let t = P.get_type field in
+       let _loc = P.get_location field in
 
        (* Is flen an integer constant?  If so, what is it?  This
         * is very simple-minded and only detects simple constants.
         *)
        let flen_is_const = expr_is_constant flen in
 
-       let name_of_int_extract_const = function
-           (* XXX As an enhancement we should allow a 64-bit-only
-            * mode which lets us use 'int' up to 63 bits and won't
-            * compile on 32-bit platforms.
-            *)
+       let int_extract_const = function
            (* XXX The meaning of signed/unsigned breaks down at
             * 31, 32, 63 and 64 bits.
             *)
-         | (1, _, _) -> "extract_bit"
-         | ((2|3|4|5|6|7|8), _, false) -> "extract_char_unsigned"
-         | ((2|3|4|5|6|7|8), _, true) -> "extract_char_signed"
-         | (i, BigEndian, false) when i <= 31 -> "extract_int_be_unsigned"
-         | (i, BigEndian, true) when i <= 31 -> "extract_int_be_signed"
-         | (i, LittleEndian, false) when i <= 31 -> "extract_int_le_unsigned"
-         | (i, LittleEndian, true) when i <= 31 -> "extract_int_le_signed"
-         | (i, NativeEndian, false) when i <= 31 -> "extract_int_ne_unsigned"
-         | (i, NativeEndian, true) when i <= 31 -> "extract_int_ne_signed"
-         | (32, BigEndian, false) -> "extract_int32_be_unsigned"
-         | (32, BigEndian, true) -> "extract_int32_be_signed"
-         | (32, LittleEndian, false) -> "extract_int32_le_unsigned"
-         | (32, LittleEndian, true) -> "extract_int32_le_signed"
-         | (32, NativeEndian, false) -> "extract_int32_ne_unsigned"
-         | (32, NativeEndian, true) -> "extract_int32_ne_signed"
-         | (_, BigEndian, false) -> "extract_int64_be_unsigned"
-         | (_, BigEndian, true) -> "extract_int64_be_signed"
-         | (_, LittleEndian, false) -> "extract_int64_le_unsigned"
-         | (_, LittleEndian, true) -> "extract_int64_le_signed"
-         | (_, NativeEndian, false) -> "extract_int64_ne_unsigned"
-         | (_, NativeEndian, true) -> "extract_int64_ne_signed"
+         | (1, _, _) ->
+             <:expr<Bitmatch.extract_bit>>
+         | ((2|3|4|5|6|7|8), _, false) ->
+             <:expr<Bitmatch.extract_char_unsigned>>
+         | ((2|3|4|5|6|7|8), _, true) ->
+             <:expr<Bitmatch.extract_char_signed>>
+         | (i, P.ConstantEndian BigEndian, false) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_be_unsigned>>
+         | (i, P.ConstantEndian BigEndian, true) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_be_signed>>
+         | (i, P.ConstantEndian LittleEndian, false) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_le_unsigned>>
+         | (i, P.ConstantEndian LittleEndian, true) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_le_signed>>
+         | (i, P.ConstantEndian NativeEndian, false) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_ne_unsigned>>
+         | (i, P.ConstantEndian NativeEndian, true) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_ne_signed>>
+         | (i, P.EndianExpr expr, false) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_ee_unsigned $expr$>>
+         | (i, P.EndianExpr expr, true) when i <= 31 ->
+             <:expr<Bitmatch.extract_int_ee_signed $expr$>>
+         | (32, P.ConstantEndian BigEndian, false) ->
+             <:expr<Bitmatch.extract_int32_be_unsigned>>
+         | (32, P.ConstantEndian BigEndian, true) ->
+             <:expr<Bitmatch.extract_int32_be_signed>>
+         | (32, P.ConstantEndian LittleEndian, false) ->
+             <:expr<Bitmatch.extract_int32_le_unsigned>>
+         | (32, P.ConstantEndian LittleEndian, true) ->
+             <:expr<Bitmatch.extract_int32_le_signed>>
+         | (32, P.ConstantEndian NativeEndian, false) ->
+             <:expr<Bitmatch.extract_int32_ne_unsigned>>
+         | (32, P.ConstantEndian NativeEndian, true) ->
+             <:expr<Bitmatch.extract_int32_ne_signed>>
+         | (32, P.EndianExpr expr, false) ->
+             <:expr<Bitmatch.extract_int32_ee_unsigned $expr$>>
+         | (32, P.EndianExpr expr, true) ->
+             <:expr<Bitmatch.extract_int32_ee_signed $expr$>>
+         | (_, P.ConstantEndian BigEndian, false) ->
+             <:expr<Bitmatch.extract_int64_be_unsigned>>
+         | (_, P.ConstantEndian BigEndian, true) ->
+             <:expr<Bitmatch.extract_int64_be_signed>>
+         | (_, P.ConstantEndian LittleEndian, false) ->
+             <:expr<Bitmatch.extract_int64_le_unsigned>>
+         | (_, P.ConstantEndian LittleEndian, true) ->
+             <:expr<Bitmatch.extract_int64_le_signed>>
+         | (_, P.ConstantEndian NativeEndian, false) ->
+             <:expr<Bitmatch.extract_int64_ne_unsigned>>
+         | (_, P.ConstantEndian NativeEndian, true) ->
+             <:expr<Bitmatch.extract_int64_ne_signed>>
+         | (_, P.EndianExpr expr, false) ->
+             <:expr<Bitmatch.extract_int64_ee_unsigned $expr$>>
+         | (_, P.EndianExpr expr, true) ->
+             <:expr<Bitmatch.extract_int64_ee_signed $expr$>>
        in
-       let name_of_int_extract = function
-           (* XXX As an enhancement we should allow users to
-            * specify that a field length can fit into a char/int/int32
-            * (of course, this would have to be checked at runtime).
-            *)
-         | (BigEndian, false) -> "extract_int64_be_unsigned"
-         | (BigEndian, true) -> "extract_int64_be_signed"
-         | (LittleEndian, false) -> "extract_int64_le_unsigned"
-         | (LittleEndian, true) -> "extract_int64_le_signed"
-         | (NativeEndian, false) -> "extract_int64_ne_unsigned"
-         | (NativeEndian, true) -> "extract_int64_ne_signed"
+       let int_extract = function
+         | (P.ConstantEndian BigEndian, false) ->
+             <:expr<Bitmatch.extract_int64_be_unsigned>>
+         | (P.ConstantEndian BigEndian, true) ->
+             <:expr<Bitmatch.extract_int64_be_signed>>
+         | (P.ConstantEndian LittleEndian, false) ->
+             <:expr<Bitmatch.extract_int64_le_unsigned>>
+         | (P.ConstantEndian LittleEndian, true) ->
+             <:expr<Bitmatch.extract_int64_le_signed>>
+         | (P.ConstantEndian NativeEndian, false) ->
+             <:expr<Bitmatch.extract_int64_ne_unsigned>>
+         | (P.ConstantEndian NativeEndian, true) ->
+             <:expr<Bitmatch.extract_int64_ne_signed>>
+         | (P.EndianExpr expr, false) ->
+             <:expr<Bitmatch.extract_int64_ee_unsigned $expr$>>
+         | (P.EndianExpr expr, true) ->
+             <:expr<Bitmatch.extract_int64_ee_signed $expr$>>
        in
 
        let expr =
          match t, flen_is_const with
          (* Common case: int field, constant flen *)
-         | Int, Some i when i > 0 && i <= 64 ->
-             let extract_func = name_of_int_extract_const (i,endian,signed) in
+         | P.Int, Some i when i > 0 && i <= 64 ->
+             let extract_fn = int_extract_const (i,endian,signed) in
              let v = gensym "val" in
              <:expr<
-               if $lid:len$ >= $flen$ then (
+               if $lid:len$ >= $`int:i$ then (
                  let $lid:v$, $lid:off$, $lid:len$ =
-                   Bitmatch.$lid:extract_func$ $lid:data$ $lid:off$ $lid:len$
-                     $flen$ in
+                   $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $`int:i$ in
                  match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
                )
              >>
 
-         | Int, Some _ ->
+         | P.Int, Some _ ->
              Loc.raise _loc (Failure "length of int field must be [1..64]")
 
          (* Int field, non-const flen.  We have to test the range of
           * the field at runtime.  If outside the range it's a no-match
           * (not an error).
           *)
-         | Int, None ->
-             let extract_func = name_of_int_extract (endian,signed) in
+         | P.Int, None ->
+             let extract_fn = int_extract (endian,signed) in
              let v = gensym "val" in
              <:expr<
                if $flen$ >= 1 && $flen$ <= 64 && $flen$ <= $lid:len$ then (
                  let $lid:v$, $lid:off$, $lid:len$ =
-                   Bitmatch.$lid:extract_func$ $lid:data$ $lid:off$ $lid:len$
-                     $flen$ in
+                   $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $flen$ in
                  match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
                )
              >>
 
           (* String, constant flen > 0. *)
-         | String, Some i when i > 0 && i land 7 = 0 ->
+         | P.String, Some i when i > 0 && i land 7 = 0 ->
              let bs = gensym "bs" in
              <:expr<
-               if $lid:len$ >= $flen$ then (
+               if $lid:len$ >= $`int:i$ then (
                  let $lid:bs$, $lid:off$, $lid:len$ =
                    Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
-                     $flen$ in
+                     $`int:i$ in
                  match Bitmatch.string_of_bitstring $lid:bs$ with
                  | $fpatt$ when true -> $inner$
                  | _ -> ()
@@ -599,7 +632,7 @@ let output_bitmatch _loc bs cases =
           (* String, constant flen = -1, means consume all the
           * rest of the input.
           *)
-         | String, Some i when i = -1 ->
+         | P.String, Some i when i = -1 ->
              let bs = gensym "bs" in
              <:expr<
                let $lid:bs$, $lid:off$, $lid:len$ =
@@ -609,13 +642,13 @@ let output_bitmatch _loc bs cases =
                | _ -> ()
              >>
 
-         | String, Some _ ->
+         | P.String, Some _ ->
              Loc.raise _loc (Failure "length of string must be > 0 and a multiple of 8, or the special value -1")
 
          (* String field, non-const flen.  We check the flen is > 0
           * and a multiple of 8 (-1 is not allowed here), at runtime.
           *)
-         | String, None ->
+         | P.String, None ->
              let bs = gensym "bs" in
              <:expr<
                if $flen$ >= 0 && $flen$ <= $lid:len$
@@ -633,7 +666,7 @@ let output_bitmatch _loc bs cases =
           * At the moment all we can do is assign the bitstring to an
           * identifier.
           *)
-         | Bitstring, Some i when i >= 0 ->
+         | P.Bitstring, Some i when i >= 0 ->
              let ident =
                match fpatt with
                | <:patt< $lid:ident$ >> -> ident
@@ -642,10 +675,10 @@ let output_bitmatch _loc bs cases =
                    Loc.raise _loc
                      (Failure "cannot compare a bitstring to a constant") in
              <:expr<
-               if $lid:len$ >= $flen$ then (
+               if $lid:len$ >= $`int:i$ then (
                  let $lid:ident$, $lid:off$, $lid:len$ =
                    Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
-                     $flen$ in
+                     $`int:i$ in
                  $inner$
                )
              >>
@@ -653,7 +686,7 @@ let output_bitmatch _loc bs cases =
           (* Bitstring, constant flen = -1, means consume all the
           * rest of the input.
           *)
-         | Bitstring, Some i when i = -1 ->
+         | P.Bitstring, Some i when i = -1 ->
              let ident =
                match fpatt with
                | <:patt< $lid:ident$ >> -> ident
@@ -667,13 +700,13 @@ let output_bitmatch _loc bs cases =
                  $inner$
              >>
 
-         | Bitstring, Some _ ->
+         | P.Bitstring, Some _ ->
              Loc.raise _loc (Failure "length of bitstring must be >= 0 or the special value -1")
 
          (* Bitstring field, non-const flen.  We check the flen is >= 0
           * (-1 is not allowed here) at runtime.
           *)
-         | Bitstring, None ->
+         | P.Bitstring, None ->
              let ident =
                match fpatt with
                | <:patt< $lid:ident$ >> -> ident
@@ -694,7 +727,7 @@ let output_bitmatch _loc bs cases =
        (* Emit extra debugging code. *)
        let expr =
          if not debug then expr else (
-           let field = string_of_field field in
+           let field = P.string_of_field field in
 
            <:expr<
              if !Bitmatch.debug then (
@@ -768,26 +801,90 @@ let output_bitmatch _loc bs cases =
                                    $int:loc_line$, $int:loc_char$))
   >>
 
+(* Add a named pattern. *)
+let add_named_pattern _loc name pattern =
+  Hashtbl.add pattern_hash name pattern
+
+(* Expand a named pattern from the pattern_hash. *)
+let expand_named_pattern _loc name =
+  try Hashtbl.find pattern_hash name
+  with Not_found ->
+    Loc.raise _loc (Failure (sprintf "named pattern not found: %s" name))
+
+(* Add named patterns from a file.  See the documentation on the
+ * directory search path in bitmatch_persistent.mli
+ *)
+let load_patterns_from_file _loc filename =
+  let chan =
+    if Filename.is_relative filename && Filename.is_implicit filename then (
+      (* Try current directory. *)
+      try open_in filename
+      with _ ->
+       (* Try OCaml library directory. *)
+       try open_in (Filename.concat Bitmatch_config.ocamllibdir filename)
+       with exn -> Loc.raise _loc exn
+    ) else (
+      try open_in filename
+      with exn -> Loc.raise _loc exn
+    ) in
+  let names = ref [] in
+  (try
+     let rec loop () =
+       let name = P.named_from_channel chan in
+       names := name :: !names
+     in
+     loop ()
+   with End_of_file -> ()
+  );
+  close_in chan;
+  let names = List.rev !names in
+  List.iter (
+    function
+    | name, P.Pattern patt -> add_named_pattern _loc name patt
+    | _, P.Constructor _ -> () (* just ignore these for now *)
+  ) names
+
 EXTEND Gram
-  GLOBAL: expr;
+  GLOBAL: expr str_item;
 
+  (* Qualifiers are a list of identifiers ("string", "bigendian", etc.)
+   * followed by an optional expression (used in certain cases).  Note
+   * that we are careful not to declare any explicit reserved words.
+   *)
   qualifiers: [
-    [ LIST0 [ q = LIDENT -> q ] SEP "," ]
+    [ LIST0
+       [ q = LIDENT;
+         e = OPT [ "("; e = expr; ")" -> e ] -> (q, e) ]
+       SEP "," ]
   ];
 
-  (* Field used in the bitmatch operator (a pattern). *)
+  (* Field used in the bitmatch operator (a pattern).  This can actually
+   * return multiple fields, in the case where the 'field' is a named
+   * persitent pattern.
+   *)
   patt_field: [
     [ fpatt = patt; ":"; len = expr LEVEL "top";
       qs = OPT [ ":"; qs = qualifiers -> qs ] ->
-       parse_field _loc fpatt len qs patt_printer
+       let field = P.create_pattern_field _loc in
+       let field = P.set_patt field fpatt in
+       let field = P.set_length field len in
+       [parse_field _loc field qs]     (* Normal, single field. *)
+    | ":"; name = LIDENT ->
+       expand_named_pattern _loc name (* Named -> list of fields. *)
     ]
   ];
 
   (* Case inside bitmatch operator. *)
-  match_case: [
+  patt_fields: [
     [ "{";
       fields = LIST0 patt_field SEP ";";
-      "}";
+      "}" ->
+       List.concat fields
+    ]
+  ];
+
+  patt_case: [
+    [ fields = patt_fields;
       bind = OPT [ "as"; name = LIDENT -> name ];
       whenclause = OPT [ "when"; e = expr -> e ]; "->";
       code = expr ->
@@ -799,7 +896,18 @@ EXTEND Gram
   constr_field: [
     [ fexpr = expr LEVEL "top"; ":"; len = expr LEVEL "top";
       qs = OPT [ ":"; qs = qualifiers -> qs ] ->
-       parse_field _loc fexpr len qs expr_printer
+       let field = P.create_constructor_field _loc in
+       let field = P.set_expr field fexpr in
+       let field = P.set_length field len in
+       parse_field _loc field qs
+    ]
+  ];
+
+  constr_fields: [
+    [ "{";
+      fields = LIST0 constr_field SEP ";";
+      "}" ->
+       fields
     ]
   ];
 
@@ -807,16 +915,34 @@ EXTEND Gram
   expr: LEVEL ";" [
     [ "bitmatch";
       bs = expr; "with"; OPT "|";
-      cases = LIST1 match_case SEP "|" ->
+      cases = LIST1 patt_case SEP "|" ->
        output_bitmatch _loc bs cases
     ]
 
   (* Constructor. *)
-  | [ "BITSTRING"; "{";
-      fields = LIST0 constr_field SEP ";";
-      "}" ->
+  | [ "BITSTRING";
+      fields = constr_fields ->
        output_constructor _loc fields
     ]
   ];
 
+  (* Named persistent patterns.
+   *
+   * NB: Currently only allowed at the top level.  We can probably lift
+   * this restriction later if necessary.  We only deal with patterns
+   * at the moment, not constructors, but the infrastructure to do
+   * constructors is in place.
+   *)
+  str_item: LEVEL "top" [
+    [ "let"; "bitmatch";
+      name = LIDENT; "="; fields = patt_fields ->
+       add_named_pattern _loc name fields;
+        (* The statement disappears, but we still need a str_item so ... *)
+        <:str_item< >>
+    | "open"; "bitmatch"; filename = STRING ->
+       load_patterns_from_file _loc filename;
+       <:str_item< >>
+    ]
+  ];
+
 END