mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
6.98k stars 332 forks source link

How do I know the concrete types for functions that return the `error` interface #1009

Closed hwittenborn closed 1 year ago

hwittenborn commented 1 year ago

This is a follow-up to #1008 - I made this new issue because I closed the old one a bit too early and I wasn't sure if anyone would be notified about new comments on the issue.

Anyway, I'm working on some Rust bindings for this library, and a lot of functions throughout the library return the error {} interface instead of a concrete type.

I'm wanting to return concrete error types to library users via an enum in that library, but the fact that error {} is returned a lot made that a bit challenging.

We discussed in the other issue how there was a concrete type for that specific function I was using, but is there any way to detect what concrete types might be available for any given error {} return type directly from the library docs? Or would my best bet be to just check over a known list of concrete error types for all errors that get returned throughout the library, and then see what error they match up to?

mvdan commented 1 year ago

Go doesn't treat errors like enums - when a function says it returns error, it really could be anything. A function might document the set of errors it could return, but that's simply a human promise, not actually enforced by the compiler.

We do have some exported error types, like https://pkg.go.dev/mvdan.cc/sh/v3/syntax#ParseError, but others are not exported, like https://pkg.go.dev/mvdan.cc/sh/v3/interp#NewExitStatus.

We could certainly try to do better in terms of exporting and documenting the error types we use, but ultimately it would be best-effort. If you're writing a Rust wrapper for a Go API, I think you would always have to support arbitrary error types as a fallback, e.g. https://pkg.go.dev/errors#New.

hwittenborn commented 1 year ago

Yeah I was thinking interfaces couldn't be compiler-guaranteed to be any specific type, I was mainly just checking if there was a list of specific errors from this library that I overlooked or something. It made sense that there would be a fallback unknown error type regardless though, just because some functions accept user-defined callbacks where errors could occur in.

I'm fine with the current setup for errors in the library, I'll just look for all of them that are present in the library and map those all over.

Thanks a ton for the help!