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
This post covers
XOr, which are used to match either one of two parsers.
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.
T is useful in cases where the two parsers don’t return the same type.
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
Author Justin Pealing