-
Notifications
You must be signed in to change notification settings - Fork 10
/
parser.go
457 lines (374 loc) · 9.81 KB
/
parser.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
// Copyright 2016 Steven Oud. All rights reserved.
// Use of this source code is governed by a MIT-style license that can be found
// in the LICENSE file.
package mathcat
import (
"errors"
"fmt"
"math"
"math/big"
)
// Parser holds the lexed tokens, token position, declared variables and stacks
// used throughout the parsing of an expression.
//
// By default, variables always contains the constants defined below. These can
// however be overwritten.
type Parser struct {
Tokens Tokens
Variables map[string]*big.Rat
pos int
tok *Token
operands, operators, arity stack
}
var (
// RatTrue represents true in boolean operations
RatTrue = big.NewRat(1, 1)
// RatFalse represents false in boolean operations
RatFalse = big.NewRat(0, 1)
ErrUnmatchedParentheses = errors.New("Unmatched parentheses")
ErrMisplacedComma = errors.New("Misplaced ‘,’")
ErrAssignToLiteral = errors.New("Can't assign to literal")
defaultVariables = map[string]*big.Rat{
"pi": new(big.Rat).SetFloat64(math.Pi),
"tau": new(big.Rat).Mul(new(big.Rat).SetFloat64(math.Pi), big.NewRat(2, 1)),
"phi": new(big.Rat).SetFloat64(math.Phi),
"e": new(big.Rat).SetFloat64(math.E),
"true": RatTrue,
"false": RatFalse,
}
)
// New initializes a new Parser instance, useful when you want to run multiple
// expression and/or use variables.
func New() *Parser {
parser := &Parser{}
parser.Variables = make(map[string]*big.Rat)
for k, v := range defaultVariables {
parser.Variables[k] = v
}
return parser
}
// Eval evaluates an expression and returns its result and any errors found.
//
// Example:
// res, err := mathcat.Eval("2 * 2 * 2") // 8
func Eval(expr string) (*big.Rat, error) {
tokens, err := Lex(expr)
// If a lexer error occurred don't parse
if err != nil {
return nil, err
}
p := New()
p.Tokens = tokens
return p.parse()
}
// Run executes an expression on an existing parser instance. Useful for
// variable assignment.
//
// Example:
// p.Run("a = 555")
// p.Run("a += 45")
// res, err := p.Run("a + a") // 1200
func (p *Parser) Run(expr string) (*big.Rat, error) {
tokens, err := Lex(expr)
if err != nil {
return nil, err
}
p.reset()
p.Tokens = tokens
return p.parse()
}
// Exec executes an expression with a given map of variables.
//
// Example:
// res, err := mathcat.Exec("a + b * b", map[string]*big.Rat{
// "a": big.NewRat(1, 1),
// "b": big.NewRat(3, 1),
// }) // 10
func Exec(expr string, vars map[string]*big.Rat) (*big.Rat, error) {
tokens, err := Lex(expr)
if err != nil {
return nil, err
}
p := New()
p.Tokens = tokens
for name, val := range vars {
if !IsValidIdent(name) {
return nil, fmt.Errorf("Invalid variable name: ‘%s’", name)
}
p.Variables[name] = val
}
return p.parse()
}
// GetVar gets an existing variable.
//
// Example:
// p.Run("酷 = -33")
// if val, err := p.GetVar("酷"); !err {
// fmt.Printf("%f\n", val) // -33
// }
func (p Parser) GetVar(index string) (*big.Rat, error) {
if val, ok := p.Variables[index]; ok {
return val, nil
}
return nil, fmt.Errorf("Undefined variable ‘%s’", index)
}
func (p *Parser) parse() (*big.Rat, error) {
// Initializing current token value
p.tok = p.Tokens[0]
for !p.eat().Is(Eol) {
switch {
case p.tok.IsLiteral():
if p.peek().Is(Lparen) {
// It's a function call, push to operators stack instead
p.operators.Push(p.tok)
// Check ahead if the function call has any argument at all, so
// we can do accurate tracking of arity
if p.peekN(2).Is(Rparen) {
p.arity.Push(0)
} else {
p.arity.Push(1)
}
break
}
p.operands.Push(p.tok)
case p.tok.Is(Lparen):
p.operators.Push(p.tok)
case p.tok.Is(Comma):
for {
if p.operators.Empty() {
return nil, ErrMisplacedComma
}
if p.operators.Top().(*Token).Is(Lparen) {
break
}
val, err := p.evaluate(p.operators.Pop().(*Token))
if err != nil {
return nil, err
}
p.operands.Push(val)
}
p.arity.Push(p.arity.Pop().(int) + 1)
case p.tok.IsOperator():
if err := p.handleOperator(); err != nil {
return nil, err
}
case p.tok.Is(Rparen):
for {
if p.operators.Empty() {
return nil, ErrUnmatchedParentheses
}
top := p.operators.Pop().(*Token)
if top.Is(Lparen) {
break
}
val, err := p.evaluate(top)
if err != nil {
return nil, err
}
p.operands.Push(val)
}
}
}
// Evaluate remaining operators
for !p.operators.Empty() {
top := p.operators.Pop().(*Token)
if top.Is(Lparen) {
return nil, ErrUnmatchedParentheses
}
val, err := p.evaluate(top)
if err != nil {
return nil, err
}
p.operands.Push(val)
}
// If there are no operands, the expression is useless and doesn't do
// anything, for example `()`
if p.operands.Empty() {
return new(big.Rat), nil
}
// Single operand left means the expression was evaluated successful
if len(p.operands) == 1 {
return p.lookup(p.operands[0])
}
// Leftover token on operand stack indicates invalid syntax
return nil, fmt.Errorf("Unexpected ‘%s’", p.operands.Top())
}
func (p *Parser) handleOperator() error {
var o1, o2 operator
o1 = operators[p.tok.Type]
// No operators yet, just push to operators stack
if p.operators.Empty() {
p.operators.Push(p.tok)
return nil
}
// While there's a function at the top of the operator stack, or an operator
// with higher precedence than o1, pop operators to operands
for p.operators.Top().(*Token).Is(Ident) || p.operators.Top().(*Token).IsOperator() {
// Function call, always take precedence over operator
if p.operators.Top().(*Token).Is(Ident) {
function := p.operators.Pop().(*Token)
val, err := p.evaluateFunc(function)
if err != nil {
return err
}
p.operands.Push(val)
} else {
o2 = operators[p.operators.Top().(*Token).Type]
// Another operator at top, check precedence
if o2.hasHigherPrecThan(o1) {
operator := p.operators.Pop().(*Token)
val, err := p.evaluateOp(operator)
if err != nil {
return err
}
p.operands.Push(val)
} else {
break
}
}
if p.operators.Empty() {
break
}
}
p.operators.Push(p.tok)
return nil
}
// evaluate gets called when an operator or function call has to be evaluated
// for a result. In case of a function, evaluateFunc is called and in case of
// an operator evaluateOp is called.
func (p *Parser) evaluate(tok *Token) (*big.Rat, error) {
if tok.IsOperator() {
return p.evaluateOp(tok)
}
return p.evaluateFunc(tok)
}
func (p *Parser) evaluateFunc(tok *Token) (*big.Rat, error) {
var (
function function
ok bool
i int
)
if function, ok = funcs[tok.Value]; !ok {
return nil, fmt.Errorf("Undefined function ‘%s’", tok)
}
if arity := p.arity.Pop().(int); arity != function.arity {
return nil, fmt.Errorf("Invalid argument count for ‘%s’ (expected %d, got %d)", tok, function.arity, arity)
}
// Start popping off arguments for the function call
args := make([]*big.Rat, function.arity)
for i = function.arity - 1; i >= 0; i-- {
if p.operands.Empty() {
return nil, ErrMisplacedComma
}
arg, err := p.lookup(p.operands.Pop())
if err != nil {
return nil, err
}
args[i] = arg
}
return function.fn(args), nil
}
func (p *Parser) evaluateOp(operator *Token) (*big.Rat, error) {
var (
result *big.Rat
lhs, rhs *big.Rat
err error
lhsToken interface{}
)
if p.operands.Empty() {
return nil, fmt.Errorf("Unexpected ‘%s’", operator)
}
if rhs, err = p.lookup(p.operands.Pop()); err != nil {
return nil, err
}
// Unary operators have no left hand side
if op := operators[operator.Type]; !op.unary {
if p.operands.Empty() {
return nil, fmt.Errorf("Unexpected ‘%s’", operator)
}
// Save the token in case of a assignment variable is used and we need
// to save the result in a variable
lhsToken = p.operands.Pop()
// Don't lookup the left hand side if = is used so we can do initial
// assignment
if !operator.Is(Eq) {
lhs, err = p.lookup(lhsToken)
if err != nil {
return nil, err
}
}
}
result, err = executeExpression(operator, lhs, rhs)
if err != nil {
return nil, err
}
if operator.IsAssignment() {
// Save result in variable
if val, ok := lhsToken.(*Token); !(ok && val.Is(Ident)) {
return nil, ErrAssignToLiteral
}
p.Variables[lhsToken.(*Token).Value] = result
}
return result, nil
}
// Look up a literal. If it's an identifier, check the parser's variables map,
// otherwise convert the tokenized string to a rational number.
func (p *Parser) lookup(val interface{}) (*big.Rat, error) {
// val can be a token or a rational, if it's a rational it has been already
// evaluated and we don't need to do anything
if v, ok := val.(*big.Rat); ok {
return v, nil
}
var (
ok bool
res = new(big.Rat)
)
bases := [...]int{
Hex: 16,
Octal: 8,
Binary: 2,
}
tok := val.(*Token)
switch tok.Type {
case Decimal:
res, ok = res.SetString(tok.Value)
if !ok {
return nil, fmt.Errorf("Error parsing ‘%s’: invalid %s", tok.Value, tok.Type)
}
case Hex, Binary, Octal:
tmpInt := new(big.Int)
// Remove prefix of literal and convert to int first
tmpInt, ok = tmpInt.SetString(tok.Value[2:], bases[tok.Type])
if !ok {
return nil, fmt.Errorf("Error parsing ‘%s’: invalid %s", tok.Value, tok.Type)
}
res.SetInt(tmpInt)
case Ident:
res, err := p.GetVar(tok.Value)
if err != nil {
return nil, err
}
return res, nil
default:
return nil, fmt.Errorf("Invalid lookup type ‘%s’", tok)
}
return res, nil
}
func (p *Parser) reset() {
p.Tokens = nil
p.pos = 0
p.operators = nil
p.operands = nil
p.arity = nil
}
func (p *Parser) peek() *Token {
return p.Tokens[p.pos]
}
func (p *Parser) peekN(n int) *Token {
return p.Tokens[p.pos-1+n]
}
func (p *Parser) eat() *Token {
p.tok = p.peek()
p.pos++
return p.tok
}