48 lines
965 B
Go
48 lines
965 B
Go
package compiler
|
|
|
|
import "fmt"
|
|
|
|
type LabelStack struct {
|
|
stack []string
|
|
counter int
|
|
prefix string
|
|
}
|
|
|
|
func NewLabelStack(prefix string) *LabelStack {
|
|
return &LabelStack{
|
|
stack: make([]string, 0),
|
|
counter: 0,
|
|
prefix: prefix,
|
|
}
|
|
}
|
|
|
|
func (ls *LabelStack) Push() string {
|
|
ls.counter++
|
|
label := fmt.Sprintf("%s%d", ls.prefix, ls.counter)
|
|
ls.stack = append(ls.stack, label)
|
|
return label
|
|
}
|
|
|
|
func (ls *LabelStack) Peek() (string, error) {
|
|
if len(ls.stack) == 0 {
|
|
return "", fmt.Errorf("stack underflow: %s stack is empty", ls.prefix)
|
|
}
|
|
return ls.stack[len(ls.stack)-1], nil
|
|
}
|
|
|
|
func (ls *LabelStack) Pop() (string, error) {
|
|
if len(ls.stack) == 0 {
|
|
return "", fmt.Errorf("stack underflow: %s stack is empty", ls.prefix)
|
|
}
|
|
label := ls.stack[len(ls.stack)-1]
|
|
ls.stack = ls.stack[:len(ls.stack)-1]
|
|
return label, nil
|
|
}
|
|
|
|
func (ls *LabelStack) IsEmpty() bool {
|
|
return len(ls.stack) == 0
|
|
}
|
|
|
|
func (ls *LabelStack) Size() int {
|
|
return len(ls.stack)
|
|
}
|