heap.go 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package rt
  2. import (
  3. "cp/object"
  4. "fmt"
  5. "reflect"
  6. )
  7. type INTEGER int
  8. type Variable interface {
  9. Set(interface{})
  10. }
  11. func (i *INTEGER) Set(val interface{}) {
  12. if val == nil {
  13. panic("cannot be nil")
  14. }
  15. switch val.(type) {
  16. case int:
  17. *i = INTEGER(val.(int))
  18. case INTEGER:
  19. *i = val.(INTEGER)
  20. case *INTEGER:
  21. *i = *val.(*INTEGER)
  22. default:
  23. fmt.Print(reflect.TypeOf(val), " ")
  24. panic("wrong type for INTEGER")
  25. }
  26. fmt.Println("set", int(*i))
  27. }
  28. type Heap interface {
  29. This(obj object.Object) Variable
  30. }
  31. type stdHeap struct {
  32. inner map[interface{}]interface{}
  33. }
  34. func NewHeap() Heap {
  35. return new(stdHeap).Init()
  36. }
  37. func (h *stdHeap) Init() *stdHeap {
  38. h.inner = make(map[interface{}]interface{}, 0)
  39. return h
  40. }
  41. func (h *stdHeap) This(obj object.Object) (ptr Variable) {
  42. p := h.inner[obj]
  43. if p == nil {
  44. switch obj.Type() {
  45. case object.INTEGER:
  46. ptr = new(INTEGER)
  47. h.inner[obj] = ptr
  48. default:
  49. fmt.Println(obj.Type())
  50. panic("unknown object type")
  51. }
  52. } else {
  53. ptr = p.(Variable)
  54. }
  55. return ptr
  56. }