aboutsummaryrefslogtreecommitdiff
path: root/tokenizer.go
blob: df4b08f7ce4e1961072a00a1e42c8162c7859628 (plain) (blame)
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (c) 2020 Alexander Kiryukhin <a.kiryukhin@mail.ru>

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package executor

import (
	"fmt"
	"strconv"
)

type tokenizer struct {
	str           string
	numberBuffer  string
	strBuffer     string
	allowNegative bool
	tkns          []*token
	operators     map[string]*Operator
}

func newTokenizer(str string, operators map[string]*Operator) *tokenizer {
	return &tokenizer{str: str, numberBuffer: "", strBuffer: "", allowNegative: true, tkns: []*token{}, operators: operators}
}

func (t *tokenizer) emptyNumberBufferAsLiteral() error {
	if t.numberBuffer != "" {
		f, err := strconv.ParseFloat(t.numberBuffer, 64)
		if err != nil {
			return fmt.Errorf("invalid number %s", t.numberBuffer)
		}
		t.tkns = append(t.tkns, newToken(literalType, "", f))
	}
	t.numberBuffer = ""
	return nil
}

func (t *tokenizer) emptyStrBufferAsVariable() {
	if t.strBuffer != "" {
		t.tkns = append(t.tkns, newToken(variableType, t.strBuffer, 0))
		t.strBuffer = ""
	}
}

func (t *tokenizer) tokenize() error {
	for _, ch := range t.str {
		if ch == ' ' {
			continue
		}
		ch := byte(ch)
		switch true {
		case isAlpha(ch):
			if t.numberBuffer != "" {
				if err := t.emptyNumberBufferAsLiteral(); err != nil {
					return err
				}
				t.tkns = append(t.tkns, newToken(operatorType, "*", 0))
				t.numberBuffer = ""
			}
			t.allowNegative = false
			t.strBuffer += string(ch)
		case isNumber(ch):
			t.numberBuffer += string(ch)
			t.allowNegative = false
		case isDot(ch):
			t.numberBuffer += string(ch)
			t.allowNegative = false
		case isLP(ch):
			if t.strBuffer != "" {
				t.tkns = append(t.tkns, newToken(functionType, t.strBuffer, 0))
				t.strBuffer = ""
			} else if t.numberBuffer != "" {
				if err := t.emptyNumberBufferAsLiteral(); err != nil {
					return err
				}
				t.tkns = append(t.tkns, newToken(operatorType, "*", 0))
				t.numberBuffer = ""
			}
			t.allowNegative = true
			t.tkns = append(t.tkns, newToken(leftParenthesisType, "", 0))
		case isRP(ch):
			if err := t.emptyNumberBufferAsLiteral(); err != nil {
				return err
			}
			t.emptyStrBufferAsVariable()
			t.allowNegative = false
			t.tkns = append(t.tkns, newToken(rightParenthesisType, "", 0))
		case isComma(ch):
			if err := t.emptyNumberBufferAsLiteral(); err != nil {
				return err
			}
			t.emptyStrBufferAsVariable()
			t.tkns = append(t.tkns, newToken(funcSep, "", 0))
			t.allowNegative = true
		default:
			if t.allowNegative && ch == '-' {
				t.numberBuffer += "-"
				t.allowNegative = false
				continue
			}
			if err := t.emptyNumberBufferAsLiteral(); err != nil {
				return err
			}
			t.emptyStrBufferAsVariable()
			if len(t.tkns) > 0 && t.tkns[len(t.tkns)-1].Type == operatorType {
				t.tkns[len(t.tkns)-1].SValue += string(ch)
			} else {
				t.tkns = append(t.tkns, newToken(operatorType, string(ch), 0))
			}
			t.allowNegative = true
		}
	}
	if err := t.emptyNumberBufferAsLiteral(); err != nil {
		return err
	}
	t.emptyStrBufferAsVariable()
	return nil
}

func (t *tokenizer) toRPN() ([]*token, error) {
	var tkns []*token
	var stack tokenStack
	for _, tkn := range t.tkns {
		switch tkn.Type {
		case literalType:
			tkns = append(tkns, tkn)
		case variableType:
			tkns = append(tkns, tkn)
		case functionType:
			stack.Push(tkn)
		case funcSep:
			for stack.Head().Type != leftParenthesisType {
				if stack.Head().Type == eof {
					return nil, ErrInvalidExpression
				}
				tkns = append(tkns, stack.Pop())
			}
		case operatorType:
			leftOp, ok := t.operators[tkn.SValue]
			if !ok {
				return nil, fmt.Errorf("unknown operator: %s", tkn.SValue)
			}
			for {
				if stack.Head().Type == operatorType {
					rightOp, ok := t.operators[stack.Head().SValue]
					if !ok {
						return nil, fmt.Errorf("unknown operator: %s", stack.Head().SValue)
					}
					if leftOp.Priority < rightOp.Priority || (leftOp.Priority == rightOp.Priority && leftOp.Assoc == RightAssoc) {
						tkns = append(tkns, stack.Pop())
						continue
					}
				}
				break
			}
			stack.Push(tkn)
		case leftParenthesisType:
			stack.Push(tkn)
		case rightParenthesisType:
			for stack.Head().Type != leftParenthesisType {
				if stack.Head().Type == eof {
					return nil, ErrInvalidParenthesis
				}
				tkns = append(tkns, stack.Pop())
			}
			stack.Pop()
			if stack.Head().Type == functionType {
				tkns = append(tkns, stack.Pop())
			}
		}
	}
	for stack.Head().Type != eof {
		if stack.Head().Type == leftParenthesisType {
			return nil, ErrInvalidParenthesis
		}
		tkns = append(tkns, stack.Pop())
	}
	return tkns, nil
}

type tokenStack struct {
	ts []*token
}

func (ts *tokenStack) Push(t *token) {
	ts.ts = append(ts.ts, t)
}

func (ts *tokenStack) Pop() *token {
	if len(ts.ts) == 0 {
		return &token{Type: eof}
	}
	var head *token
	head, ts.ts = ts.ts[len(ts.ts)-1], ts.ts[:len(ts.ts)-1]
	return head
}

func (ts *tokenStack) Head() *token {
	if len(ts.ts) == 0 {
		return &token{Type: eof}
	}
	return ts.ts[len(ts.ts)-1]
}

func isComma(ch byte) bool {
	return ch == ','
}

func isDot(ch byte) bool {
	return ch == '.'
}

func isNumber(ch byte) bool {
	return ch >= '0' && ch <= '9'
}

func isAlpha(ch byte) bool {
	return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch == '_'
}

func isLP(ch byte) bool {
	return ch == '('
}

func isRP(ch byte) bool {
	return ch == ')'
}