error.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package parser
  2. import "kumachan/parser/ast"
  3. import "kumachan/parser/syntax"
  4. import . "kumachan/error"
  5. type Error struct {
  6. Tree *ast.Tree
  7. HasExpectedPart bool
  8. ExpectedPart syntax.Id
  9. NodeIndex int // may be bigger than the index of last token
  10. }
  11. func (err *Error) Desc() ErrorMessage {
  12. var node = err.Tree.Nodes[err.NodeIndex]
  13. var got string
  14. if node.Pos >= len(err.Tree.Tokens) {
  15. got = "EOF"
  16. } else {
  17. got = syntax.Id2Name[err.Tree.Tokens[node.Pos].Id]
  18. }
  19. var desc = make(ErrorMessage, 0)
  20. if err.HasExpectedPart {
  21. desc.WriteText(TS_ERROR, "Syntax unit")
  22. desc.WriteInnerText(TS_INLINE, syntax.Id2Name[err.ExpectedPart])
  23. desc.WriteText(TS_ERROR, "expected")
  24. } else {
  25. desc.WriteText(TS_ERROR, "Parser stuck")
  26. }
  27. desc.Write(T_SPACE)
  28. desc.WriteText(TS_ERROR, "(got")
  29. desc.Write(T_SPACE)
  30. desc.WriteText(TS_INLINE, got)
  31. desc.WriteText(TS_ERROR, ")")
  32. return desc
  33. }
  34. func (err *Error) Message() ErrorMessage {
  35. var tree = err.Tree
  36. var node = tree.Nodes[err.NodeIndex]
  37. var token_index int
  38. if node.Pos >= len(tree.Tokens) {
  39. token_index = len(tree.Tokens)-1
  40. } else {
  41. token_index = node.Pos
  42. }
  43. var token = tree.Tokens[token_index]
  44. var token_span_size = token.Span.End - token.Span.Start
  45. for (token_index + 1) < len(tree.Tokens) && token_span_size == 0 {
  46. token_index += 1
  47. token = tree.Tokens[token_index]
  48. token_span_size = token.Span.End - token.Span.Start
  49. }
  50. var point = tree.Info[token.Span.Start]
  51. var desc = err.Desc()
  52. return FormatError (
  53. tree.Code, tree.Info, tree.SpanMap,
  54. tree.Name, point, token.Span,
  55. ERR_FOV, TS_SPOT, desc,
  56. )
  57. }