Skip to content

Commit c80176f

Browse files
committed
support optional fields
You can do `$?` to try and parse something. This is convenient.
1 parent a0705d9 commit c80176f

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

crates/formality-macros/src/debug.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,7 @@ fn debug_variant_with_attr(
149149
stream.extend(match op {
150150
spec::FormalitySpecOp::Field {
151151
name,
152-
mode: FieldMode::Single,
152+
mode: FieldMode::Single | FieldMode::Optional,
153153
} => {
154154
quote_spanned! {
155155
name.span() =>

crates/formality-macros/src/parse.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,17 @@ fn parse_variant_with_attr(
157157
}
158158
}
159159

160+
spec::FormalitySpecOp::Field {
161+
name,
162+
mode: FieldMode::Optional,
163+
} => {
164+
quote_spanned! {
165+
name.span() =>
166+
let (#name, text) = parse::CoreParse::parse_opt(scope, text)?;
167+
let #name = #name.unwrap_or_default();
168+
}
169+
}
170+
160171
spec::FormalitySpecOp::Field {
161172
name,
162173
mode: FieldMode::Many,

crates/formality-macros/src/spec.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ pub enum FieldMode {
4545
/// If the next op is a fixed character, stop parsing when we see that.
4646
/// Otherwise parse as many we can greedily.
4747
Comma,
48+
49+
/// $?x -- parse `x` if we can, but otherwise use `Default`
50+
Optional,
4851
}
4952

5053
impl syn::parse::Parse for FormalitySpec {
@@ -124,6 +127,7 @@ fn parse_variable_binding(
124127
let mode = match punct.as_char() {
125128
',' => FieldMode::Comma,
126129
'*' => FieldMode::Many,
130+
'?' => FieldMode::Optional,
127131
'$' => return Ok(FormalitySpecOp::Char { punct }),
128132
_ => return error(),
129133
};

0 commit comments

Comments
 (0)