data.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Any interface{}
  6. type Symbol string
  7. type Environment map[Symbol]Any
  8. type Scope struct {
  9. env Environment
  10. parent *Scope
  11. }
  12. func NewRootScope() *Scope {
  13. s := NewScope(nil)
  14. for k, v := range Builtins {
  15. s.env[k] = v
  16. }
  17. return s
  18. }
  19. func NewScope(parent *Scope) *Scope {
  20. return &Scope{make(Environment), parent}
  21. }
  22. func (s *Scope) evalFunctionCall(sexp []Any) Any {
  23. f := s.Eval(sexp[0])
  24. switch fn := f.(type) {
  25. case Macro:
  26. expansion := internalMacroExpand(s, sexp)
  27. return s.Eval(expansion)
  28. case Function:
  29. return fn.Apply(s, sexp[1:])
  30. case ApplyFn:
  31. return fn(s, sexp[1:])
  32. default:
  33. panic(fmt.Errorf("Not a function (main): %s", sexp[0]))
  34. }
  35. }
  36. func (s *Scope) Eval(sexp Any) Any {
  37. switch sexp := sexp.(type) {
  38. case []Any:
  39. if len(sexp) < 1 {
  40. return nil
  41. } else {
  42. return s.evalFunctionCall(sexp)
  43. }
  44. case Symbol:
  45. v, err := s.Lookup(sexp)
  46. if err != nil {
  47. panic(err)
  48. }
  49. return v
  50. default:
  51. return sexp
  52. }
  53. return nil
  54. }
  55. func (s *Scope) EvalAll(sexps []Any) []Any {
  56. res := make([]Any, len(sexps))
  57. for i, v := range sexps {
  58. res[i] = s.Eval(v)
  59. }
  60. return res
  61. }
  62. func (s *Scope) Add(sym Symbol, val Any) error {
  63. _, ok := s.env[sym]
  64. if ok {
  65. return fmt.Errorf("symbol: \"%s\" already defined in this scope", s)
  66. }
  67. s.env[sym] = val
  68. return nil
  69. }
  70. func (s *Scope) Override(sym Symbol, val Any) {
  71. s.env[sym] = val
  72. }
  73. func (s *Scope) getRootScope() *Scope {
  74. if s.parent == nil {
  75. return s
  76. } else {
  77. return s.parent.getRootScope()
  78. }
  79. }
  80. func (s *Scope) Lookup(sym Symbol) (Any, error) {
  81. val, ok := s.env[sym]
  82. if !ok && s.parent != nil {
  83. return s.parent.Lookup(sym)
  84. } else if !ok && s.parent == nil {
  85. return nil, fmt.Errorf("unknown variable: %s", sym)
  86. }
  87. return val, nil
  88. }