Crate nom[][src]

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

extern crate nom;

use nom::{
  IResult,
  bytes::complete::{tag, take_while_m_n},
  combinator::map_res,
  sequence::tuple};

#[derive(Debug,PartialEq)]
pub struct Color {
  pub red:     u8,
  pub green:   u8,
  pub blue:    u8,
}

fn from_hex(input: &str) -> Result<u8, std::num::ParseIntError> {
  u8::from_str_radix(input, 16)
}

fn is_hex_digit(c: char) -> bool {
  c.is_digit(16)
}

fn hex_primary(input: &str) -> IResult<&str, u8> {
  map_res(
    take_while_m_n(2, 2, is_hex_digit),
    from_hex
  )(input)
}

fn hex_color(input: &str) -> IResult<&str, Color> {
  let (input, _) = tag("#")(input)?;
  let (input, (red, green, blue)) = tuple((hex_primary, hex_primary, hex_primary))(input)?;

  Ok((input, Color { red, green, blue }))
}

fn main() {
  assert_eq!(hex_color("#2F14DF"), Ok(("", Color {
    red: 47,
    green: 20,
    blue: 223,
  })));
}

The code is available on Github

There are a few guides with more details about the design of nom macros, how to write parsers, or the error management system.

Looking for a specific combinator? Read the “choose a combinator” guide

If you are upgrading to nom 5.0, please read the migration document.

See also the FAQ.

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 a very specific purpose, like “take 5 bytes”, or “recognize the word ‘HTTP’”, and assemble then 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:

Here is an example of one such parser, to recognize text between parentheses:

use nom::{
  IResult,
  sequence::delimited,
  // see the "streaming/complete" paragraph lower for an explanation of these submodules
  character::complete::char,
  bytes::complete::is_not
};

fn parens(input: &str) -> IResult<&str, &str> {
  delimited(char('('), is_not(")"), char(')'))(input)
}

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:

#[macro_use]
extern crate nom;

use nom::{IResult, Err, Needed};

fn take4(i: &[u8]) -> IResult<&[u8], &[u8]>{
  if i.len() < 4 {
    Err(Err::Incomplete(Needed::Size(4)))
  } else {
    Ok((&i[4..], &i[0..4]))
  }
}

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 function and macros to help in developing parsers.

With functions, you would write it like this:

use nom::{IResult, bytes::streaming::take};
fn take4(input: &str) -> IResult<&str, &str> {
  take(4u8)(input)
}

With macros, you would write it like this:

#[macro_use]
extern crate nom;

named!(take4, take!(4));

nom has used macros for combinators from versions 1 to 4, and from version 5, it proposes new combinators as functions, but still allows the macros style (macros have been rewritten to use the functions under the hood). For new parsers, we recommend using the functions instead of macros, since rustc messages will be much easier to understand.

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:

fn parser(input: I) -> IResult<I, O, E>;

Or like this, if you don’t want to specify a custom error type (it will be u32 by default):

fn parser(input: I) -> IResult<I, O>;

IResult is an alias for the Result type:

use nom::{Needed, error::ErrorKind};

type IResult<I, O, E = (I,ErrorKind)> = Result<(I, O), Err<E>>;

enum Err<E> {
  Incomplete(Needed),
  Error(E),
  Failure(E),
}

It can have the following values:

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 nom::IResult;
use nom::bytes::complete::{tag, take};
fn abcd_parser(i: &str) -> IResult<&str, &str> {
  tag("abcd")(i) // will consume bytes if the input begins with "abcd"
}

fn take_10(i: &[u8]) -> IResult<&[u8], &[u8]> {
  take(10u8)(i) // will consume and return 10 bytes of input
}

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 nom::IResult;
use nom::branch::alt;
use nom::bytes::complete::tag;

let alt_tags = alt((tag("abcd"), tag("efgh")));

assert_eq!(alt_tags(&b"abcdxxx"[..]), Ok((&b"xxx"[..], &b"abcd"[..])));
assert_eq!(alt_tags(&b"efghxxx"[..]), Ok((&b"xxx"[..], &b"efgh"[..])));
assert_eq!(alt_tags(&b"ijklxxx"[..]), Err(nom::Err::Error((&b"ijklxxx"[..], nom::error::ErrorKind::Tag))));

The opt combinator makes a parser optional. If the child parser returns an error, opt will still succeed and return None:

use nom::{IResult, combinator::opt, bytes::complete::tag};
fn abcd_opt(i: &[u8]) -> IResult<&[u8], Option<&[u8]>> {
  opt(tag("abcd"))(i)
}

assert_eq!(abcd_opt(&b"abcdxxx"[..]), Ok((&b"xxx"[..], Some(&b"abcd"[..]))));
assert_eq!(abcd_opt(&b"efghxxx"[..]), Ok((&b"efghxxx"[..], None)));

many0 applies a parser 0 or more times, and returns a vector of the aggregated results:

use nom::{IResult, multi::many0, bytes::complete::tag};
use std::str;

fn multi(i: &str) -> IResult<&str, Vec<&str>> {
  many0(tag("abcd"))(i)
}

let a = "abcdef";
let b = "abcdabcdef";
let c = "azerty";
assert_eq!(multi(a), Ok(("ef",     vec!["abcd"])));
assert_eq!(multi(b), Ok(("ef",     vec!["abcd", "abcd"])));
assert_eq!(multi(c), Ok(("azerty", Vec::new())));

Here are some basic combining macros available:

There are more complex (and more useful) parsers like tuple!, which is used to apply a series of parsers then assemble their results.

Example with tuple:

use nom::{error::ErrorKind, Needed,
number::streaming::be_u16,
bytes::streaming::{tag, take},
sequence::tuple};

let tpl = tuple((be_u16, take(3u8), tag("fg")));

assert_eq!(
  tpl(&b"abcdefgh"[..]),
  Ok((
    &b"h"[..],
    (0x6162u16, &b"cde"[..], &b"fg"[..])
  ))
);
assert_eq!(tpl(&b"abcde"[..]), Err(nom::Err::Incomplete(Needed::Size(2))));
let input = &b"abcdejk"[..];
assert_eq!(tpl(input), Err(nom::Err::Error((&input[5..], ErrorKind::Tag))));

But you can also use a sequence of combinators written in imperative style, thanks to the ? operator:

use nom::{IResult, bytes::complete::tag};

#[derive(Debug, PartialEq)]
struct A {
  a: u8,
  b: u8
}

fn ret_int1(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,1)) }
fn ret_int2(i:&[u8]) -> IResult<&[u8], u8> { Ok((i,2)) }

fn f(i: &[u8]) -> IResult<&[u8], A> {
  // if successful, the parser returns `Ok((remaining_input, output_value))` that we can destructure
  let (i, _) = tag("abcd")(i)?;
  let (i, a) = ret_int1(i)?;
  let (i, _) = tag("efgh")(i)?;
  let (i, b) = ret_int2(i)?;

  Ok((i, A { a, b }))
}

let r = f(b"abcdefghX");
assert_eq!(r, Ok((&b"X"[..], A{a: 1, b: 2})));

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 nom::{IResult, Err, Needed, error::ErrorKind, bytes, character};

fn take_streaming(i: &[u8]) -> IResult<&[u8], &[u8]> {
  bytes::streaming::take(4u8)(i)
}

fn take_complete(i: &[u8]) -> IResult<&[u8], &[u8]> {
  bytes::complete::take(4u8)(i)
}

// both parsers will take 4 bytes as expected
assert_eq!(take_streaming(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));
assert_eq!(take_complete(&b"abcde"[..]), Ok((&b"e"[..], &b"abcd"[..])));

// if the input is smaller than 4 bytes, the streaming parser
// will return `Incomplete` to indicate that we need more data
assert_eq!(take_streaming(&b"abc"[..]), Err(Err::Incomplete(Needed::Size(4))));

// but the complete parser will return an error
assert_eq!(take_complete(&b"abc"[..]), Err(Err::Error((&b"abc"[..], ErrorKind::Eof))));

// the alpha0 function recognizes 0 or more alphabetic characters
fn alpha0_streaming(i: &str) -> IResult<&str, &str> {
  character::streaming::alpha0(i)
}

fn alpha0_complete(i: &str) -> IResult<&str, &str> {
  character::complete::alpha0(i)
}

// if there's a clear limit to the recognized characters, both parsers work the same way
assert_eq!(alpha0_streaming("abcd;"), Ok((";", "abcd")));
assert_eq!(alpha0_complete("abcd;"), Ok((";", "abcd")));

// 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!(alpha0_streaming("abcd"), Err(Err::Incomplete(Needed::Size(1))));

// while the complete version knows that all of the data is there
assert_eq!(alpha0_complete("abcd"), Ok(("", "abcd")));

Going further: read the guides!

Re-exports

pub use self::methods::*;
pub use self::bits::*;
pub use self::whitespace::*;

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 std or core/alloc. This is how serde does it, albeit there it is not public.

methods

method combinators

multi

combinators applying their child parser multiple times

number

parsers recognizing numbers

sequence

combinators applying parsers in sequence

whitespace

Support for whitespace delimited formats

Macros

add_return_error

Add an error if the child parser fails

alt

Try a list of parsers and return the result of the first successful one

apply_m

do not use: method combinators moved to the nom-methods crate

bits

Transforms its byte slice input into a bit stream for the underlying parser. This allows the given bit stream parser to work on a byte slice input.

bytes

Counterpart to bits, bytes! transforms its bit stream input into a byte slice for the underlying parser, allowing byte-slice parsers to work on bit streams.

call

Used to wrap common expressions and function as macros

call_m

do not use: method combinators moved to the nom-methods crate

char

matches one character: `char!(char) => &u8 -> IResult<&u8, char>

complete

replaces a Incomplete returned by the child parser with an Error

cond

cond!(bool, I -> IResult<I,O>) => I -> IResult<I, Option<O>> Conditional combinator

count

count!(I -> IResult<I,O>, nb) => I -> IResult<I, Vec<O>> Applies the child parser a specified number of times

dbg

Prints a message if the parser fails

dbg_dmp

Prints a message and the input if the parser fails

delimited

delimited!(I -> IResult<I,T>, I -> IResult<I,O>, I -> IResult<I,U>) => I -> IResult<I, O> delimited(opening, X, closing) returns X

do_parse

do_parse!(I->IResult<I,A> >> I->IResult<I,B> >> ... I->IResult<I,X> , ( O ) ) => I -> IResult<I, O> do_parse applies sub parsers in a sequence. it can store intermediary results and make them available for later parsers

eat_separator

helper macros to build a separator parser

eof

eof!() returns its input if it is at the end of input data

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::ErrorKind and the position in the input

escaped

escaped!(T -> IResult<T, T>, U, T -> IResult<T, T>) => T -> IResult<T, T> where T: InputIter, U: AsChar matches a byte string with escaped characters.

escaped_transform

escaped_transform!(&[T] -> IResult<&[T], &[T]>, T, &[T] -> IResult<&[T], &[T]>) => &[T] -> IResult<&[T], Vec<T>> matches a byte string with escaped characters.

exact

exact!() will fail if the child parser does not consume the whole data

fix_error

translate parser result from IResult<I,O,u32> to IResult<I,O,E> with a custom type

flat_map

flat_map!(R -> IResult<R,S>, S -> IResult<S,T>) => R -> IResult<R, T>

fold_many0

fold_many0!(I -> IResult<I,O>, R, Fn(R, O) -> R) => I -> IResult<I, R> Applies the parser 0 or more times and folds the list of return values

fold_many1

fold_many1!(I -> IResult<I,O>, R, Fn(R, O) -> R) => I -> IResult<I, R> Applies the parser 1 or more times and folds the list of return values

fold_many_m_n

fold_many_m_n!(usize, usize, I -> IResult<I,O>, R, Fn(R, O) -> R) => I -> IResult<I, R> Applies the parser between m and n times (n included) and folds the list of return value

i16

if the parameter is nom::Endianness::Big, parse a big endian i16 integer, otherwise a little endian i16 integer

i32

if the parameter is nom::Endianness::Big, parse a big endian i32 integer, otherwise a little endian i32 integer

i64

if the parameter is nom::Endianness::Big, parse a big endian i64 integer, otherwise a little endian i64 integer

i128

if the parameter is nom::Endianness::Big, parse a big endian i64 integer, otherwise a little endian i64 integer

is_a

is_a!(&[T]) => &[T] -> IResult<&[T], &[T]> returns the longest list of bytes that appear in the provided array

is_not

is_not!(&[T:AsBytes]) => &[T] -> IResult<&[T], &[T]> returns the longest list of bytes that do not appear in the provided array

length_count

length_count!(I -> IResult<I, nb>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>> gets a number from the first parser, then applies the second parser that many times

length_data

length_data!(I -> IResult<I, nb>) => O

length_value

length_value!(I -> IResult<I, nb>, I -> IResult<I,O>) => I -> IResult<I, O>

many0

many0!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>> Applies the parser 0 or more times and returns the list of results in a Vec.

many0_count

many0_count!(I -> IResult<I,O>) => I -> IResult<I, usize> Applies the parser 0 or more times and returns the number of times the parser was applied.

many1

many1!(I -> IResult<I,O>) => I -> IResult<I, Vec<O>> Applies the parser 1 or more times and returns the list of results in a Vec

many1_count

many1_count!(I -> IResult<I,O>) => I -> IResult<I, usize> Applies the parser 1 or more times and returns the number of times the parser was applied.

many_m_n

many_m_n!(usize, usize, I -> IResult<I,O>) => I -> IResult<I, Vec<O>> Applies the parser between m and n times (n included) and returns the list of results in a Vec

many_till

many_till!(I -> IResult<I,O>, I -> IResult<I,P>) => I -> IResult<I, (Vec<O>, P)> Applies the first parser until the second applies. Returns a tuple containing the list of results from the first in a Vec and the result of the second.

map

map!(I -> IResult<I, O>, O -> P) => I -> IResult<I, P>

map_opt

map_opt!(I -> IResult<I, O>, O -> Option<P>) => I -> IResult<I, P> maps a function returning an Option on the output of a parser

map_res

map_res!(I -> IResult<I, O>, O -> Result<P>) => I -> IResult<I, P> maps a function returning a Result on the output of a parser

method

do not use: method combinators moved to the nom-methods crate

named

Makes a function from a parser combination

named_args

Makes a function from a parser combination with arguments.

named_attr

Makes a function from a parser combination, with attributes

none_of

matches anything but the provided characters

not

not!(I -> IResult<I,O>) => I -> IResult<I, ()> returns a result only if the embedded parser returns Error or Err(Err::Incomplete) does not consume the input

one_of

Character level parsers matches one of the provided characters

opt

opt!(I -> IResult<I,O>) => I -> IResult<I, Option<O>> make the underlying parser optional

opt_res

opt_res!(I -> IResult<I,O>) => I -> IResult<I, Result<nom::Err,O>> make the underlying parser optional

pair

pair!(I -> IResult<I,O>, I -> IResult<I,P>) => I -> IResult<I, (O,P)> pair returns a tuple of the results of its two child parsers of both succeed

parse_to

parse_to!(O) => I -> IResult<I, O> uses the parse method from std::str::FromStr to convert the current input to the specified type

peek

peek!(I -> IResult<I,O>) => I -> IResult<I, O> returns a result without consuming the input

permutation

permutation!(I -> IResult<I,A>, I -> IResult<I,B>, ... I -> IResult<I,X> ) => I -> IResult<I, (A,B,...X)> applies its sub parsers in a sequence, but independent from their order this parser will only succeed if all of its sub parsers succeed

preceded

preceded!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, O> preceded returns the result of its second parser if both succeed

recognize

recognize!(I -> IResult<I, O> ) => I -> IResult<I, I> if the child parser was successful, return the consumed input as produced value

return_error

Prevents backtracking if the child parser fails

sep

sep is the parser rewriting macro for whitespace separated formats

separated_list

separated_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>> separated_list(sep, X) returns a Vec

separated_nonempty_list

separated_nonempty_list!(I -> IResult<I,T>, I -> IResult<I,O>) => I -> IResult<I, Vec<O>> separated_nonempty_list(sep, X) returns a Vec

separated_pair

separated_pair!(I -> IResult<I,O>, I -> IResult<I, T>, I -> IResult<I,P>) => I -> IResult<I, (O,P)> separated_pair(X,sep,Y) returns a tuple of its first and third child parsers if all 3 succeed

switch

switch!(I -> IResult<I,P>, P => I -> IResult<I,O> | ... | P => I -> IResult<I,O> ) => I -> IResult<I, O> choose the next parser depending on the result of the first one, if successful, and returns the result of the second parser

tag

tag!(&[T]: nom::AsBytes) => &[T] -> IResult<&[T], &[T]> declares a byte array as a suite to recognize

tag_bits

Matches the given bit pattern.

tag_no_case

tag_no_case!(&[T]) => &[T] -> IResult<&[T], &[T]> declares a case insensitive ascii string as a suite to recognize

take

take!(nb) => &[T] -> IResult<&[T], &[T]> generates a parser consuming the specified number of bytes

take_bits

Consumes the specified number of bits and returns them as the specified type.

take_str

take_str!(nb) => &[T] -> IResult<&[T], &str> same as take! but returning a &str

take_till

take_till!(T -> bool) => &[T] -> IResult<&[T], &[T]> returns the longest list of bytes until the provided function succeeds

take_till1

take_till1!(T -> bool) => &[T] -> IResult<&[T], &[T]> returns the longest non empty list of bytes until the provided function succeeds

take_until

take_until!(tag) => &[T] -> IResult<&[T], &[T]> consumes data until it finds the specified tag.

take_until1

take_until1!(tag) => &[T] -> IResult<&[T], &[T]> consumes data (at least one byte) until it finds the specified tag

take_while

take_while!(T -> bool) => &[T] -> IResult<&[T], &[T]> returns the longest list of bytes until the provided function fails.

take_while1

take_while1!(T -> bool) => &[T] -> IResult<&[T], &[T]> returns the longest (non empty) list of bytes until the provided function fails.

take_while_m_n

take_while_m_n!(m: usize, n: usize, T -> bool) => &[T] -> IResult<&[T], &[T]> returns a list of bytes or characters for which the provided function returns true. the returned list’s size will be at least m, and at most n

tap

tap!(name: I -> IResult<I,O> => { block }) => I -> IResult<I, O> allows access to the parser’s result without affecting it

terminated

terminated!(I -> IResult<I,O>, I -> IResult<I,T>) => I -> IResult<I, O> terminated returns the result of its first parser if both succeed

try_parse

A bit like std::try!, this macro will return the remaining input and parsed value if the child parser returned Ok, and will do an early return for the Err side.

tuple

tuple!(I->IResult<I,A>, I->IResult<I,B>, ... I->IResult<I,X>) => I -> IResult<I, (A, B, ..., X)> chains parsers and assemble the sub results in a tuple.

u16

if the parameter is nom::Endianness::Big, parse a big endian u16 integer, otherwise a little endian u16 integer

u32

if the parameter is nom::Endianness::Big, parse a big endian u32 integer, otherwise a little endian u32 integer

u64

if the parameter is nom::Endianness::Big, parse a big endian u64 integer, otherwise a little endian u64 integer

u128

if the parameter is nom::Endianness::Big, parse a big endian u128 integer, otherwise a little endian u128 integer

value

value!(T, R -> IResult<R, S> ) => R -> IResult<R, T>

verify

verify!(I -> IResult<I, O>, O -> bool) => I -> IResult<I, O> returns the result of the child parser if it satisfies a verification function

wrap_sep

applies the separator parser before the other parser

wsDeprecated

ws!(I -> IResult<I,O>) => I -> IResult<I, O>

Enums

CompareResult

indicates wether a comparison was successful, an error, or if more data was needed

Err

The Err enum 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 in escaped_transform

FindSubstring

look for a substring in self

FindToken

look for a token in self

HexDisplay

Helper trait to show a byte slice as a hex dump

InputIter

abstracts common iteration operations on the input type

InputLength

abstract method to calculate the input length

InputTake

abstracts slicing operations

InputTakeAtPosition

methods to take as much input as possible until the provided function returns true for the current element

Offset

useful functions to calculate the offset between slices and show a hexdump of a slice

ParseTo

used to integrate str’s parse() method

Slice

slicing operations using ranges

ToUsize

Helper trait to convert numbers to usize

UnspecializedInput

Dummy trait used for default implementations (currently only used for InputTakeAtPosition).

Functions

dbg_dmp

Prints a message and the input if the parser fails

Type Definitions

IResult

Holds the result of parsing functions