vektah / goparsify

golang parser-combinator library
MIT License
73 stars 16 forks source link

Ability to validate the parsed token #8

Closed yusup-abdullaev closed 2 years ago

yusup-abdullaev commented 2 years ago

First, I want to say that this library is really really helpful for the small user command parser which I am writing. Thank you so much.

The question which I have - is there an ability to validate the token which I parsed? Example: I have a parser which handles the date in format YYYY-MM-DD:

    date = Regex("\\d\\d\\d\\d-\\d\\d-\\d\\d").Map(func(n *Result) {
        d, err := time.Parse("2006-01-02", n.Token)
        if err != nil {
            // do something to signal to parser to stop execution
        } else {
            n.Result = d
        }
    })

Is there an ability to add extra code which will inspect the extracted token and validate it?

yusup-abdullaev commented 2 years ago

So what I did - I created an private function which does the same as Regex but also validates the match:

func regExt(pattern string, validate func(token string) error) Parser {
    re := regexp.MustCompile("^" + pattern)
    return NewParser(pattern, func(ps *State, node *Result) {
        ps.WS(ps)
        match := re.FindString(ps.Get())
        if match == "" {
            ps.ErrorHere(pattern)
            return
        }
        if err := validate(match); err != nil {
            ps.ErrorHere(pattern)
            return
        }
        ps.Advance(len(match))
        node.Token = match
    })
}

This does the work for me and the issue is closed.