dispatch/vendor/github.com/tdewolff/parse/v2/error.go

49 lines
1.2 KiB
Go
Raw Normal View History

2018-12-17 13:41:24 +00:00
package parse
import (
"fmt"
"io"
"github.com/tdewolff/parse/v2/buffer"
)
// Error is a parsing error returned by parser. It contains a message and an offset at which the error occurred.
type Error struct {
Message string
2020-04-29 02:23:32 +00:00
Line int
Column int
Context string
2018-12-17 13:41:24 +00:00
}
// NewError creates a new error
2020-04-29 02:23:32 +00:00
func NewError(r io.Reader, offset int, message string, a ...interface{}) *Error {
line, column, context := Position(r, offset)
if 0 < len(a) {
message = fmt.Sprintf(message, a...)
}
2018-12-17 13:41:24 +00:00
return &Error{
2020-04-29 02:23:32 +00:00
Message: message,
Line: line,
Column: column,
Context: context,
2018-12-17 13:41:24 +00:00
}
}
2019-06-09 00:01:48 +00:00
// NewErrorLexer creates a new error from an active Lexer.
2020-04-29 02:23:32 +00:00
func NewErrorLexer(l *buffer.Lexer, message string, a ...interface{}) *Error {
2018-12-17 13:41:24 +00:00
r := buffer.NewReader(l.Bytes())
offset := l.Offset()
2020-04-29 02:23:32 +00:00
return NewError(r, offset, message, a...)
2018-12-17 13:41:24 +00:00
}
2020-04-29 02:23:32 +00:00
// Positions returns the line, column, and context of the error.
2018-12-17 13:41:24 +00:00
// Context is the entire line at which the error occurred.
func (e *Error) Position() (int, int, string) {
2020-04-29 02:23:32 +00:00
return e.Line, e.Column, e.Context
2018-12-17 13:41:24 +00:00
}
// Error returns the error string, containing the context and line + column number.
func (e *Error) Error() string {
2020-04-29 02:23:32 +00:00
return fmt.Sprintf("%s on line %d and column %d\n%s", e.Message, e.Line, e.Column, e.Context)
2018-12-17 13:41:24 +00:00
}