ast.go 1.2 KB

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