forked from crestonbunch/godata
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathsearch_parser.go
59 lines (50 loc) · 1.48 KB
/
search_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
package godata
import "context"
type SearchTokenType int
func (s SearchTokenType) Value() int {
return (int)(s)
}
const (
SearchTokenLiteral SearchTokenType = iota
SearchTokenOpenParen
SearchTokenCloseParen
SearchTokenOp
SearchTokenWhitespace
)
var GlobalSearchTokenizer = SearchTokenizer()
var GlobalSearchParser = SearchParser()
// Convert an input string from the $filter part of the URL into a parse
// tree that can be used by providers to create a response.
func ParseSearchString(ctx context.Context, filter string) (*GoDataSearchQuery, error) {
tokens, err := GlobalSearchTokenizer.Tokenize(ctx, filter)
if err != nil {
return nil, err
}
postfix, err := GlobalSearchParser.InfixToPostfix(ctx, tokens)
if err != nil {
return nil, err
}
tree, err := GlobalSearchParser.PostfixToTree(ctx, postfix)
if err != nil {
return nil, err
}
return &GoDataSearchQuery{tree, filter}, nil
}
// Create a tokenizer capable of tokenizing filter statements
func SearchTokenizer() *Tokenizer {
t := Tokenizer{}
t.Add("^\\\"[^\\\"]+\\\"", SearchTokenLiteral)
t.Add("^\\(", SearchTokenOpenParen)
t.Add("^\\)", SearchTokenCloseParen)
t.Add("^(OR|AND|NOT)", SearchTokenOp)
t.Add("^[\\w]+", SearchTokenLiteral)
t.Ignore("^ ", SearchTokenWhitespace)
return &t
}
func SearchParser() *Parser {
parser := EmptyParser()
parser.DefineOperator("NOT", 1, OpAssociationNone, 3)
parser.DefineOperator("AND", 2, OpAssociationLeft, 2)
parser.DefineOperator("OR", 2, OpAssociationLeft, 1)
return parser
}