11 KiB
nom, eating data byte by byte
nom is a parser combinators library written in Rust. Its goal is to provide tools to build safe parsers without compromising the speed or memory consumption. To that end, it uses extensively Rust's strong typing and memory safety to produce fast and correct parsers, and provides macros and traits to abstract most of the error prone plumbing.
Example
Hexadecimal color parser:
#[macro_use]
extern crate nom;
#[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 {
let c = c as u8;
(c >= 0x30 && c <= 0x39) || (c >= 0x41 && c <= 0x46) || (c >= 0x61 && c <= 0x66)
}
named!(hex_primary<&str, u8>,
map_res!(take_while_m_n!(2, 2, is_hex_digit), from_hex)
);
named!(hex_color<&str, Color>,
do_parse!(
tag!("#") >>
red: hex_primary >>
green: hex_primary >>
blue: hex_primary >>
(Color { red, green, blue })
)
);
#[test]
fn parse_color() {
assert_eq!(hex_color("#2F14DF"), Ok(("", Color {
red: 47,
green: 20,
blue: 223,
})));
}
Documentation
- Reference documentation.
- Various design documents and tutorials.
- list of combinators and their behaviour
If you need any help developing your parsers, please ping geal
on IRC (mozilla, freenode, geeknode, oftc), go to #nom
on Mozilla IRC, or on the Gitter chat room.
Why use nom
If you want to write:
binary format parsers
nom was designed to properly parse binary formats from the beginning. Compared to the usual handwritten C parsers, nom parsers are just as fast, free from buffer overflow vulnerabilities, and handle common patterns for you:
- TLV
- bit level parsing
- hexadecimal viewer in the debugging macros for easy data analysis
- streaming parsers for network formats and huge files
Example projects:
Text format parsers
While nom was made for binary format at first, but it soon grew to work just as well with text formats. From line based formats like CSV, to more complex, nested formats such as JSON, nom can manage it, and provides you with useful tools:
- fast case insensitive comparison
- recognizers for escaped strings
- regular expressions can be embedded in nom parsers to represent complex character patterns succintly
- special care has been given to managing non ASCII characters properly
Example projects:
Programming language parsers
While programming language parsers are usually written manually for more flexibility and performance, nom can be (and has been successfully) used as a prototyping parser for a language.
nom will get you started quickly with powerful custom error types, that you can leverage with nom_locate to pinpoint the exact line and column of the error. No need for separate tokenizing, lexing and parsing phases: nom can automatically handle whitespace parsing, and construct an AST in place.
Example projects:
- PHP VM
- Rust parser
- eve language prototype
- xshade shading language
Streaming formats
While a lot of formats (and the code handling them) assume that they can fit the complete data in memory, there are formats for which we only get a part of the data at once, like network formats, or huge files. nom has been designed for a correct behaviour with partial data: if there is not enough data to decide, nom will tell you it needs more instead of silently returning a wrong result. Whether your data comes entirely or in chunks, the result should be the same.
It allows you to build powerful, deterministic state machines for your protocols.
Example projects:
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 file and generating the corresponding code, you use very small functions with 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 has 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
Technical features
nom parsers are for:
- byte-oriented: the basic type is
&[u8]
and parsers will work as much as possible on byte array slices (but are not limited to them) - bit-oriented: nom can address a byte slice as a bit stream
- string-oriented: the same kind of combinators can apply on UTF-8 strings as well
- zero-copy: if a parser returns a subset of its input data, it will return a slice of that input, without copying
- streaming: nom can work on partial data and detect when it needs more data to produce a correct result
- macro based syntax: easier parser building through macro usage
- descriptive errors: the parsers can aggregate a list of error codes with pointers to the incriminated input slice. Those error lists can be pattern matched to provide useful messages.
- custom error types: you can provide a specific type to improve errors returned by parsers
- safe parsing: nom leverages Rust's safe memory handling and powerful types, and parsers are routinely fuzzed and tested with real world data. So far, the only flaws found by fuzzing were in code written outside of nom
- speed: benchmarks have shown that nom parsers often outperform many parser combinators library like Parsec and attoparsec, some regular expression engines and even handwritten C parsers
Some benchmarks are available on Github.
Installation
nom is available on crates.io and can be included in your Cargo enabled project like this:
[dependencies]
nom = "^3.2"
Then include it in your code like this:
#[macro_use]
extern crate nom;
NOTE: if you have existing code using nom below the 4.0 version, please take a look at the upgrade documentation to handle the breaking changes.
There are a few compilation features:
std
: (activated by default) if disabled, nom can work inno_std
buildsnightly
: enables helpful error messages if you use a nightly compilerregexp
: enables regular expression parsers with theregex
crateregexp_macros
: enables regular expression parsers with theregex
andregex_macros
crates. Regular expressions can be defined at compile time, but it requires a nightly version of rustcverbose-errors
: accumulate error codes and input positions as you backtrack through the parser tree. This gives you precise information about which part of the parser was affected by which part of the input
You can activate those features like this:
[dependencies.nom]
version = "^3.2"
features = ["regexp"]
Parsers written with nom
Here is a list of known projects using nom:
- Text file formats:
- Programming languages:
- Interface definition formats:
- Audio, video and image formats:
- Document formats:
- Database formats:
- Network protocol formats:
- Language specifications:
- using nom as lexer and parser
Want to create a new parser using nom
? A list of not yet implemented formats is available here.
Want to add your parser here? Create a pull request for it!