1package parse
 2
 3import (
 4	"bytes"
 5	"fmt"
 6	"io"
 7)
 8
 9// Error is a parsing error returned by parser. It contains a message and an offset at which the error occurred.
10type Error struct {
11	Message string
12	Line    int
13	Column  int
14	Context string
15}
16
17// NewError creates a new error
18func NewError(r io.Reader, offset int, message string, a ...interface{}) *Error {
19	line, column, context := Position(r, offset)
20	if 0 < len(a) {
21		message = fmt.Sprintf(message, a...)
22	}
23	return &Error{
24		Message: message,
25		Line:    line,
26		Column:  column,
27		Context: context,
28	}
29}
30
31// NewErrorLexer creates a new error from an active Lexer.
32func NewErrorLexer(l *Input, message string, a ...interface{}) *Error {
33	r := bytes.NewBuffer(l.Bytes())
34	offset := l.Offset()
35	return NewError(r, offset, message, a...)
36}
37
38// Position returns the line, column, and context of the error.
39// Context is the entire line at which the error occurred.
40func (e *Error) Position() (int, int, string) {
41	return e.Line, e.Column, e.Context
42}
43
44// Error returns the error string, containing the context and line + column number.
45func (e *Error) Error() string {
46	return fmt.Sprintf("%s on line %d and column %d\n%s", e.Message, e.Line, e.Column, e.Context)
47}