label
label(p: Parser, m: string): Parser
Changes the error message of a parser if it fails normally when executed. If the parser succeeds or fails fatally, label
has no effect.
Every parser that can fail already accepts an alternative error message as an optional parameter. The purpose of label
is to provide a way to change the error message after the parser has already been created.
For instance, one might create a parser like this:
const quoted = between(char('"'), char('"'), many(noneof('"')))
If this parser is applied to an input that does not begin with a quotation mark, it will fail with a message that includes Expected '"'
. This might be a good error message for a certain context, but this quoted parser could be re-used several times in several different contexts, some of which might want to have a different error message. Rather than creating a new version of the quoted
parser that changes nothing but the message, one could use label
instead:
const newQuoted = label(quoted, 'a quoted string')
This new parser does exactly the same thing as quoted
, but if it meets an input that does not begin with a quotation mark, it will instead produce a message that includes Expected a quoted string
.
There is nothing preventing you from using label
with a parser during creation time, something like label(letter(), 'some letter')
instead of letter('some letter')
. This is not recommended however. If the desired error message is known at creation time, pass it directly to the parser instead of using label
. In many cases it won't matter, but backtracking parser in particular will work much better without label
.
Speaking of that, take care when using label
with backtracking parsers. Not only does label
not produce a nested error message when backtracking happens, it will also eliminate all backtracking information from the error message altogether. Unless the label
message takes this into account, it can be a source of great confusion.
Note that the message parameter m
is required. This is not typical of other parsers in the library.
Example
const twoLetters = seq(letter(), letter())
const parser = label(twoLetters, 'two letters')
const s = parse(parser, 'ab')
console.log(status(s)) // "ok"
console.log(success(s)) // ["a","b"]
const f = parse(parser, '12')
console.log(status(f)) // "fail"
console.log(failure(f)) // Parse error at (line 1, column 1):
//
// 12
// ^
// Expected two letters
const t = parse(parser, 'a1')
console.log(status(t)) // "fatal"
console.log(failure(f)) // Parse error at (line 1, column 2):
//
// 12
// ^
// Expected a letter
Parameters
p
: The parser that is applied.m
: The expected error message that will take the place of whatever error message is generated byp
.
Success
- Succeeds if
p
succeeds. Returnsp
's result.
Failure
- Fails if
p
fails. The error message wil becomeexpected(m)
.
Fatal Failure
- Fails fatally if
p
fails fatally.
Throws
- Throws an error if
p
is not a parser. - Throws an error if
m
is not a string.