ErrorMethods
This class exposes helpful combinators that are specialised for generating more helpful errors messages.
This extension class operates on values that are convertible to parsers. It enables the use of error combinators, which can be used for data validation, error annotation, or immediate failing.
Type parameters
- P
-
the type of base value that this class is used on (the conversion to
Parsley
) is summoned automatically.
Value parameters
- con
-
a conversion that allows values convertible to parsers to be used.
- p
-
the value that this class is enabling methods on.
Attributes
- Constructor
-
This constructor should not be called manually, it is designed to be used via Scala's implicit resolution.
- Version
-
3.0.0
- Source
- combinator.scala
- Graph
-
- Supertypes
Members list
Grouped members
Error Enrichment Combinators
These combinators add additional information - or refine the existing information within - to an error message that has been generated within the scope of the parser they have been called on. These are a very basic, but effective, way of improving the quality of error messages generated by Parsley.
This combinator changes the expected component of any errors generated by this parser.
This combinator changes the expected component of any errors generated by this parser.
This is just an alias for the label
combinator.
Known as <?>
in Haskell.
Attributes
- See also
- Since
-
3.0.0
- Source
- combinator.scala
This combinator adds a reason to error messages generated by this parser.
This combinator adds a reason to error messages generated by this parser.
When this parser fails having not observably* consumed input, this combinator adds reason
to the error message, which should justify why the error occured. Unlike error labels, which may persist if more progress is made having not consumed input, reasons are not carried forward in the error message, and are lost.
*a parser is said to observably consume input when error messages generated by a parser p
occur at a deeper offset than p
originally started at. While this sounds like it is the same as "having consumed input" for the purposes of backtracking, they are disjoint concepts:
in
attempt(p)
,p
can observably consume input even though the wider parser does not consume input due to theattempt
.in
amend(p)
,p
can consume input and may not backtrack even though the consumption is not observable in the error message due to theamend
.
Value parameters
- reason
-
the reason why a parser failed.
Attributes
- Returns
-
a parser that produces the given reason for failure if it fails.
- Since
-
3.0.0
- Source
- combinator.scala
This combinator hides the expected component of errors generated by this parser.
This combinator hides the expected component of errors generated by this parser.
When this parser fails having not observably* consumed input, this combinator hides any error labels assigned to the expected item by any label
combinators, or indeed the base raw labels produced by the input consuming combinators themselves.
This can be useful, say, for hiding whitespace labels, which are not normally useful information to include in an error message for whitespace insensitive grammars.
*a parser is said to observably consume input when error messages generated by a parser p
occur at a deeper offset than p
originally started at. While this sounds like it is the same as "having consumed input" for the purposes of backtracking, they are disjoint concepts:
in
attempt(p)
,p
can observably consume input even though the wider parser does not consume input due to theattempt
.in
amend(p)
,p
can consume input and may not backtrack even though the consumption is not observable in the error message due to theamend
.
Attributes
- Returns
-
a parser that does not produce an expected component on failure.
- Since
-
3.0.0
- Source
- combinator.scala
This combinator changes the expected component of any errors generated by this parser.
This combinator changes the expected component of any errors generated by this parser.
When this parser fails having not observably* consumed input, the expected component of the generated error message is set to be the given item
.
*a parser is said to observably consume input when error messages generated by a parser p
occur at a deeper offset than p
originally started at. While this sounds like it is the same as "having consumed input" for the purposes of backtracking, they are disjoint concepts:
in
attempt(p)
,p
can observably consume input even though the wider parser does not consume input due to theattempt
.in
amend(p)
,p
can consume input and may not backtrack even though the consumption is not observable in the error message due to theamend
.
Value parameters
- item
-
the name to give to the expected component of any qualifying errors.
- items
-
any further labels to assign to this parser.
Attributes
- Returns
-
a parser that expects
item
on failure. - Since
-
3.0.0
- Source
- combinator.scala
Filtering Combinators
These combinators perform filtering on a parser, with particular emphasis on generating meaningful error messages if the filtering fails. This is particularly useful for data validation within the parser, as very instructive error messages describing what went wrong can be generated. These combinators often filter using a PartialFunction
: this may be because they combine filtering with mapping (in which case, the error message is provided separately), or the function may produce a String
. In these cases, the partial function is producing the error messages: if the input to the function is defined, this means that it is invalid and the filtering will fail using the message obtained from the succesful partial function invocation.
This combinator applies a partial function pf
to the result of this parser if its result is defined for pf
, failing if it is not.
This combinator applies a partial function pf
to the result of this parser if its result is defined for pf
, failing if it is not.
First, parse this parser. If it succeeds, test whether its result x
is in the domain of the partial function pf
. If it is defined for pf
, return pf(x)
. Otherwise, if the result was undefined then fail producing a specialised error message with msg
. Equivalent to a guardAgainst
(whose msggen
ignores its argument) followed by a map
.
Value parameters
- msg0
-
the first error message to use if the filtering fails.
- msgs
-
the remaining error messages to use if the filtering fails.
- pf
-
the partial function used to both filter the result of this parser and transform it.
Attributes
- Returns
-
a parser which returns the result of this parser applied to pf, if possible.
- See also
-
collect
, which is a basic version of this same combinator with no customised error message.guardAgainst
, which is similar tocollectMsg
, except it does not transform the data. - Since
-
3.0.0
- Note
-
when this combinator fails (and not this parser itself), it will generate errors rooted at the start of the parse (as if
amend
had been used) and the caret will span the entire successful parse of this parser.implemented in terms of
collectWith
. - Example
-
A good example of this combinator in use is for handling overflow in numeric literals.
val integer: Parsley[BigInt] = ... // this should be amended/entrenched for best results val int16: Parsley[Short] = integer.collectMsg("integer literal should within the range -2^16 to +2^16-1") { case x if x >= Short.MinValue && x <= Short.MaxValue => x.toShort }
- Source
- combinator.scala
This combinator applies a partial function pf
to the result of this parser if its result is defined for pf
, failing if it is not.
This combinator applies a partial function pf
to the result of this parser if its result is defined for pf
, failing if it is not.
First, parse this parser. If it succeeds, test whether its result x
is in the domain of the partial function pf
. If it is defined for pf
, return pf(x)
. Otherwise, if the result was undefined then fail producing a specialised error message with msggen(x)
. Equivalent to a guardAgainst
followed by a map
.
Value parameters
- msggen
-
a function that generates the error messages to use if the filtering fails.
- pf
-
the partial function used to both filter the result of this parser and transform it.
Attributes
- Returns
-
a parser which returns the result of this parser applied to pf, if possible.
- See also
-
collect
, which is a basic version of this same combinator with no customised error message.guardAgainst
, which is similar tocollectMsg
, except it does not transform the data. - Since
-
4.0.0
- Note
-
when this combinator fails (and not this parser itself), it will generate errors rooted at the start of the parse (as if
amend
had been used) and the caret will span the entire successful parse of this parser.implemented in terms of
collectWith
. - Example
-
A good example of this combinator in use is for handling overflow in numeric literals.
val integer: Parsley[BigInt] = ... // this should be amended/entrenched for best results val int16: Parsley[Short] = integer.collectMsg(n => Seq(s"integer literal $n is not within the range -2^16 to +2^16-1")) { case x if x >= Short.MinValue && x <= Short.MaxValue => x.toShort }
- Source
- combinator.scala
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
First, parse this parser. If it succeeds then take its result x
and test if pred.isDefinedAt(x)
is true. If it is false, the parser succeeds, returning x
. Otherwise, pred(x)
will yield a reason reason
and the parser will fail with reason
provided to the generated error message à la explain
.
This is useful for performing data validation, but where a definitive reason can be given for the failure. In this instance, the rest of the error message is generated as normal, with the expected and unexpected components still given, along with any other generated reasons.
Value parameters
- pred
-
the predicate that is tested against the parser result, which also generates errors.
Attributes
- Returns
-
a parser that returns the result of this parser if it fails the predicate.
- See also
-
filterNot
, which is a basic version of this same combinator with no customised reason.guardAgainst
, which is similar tofilterOut
, except it generates a specialised error as opposed to just a reason. - Since
-
3.0.0
- Note
-
implemented in terms of
filterWith
.when this combinator fails (and not this parser itself), it will generate errors rooted at the start of the parse (as if
amend
had been used) and the caret will span the entire successful parse of this parser. - Example
-
scala> import parsley.character.letter scala> val keywords = Set("if", "then", "else") scala> val ident = stringOfSome(letter).filterOut { case v if keywords.contains(v) => s"keyword $v cannot be an identifier" } scala> ident.parse("hello") val res0 = Success("hello") scala> ident.parse("if") val res1 = Failure(..)
- Source
- combinator.scala
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
First, parse this parser. If it succeeds then take its result x
and test of pred.isDefinedAt(x)
is true. If it is false, the parser succeeds, returning x
. Otherwise pred(x)
will yield an error message msg
and the parser will fail, producing a specialised error only consisting of the message msg
à la fail
.
This is useful for performing data validation, but where failure is not tied to the grammar but some other property of the results. For instance, with the identifier example given for filterOut
, it is reasonable to suggest that an identifier was expected, and a keyword is not a valid identifier: i.e. these components still make sense. Where guardAgainst
shines, however, is in scenarios where the expected alternatives, or the unexpected component itself distract from the cause of the error, or are irrelevant in some way. This might be because guardAgainst
is checking some property of the data that is possible to encode in the grammar, but otherwise impractical, either because it is hard to maintain or generates poor error messages for the user.
Value parameters
- pred
-
the predicate that is tested against the parser result, which also generates errors.
Attributes
- Returns
-
a parser that returns the result of this parser if it fails the predicate.
- See also
-
filterNot
, which is a basic version of this same combinator with no customised error message.filterOut
, which is similar toguardAgainst
, except it generates a reason for failure and not a specialised error.collectMsg
, which is similar toguardAgainst
, but can also transform the data on success. - Since
-
4.0.0
- Note
-
when this combinator fails (and not this parser itself), it will generate errors rooted at the start of the parse (as if
amend
had been used) and the caret will span the entire successful parse of this parser.implemented in terms of
filterWith
. - Example
-
Suppose we are parsing a data-format for graphs, and a restriction has been placed that ensures that the numeric identifiers of each declared node must be ordered. This has, for whatever reason, been specified as a syntactic property of the data. This is possible to encode using context-sensitive parsing (since each new node can only be parsed according to the previous one), but is fairly difficult and impractical. Instead, when all the declarations have been read, a
guardAgainst
can be used to prevent mis-ordering:val node = integer val nodes = many(node).guardAgainst { case ns if ns.nonEmpty && ns.zip(ns.tail).exists { case (x, y) => x == y } => val Some((x, _)) = ns.zip(ns.tail).find { case (x, y) => x == y } Seq(s"node $x has been declared twice") case ns if ns.nonEmpty && ns.zip(ns.tail).exists { case (x, y) => x > y } => val Some((x, y)) = ns.zip(ns.tail).find { case (x, y) => x > y } Seq(s"nodes $x and $y are declared in the wrong order", "all nodes should be ordered") }
- Source
- combinator.scala
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
First, parse this parser. If it succeeds then take its result x
and test if pred.isDefinedAt(x)
is true. If it is false, the parser succeeds, returning x
. Otherwise, pred(x)
will yield a unexpected label and the parser will fail using unexpected
and that label.
This is useful for performing data validation, but where a the failure results in the entire token being unexpected. In this instance, the rest of the error message is generated as normal, with the expected components still given, along with any generated reasons.
Value parameters
- pred
-
the predicate that is tested against the parser result, which also generates errors.
Attributes
- Returns
-
a parser that returns the result of this parser if it fails the predicate.
- See also
-
filterNot
, which is a basic version of this same combinator with no unexpected message.filterOut
, which is a variant that produces a reason for failure as opposed to an unexpected message.guardAgainst
, which is similar tounexpectedWhen
, except it generates a specialised error instead.unexpectedWithReasonWhen
, which is similar, but also has a reason associated. - Since
-
3.0.0
- Note
-
when this combinator fails (and not this parser itself), it will generate errors rooted at the start of the parse (as if
amend
had been used) and the caret will span the entire successful parse of this parser.implemented in terms of
filterWith
. - Example
-
scala> import parsley.character.letter scala> val keywords = Set("if", "then", "else") scala> val ident = stringOfSome(letter).unexpectedWhen { case v if keywords.contains(v) => s"keyword $v" } scala> ident.parse("hello") val res0 = Success("hello") scala> ident.parse("if") val res1 = Failure(..)
- Source
- combinator.scala
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
This combinator filters the result of this parser using the given partial-predicate, succeeding only when the predicate is undefined.
First, parse this parser. If it succeeds then take its result x
and test if pred.isDefinedAt(x)
is true. If it is false, the parser succeeds, returning x
. Otherwise, pred(x)
will yield a unexpected label and the parser will fail using unexpected
and that label as well as a reason.
This is useful for performing data validation, but where a the failure results in the entire token being unexpected. In this instance, the rest of the error message is generated as normal, with the expected components still given, along with any generated reasons.
Value parameters
- pred
-
the predicate that is tested against the parser result, which also generates errors.
Attributes
- Returns
-
a parser that returns the result of this parser if it fails the predicate.
- See also
-
filterNot
, which is a basic version of this same combinator with no unexpected message or reason.filterOut
, which is a variant that just produces a reason for failure with no unexpected message.guardAgainst
, which is similar tounexpectedWhen
, except it generates a specialised error instead.unexpectedWhen
, which is similar, but with no associated reason. - Since
-
4.2.0
- Note
-
implemented in terms of
filterWith
. - Example
-
scala> import parsley.character.letter scala> val keywords = Set("if", "then", "else") scala> val ident = stringOfSome(letter).unexpectedWhenWithReason { case v if keywords.contains(v) => (s"keyword $v", "keywords cannot be identifiers") } scala> ident.parse("hello") val res0 = Success("hello") scala> ident.parse("if") val res1 = Failure(..)
- Source
- combinator.scala
Generic Filtering Combinators
This combinators generalise the combinators from above, which are all special cases of them. Each of these takes the characteristic predicate or function of the regular variants, but takes an errGen
object that can be used to fine-tune the error messages. These offer some flexiblity not offered by the specialised filtering combinators, but are a little more verbose to use.
This combinator conditionally transforms the result of this parser with a given partial function, generating an error with the given error generator if the function is not defined on the result of this parser.
This combinator conditionally transforms the result of this parser with a given partial function, generating an error with the given error generator if the function is not defined on the result of this parser.
Like collect
, except allows for the error message generated to be fine-tuned with respect to the parsers result and width of input consumed using an ErrorGen
object.
Value parameters
- errGen
-
how to generate error messages based on the result of this parser.
- pf
-
the partial function used to both filter the result of this parser and transform it.
Attributes
- Since
-
4.4.0
- Source
- combinator.scala
This combinator filters the result of this parser with the given predicate, generating an error with the given error generator if the function returned false
.
This combinator filters the result of this parser with the given predicate, generating an error with the given error generator if the function returned false
.
Like filter
, except allows for the error message generated to be fine-tuned with respect to the parsers result and width of input consumed using an ErrorGen
object.
Value parameters
- errGen
-
how to generate error messages based on the result of this parser.
- pred
-
the predicate that is tested against the parser result.
Attributes
- Since
-
4.4.0
- Source
- combinator.scala
This combinator conditionally transforms the result of this parser with a given function, generating an error with the given error generator if the function returns None
given the result of this parser.
This combinator conditionally transforms the result of this parser with a given function, generating an error with the given error generator if the function returns None
given the result of this parser.
Like mapFilter
, except allows for the error message generated to be fine-tuned with respect to the parsers result and width of input consumed using an ErrorGen
object.
Value parameters
- errGen
-
how to generate error messages based on the result of this parser.
- f
-
the function used to both filter the result of this parser and transform it.
Attributes
- Since
-
4.4.0
- Source
- combinator.scala