Repository navigation
Expand file tree
/
Copy pathassertion_parser.go
More file actions
344 lines (305 loc) · 8.24 KB
/
Copy pathassertion_parser.go
File metadata and controls
344 lines (305 loc) · 8.24 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package libkb
import (
"fmt"
"regexp"
"strings"
)
const (
NONE = iota
OR
AND
LPAREN
RPAREN
URL
EOF
ERROR
)
type Token struct {
Typ int
value []byte
}
func (t Token) getString() string {
return string(t.value)
}
func (t Token) unexpectedError() error {
switch t.Typ {
case EOF:
return NewAssertionParseError("Unexpected EOF parsing assertion")
case ERROR:
// Nothing was matched when arrived at t.value.
return NewAssertionParseError("Syntax error when parsing: %v", t.getString())
default:
return NewAssertionParseError("Unexpected token: %s", t.getString())
}
}
func byteArrayEq(a1, a2 []byte) bool {
if len(a1) != len(a2) {
return false
}
for i, c := range a1 {
if c != a2[i] {
return false
}
}
return true
}
func (t Token) Eq(t2 Token) bool {
return (t.Typ == t2.Typ) && byteArrayEq(t.value, t2.value)
}
func NewToken(typ int) Token {
return Token{Typ: typ}
}
type Lexer struct {
buffer []byte
last Token
putback bool
}
// Disjunction: '||' ','
// Conjunction: '&&' '+'
// Parens: '(' ')'
// URL:
var lexerURLCharsRxx = `([^ \n\t&|()\[\],+#]+)` // anything but control chars
var lexerURLSquareRxx = `(\[[^ \n\t#\[\]]*\])` // square bracket syntax, allows pretty much anything in
// URL has a character group and optionally square bracket groups
var lexerURLRxx = `((` + lexerURLCharsRxx + lexerURLSquareRxx + `?)|(` + lexerURLSquareRxx + `?` + lexerURLCharsRxx + `))`
var lexerItemRxx = regexp.MustCompile(`^((\|\|)|(\,)|(\&\&)|(\+)|(\()|(\))|` + lexerURLRxx + `)`)
var lexerWhitespaceRxx = regexp.MustCompile(`^([\n\t ]+)`)
func NewLexer(s string) *Lexer {
l := &Lexer{buffer: []byte(s)}
l.stripBuffer()
return l
}
// strip whitespace off the front
func (lx *Lexer) stripBuffer() {
if len(lx.buffer) > 0 {
if match := lexerWhitespaceRxx.FindSubmatchIndex(lx.buffer); match != nil {
lx.buffer = lx.buffer[match[3]:]
}
}
}
func (lx *Lexer) advanceBuffer(i int) {
lx.buffer = lx.buffer[i:]
lx.stripBuffer()
}
func (lx *Lexer) Putback() {
lx.putback = true
}
func (lx *Lexer) Get() Token {
var ret Token
if lx.putback {
ret = lx.last
lx.putback = false
} else if len(lx.buffer) == 0 {
ret = NewToken(EOF)
} else if match := lexerItemRxx.FindSubmatchIndex(lx.buffer); match != nil {
// First 2 in seq are NONE: one for the full expr, another for the
// outer ^() group.
// NOTE: There are a lot more groups due to `lexerURLRxx` inclusion in
// `lexerItemRxx`, but they happen at the end and we ignore them. We
// only capture the "outer" group which is URL here. To keep things simple,
// make sure URL is the last group checked here.
seq := []int{NONE, NONE, OR, OR, AND, AND, LPAREN, RPAREN, URL}
for i := 2; i <= len(seq); i++ {
if match[i*2] >= 0 {
ret = Token{Typ: seq[i], value: lx.buffer[match[2*i]:match[2*i+1]]}
lx.advanceBuffer(match[2*i+1])
break
}
}
} else {
ret = Token{Typ: ERROR, value: lx.buffer}
lx.buffer = nil
}
lx.last = ret
return ret
}
type Parser struct {
lexer *Lexer
err error
andOnly bool
}
func NewParser(lexer *Lexer) *Parser {
ret := &Parser{lexer, nil, false}
return ret
}
func NewAssertionAnd(left, right AssertionExpression) AssertionAnd {
factors := []AssertionExpression{left, right}
return AssertionAnd{factors}
}
func NewAssertionOr(left, right AssertionExpression, symbol string) AssertionOr {
terms := []AssertionExpression{left, right}
return AssertionOr{
terms: terms,
symbol: symbol,
}
}
func NewAssertionKeybaseUsername(username string) AssertionKeybase {
return AssertionKeybase{AssertionURLBase: AssertionURLBase{Key: "keybase", Value: username}}
}
func (p *Parser) Parse(ctx AssertionContext) AssertionExpression {
ret := p.parseExpr(ctx)
if ret != nil {
tok := p.lexer.Get()
switch tok.Typ {
case EOF:
// expected
case ERROR:
p.err = NewAssertionParseError("Found error at end of input (%s)",
tok.value)
ret = nil
default:
p.err = NewAssertionParseError("Found junk at end of input: %s",
tok.value)
ret = nil
}
}
return ret
}
func (p *Parser) parseTerm(ctx AssertionContext) (ret AssertionExpression) {
factor := p.parseFactor(ctx)
tok := p.lexer.Get()
if tok.Typ == AND {
term := p.parseTerm(ctx)
ret = NewAssertionAnd(factor, term)
} else {
ret = factor
p.lexer.Putback()
}
return ret
}
func (p *Parser) parseFactor(ctx AssertionContext) (ret AssertionExpression) {
tok := p.lexer.Get()
switch tok.Typ {
case URL:
url, err := ParseAssertionURL(ctx, tok.getString(), false)
if err != nil {
p.err = err
} else {
ret = url
}
case LPAREN:
if ex := p.parseExpr(ctx); ex == nil {
ret = nil
p.err = NewAssertionParseError("Illegal parenthetical expression")
} else {
tok = p.lexer.Get()
if tok.Typ == RPAREN {
ret = ex
} else {
ret = nil
p.err = NewAssertionParseError("Unbalanced parentheses")
}
}
default:
p.err = tok.unexpectedError()
}
return ret
}
func (p *Parser) parseExpr(ctx AssertionContext) (ret AssertionExpression) {
term := p.parseTerm(ctx)
tok := p.lexer.Get()
if tok.Typ != OR {
ret = term
p.lexer.Putback()
} else if p.andOnly {
p.err = NewAssertionParseErrorWithReason(
AssertionParseErrorReasonUnexpectedOR,
"Unexpected 'OR' operator (no '||'s or ','s allowed in this context)",
)
} else {
ex := p.parseExpr(ctx)
ret = NewAssertionOr(term, ex, string(tok.value))
}
return ret
}
func AssertionParse(ctx AssertionContext, s string) (AssertionExpression, error) {
lexer := NewLexer(s)
parser := Parser{
lexer: lexer,
err: nil,
andOnly: false,
}
ret := parser.Parse(ctx)
return ret, parser.err
}
func AssertionParseAndOnly(ctx AssertionContext, s string) (AssertionExpression, error) {
lexer := NewLexer(s)
parser := Parser{
lexer: lexer,
err: nil,
andOnly: true,
}
ret := parser.Parse(ctx)
return ret, parser.err
}
// Parse an assertion list like "alice,bob&&bob@twitter#char"
// OR nodes are not allowed (asides from the commas)
func ParseAssertionsWithReaders(ctx AssertionContext, assertions string) (writers, readers []AssertionExpression, err error) {
if len(assertions) == 0 {
return writers, readers, fmt.Errorf("empty assertion")
}
split := strings.Split(assertions, "#")
if len(split) > 2 {
return writers, readers, fmt.Errorf("too many reader divisions ('#') in assertions: %v", assertions)
}
writers, err = ParseAssertionList(ctx, split[0])
if err != nil {
return writers, readers, err
}
if len(split) >= 2 && len(split[1]) > 0 {
readers, err = ParseAssertionList(ctx, split[1])
if err != nil {
return writers, readers, err
}
}
return writers, readers, nil
}
// Parse a string into one or more assertions. Only AND assertions are allowed within each part.
// like "alice,bob&&bob@twitter"
func ParseAssertionList(ctx AssertionContext, assertionsStr string) (res []AssertionExpression, err error) {
expr, err := AssertionParse(ctx, assertionsStr)
if err != nil {
return res, err
}
return unpackAssertionList(expr)
}
// Unpack an assertion with one or more comma-separated parts. Only AND assertions are allowed within each part.
func unpackAssertionList(expr AssertionExpression) (res []AssertionExpression, err error) {
switch expr := expr.(type) {
case AssertionOr:
// List (or recursive tree) of comma-separated items.
if expr.symbol != "," {
// Don't allow "||". That would be confusing.
return res, fmt.Errorf("disallowed OR expression: '%v'", expr.symbol)
}
for _, sub := range expr.terms {
// Recurse because "a,b,c" could look like (OR a (OR b c))
sublist, err := unpackAssertionList(sub)
if err != nil {
return res, err
}
res = append(res, sublist...)
}
return res, nil
default:
// Just one item.
err = checkAssertionListItem(expr)
return []AssertionExpression{expr}, err
}
}
// A single item in a comma-separated assertion list must not have any ORs in its subtree.
func checkAssertionListItem(expr AssertionExpression) error {
if expr.HasOr() {
return fmt.Errorf("assertions with OR are not allowed here")
}
switch expr.(type) {
case AssertionOr:
// this should never happen
return fmt.Errorf("assertion parse fault: unexpected OR")
default:
// Anything else is allowed.
return nil
}
}