-
Notifications
You must be signed in to change notification settings - Fork 6
/
parser.go
754 lines (663 loc) · 21.1 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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
/*
Copyright © 2024 Acronis International GmbH.
Released under MIT license.
*/
package cti
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/google/uuid"
)
const (
// InheritanceSeparator is a character that separates inheritance parts in CTI expression.
InheritanceSeparator = '~'
// Wildcard is a character that represents wildcard in CTI expression.
Wildcard = '*'
)
// ParseError wraps any parsing error.
type ParseError struct {
Err error
RawExpression string
}
// Error implements "error" interface.
func (e *ParseError) Error() string {
return e.Err.Error()
}
// Unwrap implements Wrapper interface.
func (e *ParseError) Unwrap() error {
return e.Err
}
// ErrNotExpression is returned when an input is not a CTI expression.
var ErrNotExpression = errors.New("not CTI expression")
type versionStrategy uint8
const (
versionStrategyRequireFull versionStrategy = iota
versionStrategyRequireOnlyMajor
versionStrategyAllowEmpty
)
type parserParams struct {
queryDisabled bool
attributeSelectorDisabled bool
versionStrategy versionStrategy
wildcardDisabled bool
}
// Parser is an object for parsing CTI expressions.
type Parser struct {
allowAnonymousEntity bool
allowedDynamicParameterNames []string
}
// ParserOpts represents a parsing options.
type ParserOpts struct {
AllowedDynamicParameterNames []string
}
// NewParser creates new Parser.
// Available options:
// - WithAllowAnonymousEntity(b bool) - allows parsing anonymous entity UUID in CTI expressions.
// - WithAllowedDynamicParameterNames(names ...string) - allows specifying dynamic parameter names that can be used in CTI expressions.
func NewParser(opts ...ParserOption) *Parser {
pOpts := makeParserOptions(opts...)
return &Parser{
allowAnonymousEntity: pOpts.allowAnonymousEntity,
allowedDynamicParameterNames: pOpts.allowedDynamicParameterNames,
}
}
// Parse parses input string as a CTI expression.
// It accepts all kinds of expressions including identifiers, queries and attribute selectors.
// See ParseQuery, ParseAttributeSelector, ParseIdentifier, ParseReference for more specific parsing.
func Parse(input string, opts ...ParserOption) (Expression, error) {
return NewParser(opts...).Parse(input)
}
// MustParse parses input string as a CTI expression and panics on error.
// See Parse for more details.
func MustParse(input string, opts ...ParserOption) Expression {
return NewParser(opts...).MustParse(input)
}
// ParseQuery parses input string as a CTI expression.
// For more details see ParseQuery in Parser.
func ParseQuery(input string, opts ...ParserOption) (Expression, error) {
return NewParser(opts...).ParseQuery(input)
}
// ParseAttributeSelector parses input string as a CTI expression.
// For more details see ParseAttributeSelector in Parser.
func ParseAttributeSelector(input string, opts ...ParserOption) (Expression, error) {
return NewParser(opts...).ParseAttributeSelector(input)
}
// ParseIdentifier parses input string as a CTI expression.
// For more details see ParseIdentifier in Parser.
func ParseIdentifier(input string, opts ...ParserOption) (Expression, error) {
return NewParser(opts...).ParseIdentifier(input)
}
// ParseReference parses input string as a CTI expression.
// For more details see ParseReference in Parser.
func ParseReference(input string, opts ...ParserOption) (Expression, error) {
return NewParser(opts...).ParseReference(input)
}
// Parse parses input string as a CTI expression.
// It accepts all kinds of expressions including identifiers, references, queries and attribute selectors.
// See ParseQuery, ParseAttributeSelector, ParseIdentifier, ParseReference for more specific parsing.
func (p *Parser) Parse(input string) (Expression, error) {
return p.parse(input, parserParams{
queryDisabled: false,
attributeSelectorDisabled: false,
versionStrategy: versionStrategyRequireFull,
wildcardDisabled: false,
})
}
// ParseQuery parses input string as a CTI expression. It allows only query but not attribute selectors.
// In addition, wildcard is not allowed and optional minor version is allowed.
func (p *Parser) ParseQuery(input string) (Expression, error) {
return p.parse(input, parserParams{
queryDisabled: false,
attributeSelectorDisabled: true,
versionStrategy: versionStrategyRequireOnlyMajor,
wildcardDisabled: true,
})
}
// ParseAttributeSelector parses input string as a CTI expression. It allows only attribute selectors but not queries.
// In addition, wildcard is not allowed and optional minor version is allowed.
// It returns error if attribute selector is absent in input string.
func (p *Parser) ParseAttributeSelector(input string) (Expression, error) {
expr, err := p.parse(input, parserParams{
queryDisabled: true,
attributeSelectorDisabled: false,
versionStrategy: versionStrategyRequireOnlyMajor,
wildcardDisabled: true,
})
if err != nil {
return emptyExpression, err
}
if expr.AttributeSelector == "" {
return emptyExpression, fmt.Errorf("attribute selector is absent in input string")
}
return expr, nil
}
// ParseIdentifier parses input string as a CTI expression. It allows only identifiers without queries and attribute selectors.
// In addition, wildcard and optional version are not allowed.
func (p *Parser) ParseIdentifier(input string) (Expression, error) {
return p.parse(input, parserParams{
queryDisabled: true,
attributeSelectorDisabled: true,
versionStrategy: versionStrategyRequireFull,
wildcardDisabled: true,
})
}
// ParseReference parses input string as a CTI expression. It allows only identifiers without queries and attribute selectors.
// In addition, wildcards and optional full version are allowed.
func (p *Parser) ParseReference(input string) (Expression, error) {
return p.parse(input, parserParams{
queryDisabled: true,
attributeSelectorDisabled: true,
versionStrategy: versionStrategyAllowEmpty,
wildcardDisabled: false,
})
}
func (p *Parser) parse(input string, params parserParams) (Expression, error) {
expr, err := p.parseExpression(input, params)
if err != nil {
return emptyExpression, &ParseError{Err: err, RawExpression: input}
}
return expr, nil
}
// MustParse parses input string as a CTI expression and panics on error.
func (p *Parser) MustParse(input string) Expression {
expr, err := p.Parse(input)
if err != nil {
panic(err)
}
return expr
}
func (p *Parser) parseExpression(s string, params parserParams) (Expression, error) {
if !strings.HasPrefix(s, "cti.") {
return emptyExpression, ErrNotExpression
}
s = s[4:] // cut "cti." prefix
var err error
var queryAttributes QueryAttributeSlice
var attributeSelector AttributeName
var anonymousEntityUUID uuid.NullUUID
parseQueryOrSelectorIfPresent := func(s string) (string, error) {
if !params.queryDisabled {
if queryAttributes, s, err = p.parseQueryAttributesIfPresent(s); err != nil {
return s, fmt.Errorf("parse query attributes: %w", err)
}
}
if !params.attributeSelectorDisabled && len(queryAttributes) == 0 {
if attributeSelector, s, err = p.parseAttributeSelectorIfPresent(s); err != nil {
return s, fmt.Errorf("parse attribute selector: %w", err)
}
}
return s, nil
}
var head *Node
var tail *Node
for s != "" {
if head != nil {
if tail.HasWildcard() {
return emptyExpression, fmt.Errorf(`expression may have wildcard "%c" only at the end`, Wildcard)
}
if anonymousEntityUUID.Valid {
return emptyExpression, fmt.Errorf(`expression may have anonymous entity UUID only at the end`)
}
if len(queryAttributes) != 0 {
return emptyExpression, fmt.Errorf(`expression may have query only at the end`)
}
if attributeSelector != "" {
return emptyExpression, fmt.Errorf(`expression may have attribute selector only at the end`)
}
if s[0] != InheritanceSeparator {
return emptyExpression, fmt.Errorf(`expect "%c", got "%c"`, InheritanceSeparator, s[0])
}
s = s[1:]
if s == "" {
// Dangling separator; e.g. "cti.a.p.gr.namespace.v1.2~"
return emptyExpression, fmt.Errorf(`unexpected dangling separator "%c"`, InheritanceSeparator)
}
if p.allowAnonymousEntity && len(s) >= 36 {
if anonymousEntityUUID.UUID, err = uuid.Parse(s[:36]); err == nil {
anonymousEntityUUID.Valid = true
if s, err = parseQueryOrSelectorIfPresent(s[36:]); err != nil {
return emptyExpression, err
}
continue
}
}
}
node := &Node{}
if s[0] == '$' {
if s, err = p.parseDynamicParameterToNode(s[1:], node); err != nil {
return emptyExpression, fmt.Errorf("parse dynamic parameter: %w", err)
}
} else if s, err = p.parseChunkToNode(s, node, params); err != nil {
return emptyExpression, err
}
if !node.HasWildcard() {
if s, err = parseQueryOrSelectorIfPresent(s); err != nil {
return emptyExpression, err
}
}
if head == nil {
head = node
tail = node
continue
}
tail.Child = node
tail = node
}
return Expression{
parser: p,
Head: head,
QueryAttributes: queryAttributes,
AttributeSelector: attributeSelector,
AnonymousEntityUUID: anonymousEntityUUID,
}, nil
}
func (p *Parser) parseDynamicParameterToNode(s string, node *Node) (tail string, err error) {
if s == "" {
return s, fmt.Errorf(`expect "{", got end of string`)
}
if s[0] != '{' {
return s, fmt.Errorf(`expect "{", got "%c"`, s[0])
}
i := 1
for i < len(s) && s[i] != '}' {
i++
}
if i == len(s) {
return s, fmt.Errorf(`expect "}", got end of string`)
}
paramName := s[1:i]
for _, allowedParamName := range p.allowedDynamicParameterNames {
if paramName == allowedParamName {
node.DynamicParameterName = paramName
return s[i+1:], nil
}
}
return s, fmt.Errorf("unknown dynamic parameter %q", paramName)
}
func (p *Parser) parseChunkToNode(s string, node *Node, params parserParams) (tail string, err error) {
var val string
// Vendor
if val, s, err = p.parseVendorOrPackage(s); err != nil {
return s, fmt.Errorf("parse vendor: %w", err)
}
node.Vendor = Vendor(val)
if node.Vendor.IsWildCard() {
if params.wildcardDisabled {
return s, fmt.Errorf("parse vendor: wildcard is disabled")
}
return s, nil
}
// Package
if val, s, err = p.parseVendorOrPackage(s); err != nil {
return s, fmt.Errorf("parse package: %w", err)
}
node.Package = Package(val)
if node.Package.IsWildCard() {
if params.wildcardDisabled {
return s, fmt.Errorf("parse package: wildcard is disabled")
}
return s, nil
}
// EntityName and version
if node.EntityName, node.Version, s, err = p.parseEntityNameAndVersion(s); err != nil {
return s, fmt.Errorf("parse entity name and version: %w", err)
}
if node.EntityName.EndsWithWildcard() || node.Version.HasWildcard() {
if params.wildcardDisabled {
return s, fmt.Errorf("parse entity name and version: wildcard is disabled")
}
return s, nil
}
if !node.Version.Major.Valid && params.versionStrategy != versionStrategyAllowEmpty {
return s, fmt.Errorf("parse entity name and version: version is missing")
}
if !node.Version.Minor.Valid && params.versionStrategy == versionStrategyRequireFull {
return s, fmt.Errorf("parse entity name and version: minor part of version is missing")
}
return s, nil
}
func (p *Parser) parseVendorOrPackage(s string) (identifier string, tail string, err error) {
if s == "" {
return "", "", fmt.Errorf("cannot be empty")
}
if s[0] == Wildcard {
if len(s) > 1 && s[1] != InheritanceSeparator && s[1] != '[' && s[1] != '@' {
return "", s, fmt.Errorf(`can be "%c" or contain only lower letters, digits, and "_"`, Wildcard)
}
return string(Wildcard), s[1:], nil
}
i := 0
for ; i < len(s) && s[i] != '.'; i++ {
switch {
case checkByteIsDigit(s[i]) || s[i] == '_':
if i == 0 {
return "", s, fmt.Errorf(`can be "%c" or start only with letter`, Wildcard)
}
case s[i] >= 'a' && s[i] <= 'z':
default:
return "", s, fmt.Errorf(`can be "%c" or contain only lower letters, digits, and "_"`, Wildcard)
}
}
val := s[:i]
if val == "" {
return "", s, fmt.Errorf("cannot be empty")
}
if i < len(s) && s[i] == '.' {
i++
}
return val, s[i:], nil
}
//nolint:funlen,gocyclo // func implements an alg with well-defined concrete purpose, so high cyclomatic complexity is ok here
func (p *Parser) parseEntityNameAndVersion(s string) (name EntityName, ver Version, tail string, err error) {
if s == "" {
return "", Version{}, s, fmt.Errorf(`entity name cannot be empty`)
}
majorIdx := -1
minorIdx := -1
i := 0
loop:
for ; i < len(s) && s[i] != InheritanceSeparator && s[i] != '[' && s[i] != '@'; i++ {
switch {
case s[i] == '.':
if i == 0 {
return "", Version{}, s, fmt.Errorf(`entity name can be "%c" or start only with letter or "_"`, Wildcard)
}
if i > 0 && s[i-1] == '.' {
return "", Version{}, s, fmt.Errorf(`entity name cannot have double dots ("..")`)
}
if majorIdx != -1 && minorIdx != -1 {
majorIdx = -1
minorIdx = -1
continue loop
}
if majorIdx != -1 && i < len(s)-1 && (s[i+1] == Wildcard || checkByteIsDigit(s[i+1])) {
minorIdx = i + 1
}
case s[i] == '_':
if i > 0 && s[i-1] == '_' {
return "", Version{}, s, fmt.Errorf(`entity name cannot have double underscores ("__")`)
}
majorIdx = -1
minorIdx = -1
case s[i] >= 'a' && s[i] <= 'z':
if i > 0 && s[i-1] == '.' && s[i] == 'v' && i < len(s)-1 && (s[i+1] == Wildcard || checkByteIsDigit(s[i+1])) {
majorIdx = i + 1
minorIdx = -1
continue loop
}
majorIdx = -1
minorIdx = -1
case checkByteIsDigit(s[i]):
if i == 0 {
return "", Version{}, s, fmt.Errorf(`entity name can be "%c" or start only with letter`, Wildcard)
}
case s[i] == Wildcard:
if i > 0 {
//nolint:gocritic // if-else if more readable here than nested switch.
if minorIdx != -1 {
if minorIdx != i {
return "", Version{}, s, fmt.Errorf(`minor part of version is invalid`)
}
} else if majorIdx != -1 {
if majorIdx != i {
return "", Version{}, s, fmt.Errorf(`major part of version is invalid`)
}
} else {
if s[i-1] != '.' {
return "", Version{}, s, fmt.Errorf(
`wildcard "%c" in entity name may be only after dot (".")`, Wildcard)
}
}
}
i++
break loop
default:
return "", Version{}, s, fmt.Errorf(
`entity name can be "%c" or contain only lower letters, digits, "." and "_"`, Wildcard)
}
}
newS := s[i:]
if majorIdx == -1 {
nameStr := s[:i]
if strings.HasSuffix(nameStr, ".v") {
nameStr = strings.TrimSuffix(nameStr, ".v")
if nameStr == "" {
return "", Version{}, s, fmt.Errorf(`entity name cannot be empty`)
}
return EntityName(nameStr), Version{}, newS, nil
}
entityName := EntityName(nameStr)
if !entityName.EndsWithWildcard() {
return "", Version{}, s, fmt.Errorf("version is missing")
}
return entityName, Version{}, newS, nil
}
nameStr := s[:majorIdx-2]
if nameStr == "" {
return "", Version{}, s, fmt.Errorf(`entity name cannot be empty`)
}
entityName := EntityName(nameStr)
// Parse and validate major version part.
ver, err = p.parseVersion(s, majorIdx, minorIdx, i)
if err != nil {
return "", Version{}, s, err
}
return entityName, ver, newS, err
}
func (p *Parser) parseVersion(s string, majorIdx int, minorIdx int, pos int) (Version, error) {
if s[majorIdx] == Wildcard {
return Version{HasMajorWildcard: true}, nil
}
var minorIsAbsent bool
if minorIdx == -1 {
minorIsAbsent = true
minorIdx = pos + 1
}
parseVersionPart := func(s, partName string) (int, error) {
if s != "" && s[0] == '0' && s != "0" {
return 0, fmt.Errorf("%s part of version cannot contain leading zero", partName)
}
ver, err := strconv.Atoi(s)
if err != nil {
return 0, fmt.Errorf("parse %s part of version: %w", partName, err)
}
if ver < 0 {
return 0, fmt.Errorf("%s part of version should be >= 0", partName)
}
return ver, nil
}
majorVerStr := s[majorIdx : minorIdx-1]
majorVer, err := parseVersionPart(majorVerStr, "major")
if err != nil {
return Version{}, err
}
if minorIsAbsent {
return NewPartialVersion(uint(majorVer)), nil
}
var minorVer int
// Parse and validate minor version part
if s[minorIdx] == Wildcard {
return Version{Major: NullVersion{uint(majorVer), true}, HasMinorWildcard: true}, nil
}
minorVerStr := s[minorIdx:pos]
minorVer, err = parseVersionPart(minorVerStr, "minor")
if err != nil {
return Version{}, err
}
if majorVer == 0 && minorVer == 0 {
return Version{}, fmt.Errorf("version must be higher than 0.0")
}
return NewVersion(uint(majorVer), uint(minorVer)), nil
}
func (p *Parser) parseAttributeSelectorIfPresent(s string) (AttributeName, string, error) {
if s == "" || s[0] != '@' {
return "", s, nil
}
return p.parseAttributeName(s[1:])
}
func (p *Parser) parseQueryAttributesIfPresent(s string) ([]QueryAttribute, string, error) {
if s == "" || s[0] != '[' {
return nil, s, nil
}
ss := s[1:]
var res []QueryAttribute
var queryAttr QueryAttribute
var err error
for {
ss = trimLeftSpaces(ss)
if ss == "" {
return nil, s, fmt.Errorf("unexpected end of string")
}
if ss[0] == ']' {
ss = ss[1:]
break
}
if len(res) != 0 {
if ss[0] != ',' {
return nil, s, fmt.Errorf(`expect ",", got "%c"`, ss[0])
}
ss = trimLeftSpaces(ss[1:])
}
queryAttr, ss, err = p.parseQueryAttribute(ss)
if err != nil {
return nil, s, err
}
for i := range res {
if res[i].Name == queryAttr.Name {
return nil, s, fmt.Errorf("non-unique query attribute %q", queryAttr.Name)
}
}
res = append(res, queryAttr)
}
if len(res) == 0 {
return nil, s, fmt.Errorf("query attribute list is empty")
}
return res, ss, nil
}
func (p *Parser) parseQueryAttribute(s string) (QueryAttribute, string, error) {
// Parse attribute name.
attrName, ss, err := p.parseAttributeName(s)
if err != nil {
return QueryAttribute{}, s, err
}
// Parse "="
ss = trimLeftSpaces(ss)
if ss == "" {
return QueryAttribute{}, s, fmt.Errorf(`expect "=", got end of string`)
}
if ss[0] != '=' {
return QueryAttribute{}, s, fmt.Errorf(`expect "=", got "%c"`, ss[0])
}
ss = trimLeftSpaces(ss[1:])
// Parse attribute value.
attrVal, ss, err := p.parseQueryAttributeValue(ss)
if err != nil {
return QueryAttribute{}, s, err
}
exp, err := p.ParseReference(attrVal)
if err != nil {
if errors.Is(err, ErrNotExpression) {
return QueryAttribute{Name: attrName, Value: QueryAttributeValue{Raw: attrVal}}, ss, nil
}
return QueryAttribute{}, s, fmt.Errorf("parse attribute %q as CTI: %w", attrName, err)
}
return QueryAttribute{Name: attrName, Value: QueryAttributeValue{Raw: attrVal, Expression: exp}}, ss, nil
}
func (p *Parser) parseAttributeName(s string) (attrName AttributeName, newS string, err error) {
var i int
loop:
for ; i < len(s); i++ {
switch {
case (s[i] >= '0' && s[i] <= '9') || s[i] == '_':
if i == 0 || s[i-1] == '.' {
return "", s, fmt.Errorf("attribute name and its each part should start with letter")
}
case s[i] == '.':
if i == 0 {
return "", s, fmt.Errorf("attribute name should start with letter")
}
if s[i-1] == '.' {
return "", s, fmt.Errorf(`attribute name cannot have double dots ("..")`)
}
case (s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'A' && s[i] <= 'Z'):
default:
break loop
}
}
if i == 0 {
return "", s, fmt.Errorf(`attribute name cannot be empty and should contain only letters, digits, ".", and "_"`)
}
if s[i-1] == '.' {
return "", s, fmt.Errorf(`attribute name cannot end with dot (".")`)
}
return AttributeName(s[:i]), s[i:], nil
}
func (p *Parser) parseQueryAttributeValue(s string) (attrVal string, newS string, err error) {
if s == "" {
return "", s, fmt.Errorf(`expect attribute value, got end of string`)
}
fn := p.parseQueryAttributeValueNotInQuotes
if s[0] == '"' || s[0] == '\'' {
fn = p.parseQueryAttributeValueInQuotes
}
return fn(s)
}
func (p *Parser) parseQueryAttributeValueInQuotes(s string) (val string, newS string, err error) {
quote := s[0]
escapeCount := 0
i := 1 // skip quote
var hasEscapedClosingBracket bool
loop:
for ; i < len(s); i++ {
switch s[i] {
case quote:
if escapeCount%2 == 1 {
hasEscapedClosingBracket = true
escapeCount = 0
continue loop
}
break loop
case '\\':
escapeCount++
default:
escapeCount = 0
}
}
if i == len(s) {
return "", s, fmt.Errorf("unexpected end of string while parsing attribute value")
}
attrVal := s[1:i]
if attrVal == "" {
return "", s, fmt.Errorf("attribute value cannot be empty")
}
if hasEscapedClosingBracket {
attrVal = strings.ReplaceAll(attrVal, string([]byte{'\\', quote}), string([]byte{quote}))
}
return attrVal, s[i+1:], nil
}
func (p *Parser) parseQueryAttributeValueNotInQuotes(s string) (val string, newS string, err error) {
i := 0
for i < len(s) && s[i] != ',' && s[i] != ']' && s[i] != ' ' {
i++
}
if i == len(s) {
return "", s, fmt.Errorf("unexpected end of string while parsing attribute value")
}
attrVal := s[:i]
if attrVal == "" {
return "", s, fmt.Errorf("attribute value cannot be empty")
}
return attrVal, s[i:], nil
}
func trimLeftSpaces(s string) string {
i := 0
for i < len(s) && s[i] == ' ' {
i++
}
return s[i:]
}
func checkByteIsDigit(b byte) bool {
return b >= '0' && b <= '9'
}