object.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. StringObj = "STRING"
  18. BuiltinObj = "BUILTIN"
  19. )
  20. // Object source code as an Object
  21. type Object interface {
  22. Type() ObjType
  23. Inspect() string
  24. }
  25. // BuiltinFunction 内建函数数据
  26. type BuiltinFunction func(args ...Object) Object
  27. type Integer struct {
  28. Value int64
  29. }
  30. func (i *Integer) Type() ObjType { return IntegerObj }
  31. func (i *Integer) Inspect() string { return fmt.Sprintf("%d", i.Value) }
  32. type Boolean struct {
  33. Value bool
  34. }
  35. func (b *Boolean) Type() ObjType { return BooleanObj }
  36. func (b *Boolean) Inspect() string { return fmt.Sprintf("%t", b.Value) }
  37. type Null struct{}
  38. func (n *Null) Type() ObjType { return NullObj }
  39. func (n *Null) Inspect() string { return "null" }
  40. type ReturnValue struct {
  41. Value Object
  42. }
  43. func (rv *ReturnValue) Type() ObjType { return ReturnValueObj }
  44. func (rv *ReturnValue) Inspect() string { return rv.Value.Inspect() }
  45. type Error struct {
  46. Msg string
  47. }
  48. func (e *Error) Type() ObjType { return ErrorObj }
  49. func (e *Error) Inspect() string { return "ERROR: " + e.Msg }
  50. type Function struct {
  51. Parameters []*ast.Identifier
  52. Body *ast.BlockStatement
  53. Env *Environment
  54. }
  55. func (f *Function) Type() ObjType { return FunctionObj }
  56. func (f *Function) Inspect() string {
  57. var out bytes.Buffer
  58. params := []string{}
  59. for _, p := range f.Parameters {
  60. params = append(params, p.String())
  61. }
  62. out.WriteString("fn")
  63. out.WriteString("(")
  64. out.WriteString(strings.Join(params, ", "))
  65. out.WriteString(") {\n")
  66. out.WriteString(f.Body.String())
  67. out.WriteString("\n}")
  68. return out.String()
  69. }
  70. type String struct {
  71. Value string
  72. }
  73. func (s *String) Type() ObjType { return StringObj }
  74. func (s *String) Inspect() string { return s.Value }
  75. type Builtin struct {
  76. Fn BuiltinFunction
  77. }
  78. func (b Builtin) Type() ObjType { return BuiltinObj }
  79. func (b Builtin) Inspect() string { return "builtin function" }