nom_derive/docs.rs
1//! The `docs` pseudo-module contains `nom-derive` documentation. Objects from this module
2//! are only used to add documentation, and are not used in the crate.
3
4/// The `Nom` derive automatically generates an implementation of the [`Parse`](super::Parse) trait
5/// for the structure using [nom] parsers, when possible. It will try to infer parsers for
6/// primitive of known types, but also allows you to specify parsers using custom attributes.
7///
8/// The code generates 3 methods:
9/// - `parse_be`: parse object as big-endian
10/// - `parse_le`: parse object as little-endian
11/// - `parse`: default function, wraps a call to `parse_be`
12///
13/// If the endianness of the struct is fixed (for ex. using the top-level `BigEndian` or
14/// `LittleEndian` attributes, or the `NomBE` and `NomLE` custom derive), then the implementation
15/// always uses this endianness, and all 3 functions are equivalent.
16///
17/// When there are extra args or a selector, it is not possible to generate the trait
18/// implementation (function signatures are different). In that case, an implementation block is
19/// generate with the same 3 functions.
20///
21/// Deriving parsers supports `struct` and `enum` types.
22///
23/// Many examples are provided, and more can be found in the [project
24/// tests](https://github.com/rust-bakery/nom-derive/tree/master/tests).
25///
26/// [nom]: https://github.com/Geal/nom
27///
28/// # Table of contents
29///
30/// - [Attributes](#attributes)
31/// - [Byteorder](#byteorder)
32/// - [Deriving parsers for `Struct`](#deriving-parsers-for-struct)
33/// - [Deriving parsers for `Enum`](#deriving-parsers-for-enum)
34/// - [Generic Errors](#generic-errors)
35/// - [Generic Type Parameters](#generic-type-parameters)
36///
37/// # Attributes
38///
39/// Derived parsers can be controlled using the `nom` attribute, with a sub-attribute.
40/// For example, `#[nom(Value)]`.
41///
42/// *Note: order of attributes is important!*
43/// `~[nom(Count="4", Parse="be_u16")]` is not the same as `#[nom(Parse="be_u16", Count="4")]` (which is not valid,
44/// since end-item parsing function is given before specifying that this primitive function is applied
45/// multiple times).
46///
47/// Most combinators support using literal strings `#[nom(Count="4")]` or
48/// parenthesized values `#[nom(Count(4))]`
49///
50/// To specify multiple attributes, use a comma-separated list: `#[nom(Debug, Count="4")]`.
51///
52/// The available attributes are:
53///
54/// | Attribute | Supports | Description
55/// |-----------|------------------|------------
56/// | [AlignAfter](#alignment-and-padding) | fields | skip bytes until aligned to a multiple of the provided value, after parsing value
57/// | [AlignBefore](#alignment-and-padding) | fields | skip bytes until aligned to a multiple of the provided value, before parsing value
58/// | [BigEndian](#byteorder) | all | Set the endianness to big endian
59/// | [Cond](#conditional-values) | fields | Used on an `Option<T>` to read a value of type `T` only if the condition is met
60/// | [Complete](#complete) | all | Transforms Incomplete into Error
61/// | [Count](#count) | fields | Set the expected number of items to parse
62/// | [Debug](#debug) | all | Print error message and input if parser fails (at runtime)
63/// | [DebugDerive](#debugderive) | top-level | Print the generated code to stderr during build
64/// | [Default](#default) | fields | Do not parse, set a field to the default value for the type
65/// | [ErrorIf](#verifications) | fields | Before parsing, check condition is true and return an error if false.
66/// | [Exact](#exact) | top-level | Check that input was entirely consumed by parser
67/// | [GenericErrors](#generic-errors) | top-level | Change function signature to accept generic type parameter for error
68/// | [If](#conditional-values) | fields | Similar to `Cond`
69/// | [Ignore](#default) | fields | An alias for `default`
70/// | [InputName](#input-name) | top-level | Change the internal name of input
71/// | [Into](#into) | fields | Automatically converts the child parser's result to another type
72/// | [LengthCount](#lengthcount) | fields | Specify a parser to get the number of items, and parse the expected number of items
73/// | [LittleEndian](#byteorder) | all | Set the endianness to little endian
74/// | [Map](#map) | fields | Parse field, then apply a function
75/// | [Move](#alignment-and-padding) | fields | add the specified offset to current position, before parsing
76/// | [MoveAbs](#alignment-and-padding) | fields | go to the specified absoluted position, before parsing
77/// | [Parse](#custom-parsers) | fields | Use a custom parser function for reading from a file
78/// | [PreExec](#preexec) | all | Execute Rust code before parsing field or struct
79/// | [PostExec](#postexec) | all | Execute Rust code after parsing field or struct
80/// | [Selector](#deriving-parsers-for-enum) | all | Used to specify the value matching an enum variant
81/// | [SetEndian](#byteorder) | all | Dynamically set the endianness
82/// | [SkipAfter](#alignment-and-padding) | fields | skip the specified number of bytes, after parsing
83/// | [SkipBefore](#alignment-and-padding) | fields | skip the specified number of bytes, before parsing
84/// | [Tag](#tag) | fields | Parse a constant pattern
85/// | [Take](#take) | fields | Take `n` bytes of input
86/// | [Value](#value) | fields | Store result of evaluated expression in field
87/// | [Verify](#verifications) | fields | After parsing, check that condition is true and return an error if false.
88///
89/// See below for examples.
90///
91/// # Deriving parsers for `Struct`
92///
93/// The `Nom` derive automatically generates an implementation of the [`Parse`](super::Parse) trait
94/// for the structure using [nom] parsers, when possible. It will try to infer parsers for
95/// primitive of known types, but also allows you to specify parsers using custom attributes.
96///
97/// The code generates 3 methods:
98/// - `parse_be`: parse object as big-endian
99/// - `parse_le`: parse object as little-endian
100/// - `parse`: default function, wraps a call to `parse_be`
101///
102/// These methods are contained in a generated implementation of the `Parse` trait.
103/// Note: if `ExtraArgs` is specified, the generated code cannot implement the `Parse` trait (the
104/// function signatures are different because of the extra arguments).
105///
106/// Import the `Nom` derive attribute:
107///
108/// ```rust
109/// use nom_derive::*;
110/// ```
111/// and add it to structs or enums.
112/// The `Parse` trait is required for primitive types (`u8`, `u16`, ...).
113///
114/// For simple structures, the parsers are automatically generated:
115///
116/// ```rust
117/// # use nom_derive::*;
118/// #
119/// # #[derive(Debug,PartialEq)] // for assert_eq!
120/// #[derive(Nom)]
121/// struct S {
122/// a: u32,
123/// b: u16,
124/// c: u16
125/// }
126///
127/// # let input = b"\x00\x00\x00\x01\x12\x34\x56\x78";
128/// # let res = S::parse(input);
129/// # assert_eq!(res, Ok((&input[8..],S{a:1,b:0x1234,c:0x5678})));
130/// ```
131///
132/// This also work for tuple structs:
133///
134/// ```rust
135/// # use nom_derive::*;
136/// #
137/// # #[derive(Debug, PartialEq)] // for assert_eq!
138/// #[derive(Nom)]
139/// struct S(u32);
140/// #
141/// # let input = b"\x00\x00\x00\x01";
142/// # let res = S::parse(input);
143/// # assert_eq!(res, Ok((&input[4..],S(1))));
144/// ```
145///
146/// ## Byteorder
147///
148/// By default, multiple methods are generated: one for big-endian and one for little-endian.
149///
150/// The `BigEndian` or `LittleEndian` attributes can be applied to a struct to specify that it must
151/// always be parsed as the given endianness. In that case, the methods `parse_be` and `parse_le`
152/// will be generated as usual, but will use only the given endianness (and thus are equivalent).
153///
154/// ```rust
155/// # use nom_derive::*;
156/// #
157/// # #[derive(Debug, PartialEq)] // for assert_eq!
158/// #[derive(Nom)]
159/// #[nom(LittleEndian)]
160/// struct LittleEndianStruct {
161/// a: u32,
162/// b: u16,
163/// c: u16
164/// }
165///
166/// let input = b"\x00\x00\x00\x01\x12\x34\x56\x78";
167/// let res = LittleEndianStruct::parse(input);
168/// assert_eq!(res, Ok((&input[8..],
169/// LittleEndianStruct{a:0x0100_0000,b:0x3412,c:0x7856}))
170/// );
171/// ```
172///
173/// It is also equivalent (and shorter) to use the `NomBE` or `NomLE` custom derive:
174///
175/// ```rust
176/// # use nom_derive::*;
177/// #
178/// # #[derive(Debug, PartialEq)] // for assert_eq!
179/// #[derive(NomLE)] // all fields will be parsed as little-endian
180/// struct LittleEndianStruct {
181/// a: u32,
182/// b: u16,
183/// c: u16
184/// }
185///
186/// let input = b"\x00\x00\x00\x01\x12\x34\x56\x78";
187/// let res = LittleEndianStruct::parse(input);
188/// assert_eq!(res, Ok((&input[8..],
189/// LittleEndianStruct{a:0x0100_0000,b:0x3412,c:0x7856}))
190/// );
191/// ```
192///
193/// The `BigEndian` and `LittleEndian` attributes can be specified for struct fields.
194/// The corresponding field will always be parsed using the given endianness in the generated
195/// `parse_be` and `parse_le` methods.
196///
197/// If both per-struct and per-field attributes are present, the more specific wins.
198///
199/// For example, the all fields of the following struct will be parsed as big-endian,
200/// except `b`:
201///
202/// ```rust
203/// # use nom_derive::*;
204/// #
205/// # #[derive(Debug,PartialEq)] // for assert_eq!
206/// #[derive(Nom)]
207/// #[nom(BigEndian)]
208/// struct MixedEndianStruct {
209/// a: u32,
210/// #[nom(LittleEndian)]
211/// b: u16,
212/// c: u16
213/// }
214///
215/// # let input = b"\x00\x00\x00\x01\x12\x34\x56\x78";
216/// # let res = MixedEndianStruct::parse(input);
217/// # assert_eq!(res, Ok((&input[8..],
218/// # MixedEndianStruct{a:0x1,b:0x3412,c:0x5678}))
219/// # );
220/// ```
221///
222/// The `SetEndian` attribute changes the endianness of all following integer parsers to the
223/// provided endianness (expected argument has type `nom::number::Endianness`). The expression
224/// can be any expression or function returning an endianness, and will be evaluated once
225/// at the location of the attribute.
226///
227/// Only the parsers after this attribute (including it) are affected: if `SetEndian` is applied to
228/// the third field of a struct having 4 fields, only the fields 3 and 4 will have dynamic
229/// endianness.
230///
231/// This allows dynamic (runtime) change of the endianness, at a small cost (a test is done before
232/// every following integer parser).
233/// However, if the argument is static or known at compilation, the compiler will remove the test
234/// during optimization.
235///
236/// If a `BigEndian` or `LittleEndian` is applied to a field, its definition is used prior to
237/// `SetEndian`.
238///
239/// For ex, to create a parse function having two arguments (`input`, and the endianness):
240///
241/// ```rust
242/// # use nom_derive::*;
243/// # use nom::number::Endianness;
244/// #
245/// # #[derive(Debug,PartialEq)] // for assert_eq!
246/// #[derive(Nom)]
247/// #[nom(ExtraArgs(endian: Endianness))]
248/// #[nom(SetEndian(endian))] // Set dynamically the endianness
249/// struct MixedEndianStruct {
250/// a: u32,
251/// b: u16,
252/// #[nom(BigEndian)] // Field c will always be parsed as BigEndian
253/// c: u16
254/// }
255///
256/// # let input = b"\x00\x00\x00\x01\x12\x34\x56\x78";
257/// let res = MixedEndianStruct::parse(input, Endianness::Big);
258/// # assert_eq!(res, Ok((&input[8..],
259/// # MixedEndianStruct{a:0x1,b:0x1234,c:0x5678}))
260/// # );
261/// # let res = MixedEndianStruct::parse(input, Endianness::Little);
262/// # assert_eq!(res, Ok((&input[8..],
263/// # MixedEndianStruct{a:0x0100_0000,b:0x3412,c:0x5678}))
264/// # );
265/// ```
266///
267/// # Deriving and Inferring Parsers
268///
269/// `nom-derive` is also able to infer parsers for some usual types: integers, `Option`, `Vec`, etc.
270///
271/// If the parser cannot be inferred, a default function will be called. It is also possible to
272/// override this using the `Parse` attribute.
273///
274/// Following sections give more details.
275///
276/// ## Option types
277///
278/// If a field is an `Option<T>`, the generated parser is `opt(complete(T::parse))`
279///
280/// For ex:
281/// ```rust
282/// # use nom_derive::*;
283/// #
284/// # #[derive(Debug,PartialEq)] // for assert_eq!
285/// #[derive(Nom)]
286/// struct S {
287/// a: Option<u32>
288/// }
289///
290/// let input = b"\x00\x00\x00\x01";
291/// let res = S::parse(input);
292/// assert_eq!(res, Ok((&input[4..],S{a:Some(1)})));
293/// ```
294///
295/// ## Vec types
296///
297/// If a field is an `Vec<T>`, the generated parser is `many0(complete(T::parse))`
298///
299/// For ex:
300/// ```rust
301/// # use nom_derive::*;
302/// #
303/// # #[derive(Debug,PartialEq)] // for assert_eq!
304/// #[derive(Nom)]
305/// struct S {
306/// a: Vec<u16>
307/// }
308///
309/// let input = b"\x00\x00\x00\x01";
310/// let res = S::parse(input);
311/// assert_eq!(res, Ok((&input[4..],S{a:vec![0,1]})));
312/// ```
313///
314/// ## Count
315///
316/// The `Count(n)` attribute can be used to specify the number of items to parse.
317///
318/// Notes:
319/// - the subparser is inferred as usual (item type must be `Vec< ... >`)
320/// - the number of items (`n`) can be any expression, and will be cast to `usize`
321///
322/// For ex:
323/// ```rust
324/// # use nom_derive::*;
325/// #
326/// # #[derive(Debug,PartialEq)] // for assert_eq!
327/// #[derive(Nom)]
328/// struct S {
329/// a: u16,
330/// #[nom(Count="a")]
331/// b: Vec<u16>
332/// }
333/// #
334/// # let input = b"\x00\x01\x12\x34";
335/// # let res = S::parse(input);
336/// # assert_eq!(res, Ok((&input[4..],S{a:1, b:vec![0x1234]})));
337/// ```
338///
339/// ## LengthCount
340///
341/// The `LengthCount="parser"` attribute can be used to specify a parser to get a number, and
342/// use this number to parse an expected number of items.
343///
344/// Notes:
345/// - the subparser is inferred as usual (item type must be `Vec< ... >`)
346/// - the length parser must return a number
347///
348/// For ex:
349/// ```rust
350/// # use nom_derive::*;
351/// # use nom::number::streaming::be_u16;
352/// #
353/// # #[derive(Debug,PartialEq)] // for assert_eq!
354/// #[derive(Nom)]
355/// struct S {
356/// #[nom(LengthCount="be_u16")]
357/// b: Vec<u16>
358/// }
359/// #
360/// # let input = b"\x00\x01\x12\x34";
361/// # let res = S::parse(input);
362/// # assert_eq!(res, Ok((&input[4..],S{b:vec![0x1234]})));
363/// ```
364///
365/// ## Tag
366///
367/// The `Tag(value)` attribute is used to parse a constant value (or "magic").
368///
369/// For ex:
370/// ```rust
371/// # use nom_derive::*;
372/// #
373/// # #[derive(Debug,PartialEq)] // for assert_eq!
374/// #[derive(Nom)]
375/// struct S<'a> {
376/// #[nom(Tag(b"TAG"))]
377/// tag: &'a[u8],
378/// a: u16,
379/// b: u16,
380/// }
381/// #
382/// # let input = b"TAG\x00\x01\x12\x34";
383/// # let res = S::parse(input);
384/// # assert_eq!(res, Ok((&input[7..],S{tag: b"TAG", a:1, b:0x1234})));
385/// ```
386///
387/// ## Take
388///
389/// The `Take="n"` attribute can be used to take `n` bytes of input.
390///
391/// Notes:
392/// - the number of items (`n`) can be any expression, and will be cast to `usize`
393///
394/// For ex:
395/// ```rust
396/// # use nom_derive::*;
397/// #
398/// # #[derive(Debug,PartialEq)] // for assert_eq!
399/// #[derive(Nom)]
400/// struct S<'a> {
401/// a: u16,
402/// #[nom(Take="1")]
403/// b: &'a [u8],
404/// }
405/// #
406/// # let input = b"\x00\x01\x12\x34";
407/// # let res = S::parse(input);
408/// # assert_eq!(res, Ok((&input[3..],S{a:1, b:&[0x12]})));
409/// ```
410///
411/// ## Default parsing function
412///
413/// If a field with type `T` is not a primitive or known type, the generated parser is
414/// `T::parse(input)`.
415///
416/// This function can be automatically derived, or specified as a method for the struct.
417/// In that case, the function must be a static method with the same API as a
418/// [nom] combinator, returning the wrapped struct when parsing succeeds.
419///
420/// For example (using `Nom` derive):
421/// ```rust
422/// # use nom_derive::*;
423/// #
424/// # #[derive(Debug,PartialEq)] // for assert_eq!
425/// #[derive(Nom)]
426/// struct S2 {
427/// c: u16
428/// }
429///
430/// # #[derive(Debug,PartialEq)] // for assert_eq!
431/// #[derive(Nom)]
432/// struct S {
433/// a: u16,
434/// b: S2
435/// }
436/// #
437/// # let input = b"\x00\x00\x00\x01";
438/// # let res = S::parse(input);
439/// # assert_eq!(res, Ok((&input[4..],S{a:0,b:S2{c:1}})));
440/// ```
441///
442/// Example (implementing the `Parse` trait manually):
443/// ```rust
444/// # use nom_derive::*;
445/// # use nom::IResult;
446/// # use nom::combinator::map;
447/// # use nom::number::streaming::le_u16;
448/// #
449/// # #[derive(Debug,PartialEq)] // for assert_eq!
450/// // no Nom derive
451/// struct S2 {
452/// c: u16
453/// }
454///
455/// impl<'a> Parse<&'a[u8]> for S2 {
456/// fn parse(i:&'a [u8]) -> IResult<&'a [u8],S2> {
457/// map(
458/// le_u16, // little-endian
459/// |c| S2{c} // return a struct S2
460/// )(i)
461/// }
462/// }
463///
464/// # #[derive(Debug,PartialEq)] // for assert_eq!
465/// #[derive(Nom)]
466/// struct S {
467/// a: u16,
468/// b: S2
469/// }
470/// #
471/// # let input = b"\x00\x00\x00\x01";
472/// # let res = S::parse(input);
473/// # assert_eq!(res, Ok((&input[4..],S{a:0,b:S2{c:256}})));
474/// ```
475///
476/// ## Custom parsers
477///
478/// Sometimes, the default parsers generated automatically are not those you
479/// want.
480///
481/// The `Parse` custom attribute allows for specifying the parser that
482/// will be inserted in the nom parser.
483///
484/// The parser is called with input as argument, so the signature of the parser
485/// must be equivalent to:
486///
487/// ```rust,ignore
488/// fn parser(i: &[u8]) -> IResult<&[u8], T> {
489/// // ...
490/// }
491/// ```
492///
493/// For example, to specify the parser of a field:
494///
495/// ```rust
496/// # use nom_derive::*;
497/// # use nom::number::streaming::le_u16;
498/// #
499/// # #[derive(Debug,PartialEq)] // for assert_eq!
500/// #[derive(Nom)]
501/// struct S{
502/// #[nom(Parse="le_u16")]
503/// a: u16
504/// }
505/// #
506/// # let input = b"\x00\x01";
507/// # let res = S::parse(input);
508/// # assert_eq!(res, Ok((&input[2..],S{a:256})));
509/// ```
510///
511/// The `Parse` argument can be a complex expression:
512/// ```rust
513/// # use nom_derive::*;
514/// # use nom::combinator::cond;
515/// # use nom::number::streaming::be_u16;
516/// #
517/// # #[derive(Debug,PartialEq)] // for assert_eq!
518/// #[derive(Nom)]
519/// struct S{
520/// pub a: u8,
521/// #[nom(Parse="cond(a > 0,be_u16)")]
522/// pub b: Option<u16>,
523/// }
524/// #
525/// # let input = b"\x01\x00\x01";
526/// # let res = S::parse(input);
527/// # assert_eq!(res, Ok((&input[3..],S{a:1,b:Some(1)})));
528/// ```
529/// Note that you are responsible from providing correct code.
530///
531/// ## Default
532///
533/// If a field is marked as `Ignore` (or `Default`), it will not be parsed.
534/// Its value will be the default value for the field type.
535///
536/// This is convenient if the structured has more fields than the serialized value.
537///
538/// ```rust
539/// # use nom_derive::*;
540/// #
541/// # #[derive(Debug,PartialEq)] // for assert_eq!
542/// #[derive(Nom)]
543/// struct S{
544/// pub a: u8,
545/// #[nom(Ignore)]
546/// pub b: Option<u16>,
547/// }
548/// #
549/// # let input = b"\x01\x00\x01";
550/// # let res = S::parse(input);
551/// # assert_eq!(res, Ok((&input[1..],S{a:1,b:None})));
552/// ```
553///
554/// ## Complete
555///
556/// The `Complete` attribute transforms Incomplete into Error.
557///
558/// Default is to use streaming parsers. If there are not enough bytes, error will look like
559/// `Err(Error::Incomplete(Needed(5)))`. A streaming parser can use this to determine if data is missing,
560/// wait for more data, then call again the parse function.
561///
562/// When the parser has the entire data, it is more useful to transform this into an error to stop
563/// parsing, using the `Complete` attribute.
564///
565/// This attribute can be used on a specific field:
566///
567/// ```rust
568/// # use nom_derive::*;
569/// # use nom::number::streaming::be_u8;
570/// #
571/// # #[derive(Debug,PartialEq)] // for assert_eq!
572/// #[derive(Nom)]
573/// struct S{
574/// pub a: u8,
575/// #[nom(Complete)]
576/// pub b: u64,
577/// }
578/// #
579/// # let input = b"\x01\x00\x01";
580/// # let res = S::parse(input).expect_err("parse error");
581/// # assert!(!res.is_incomplete());
582/// ```
583///
584/// This attribute can be also used on the entire object, applying to every fields:
585///
586/// ```rust
587/// # use nom_derive::*;
588/// # use nom::number::streaming::be_u8;
589/// #
590/// # #[derive(Debug,PartialEq)] // for assert_eq!
591/// #[derive(Nom)]
592/// #[nom(Complete)]
593/// struct S{
594/// pub a: u8,
595/// pub b: u64,
596/// }
597/// #
598/// # let input = b"\x01\x00\x01";
599/// # let res = S::parse(input).expect_err("parse error");
600/// # assert!(!res.is_incomplete());
601/// ```
602///
603/// ## Into
604///
605/// The `Into` attribute automatically converts the child parser's output and error types to other types.
606///
607/// It requires the output and error type to implement the `Into` trait.
608///
609/// This attribute can be used on a specific field:
610///
611/// ```rust
612/// # use nom_derive::*;
613/// # use nom::IResult;
614/// # use nom::character::streaming::alpha1;
615/// # use nom::number::streaming::be_u8;
616/// #
617/// fn parser1(i: &[u8]) -> IResult<&[u8], &[u8]> {
618/// alpha1(i)
619/// }
620/// #
621/// # #[derive(Debug,PartialEq)] // for assert_eq!
622/// #[derive(Nom)]
623/// struct S{
624/// pub a: u8,
625/// #[nom(Into, Parse = "parser1")]
626/// pub b: Vec<u8>,
627/// }
628/// #
629/// # let input = b"\x01abcd\x00";
630/// # let res = S::parse(input).expect("parse error");
631/// ```
632///
633/// ## Map
634///
635/// The `Map` attribute can be used to apply a function to the result
636/// of the parser.
637/// It is often used combined with the `Parse` attribute.
638///
639/// ```rust
640/// # use nom_derive::*;
641/// # use nom::number::streaming::be_u8;
642/// #
643/// # #[derive(Debug,PartialEq)] // for assert_eq!
644/// #[derive(Nom)]
645/// struct S{
646/// pub a: u8,
647/// #[nom(Map = "|x: u8| x.to_string()", Parse="be_u8")]
648/// pub b: String,
649/// }
650/// #
651/// # let input = b"\x01\x00\x01";
652/// # let res = S::parse(input);
653/// # assert_eq!(res, Ok((&input[2..],S{a:1,b:"0".to_string()})));
654/// ```
655///
656/// ## Conditional Values
657///
658/// The `Cond` custom attribute allows for specifying a condition.
659/// The generated parser will use the `cond!` combinator, which calls the
660/// child parser only if the condition is met.
661/// The type with this attribute must be an `Option` type.
662///
663/// ```rust
664/// # use nom_derive::*;
665/// #
666/// # #[derive(Debug,PartialEq)] // for assert_eq!
667/// #[derive(Nom)]
668/// struct S{
669/// pub a: u8,
670/// #[nom(Cond="a == 1")]
671/// pub b: Option<u16>,
672/// }
673/// #
674/// # let input = b"\x01\x00\x01";
675/// # let res = S::parse(input);
676/// # assert_eq!(res, Ok((&input[3..],S{a:1,b:Some(1)})));
677/// ```
678///
679/// ## Value
680///
681/// The `Value` attribute does not parse data. It is used to store the result
682/// of the evaluated expression in the variable.
683///
684/// Previous fields can be used in the expression.
685///
686/// ```rust
687/// # use nom_derive::*;
688/// # use nom::number::streaming::be_u8;
689/// #
690/// # #[derive(Debug,PartialEq)] // for assert_eq!
691/// #[derive(Nom)]
692/// struct S{
693/// pub a: u8,
694/// #[nom(Value = "a.to_string()")]
695/// pub b: String,
696/// }
697/// #
698/// # let input = b"\x01\x00\x01";
699/// # let res = S::parse(input);
700/// # assert_eq!(res, Ok((&input[1..],S{a:1,b:"1".to_string()})));
701/// ```
702///
703/// ## Verifications
704///
705/// The `Verify` custom attribute allows for specifying a verifying function.
706/// The generated parser will use the `verify` combinator, which calls the
707/// child parser only if is verifies a condition (and otherwise raises an error).
708///
709/// The argument used in verify function is passed as a reference.
710///
711/// ```rust
712/// # use nom_derive::*;
713/// #
714/// # #[derive(Debug,PartialEq)] // for assert_eq!
715/// #[derive(Nom)]
716/// struct S{
717/// #[nom(Verify="*a == 1")]
718/// pub a: u8,
719/// }
720/// #
721/// # let input = b"\x01";
722/// # let res = S::parse(input);
723/// # assert_eq!(res, Ok((&input[1..],S{a:1})));
724/// ```
725///
726/// The `ErrorIf` checks the provided condition, and return an error if the
727/// test returns false.
728/// The condition is tested before any parsing occurs for this field, and does not
729/// change the input pointer.
730///
731/// Error has type `ErrorKind::Verify` (nom).
732///
733/// The argument used in verify function is passed as a reference.
734///
735/// ```rust
736/// # use nom_derive::*;
737/// #
738/// # #[derive(Debug,PartialEq)] // for assert_eq!
739/// #[derive(Nom)]
740/// struct S{
741/// pub a: u8,
742/// #[nom(ErrorIf(a != 1))]
743/// pub b: u8,
744/// }
745/// #
746/// # let input = b"\x01\x02";
747/// # let res = S::parse(input);
748/// # assert_eq!(res, Ok((&input[2..],S{a:1, b:2})));
749/// ```
750///
751/// ## Exact
752///
753/// The `Exact` custom attribute adds a verification after parsing the entire element.
754/// It succeeds if the input has been entirely consumed by the parser.
755///
756/// ```rust
757/// # use nom_derive::*;
758/// #
759/// # #[derive(Debug,PartialEq)] // for assert_eq!
760/// #[derive(Nom)]
761/// #[nom(Exact)]
762/// struct S{
763/// pub a: u8,
764/// }
765/// #
766/// # let input = b"\x01\x01";
767/// # let res = S::parse(&input[1..]);
768/// # assert!(res.is_ok());
769/// # let res = S::parse(input);
770/// # assert!(res.is_err());
771/// ```
772///
773/// ## PreExec
774///
775/// The `PreExec` custom attribute executes the provided code before parsing
776/// the field or structure.
777///
778/// This attribute can be specified multiple times. Statements will be executed in order.
779///
780/// Note that the current input can be accessed, as a regular variable (see [InputName](#input-name)).
781/// If you create a new variable with the same name, it will be used as input (resulting in
782/// side-effects).
783///
784/// Expected value: a valid Rust statement
785///
786/// ```rust
787/// # use nom_derive::*;
788/// #
789/// # #[derive(Debug,PartialEq)] // for assert_eq!
790/// #[derive(Nom)]
791/// struct S{
792/// #[nom(PreExec="let sz = i.len();")]
793/// pub a: u8,
794/// #[nom(Value(sz))]
795/// pub sz: usize,
796/// }
797/// #
798/// # let input = b"\x01";
799/// # let res = S::parse(input);
800/// # assert_eq!(res, Ok((&input[1..],S{a:1, sz:1})));
801/// ```
802///
803/// ## PostExec
804///
805/// The `PostExec` custom attribute executes the provided code after parsing
806/// the field or structure.
807///
808/// This attribute can be specified multiple times. Statements will be executed in order.
809///
810/// Note that the current input can be accessed, as a regular variable (see [InputName](#input-name)).
811/// If you create a new variable with the same name, it will be used as input (resulting in
812/// side-effects).
813///
814/// Expected value: a valid Rust statement
815///
816/// ```rust
817/// # use nom_derive::*;
818/// #
819/// # #[derive(Debug,PartialEq)] // for assert_eq!
820/// #[derive(Nom)]
821/// struct S{
822/// #[nom(PostExec="let b = a + 1;")]
823/// pub a: u8,
824/// #[nom(Value(b))]
825/// pub b: u8,
826/// }
827/// #
828/// # let input = b"\x01";
829/// # let res = S::parse(input);
830/// # assert_eq!(res, Ok((&input[1..],S{a:1, b:2})));
831/// ```
832///
833/// If applied to the top-level element, the statement is executing after the entire element
834/// is parsed.
835///
836/// If parsing a structure, the built structure is available in the `struct_def` variable.
837///
838/// If parsing an enum, the built structure is available in the `enum_def` variable.
839///
840/// ```rust
841/// # use nom_derive::*;
842/// #
843/// # #[derive(PartialEq)] // for assert_eq!
844/// #[derive(Debug)]
845/// #[derive(Nom)]
846/// #[nom(PostExec(println!("parsing done: {:?}", struct_def);))]
847/// struct S{
848/// pub a: u8,
849/// pub b: u8,
850/// }
851/// #
852/// # let input = b"\x01\x02";
853/// # let res = S::parse(input);
854/// # assert_eq!(res, Ok((&input[2..],S{a:1, b:2})));
855/// ```
856///
857/// ## Alignment and Padding
858///
859/// - `AlignAfter`/`AlignBefore`: skip bytes until aligned to a multiple of the provided value
860/// Alignment is calculated to the start of the original parser input
861/// - `SkipAfter`/`SkipBefore`: skip the specified number of bytes
862/// - `Move`: add the speficied offset to current position, before parsing. Offset can be negative.
863/// - `MoveAbs`: go to specified absolute position (relative to the start of original parser
864/// input), before parsing
865///
866/// If multiple directives are provided, they are applied in order of appearance of the
867/// attribute.
868///
869/// If the new position would be before the start of the slice or beyond its end,
870/// an error is raised (`TooLarge` or `Incomplete`, depending on the case).
871///
872/// Expected value: a valid Rust value (immediate value, or expression)
873///
874/// ```rust
875/// # use nom_derive::*;
876/// #
877/// # #[derive(Debug,PartialEq)] // for assert_eq!
878/// #[derive(Nom)]
879/// struct S{
880/// pub a: u8,
881/// #[nom(AlignBefore(4))]
882/// pub b: u8,
883/// }
884/// #
885/// # let input = b"\x01\x00\x00\x00\x02";
886/// # let res = S::parse(input);
887/// # assert_eq!(res, Ok((&input[5..],S{a:1, b:2})));
888/// ```
889///
890/// # Deriving parsers for `Enum`
891///
892/// The `Nom` attribute can also used to generate parser for `Enum` types.
893/// The generated parser will used a value (called *selector*) to determine
894/// which attribute variant is parsed.
895/// Named and unnamed enums are supported.
896///
897/// In addition of `derive(Nom)`, a `Selector` attribute must be used:
898/// - on the structure, to specify the type of selector to match
899/// - on each variant, to specify the value associated with this variant.
900///
901/// Expected values:
902/// - top-level: a valid Rust type
903/// - fields: a valid Rust match arm expression (for ex: `0`). *Note*: this expression can
904/// contain a pattern guard (for ex: `x if x > 2`)
905///
906/// ```rust
907/// # use nom_derive::*;
908/// #
909/// # #[derive(Debug,PartialEq)] // for assert_eq!
910/// #[derive(Nom)]
911/// #[nom(Selector="u8")]
912/// pub enum U1{
913/// #[nom(Selector="0")] Field1(u32),
914/// #[nom(Selector="1")] Field2(Option<u32>),
915/// }
916/// #
917/// # let input = b"\x00\x00\x00\x02";
918/// # let res = U1::parse(input, 0);
919/// # assert_eq!(res, Ok((&input[4..],U1::Field1(2))));
920/// ```
921///
922/// The generated function will look like:
923///
924/// <pre>
925/// impl U1{
926/// pub fn parse_be(i:&[u8], selector: u8) -> IResult<&[u8],U1> {
927/// match selector {
928/// ...
929/// }
930/// }
931/// pub fn parse_le(i:&[u8], selector: u8) -> IResult<&[u8],U1> {
932/// match selector {
933/// ...
934/// }
935/// }
936/// pub fn parse(i:&[u8], selector: u8) -> IResult<&[u8],U1> {
937/// U1::parse_be(i, selector)
938/// }
939/// }
940/// </pre>
941///
942/// Note that it is not possible to generate an implementation of the `Parse` trait, since the
943/// function signature has an extra argument (the selector).
944/// Except this extra argument, the generated implementation behaves the same as the trait.
945///
946/// It can be called either directly (`U1::parse(n)`) or using nom
947/// (`call!(U1::parse,n)`).
948///
949/// The selector can be a primitive type (`u8`), or any other type implementing the `PartialEq`
950/// trait.
951///
952/// ```rust
953/// # use nom_derive::*;
954/// #
955/// #[derive(Debug,PartialEq,Eq,Clone,Copy,Nom)]
956/// pub struct MessageType(pub u8);
957///
958/// # #[derive(Debug,PartialEq)] // for assert_eq!
959/// #[derive(Nom)]
960/// #[nom(Selector="MessageType")]
961/// pub enum U1{
962/// #[nom(Selector="MessageType(0)")] Field1(u32),
963/// #[nom(Selector="MessageType(1)")] Field2(Option<u32>),
964/// }
965///
966/// // Example of call from a struct:
967/// #[derive(Nom)]
968/// pub struct S1{
969/// pub msg_type: MessageType,
970/// #[nom(Parse="{ |i| U1::parse(i, msg_type) }")]
971/// pub msg_value: U1
972/// }
973/// #
974/// # let input = b"\x00\x00\x00\x02";
975/// # let res = U1::parse(input, MessageType(0));
976/// # assert_eq!(res, Ok((&input[4..],U1::Field1(2))));
977/// ```
978///
979/// ## Default case
980///
981/// By default, if no value of the selector matches the input value, a nom error
982/// `ErrorKind::Switch` is raised. This can be changed by using `_` as selector
983/// value for one the variants.
984///
985/// ```rust
986/// # use nom_derive::*;
987/// #
988/// # #[derive(Debug,PartialEq)] // for assert_eq!
989/// #[derive(Nom)]
990/// #[nom(Selector="u8")]
991/// pub enum U2{
992/// #[nom(Selector="0")] Field1(u32),
993/// #[nom(Selector="_")] Field2(u32),
994/// }
995/// #
996/// # let input = b"\x00\x00\x00\x02";
997/// # let res = U2::parse(input, 123);
998/// # assert_eq!(res, Ok((&input[4..],U2::Field2(2))));
999/// ```
1000///
1001/// If the `_` selector is not the last variant, the generated code will use it
1002/// as the last match to avoid unreachable code.
1003///
1004/// ## Special case: specifying parsers for fields
1005///
1006/// Sometimes, an unnamed field requires a custom parser. In that case, the
1007/// *field* (not the variant) must be annotated with attribute `Parse`.
1008///
1009/// Named fields:
1010///
1011/// ```rust
1012/// # use nom_derive::*;
1013/// # use nom::bytes::streaming::take;
1014/// #
1015/// # #[derive(Debug,PartialEq,Eq,Clone,Copy,Nom)]
1016/// # pub struct MessageType(pub u8);
1017/// #
1018/// #[derive(Nom)]
1019/// #[nom(Selector="MessageType")]
1020/// pub enum U3<'a>{
1021/// #[nom(Selector="MessageType(0)")] Field1{a:u32},
1022/// #[nom(Selector="MessageType(1)")] Field2{
1023/// #[nom(Parse="take(4 as usize)")]
1024/// a: &'a[u8]
1025/// },
1026/// }
1027/// ```
1028///
1029/// Unnamed fields:
1030///
1031/// ```rust
1032/// # use nom_derive::*;
1033/// # use nom::bytes::streaming::take;
1034/// #
1035/// # #[derive(Debug,PartialEq,Eq,Clone,Copy,Nom)]
1036/// # pub struct MessageType(pub u8);
1037/// #
1038/// #[derive(Nom)]
1039/// #[nom(Selector="MessageType")]
1040/// pub enum U3<'a>{
1041/// #[nom(Selector="MessageType(0)")] Field1(u32),
1042/// #[nom(Selector="MessageType(1)")] Field2(
1043/// #[nom(Parse="take(4 as usize)")] &'a[u8]
1044/// ),
1045/// }
1046/// ```
1047///
1048/// ## Special case: fieldless enums
1049///
1050/// If the entire enum is fieldless (a list of constant integer values), a
1051/// parser can be derived if
1052/// - the `Enum` has a `repr(ty)` attribute, with `ty` an integer type
1053/// - the `Enum` implements the `Eq` trait
1054///
1055/// In that case, the `Selector` attribute must *not* be specified.
1056///
1057/// Note: if `ExtraArgs` is not specified, the generated code is an implementation of the `Parse`
1058/// trait.
1059///
1060/// ```rust
1061/// # use nom_derive::*;
1062/// # use nom::*;
1063/// # use nom::number::streaming::be_u8;
1064/// #
1065/// # #[derive(Debug,PartialEq)] // for assert_eq!
1066/// #[repr(u8)]
1067/// #[derive(Eq,Nom)]
1068/// pub enum U3{
1069/// A,
1070/// B = 2,
1071/// C
1072/// }
1073/// #
1074/// # let empty : &[u8] = b"";
1075/// # assert_eq!(
1076/// # U3::parse(b"\x00"),
1077/// # Ok((empty,U3::A))
1078/// # );
1079/// # assert!(
1080/// # U3::parse(b"\x01").is_err()
1081/// # );
1082/// # assert_eq!(
1083/// # U3::parse(b"\x02"),
1084/// # Ok((empty,U3::B))
1085/// # );
1086/// ```
1087///
1088/// The generated parser will parse an element of type `ty` (as Big Endian), try
1089/// to match to enum values, and return an instance of `Enum` if it succeeds
1090/// (wrapped in an `IResult`).
1091///
1092/// For ex, `U3::parse(b"\x02")` will return `Ok((&b""[..],U3::B))`.
1093///
1094/// ## Input Name
1095///
1096/// Internally, the parser will use a variable to follow the input.
1097/// By default, this variable is named `i`.
1098///
1099/// This can cause problems, for example, if one field of the structure has the same name
1100///
1101/// The internal variable name can be renamed using the `InputName` top-level attribute.
1102///
1103/// ```rust
1104/// # use nom_derive::*;
1105/// #
1106/// # #[derive(Debug,PartialEq)] // for assert_eq!
1107/// #[derive(Nom)]
1108/// #[nom(InputName(aaa))]
1109/// pub struct S {
1110/// pub i: u8,
1111/// }
1112/// #
1113/// # let empty : &[u8] = b"";
1114/// # assert_eq!(
1115/// # S::parse(b"\x00"),
1116/// # Ok((empty, S{i:0}))
1117/// # );
1118/// ```
1119///
1120/// Note that this variable can be used as usual, for ex. to peek data
1121/// without advancing in the current stream, determining the length of
1122/// remaining bytes, etc.
1123///
1124/// ```rust
1125/// # use nom_derive::*;
1126/// #
1127/// # #[derive(Debug,PartialEq)] // for assert_eq!
1128/// #[derive(Nom)]
1129/// #[nom(InputName(i))]
1130/// pub struct S {
1131/// pub a: u8,
1132/// #[nom(Value(i.len()))]
1133/// pub remaining_len: usize,
1134/// }
1135/// #
1136/// # let empty : &[u8] = b"";
1137/// # assert_eq!(
1138/// # S::parse(b"\x00"),
1139/// # Ok((empty, S{a:0, remaining_len:0}))
1140/// # );
1141/// ```
1142///
1143/// **This can create side-effects**: if you create a variable with the same name
1144/// as the input, it will shadow it. While this will is generally an error, it can
1145/// sometimes be useful.
1146///
1147/// For example, to skip 2 bytes of input:
1148///
1149/// ```rust
1150/// # use nom_derive::*;
1151/// #
1152/// # #[derive(Debug,PartialEq)] // for assert_eq!
1153/// #[derive(Nom)]
1154/// #[nom(InputName(i))]
1155/// pub struct S {
1156/// pub a: u8,
1157/// // skip 2 bytes
1158/// // XXX this will panic if input is smaller than 2 bytes at this points
1159/// #[nom(PreExec(let i = &i[2..];))]
1160/// pub b: u8,
1161/// }
1162/// #
1163/// # let empty : &[u8] = b"";
1164/// # assert_eq!(
1165/// # S::parse(b"\x00\x01\x02\x03"),
1166/// # Ok((empty, S{a:0, b:3}))
1167/// # );
1168/// ```
1169///
1170/// ## Debug
1171///
1172/// Errors in generated parsers may be hard to understand and debug.
1173///
1174/// The `Debug` attribute insert calls to nom's `dbg_dmp` function, which will print
1175/// an error message and the input if the parser fails. This attribute can be applied to either
1176/// fields, or at top-level (all sub-parsers will be wrapped).
1177///
1178/// This helps resolving parse errors (at runtime).
1179///
1180/// ```rust
1181/// # use nom_derive::*;
1182/// #
1183/// #[derive(Nom)]
1184/// pub struct S {
1185/// pub a: u32,
1186/// #[nom(Debug)]
1187/// pub b: u64,
1188/// }
1189/// ```
1190///
1191/// ## DebugDerive
1192///
1193/// The `DebugDerive` attribute, if applied to top-level, makes the generator print the
1194/// generated code to `stderr`.
1195///
1196/// This helps resolving compiler errors.
1197///
1198/// ```rust
1199/// # use nom_derive::*;
1200/// #
1201/// #[derive(Nom)]
1202/// #[nom(DebugDerive)]
1203/// pub struct S {
1204/// pub a: u32,
1205/// }
1206/// ```
1207///
1208/// # Generic Errors
1209///
1210/// By default, `nom-derive` will use `nom`'s default error type (`(&[u8], ErrorKind)`). In most cases,
1211/// this will be enough for a simple parser.
1212/// However, there are some cases like debugging a runtime error, or using custom error types, where this
1213/// error type is not easy to use.
1214///
1215/// The `GenericErrors` attribute changes the generated function signature to have a generic type parameter
1216/// for the error type:
1217///
1218/// ```rust
1219/// # use nom_derive::*;
1220/// #
1221/// #[derive(Nom)]
1222/// #[nom(GenericErrors)]
1223/// pub struct S {
1224/// pub a: u32,
1225/// }
1226/// ```
1227/// will generate the following code signature (simplified):
1228/// ```rust,ignore
1229/// impl <'nom, E> Parse <&'nom [u8], E> for S
1230/// where
1231/// E : nom::error::ParseError <&'nom [u8]>
1232/// {
1233/// fn parse_be(orig_i : &'nom [u8]) -> IResult <&'nom [u8], Self, E>
1234/// {
1235/// ...
1236/// }
1237/// }
1238/// ```
1239///
1240/// The `parse` method requires to give a concrete type for the error type when called:
1241/// ```rust,ignore
1242/// let res: IResult<_, _, VerboseError<_>> = S::parse_be(input);
1243/// let (rem, res) = res.unwrap();
1244/// ```
1245///
1246/// This attribute has the following requirements:
1247/// - The error type must implement `nom::error::ParseError<&[u8]>`
1248/// - All subparsers must return compatible error types
1249///
1250/// # Generic Type Parameters
1251///
1252/// `nom-derive` supports generic type parameters in the `struct` or `enum` definition.
1253///
1254/// Requirements:
1255/// - Every generic type parameter must implement the [Parse](crate::Parse) trait from this crate
1256/// - Note: it the generic type is not boxed, this often require the type to be `Sized`
1257///
1258/// Example:
1259/// ```rust
1260/// # use nom_derive::*;
1261/// #
1262/// #[derive(Nom)]
1263/// pub struct S<T> where T: Sized {
1264/// pub a: u32,
1265/// pub t: T,
1266/// }
1267/// ```
1268///
1269/// Generic type parameters can also be used with generic errors.
1270#[allow(non_snake_case)]
1271pub mod Nom {}