forked from grafana/loki
-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.go
118 lines (101 loc) · 2.15 KB
/
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
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
package logql
import (
"errors"
"fmt"
"strconv"
"strings"
"text/scanner"
"github.com/prometheus/prometheus/model/labels"
)
func init() {
// Improve the error messages coming out of yacc.
exprErrorVerbose = true
for str, tok := range tokens {
exprToknames[tok-exprPrivate+1] = str
}
}
// ParseExpr parses a string and returns an Expr.
func ParseExpr(input string) (Expr, error) {
l := lexer{
parser: exprNewParser().(*exprParserImpl),
}
l.Init(strings.NewReader(input))
l.Scanner.Error = func(_ *scanner.Scanner, msg string) {
l.Error(msg)
}
e := l.parser.Parse(&l)
if e != 0 || len(l.errs) > 0 {
return nil, l.errs[0]
}
return l.expr, nil
}
// ParseMatchers parses a string and returns labels matchers, if the expression contains
// anything else it will return an error.
func ParseMatchers(input string) ([]*labels.Matcher, error) {
expr, err := ParseExpr(input)
if err != nil {
return nil, err
}
matcherExpr, ok := expr.(*matchersExpr)
if !ok {
return nil, errors.New("only label matchers is supported")
}
return matcherExpr.matchers, nil
}
var tokens = map[string]int{
",": COMMA,
".": DOT,
"{": OPEN_BRACE,
"}": CLOSE_BRACE,
"=": EQ,
"!=": NEQ,
"=~": RE,
"!~": NRE,
"|=": PIPE_EXACT,
"|~": PIPE_MATCH,
}
type lexer struct {
scanner.Scanner
errs []ParseError
expr Expr
parser *exprParserImpl
}
func (l *lexer) Lex(lval *exprSymType) int {
r := l.Scan()
switch r {
case scanner.EOF:
return 0
case scanner.String:
var err error
lval.str, err = strconv.Unquote(l.TokenText())
if err != nil {
l.Error(err.Error())
return 0
}
return STRING
}
if tok, ok := tokens[l.TokenText()+string(l.Peek())]; ok {
l.Next()
return tok
}
if tok, ok := tokens[l.TokenText()]; ok {
return tok
}
lval.str = l.TokenText()
return IDENTIFIER
}
func (l *lexer) Error(msg string) {
l.errs = append(l.errs, ParseError{
msg: msg,
line: l.Line,
col: l.Column,
})
}
// ParseError is what is returned when we failed to parse.
type ParseError struct {
msg string
line, col int
}
func (p ParseError) Error() string {
return fmt.Sprintf("parse error at line %d, col %d: %s", p.line, p.col, p.msg)
}