object.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package object
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github/runnignwater/monkey/ast"
  6. "strings"
  7. )
  8. // ObjType type of object
  9. type ObjType string
  10. const (
  11. IntegerObj = "INTEGER"
  12. BooleanObj = "BOOLEAN"
  13. NullObj = "NULL"
  14. ReturnValueObj = "RETURN_VALUE"
  15. ErrorObj = "ERROR"
  16. FunctionObj = "FUNCTION"
  17. )
  18. // Object source code as an Object
  19. type Object interface {
  20. Type() ObjType
  21. Inspect() string
  22. }
  23. type Integer struct {
  24. Value int64
  25. }
  26. func (i *Integer) Type() ObjType { return IntegerObj }
  27. func (i *Integer) Inspect() string { return fmt.Sprintf("%d", i.Value) }
  28. type Boolean struct {
  29. Value bool
  30. }
  31. func (b *Boolean) Type() ObjType { return BooleanObj }
  32. func (b *Boolean) Inspect() string { return fmt.Sprintf("%t", b.Value) }
  33. type Null struct{}
  34. func (n *Null) Type() ObjType { return NullObj }
  35. func (n *Null) Inspect() string { return "null" }
  36. type ReturnValue struct {
  37. Value Object
  38. }
  39. func (rv *ReturnValue) Type() ObjType { return ReturnValueObj }
  40. func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }
  41. type Error struct {
  42. Msg string
  43. }
  44. func (e *Error) Type() ObjType { return ErrorObj }
  45. func (e *Error) Inspect() string { return "ERROR: " + e.Msg }
  46. type Function struct {
  47. Parameters []*ast.Identifier
  48. Body *ast.BlockStatement
  49. Env *Environment
  50. }
  51. func (f *Function) Type() ObjType { return FunctionObj }
  52. func (f *Function) Inspect() string {
  53. var out bytes.Buffer
  54. params := []string{}
  55. for _, p := range f.Parameters {
  56. params = append(params, p.String())
  57. }
  58. out.WriteString("fn")
  59. out.WriteString("(")
  60. out.WriteString(strings.Join(params, ", "))
  61. out.WriteString(") {\n")
  62. out.WriteString(f.Body.String())
  63. out.WriteString("\n}")
  64. return out.String()
  65. }