parjs
parjs copied to clipboard
How to set custom "expecting" messages?
Hi, it would be very useful to have some utility when creating parsers with the combinators, to set the .expecting message to something custom.
That way when I see my trace, I could have really useful messages in the context of my domain instead of the technical messages I see right now.
Example of current messages:

I'd like them to read expecting: "a header definition" or expecting: "an email address" etc.
Ended up rolling my own (in javascript). It looks like this:
export function called(expecting) {
return defineCombinator((source) => {
return new (class Called extends ParjserBase {
type = "called";
expecting = expecting;
_apply(ps) {
source.apply(ps);
}
})();
});
}
Usage:
email.pipe(called("email address"))
I'm happy with this workaround/extension, but if a maintainer of this project feels like this would be a good addition, maybe it can be added.
For what it's worth, here is a typescript version that seems to be working for me.
export function called<T>(expecting: string): ParjsCombinator<T, T> {
return defineCombinator((inner) => {
return new (class Called extends ParjserBase {
expecting = expecting;
type = expecting;
_apply(ps: ParsingState): void {
inner.apply(ps);
}
})();
});
}
Hope this can be useful to someone.
Thank you! Added via https://github.com/GregRos/parjs/commit/1f27bd1f21008bb2489413fa36668da9cb3ba4cd
const p = string("example").expects("The string 'example'")