Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Matching to TokenListParser #72

Closed
AndrewSav opened this issue Dec 18, 2018 · 0 comments · Fixed by #132
Closed

Add Matching to TokenListParser #72

AndrewSav opened this issue Dec 18, 2018 · 0 comments · Fixed by #132

Comments

@AndrewSav
Copy link
Contributor

AndrewSav commented Dec 18, 2018

As discussed on Gitter, sometimes a parser ends up being used twice for parsing the same piece of text: first time in tokenizer, and second one via Apply in the parser. This is because if we use a enum for TKind there is nowhere to store the initial parsing result.

Instead of using a enum for result of tokenization, thus it could be advisable using a normal class, that has the token type as a field. This way the parser will have access to the parsed result and will not need to call Apply to execute parsing again.

To facilitate this approach we would use Matching instead of Token.EqualTo to be able to select on type, which now became object field.

Matching method could look like this:

public static TokenListParser<TKind, Token<TKind>> Matching<TKind>(Func<TKind, bool> predicate, string name)
{
    if (predicate == null) throw new ArgumentNullException(nameof(predicate));
    if (name == null) throw new ArgumentNullException(nameof(name));

    return Matching(predicate, new[] { name });
}

private static TokenListParser<TKind, Token<TKind>> Matching<TKind>(Func<TKind, bool> predicate, string[] expectations)
{
    if (predicate == null) throw new ArgumentNullException(nameof(predicate));
    if (expectations == null) throw new ArgumentNullException(nameof(expectations));

    return input =>
    {
        var next = input.ConsumeToken();
        if (!next.HasValue || !predicate(next.Value.Kind))
            return TokenListParserResult.Empty<TKind, Token<TKind>>(input , expectations);

        return next;
    };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants