error.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package parse
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  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. Line int
  11. Column int
  12. Context string
  13. }
  14. // NewError creates a new error
  15. func NewError(r io.Reader, offset int, message string, a ...interface{}) *Error {
  16. line, column, context := Position(r, offset)
  17. if 0 < len(a) {
  18. message = fmt.Sprintf(message, a...)
  19. }
  20. return &Error{
  21. Message: message,
  22. Line: line,
  23. Column: column,
  24. Context: context,
  25. }
  26. }
  27. // NewErrorLexer creates a new error from an active Lexer.
  28. func NewErrorLexer(l *Input, message string, a ...interface{}) *Error {
  29. r := bytes.NewBuffer(l.Bytes())
  30. offset := l.Offset()
  31. return NewError(r, offset, message, a...)
  32. }
  33. // Position returns the line, column, and context of the error.
  34. // Context is the entire line at which the error occurred.
  35. func (e *Error) Position() (int, int, string) {
  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. return fmt.Sprintf("%s on line %d and column %d\n%s", e.Message, e.Line, e.Column, e.Context)
  41. }