google / starlark-go

Starlark in Go: the Starlark configuration language, implemented in Go
BSD 3-Clause "New" or "Revised" License
2.32k stars 212 forks source link

API: add way to return error, which got during iteration #366

Closed tdakkota closed 3 years ago

tdakkota commented 3 years ago

Current iterator API https://github.com/google/starlark-go/blob/74c10e2c17dcdb1cd5ff8044e33d9338820db233/starlark/value.go#L238-L244 does not allow to return error, which got during iteration.

As I understand, Java implementation uses exception to pass errors. https://github.com/bazelbuild/bazel/blob/f78ffb5fb2f37d20acd1320ed37080c26b32e607/src/main/java/net/starlark/java/eval/Eval.java#L118-L119

I think Go implementation can provide a special interface like

type ErrIterator interface {
       Iterator
       Err() error
}

Example usage:

iter := iterable.Iterator()
defer iter.Done()
var x Value
for iter.Next(&x) {
      ...
}
if errIter, ok := iter.(ErrIterator); ok {
    if err := errIter.Err(); err != nil {
        return err
    }
}
adonovan commented 3 years ago

While the proposed change would not cause any existing program not to compile, it is a semantically breaking change to the contract of an existing interface. That is, every place that currently calls Iterator.Done would become responsible for checking whether the iterator implements ErrIterator and handling the result of the Err method if so; failure to do so would cause errors to be silently ignored.