datastack.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package glisp
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type DataStackElem struct {
  7. expr Sexp
  8. }
  9. func (d DataStackElem) IsStackElem() {}
  10. func (stack *Stack) PushExpr(expr Sexp) {
  11. stack.Push(DataStackElem{expr})
  12. }
  13. func (stack *Stack) PopExpr() (Sexp, error) {
  14. elem, err := stack.Pop()
  15. if err != nil {
  16. return nil, err
  17. }
  18. return elem.(DataStackElem).expr, nil
  19. }
  20. func (stack *Stack) GetExpressions(n int) ([]Sexp, error) {
  21. stack_start := stack.tos - n + 1
  22. if stack_start < 0 {
  23. return nil, errors.New("not enough items on stack")
  24. }
  25. arr := make([]Sexp, n)
  26. for i := 0; i < n; i++ {
  27. arr[i] = stack.elements[stack_start+i].(DataStackElem).expr
  28. }
  29. return arr, nil
  30. }
  31. func (stack *Stack) PopExpressions(n int) ([]Sexp, error) {
  32. expressions, err := stack.GetExpressions(n)
  33. if err != nil {
  34. return nil, err
  35. }
  36. stack.tos -= n
  37. return expressions, nil
  38. }
  39. func (stack *Stack) GetExpr(n int) (Sexp, error) {
  40. elem, err := stack.Get(n)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return elem.(DataStackElem).expr, nil
  45. }
  46. func (stack *Stack) PrintStack() {
  47. fmt.Printf("\t%d elements\n", stack.tos+1)
  48. for i := 0; i <= stack.tos; i++ {
  49. expr := stack.elements[i].(DataStackElem).expr
  50. fmt.Println("\t" + expr.SexpString())
  51. }
  52. }