forked from nickng/migo
/
stack.go
56 lines (47 loc) · 1.08 KB
/
stack.go
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
package migo
import (
"errors"
"sync"
)
var (
// ErrEmptyStack is the error message if the Statement stack is empty.
ErrEmptyStack = errors.New("stack: empty")
)
// StmtsStack is a stack of []Statement.
//
// StmtsStack is mostly used for building nested control-flow of the MiGo
// language.
type StmtsStack struct {
sync.Mutex
s [][]Statement
}
// NewStmtsStack creates a new StmtsStack.
func NewStmtsStack() *StmtsStack {
return &StmtsStack{s: [][]Statement{}}
}
// Push adds a new Statement to the top of stack.
func (s *StmtsStack) Push(stmt []Statement) {
s.Lock()
defer s.Unlock()
s.s = append(s.s, stmt)
}
// Pop removes and returns a Statement from top of stack.
func (s *StmtsStack) Pop() ([]Statement, error) {
s.Lock()
defer s.Unlock()
size := len(s.s)
if size == 0 {
return nil, ErrEmptyStack
}
stmt := s.s[size-1]
s.s = s.s[:size-1]
return stmt, nil
}
// Size returns the number of elements in stack.
func (s *StmtsStack) Size() int {
return len(s.s)
}
// IsEmpty returns true if stack is empty.
func (s *StmtsStack) IsEmpty() bool {
return len(s.s) == 0
}