[][src]Crate nom_derive


License: MIT Apache License 2.0 docs.rs Build Status Crates.io Version


nom-derive is a custom derive attribute, to derive nom parsers automatically from the structure definition.

It is not meant to replace nom, but to provide a quick and easy way to generate parsers for structures, especially for simple structures. This crate aims at simplifying common cases. In some cases, writing the parser manually will remain more efficient.

Feedback welcome !


This crate exposes a single custom-derive macro Nom which implements parse for the struct it is applied to.

The goal of this project is that:

  • derive(Nom) should be enough for you to derive nom parsers for simple structures easily, without having to write it manually
  • it allows overriding any parsing method by your own
  • it allows using generated parsing functions along with handwritten parsers and combining them without efforts
  • it remains as fast as nom

nom-derive adds declarative parsing to nom. It also allows mixing with procedural parsing easily, making writing parsers for byte-encoded formats very easy.

For example:

use nom_derive::Nom;

struct S {
  a: u32,
  b: u16,
  c: u16

This adds a static method parse to S, with the following signature:

This example is not tested
impl S {
    pub fn parse(i: &[u8]) -> nom::IResult(&[u8], S);

To parse input, just call let res = S::parse(input);.

For extensive documentation of all attributes and examples, see the Nom derive attribute documentation.

Many examples are provided, and more can be found in the project tests.

Debug tips

  • If the generated parser does not compile, add #[nom(DebugDerive)] to the structure. It will dump the generated parser to stderr.
  • If the generated parser fails at runtime, try adding #[nom(Debug)] to the structure or to fields. It wraps subparsers in dbg_dmp and will print the field name and input to stderr if the parser fails.

Derive Macros


The Nom derive automatically generates a parse function for the structure using nom parsers. It will try to infer parsers for primitive of known types, but also allows you to specify parsers using custom attributes.


This derive macro behaves exactly like Nom derive, except it prints the generated parser on stderr. This is helpful for debugging generated parsers.