cedar-policy / cedar-go

Golang implementation of the Cedar Policy Language
Apache License 2.0
83 stars 9 forks source link

Use a Struct for parser errors to expose the position information programatically #27

Open JoshuaWilkes opened 2 months ago

JoshuaWilkes commented 2 months ago

I have started experimenting with a feature that requires returning an error the to user if a when cedar expression is invalid. At the moment I use something like this to test the expression.

selectorPolicy, err := cedar.NewPolicySet("", []byte(fmt.Sprintf(`permit(principal,action,resource) when { %s };`, whenExpression)))

I would like to be able to use the error result programatically to provide feedback about the exact error position and details. Likely adding some syntax highlighting in my app.

The errors returned by the current version of the parser use fmt.Errorf(), if this was swapped for a struct alongs the lines of this, it could be used to extract the exact details of the error.

type ScanError struct {
    Message  string
    Position Position
}

func (e ScanError) Error() string {
    return fmt.Sprintf("%v: %s", e.Position, e.Message)
}

func (s *scanner) error(msg string) {
    s.tokEnd = s.srcPos - s.lastCharLen // make sure token text is terminated
    s.err = ScanError{
        Message:  msg,
        Position: s.position,
    }
}

I'm happy to contribute some code here, though I note you have some recent work pending to stabilise the AST and parsing code so will hold off for now.

Edit: I see that the new version v0.2.0 has been released to I will check that out and see if there is a way forward here :)

philhassey commented 2 months ago

We haven't exposed the parser and parser errors in v0.2.0, but I think the programmatic AST creation might be worth checking out as an alternative to what you are trying to do. (See the tests here for some example usage: https://github.com/cedar-policy/cedar-go/blob/main/ast/ast_test.go )

Thanks! -Phil