Sprache Part 4: Or and XOr
Contents
This is part of a series of posts documenting Sprache:
- Sprache Part 1: Parsing Characters
- Sprache Part 2: Parsing Strings
- Sprache Part 3: Repetition (Many, AtLeastOnce, Until, Repeat, Once)
- Sprache Part 4: Or and XOr
- Sprache Part 5: Select, Return, and Regex
- Sprache Part 6: DelimitedBy
- Sprache Part 7: ChainOperator and ChainRightOperator
- Sprache Part 8: Token, Contained, Identifier, LineTerminator
- Sprache Part 9: Positioned
- Sprache Part 10: Optional and XOptional
- Sprache Part 11: Parsing Comments
- Sprache Part 12: Ref, Named, End, Not, Except, Then, Where, Preview, Concat
This post covers Or
and XOr
, which are used to match either one of two parsers.
Or
Or
is used to match either one of two parsers.
Parser<T> Or<T>(this Parser<T> first, Parser<T> second)
The following example matches any one of the 4 keywords “return”, “function”, “switch” and “if”.
|
|
The order of the parsers matters - if the first parser matches that result will be returned regardless of whether the second parser matches. In this next example the parser looking for a “foobar” keyword will never match, as the identifier parser will always match first.
|
|
Explicitly supplying T
is useful in cases where the two parsers don’t return the same type.
XOr
XOr
is also used to match either one of two parsers.
Parser<T> XOr<T>(this Parser<T> first, Parser<T> second)
XOr
differs from Or
in that it won’t try the second parser if the first parser matched 1 or more characters, as we can see in the following contrived example where “far” (which is a valid identifier) isn’t parsed by the parser as it partially matched “foo”.
|
|
As I understand it this (along with all the other X* parser variants), is intended to give better error messsages by failing fast, however the Or
method has logic built in to choose the most sensible error message so in reality I struggled to come up with a good example where using XOr
helped.
Author Justin Pealing
LastMod 2020-03-30