error.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package parse
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/tdewolff/parse/buffer"
  6. )
  7. // Error is a parsing error returned by parser. It contains a message and an offset at which the error occurred.
  8. type Error struct {
  9. Message string
  10. r io.Reader
  11. Offset int
  12. line int
  13. column int
  14. context string
  15. }
  16. // NewError creates a new error
  17. func NewError(msg string, r io.Reader, offset int) *Error {
  18. return &Error{
  19. Message: msg,
  20. r: r,
  21. Offset: offset,
  22. }
  23. }
  24. // NewErrorLexer creates a new error from a *buffer.Lexer
  25. func NewErrorLexer(msg string, l *buffer.Lexer) *Error {
  26. r := buffer.NewReader(l.Bytes())
  27. offset := l.Offset()
  28. return NewError(msg, r, offset)
  29. }
  30. // Positions re-parses the file to determine the line, column, and context of the error.
  31. // Context is the entire line at which the error occurred.
  32. func (e *Error) Position() (int, int, string) {
  33. if e.line == 0 {
  34. e.line, e.column, e.context, _ = Position(e.r, e.Offset)
  35. }
  36. return e.line, e.column, e.context
  37. }
  38. // Error returns the error string, containing the context and line + column number.
  39. func (e *Error) Error() string {
  40. line, column, context := e.Position()
  41. return fmt.Sprintf("parse error:%d:%d: %s\n%s", line, column, e.Message, context)
  42. }