1 (* Bitmatch syntax extension.
2 * Copyright (C) 2008 Red Hat Inc., Richard W.M. Jones
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version,
8 * with the OCaml linking exception described in COPYING.LIB.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
29 module P = Bitmatch_persistent
31 (* If this is true then we emit some debugging code which can
32 * be useful to tell what is happening during matches. You
33 * also need to do 'Bitmatch.debug := true' in your main program.
35 * If this is false then no extra debugging code is emitted.
39 (* Hashtable storing named persistent patterns. *)
40 let pattern_hash : (string, P.pattern) Hashtbl.t = Hashtbl.create 13
42 let locfail _loc msg = Loc.raise _loc (Failure msg)
44 (* Work out if an expression is an integer constant.
46 * Returns [Some i] if so (where i is the integer value), else [None].
48 * Fairly simplistic algorithm: we can only detect simple constant
49 * expressions such as [k], [k+c], [k-c] etc.
51 let rec expr_is_constant = function
52 | <:expr< $int:i$ >> -> (* Literal integer constant. *)
53 Some (int_of_string i)
54 | <:expr< $lid:op$ $a$ $b$ >> ->
55 (match expr_is_constant a, expr_is_constant b with
56 | Some a, Some b -> (* Integer binary operations. *)
57 let ops = ["+", (+); "-", (-); "*", ( * ); "/", (/);
58 "land", (land); "lor", (lor); "lxor", (lxor);
59 "lsl", (lsl); "lsr", (lsr); "asr", (asr);
61 (try Some ((List.assoc op ops) a b) with Not_found -> None)
65 (* Generate a fresh, unique symbol each time called. *)
70 sprintf "__pabitmatch_%s_%d" name i
72 (* Deal with the qualifiers which appear for a field of both types. *)
73 let parse_field _loc field qs =
74 let fail = locfail _loc in
76 let endian_set, signed_set, type_set, offset_set, field =
78 | None -> (false, false, false, false, field)
80 let check already_set msg = if already_set then fail msg in
82 (endian_set, signed_set, type_set, offset_set, field) =
84 | "endian", Some expr ->
85 check endian_set "an endian flag has been set already";
86 let field = P.set_endian_expr field expr in
87 (true, signed_set, type_set, offset_set, field)
89 fail "qualifier 'endian' should be followed by an expression"
90 | "offset", Some expr ->
91 check offset_set "an offset has been set already";
92 let field = P.set_offset field expr in
93 (endian_set, signed_set, type_set, true, field)
95 fail "qualifier 'offset' should be followed by an expression"
97 fail (s ^ ": unknown qualifier, or qualifier should not be followed by an expression")
99 let endian_quals = ["bigendian", BigEndian;
100 "littleendian", LittleEndian;
101 "nativeendian", NativeEndian] in
102 let sign_quals = ["signed", true; "unsigned", false] in
103 let type_quals = ["int", P.set_type_int;
104 "string", P.set_type_string;
105 "bitstring", P.set_type_bitstring] in
106 if List.mem_assoc qual endian_quals then (
107 check endian_set "an endian flag has been set already";
108 let field = P.set_endian field (List.assoc qual endian_quals) in
109 (true, signed_set, type_set, offset_set, field)
110 ) else if List.mem_assoc qual sign_quals then (
111 check signed_set "a signed flag has been set already";
112 let field = P.set_signed field (List.assoc qual sign_quals) in
113 (endian_set, true, type_set, offset_set, field)
114 ) else if List.mem_assoc qual type_quals then (
115 check type_set "a type flag has been set already";
116 let field = List.assoc qual type_quals field in
117 (endian_set, signed_set, true, offset_set, field)
119 fail (qual ^ ": unknown qualifier, or qualifier should be followed by an expression") in
120 List.fold_left apply_qualifier (false, false, false, false, field) qs in
122 (* If type is set to string or bitstring then endianness and
123 * signedness qualifiers are meaningless and must not be set.
126 let t = P.get_type field in
127 if (t = P.Bitstring || t = P.String) && (endian_set || signed_set) then
128 fail "string types and endian or signed qualifiers cannot be mixed" in
130 (* Default endianness, signedness, type if not set already. *)
131 let field = if endian_set then field else P.set_endian field BigEndian in
132 let field = if signed_set then field else P.set_signed field false in
133 let field = if type_set then field else P.set_type_int field in
137 (* Choose the right constructor function. *)
138 let build_bitmatch_call _loc funcname length endian signed =
139 match length, endian, signed with
140 (* XXX The meaning of signed/unsigned breaks down at
141 * 31, 32, 63 and 64 bits.
143 | (Some 1, _, _) -> <:expr<Bitmatch.$lid:funcname ^ "_bit"$ >>
144 | (Some (2|3|4|5|6|7|8), _, sign) ->
145 let call = Printf.sprintf "%s_char_%s"
146 funcname (if sign then "signed" else "unsigned") in
147 <:expr< Bitmatch.$lid:call$ >>
148 | (len, endian, signed) ->
149 let t = match len with
150 | Some i when i <= 31 -> "int"
153 let sign = if signed then "signed" else "unsigned" in
155 | P.ConstantEndian constant ->
156 let endianness = match constant with
158 | LittleEndian -> "le"
159 | NativeEndian -> "ne" in
160 let call = Printf.sprintf "%s_%s_%s_%s"
161 funcname t endianness sign in
162 <:expr< Bitmatch.$lid:call$ >>
163 | P.EndianExpr expr ->
164 let call = Printf.sprintf "%s_%s_%s_%s"
165 funcname t "ee" sign in
166 <:expr< Bitmatch.$lid:call$ $expr$ >>
168 (* Generate the code for a constructor, ie. 'BITSTRING ...'. *)
169 let output_constructor _loc fields =
170 (* This function makes code to raise a Bitmatch.Construct_failure exception
171 * containing a message and the current _loc context.
172 * (Thanks to Bluestorm for suggesting this).
174 let construct_failure _loc msg =
176 Bitmatch.Construct_failure
178 $`str:Loc.file_name _loc$,
179 $`int:Loc.start_line _loc$,
180 $`int:Loc.start_off _loc - Loc.start_bol _loc$)
183 let raise_construct_failure _loc msg =
184 <:expr< raise $construct_failure _loc msg$ >>
187 (* Bitstrings are created like the 'Buffer' module (in fact, using
188 * the Buffer module), by appending snippets to a growing buffer.
189 * This is reasonably efficient and avoids a lot of garbage.
191 let buffer = gensym "buffer" in
193 (* General exception which is raised inside the constructor functions
194 * when an int expression is out of range at runtime.
196 let exn = gensym "exn" in
197 let exn_used = ref false in
199 (* Convert each field to a simple bitstring-generating expression. *)
200 let fields = List.map (
202 let fexpr = P.get_expr field in
203 let flen = P.get_length field in
204 let endian = P.get_endian field in
205 let signed = P.get_signed field in
206 let t = P.get_type field in
207 let _loc = P.get_location field in
208 let offset = P.get_offset field in
210 let fail = locfail _loc in
212 (* offset() not supported in constructors. Implementation of
213 * forward-only offsets is fairly straightforward: we would
214 * need to just calculate the length of padding here and add
215 * it to what has been constructed. For general offsets,
216 * including going backwards, that would require a rethink in
217 * how we construct bitstrings.
219 if offset <> None then
220 fail "offset expressions are not supported in BITSTRING constructors";
222 (* Is flen an integer constant? If so, what is it? This
223 * is very simple-minded and only detects simple constants.
225 let flen_is_const = expr_is_constant flen in
227 let int_construct_const (i, endian, signed) =
228 build_bitmatch_call _loc "construct" (Some i) endian signed in
229 let int_construct (endian, signed) =
230 build_bitmatch_call _loc "construct" None endian signed in
233 match t, flen_is_const with
234 (* Common case: int field, constant flen.
236 * Range checks are done inside the construction function
237 * because that's a lot simpler w.r.t. types. It might
238 * be better to move them here. XXX
240 | P.Int, Some i when i > 0 && i <= 64 ->
241 let construct_fn = int_construct_const (i,endian,signed) in
245 $construct_fn$ $lid:buffer$ $fexpr$ $`int:i$ $lid:exn$
249 fail "length of int field must be [1..64]"
251 (* Int field, non-constant length. We need to perform a runtime
252 * test to ensure the length is [1..64].
254 * Range checks are done inside the construction function
255 * because that's a lot simpler w.r.t. types. It might
256 * be better to move them here. XXX
259 let construct_fn = int_construct (endian,signed) in
263 if $flen$ >= 1 && $flen$ <= 64 then
264 $construct_fn$ $lid:buffer$ $fexpr$ $flen$ $lid:exn$
266 $raise_construct_failure _loc "length of int field must be [1..64]"$
269 (* String, constant length > 0, must be a multiple of 8. *)
270 | P.String, Some i when i > 0 && i land 7 = 0 ->
271 let bs = gensym "bs" in
274 let $lid:bs$ = $fexpr$ in
275 if String.length $lid:bs$ = $`int:j$ then
276 Bitmatch.construct_string $lid:buffer$ $lid:bs$
278 $raise_construct_failure _loc "length of string does not match declaration"$
281 (* String, constant length -1, means variable length string
284 | P.String, Some (-1) ->
285 <:expr< Bitmatch.construct_string $lid:buffer$ $fexpr$ >>
287 (* String, constant length = 0 is probably an error, and so is
290 | P.String, Some _ ->
291 fail "length of string must be > 0 and a multiple of 8, or the special value -1"
293 (* String, non-constant length.
294 * We check at runtime that the length is > 0, a multiple of 8,
295 * and matches the declared length.
298 let bslen = gensym "bslen" in
299 let bs = gensym "bs" in
301 let $lid:bslen$ = $flen$ in
302 if $lid:bslen$ > 0 then (
303 if $lid:bslen$ land 7 = 0 then (
304 let $lid:bs$ = $fexpr$ in
305 if String.length $lid:bs$ = ($lid:bslen$ lsr 3) then
306 Bitmatch.construct_string $lid:buffer$ $lid:bs$
308 $raise_construct_failure _loc "length of string does not match declaration"$
310 $raise_construct_failure _loc "length of string must be a multiple of 8"$
312 $raise_construct_failure _loc "length of string must be > 0"$
315 (* Bitstring, constant length >= 0. *)
316 | P.Bitstring, Some i when i >= 0 ->
317 let bs = gensym "bs" in
319 let $lid:bs$ = $fexpr$ in
320 if Bitmatch.bitstring_length $lid:bs$ = $`int:i$ then
321 Bitmatch.construct_bitstring $lid:buffer$ $lid:bs$
323 $raise_construct_failure _loc "length of bitstring does not match declaration"$
326 (* Bitstring, constant length -1, means variable length bitstring
329 | P.Bitstring, Some (-1) ->
330 <:expr< Bitmatch.construct_bitstring $lid:buffer$ $fexpr$ >>
332 (* Bitstring, constant length < -1 is an error. *)
333 | P.Bitstring, Some _ ->
334 fail "length of bitstring must be >= 0 or the special value -1"
336 (* Bitstring, non-constant length.
337 * We check at runtime that the length is >= 0 and matches
338 * the declared length.
340 | P.Bitstring, None ->
341 let bslen = gensym "bslen" in
342 let bs = gensym "bs" in
344 let $lid:bslen$ = $flen$ in
345 if $lid:bslen$ >= 0 then (
346 let $lid:bs$ = $fexpr$ in
347 if Bitmatch.bitstring_length $lid:bs$ = $lid:bslen$ then
348 Bitmatch.construct_bitstring $lid:buffer$ $lid:bs$
350 $raise_construct_failure _loc "length of bitstring does not match declaration"$
352 $raise_construct_failure _loc "length of bitstring must be > 0"$
357 (* Create the final bitstring. Start by creating an empty buffer
358 * and then evaluate each expression above in turn which will
359 * append some more to the bitstring buffer. Finally extract
362 * XXX We almost have enough information to be able to guess
363 * a good initial size for the buffer.
367 | [] -> <:expr< [] >>
368 | h::t -> List.fold_left (fun h t -> <:expr< $h$; $t$ >>) h t in
372 let $lid:buffer$ = Bitmatch.Buffer.create () in
374 Bitmatch.Buffer.contents $lid:buffer$
379 let $lid:exn$ = $construct_failure _loc "value out of range"$ in
385 (* Generate the code for a bitmatch statement. '_loc' is the
386 * location, 'bs' is the bitstring parameter, 'cases' are
387 * the list of cases to test against.
389 let output_bitmatch _loc bs cases =
390 let data = gensym "data" and off = gensym "off" and len = gensym "len" in
391 let result = gensym "result" in
393 (* This generates the field extraction code for each
394 * field in a single case. There must be enough remaining data
395 * in the bitstring to satisfy the field.
397 * As we go through the fields, symbols 'data', 'off' and 'len'
398 * track our position and remaining length in the bitstring.
400 * The whole thing is a lot of nested 'if' statements. Code
401 * is generated from the inner-most (last) field outwards.
403 let rec output_field_extraction inner = function
406 let fpatt = P.get_patt field in
407 let flen = P.get_length field in
408 let endian = P.get_endian field in
409 let signed = P.get_signed field in
410 let t = P.get_type field in
411 let _loc = P.get_location field in
412 let offset = P.get_offset field in
414 let fail = locfail _loc in
416 (* Is flen (field len) an integer constant? If so, what is it?
417 * This will be [Some i] if it's a constant or [None] if it's
418 * non-constant or we couldn't determine.
420 let flen_is_const = expr_is_constant flen in
422 let int_extract_const (i, endian, signed) =
423 build_bitmatch_call _loc "extract" (Some i) endian signed in
424 let int_extract (endian, signed) =
425 build_bitmatch_call _loc "extract" None endian signed in
428 match t, flen_is_const with
429 (* Common case: int field, constant flen *)
430 | P.Int, Some i when i > 0 && i <= 64 ->
431 let extract_fn = int_extract_const (i,endian,signed) in
432 let v = gensym "val" in
434 if $lid:len$ >= $`int:i$ then (
435 let $lid:v$, $lid:off$, $lid:len$ =
436 $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $`int:i$ in
437 match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
442 fail "length of int field must be [1..64]"
444 (* Int field, non-const flen. We have to test the range of
445 * the field at runtime. If outside the range it's a no-match
449 let extract_fn = int_extract (endian,signed) in
450 let v = gensym "val" in
452 if $flen$ >= 1 && $flen$ <= 64 && $flen$ <= $lid:len$ then (
453 let $lid:v$, $lid:off$, $lid:len$ =
454 $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $flen$ in
455 match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
459 (* String, constant flen > 0. *)
460 | P.String, Some i when i > 0 && i land 7 = 0 ->
461 let bs = gensym "bs" in
463 if $lid:len$ >= $`int:i$ then (
464 let $lid:bs$, $lid:off$, $lid:len$ =
465 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
467 match Bitmatch.string_of_bitstring $lid:bs$ with
468 | $fpatt$ when true -> $inner$
473 (* String, constant flen = -1, means consume all the
476 | P.String, Some i when i = -1 ->
477 let bs = gensym "bs" in
479 let $lid:bs$, $lid:off$, $lid:len$ =
480 Bitmatch.extract_remainder $lid:data$ $lid:off$ $lid:len$ in
481 match Bitmatch.string_of_bitstring $lid:bs$ with
482 | $fpatt$ when true -> $inner$
486 | P.String, Some _ ->
487 fail "length of string must be > 0 and a multiple of 8, or the special value -1"
489 (* String field, non-const flen. We check the flen is > 0
490 * and a multiple of 8 (-1 is not allowed here), at runtime.
493 let bs = gensym "bs" in
495 if $flen$ >= 0 && $flen$ <= $lid:len$
496 && $flen$ land 7 = 0 then (
497 let $lid:bs$, $lid:off$, $lid:len$ =
498 Bitmatch.extract_bitstring
499 $lid:data$ $lid:off$ $lid:len$ $flen$ in
500 match Bitmatch.string_of_bitstring $lid:bs$ with
501 | $fpatt$ when true -> $inner$
506 (* Bitstring, constant flen >= 0.
507 * At the moment all we can do is assign the bitstring to an
510 | P.Bitstring, Some i when i >= 0 ->
513 | <:patt< $lid:ident$ >> -> ident
514 | <:patt< _ >> -> "_"
516 fail "cannot compare a bitstring to a constant" in
518 if $lid:len$ >= $`int:i$ then (
519 let $lid:ident$, $lid:off$, $lid:len$ =
520 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
526 (* Bitstring, constant flen = -1, means consume all the
529 | P.Bitstring, Some i when i = -1 ->
532 | <:patt< $lid:ident$ >> -> ident
533 | <:patt< _ >> -> "_"
535 fail "cannot compare a bitstring to a constant" in
537 let $lid:ident$, $lid:off$, $lid:len$ =
538 Bitmatch.extract_remainder $lid:data$ $lid:off$ $lid:len$ in
542 | P.Bitstring, Some _ ->
543 fail "length of bitstring must be >= 0 or the special value -1"
545 (* Bitstring field, non-const flen. We check the flen is >= 0
546 * (-1 is not allowed here) at runtime.
548 | P.Bitstring, None ->
551 | <:patt< $lid:ident$ >> -> ident
552 | <:patt< _ >> -> "_"
554 fail "cannot compare a bitstring to a constant" in
556 if $flen$ >= 0 && $flen$ <= $lid:len$ then (
557 let $lid:ident$, $lid:off$, $lid:len$ =
558 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
565 (* Computed offset: only offsets forward are supported.
567 * We try hard to optimize this based on what we know. Are
568 * we at a predictable offset now? (Look at the outer 'fields'
569 * list and see if they all have constant field length starting
570 * at some constant offset). Is this offset constant?
572 * Based on this we can do a lot of the computation at
573 * compile time, or defer it to runtime only if necessary.
575 * In all cases, the off and len fields get updated.
579 | None -> expr (* common case: there was no offset expression *)
580 | Some offset_expr ->
581 (* This will be [Some i] if offset is a constant expression
582 * or [None] if it's a non-constant.
584 let requested_offset = expr_is_constant offset_expr in
586 (* This will be [Some i] if our current offset is known
587 * at compile time, or [None] if we can't determine it.
590 let has_constant_offset field =
591 match P.get_offset field with
594 match expr_is_constant expr with
598 let get_constant_offset field =
599 match P.get_offset field with
600 | None -> assert false
602 match expr_is_constant expr with
603 | None -> assert false
607 let has_constant_len field =
608 match expr_is_constant (P.get_length field) with
610 | Some i when i > 0 -> true
613 let get_constant_len field =
614 match expr_is_constant (P.get_length field) with
615 | None -> assert false
616 | Some i when i > 0 -> i
617 | Some _ -> assert false
620 let rec loop = function
621 (* first field has constant offset 0 *)
623 (* field with constant offset & length *)
625 when has_constant_offset field &&
626 has_constant_len field ->
627 Some (get_constant_offset field + get_constant_len field)
628 (* field with no offset & constant length *)
630 when P.get_offset field = None &&
631 has_constant_len field ->
632 (match loop fields with
634 | Some offset -> Some (offset + get_constant_len field))
635 (* else, can't work out the offset *)
640 (* Look at the current offset and requested offset cases and
641 * determine what code to generate.
643 match current_offset, requested_offset with
644 (* This is the good case: both the current offset and
645 * the requested offset are constant, so we can remove
646 * almost all the runtime checks.
648 | Some current_offset, Some requested_offset ->
649 let move = requested_offset - current_offset in
651 fail (sprintf "requested offset is less than the current offset (%d < %d)" requested_offset current_offset);
652 (* Add some code to move the offset and length by a
653 * constant amount, and a runtime test that len >= 0
654 * (XXX possibly the runtime test is unnecessary?)
657 let $lid:off$ = $lid:off$ + $`int:move$ in
658 let $lid:len$ = $lid:len$ - $`int:move$ in
659 if $lid:len$ >= 0 then $expr$
661 (* In any other case, we need to use runtime checks.
663 * XXX It's not clear if a backwards move detected at runtime
664 * is merely a match failure, or a runtime error. At the
665 * moment it's just a match failure since bitmatch generally
666 * doesn't raise runtime errors.
669 let move = gensym "move" in
671 let $lid:move$ = $offset_expr$ - $lid:off$ in
672 if $lid:move$ >= 0 then (
673 let $lid:off$ = $lid:off$ + $lid:move$ in
674 let $lid:len$ = $lid:len$ - $lid:move$ in
675 if $lid:len$ >= 0 then $expr$
677 >> in (* end of computed offset code *)
679 (* Emit extra debugging code. *)
681 if not debug then expr else (
682 let field = P.string_of_pattern_field field in
685 if !Bitmatch.debug then (
686 Printf.eprintf "PA_BITMATCH: TEST:\n";
687 Printf.eprintf " %s\n" $str:field$;
688 Printf.eprintf " off %d len %d\n%!" $lid:off$ $lid:len$;
689 (*Bitmatch.hexdump_bitstring stderr
690 ($lid:data$,$lid:off$,$lid:len$);*)
696 output_field_extraction expr fields
699 (* Convert each case in the match. *)
700 let cases = List.map (
701 fun (fields, bind, whenclause, code) ->
702 let inner = <:expr< $lid:result$ := Some ($code$); raise Exit >> in
704 match whenclause with
706 <:expr< if $whenclause$ then $inner$ >>
712 let $lid:name$ = ($lid:data$, $lid:off$, $lid:len$) in
716 output_field_extraction inner (List.rev fields)
719 (* Join them into a single expression.
721 * Don't do it with a normal fold_right because that leaves
722 * 'raise Exit; ()' at the end which causes a compiler warning.
723 * Hence a bit of complexity here.
725 * Note that the number of cases is always >= 1 so List.hd is safe.
727 let cases = List.rev cases in
729 List.fold_left (fun base case -> <:expr< $case$ ; $base$ >>)
730 (List.hd cases) (List.tl cases) in
732 (* The final code just wraps the list of cases in a
733 * try/with construct so that each case is tried in
734 * turn until one case matches (that case sets 'result'
735 * and raises 'Exit' to leave the whole statement).
736 * If result isn't set by the end then we will raise
737 * Match_failure with the location of the bitmatch
738 * statement in the original code.
740 let loc_fname = Loc.file_name _loc in
741 let loc_line = string_of_int (Loc.start_line _loc) in
742 let loc_char = string_of_int (Loc.start_off _loc - Loc.start_bol _loc) in
745 let ($lid:data$, $lid:off$, $lid:len$) = $bs$ in
746 let $lid:result$ = ref None in
750 match ! $lid:result$ with
752 | None -> raise (Match_failure ($str:loc_fname$,
753 $int:loc_line$, $int:loc_char$))
756 (* Add a named pattern. *)
757 let add_named_pattern _loc name pattern =
758 Hashtbl.add pattern_hash name pattern
760 (* Expand a named pattern from the pattern_hash. *)
761 let expand_named_pattern _loc name =
762 try Hashtbl.find pattern_hash name
764 locfail _loc (sprintf "named pattern not found: %s" name)
766 (* Add named patterns from a file. See the documentation on the
767 * directory search path in bitmatch_persistent.mli
769 let load_patterns_from_file _loc filename =
771 if Filename.is_relative filename && Filename.is_implicit filename then (
772 (* Try current directory. *)
775 (* Try OCaml library directory. *)
776 try open_in (Filename.concat Bitmatch_config.ocamllibdir filename)
777 with exn -> Loc.raise _loc exn
780 with exn -> Loc.raise _loc exn
782 let names = ref [] in
785 let name = P.named_from_channel chan in
786 names := name :: !names
789 with End_of_file -> ()
792 let names = List.rev !names in
795 | name, P.Pattern patt ->
797 locfail _loc (sprintf "pattern %s: no fields" name);
798 add_named_pattern _loc name patt
799 | _, P.Constructor _ -> () (* just ignore these for now *)
803 GLOBAL: expr str_item;
805 (* Qualifiers are a list of identifiers ("string", "bigendian", etc.)
806 * followed by an optional expression (used in certain cases). Note
807 * that we are careful not to declare any explicit reserved words.
812 e = OPT [ "("; e = expr; ")" -> e ] -> (q, e) ]
816 (* Field used in the bitmatch operator (a pattern). This can actually
817 * return multiple fields, in the case where the 'field' is a named
821 [ fpatt = patt; ":"; len = expr LEVEL "top";
822 qs = OPT [ ":"; qs = qualifiers -> qs ] ->
823 let field = P.create_pattern_field _loc in
824 let field = P.set_patt field fpatt in
825 let field = P.set_length field len in
826 [parse_field _loc field qs] (* Normal, single field. *)
827 | ":"; name = LIDENT ->
828 expand_named_pattern _loc name (* Named -> list of fields. *)
832 (* Case inside bitmatch operator. *)
835 fields = LIST0 patt_field SEP ";";
842 [ fields = patt_fields;
843 bind = OPT [ "as"; name = LIDENT -> name ];
844 whenclause = OPT [ "when"; e = expr -> e ]; "->";
846 (fields, bind, whenclause, code)
850 (* Field used in the BITSTRING constructor (an expression). *)
852 [ fexpr = expr LEVEL "top"; ":"; len = expr LEVEL "top";
853 qs = OPT [ ":"; qs = qualifiers -> qs ] ->
854 let field = P.create_constructor_field _loc in
855 let field = P.set_expr field fexpr in
856 let field = P.set_length field len in
857 parse_field _loc field qs
863 fields = LIST0 constr_field SEP ";";
869 (* 'bitmatch' expressions. *)
872 bs = expr; "with"; OPT "|";
873 cases = LIST1 patt_case SEP "|" ->
874 output_bitmatch _loc bs cases
879 fields = constr_fields ->
880 output_constructor _loc fields
884 (* Named persistent patterns.
886 * NB: Currently only allowed at the top level. We can probably lift
887 * this restriction later if necessary. We only deal with patterns
888 * at the moment, not constructors, but the infrastructure to do
889 * constructors is in place.
891 str_item: LEVEL "top" [
893 name = LIDENT; "="; fields = patt_fields ->
894 add_named_pattern _loc name fields;
895 (* The statement disappears, but we still need a str_item so ... *)
897 | "open"; "bitmatch"; filename = STRING ->
898 load_patterns_from_file _loc filename;