Crate nom
nom, eating data byte by byte
nom is a parser combinator library with a focus on safe parsing, streaming patterns, and as much as possible zero copy.
Example
use ;
The code is available on GitHub
There are a few guides with more details about how to write parsers, or the error management system. You can also check out the [recipes] module that contains examples of common patterns.
Looking for a specific combinator? Read the "choose a combinator" guide
If you are upgrading to nom 5.0, please read the migration document.
Parser combinators
Parser combinators are an approach to parsers that is very different from software like lex and yacc. Instead of writing the grammar in a separate syntax and generating the corresponding code, you use very small functions with very specific purposes, like "take 5 bytes", or "recognize the word 'HTTP'", and assemble them in meaningful patterns like "recognize 'HTTP', then a space, then a version". The resulting code is small, and looks like the grammar you would have written with other parser approaches.
This gives us a few advantages:
- The parsers are small and easy to write
- The parsers components are easy to reuse (if they're general enough, please add them to nom!)
- The parsers components are easy to test separately (unit tests and property-based tests)
- The parser combination code looks close to the grammar you would have written
- You can build partial parsers, specific to the data you need at the moment, and ignore the rest
Here is an example of one such parser, to recognize text between parentheses:
use ;
It defines a function named parens which will recognize a sequence of the
character (, the longest byte array not containing ), then the character
), and will return the byte array in the middle.
Here is another parser, written without using nom's combinators this time:
use ;
#
This function takes a byte array as input, and tries to consume 4 bytes. Writing all the parsers manually, like this, is dangerous, despite Rust's safety features. There are still a lot of mistakes one can make. That's why nom provides a list of functions to help in developing parsers.
With functions, you would write it like this:
use ;
A parser in nom is a function which, for an input type I, an output type O
and an optional error type E, will have the following signature:
;
Or like this, if you don't want to specify a custom error type (it will be (I, ErrorKind) by default):
;
IResult is an alias for the Result type:
use ;
type IResult<I, O, E = > = ;
It can have the following values:
- A correct result
Ok((I,O))with the first element being the remaining of the input (not parsed yet), and the second the output value; - An error
Err(Err::Error(c))withcan error that can be built from the input position and a parser specific error - An error
Err(Err::Incomplete(Needed))indicating that more input is necessary.Neededcan indicate how much data is needed - An error
Err(Err::Failure(c)). It works like theErrorcase, except it indicates an unrecoverable error: We cannot backtrack and test another parser
Please refer to the "choose a combinator" guide for an exhaustive list of parsers. See also the rest of the documentation here.
Making new parsers with function combinators
nom is based on functions that generate parsers, with a signature like
this: (arguments) -> impl Fn(Input) -> IResult<Input, Output, Error>.
The arguments of a combinator can be direct values (like take which uses
a number of bytes or character as argument) or even other parsers (like
delimited which takes as argument 3 parsers, and returns the result of
the second one if all are successful).
Here are some examples:
use IResult;
use ;
Combining parsers
There are higher level patterns, like the alt combinator, which
provides a choice between multiple parsers. If one branch fails, it tries
the next, and returns the result of the first parser that succeeds:
use ;
use alt;
use tag;
let mut alt_tags = alt;
assert_eq!;
assert_eq!;
assert_eq!;
The opt combinator makes a parser optional. If the child parser returns
an error, opt will still succeed and return None:
use ;
assert_eq!;
assert_eq!;
many0 applies a parser 0 or more times, and returns a vector of the aggregated results:
#
#
#
#
Here are some basic combinators available:
opt: Will make the parser optional (if it returns theOtype, the new parser returnsOption<O>)many0: Will apply the parser 0 or more times (if it returns theOtype, the new parser returnsVec<O>)many1: Will apply the parser 1 or more times
There are more complex (and more useful) parsers like tuples, which are used to apply a series of parsers then assemble their results.
Example with a tuple of parsers:
#
But you can also use a sequence of combinators written in imperative style,
thanks to the ? operator:
#
Streaming / Complete
Some of nom's modules have streaming or complete submodules. They hold
different variants of the same combinators.
A streaming parser assumes that we might not have all of the input data. This can happen with some network protocol or large file parsers, where the input buffer can be full and need to be resized or refilled.
A complete parser assumes that we already have all of the input data. This will be the common case with small files that can be read entirely to memory.
Here is how it works in practice:
use ;
// both parsers will take 4 bytes as expected
assert_eq!;
assert_eq!;
// if the input is smaller than 4 bytes, the streaming parser
// will return `Incomplete` to indicate that we need more data
assert_eq!;
// but the complete parser will return an error
assert_eq!;
// the alpha0 function recognizes 0 or more alphabetic characters
// if there's a clear limit to the recognized characters, both parsers work the same way
assert_eq!;
assert_eq!;
// but when there's no limit, the streaming version returns `Incomplete`, because it cannot
// know if more input data should be recognized. The whole input could be "abcd;", or
// "abcde;"
assert_eq!;
// while the complete version knows that all of the data is there
assert_eq!;
Going further: Read the guides, check out the [recipes]!
Modules
- bits Bit level parsers
- branch Choice combinators
- bytes Parsers recognizing bytes streams
- character Character specific parsers and combinators
- combinator General purpose combinators
- error Error management
-
lib
Lib module to re-export everything needed from
stdorcore/alloc. This is howserdedoes it, albeit there it is not public. - multi Combinators applying their child parser multiple times
- number Parsers recognizing numbers
-
recipes
Common recipes to build nom parsers
- sequence Combinators applying parsers in sequence
Structs
-
And
Implementation of
Parser::and -
AndThen
Implementation of
Parser::and_then - Check Applies the parser, but do not a produce a value
- Complete Indicates that the input data is complete: no more data may be added later
- Emit Produces a value. This is the default behaviour for parsers
-
FlatMap
Implementation of
Parser::flat_map -
Into
Implementation of
Parser::into -
Map
Implementation of
Parser::map -
MapOpt
Implementation of
Parser::map_opt -
MapRes
Implementation of
Parser::map_res -
Or
Implementation of
Parser::or - OutputM Holds the parser execution modifiers: output [Mode], error [Mode] and streaming behaviour for input data
- SaturatingIterator A saturating iterator for usize.
- Streaming Indicates that the input data is streaming: more data may be available later
Enums
- CompareResult Indicates whether a comparison was successful, an error, or if more data was needed
-
Err
The
Errenum indicates the parser was not successful -
Needed
Contains information on needed data if a parser returned
Incomplete
Traits
- AsBytes Helper trait for types that can be viewed as a byte slice
- AsChar Transforms common types to a char for basic token parsing
- Compare Abstracts comparison operations
- ErrorConvert Equivalent From implementation to avoid orphan rules in bits parsers
-
ExtendInto
Abstracts something which can extend an
Extend. Used to build modified input slices inescaped_transform - FindSubstring Look for a substring in self
- FindToken Look for a token in self
- Finish Helper trait to convert a parser's result to a more manageable type
- HexDisplay Helper trait to show a byte slice as a hex dump
- Input Parser input types must implement this trait
- IsStreaming Specifies the behaviour when a parser encounters an error that could be due to partial ata
- Mode Parser mode: influences how combinators build values
- NomRange Abstractions for range-like types.
- Offset Useful functions to calculate the offset between slices and show a hexdump of a slice
- OutputMode Trait Defining the parser's execution
-
ParseTo
Used to integrate
str'sparse()method - Parser All nom parsers implement this trait
- ToUsize Helper trait to convert numbers to usize.
Type Aliases
Macros
-
error_node_position
Creates a parse error from a
nom::ErrorKind, the position in the input and the next error in the parsing tree -
error_position
Creates a parse error from a
nom::ErrorKindand the position in the input