value.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package value
  2. import "fmt"
  3. type Value interface {
  4. ID() int
  5. Name() string
  6. // Proto/type of the value.
  7. Type() Type
  8. String() string
  9. Parent() Value
  10. Members() []Value
  11. }
  12. // A type is also a value
  13. type Type Value
  14. var TypeType Type = NewObject(-1, "Type", nil, nil)
  15. var ObjectType Type = NewObject(-2, "Object", TypeType, nil)
  16. var StringType Type = NewObject(-3, "String", ObjectType, nil)
  17. var IntType Type = NewObject(-4, "Int", ObjectType, nil)
  18. type Object struct {
  19. id int
  20. name string
  21. typ Type
  22. parent Value
  23. members []Value
  24. }
  25. func (o Object) String() string {
  26. return fmt.Sprintf("%s: %d", o.typ, o.name)
  27. }
  28. func (o Object) ID() int {
  29. return o.id
  30. }
  31. func (o Object) Name() string {
  32. return o.name
  33. }
  34. func (o Object) Parent() Value {
  35. return o.parent
  36. }
  37. func (o Object) Members() []Value {
  38. return o.members
  39. }
  40. func (o Object) Type() Type {
  41. return o.typ
  42. }
  43. func NewObject(id int, name string, typ Type,
  44. parent Value, members ...Value) Object {
  45. return Object{
  46. id: id, name: name, typ: typ, parent: parent, members: members,
  47. }
  48. }
  49. type String struct {
  50. Object
  51. Value string
  52. }
  53. func (s String) String() string {
  54. return s.Value
  55. }
  56. func NewString(value string, id int, name string,
  57. parent Value, members ...Value) String {
  58. return String{Object: NewObject(id, name, StringType, parent, members...),
  59. Value: value}
  60. }
  61. type Int struct {
  62. Object
  63. Value int64
  64. }
  65. func NewInt(value int64, id int, name string,
  66. parent Value, members ...Value) Int {
  67. return Int{Object: NewObject(id, name, IntType, parent, members...),
  68. Value: value}
  69. }
  70. func (i Int) String() string {
  71. return fmt.Sprintf("%d", i.Value)
  72. }
  73. type List struct {
  74. Object
  75. }
  76. func NewList(value int64, id int, name string,
  77. parent Value, members ...Value) List {
  78. return List{Object: NewObject(id, name, IntType, parent, members...)}
  79. }
  80. func (l List) String() string {
  81. return fmt.Sprintf("[%v]", l.members)
  82. }
  83. var _ Value = String{}
  84. var _ Value = Int{}
  85. var _ Value = List{}