ast.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. }
  74. // return <expression>;
  75. type ReturnStatement struct {
  76. Token token.Token // the token.RETURN
  77. returnValue Expression
  78. }
  79. func (rs *ReturnStatement) TokenLiteral() string {
  80. return rs.Token.Literal
  81. }
  82. func (rs *ReturnStatement) statementNode() {
  83. panic("implement me")
  84. }