Skip to content

Commit 6913224

Browse files
committed
Refactoring
1 parent cba3ed1 commit 6913224

File tree

2 files changed

+14
-20
lines changed

2 files changed

+14
-20
lines changed

query/parse.go

Lines changed: 12 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -72,24 +72,22 @@ func isSpace(c byte) bool {
7272
return c == ' ' || c == '\t'
7373
}
7474

75-
// globally tracking parentheses
76-
var parenBalance int
77-
7875
// Parse parses a string into a query.
7976
func Parse(qStr string) (Q, error) {
8077
b := []byte(qStr)
81-
parenBalance = 0
78+
parenBalance := 0
8279
qs, _, err := parseExprList(b, &parenBalance)
8380

81+
if err != nil {
82+
return nil, err
83+
}
84+
8485
if parenBalance < 0 {
8586
return nil, fmt.Errorf("right parentheses unbalanced")
8687
}
8788
if parenBalance > 0 {
8889
return nil, fmt.Errorf("left parentheses unbalanced")
8990
}
90-
if err != nil {
91-
return nil, err
92-
}
9391

9492
q, err := parseOperators(qs)
9593
if err != nil {
@@ -337,24 +335,19 @@ func parseExprList(in []byte, parenBalance *int) ([]Q, int, error) {
337335
for len(b) > 0 && isSpace(b[0]) {
338336
b = b[1:]
339337
}
340-
// fmt.Println("PAREN BALANCE: ", parenBalance, string(b))
341338
tok, _ := nextToken(b)
342339
if tok != nil {
343-
switch tok.Type {
344-
case tokParenOpen:
340+
if tok.Type == tokParenOpen {
345341
(*parenBalance)++
346-
case tokParenClose:
342+
} else if tok.Type == tokParenClose {
347343
(*parenBalance)--
344+
break
345+
} else if tok.Type == tokOr {
346+
qs = append(qs, &orOperator{})
347+
b = b[len(tok.Input):]
348+
continue
348349
}
349350
}
350-
// fmt.Println("PAREN BALANCE AFTER: ", parenBalance, tok)
351-
if tok != nil && tok.Type == tokParenClose {
352-
break
353-
} else if tok != nil && tok.Type == tokOr {
354-
qs = append(qs, &orOperator{})
355-
b = b[len(tok.Input):]
356-
continue
357-
}
358351

359352
q, n, err := parseExpr(b, parenBalance)
360353
if err != nil {

query/parse_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,8 @@ func TestParseQuery(t *testing.T) {
124124
{"abc or", nil},
125125
{"or abc", nil},
126126
{"def or or abc", nil},
127-
127+
128+
// unbalanced parentheses
128129
{"(", nil},
129130
{"((", nil},
130131
{"(((", nil},

0 commit comments

Comments
 (0)