error.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package parser
  2. import (
  3. "fmt"
  4. "sort"
  5. "github.com/robertkrimen/otto/file"
  6. "github.com/robertkrimen/otto/token"
  7. )
  8. const (
  9. err_UnexpectedToken = "Unexpected token %v"
  10. err_UnexpectedEndOfInput = "Unexpected end of input"
  11. )
  12. // UnexpectedNumber: 'Unexpected number',
  13. // UnexpectedString: 'Unexpected string',
  14. // UnexpectedIdentifier: 'Unexpected identifier',
  15. // UnexpectedReserved: 'Unexpected reserved word',
  16. // NewlineAfterThrow: 'Illegal newline after throw',
  17. // InvalidRegExp: 'Invalid regular expression',
  18. // UnterminatedRegExp: 'Invalid regular expression: missing /',
  19. // InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
  20. // InvalidLHSInForIn: 'Invalid left-hand side in for-in',
  21. // MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
  22. // NoCatchOrFinally: 'Missing catch or finally after try',
  23. // UnknownLabel: 'Undefined label \'%0\'',
  24. // Redeclaration: '%0 \'%1\' has already been declared',
  25. // IllegalContinue: 'Illegal continue statement',
  26. // IllegalBreak: 'Illegal break statement',
  27. // IllegalReturn: 'Illegal return statement',
  28. // StrictModeWith: 'Strict mode code may not include a with statement',
  29. // StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
  30. // StrictVarName: 'Variable name may not be eval or arguments in strict mode',
  31. // StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
  32. // StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
  33. // StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
  34. // StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
  35. // StrictDelete: 'Delete of an unqualified identifier in strict mode.',
  36. // StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
  37. // AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
  38. // AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
  39. // StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
  40. // StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
  41. // StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
  42. // StrictReservedWord: 'Use of future reserved word in strict mode'
  43. // A SyntaxError is a description of an ECMAScript syntax error.
  44. // An Error represents a parsing error. It includes the position where the error occurred and a message/description.
  45. type Error struct {
  46. Position file.Position
  47. Message string
  48. }
  49. // FIXME Should this be "SyntaxError"?
  50. func (self Error) Error() string {
  51. filename := self.Position.Filename
  52. if filename == "" {
  53. filename = "(anonymous)"
  54. }
  55. return fmt.Sprintf("%s: Line %d:%d %s",
  56. filename,
  57. self.Position.Line,
  58. self.Position.Column,
  59. self.Message,
  60. )
  61. }
  62. func (self *_parser) error(place interface{}, msg string, msgValues ...interface{}) *Error {
  63. var idx file.Idx
  64. switch place := place.(type) {
  65. case int:
  66. idx = self.idxOf(place)
  67. case file.Idx:
  68. if place == 0 {
  69. idx = self.idxOf(self.chrOffset)
  70. } else {
  71. idx = place
  72. }
  73. default:
  74. panic(fmt.Errorf("error(%T, ...)", place))
  75. }
  76. position := self.position(idx)
  77. msg = fmt.Sprintf(msg, msgValues...)
  78. self.errors.Add(position, msg)
  79. return self.errors[len(self.errors)-1]
  80. }
  81. func (self *_parser) errorUnexpected(idx file.Idx, chr rune) error {
  82. if chr == -1 {
  83. return self.error(idx, err_UnexpectedEndOfInput)
  84. }
  85. return self.error(idx, err_UnexpectedToken, token.ILLEGAL)
  86. }
  87. func (self *_parser) errorUnexpectedToken(tkn token.Token) error {
  88. switch tkn {
  89. case token.EOF:
  90. return self.error(file.Idx(0), err_UnexpectedEndOfInput)
  91. }
  92. value := tkn.String()
  93. switch tkn {
  94. case token.BOOLEAN, token.NULL:
  95. value = self.literal
  96. case token.IDENTIFIER:
  97. return self.error(self.idx, "Unexpected identifier")
  98. case token.KEYWORD:
  99. // TODO Might be a future reserved word
  100. return self.error(self.idx, "Unexpected reserved word")
  101. case token.NUMBER:
  102. return self.error(self.idx, "Unexpected number")
  103. case token.STRING:
  104. return self.error(self.idx, "Unexpected string")
  105. }
  106. return self.error(self.idx, err_UnexpectedToken, value)
  107. }
  108. // ErrorList is a list of *Errors.
  109. type ErrorList []*Error // nolint: errname
  110. // Add adds an Error with given position and message to an ErrorList.
  111. func (self *ErrorList) Add(position file.Position, msg string) {
  112. *self = append(*self, &Error{position, msg})
  113. }
  114. // Reset resets an ErrorList to no errors.
  115. func (self *ErrorList) Reset() { *self = (*self)[0:0] }
  116. func (self ErrorList) Len() int { return len(self) }
  117. func (self ErrorList) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
  118. func (self ErrorList) Less(i, j int) bool {
  119. x := &self[i].Position
  120. y := &self[j].Position
  121. if x.Filename < y.Filename {
  122. return true
  123. }
  124. if x.Filename == y.Filename {
  125. if x.Line < y.Line {
  126. return true
  127. }
  128. if x.Line == y.Line {
  129. return x.Column < y.Column
  130. }
  131. }
  132. return false
  133. }
  134. func (self ErrorList) Sort() {
  135. sort.Sort(self)
  136. }
  137. // Error implements the Error interface.
  138. func (self ErrorList) Error() string {
  139. switch len(self) {
  140. case 0:
  141. return "no errors"
  142. case 1:
  143. return self[0].Error()
  144. }
  145. return fmt.Sprintf("%s (and %d more errors)", self[0].Error(), len(self)-1)
  146. }
  147. // Err returns an error equivalent to this ErrorList.
  148. // If the list is empty, Err returns nil.
  149. func (self ErrorList) Err() error {
  150. if len(self) == 0 {
  151. return nil
  152. }
  153. return self
  154. }