How to handle a missing list value? #305
-
I would like to parse something as a list, but where some values might be missing, for example consider a CSV file:
I hacked something by having an action on the separator (and if I see two separators without value, observe an empty), but I have the feeling it's not the cleanest solution. I looked through the rules but I didn't find something like opt_or_else<Foo, Bar> that would match a Foo, or trigger action for Bar if Foo wasn't available. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 2 replies
-
This is very similar to error recovery. Take a look at the examples for that. My approach is to use if_then_else like this: struct foo : digit { }; // Any single digit is a foo
struct bar : success { }; // bar always succeeds, used to activate an action or create a parse tree node.
struct COMMA : one< ',' > { };
struct ws : space { };
struct possible_foo :
if_then_else<
at< foo >, // If we're at a foo
foo, // then process it
bar // otherwise process a bar
> { };
struct csv : list< possible_foo, COMMA, ws > { }; This may not do exactly what you want, but it should help point you in the right direction, I think. Given your input, the trace goes like this:
|
Beta Was this translation helpful? Give feedback.
-
Just use struct Foo : ... {};
struct Bar : success {};
struct OptFoo : sor< Foo, Bar > {}; Which will trigger the action for If you want to fail the whole rule when struct FooWithFailActionBar : sor< Foo, seq< Bar, failure > > {}; |
Beta Was this translation helpful? Give feedback.
-
Another possibility, keeping the CSV example, is to set up the fields to also match on empty content, e.g.
where the action for |
Beta Was this translation helpful? Give feedback.
-
Thank you, I have implemented a combination of @d-frey and @ColinH answers, because I need to be able to handle a missing value after the last comma too. |
Beta Was this translation helpful? Give feedback.
Just use
sor<>
:Which will trigger the action for
Foo
if it matches, the action forBar
otherwise.If you want to fail the whole rule when
Foo
doesn't match, but you still want an action forBar
to be triggered when it fails, you can use: