blob: 68616b7c96ba4497b22c8ad2872f31bc2b9b830f (
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
|
package lexpr
import "context"
func infixToRpn(ctx context.Context, tokens <-chan Token) <-chan Token {
out := make(chan Token)
stack := TokenStack{}
go func() {
defer func() {
if len(stack) > 0 {
for {
if stack.Head().typ == lp {
out <- Token{
typ: tokError,
value: "invalid brakets",
}
break
}
out <- stack.Pop()
if len(stack) == 0 {
break
}
}
}
close(out)
}()
for {
select {
case <-ctx.Done():
return
case tkn, ok := <-tokens:
if !ok {
return
}
switch tkn.typ {
case number, word, str, tokError:
out <- tkn
case funct:
stack.Push(tkn)
case sep:
for stack.Head().typ != lp {
if len(stack) == 0 {
out <- Token{
typ: tokError,
value: "no arg separator or opening braket",
}
return
}
out <- stack.Pop()
}
case op:
for len(stack) > 0 && (stack.Head().typ != op || (stack.Head().priority >= tkn.priority)) {
out <- stack.Pop()
}
stack.Push(tkn)
case lp:
stack.Push(tkn)
case rp:
for stack.Head().typ != lp {
if len(stack) == 0 {
out <- Token{
typ: tokError,
value: "no opening braket",
}
return
}
out <- stack.Pop()
}
stack.Pop()
if stack.Head().typ == funct {
out <- stack.Pop()
}
}
}
}
}()
return out
}
|