parjs icon indicating copy to clipboard operation
parjs copied to clipboard

How to set custom "expecting" messages?

Open mikavilpas opened this issue 4 years ago • 1 comments

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:

image

I'd like them to read expecting: "a header definition" or expecting: "an email address" etc.

mikavilpas avatar Jul 05 '21 12:07 mikavilpas

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.

mikavilpas avatar Jul 05 '21 13:07 mikavilpas

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.

mikavilpas avatar Apr 15 '23 17:04 mikavilpas

Thank you! Added via https://github.com/GregRos/parjs/commit/1f27bd1f21008bb2489413fa36668da9cb3ba4cd

const p = string("example").expects("The string 'example'")

GregRos avatar Sep 05 '23 23:09 GregRos