Skip to content

Commit

Permalink
Resolve issue 406 for structs
Browse files Browse the repository at this point in the history
  • Loading branch information
DJDuque committed Apr 25, 2024
1 parent 73211ad commit b1eb11e
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
16 changes: 14 additions & 2 deletions src/macros/seq.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
/// // Parse into structs / tuple-structs
/// fn field(input: &mut &[u8]) -> PResult<Field> {
/// seq!{Field {
/// namespace: empty.value(5),
/// // `#[temp]` fields can be referenced later
/// // but they are ignored when building the struct
/// #[temp] ten: empty.value(10),
/// namespace: empty.value(ten / 2),
/// name: alphanumeric1.map(|s: &[u8]| s.to_owned()),
/// // `_` fields are ignored when building the struct
/// _: (space0, b':', space0),
Expand Down Expand Up @@ -119,13 +122,14 @@ macro_rules! seq_parse_struct_fields {
};
(
$input: ident;
$head_field: ident : $head_parser: expr, $($fields: tt)*
$(#[temp])? $head_field: ident : $head_parser: expr, $($fields: tt)*
) => {
let $head_field = $head_parser.parse_next($input)?;
$crate::seq_parse_struct_fields!($input; $($fields)*)
};
(
$input: ident;
// `#[temp]` in the last field makes no sense
$head_field: ident : $head_parser: expr
) => {
let $head_field = $head_parser.parse_next($input)?;
Expand Down Expand Up @@ -192,6 +196,14 @@ macro_rules! seq_init_struct_fields {
) => {
$crate::seq_init_struct_fields!( (); $name ; $($inits)* )
};
(
(#[temp] $head_field: ident : $head_parser: expr, $($fields: tt)*);
$name: ident;
$($inits: tt)*
) =>
{
$crate::seq_init_struct_fields!( ( $($fields)* ) ; $name ; $($inits)* )
};
(
($head_field: ident : $head_parser: expr, $($fields: tt)*);
$name: ident;
Expand Down
40 changes: 40 additions & 0 deletions src/macros/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,46 @@ fn seq_struct_default_init() {
);
}

#[test]
fn seq_struct_referring_elided() {
#[derive(Debug, PartialEq, Default)]
struct Point {
x: u32,
y: u32,
}

fn parser(input: &mut &str) -> PResult<Point> {
seq! {
Point {
#[temp] half_x: dec_uint::<_, u32, _>,
x: empty.value(half_x * 2),
_: ',',
#[temp] half_y: dec_uint::<_, u32, _>,
y: empty.value(half_y * 2),
}
}
.parse_next(input)
}
assert_eq!(
parser.parse_peek("123,4 remaining"),
Ok((" remaining", Point { x: 246, y: 8 },)),
);
assert_eq!(
parser.parse_peek("123, remaining"),
Err(ErrMode::Backtrack(ParserError::from_error_kind(
&" remaining",
ErrorKind::Fail
)))
);
assert_eq!(
parser.parse_peek(""),
Err(ErrMode::Backtrack(ParserError::from_error_kind(
&"",
ErrorKind::Fail
)))
);
}

#[test]
fn seq_struct_trailing_comma_elided() {
#![allow(dead_code)]
Expand Down

0 comments on commit b1eb11e

Please sign in to comment.