Attribute Macro parse_from

Source
#[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,
}