#[parse_from]Expand description
This macro generates a nom_parse_trait::ParseFrom implementation for a struct or enum using
the provided nom expression(s). The expression should return a tuple for the parsed fields.
§Examples
§Basic struct with fields
This first example shows how to parse a simple struct with two fields, using the separated_pair
combinator. Here we also show some of the special parsing that goes on behind the scenes, where
the special {} syntax means that it infers the type parser it needs to use in that place. Also,
we accept normal strings as matching input, which will be translated to tag function calls.
use nom_parse_macros::parse_from;
#[parse_from(separated_pair({}, (space0, ",", space0), {}))]
struct NumberPair {
x: u32,
y: u32,
}§Basic enum with variants
This example shows how we can define a format for each variant in an enum. The first variant
actually uses the default ParseFrom implementation for parsing the u32. The Numbers variant
uses a custom format, which is a delimited list of u32 values.
use nom_parse_macros::parse_from;
#[parse_from]
enum MultipleTypes {
Number(u32),
#[format(delimited('(', separated_list0(",", {}), ')'))]
Numbers(Vec<u32>),
}§Derived fields
Sometimes it’s useful to have a field that is not actually parsed, but derived from the other
fields. This can be done with the #[derived] attribute. In this example, we derive the sum of
the two fields x and y.
use nom_parse_macros::parse_from;
#[parse_from(separated_pair({}, (space0, ",", space0), {}))]
struct NumberPair {
x: u32,
y: u32,
#[derived(x + y)]
sum: u32,
}§Match verbatim
This example shows how to match a string verbatim. This is useful when you have a very simple
format that you want to parse. In this case, we match a vector inside braces. As you can see
the {} placeholders are replaced with the corresponding field parsers.
use nom_parse_macros::parse_from;
#[parse_from(match "({}, {})")]
struct Vector {
x: f32,
y: f32,
}§Adding extra where clauses
This example shows how to add extra where clauses to the generated implementation. This is useful when the default trait bounds are not sufficient for your use case. In this case, we add a bound that the type N must implement the Default trait.
Both the standard where clause of the struct itself as well as the extra where clause in the macro are included in the generated implementation.
use nom_parse_macros::parse_from;
#[parse_from(separated_pair({}, (space0, "->", space0), {}) where N: Default)]
struct LineSegment<const D: usize, N> where N: Copy {
start: [N; D],
end: [N; D],
}