github.com/cowsed/Parser@v0.0.0-20211216032244-48b10019d380/stack.go (about)

     1  package parser
     2  
     3  import "fmt"
     4  
     5  //TokenStack is FIFO stack of tokens for parsing
     6  type TokenStack struct {
     7  	elements []Token
     8  	top      int
     9  }
    10  
    11  //NewTokenStack returns an empty TokenStack
    12  func NewTokenStack() TokenStack {
    13  	return TokenStack{
    14  		elements: []Token{},
    15  		top:      0,
    16  	}
    17  
    18  }
    19  
    20  //Len Returns the length of the stack
    21  func (s *TokenStack) Len() int {
    22  	return len(s.elements)
    23  }
    24  
    25  //Push pushes a token to the stack
    26  func (s *TokenStack) Push(n Token) {
    27  	s.elements = append(s.elements, n)
    28  	s.top++
    29  }
    30  
    31  //Pop takes a token from the stack
    32  func (s *TokenStack) Pop() (Token, error) {
    33  	if s.top <= 0 {
    34  		return Token{}, fmt.Errorf("0 Length Stack")
    35  	}
    36  	n := s.elements[(s.top - 1)]
    37  	s.elements = s.elements[0 : s.top-1]
    38  	s.top--
    39  	return n, nil
    40  }
    41  
    42  //Peek looks at the top of the stack without removing it
    43  func (s *TokenStack) Peek() (Token, error) {
    44  	if s.top <= 0 {
    45  		return Token{}, fmt.Errorf("0 Length Stack")
    46  	}
    47  	n := s.elements[(s.top - 1)]
    48  	return n, nil
    49  }
    50  
    51  //ExpressionStack is a FIFO stack of expression elements
    52  type ExpressionStack struct {
    53  	elements []Expression
    54  	top      int
    55  }
    56  
    57  //NewExpressionStack returns an empty expression stack
    58  func NewExpressionStack() ExpressionStack {
    59  	return ExpressionStack{
    60  		elements: []Expression{},
    61  		top:      0,
    62  	}
    63  
    64  }
    65  
    66  //Len Returns the length of the stack
    67  func (s *ExpressionStack) Len() int {
    68  	return len(s.elements)
    69  }
    70  
    71  //Push pushes a token to the stack
    72  func (s *ExpressionStack) Push(n Expression) {
    73  	s.elements = append(s.elements, n)
    74  	s.top++
    75  }
    76  
    77  //Pop takes a token from the stack
    78  func (s *ExpressionStack) Pop() (Expression, error) {
    79  	if s.top <= 0 {
    80  		return nil, fmt.Errorf("0 Length Stack")
    81  	}
    82  	n := s.elements[(s.top - 1)]
    83  	s.elements = s.elements[0 : s.top-1]
    84  	s.top--
    85  	return n, nil
    86  }
    87  
    88  //Peek looks at the top of the stack without removing it
    89  func (s *ExpressionStack) Peek() (Expression, error) {
    90  	if s.top <= 0 {
    91  		return nil, fmt.Errorf("0 Length Stack")
    92  	}
    93  	n := s.elements[(s.top - 1)]
    94  	return n, nil
    95  }