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 (* These symbols are used through the generated code to record our
391 * current position within the bitstring:
393 * data - original bitstring data (string, never changes)
395 * off - current offset within data (int, increments as we move through
397 * len - current remaining length within data (int, decrements as
398 * we move through the bitstring)
400 * original_off - saved offset at the start of the match (never changes)
401 * original_len - saved length at the start of the match (never changes)
403 let data = gensym "data"
404 and off = gensym "off"
405 and len = gensym "len"
406 and original_off = gensym "original_off"
407 and original_len = gensym "original_len"
408 (* This is where the result will be stored (a reference). *)
409 and result = gensym "result" in
411 (* This generates the field extraction code for each
412 * field in a single case. There must be enough remaining data
413 * in the bitstring to satisfy the field.
415 * As we go through the fields, symbols 'data', 'off' and 'len'
416 * track our position and remaining length in the bitstring.
418 * The whole thing is a lot of nested 'if'/'match' statements.
419 * Code is generated from the inner-most (last) field outwards.
421 let rec output_field_extraction inner = function
424 let fpatt = P.get_patt field in
425 let flen = P.get_length field in
426 let endian = P.get_endian field in
427 let signed = P.get_signed field in
428 let t = P.get_type field in
429 let _loc = P.get_location field in
430 let offset = P.get_offset field in
432 let fail = locfail _loc in
434 (* Is flen (field len) an integer constant? If so, what is it?
435 * This will be [Some i] if it's a constant or [None] if it's
436 * non-constant or we couldn't determine.
438 let flen_is_const = expr_is_constant flen in
440 let int_extract_const (i, endian, signed) =
441 build_bitmatch_call _loc "extract" (Some i) endian signed in
442 let int_extract (endian, signed) =
443 build_bitmatch_call _loc "extract" None endian signed in
446 match t, flen_is_const with
447 (* Common case: int field, constant flen *)
448 | P.Int, Some i when i > 0 && i <= 64 ->
449 let extract_fn = int_extract_const (i,endian,signed) in
450 let v = gensym "val" in
452 if $lid:len$ >= $`int:i$ then (
453 let $lid:v$, $lid:off$, $lid:len$ =
454 $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $`int:i$ in
455 match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
460 fail "length of int field must be [1..64]"
462 (* Int field, non-const flen. We have to test the range of
463 * the field at runtime. If outside the range it's a no-match
467 let extract_fn = int_extract (endian,signed) in
468 let v = gensym "val" in
470 if $flen$ >= 1 && $flen$ <= 64 && $flen$ <= $lid:len$ then (
471 let $lid:v$, $lid:off$, $lid:len$ =
472 $extract_fn$ $lid:data$ $lid:off$ $lid:len$ $flen$ in
473 match $lid:v$ with $fpatt$ when true -> $inner$ | _ -> ()
477 (* String, constant flen > 0. *)
478 | P.String, Some i when i > 0 && i land 7 = 0 ->
479 let bs = gensym "bs" in
481 if $lid:len$ >= $`int:i$ then (
482 let $lid:bs$, $lid:off$, $lid:len$ =
483 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
485 match Bitmatch.string_of_bitstring $lid:bs$ with
486 | $fpatt$ when true -> $inner$
491 (* String, constant flen = -1, means consume all the
494 | P.String, Some i when i = -1 ->
495 let bs = gensym "bs" in
497 let $lid:bs$, $lid:off$, $lid:len$ =
498 Bitmatch.extract_remainder $lid:data$ $lid:off$ $lid:len$ in
499 match Bitmatch.string_of_bitstring $lid:bs$ with
500 | $fpatt$ when true -> $inner$
504 | P.String, Some _ ->
505 fail "length of string must be > 0 and a multiple of 8, or the special value -1"
507 (* String field, non-const flen. We check the flen is > 0
508 * and a multiple of 8 (-1 is not allowed here), at runtime.
511 let bs = gensym "bs" in
513 if $flen$ >= 0 && $flen$ <= $lid:len$
514 && $flen$ land 7 = 0 then (
515 let $lid:bs$, $lid:off$, $lid:len$ =
516 Bitmatch.extract_bitstring
517 $lid:data$ $lid:off$ $lid:len$ $flen$ in
518 match Bitmatch.string_of_bitstring $lid:bs$ with
519 | $fpatt$ when true -> $inner$
524 (* Bitstring, constant flen >= 0.
525 * At the moment all we can do is assign the bitstring to an
528 | P.Bitstring, Some i when i >= 0 ->
531 | <:patt< $lid:ident$ >> -> ident
532 | <:patt< _ >> -> "_"
534 fail "cannot compare a bitstring to a constant" in
536 if $lid:len$ >= $`int:i$ then (
537 let $lid:ident$, $lid:off$, $lid:len$ =
538 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
544 (* Bitstring, constant flen = -1, means consume all the
547 | P.Bitstring, Some i when i = -1 ->
550 | <:patt< $lid:ident$ >> -> ident
551 | <:patt< _ >> -> "_"
553 fail "cannot compare a bitstring to a constant" in
555 let $lid:ident$, $lid:off$, $lid:len$ =
556 Bitmatch.extract_remainder $lid:data$ $lid:off$ $lid:len$ in
560 | P.Bitstring, Some _ ->
561 fail "length of bitstring must be >= 0 or the special value -1"
563 (* Bitstring field, non-const flen. We check the flen is >= 0
564 * (-1 is not allowed here) at runtime.
566 | P.Bitstring, None ->
569 | <:patt< $lid:ident$ >> -> ident
570 | <:patt< _ >> -> "_"
572 fail "cannot compare a bitstring to a constant" in
574 if $flen$ >= 0 && $flen$ <= $lid:len$ then (
575 let $lid:ident$, $lid:off$, $lid:len$ =
576 Bitmatch.extract_bitstring $lid:data$ $lid:off$ $lid:len$
583 (* Computed offset: only offsets forward are supported.
585 * We try hard to optimize this based on what we know. Are
586 * we at a predictable offset now? (Look at the outer 'fields'
587 * list and see if they all have constant field length starting
588 * at some constant offset). Is this offset constant?
590 * Based on this we can do a lot of the computation at
591 * compile time, or defer it to runtime only if necessary.
593 * In all cases, the off and len fields get updated.
597 | None -> expr (* common case: there was no offset expression *)
598 | Some offset_expr ->
599 (* This will be [Some i] if offset is a constant expression
600 * or [None] if it's a non-constant.
602 let requested_offset = expr_is_constant offset_expr in
604 (* This will be [Some i] if our current offset is known
605 * at compile time, or [None] if we can't determine it.
608 let has_constant_offset field =
609 match P.get_offset field with
612 match expr_is_constant expr with
616 let get_constant_offset field =
617 match P.get_offset field with
618 | None -> assert false
620 match expr_is_constant expr with
621 | None -> assert false
625 let has_constant_len field =
626 match expr_is_constant (P.get_length field) with
628 | Some i when i > 0 -> true
631 let get_constant_len field =
632 match expr_is_constant (P.get_length field) with
633 | None -> assert false
634 | Some i when i > 0 -> i
635 | Some _ -> assert false
638 let rec loop = function
639 (* first field has constant offset 0 *)
641 (* field with constant offset & length *)
643 when has_constant_offset field &&
644 has_constant_len field ->
645 Some (get_constant_offset field + get_constant_len field)
646 (* field with no offset & constant length *)
648 when P.get_offset field = None &&
649 has_constant_len field ->
650 (match loop fields with
652 | Some offset -> Some (offset + get_constant_len field))
653 (* else, can't work out the offset *)
658 (* Look at the current offset and requested offset cases and
659 * determine what code to generate.
661 match current_offset, requested_offset with
662 (* This is the good case: both the current offset and
663 * the requested offset are constant, so we can remove
664 * almost all the runtime checks.
666 | Some current_offset, Some requested_offset ->
667 let move = requested_offset - current_offset in
669 fail (sprintf "requested offset is less than the current offset (%d < %d)" requested_offset current_offset);
670 (* Add some code to move the offset and length by a
671 * constant amount, and a runtime test that len >= 0
672 * (XXX possibly the runtime test is unnecessary?)
675 let $lid:off$ = $lid:off$ + $`int:move$ in
676 let $lid:len$ = $lid:len$ - $`int:move$ in
677 if $lid:len$ >= 0 then $expr$
679 (* In any other case, we need to use runtime checks.
681 * XXX It's not clear if a backwards move detected at runtime
682 * is merely a match failure, or a runtime error. At the
683 * moment it's just a match failure since bitmatch generally
684 * doesn't raise runtime errors.
687 let move = gensym "move" in
690 $offset_expr$ - ($lid:off$ - $lid:original_off$) in
691 if $lid:move$ >= 0 then (
692 let $lid:off$ = $lid:off$ + $lid:move$ in
693 let $lid:len$ = $lid:len$ - $lid:move$ in
694 if $lid:len$ >= 0 then $expr$
696 >> in (* end of computed offset code *)
698 (* Emit extra debugging code. *)
700 if not debug then expr else (
701 let field = P.string_of_pattern_field field in
704 if !Bitmatch.debug then (
705 Printf.eprintf "PA_BITMATCH: TEST:\n";
706 Printf.eprintf " %s\n" $str:field$;
707 Printf.eprintf " off %d len %d\n%!" $lid:off$ $lid:len$;
708 (*Bitmatch.hexdump_bitstring stderr
709 ($lid:data$,$lid:off$,$lid:len$);*)
715 output_field_extraction expr fields
718 (* Convert each case in the match. *)
719 let cases = List.map (
720 fun (fields, bind, whenclause, code) ->
721 let inner = <:expr< $lid:result$ := Some ($code$); raise Exit >> in
723 match whenclause with
725 <:expr< if $whenclause$ then $inner$ >>
731 let $lid:name$ = ($lid:data$, $lid:off$, $lid:len$) in
735 output_field_extraction inner (List.rev fields)
738 (* Join them into a single expression.
740 * Don't do it with a normal fold_right because that leaves
741 * 'raise Exit; ()' at the end which causes a compiler warning.
742 * Hence a bit of complexity here.
744 * Note that the number of cases is always >= 1 so List.hd is safe.
746 let cases = List.rev cases in
748 List.fold_left (fun base case -> <:expr< $case$ ; $base$ >>)
749 (List.hd cases) (List.tl cases) in
751 (* The final code just wraps the list of cases in a
752 * try/with construct so that each case is tried in
753 * turn until one case matches (that case sets 'result'
754 * and raises 'Exit' to leave the whole statement).
755 * If result isn't set by the end then we will raise
756 * Match_failure with the location of the bitmatch
757 * statement in the original code.
759 let loc_fname = Loc.file_name _loc in
760 let loc_line = string_of_int (Loc.start_line _loc) in
761 let loc_char = string_of_int (Loc.start_off _loc - Loc.start_bol _loc) in
764 (* Note we save the original offset/length at the start of the match
765 * in 'original_off'/'original_len' symbols. 'data' never changes.
767 let ($lid:data$, $lid:original_off$, $lid:original_len$) = $bs$ in
768 let $lid:off$ = $lid:original_off$ and $lid:len$ = $lid:original_len$ in
769 let $lid:result$ = ref None in
773 match ! $lid:result$ with
775 | None -> raise (Match_failure ($str:loc_fname$,
776 $int:loc_line$, $int:loc_char$))
779 (* Add a named pattern. *)
780 let add_named_pattern _loc name pattern =
781 Hashtbl.add pattern_hash name pattern
783 (* Expand a named pattern from the pattern_hash. *)
784 let expand_named_pattern _loc name =
785 try Hashtbl.find pattern_hash name
787 locfail _loc (sprintf "named pattern not found: %s" name)
789 (* Add named patterns from a file. See the documentation on the
790 * directory search path in bitmatch_persistent.mli
792 let load_patterns_from_file _loc filename =
794 if Filename.is_relative filename && Filename.is_implicit filename then (
795 (* Try current directory. *)
798 (* Try OCaml library directory. *)
799 try open_in (Filename.concat Bitmatch_config.ocamllibdir filename)
800 with exn -> Loc.raise _loc exn
803 with exn -> Loc.raise _loc exn
805 let names = ref [] in
808 let name = P.named_from_channel chan in
809 names := name :: !names
812 with End_of_file -> ()
815 let names = List.rev !names in
818 | name, P.Pattern patt ->
820 locfail _loc (sprintf "pattern %s: no fields" name);
821 add_named_pattern _loc name patt
822 | _, P.Constructor _ -> () (* just ignore these for now *)
826 GLOBAL: expr str_item;
828 (* Qualifiers are a list of identifiers ("string", "bigendian", etc.)
829 * followed by an optional expression (used in certain cases). Note
830 * that we are careful not to declare any explicit reserved words.
835 e = OPT [ "("; e = expr; ")" -> e ] -> (q, e) ]
839 (* Field used in the bitmatch operator (a pattern). This can actually
840 * return multiple fields, in the case where the 'field' is a named
844 [ fpatt = patt; ":"; len = expr LEVEL "top";
845 qs = OPT [ ":"; qs = qualifiers -> qs ] ->
846 let field = P.create_pattern_field _loc in
847 let field = P.set_patt field fpatt in
848 let field = P.set_length field len in
849 [parse_field _loc field qs] (* Normal, single field. *)
850 | ":"; name = LIDENT ->
851 expand_named_pattern _loc name (* Named -> list of fields. *)
855 (* Case inside bitmatch operator. *)
858 fields = LIST0 patt_field SEP ";";
865 [ fields = patt_fields;
866 bind = OPT [ "as"; name = LIDENT -> name ];
867 whenclause = OPT [ "when"; e = expr -> e ]; "->";
869 (fields, bind, whenclause, code)
873 (* Field used in the BITSTRING constructor (an expression). *)
875 [ fexpr = expr LEVEL "top"; ":"; len = expr LEVEL "top";
876 qs = OPT [ ":"; qs = qualifiers -> qs ] ->
877 let field = P.create_constructor_field _loc in
878 let field = P.set_expr field fexpr in
879 let field = P.set_length field len in
880 parse_field _loc field qs
886 fields = LIST0 constr_field SEP ";";
892 (* 'bitmatch' expressions. *)
895 bs = expr; "with"; OPT "|";
896 cases = LIST1 patt_case SEP "|" ->
897 output_bitmatch _loc bs cases
902 fields = constr_fields ->
903 output_constructor _loc fields
907 (* Named persistent patterns.
909 * NB: Currently only allowed at the top level. We can probably lift
910 * this restriction later if necessary. We only deal with patterns
911 * at the moment, not constructors, but the infrastructure to do
912 * constructors is in place.
914 str_item: LEVEL "top" [
916 name = LIDENT; "="; fields = patt_fields ->
917 add_named_pattern _loc name fields;
918 (* The statement disappears, but we still need a str_item so ... *)
920 | "open"; "bitmatch"; filename = STRING ->
921 load_patterns_from_file _loc filename;