about summary refs log tree commit diff
path: root/pkg/lang/vm/stack.go
blob: 9cf7db8d8ba106cfa6f265fb07f3d7f71de02ccb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package vm

import (
	"jinx/pkg/lang/vm/value"
)

type CallStack []*LocalStack

func NewCallStack() CallStack {
	return []*LocalStack{{}}
}

func (cs *CallStack) Push() error {
	if len(*cs) > 1000 {
		return ErrCallStackOverflow
	}

	*cs = append(*cs, &LocalStack{})
	return nil
}

func (cs *CallStack) Pop() error {
	if len(*cs) <= 1 {
		return ErrCantPopRootFrame
	}

	*cs = (*cs)[:len(*cs)-1]
	return nil
}

func (cs *CallStack) Top() *LocalStack {
	return (*cs)[len(*cs)-1]
}

func (cs *CallStack) Prev() (*LocalStack, error) {
	if len(*cs) <= 1 {
		return nil, ErrNoPreviousCallFrame
	}

	return (*cs)[len(*cs)-2], nil
}

type LocalStack []value.Value

func (ls *LocalStack) Push(v value.Value) error {
	if len(*ls) > 1000 {
		return ErrLocalStackOverflow
	}

	*ls = append(*ls, v)
	return nil
}

func (ls *LocalStack) Pop() (value.Value, error) {
	if len(*ls) == 0 {
		return value.Value{}, ErrCallFrameEmpty
	}

	v := (*ls)[len(*ls)-1]
	*ls = (*ls)[:len(*ls)-1]
	return v, nil
}

func (ls *LocalStack) At(at int) (value.Value, error) {
	if at >= len(*ls) {
		return value.Value{}, ErrLocalIndexOutOfBounds{
			Index: at,
			Len:   len(*ls),
		}
	}

	return (*ls)[at], nil
}