-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
155 lines (121 loc) · 2.14 KB
/
utils.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
package parser
import "strings"
func isTerm(s string) bool {
l := len(s)
first := s[:1]
last := s[l-1:]
if l > 4 {
firstPart := s[:4]
if firstPart == operatorNot {
first = s[4:5]
}
}
if first == openExp && last == closeExp {
return true
}
return false
}
func containsOperator(s string) bool {
return strings.Contains(s, operatorAnd) ||
strings.Contains(s, operatorOr) ||
strings.Contains(s, operatorNot)
}
func testParentheses(s string) bool {
q := 0
for i := 0; i < len(s); i++ {
t := s[i : i+1]
if t == openExp {
q++
} else if t == closeExp {
q--
}
if q < 0 {
return false
}
}
return q == 0
}
func simplify(s string) (string, error) {
st := strings.Trim(s, separator)
if st == "" {
return "", ErrorExpression
}
st = strings.ReplaceAll(st, "not(", "not (")
if !testParentheses(st) {
return "", ErrorParentheses
}
l := len(st) - 1
first := st[:1]
last := st[l:]
if first == openExp && last == closeExp {
middle := st[1:l]
r, err := simplify(middle)
if err == ErrorParentheses {
return st, nil
}
return r, err
}
return st, nil
}
func testExpression(s string) bool {
if s == "" {
return false
}
st, err := simplify(s)
if err != nil {
return false
}
var parts []string
if !containsOperator(st) {
l := len(st)
if l >= 3 {
wrongStart := st[:3]
wrongEnd := st[l-3:]
if wrongStart == "or " {
return false
}
if wrongEnd == " or" {
return false
}
}
if l >= 3 {
wrongEnd := st[l-3:]
if wrongEnd == "not" {
return false
}
}
if l >= 4 {
wrongStart := st[:4]
wrongEnd := st[l-4:]
if wrongStart == "and " {
return false
}
if wrongEnd == " and" {
return false
}
}
return true
}
parts, _ = splitOr(st)
if len(parts) > 1 {
for _, part := range parts {
if !testExpression(part) {
return false
}
}
return true
}
parts, _ = splitAnd(st)
if len(parts) > 1 {
for _, part := range parts {
if !testExpression(part) {
return false
}
}
return true
}
if len(st) >= len(operatorNot) && st[:len(operatorNot)] == operatorNot {
return testExpression(st[4:])
}
return false
}