-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlexer.go
97 lines (87 loc) · 2 KB
/
lexer.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// Copyright 2013 Rodrigo Moraes. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package bantam
import (
"fmt"
)
// Lexer defines an interface for lexical scanners.
//
// We don't have a real lexer implementation in this package, only a dummy one
// in the tests.
type Lexer interface {
Next() Token
}
// NewStack returns a stack for the given lexer.
func NewStack(lexer Lexer) *Stack {
return &Stack{lexer: lexer}
}
// Stack is a basic LIFO stack for tokens. It allows forwarding and rewinding.
type Stack struct {
lexer Lexer
tokens []Token
count int
}
// Push adds one or more tokens back to the stack.
func (s *Stack) Push(t ...Token) {
s.tokens = append(s.tokens[:s.count], t...)
s.count += len(t)
}
// Pop consumes and returns a token from the stack.
func (s *Stack) Pop() Token {
if s.count == 0 {
return s.lexer.Next()
}
s.count--
return s.tokens[s.count]
}
// Peek returns without consuming a token at the given index.
func (s *Stack) Peek(index int) Token {
switch {
case index == 0:
t := s.Pop()
s.Push(t)
return t
case index > 0:
if index < s.count {
return s.tokens[index]
}
t := make([]Token, index+1)
for index >= 0 {
t[index] = s.Pop()
index--
}
s.Push(t...)
return t[0]
}
panic(fmt.Errorf("Peek received negative index"))
}
// Expect consumes a token if matches one of the expected types. Otherwise
// it panics.
func (s *Stack) Expect(expected ...TokenType) Token {
t := s.Pop()
switch len(expected) {
case 1:
if t.Type == expected[0] {
return t
}
default:
for _, e := range expected {
if t.Type == e {
return t
}
}
}
s.Push(t)
panic(fmt.Errorf("expected token %s and found %s", expected, t.Type))
}
// Match consumes a token if it is of the expected type, returning true.
// Otherwise the token is not consumed and it returns false.
func (s *Stack) Match(expected TokenType) bool {
t := s.Pop()
if t.Type != expected {
s.Push(t)
return false
}
return true
}