Debian Codegraph @

parser.go

raw
1 // Package cascadia is an implementation of CSS selectors.
2 package cascadia
3
4 import (
5 "errors"
6 "fmt"
7 "regexp"
8 "strconv"
9 "strings"
10 )
11
12 // a parser for CSS selectors
13 type parser struct {
14 s string // the source text
15 i int // the current position
16 depth int // current nesting depth
17
18 // if `false`, parsing a pseudo-element
19 // returns an error.
20 acceptPseudoElements bool
21 }
22
23 // parseEscape parses a backslash escape.
24 func (p *parser) parseEscape() (result string, err error) {
25 if len(p.s) < p.i+2 || p.s[p.i] != '\\' {
26 return "", errors.New("invalid escape sequence")
27 }
28
29 start := p.i + 1
30 c := p.s[start]
31 switch {
32 case c == '\r' || c == '\n' || c == '\f':
33 return "", errors.New("escaped line ending outside string")
34 case hexDigit(c):
35 // unicode escape (hex)
36 var i int
37 for i = start; i < start+6 && i < len(p.s) && hexDigit(p.s[i]); i++ {
38 // empty
39 }
40 v, _ := strconv.ParseUint(p.s[start:i], 16, 64)
41 if len(p.s) > i {
42 switch p.s[i] {
43 case '\r':
44 i++
45 if len(p.s) > i && p.s[i] == '\n' {
46 i++
47 }
48 case ' ', '\t', '\n', '\f':
49 i++
50 }
51 }
52 p.i = i
53 return string(rune(v)), nil
54 }
55
56 // Return the literal character after the backslash.
57 result = p.s[start : start+1]
58 p.i += 2
59 return result, nil
60 }
61
62 // toLowerASCII returns s with all ASCII capital letters lowercased.
63 func toLowerASCII(s string) string {
64 var b []byte
65 for i := 0; i < len(s); i++ {
66 if c := s[i]; 'A' <= c && c <= 'Z' {
67 if b == nil {
68 b = make([]byte, len(s))
69 copy(b, s)
70 }
71 b[i] = s[i] + ('a' - 'A')
72 }
73 }
74
75 if b == nil {
76 return s
77 }
78
79 return string(b)
80 }
81
82 func hexDigit(c byte) bool {
83 return '0' <= c && c <= '9' || 'a' <= c && c <= 'f' || 'A' <= c && c <= 'F'
84 }
85
86 // nameStart returns whether c can be the first character of an identifier
87 // (not counting an initial hyphen, or an escape sequence).
88 func nameStart(c byte) bool {
89 return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_' || c > 127
90 }
91
92 // nameChar returns whether c can be a character within an identifier
93 // (not counting an escape sequence).
94 func nameChar(c byte) bool {
95 return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || c == '_' || c > 127 ||
96 c == '-' || '0' <= c && c <= '9'
97 }
98
99 // parseIdentifier parses an identifier.
100 func (p *parser) parseIdentifier() (result string, err error) {
101 const prefix = '-'
102 var numPrefix int
103
104 for len(p.s) > p.i && p.s[p.i] == prefix {
105 p.i++
106 numPrefix++
107 }
108
109 if len(p.s) <= p.i {
110 return "", errors.New("expected identifier, found EOF instead")
111 }
112
113 if c := p.s[p.i]; !(nameStart(c) || c == '\\') {
114 return "", fmt.Errorf("expected identifier, found %c instead", c)
115 }
116
117 result, err = p.parseName()
118 if numPrefix > 0 && err == nil {
119 result = strings.Repeat(string(prefix), numPrefix) + result
120 }
121 return
122 }
123
124 // parseName parses a name (which is like an identifier, but doesn't have
125 // extra restrictions on the first character).
126 func (p *parser) parseName() (result string, err error) {
127 i := p.i
128 loop:
129 for i < len(p.s) {
130 c := p.s[i]
131 switch {
132 case nameChar(c):
133 start := i
134 for i < len(p.s) && nameChar(p.s[i]) {
135 i++
136 }
137 result += p.s[start:i]
138 case c == '\\':
139 p.i = i
140 val, err := p.parseEscape()
141 if err != nil {
142 return "", err
143 }
144 i = p.i
145 result += val
146 default:
147 break loop
148 }
149 }
150
151 if result == "" {
152 return "", errors.New("expected name, found EOF instead")
153 }
154
155 p.i = i
156 return result, nil
157 }
158
159 // parseString parses a single- or double-quoted string.
160 func (p *parser) parseString() (result string, err error) {
161 i := p.i
162 if len(p.s) < i+2 {
163 return "", errors.New("expected string, found EOF instead")
164 }
165
166 quote := p.s[i]
167 i++
168
169 loop:
170 for i < len(p.s) {
171 switch p.s[i] {
172 case '\\':
173 if len(p.s) > i+1 {
174 switch c := p.s[i+1]; c {
175 case '\r':
176 if len(p.s) > i+2 && p.s[i+2] == '\n' {
177 i += 3
178 continue loop
179 }
180 fallthrough
181 case '\n', '\f':
182 i += 2
183 continue loop
184 }
185 }
186 p.i = i
187 val, err := p.parseEscape()
188 if err != nil {
189 return "", err
190 }
191 i = p.i
192 result += val
193 case quote:
194 break loop
195 case '\r', '\n', '\f':
196 return "", errors.New("unexpected end of line in string")
197 default:
198 start := i
199 for i < len(p.s) {
200 if c := p.s[i]; c == quote || c == '\\' || c == '\r' || c == '\n' || c == '\f' {
201 break
202 }
203 i++
204 }
205 result += p.s[start:i]
206 }
207 }
208
209 if i >= len(p.s) {
210 return "", errors.New("EOF in string")
211 }
212
213 // Consume the final quote.
214 i++
215
216 p.i = i
217 return result, nil
218 }
219
220 // parseRegex parses a regular expression; the end is defined by encountering an
221 // unmatched closing ')' or ']' which is not consumed
222 func (p *parser) parseRegex() (rx *regexp.Regexp, err error) {
223 i := p.i
224 if len(p.s) < i+2 {
225 return nil, errors.New("expected regular expression, found EOF instead")
226 }
227
228 // number of open parens or brackets;
229 // when it becomes negative, finished parsing regex
230 open := 0
231
232 loop:
233 for i < len(p.s) {
234 switch p.s[i] {
235 case '(', '[':
236 open++
237 case ')', ']':
238 open--
239 if open < 0 {
240 break loop
241 }
242 }
243 i++
244 }
245
246 if i >= len(p.s) {
247 return nil, errors.New("EOF in regular expression")
248 }
249 rx, err = regexp.Compile(p.s[p.i:i])
250 p.i = i
251 return rx, err
252 }
253
254 // skipWhitespace consumes whitespace characters and comments.
255 // It returns true if there was actually anything to skip.
256 func (p *parser) skipWhitespace() bool {
257 i := p.i
258 for i < len(p.s) {
259 switch p.s[i] {
260 case ' ', '\t', '\r', '\n', '\f':
261 i++
262 continue
263 case '/':
264 if strings.HasPrefix(p.s[i:], "/*") {
265 end := strings.Index(p.s[i+len("/*"):], "*/")
266 if end != -1 {
267 i += end + len("/**/")
268 continue
269 }
270 }
271 }
272 break
273 }
274
275 if i > p.i {
276 p.i = i
277 return true
278 }
279
280 return false
281 }
282
283 // consumeParenthesis consumes an opening parenthesis and any following
284 // whitespace. It returns true if there was actually a parenthesis to skip.
285 func (p *parser) consumeParenthesis() bool {
286 if p.i < len(p.s) && p.s[p.i] == '(' {
287 p.i++
288 p.skipWhitespace()
289 return true
290 }
291 return false
292 }
293
294 // consumeClosingParenthesis consumes a closing parenthesis and any preceding
295 // whitespace. It returns true if there was actually a parenthesis to skip.
296 func (p *parser) consumeClosingParenthesis() bool {
297 i := p.i
298 p.skipWhitespace()
299 if p.i < len(p.s) && p.s[p.i] == ')' {
300 p.i++
301 return true
302 }
303 p.i = i
304 return false
305 }
306
307 // parseTypeSelector parses a type selector (one that matches by tag name).
308 func (p *parser) parseTypeSelector() (result tagSelector, err error) {
309 tag, err := p.parseIdentifier()
310 if err != nil {
311 return
312 }
313 return tagSelector{tag: toLowerASCII(tag)}, nil
314 }
315
316 // parseIDSelector parses a selector that matches by id attribute.
317 func (p *parser) parseIDSelector() (idSelector, error) {
318 if p.i >= len(p.s) {
319 return idSelector{}, fmt.Errorf("expected id selector (#id), found EOF instead")
320 }
321 if p.s[p.i] != '#' {
322 return idSelector{}, fmt.Errorf("expected id selector (#id), found '%c' instead", p.s[p.i])
323 }
324
325 p.i++
326 id, err := p.parseName()
327 if err != nil {
328 return idSelector{}, err
329 }
330
331 return idSelector{id: id}, nil
332 }
333
334 // parseClassSelector parses a selector that matches by class attribute.
335 func (p *parser) parseClassSelector() (classSelector, error) {
336 if p.i >= len(p.s) {
337 return classSelector{}, fmt.Errorf("expected class selector (.class), found EOF instead")
338 }
339 if p.s[p.i] != '.' {
340 return classSelector{}, fmt.Errorf("expected class selector (.class), found '%c' instead", p.s[p.i])
341 }
342
343 p.i++
344 class, err := p.parseIdentifier()
345 if err != nil {
346 return classSelector{}, err
347 }
348
349 return classSelector{class: class}, nil
350 }
351
352 // parseAttributeSelector parses a selector that matches by attribute value.
353 func (p *parser) parseAttributeSelector() (attrSelector, error) {
354 if p.i >= len(p.s) {
355 return attrSelector{}, fmt.Errorf("expected attribute selector ([attribute]), found EOF instead")
356 }
357 if p.s[p.i] != '[' {
358 return attrSelector{}, fmt.Errorf("expected attribute selector ([attribute]), found '%c' instead", p.s[p.i])
359 }
360
361 p.i++
362 p.skipWhitespace()
363 key, err := p.parseIdentifier()
364 if err != nil {
365 return attrSelector{}, err
366 }
367 key = toLowerASCII(key)
368
369 p.skipWhitespace()
370 if p.i >= len(p.s) {
371 return attrSelector{}, errors.New("unexpected EOF in attribute selector")
372 }
373
374 if p.s[p.i] == ']' {
375 p.i++
376 return attrSelector{key: key, operation: ""}, nil
377 }
378
379 if p.i+2 >= len(p.s) {
380 return attrSelector{}, errors.New("unexpected EOF in attribute selector")
381 }
382
383 op := p.s[p.i : p.i+2]
384 if op[0] == '=' {
385 op = "="
386 } else if op[1] != '=' {
387 return attrSelector{}, fmt.Errorf(`expected equality operator, found "%s" instead`, op)
388 }
389 p.i += len(op)
390
391 p.skipWhitespace()
392 if p.i >= len(p.s) {
393 return attrSelector{}, errors.New("unexpected EOF in attribute selector")
394 }
395 var val string
396 var rx *regexp.Regexp
397 if op == "#=" {
398 rx, err = p.parseRegex()
399 } else {
400 switch p.s[p.i] {
401 case '\'', '"':
402 val, err = p.parseString()
403 default:
404 val, err = p.parseIdentifier()
405 }
406 }
407 if err != nil {
408 return attrSelector{}, err
409 }
410
411 p.skipWhitespace()
412 if p.i >= len(p.s) {
413 return attrSelector{}, errors.New("unexpected EOF in attribute selector")
414 }
415
416 // check if the attribute contains an ignore case flag
417 ignoreCase := false
418 if p.s[p.i] == 'i' || p.s[p.i] == 'I' {
419 ignoreCase = true
420 p.i++
421 }
422
423 p.skipWhitespace()
424 if p.i >= len(p.s) {
425 return attrSelector{}, errors.New("unexpected EOF in attribute selector")
426 }
427
428 if p.s[p.i] != ']' {
429 return attrSelector{}, fmt.Errorf("expected ']', found '%c' instead", p.s[p.i])
430 }
431 p.i++
432
433 switch op {
434 case "=", "!=", "~=", "|=", "^=", "$=", "*=", "#=":
435 return attrSelector{key: key, val: val, operation: op, regexp: rx, insensitive: ignoreCase}, nil
436 default:
437 return attrSelector{}, fmt.Errorf("attribute operator %q is not supported", op)
438 }
439 }
440
441 var (
442 errExpectedParenthesis = errors.New("expected '(' but didn't find it")
443 errExpectedClosingParenthesis = errors.New("expected ')' but didn't find it")
444 errUnmatchedParenthesis = errors.New("unmatched '('")
445 )
446
447 // parsePseudoclassSelector parses a pseudoclass selector like :not(p) or a pseudo-element
448 // For backwards compatibility, both ':' and '::' prefix are allowed for pseudo-elements.
449 // https://drafts.csswg.org/selectors-3/#pseudo-elements
450 // Returning a nil `Sel` (and a nil `error`) means we found a pseudo-element.
451 func (p *parser) parsePseudoclassSelector() (out Sel, pseudoElement string, err error) {
452 if p.i >= len(p.s) {
453 return nil, "", fmt.Errorf("expected pseudoclass selector (:pseudoclass), found EOF instead")
454 }
455 if p.s[p.i] != ':' {
456 return nil, "", fmt.Errorf("expected attribute selector (:pseudoclass), found '%c' instead", p.s[p.i])
457 }
458
459 p.i++
460 var mustBePseudoElement bool
461 if p.i >= len(p.s) {
462 return nil, "", fmt.Errorf("got empty pseudoclass (or pseudoelement)")
463 }
464 if p.s[p.i] == ':' { // we found a pseudo-element
465 mustBePseudoElement = true
466 p.i++
467 }
468
469 name, err := p.parseIdentifier()
470 if err != nil {
471 return
472 }
473 name = toLowerASCII(name)
474 if mustBePseudoElement && (name != "after" && name != "backdrop" && name != "before" &&
475 name != "cue" && name != "first-letter" && name != "first-line" && name != "grammar-error" &&
476 name != "marker" && name != "placeholder" && name != "selection" && name != "spelling-error") {
477 return out, "", fmt.Errorf("unknown pseudoelement :%s", name)
478 }
479
480 switch name {
481 case "not", "has", "haschild":
482 if !p.consumeParenthesis() {
483 return out, "", errExpectedParenthesis
484 }
485 sel, parseErr := p.parseSelectorGroup()
486 if parseErr != nil {
487 return out, "", parseErr
488 }
489 if !p.consumeClosingParenthesis() {
490 return out, "", errExpectedClosingParenthesis
491 }
492
493 out = relativePseudoClassSelector{name: name, match: sel}
494
495 case "contains", "containsown":
496 if !p.consumeParenthesis() {
497 return out, "", errExpectedParenthesis
498 }
499 if p.i == len(p.s) {
500 return out, "", errUnmatchedParenthesis
501 }
502 var val string
503 switch p.s[p.i] {
504 case '\'', '"':
505 val, err = p.parseString()
506 default:
507 val, err = p.parseIdentifier()
508 }
509 if err != nil {
510 return out, "", err
511 }
512 val = strings.ToLower(val)
513 p.skipWhitespace()
514 if p.i >= len(p.s) {
515 return out, "", errors.New("unexpected EOF in pseudo selector")
516 }
517 if !p.consumeClosingParenthesis() {
518 return out, "", errExpectedClosingParenthesis
519 }
520
521 out = containsPseudoClassSelector{own: name == "containsown", value: val}
522
523 case "matches", "matchesown":
524 if !p.consumeParenthesis() {
525 return out, "", errExpectedParenthesis
526 }
527 rx, err := p.parseRegex()
528 if err != nil {
529 return out, "", err
530 }
531 if p.i >= len(p.s) {
532 return out, "", errors.New("unexpected EOF in pseudo selector")
533 }
534 if !p.consumeClosingParenthesis() {
535 return out, "", errExpectedClosingParenthesis
536 }
537
538 out = regexpPseudoClassSelector{own: name == "matchesown", regexp: rx}
539
540 case "nth-child", "nth-last-child", "nth-of-type", "nth-last-of-type":
541 if !p.consumeParenthesis() {
542 return out, "", errExpectedParenthesis
543 }
544 a, b, err := p.parseNth()
545 if err != nil {
546 return out, "", err
547 }
548 if !p.consumeClosingParenthesis() {
549 return out, "", errExpectedClosingParenthesis
550 }
551 last := name == "nth-last-child" || name == "nth-last-of-type"
552 ofType := name == "nth-of-type" || name == "nth-last-of-type"
553 out = nthPseudoClassSelector{a: a, b: b, last: last, ofType: ofType}
554
555 case "first-child":
556 out = nthPseudoClassSelector{a: 0, b: 1, ofType: false, last: false}
557 case "last-child":
558 out = nthPseudoClassSelector{a: 0, b: 1, ofType: false, last: true}
559 case "first-of-type":
560 out = nthPseudoClassSelector{a: 0, b: 1, ofType: true, last: false}
561 case "last-of-type":
562 out = nthPseudoClassSelector{a: 0, b: 1, ofType: true, last: true}
563 case "only-child":
564 out = onlyChildPseudoClassSelector{ofType: false}
565 case "only-of-type":
566 out = onlyChildPseudoClassSelector{ofType: true}
567 case "input":
568 out = inputPseudoClassSelector{}
569 case "empty":
570 out = emptyElementPseudoClassSelector{}
571 case "root":
572 out = rootPseudoClassSelector{}
573 case "link":
574 out = linkPseudoClassSelector{}
575 case "lang":
576 if !p.consumeParenthesis() {
577 return out, "", errExpectedParenthesis
578 }
579 if p.i == len(p.s) {
580 return out, "", errUnmatchedParenthesis
581 }
582 val, err := p.parseIdentifier()
583 if err != nil {
584 return out, "", err
585 }
586 val = strings.ToLower(val)
587 p.skipWhitespace()
588 if p.i >= len(p.s) {
589 return out, "", errors.New("unexpected EOF in pseudo selector")
590 }
591 if !p.consumeClosingParenthesis() {
592 return out, "", errExpectedClosingParenthesis
593 }
594 out = langPseudoClassSelector{lang: val}
595 case "enabled":
596 out = enabledPseudoClassSelector{}
597 case "disabled":
598 out = disabledPseudoClassSelector{}
599 case "checked":
600 out = checkedPseudoClassSelector{}
601 case "visited", "hover", "active", "focus", "target":
602 // Not applicable in a static context: never match.
603 out = neverMatchSelector{value: ":" + name}
604 case "after", "backdrop", "before", "cue", "first-letter", "first-line", "grammar-error", "marker", "placeholder", "selection", "spelling-error":
605 return nil, name, nil
606 default:
607 return out, "", fmt.Errorf("unknown pseudoclass or pseudoelement :%s", name)
608 }
609 return
610 }
611
612 // parseInteger parses a decimal integer.
613 func (p *parser) parseInteger() (int, error) {
614 i := p.i
615 start := i
616 for i < len(p.s) && '0' <= p.s[i] && p.s[i] <= '9' {
617 i++
618 }
619 if i == start {
620 return 0, errors.New("expected integer, but didn't find it")
621 }
622 p.i = i
623
624 val, err := strconv.Atoi(p.s[start:i])
625 if err != nil {
626 return 0, err
627 }
628
629 return val, nil
630 }
631
632 // parseNth parses the argument for :nth-child (normally of the form an+b).
633 func (p *parser) parseNth() (a, b int, err error) {
634 // initial state
635 if p.i >= len(p.s) {
636 goto eof
637 }
638 switch p.s[p.i] {
639 case '-':
640 p.i++
641 goto negativeA
642 case '+':
643 p.i++
644 goto positiveA
645 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
646 goto positiveA
647 case 'n', 'N':
648 a = 1
649 p.i++
650 goto readN
651 case 'o', 'O', 'e', 'E':
652 id, nameErr := p.parseName()
653 if nameErr != nil {
654 return 0, 0, nameErr
655 }
656 id = toLowerASCII(id)
657 if id == "odd" {
658 return 2, 1, nil
659 }
660 if id == "even" {
661 return 2, 0, nil
662 }
663 return 0, 0, fmt.Errorf("expected 'odd' or 'even', but found '%s' instead", id)
664 default:
665 goto invalid
666 }
667
668 positiveA:
669 if p.i >= len(p.s) {
670 goto eof
671 }
672 switch p.s[p.i] {
673 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
674 a, err = p.parseInteger()
675 if err != nil {
676 return 0, 0, err
677 }
678 goto readA
679 case 'n', 'N':
680 a = 1
681 p.i++
682 goto readN
683 default:
684 goto invalid
685 }
686
687 negativeA:
688 if p.i >= len(p.s) {
689 goto eof
690 }
691 switch p.s[p.i] {
692 case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
693 a, err = p.parseInteger()
694 if err != nil {
695 return 0, 0, err
696 }
697 a = -a
698 goto readA
699 case 'n', 'N':
700 a = -1
701 p.i++
702 goto readN
703 default:
704 goto invalid
705 }
706
707 readA:
708 if p.i >= len(p.s) {
709 goto eof
710 }
711 switch p.s[p.i] {
712 case 'n', 'N':
713 p.i++
714 goto readN
715 default:
716 // The number we read as a is actually b.
717 return 0, a, nil
718 }
719
720 readN:
721 p.skipWhitespace()
722 if p.i >= len(p.s) {
723 goto eof
724 }
725 switch p.s[p.i] {
726 case '+':
727 p.i++
728 p.skipWhitespace()
729 b, err = p.parseInteger()
730 if err != nil {
731 return 0, 0, err
732 }
733 return a, b, nil
734 case '-':
735 p.i++
736 p.skipWhitespace()
737 b, err = p.parseInteger()
738 if err != nil {
739 return 0, 0, err
740 }
741 return a, -b, nil
742 default:
743 return a, 0, nil
744 }
745
746 eof:
747 return 0, 0, errors.New("unexpected EOF while attempting to parse expression of form an+b")
748
749 invalid:
750 return 0, 0, errors.New("unexpected character while attempting to parse expression of form an+b")
751 }
752
753 // parseSimpleSelectorSequence parses a selector sequence that applies to
754 // a single element.
755 func (p *parser) parseSimpleSelectorSequence() (Sel, error) {
756 var selectors []Sel
757
758 if p.i >= len(p.s) {
759 return nil, errors.New("expected selector, found EOF instead")
760 }
761
762 switch p.s[p.i] {
763 case '*':
764 // It's the universal selector. Just skip over it, since it doesn't affect the meaning.
765 p.i++
766 if p.i+2 < len(p.s) && p.s[p.i:p.i+2] == "|*" { // other version of universal selector
767 p.i += 2
768 }
769 case '#', '.', '[', ':':
770 // There's no type selector. Wait to process the other till the main loop.
771 default:
772 r, err := p.parseTypeSelector()
773 if err != nil {
774 return nil, err
775 }
776 selectors = append(selectors, r)
777 }
778
779 var pseudoElement string
780 loop:
781 for p.i < len(p.s) {
782 var (
783 ns Sel
784 newPseudoElement string
785 err error
786 )
787 switch p.s[p.i] {
788 case '#':
789 ns, err = p.parseIDSelector()
790 case '.':
791 ns, err = p.parseClassSelector()
792 case '[':
793 ns, err = p.parseAttributeSelector()
794 case ':':
795 ns, newPseudoElement, err = p.parsePseudoclassSelector()
796 default:
797 break loop
798 }
799 if err != nil {
800 return nil, err
801 }
802 // From https://drafts.csswg.org/selectors-3/#pseudo-elements :
803 // "Only one pseudo-element may appear per selector, and if present
804 // it must appear after the sequence of simple selectors that
805 // represents the subjects of the selector.""
806 if ns == nil { // we found a pseudo-element
807 if pseudoElement != "" {
808 return nil, fmt.Errorf("only one pseudo-element is accepted per selector, got %s and %s", pseudoElement, newPseudoElement)
809 }
810 if !p.acceptPseudoElements {
811 return nil, fmt.Errorf("pseudo-element %s found, but pseudo-elements support is disabled", newPseudoElement)
812 }
813 pseudoElement = newPseudoElement
814 } else {
815 if pseudoElement != "" {
816 return nil, fmt.Errorf("pseudo-element %s must be at the end of selector", pseudoElement)
817 }
818 selectors = append(selectors, ns)
819 }
820
821 }
822 if len(selectors) == 1 && pseudoElement == "" { // no need wrap the selectors in compoundSelector
823 return selectors[0], nil
824 }
825 return compoundSelector{selectors: selectors, pseudoElement: pseudoElement}, nil
826 }
827
828 // parseSelector parses a selector that may include combinators.
829 func (p *parser) parseSelector() (Sel, error) {
830 p.skipWhitespace()
831 result, err := p.parseSimpleSelectorSequence()
832 if err != nil {
833 return nil, err
834 }
835
836 for {
837 var (
838 combinator byte
839 c Sel
840 )
841 if p.skipWhitespace() {
842 combinator = ' '
843 }
844 if p.i >= len(p.s) {
845 return result, nil
846 }
847
848 switch p.s[p.i] {
849 case '+', '>', '~':
850 combinator = p.s[p.i]
851 p.i++
852 p.skipWhitespace()
853 case ',', ')':
854 // These characters can't begin a selector, but they can legally occur after one.
855 return result, nil
856 }
857
858 if combinator == 0 {
859 return result, nil
860 }
861
862 c, err = p.parseSimpleSelectorSequence()
863 if err != nil {
864 return nil, err
865 }
866 result = combinedSelector{first: result, combinator: combinator, second: c}
867 }
868 }
869
870 const maxParseDepth = 1000
871
872 // parseSelectorGroup parses a group of selectors, separated by commas.
873 func (p *parser) parseSelectorGroup() (SelectorGroup, error) {
874 if p.depth > maxParseDepth {
875 return nil, fmt.Errorf("selector nesting too deep (max %d)", maxParseDepth)
876 }
877 p.depth++
878 defer func() { p.depth-- }()
879
880 current, err := p.parseSelector()
881 if err != nil {
882 return nil, err
883 }
884 result := SelectorGroup{current}
885
886 for p.i < len(p.s) {
887 if p.s[p.i] != ',' {
888 break
889 }
890 p.i++
891 c, err := p.parseSelector()
892 if err != nil {
893 return nil, err
894 }
895 result = append(result, c)
896 }
897 return result, nil
898 }