/
css_parser.go
1718 lines (1506 loc) · 50.6 KB
/
css_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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package css_parser
import (
"fmt"
"strings"
"github.com/evanw/esbuild/internal/ast"
"github.com/evanw/esbuild/internal/compat"
"github.com/evanw/esbuild/internal/css_ast"
"github.com/evanw/esbuild/internal/css_lexer"
"github.com/evanw/esbuild/internal/logger"
)
// This is mostly a normal CSS parser with one exception: the addition of
// support for parsing https://drafts.csswg.org/css-nesting-1/.
type parser struct {
log logger.Log
source logger.Source
tokens []css_lexer.Token
legalComments []css_lexer.Comment
stack []css_lexer.T
importRecords []ast.ImportRecord
tracker logger.LineColumnTracker
index int
end int
legalCommentIndex int
prevError logger.Loc
options Options
}
type Options struct {
OriginalTargetEnv string
UnsupportedCSSFeatures compat.CSSFeature
MinifySyntax bool
MinifyWhitespace bool
}
func Parse(log logger.Log, source logger.Source, options Options) css_ast.AST {
result := css_lexer.Tokenize(log, source)
p := parser{
log: log,
source: source,
tracker: logger.MakeLineColumnTracker(&source),
options: options,
tokens: result.Tokens,
legalComments: result.LegalComments,
prevError: logger.Loc{Start: -1},
}
p.end = len(p.tokens)
rules := p.parseListOfRules(ruleContext{
isTopLevel: true,
parseSelectors: true,
})
p.expect(css_lexer.TEndOfFile)
return css_ast.AST{
Rules: rules,
ImportRecords: p.importRecords,
ApproximateLineCount: result.ApproximateLineCount,
SourceMapComment: result.SourceMapComment,
}
}
func (p *parser) advance() {
if p.index < p.end {
p.index++
}
}
func (p *parser) at(index int) css_lexer.Token {
if index < p.end {
return p.tokens[index]
}
if p.end < len(p.tokens) {
return css_lexer.Token{
Kind: css_lexer.TEndOfFile,
Range: logger.Range{Loc: p.tokens[p.end].Range.Loc},
}
}
return css_lexer.Token{
Kind: css_lexer.TEndOfFile,
Range: logger.Range{Loc: logger.Loc{Start: int32(len(p.source.Contents))}},
}
}
func (p *parser) current() css_lexer.Token {
return p.at(p.index)
}
func (p *parser) next() css_lexer.Token {
return p.at(p.index + 1)
}
func (p *parser) raw() string {
t := p.current()
return p.source.Contents[t.Range.Loc.Start:t.Range.End()]
}
func (p *parser) decoded() string {
return p.current().DecodedText(p.source.Contents)
}
func (p *parser) peek(kind css_lexer.T) bool {
return kind == p.current().Kind
}
func (p *parser) eat(kind css_lexer.T) bool {
if p.peek(kind) {
p.advance()
return true
}
return false
}
func (p *parser) expect(kind css_lexer.T) bool {
return p.expectWithMatchingLoc(kind, logger.Loc{Start: -1})
}
func (p *parser) expectWithMatchingLoc(kind css_lexer.T, matchingLoc logger.Loc) bool {
if p.eat(kind) {
return true
}
t := p.current()
if (t.Flags & css_lexer.DidWarnAboutSingleLineComment) != 0 {
return false
}
var text string
var suggestion string
var notes []logger.MsgData
expected := kind.String()
if strings.HasPrefix(expected, "\"") && strings.HasSuffix(expected, "\"") {
suggestion = expected[1 : len(expected)-1]
}
if (kind == css_lexer.TSemicolon || kind == css_lexer.TColon) && p.index > 0 && p.at(p.index-1).Kind == css_lexer.TWhitespace {
// Have a nice error message for forgetting a trailing semicolon or colon
text = fmt.Sprintf("Expected %s", expected)
t = p.at(p.index - 1)
} else if (kind == css_lexer.TCloseBrace || kind == css_lexer.TCloseBracket || kind == css_lexer.TCloseParen) && matchingLoc.Start != -1 {
// Have a nice error message for forgetting a closing brace/bracket/parenthesis
c := p.source.Contents[matchingLoc.Start : matchingLoc.Start+1]
text = fmt.Sprintf("Expected %s to go with %q", expected, c)
notes = append(notes, p.tracker.MsgData(logger.Range{Loc: matchingLoc, Len: 1}, fmt.Sprintf("The unbalanced %q is here:", c)))
} else {
switch t.Kind {
case css_lexer.TEndOfFile, css_lexer.TWhitespace:
text = fmt.Sprintf("Expected %s but found %s", expected, t.Kind.String())
t.Range.Len = 0
case css_lexer.TBadURL, css_lexer.TBadString:
text = fmt.Sprintf("Expected %s but found %s", expected, t.Kind.String())
default:
text = fmt.Sprintf("Expected %s but found %q", expected, p.raw())
}
}
if t.Range.Loc.Start > p.prevError.Start {
data := p.tracker.MsgData(t.Range, text)
data.Location.Suggestion = suggestion
p.log.AddMsgID(logger.MsgID_CSS_CSSSyntaxError, logger.Msg{Kind: logger.Warning, Data: data, Notes: notes})
p.prevError = t.Range.Loc
}
return false
}
func (p *parser) unexpected() {
if t := p.current(); t.Range.Loc.Start > p.prevError.Start && (t.Flags&css_lexer.DidWarnAboutSingleLineComment) == 0 {
var text string
switch t.Kind {
case css_lexer.TEndOfFile, css_lexer.TWhitespace:
text = fmt.Sprintf("Unexpected %s", t.Kind.String())
t.Range.Len = 0
case css_lexer.TBadURL, css_lexer.TBadString:
text = fmt.Sprintf("Unexpected %s", t.Kind.String())
default:
text = fmt.Sprintf("Unexpected %q", p.raw())
}
p.log.AddID(logger.MsgID_CSS_CSSSyntaxError, logger.Warning, &p.tracker, t.Range, text)
p.prevError = t.Range.Loc
}
}
type ruleContext struct {
isTopLevel bool
parseSelectors bool
}
func (p *parser) parseListOfRules(context ruleContext) []css_ast.Rule {
atRuleContext := atRuleContext{}
if context.isTopLevel {
atRuleContext.charsetValidity = atRuleValid
atRuleContext.importValidity = atRuleValid
atRuleContext.isTopLevel = true
}
rules := []css_ast.Rule{}
didFindAtImport := false
loop:
for {
// If there are any legal comments immediately before the current token,
// turn them all into comment rules and append them to the current rule list
for p.legalCommentIndex < len(p.legalComments) {
comment := p.legalComments[p.legalCommentIndex]
if comment.TokenIndexAfter > uint32(p.index) {
break
}
if comment.TokenIndexAfter == uint32(p.index) {
rules = append(rules, css_ast.Rule{Loc: comment.Loc, Data: &css_ast.RComment{Text: comment.Text}})
}
p.legalCommentIndex++
}
switch p.current().Kind {
case css_lexer.TEndOfFile:
break loop
case css_lexer.TCloseBrace:
if !context.isTopLevel {
break loop
}
case css_lexer.TWhitespace:
p.advance()
continue
case css_lexer.TAtKeyword:
rule := p.parseAtRule(atRuleContext)
// Disallow "@charset" and "@import" after other rules
if context.isTopLevel {
switch r := rule.Data.(type) {
case *css_ast.RAtCharset:
// This doesn't invalidate anything because it always comes first
case *css_ast.RAtImport:
didFindAtImport = true
if atRuleContext.charsetValidity == atRuleValid {
atRuleContext.afterLoc = rule.Loc
atRuleContext.charsetValidity = atRuleInvalidAfter
}
case *css_ast.RAtLayer:
if atRuleContext.charsetValidity == atRuleValid {
atRuleContext.afterLoc = rule.Loc
atRuleContext.charsetValidity = atRuleInvalidAfter
}
// From the specification: "Note: No @layer rules are allowed between
// @import and @namespace rules. Any @layer rule that comes after an
// @import or @namespace rule will cause any subsequent @import or
// @namespace rules to be ignored."
if atRuleContext.importValidity == atRuleValid && (r.Rules != nil || didFindAtImport) {
atRuleContext.afterLoc = rule.Loc
atRuleContext.charsetValidity = atRuleInvalidAfter
atRuleContext.importValidity = atRuleInvalidAfter
}
default:
if atRuleContext.importValidity == atRuleValid {
atRuleContext.afterLoc = rule.Loc
atRuleContext.charsetValidity = atRuleInvalidAfter
atRuleContext.importValidity = atRuleInvalidAfter
}
}
}
rules = append(rules, rule)
continue
case css_lexer.TCDO, css_lexer.TCDC:
if context.isTopLevel {
p.advance()
continue
}
}
if atRuleContext.importValidity == atRuleValid {
atRuleContext.afterLoc = p.current().Range.Loc
atRuleContext.charsetValidity = atRuleInvalidAfter
atRuleContext.importValidity = atRuleInvalidAfter
}
if context.parseSelectors {
rules = append(rules, p.parseSelectorRuleFrom(p.index, parseSelectorOpts{isTopLevel: context.isTopLevel}))
} else {
rules = append(rules, p.parseQualifiedRuleFrom(p.index, parseQualifiedRuleOpts{isTopLevel: context.isTopLevel}))
}
}
if p.options.MinifySyntax {
rules = mangleRules(rules, context.isTopLevel)
}
return rules
}
func (p *parser) parseListOfDeclarations() (list []css_ast.Rule) {
list = []css_ast.Rule{}
for {
switch p.current().Kind {
case css_lexer.TWhitespace, css_lexer.TSemicolon:
p.advance()
case css_lexer.TEndOfFile, css_lexer.TCloseBrace:
list = p.processDeclarations(list)
if p.options.MinifySyntax {
list = mangleRules(list, false /* isTopLevel */)
}
return
case css_lexer.TAtKeyword:
list = append(list, p.parseAtRule(atRuleContext{
isDeclarationList: true,
allowNesting: true,
}))
case css_lexer.TDelimAmpersand:
// Reference: https://drafts.csswg.org/css-nesting-1/
list = append(list, p.parseSelectorRuleFrom(p.index, parseSelectorOpts{allowNesting: true}))
default:
list = append(list, p.parseDeclaration())
}
}
}
func mangleRules(rules []css_ast.Rule, isTopLevel bool) []css_ast.Rule {
type hashEntry struct {
indices []uint32
}
// Remove empty rules
var prevNonComment css_ast.R
n := 0
for _, rule := range rules {
nextNonComment := rule.Data
switch r := rule.Data.(type) {
case *css_ast.RAtKeyframes:
// Do not remove empty "@keyframe foo {}" rules. Even empty rules still
// dispatch JavaScript animation events, so removing them changes
// behavior: https://bugzilla.mozilla.org/show_bug.cgi?id=1004377.
case *css_ast.RAtLayer:
if len(r.Rules) == 0 && len(r.Names) > 0 {
// Do not remove empty "@layer foo {}" rules. The specification says:
// "Cascade layers are sorted by the order in which they first are
// declared, with nested layers grouped within their parent layers
// before any unlayered rules." So removing empty rules could change
// the order in which they are first declared, and is therefore invalid.
//
// We can turn "@layer foo {}" into "@layer foo;" to be shorter. But
// don't collapse anonymous "@layer {}" into "@layer;" because that is
// a syntax error.
r.Rules = nil
} else if len(r.Rules) == 1 && len(r.Names) == 1 {
// Only collapse layers if each layer has exactly one name
if r2, ok := r.Rules[0].Data.(*css_ast.RAtLayer); ok && len(r2.Names) == 1 {
// "@layer a { @layer b {} }" => "@layer a.b;"
// "@layer a { @layer b { c {} } }" => "@layer a.b { c {} }"
r.Names[0] = append(r.Names[0], r2.Names[0]...)
r.Rules = r2.Rules
}
}
case *css_ast.RKnownAt:
if len(r.Rules) == 0 {
continue
}
case *css_ast.RSelector:
if len(r.Rules) == 0 {
continue
}
// Merge adjacent selectors with the same content
// "a { color: red; } b { color: red; }" => "a, b { color: red; }"
if prevNonComment != nil {
if r, ok := rule.Data.(*css_ast.RSelector); ok {
if prev, ok := prevNonComment.(*css_ast.RSelector); ok && css_ast.RulesEqual(r.Rules, prev.Rules) &&
isSafeSelectors(r.Selectors) && isSafeSelectors(prev.Selectors) {
nextSelector:
for _, sel := range r.Selectors {
for _, prevSel := range prev.Selectors {
if sel.Equal(prevSel) {
// Don't add duplicate selectors more than once
continue nextSelector
}
}
prev.Selectors = append(prev.Selectors, sel)
}
continue
}
}
}
case *css_ast.RComment:
nextNonComment = nil
}
if nextNonComment != nil {
prevNonComment = nextNonComment
}
rules[n] = rule
n++
}
rules = rules[:n]
// Mangle non-top-level rules using a back-to-front pass. Top-level rules
// will be mangled by the linker instead for cross-file rule mangling.
if !isTopLevel {
rules = MakeDuplicateRuleMangler().RemoveDuplicateRulesInPlace(rules)
}
return rules
}
type hashEntry struct {
rules []css_ast.R
}
type DuplicateRuleRemover struct {
entries map[uint32]hashEntry
}
func MakeDuplicateRuleMangler() DuplicateRuleRemover {
return DuplicateRuleRemover{entries: make(map[uint32]hashEntry)}
}
func (remover DuplicateRuleRemover) RemoveDuplicateRulesInPlace(rules []css_ast.Rule) []css_ast.Rule {
// Remove duplicate rules, scanning from the back so we keep the last
// duplicate. Note that the linker calls this, so we do not want to do
// anything that modifies the rules themselves. One reason is that ASTs
// are immutable at the linking stage. Another reason is that merging
// CSS ASTs from separate files will mess up source maps because a single
// AST cannot simultaneously represent offsets from multiple files.
n := len(rules)
start := n
skipRule:
for i := n - 1; i >= 0; i-- {
rule := rules[i]
// For duplicate rules, omit all but the last copy
if hash, ok := rule.Data.Hash(); ok {
entry := remover.entries[hash]
for _, data := range entry.rules {
if rule.Data.Equal(data) {
continue skipRule
}
}
entry.rules = append(entry.rules, rule.Data)
remover.entries[hash] = entry
}
start--
rules[start] = rule
}
return rules[start:]
}
// Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element
var nonDeprecatedElementsSupportedByIE7 = map[string]bool{
"a": true,
"abbr": true,
"address": true,
"area": true,
"b": true,
"base": true,
"blockquote": true,
"body": true,
"br": true,
"button": true,
"caption": true,
"cite": true,
"code": true,
"col": true,
"colgroup": true,
"dd": true,
"del": true,
"dfn": true,
"div": true,
"dl": true,
"dt": true,
"em": true,
"embed": true,
"fieldset": true,
"form": true,
"h1": true,
"h2": true,
"h3": true,
"h4": true,
"h5": true,
"h6": true,
"head": true,
"hr": true,
"html": true,
"i": true,
"iframe": true,
"img": true,
"input": true,
"ins": true,
"kbd": true,
"label": true,
"legend": true,
"li": true,
"link": true,
"map": true,
"menu": true,
"meta": true,
"noscript": true,
"object": true,
"ol": true,
"optgroup": true,
"option": true,
"p": true,
"param": true,
"pre": true,
"q": true,
"ruby": true,
"s": true,
"samp": true,
"script": true,
"select": true,
"small": true,
"span": true,
"strong": true,
"style": true,
"sub": true,
"sup": true,
"table": true,
"tbody": true,
"td": true,
"textarea": true,
"tfoot": true,
"th": true,
"thead": true,
"title": true,
"tr": true,
"u": true,
"ul": true,
"var": true,
}
// This only returns true if all of these selectors are considered "safe" which
// means that they are very likely to work in any browser a user might reasonably
// be using. We do NOT want to merge adjacent qualified rules with the same body
// if any of the selectors are unsafe, since then browsers which don't support
// that particular feature would ignore the entire merged qualified rule:
//
// Input:
// a { color: red }
// b { color: red }
// input::-moz-placeholder { color: red }
//
// Valid output:
// a, b { color: red }
// input::-moz-placeholder { color: red }
//
// Invalid output:
// a, b, input::-moz-placeholder { color: red }
//
// This considers IE 7 and above to be a browser that a user could possibly use.
// Versions of IE less than 6 are not considered.
func isSafeSelectors(complexSelectors []css_ast.ComplexSelector) bool {
for _, complex := range complexSelectors {
for _, compound := range complex.Selectors {
if compound.NestingSelector != css_ast.NestingSelectorNone {
// Bail because this is an extension: https://drafts.csswg.org/css-nesting-1/
return false
}
if compound.Combinator != "" {
// "Before Internet Explorer 10, the combinator only works in standards mode"
// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors
return false
}
if compound.TypeSelector != nil {
if compound.TypeSelector.NamespacePrefix != nil {
// Bail if we hit a namespace, which doesn't work in IE before version 9
// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Type_selectors
return false
}
if compound.TypeSelector.Name.Kind == css_lexer.TIdent && !nonDeprecatedElementsSupportedByIE7[compound.TypeSelector.Name.Text] {
// Bail if this element is either deprecated or not supported in IE 7
return false
}
}
for _, ss := range compound.SubclassSelectors {
switch s := ss.(type) {
case *css_ast.SSAttribute:
if s.MatcherModifier != 0 {
// Bail if we hit a case modifier, which doesn't work in IE at all
// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
return false
}
case *css_ast.SSPseudoClass:
// Bail if this pseudo class doesn't match a hard-coded list that's
// known to work everywhere. For example, ":focus" doesn't work in IE 7.
// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
if s.Args == nil && !s.IsElement {
switch s.Name {
case "active", "first-child", "hover", "link", "visited":
continue
}
}
return false
}
}
}
}
return true
}
func (p *parser) parseURLOrString() (string, logger.Range, bool) {
t := p.current()
switch t.Kind {
case css_lexer.TString:
text := p.decoded()
p.advance()
return text, t.Range, true
case css_lexer.TURL:
text := p.decoded()
p.advance()
return text, t.Range, true
case css_lexer.TFunction:
if p.decoded() == "url" {
matchingLoc := logger.Loc{Start: p.current().Range.End() - 1}
p.advance()
t = p.current()
text := p.decoded()
if p.expect(css_lexer.TString) && p.expectWithMatchingLoc(css_lexer.TCloseParen, matchingLoc) {
return text, t.Range, true
}
}
}
return "", logger.Range{}, false
}
func (p *parser) expectURLOrString() (url string, r logger.Range, ok bool) {
url, r, ok = p.parseURLOrString()
if !ok {
p.expect(css_lexer.TURL)
}
return
}
type atRuleKind uint8
const (
atRuleUnknown atRuleKind = iota
atRuleDeclarations
atRuleInheritContext
atRuleQualifiedOrEmpty
atRuleEmpty
)
var specialAtRules = map[string]atRuleKind{
"font-face": atRuleDeclarations,
"page": atRuleDeclarations,
// These go inside "@page": https://www.w3.org/TR/css-page-3/#syntax-page-selector
"bottom-center": atRuleDeclarations,
"bottom-left-corner": atRuleDeclarations,
"bottom-left": atRuleDeclarations,
"bottom-right-corner": atRuleDeclarations,
"bottom-right": atRuleDeclarations,
"left-bottom": atRuleDeclarations,
"left-middle": atRuleDeclarations,
"left-top": atRuleDeclarations,
"right-bottom": atRuleDeclarations,
"right-middle": atRuleDeclarations,
"right-top": atRuleDeclarations,
"top-center": atRuleDeclarations,
"top-left-corner": atRuleDeclarations,
"top-left": atRuleDeclarations,
"top-right-corner": atRuleDeclarations,
"top-right": atRuleDeclarations,
// These properties are very deprecated and appear to only be useful for
// mobile versions of internet explorer (which may no longer exist?), but
// they are used by the https://ant.design/ design system so we recognize
// them to avoid the warning.
//
// Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/@viewport
// Discussion: https://github.com/w3c/csswg-drafts/issues/4766
//
"viewport": atRuleDeclarations,
"-ms-viewport": atRuleDeclarations,
// This feature has been removed from the web because it's actively harmful.
// However, there is one exception where "@-moz-document url-prefix() {" is
// accepted by Firefox to basically be an "if Firefox" conditional rule.
//
// Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/@document
// Discussion: https://bugzilla.mozilla.org/show_bug.cgi?id=1035091
//
"document": atRuleInheritContext,
"-moz-document": atRuleInheritContext,
// This is a new feature that changes how the CSS rule cascade works. It can
// end in either a "{}" block or a ";" rule terminator so we need this special
// case to support both.
//
// Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
// Motivation: https://developer.chrome.com/blog/cascade-layers/
//
"layer": atRuleQualifiedOrEmpty,
"media": atRuleInheritContext,
"scope": atRuleInheritContext,
"supports": atRuleInheritContext,
// Reference: https://drafts.csswg.org/css-nesting-1/
"nest": atRuleDeclarations,
// Reference: https://drafts.csswg.org/css-fonts-4/#font-palette-values
"font-palette-values": atRuleDeclarations,
// Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/@counter-style
// Reference: https://drafts.csswg.org/css-counter-styles/#the-counter-style-rule
"counter-style": atRuleDeclarations,
// Documentation: https://developer.mozilla.org/en-US/docs/Web/CSS/@font-feature-values
// Reference: https://drafts.csswg.org/css-fonts/#font-feature-values
"font-feature-values": atRuleDeclarations,
"annotation": atRuleDeclarations,
"character-variant": atRuleDeclarations,
"historical-forms": atRuleDeclarations,
"ornaments": atRuleDeclarations,
"styleset": atRuleDeclarations,
"stylistic": atRuleDeclarations,
"swash": atRuleDeclarations,
// Container Queries
// Reference: https://drafts.csswg.org/css-contain-3/#container-rule
"container": atRuleInheritContext,
}
type atRuleValidity uint8
const (
atRuleInvalid atRuleValidity = iota
atRuleValid
atRuleInvalidAfter
)
type atRuleContext struct {
afterLoc logger.Loc
charsetValidity atRuleValidity
importValidity atRuleValidity
isDeclarationList bool
allowNesting bool
isTopLevel bool
}
func (p *parser) parseAtRule(context atRuleContext) css_ast.Rule {
// Parse the name
atToken := p.decoded()
atRange := p.current().Range
kind := specialAtRules[atToken]
p.advance()
// Parse the prelude
preludeStart := p.index
abortRuleParser:
switch atToken {
case "charset":
switch context.charsetValidity {
case atRuleInvalid:
p.log.AddID(logger.MsgID_CSS_InvalidAtCharset, logger.Warning, &p.tracker, atRange, "\"@charset\" must be the first rule in the file")
case atRuleInvalidAfter:
p.log.AddIDWithNotes(logger.MsgID_CSS_InvalidAtCharset, logger.Warning, &p.tracker, atRange,
"\"@charset\" must be the first rule in the file",
[]logger.MsgData{p.tracker.MsgData(logger.Range{Loc: context.afterLoc},
"This rule cannot come before a \"@charset\" rule")})
case atRuleValid:
kind = atRuleEmpty
p.expect(css_lexer.TWhitespace)
if p.peek(css_lexer.TString) {
encoding := p.decoded()
if !strings.EqualFold(encoding, "UTF-8") {
p.log.AddID(logger.MsgID_CSS_UnsupportedAtCharset, logger.Warning, &p.tracker, p.current().Range,
fmt.Sprintf("\"UTF-8\" will be used instead of unsupported charset %q", encoding))
}
p.advance()
p.expect(css_lexer.TSemicolon)
return css_ast.Rule{Loc: atRange.Loc, Data: &css_ast.RAtCharset{Encoding: encoding}}
}
p.expect(css_lexer.TString)
}
case "import":
switch context.importValidity {
case atRuleInvalid:
p.log.AddID(logger.MsgID_CSS_InvalidAtImport, logger.Warning, &p.tracker, atRange, "\"@import\" is only valid at the top level")
case atRuleInvalidAfter:
p.log.AddIDWithNotes(logger.MsgID_CSS_InvalidAtImport, logger.Warning, &p.tracker, atRange,
"All \"@import\" rules must come first",
[]logger.MsgData{p.tracker.MsgData(logger.Range{Loc: context.afterLoc},
"This rule cannot come before an \"@import\" rule")})
case atRuleValid:
kind = atRuleEmpty
p.eat(css_lexer.TWhitespace)
if path, r, ok := p.expectURLOrString(); ok {
importConditionsStart := p.index
for {
if kind := p.current().Kind; kind == css_lexer.TSemicolon || kind == css_lexer.TOpenBrace ||
kind == css_lexer.TCloseBrace || kind == css_lexer.TEndOfFile {
break
}
p.parseComponentValue()
}
if p.current().Kind == css_lexer.TOpenBrace {
break // Avoid parsing an invalid "@import" rule
}
importConditions := p.convertTokens(p.tokens[importConditionsStart:p.index])
kind := ast.ImportAt
// Insert or remove whitespace before the first token
if len(importConditions) > 0 {
kind = ast.ImportAtConditional
if p.options.MinifyWhitespace {
importConditions[0].Whitespace &= ^css_ast.WhitespaceBefore
} else {
importConditions[0].Whitespace |= css_ast.WhitespaceBefore
}
}
p.expect(css_lexer.TSemicolon)
importRecordIndex := uint32(len(p.importRecords))
p.importRecords = append(p.importRecords, ast.ImportRecord{
Kind: kind,
Path: logger.Path{Text: path},
Range: r,
})
return css_ast.Rule{Loc: atRange.Loc, Data: &css_ast.RAtImport{
ImportRecordIndex: importRecordIndex,
ImportConditions: importConditions,
}}
}
}
case "keyframes", "-webkit-keyframes", "-moz-keyframes", "-ms-keyframes", "-o-keyframes":
p.eat(css_lexer.TWhitespace)
var name string
if p.peek(css_lexer.TIdent) {
name = p.decoded()
p.advance()
} else if p.eat(css_lexer.TString) {
// Consider string names to be an unknown rule even though they are allowed
// by the specification and they work in Firefox because they do not work in
// Chrome or Safari. We don't take the effort to support this Firefox-only
// feature natively. Instead, we just pass the syntax through unmodified.
break
} else if !p.expect(css_lexer.TIdent) {
break
}
p.eat(css_lexer.TWhitespace)
blockStart := p.index
matchingLoc := p.current().Range.Loc
if p.expect(css_lexer.TOpenBrace) {
var blocks []css_ast.KeyframeBlock
badSyntax:
for {
switch p.current().Kind {
case css_lexer.TWhitespace:
p.advance()
continue
case css_lexer.TCloseBrace:
p.advance()
return css_ast.Rule{Loc: atRange.Loc, Data: &css_ast.RAtKeyframes{
AtToken: atToken,
Name: name,
Blocks: blocks,
}}
case css_lexer.TEndOfFile:
break badSyntax
case css_lexer.TOpenBrace:
p.expect(css_lexer.TPercentage)
break badSyntax
default:
var selectors []string
selectors:
for {
t := p.current()
switch t.Kind {
case css_lexer.TWhitespace:
p.advance()
continue
case css_lexer.TOpenBrace:
blockMatchingLoc := p.current().Range.Loc
p.advance()
rules := p.parseListOfDeclarations()
p.expectWithMatchingLoc(css_lexer.TCloseBrace, blockMatchingLoc)
// "@keyframes { from {} to { color: red } }" => "@keyframes { to { color: red } }"
if !p.options.MinifySyntax || len(rules) > 0 {
blocks = append(blocks, css_ast.KeyframeBlock{
Selectors: selectors,
Rules: rules,
})
}
break selectors
case css_lexer.TCloseBrace, css_lexer.TEndOfFile:
p.expect(css_lexer.TOpenBrace)
break badSyntax
case css_lexer.TIdent, css_lexer.TPercentage:
text := p.decoded()
if t.Kind == css_lexer.TIdent {
if text == "from" {
if p.options.MinifySyntax {
text = "0%" // "0%" is equivalent to but shorter than "from"
}
} else if text != "to" {
p.expect(css_lexer.TPercentage)
}
} else if p.options.MinifySyntax && text == "100%" {
text = "to" // "to" is equivalent to but shorter than "100%"
}
selectors = append(selectors, text)
p.advance()
// Keyframe selectors are comma-separated
p.eat(css_lexer.TWhitespace)
if p.eat(css_lexer.TComma) {
p.eat(css_lexer.TWhitespace)
if k := p.current().Kind; k != css_lexer.TIdent && k != css_lexer.TPercentage {
p.expect(css_lexer.TPercentage)
break badSyntax
}
} else if k := p.current().Kind; k != css_lexer.TOpenBrace && k != css_lexer.TCloseBrace && k != css_lexer.TEndOfFile {
p.expect(css_lexer.TComma)
break badSyntax
}
default:
p.expect(css_lexer.TPercentage)
break badSyntax
}
}
}
}
// Otherwise, finish parsing the body and return an unknown rule
for !p.peek(css_lexer.TCloseBrace) && !p.peek(css_lexer.TEndOfFile) {
p.parseComponentValue()
}
p.expectWithMatchingLoc(css_lexer.TCloseBrace, matchingLoc)
prelude := p.convertTokens(p.tokens[preludeStart:blockStart])
block, _ := p.convertTokensHelper(p.tokens[blockStart:p.index], css_lexer.TEndOfFile, convertTokensOpts{allowImports: true})
return css_ast.Rule{Loc: atRange.Loc, Data: &css_ast.RUnknownAt{AtToken: atToken, Prelude: prelude, Block: block}}
}
case "nest":
// Reference: https://drafts.csswg.org/css-nesting-1/
p.eat(css_lexer.TWhitespace)
if kind := p.current().Kind; kind != css_lexer.TSemicolon && kind != css_lexer.TOpenBrace &&
kind != css_lexer.TCloseBrace && kind != css_lexer.TEndOfFile {
return p.parseSelectorRuleFrom(preludeStart-1, parseSelectorOpts{
atNestRange: atRange,
allowNesting: context.allowNesting,
isTopLevel: context.isTopLevel,
})
}
case "layer":
// Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/@layer
// Read the layer name list
var names [][]string
p.eat(css_lexer.TWhitespace)
if p.peek(css_lexer.TIdent) {
for {
ident, ok := p.expectValidLayerNameIdent()
if !ok {