efp.go
16.7 KB
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// Package efp (Excel Formula Parser) tokenise an Excel formula using an
// implementation of E. W. Bachtal's algorithm, found here:
// https://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
//
// Go version by Ri Xu: https://xuri.me
package efp
import (
"strconv"
"strings"
)
// QuoteDouble, QuoteSingle and other's constants are token definitions.
const (
// Character constants
QuoteDouble = "\""
QuoteSingle = "'"
BracketClose = "]"
BracketOpen = "["
BraceOpen = "{"
BraceClose = "}"
ParenOpen = "("
ParenClose = ")"
Semicolon = ";"
Whitespace = " "
Comma = ","
ErrorStart = "#"
OperatorsSN = "+-"
OperatorsInfix = "+-*/^&=><"
OperatorsPostfix = "%"
// Token type
TokenTypeNoop = "Noop"
TokenTypeOperand = "Operand"
TokenTypeFunction = "Function"
TokenTypeSubexpression = "Subexpression"
TokenTypeArgument = "Argument"
TokenTypeOperatorPrefix = "OperatorPrefix"
TokenTypeOperatorInfix = "OperatorInfix"
TokenTypeOperatorPostfix = "OperatorPostfix"
TokenTypeWhitespace = "Whitespace"
TokenTypeUnknown = "Unknown"
// Token subtypes
TokenSubTypeNothing = "Nothing"
TokenSubTypeStart = "Start"
TokenSubTypeStop = "Stop"
TokenSubTypeText = "Text"
TokenSubTypeNumber = "Number"
TokenSubTypeLogical = "Logical"
TokenSubTypeError = "Error"
TokenSubTypeRange = "Range"
TokenSubTypeMath = "Math"
TokenSubTypeConcatenation = "Concatenation"
TokenSubTypeIntersection = "Intersection"
TokenSubTypeUnion = "Union"
)
// Token encapsulate a formula token.
type Token struct {
TValue string
TType string
TSubType string
}
// Tokens directly maps the ordered list of tokens.
// Attributes:
//
// items - Ordered list
// index - Current position in the list
//
type Tokens struct {
Index int
Items []Token
}
// Parser inheritable container. TokenStack directly maps a LIFO stack of
// tokens.
type Parser struct {
Formula string
Tokens Tokens
TokenStack Tokens
Offset int
Token string
InString bool
InPath bool
InRange bool
InError bool
}
// fToken provides function to encapsulate a formula token.
func fToken(value, tokenType, subType string) Token {
return Token{
TValue: value,
TType: tokenType,
TSubType: subType,
}
}
// fTokens provides function to handle an ordered list of tokens.
func fTokens() Tokens {
return Tokens{
Index: -1,
}
}
// add provides function to add a token to the end of the list.
func (tk *Tokens) add(value, tokenType, subType string) Token {
token := fToken(value, tokenType, subType)
tk.addRef(token)
return token
}
// addRef provides function to add a token to the end of the list.
func (tk *Tokens) addRef(token Token) {
tk.Items = append(tk.Items, token)
}
// reset provides function to reset the index to -1.
func (tk *Tokens) reset() {
tk.Index = -1
}
// BOF provides function to check whether or not beginning of list.
func (tk *Tokens) BOF() bool {
return tk.Index <= 0
}
// EOF provides function to check whether or not end of list.
func (tk *Tokens) EOF() bool {
return tk.Index >= (len(tk.Items) - 1)
}
// moveNext provides function to move the index along one.
func (tk *Tokens) moveNext() bool {
if tk.EOF() {
return false
}
tk.Index++
return true
}
// current return the current token.
func (tk *Tokens) current() *Token {
if tk.Index == -1 {
return nil
}
return &tk.Items[tk.Index]
}
// next return the next token (leave the index unchanged).
func (tk *Tokens) next() *Token {
if tk.EOF() {
return nil
}
return &tk.Items[tk.Index+1]
}
// previous return the previous token (leave the index unchanged).
func (tk *Tokens) previous() *Token {
if tk.Index < 1 {
return nil
}
return &tk.Items[tk.Index-1]
}
// push provides function to push a token onto the stack.
func (tk *Tokens) push(token Token) {
tk.Items = append(tk.Items, token)
}
// pop provides function to pop a token off the stack.
func (tk *Tokens) pop() Token {
if len(tk.Items) == 0 {
return Token{
TType: TokenTypeFunction,
TSubType: TokenSubTypeStop,
}
}
t := tk.Items[len(tk.Items)-1]
tk.Items = tk.Items[:len(tk.Items)-1]
return fToken("", t.TType, TokenSubTypeStop)
}
// token provides function to non-destructively return the top item on the
// stack.
func (tk *Tokens) token() *Token {
if len(tk.Items) > 0 {
return &tk.Items[len(tk.Items)-1]
}
return nil
}
// value return the top token's value.
func (tk *Tokens) value() string {
return tk.token().TValue
}
// tp return the top token's type.
func (tk *Tokens) tp() string {
return tk.token().TType
}
// subtype return the top token's subtype.
func (tk *Tokens) subtype() string {
return tk.token().TSubType
}
// ExcelParser provides function to parse an Excel formula into a stream of
// tokens.
func ExcelParser() Parser {
return Parser{}
}
// getTokens return a token stream (list).
func (ps *Parser) getTokens(formula string) Tokens {
ps.Formula = strings.TrimSpace(ps.Formula)
f := []rune(ps.Formula)
if len(f) > 0 {
if string(f[0]) != "=" {
ps.Formula = "=" + ps.Formula
}
}
// state-dependent character evaluation (order is important)
for !ps.EOF() {
// double-quoted strings
// embeds are doubled
// end marks token
if ps.InString {
if ps.currentChar() == "\"" {
if ps.nextChar() == "\"" {
ps.Token += "\""
ps.Offset++
} else {
ps.InString = false
ps.Tokens.add(ps.Token, TokenTypeOperand, TokenSubTypeText)
ps.Token = ""
}
} else {
ps.Token += ps.currentChar()
}
ps.Offset++
continue
}
// single-quoted strings (links)
// embeds are double
// end does not mark a token
if ps.InPath {
if ps.currentChar() == "'" {
if ps.nextChar() == "'" {
ps.Token += "'"
ps.Offset++
} else {
ps.InPath = false
}
} else {
ps.Token += ps.currentChar()
}
ps.Offset++
continue
}
// bracketed strings (range offset or linked workbook name)
// no embeds (changed to "()" by Excel)
// end does not mark a token
if ps.InError {
if ps.currentChar() == "]" {
ps.InRange = false
}
ps.Token += ps.currentChar()
ps.Offset++
continue
}
// error values
// end marks a token, determined from absolute list of values
if ps.InError {
ps.Token += ps.currentChar()
ps.Offset++
errors := map[string]string{",#NULL!,": "", ",#DIV/0!,": "", ",#VALUE!,": "", ",#REF!,": "", ",#NAME?,": "", ",#NUM!,": "", ",#N/A,": ""}
_, ok := errors[","+ps.Token+","]
if ok {
ps.InError = false
ps.Tokens.add(ps.Token, TokenTypeOperand, TokenSubTypeError)
ps.Token = ""
}
continue
}
// independent character evaluation (order not important)
// establish state-dependent character evaluations
if ps.currentChar() == "\"" {
if len(ps.Token) > 0 {
// not expected
ps.Tokens.add(ps.Token, TokenTypeUnknown, "")
ps.Token = ""
}
ps.InString = true
ps.Offset++
continue
}
if ps.currentChar() == "'" {
if len(ps.Token) > 0 {
// not expected
ps.Tokens.add(ps.Token, TokenTypeUnknown, "")
ps.Token = ""
}
ps.InPath = true
ps.Offset++
continue
}
if ps.currentChar() == "[" {
ps.InRange = true
ps.Token += ps.currentChar()
ps.Offset++
continue
}
if ps.currentChar() == "#" {
if len(ps.Token) > 0 {
// not expected
ps.Tokens.add(ps.Token, TokenTypeUnknown, "")
ps.Token = ""
}
ps.InError = true
ps.Token += ps.currentChar()
ps.Offset++
continue
}
// mark start and end of arrays and array rows
if ps.currentChar() == "{" {
if len(ps.Token) > 0 {
// not expected
ps.Tokens.add(ps.Token, TokenTypeUnknown, "")
ps.Token = ""
}
ps.TokenStack.push(ps.Tokens.add("ARRAY", TokenTypeFunction, TokenSubTypeStart))
ps.TokenStack.push(ps.Tokens.add("ARRAYROW", TokenTypeFunction, TokenSubTypeStart))
ps.Offset++
continue
}
if ps.currentChar() == ";" {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.addRef(ps.TokenStack.pop())
ps.Tokens.add(",", TokenTypeArgument, "")
ps.TokenStack.push(ps.Tokens.add("ARRAYROW", TokenTypeFunction, TokenSubTypeStart))
ps.Offset++
continue
}
if ps.currentChar() == "}" {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.addRef(ps.TokenStack.pop())
ps.Tokens.addRef(ps.TokenStack.pop())
ps.Offset++
continue
}
// trim white-space
if ps.currentChar() == " " {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.add("", TokenTypeWhitespace, "")
ps.Offset++
for (ps.currentChar() == " ") && (!ps.EOF()) {
ps.Offset++
}
continue
}
// multi-character comparators
comparators := map[string]string{",>=,": "", ",<=,": "", ",<>,": ""}
_, ok := comparators[","+ps.doubleChar()+","]
if ok {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.add(ps.doubleChar(), TokenTypeOperatorInfix, TokenSubTypeLogical)
ps.Offset += 2
continue
}
// standard infix operators
operators := map[string]string{"+": "", "-": "", "*": "", "/": "", "^": "", "&": "", "=": "", ">": "", "<": ""}
_, ok = operators[ps.currentChar()]
if ok {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.add(ps.currentChar(), TokenTypeOperatorInfix, "")
ps.Offset++
continue
}
// standard postfix operators
if ps.currentChar() == "%" {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.add(ps.currentChar(), TokenTypeOperatorPostfix, "")
ps.Offset++
continue
}
// start subexpression or function
if ps.currentChar() == "(" {
if len(ps.Token) > 0 {
ps.TokenStack.push(ps.Tokens.add(ps.Token, TokenTypeFunction, TokenSubTypeStart))
ps.Token = ""
} else {
ps.TokenStack.push(ps.Tokens.add("", TokenTypeSubexpression, TokenSubTypeStart))
}
ps.Offset++
continue
}
// function, subexpression, array parameters
if ps.currentChar() == "," {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
if ps.TokenStack.tp() != TokenTypeFunction {
ps.Tokens.add(ps.currentChar(), TokenTypeOperatorInfix, TokenSubTypeUnion)
} else {
ps.Tokens.add(ps.currentChar(), TokenTypeArgument, "")
}
ps.Offset++
continue
}
// stop subexpression
if ps.currentChar() == ")" {
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
ps.Token = ""
}
ps.Tokens.addRef(ps.TokenStack.pop())
ps.Offset++
continue
}
// token accumulation
ps.Token += ps.currentChar()
ps.Offset++
}
// dump remaining accumulation
if len(ps.Token) > 0 {
ps.Tokens.add(ps.Token, TokenTypeOperand, "")
}
// move all tokens to a new collection, excluding all unnecessary white-space tokens
tokens2 := fTokens()
for ps.Tokens.moveNext() {
token := ps.Tokens.current()
if token.TType == TokenTypeWhitespace {
if ps.Tokens.BOF() || ps.Tokens.EOF() {
} else if !(((ps.Tokens.previous().TType == TokenTypeFunction) && (ps.Tokens.previous().TSubType == TokenSubTypeStop)) || ((ps.Tokens.previous().TType == TokenTypeSubexpression) && (ps.Tokens.previous().TSubType == TokenSubTypeStop)) || (ps.Tokens.previous().TType == TokenTypeOperand)) {
} else if !(((ps.Tokens.next().TType == TokenTypeFunction) && (ps.Tokens.next().TSubType == TokenSubTypeStart)) || ((ps.Tokens.next().TType == TokenTypeSubexpression) && (ps.Tokens.next().TSubType == TokenSubTypeStart)) || (ps.Tokens.next().TType == TokenTypeOperand)) {
} else {
tokens2.add(token.TValue, TokenTypeOperatorInfix, TokenSubTypeIntersection)
}
continue
}
tokens2.addRef(Token{
TValue: token.TValue,
TType: token.TType,
TSubType: token.TSubType,
})
}
// switch infix "-" operator to prefix when appropriate, switch infix "+"
// operator to noop when appropriate, identify operand and infix-operator
// subtypes, pull "@" from in front of function names
for tokens2.moveNext() {
token := tokens2.current()
if (token.TType == TokenTypeOperatorInfix) && (token.TValue == "-") {
if tokens2.BOF() {
token.TType = TokenTypeOperatorPrefix
} else if ((tokens2.previous().TType == TokenTypeFunction) && (tokens2.previous().TSubType == TokenSubTypeStop)) || ((tokens2.previous().TType == TokenTypeSubexpression) && (tokens2.previous().TSubType == TokenSubTypeStop)) || (tokens2.previous().TType == TokenTypeOperatorPostfix) || (tokens2.previous().TType == TokenTypeOperand) {
token.TSubType = TokenSubTypeMath
} else {
token.TType = TokenTypeOperatorPrefix
}
continue
}
if (token.TType == TokenTypeOperatorInfix) && (token.TValue == "+") {
if tokens2.BOF() {
token.TType = TokenTypeNoop
} else if (tokens2.previous().TType == TokenTypeFunction) && (tokens2.previous().TSubType == TokenSubTypeStop) || ((tokens2.previous().TType == TokenTypeSubexpression) && (tokens2.previous().TSubType == TokenSubTypeStop) || (tokens2.previous().TType == TokenTypeOperatorPostfix) || (tokens2.previous().TType == TokenTypeOperand)) {
token.TSubType = TokenSubTypeMath
} else {
token.TType = TokenTypeNoop
}
continue
}
if (token.TType == TokenTypeOperatorInfix) && (len(token.TSubType) == 0) {
op := map[string]string{"<": "", ">": "", "=": ""}
_, ok := op[token.TValue[0:1]]
if ok {
token.TSubType = TokenSubTypeLogical
} else if token.TValue == "&" {
token.TSubType = TokenSubTypeConcatenation
} else {
token.TSubType = TokenSubTypeMath
}
continue
}
if (token.TType == TokenTypeOperand) && (len(token.TSubType) == 0) {
if _, err := strconv.ParseFloat(token.TValue, 64); err != nil {
if (token.TValue == "TRUE") || (token.TValue == "FALSE") {
token.TSubType = TokenSubTypeLogical
} else {
token.TSubType = TokenSubTypeRange
}
} else {
token.TSubType = TokenSubTypeNumber
}
continue
}
if token.TType == TokenTypeFunction {
if (len(token.TValue) > 0) && token.TValue[0:1] == "@" {
token.TValue = token.TValue[1:]
}
continue
}
}
tokens2.reset()
// move all tokens to a new collection, excluding all noops
tokens := fTokens()
for tokens2.moveNext() {
if tokens2.current().TType != TokenTypeNoop {
tokens.addRef(Token{
TValue: tokens2.current().TValue,
TType: tokens2.current().TType,
TSubType: tokens2.current().TSubType,
})
}
}
tokens.reset()
return tokens
}
// doubleChar provides function to get two characters after the current
// position.
func (ps *Parser) doubleChar() string {
if len([]rune(ps.Formula)) >= ps.Offset+2 {
return string([]rune(ps.Formula)[ps.Offset : ps.Offset+2])
}
return ""
}
// currentChar provides function to get the character of the current position.
func (ps *Parser) currentChar() string {
return string([]rune(ps.Formula)[ps.Offset])
}
// nextChar provides function to get the next character of the current position.
func (ps *Parser) nextChar() string {
if len([]rune(ps.Formula)) >= ps.Offset+1 {
return ""
}
return string([]rune(ps.Formula)[ps.Offset+1])
}
// EOF provides function to check whether or not end of tokens stack.
func (ps *Parser) EOF() bool {
return ps.Offset >= len([]rune(ps.Formula))
}
// Parse provides function to parse formula as a token stream (list).
func (ps *Parser) Parse(formula string) []Token {
ps.Formula = formula
ps.Tokens = ps.getTokens(formula)
return ps.Tokens.Items
}
// PrettyPrint provides function to pretty the parsed result with the indented
// format.
func (ps *Parser) PrettyPrint() string {
indent := 0
output := ""
for _, t := range ps.Tokens.Items {
if t.TSubType == TokenSubTypeStop {
indent--
}
for i := 0; i < indent; i++ {
output += "\t"
}
output += t.TValue + " <" + t.TType + "> <" + t.TSubType + ">" + "\n"
if t.TSubType == TokenSubTypeStart {
indent++
}
}
return output
}
// Render provides function to get formatted formula after parsed.
func (ps *Parser) Render() string {
output := ""
for _, t := range ps.Tokens.Items {
if t.TType == TokenTypeFunction && t.TSubType == TokenSubTypeStart {
output += t.TValue + "("
} else if t.TType == TokenTypeFunction && t.TSubType == TokenSubTypeStop {
output += ")"
} else if t.TType == TokenTypeSubexpression && t.TSubType == TokenSubTypeStart {
output += "("
} else if t.TType == TokenTypeSubexpression && t.TSubType == TokenSubTypeStop {
output += ")"
} else if t.TType == TokenTypeOperand && t.TSubType == TokenSubTypeText {
output += "\"" + t.TValue + "\""
} else if t.TType == TokenTypeOperatorInfix && t.TSubType == TokenSubTypeIntersection {
output += " "
} else {
output += t.TValue
}
}
return output
}