Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f7e13e0978 | |||
| f67d8a2443 | |||
| 76e6146e9e | |||
| 1b223e3751 |
@@ -0,0 +1,45 @@
|
||||
package lexer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
_ error = (*Error)(nil)
|
||||
)
|
||||
|
||||
// Error represents a generic parsing error
|
||||
type Error struct {
|
||||
Filename string
|
||||
Line int
|
||||
Column int
|
||||
|
||||
Content string
|
||||
Err error
|
||||
}
|
||||
|
||||
func (err Error) Error() string {
|
||||
var s []string
|
||||
|
||||
switch {
|
||||
case err.Line > 0 || err.Column > 0:
|
||||
s = append(s, fmt.Sprintf("%s:%v:%v", err.Filename, err.Line, err.Column))
|
||||
case err.Filename != "":
|
||||
s = append(s, err.Filename)
|
||||
}
|
||||
|
||||
if err.Err != nil {
|
||||
s = append(s, err.Err.Error())
|
||||
}
|
||||
|
||||
if err.Content != "" {
|
||||
s = append(s, fmt.Sprintf("%q", err.Content))
|
||||
}
|
||||
|
||||
return strings.Join(s, ": ")
|
||||
}
|
||||
|
||||
func (err Error) Unwrap() error {
|
||||
return err.Err
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package core
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"io/fs"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ReadCloser adds a Close() to Readers without one
|
||||
type ReadCloser struct {
|
||||
r io.Reader
|
||||
}
|
||||
|
||||
// Read passes the Read() call to the underlying [io.Reader]
|
||||
// and fail if it was Closed()
|
||||
func (rc *ReadCloser) Read(b []byte) (int, error) {
|
||||
switch {
|
||||
case rc.r != nil:
|
||||
return rc.r.Read(b)
|
||||
default:
|
||||
return 0, fs.ErrClosed
|
||||
}
|
||||
}
|
||||
|
||||
// Close attempts to Close the underlying [io.Reader], or
|
||||
// remove it if it doesn't support Close() and fail
|
||||
// if closed twice
|
||||
func (rc *ReadCloser) Close() error {
|
||||
switch {
|
||||
case rc.r != nil:
|
||||
rc.r = nil
|
||||
return nil
|
||||
default:
|
||||
return fs.ErrClosed
|
||||
}
|
||||
}
|
||||
|
||||
// NewReadCloser wraps a [io.Reader] to satisfy
|
||||
// [io.ReadCloser] if needed
|
||||
func NewReadCloser(r io.Reader) io.ReadCloser {
|
||||
switch p := r.(type) {
|
||||
case io.ReadCloser:
|
||||
return p
|
||||
case nil:
|
||||
return nil
|
||||
default:
|
||||
return &ReadCloser{
|
||||
r: r,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewReadCloserBytes wraps a bytes slice to implement
|
||||
// a [io.ReadCloser]
|
||||
func NewReadCloserBytes(b []byte) io.ReadCloser {
|
||||
return NewReadCloser(bytes.NewReader(b))
|
||||
}
|
||||
|
||||
// NewReadCloserString wraps a string to implement
|
||||
// a [io.ReadCloser]
|
||||
func NewReadCloserString(s string) io.ReadCloser {
|
||||
return NewReadCloser(strings.NewReader(s))
|
||||
}
|
||||
Reference in New Issue
Block a user