Clarify licensing for Debian.
[ocaml-bitstring.git] / pa_bitmatch.ml
1 (* Bitmatch syntax extension.
2  * Copyright (C) 2008 Red Hat Inc., Richard W.M. Jones
3  *
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.
9  *
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.
14  *
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
18  *
19  * $Id$
20  *)
21
22 open Printf
23
24 open Camlp4.PreCast
25 open Syntax
26 open Ast
27
28 open Bitmatch
29 module P = Bitmatch_persistent
30
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.
34  *
35  * If this is false then no extra debugging code is emitted.
36  *)
37 let debug = false
38
39 (* Hashtable storing named persistent patterns. *)
40 let pattern_hash : (string, P.pattern) Hashtbl.t = Hashtbl.create 13
41
42 let locfail _loc msg = Loc.raise _loc (Failure msg)
43
44 (* Work out if an expression is an integer constant.
45  *
46  * Returns [Some i] if so (where i is the integer value), else [None].
47  *
48  * Fairly simplistic algorithm: we can only detect simple constant
49  * expressions such as [k], [k+c], [k-c] etc.
50  *)
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);
60                     "mod", (mod)] in
61          (try Some ((List.assoc op ops) a b) with Not_found -> None)
62      | _ -> None)
63   | _ -> None
64
65 (* Generate a fresh, unique symbol each time called. *)
66 let gensym =
67   let i = ref 1000 in
68   fun name ->
69     incr i; let i = !i in
70     sprintf "__pabitmatch_%s_%d" name i
71
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
75
76   let endian_set, signed_set, type_set, offset_set, field =
77     match qs with
78     | None -> (false, false, false, false, field)
79     | Some qs ->
80         let check already_set msg = if already_set then fail msg in
81         let apply_qualifier
82             (endian_set, signed_set, type_set, offset_set, field) =
83           function
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)
88           | "endian", None ->
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)
94           | "offset", None ->
95               fail "qualifier 'offset' should be followed by an expression"
96           | s, Some _ ->
97               fail (s ^ ": unknown qualifier, or qualifier should not be followed by an expression")
98           | qual, None ->
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)
118               ) else
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
121
122   (* If type is set to string or bitstring then endianness and
123    * signedness qualifiers are meaningless and must not be set.
124    *)
125   let () =
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
129
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
134
135   field
136
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.
142      *)
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"
151       | Some 32 -> "int32"
152       | _ -> "int64" in
153       let sign = if signed then "signed" else "unsigned" in
154       match endian with
155       | P.ConstantEndian constant ->
156           let endianness = match constant with
157           | BigEndian -> "be"
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$ >>
167
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).
173    *)
174   let construct_failure _loc msg =
175     <:expr<
176       Bitmatch.Construct_failure
177         ($`str:msg$,
178          $`str:Loc.file_name _loc$,
179          $`int:Loc.start_line _loc$,
180          $`int:Loc.start_off _loc - Loc.start_bol _loc$)
181     >>
182   in
183   let raise_construct_failure _loc msg =
184     <:expr< raise $construct_failure _loc msg$ >>
185   in
186
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.
190    *)
191   let buffer = gensym "buffer" in
192
193   (* General exception which is raised inside the constructor functions
194    * when an int expression is out of range at runtime.
195    *)
196   let exn = gensym "exn" in
197   let exn_used = ref false in
198
199   (* Convert each field to a simple bitstring-generating expression. *)
200   let fields = List.map (
201     fun field ->
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
209
210       let fail = locfail _loc in
211
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.
218        *)
219       if offset <> None then
220         fail "offset expressions are not supported in BITSTRING constructors";
221
222       (* Is flen an integer constant?  If so, what is it?  This
223        * is very simple-minded and only detects simple constants.
224        *)
225       let flen_is_const = expr_is_constant flen in
226
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
231
232       let expr =
233         match t, flen_is_const with
234         (* Common case: int field, constant flen.
235          *
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
239          *)
240         | P.Int, Some i when i > 0 && i <= 64 ->
241             let construct_fn = int_construct_const (i,endian,signed) in
242             exn_used := true;
243
244             <:expr<
245               $construct_fn$ $lid:buffer$ $fexpr$ $`int:i$ $lid:exn$
246             >>
247
248         | P.Int, Some _ ->
249             fail "length of int field must be [1..64]"
250
251         (* Int field, non-constant length.  We need to perform a runtime
252          * test to ensure the length is [1..64].
253          *
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
257          *)
258         | P.Int, None ->
259             let construct_fn = int_construct (endian,signed) in
260             exn_used := true;
261
262             <:expr<
263               if $flen$ >= 1 && $flen$ <= 64 then
264                 $construct_fn$ $lid:buffer$ $fexpr$ $flen$ $lid:exn$
265               else
266                 $raise_construct_failure _loc "length of int field must be [1..64]"$
267             >>
268
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
272             let j = i lsr 3 in
273             <:expr<
274               let $lid:bs$ = $fexpr$ in
275               if String.length $lid:bs$ = $`int:j$ then
276                 Bitmatch.construct_string $lid:buffer$ $lid:bs$
277               else
278                 $raise_construct_failure _loc "length of string does not match declaration"$
279             >>
280
281         (* String, constant length -1, means variable length string
282          * with no checks.
283          *)
284         | P.String, Some (-1) ->
285             <:expr< Bitmatch.construct_string $lid:buffer$ $fexpr$ >>
286
287         (* String, constant length = 0 is probably an error, and so is
288          * any other value.
289          *)
290         | P.String, Some _ ->
291             fail "length of string must be > 0 and a multiple of 8, or the special value -1"
292
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.
296          *)
297         | P.String, None ->
298             let bslen = gensym "bslen" in
299             let bs = gensym "bs" in
300             <:expr<
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$
307                   else
308                     $raise_construct_failure _loc "length of string does not match declaration"$
309                 ) else
310                   $raise_construct_failure _loc "length of string must be a multiple of 8"$
311               ) else
312                 $raise_construct_failure _loc "length of string must be > 0"$
313             >>
314
315         (* Bitstring, constant length >= 0. *)
316         | P.Bitstring, Some i when i >= 0 ->
317             let bs = gensym "bs" in
318             <:expr<
319               let $lid:bs$ = $fexpr$ in
320               if Bitmatch.bitstring_length $lid:bs$ = $`int:i$ then
321                 Bitmatch.construct_bitstring $lid:buffer$ $lid:bs$
322               else
323                 $raise_construct_failure _loc "length of bitstring does not match declaration"$
324             >>
325
326         (* Bitstring, constant length -1, means variable length bitstring
327          * with no checks.
328          *)
329         | P.Bitstring, Some (-1) ->
330             <:expr< Bitmatch.construct_bitstring $lid:buffer$ $fexpr$ >>
331
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"
335
336         (* Bitstring, non-constant length.
337          * We check at runtime that the length is >= 0 and matches
338          * the declared length.
339          *)
340         | P.Bitstring, None ->
341             let bslen = gensym "bslen" in
342             let bs = gensym "bs" in
343             <:expr<
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$
349                 else
350                   $raise_construct_failure _loc "length of bitstring does not match declaration"$
351               ) else
352                 $raise_construct_failure _loc "length of bitstring must be > 0"$
353             >> in
354       expr
355   ) fields in
356
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
360    * the bitstring.
361    *
362    * XXX We almost have enough information to be able to guess
363    * a good initial size for the buffer.
364    *)
365   let fields =
366     match fields with
367     | [] -> <:expr< [] >>
368     | h::t -> List.fold_left (fun h t -> <:expr< $h$; $t$ >>) h t in
369
370   let expr =
371     <:expr<
372       let $lid:buffer$ = Bitmatch.Buffer.create () in
373       $fields$;
374       Bitmatch.Buffer.contents $lid:buffer$
375     >> in
376
377   if !exn_used then
378     <:expr<
379       let $lid:exn$ = $construct_failure _loc "value out of range"$ in
380       $expr$
381     >>
382   else
383     expr
384
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.
388  *)
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
392
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.
396    *
397    * As we go through the fields, symbols 'data', 'off' and 'len'
398    * track our position and remaining length in the bitstring.
399    *
400    * The whole thing is a lot of nested 'if' statements. Code
401    * is generated from the inner-most (last) field outwards.
402    *)
403   let rec output_field_extraction inner = function
404     | [] -> inner
405     | field :: fields ->
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
413
414         let fail = locfail _loc in
415
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.
419          *)
420         let flen_is_const = expr_is_constant flen in
421
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
426
427         let expr =
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
433               <:expr<
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$ | _ -> ()
438                 )
439               >>
440
441           | P.Int, Some _ ->
442               fail "length of int field must be [1..64]"
443
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
446            * (not an error).
447            *)
448           | P.Int, None ->
449               let extract_fn = int_extract (endian,signed) in
450               let v = gensym "val" in
451               <:expr<
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$ | _ -> ()
456                 )
457               >>
458
459           (* String, constant flen > 0. *)
460           | P.String, Some i when i > 0 && i land 7 = 0 ->
461               let bs = gensym "bs" in
462               <:expr<
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$
466                       $`int:i$ in
467                   match Bitmatch.string_of_bitstring $lid:bs$ with
468                   | $fpatt$ when true -> $inner$
469                   | _ -> ()
470                 )
471               >>
472
473           (* String, constant flen = -1, means consume all the
474            * rest of the input.
475            *)
476           | P.String, Some i when i = -1 ->
477               let bs = gensym "bs" in
478               <:expr<
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$
483                 | _ -> ()
484               >>
485
486           | P.String, Some _ ->
487               fail "length of string must be > 0 and a multiple of 8, or the special value -1"
488
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.
491            *)
492           | P.String, None ->
493               let bs = gensym "bs" in
494               <:expr<
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$
502                     | _ -> ()
503                   )
504               >>
505
506           (* Bitstring, constant flen >= 0.
507            * At the moment all we can do is assign the bitstring to an
508            * identifier.
509            *)
510           | P.Bitstring, Some i when i >= 0 ->
511               let ident =
512                 match fpatt with
513                 | <:patt< $lid:ident$ >> -> ident
514                 | <:patt< _ >> -> "_"
515                 | _ ->
516                     fail "cannot compare a bitstring to a constant" in
517               <:expr<
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$
521                       $`int:i$ in
522                   $inner$
523                 )
524               >>
525
526           (* Bitstring, constant flen = -1, means consume all the
527            * rest of the input.
528            *)
529           | P.Bitstring, Some i when i = -1 ->
530               let ident =
531                 match fpatt with
532                 | <:patt< $lid:ident$ >> -> ident
533                 | <:patt< _ >> -> "_"
534                 | _ ->
535                     fail "cannot compare a bitstring to a constant" in
536               <:expr<
537                 let $lid:ident$, $lid:off$, $lid:len$ =
538                   Bitmatch.extract_remainder $lid:data$ $lid:off$ $lid:len$ in
539                   $inner$
540               >>
541
542           | P.Bitstring, Some _ ->
543               fail "length of bitstring must be >= 0 or the special value -1"
544
545           (* Bitstring field, non-const flen.  We check the flen is >= 0
546            * (-1 is not allowed here) at runtime.
547            *)
548           | P.Bitstring, None ->
549               let ident =
550                 match fpatt with
551                 | <:patt< $lid:ident$ >> -> ident
552                 | <:patt< _ >> -> "_"
553                 | _ ->
554                     fail "cannot compare a bitstring to a constant" in
555               <:expr<
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$
559                       $flen$ in
560                   $inner$
561                 )
562               >>
563         in
564
565         (* Computed offset: only offsets forward are supported.
566          *
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?
571          *
572          * Based on this we can do a lot of the computation at
573          * compile time, or defer it to runtime only if necessary.
574          *
575          * In all cases, the off and len fields get updated.
576          *)
577         let expr =
578           match offset with
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.
583                *)
584               let requested_offset = expr_is_constant offset_expr in
585
586               (* This will be [Some i] if our current offset is known
587                * at compile time, or [None] if we can't determine it.
588                *)
589               let current_offset =
590                 let has_constant_offset field =
591                   match P.get_offset field with
592                   | None -> false
593                   | Some expr ->
594                       match expr_is_constant expr with
595                       | None -> false
596                       | Some i -> true
597                 in
598                 let get_constant_offset field =
599                   match P.get_offset field with
600                   | None -> assert false
601                   | Some expr ->
602                       match expr_is_constant expr with
603                       | None -> assert false
604                       | Some i -> i
605                 in
606
607                 let has_constant_len field =
608                   match expr_is_constant (P.get_length field) with
609                   | None -> false
610                   | Some i when i > 0 -> true
611                   | Some _ -> false
612                 in
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
618                 in
619
620                 let rec loop = function
621                   (* first field has constant offset 0 *)
622                   | [] -> Some 0
623                   (* field with constant offset & length *)
624                   | field :: _
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 *)
629                   | field :: fields
630                       when P.get_offset field = None &&
631                         has_constant_len field ->
632                       (match loop fields with
633                        | None -> None
634                        | Some offset -> Some (offset + get_constant_len field))
635                   (* else, can't work out the offset *)
636                   | _ -> None
637                 in
638                 loop fields in
639
640               (* Look at the current offset and requested offset cases and
641                * determine what code to generate.
642                *)
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.
647                  *)
648               | Some current_offset, Some requested_offset ->
649                   let move = requested_offset - current_offset in
650                   if move < 0 then
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?)
655                    *)
656                   <:expr<
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$
660                   >>
661               (* In any other case, we need to use runtime checks.
662                *
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.
667                *)
668               | _ ->
669                   let move = gensym "move" in
670                   <:expr<
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$
676                     )
677                   >> in (* end of computed offset code *)
678
679         (* Emit extra debugging code. *)
680         let expr =
681           if not debug then expr else (
682             let field = P.string_of_pattern_field field in
683
684             <:expr<
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$);*)
691               );
692               $expr$
693             >>
694           ) in
695
696         output_field_extraction expr fields
697   in
698
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
703       let inner =
704         match whenclause with
705         | Some whenclause ->
706             <:expr< if $whenclause$ then $inner$ >>
707         | None -> inner in
708       let inner =
709         match bind with
710         | Some name ->
711             <:expr<
712               let $lid:name$ = ($lid:data$, $lid:off$, $lid:len$) in
713               $inner$
714               >>
715         | None -> inner in
716       output_field_extraction inner (List.rev fields)
717   ) cases in
718
719   (* Join them into a single expression.
720    *
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.
724    *
725    * Note that the number of cases is always >= 1 so List.hd is safe.
726    *)
727   let cases = List.rev cases in
728   let cases =
729     List.fold_left (fun base case -> <:expr< $case$ ; $base$ >>)
730       (List.hd cases) (List.tl cases) in
731
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.
739    *)
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
743
744   <:expr<
745     let ($lid:data$, $lid:off$, $lid:len$) = $bs$ in
746     let $lid:result$ = ref None in
747     (try
748       $cases$
749     with Exit -> ());
750     match ! $lid:result$ with
751     | Some x -> x
752     | None -> raise (Match_failure ($str:loc_fname$,
753                                     $int:loc_line$, $int:loc_char$))
754   >>
755
756 (* Add a named pattern. *)
757 let add_named_pattern _loc name pattern =
758   Hashtbl.add pattern_hash name pattern
759
760 (* Expand a named pattern from the pattern_hash. *)
761 let expand_named_pattern _loc name =
762   try Hashtbl.find pattern_hash name
763   with Not_found ->
764     locfail _loc (sprintf "named pattern not found: %s" name)
765
766 (* Add named patterns from a file.  See the documentation on the
767  * directory search path in bitmatch_persistent.mli
768  *)
769 let load_patterns_from_file _loc filename =
770   let chan =
771     if Filename.is_relative filename && Filename.is_implicit filename then (
772       (* Try current directory. *)
773       try open_in filename
774       with _ ->
775         (* Try OCaml library directory. *)
776         try open_in (Filename.concat Bitmatch_config.ocamllibdir filename)
777         with exn -> Loc.raise _loc exn
778     ) else (
779       try open_in filename
780       with exn -> Loc.raise _loc exn
781     ) in
782   let names = ref [] in
783   (try
784      let rec loop () =
785        let name = P.named_from_channel chan in
786        names := name :: !names
787      in
788      loop ()
789    with End_of_file -> ()
790   );
791   close_in chan;
792   let names = List.rev !names in
793   List.iter (
794     function
795     | name, P.Pattern patt ->
796         if patt = [] then
797           locfail _loc (sprintf "pattern %s: no fields" name);
798         add_named_pattern _loc name patt
799     | _, P.Constructor _ -> () (* just ignore these for now *)
800   ) names
801
802 EXTEND Gram
803   GLOBAL: expr str_item;
804
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.
808    *)
809   qualifiers: [
810     [ LIST0
811         [ q = LIDENT;
812           e = OPT [ "("; e = expr; ")" -> e ] -> (q, e) ]
813         SEP "," ]
814   ];
815
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
818    * persitent pattern.
819    *)
820   patt_field: [
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. *)
829     ]
830   ];
831
832   (* Case inside bitmatch operator. *)
833   patt_fields: [
834     [ "{";
835       fields = LIST0 patt_field SEP ";";
836       "}" ->
837         List.concat fields
838     ]
839   ];
840
841   patt_case: [
842     [ fields = patt_fields;
843       bind = OPT [ "as"; name = LIDENT -> name ];
844       whenclause = OPT [ "when"; e = expr -> e ]; "->";
845       code = expr ->
846         (fields, bind, whenclause, code)
847     ]
848   ];
849
850   (* Field used in the BITSTRING constructor (an expression). *)
851   constr_field: [
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
858     ]
859   ];
860
861   constr_fields: [
862     [ "{";
863       fields = LIST0 constr_field SEP ";";
864       "}" ->
865         fields
866     ]
867   ];
868
869   (* 'bitmatch' expressions. *)
870   expr: LEVEL ";" [
871     [ "bitmatch";
872       bs = expr; "with"; OPT "|";
873       cases = LIST1 patt_case SEP "|" ->
874         output_bitmatch _loc bs cases
875     ]
876
877   (* Constructor. *)
878   | [ "BITSTRING";
879       fields = constr_fields ->
880         output_constructor _loc fields
881     ]
882   ];
883
884   (* Named persistent patterns.
885    *
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.
890    *)
891   str_item: LEVEL "top" [
892     [ "let"; "bitmatch";
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 ... *)
896         <:str_item< >>
897     | "open"; "bitmatch"; filename = STRING ->
898         load_patterns_from_file _loc filename;
899         <:str_item< >>
900     ]
901   ];
902
903 END