ast.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package ast
  2. import "bytes"
  3. // Node is the interface implemented by every node in the AST. It extends the
  4. // fmt.Stringer interface, allowing simple printing of nodes.
  5. type Node interface {
  6. // TokenLiteral returns the literal value of the token it's associated to.
  7. TokenLiteral() string
  8. String() string
  9. }
  10. // Statement extends Node and is only a way to differentiate between expressions
  11. // and statements.
  12. type Statement interface {
  13. Node
  14. statementNode()
  15. }
  16. // Expression extends Node and is only a way to differentiate between
  17. // expressions and statements.
  18. type Expression interface {
  19. // Expression extends Node.
  20. Node
  21. expressionNode()
  22. }
  23. // Program represents the outer structure of the parser program.
  24. type Program struct {
  25. Statements []Statement
  26. }
  27. // String satisfies the Node and fmt.Stringer interfaces.
  28. func (p *Program) String() string {
  29. var out bytes.Buffer
  30. for _, s := range p.Statements {
  31. out.WriteString(s.String())
  32. }
  33. return out.String()
  34. }
  35. // TokenLiteral returns the string contents of the first statement token, which
  36. // can be an empty string if the program is empty.
  37. func (p *Program) TokenLiteral() string {
  38. if len(p.Statements) > 0 {
  39. return p.Statements[0].TokenLiteral()
  40. }
  41. return ""
  42. }