ast.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package ast
  2. import "github/runnignwater/monkey/token"
  3. /**
  4. * @Author: simon
  5. * @Author: ynwdlxm@163.com
  6. * @Date: 2022/10/2 下午8:58
  7. * @Desc:
  8. */
  9. type Node interface {
  10. TokenLiteral() string
  11. }
  12. // expressions produce values, statements don't
  13. type Statement interface {
  14. Node
  15. statementNode()
  16. }
  17. type Expression interface {
  18. Node
  19. expressionNode()
  20. }
  21. // ---------------------implementation of Node----------------------------------BEGIN-----------------------------------
  22. // Root Node of our parser produces.
  23. type Program struct {
  24. Statements []Statement
  25. }
  26. func (p *Program) TokenLiteral() string {
  27. if len(p.Statements) > 0 {
  28. return p.Statements[0].TokenLiteral()
  29. } else {
  30. return ""
  31. }
  32. }
  33. //---------------------implementation of Node-----------------------------------END-------------------------------------
  34. // let <identifier> = <expression>;
  35. //
  36. // let x = 5 AST
  37. // |-------------------|
  38. // | *ast.Program |
  39. // |-------------------|
  40. // | Statements |
  41. // |-------------------|
  42. // ↓
  43. // |-------------------|
  44. // | *ast.LetStatement |
  45. // |-------------------|
  46. // | Name |
  47. // |-------------------|
  48. // | Value |
  49. // |-------------------|
  50. //
  51. // *ast.Identifier *ast.Expression
  52. //
  53. type LetStatement struct {
  54. Token token.Token // the token.LET token
  55. Name *Identifier
  56. Value Expression
  57. }
  58. func (ls *LetStatement) TokenLiteral() string {
  59. return ls.Token.Literal
  60. }
  61. func (ls *LetStatement) statementNode() {
  62. panic("implement me")
  63. }
  64. type Identifier struct {
  65. Token token.Token // the token.IDENT token
  66. Value string
  67. }
  68. func (i *Identifier) expressionNode() {
  69. panic("implement me")
  70. }
  71. func (i *Identifier) TokenLiteral() string {
  72. return i.Token.Literal
  73. }