microsoft / ts-parsec

Writing a custom parser is a fairly common need. Although there are already parser combinators in others languages, TypeScript provides a powerful and well-structured foundation for building this. Common parser combinators’ weakness are error handling and ambiguity resolving, but these are ts-parsec’s important features. Additionally, ts-parsec provides a very easy to use programming interface, that could help people to build programming-language-scale parsers in just a few hours. This technology has already been used in Microsoft/react-native-tscodegen.
Other
353 stars 18 forks source link

Is there a way to emit parser failure from my parsers? #15

Closed loxs closed 4 years ago

loxs commented 4 years ago

I am trying to achieve this, but I can't figure out what's the proper solution:

const dateParser = apply(tok(TokenKind.ISODate), (t) => {
  const parsedDate = parseISO(t.text);
  if (isValid(parsedDate)) {
    return parsedDate;
  }
  return; //what?;
});

What is the proper idiomatic solution to this case?

vczh commented 4 years ago

@loxs Sorry to be so late to see this issue, since this project is not actively updated.

This is in my plan. You are not able to do it elegantly for now.

The secret is in the ParserOutput interface. What I would do is, write a new combinator err, accepting a sub parser, a predefined message and a predefined result. When the sub parser failed (successful === false), it replaces all error messages from the sub parser, and also add the predefined result to candidates.

For example, the usage will look like err(Number(), "A number is expected", 0). The err parser always succeeds, if Number() failed, it returns the hard-coded result.

This is what I am planning to do, but a pull request is also welcome if you are interested in doing it.

ZihanChen-MSFT commented 4 years ago

err and errd are available in 0.3.2, please checkout the document.