-
Notifications
You must be signed in to change notification settings - Fork 187
/
Copy pathcssParser.ts
2019 lines (1774 loc) · 59.7 KB
/
cssParser.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import { TokenType, Scanner, IToken } from './cssScanner';
import * as nodes from './cssNodes';
import { ParseError, CSSIssueType } from './cssErrors';
import * as languageFacts from '../languageFacts/facts';
import { TextDocument } from '../cssLanguageTypes';
import { isDefined } from '../utils/objects';
export interface IMark {
prev?: IToken;
curr: IToken;
pos: number;
}
/// <summary>
/// A parser for the css core specification. See for reference:
/// https://www.w3.org/TR/CSS21/grammar.html
/// http://www.w3.org/TR/CSS21/syndata.html#tokenization
/// </summary>
export class Parser {
public scanner: Scanner;
public token: IToken;
public prevToken?: IToken;
private lastErrorToken?: IToken;
constructor(scnr: Scanner = new Scanner()) {
this.scanner = scnr;
this.token = { type: TokenType.EOF, offset: -1, len: 0, text: '' };
this.prevToken = undefined!;
}
public peekIdent(text: string): boolean {
return TokenType.Ident === this.token.type && text.length === this.token.text.length && text === this.token.text.toLowerCase();
}
public peekKeyword(text: string): boolean {
return TokenType.AtKeyword === this.token.type && text.length === this.token.text.length && text === this.token.text.toLowerCase();
}
public peekDelim(text: string): boolean {
return TokenType.Delim === this.token.type && text === this.token.text;
}
public peek(type: TokenType): boolean {
return type === this.token.type;
}
public peekOne(...types: TokenType[]): boolean {
return types.indexOf(this.token.type) !== -1;
}
public peekRegExp(type: TokenType, regEx: RegExp): boolean {
if (type !== this.token.type) {
return false;
}
return regEx.test(this.token.text);
}
public hasWhitespace(): boolean {
return !!this.prevToken && (this.prevToken.offset + this.prevToken.len !== this.token.offset);
}
public consumeToken(): void {
this.prevToken = this.token;
this.token = this.scanner.scan();
}
public acceptUnicodeRange(): boolean {
const token = this.scanner.tryScanUnicode();
if (token) {
this.prevToken = token;
this.token = this.scanner.scan();
return true;
}
return false;
}
public mark(): IMark {
return {
prev: this.prevToken,
curr: this.token,
pos: this.scanner.pos()
};
}
public restoreAtMark(mark: IMark): void {
this.prevToken = mark.prev;
this.token = mark.curr;
this.scanner.goBackTo(mark.pos);
}
public try(func: () => nodes.Node | null): nodes.Node | null {
const pos = this.mark();
const node = func();
if (!node) {
this.restoreAtMark(pos);
return null;
}
return node;
}
public acceptOneKeyword(keywords: string[]): boolean {
if (TokenType.AtKeyword === this.token.type) {
for (const keyword of keywords) {
if (keyword.length === this.token.text.length && keyword === this.token.text.toLowerCase()) {
this.consumeToken();
return true;
}
}
}
return false;
}
public accept(type: TokenType) {
if (type === this.token.type) {
this.consumeToken();
return true;
}
return false;
}
public acceptIdent(text: string): boolean {
if (this.peekIdent(text)) {
this.consumeToken();
return true;
}
return false;
}
public acceptKeyword(text: string) {
if (this.peekKeyword(text)) {
this.consumeToken();
return true;
}
return false;
}
public acceptDelim(text: string) {
if (this.peekDelim(text)) {
this.consumeToken();
return true;
}
return false;
}
public acceptRegexp(regEx: RegExp): boolean {
if (regEx.test(this.token.text)) {
this.consumeToken();
return true;
}
return false;
}
public _parseRegexp(regEx: RegExp): nodes.Node {
let node = this.createNode(nodes.NodeType.Identifier);
do { } while (this.acceptRegexp(regEx));
return this.finish(node);
}
protected acceptUnquotedString(): boolean {
const pos = this.scanner.pos();
this.scanner.goBackTo(this.token.offset);
const unquoted = this.scanner.scanUnquotedString();
if (unquoted) {
this.token = unquoted;
this.consumeToken();
return true;
}
this.scanner.goBackTo(pos);
return false;
}
public resync(resyncTokens: TokenType[] | undefined, resyncStopTokens: TokenType[] | undefined): boolean {
while (true) {
if (resyncTokens && resyncTokens.indexOf(this.token.type) !== -1) {
this.consumeToken();
return true;
} else if (resyncStopTokens && resyncStopTokens.indexOf(this.token.type) !== -1) {
return true;
} else {
if (this.token.type === TokenType.EOF) {
return false;
}
this.token = this.scanner.scan();
}
}
}
public createNode(nodeType: nodes.NodeType): nodes.Node {
return new nodes.Node(this.token.offset, this.token.len, nodeType);
}
public create<T>(ctor: nodes.NodeConstructor<T>): T {
return new ctor(this.token.offset, this.token.len);
}
public finish<T extends nodes.Node>(node: T, error?: CSSIssueType, resyncTokens?: TokenType[], resyncStopTokens?: TokenType[]): T {
// parseNumeric misuses error for boolean flagging (however the real error mustn't be a false)
// + nodelist offsets mustn't be modified, because there is a offset hack in rulesets for smartselection
if (!(node instanceof nodes.Nodelist)) {
if (error) {
this.markError(node, error, resyncTokens, resyncStopTokens);
}
// set the node end position
if (this.prevToken) {
// length with more elements belonging together
const prevEnd = this.prevToken.offset + this.prevToken.len;
node.length = prevEnd > node.offset ? prevEnd - node.offset : 0; // offset is taken from current token, end from previous: Use 0 for empty nodes
}
}
return node;
}
public markError<T extends nodes.Node>(node: T, error: CSSIssueType, resyncTokens?: TokenType[], resyncStopTokens?: TokenType[]): void {
if (this.token !== this.lastErrorToken) { // do not report twice on the same token
node.addIssue(new nodes.Marker(node, error, nodes.Level.Error, undefined, this.token.offset, this.token.len));
this.lastErrorToken = this.token;
}
if (resyncTokens || resyncStopTokens) {
this.resync(resyncTokens, resyncStopTokens);
}
}
public parseStylesheet(textDocument: TextDocument): nodes.Stylesheet {
const versionId = textDocument.version;
const text = textDocument.getText();
const textProvider = (offset: number, length: number) => {
if (textDocument.version !== versionId) {
throw new Error('Underlying model has changed, AST is no longer valid');
}
return text.substr(offset, length);
};
return this.internalParse(text, this._parseStylesheet, textProvider);
}
public internalParse<T extends nodes.Node, U extends T | null>(input: string, parseFunc: () => U, textProvider?: nodes.ITextProvider): U;
public internalParse<T extends nodes.Node, U extends T>(input: string, parseFunc: () => U, textProvider?: nodes.ITextProvider): U {
this.scanner.setSource(input);
this.token = this.scanner.scan();
const node: U = parseFunc.bind(this)();
if (node) {
if (textProvider) {
node.textProvider = textProvider;
} else {
node.textProvider = (offset: number, length: number) => { return input.substr(offset, length); };
}
}
return node;
}
public _parseStylesheet(): nodes.Stylesheet {
const node = this.create(nodes.Stylesheet);
while (node.addChild(this._parseStylesheetStart())) {
// Parse statements only valid at the beginning of stylesheets.
}
let inRecovery = false;
do {
let hasMatch = false;
do {
hasMatch = false;
const statement = this._parseStylesheetStatement();
if (statement) {
node.addChild(statement);
hasMatch = true;
inRecovery = false;
if (!this.peek(TokenType.EOF) && this._needsSemicolonAfter(statement) && !this.accept(TokenType.SemiColon)) {
this.markError(node, ParseError.SemiColonExpected);
}
}
while (this.accept(TokenType.SemiColon) || this.accept(TokenType.CDO) || this.accept(TokenType.CDC)) {
// accept empty statements
hasMatch = true;
inRecovery = false;
}
} while (hasMatch);
if (this.peek(TokenType.EOF)) {
break;
}
if (!inRecovery) {
if (this.peek(TokenType.AtKeyword)) {
this.markError(node, ParseError.UnknownAtRule);
} else {
this.markError(node, ParseError.RuleOrSelectorExpected);
}
inRecovery = true;
}
this.consumeToken();
} while (!this.peek(TokenType.EOF));
return this.finish(node);
}
public _parseStylesheetStart(): nodes.Node | null {
return this._parseCharset();
}
public _parseStylesheetStatement(isNested: boolean = false): nodes.Node | null {
if (this.peek(TokenType.AtKeyword)) {
return this._parseStylesheetAtStatement(isNested);
}
return this._parseRuleset(isNested);
}
public _parseStylesheetAtStatement(isNested: boolean = false): nodes.Node | null {
return this._parseImport()
|| this._parseMedia(isNested)
|| this._parsePage()
|| this._parseFontFace()
|| this._parseKeyframe()
|| this._parseSupports(isNested)
|| this._parseLayer(isNested)
|| this._parsePropertyAtRule()
|| this._parseViewPort()
|| this._parseNamespace()
|| this._parseDocument()
|| this._parseContainer(isNested)
|| this._parseUnknownAtRule();
}
public _tryParseRuleset(isNested: boolean): nodes.RuleSet | null {
const mark = this.mark();
if (this._parseSelector(isNested)) {
while (this.accept(TokenType.Comma) && this._parseSelector(isNested)) {
// loop
}
if (this.accept(TokenType.CurlyL)) {
this.restoreAtMark(mark);
return this._parseRuleset(isNested);
}
}
this.restoreAtMark(mark);
return null;
}
public _parseRuleset(isNested: boolean = false): nodes.RuleSet | null {
const node = this.create(nodes.RuleSet);
const selectors = node.getSelectors();
if (!selectors.addChild(this._parseSelector(isNested))) {
return null;
}
while (this.accept(TokenType.Comma)) {
if (!selectors.addChild(this._parseSelector(isNested))) {
return this.finish(node, ParseError.SelectorExpected);
}
}
return this._parseBody(node, this._parseRuleSetDeclaration.bind(this));
}
protected _parseRuleSetDeclarationAtStatement(): nodes.Node | null {
return this._parseMedia(true)
|| this._parseSupports(true)
|| this._parseLayer(true)
|| this._parseContainer(true)
|| this._parseUnknownAtRule();
}
public _parseRuleSetDeclaration(): nodes.Node | null {
// https://www.w3.org/TR/css-syntax-3/#consume-a-list-of-declarations
if (this.peek(TokenType.AtKeyword)) {
return this._parseRuleSetDeclarationAtStatement();
}
if (!this.peek(TokenType.Ident)) {
return this._parseRuleset(true);
}
return this._tryParseRuleset(true) || this._parseDeclaration();
}
public _needsSemicolonAfter(node: nodes.Node): boolean {
switch (node.type) {
case nodes.NodeType.Keyframe:
case nodes.NodeType.ViewPort:
case nodes.NodeType.Media:
case nodes.NodeType.Ruleset:
case nodes.NodeType.Namespace:
case nodes.NodeType.If:
case nodes.NodeType.For:
case nodes.NodeType.Each:
case nodes.NodeType.While:
case nodes.NodeType.MixinDeclaration:
case nodes.NodeType.FunctionDeclaration:
case nodes.NodeType.MixinContentDeclaration:
return false;
case nodes.NodeType.ExtendsReference:
case nodes.NodeType.MixinContentReference:
case nodes.NodeType.ReturnStatement:
case nodes.NodeType.MediaQuery:
case nodes.NodeType.Debug:
case nodes.NodeType.Import:
case nodes.NodeType.AtApplyRule:
case nodes.NodeType.CustomPropertyDeclaration:
return true;
case nodes.NodeType.VariableDeclaration:
return (<nodes.VariableDeclaration>node).needsSemicolon;
case nodes.NodeType.MixinReference:
return !(<nodes.MixinReference>node).getContent();
case nodes.NodeType.Declaration:
return !(<nodes.Declaration>node).getNestedProperties();
}
return false;
}
public _parseDeclarations(parseDeclaration: () => nodes.Node | null): nodes.Declarations | null {
const node = this.create(nodes.Declarations);
if (!this.accept(TokenType.CurlyL)) {
return null;
}
let decl = parseDeclaration();
while (node.addChild(decl)) {
if (this.peek(TokenType.CurlyR)) {
break;
}
if (this._needsSemicolonAfter(decl) && !this.accept(TokenType.SemiColon)) {
return this.finish(node, ParseError.SemiColonExpected, [TokenType.SemiColon, TokenType.CurlyR]);
}
// We accepted semicolon token. Link it to declaration.
if (decl && this.prevToken && this.prevToken.type === TokenType.SemiColon) {
(decl as nodes.Declaration).semicolonPosition = this.prevToken.offset;
}
while (this.accept(TokenType.SemiColon)) {
// accept empty statements
}
decl = parseDeclaration();
}
if (!this.accept(TokenType.CurlyR)) {
return this.finish(node, ParseError.RightCurlyExpected, [TokenType.CurlyR, TokenType.SemiColon]);
}
return this.finish(node);
}
public _parseBody<T extends nodes.BodyDeclaration>(node: T, parseDeclaration: () => nodes.Node | null): T {
if (!node.setDeclarations(this._parseDeclarations(parseDeclaration))) {
return this.finish(node, ParseError.LeftCurlyExpected, [TokenType.CurlyR, TokenType.SemiColon]);
}
return this.finish(node);
}
public _parseSelector(isNested?: boolean): nodes.Selector | null {
const node = this.create(nodes.Selector);
let hasContent = false;
if (isNested) {
// nested selectors can start with a combinator
hasContent = node.addChild(this._parseCombinator());
}
while (node.addChild(this._parseSimpleSelector())) {
hasContent = true;
node.addChild(this._parseCombinator()); // optional
}
return hasContent ? this.finish(node) : null;
}
public _parseDeclaration(stopTokens?: TokenType[]): nodes.Declaration | null {
const customProperty = this._tryParseCustomPropertyDeclaration(stopTokens);
if (customProperty) {
return customProperty;
}
const node = this.create(nodes.Declaration);
if (!node.setProperty(this._parseProperty())) {
return null;
}
if (!this.accept(TokenType.Colon)) {
return <nodes.Declaration>this.finish(node, ParseError.ColonExpected, [TokenType.Colon], stopTokens || [TokenType.SemiColon]);
}
if (this.prevToken) {
node.colonPosition = this.prevToken.offset;
}
if (!node.setValue(this._parseExpr())) {
return this.finish(node, ParseError.PropertyValueExpected);
}
node.addChild(this._parsePrio());
if (this.peek(TokenType.SemiColon)) {
node.semicolonPosition = this.token.offset; // not part of the declaration, but useful information for code assist
}
return this.finish(node);
}
public _tryParseCustomPropertyDeclaration(stopTokens?: TokenType[]): nodes.CustomPropertyDeclaration | null {
if (!this.peekRegExp(TokenType.Ident, /^--/)) {
return null;
}
const node = this.create(nodes.CustomPropertyDeclaration);
if (!node.setProperty(this._parseProperty())) {
return null;
}
if (!this.accept(TokenType.Colon)) {
return this.finish(node, ParseError.ColonExpected, [TokenType.Colon]);
}
if (this.prevToken) {
node.colonPosition = this.prevToken.offset;
}
const mark = this.mark();
if (this.peek(TokenType.CurlyL)) {
// try to parse it as nested declaration
const propertySet = this.create(nodes.CustomPropertySet);
const declarations = this._parseDeclarations(this._parseRuleSetDeclaration.bind(this));
if (propertySet.setDeclarations(declarations) && !declarations.isErroneous(true)) {
propertySet.addChild(this._parsePrio());
if (this.peek(TokenType.SemiColon)) {
this.finish(propertySet);
node.setPropertySet(propertySet);
node.semicolonPosition = this.token.offset; // not part of the declaration, but useful information for code assist
return this.finish(node);
}
}
this.restoreAtMark(mark);
}
// try to parse as expression
const expression = this._parseExpr();
if (expression && !expression.isErroneous(true)) {
this._parsePrio();
if (this.peekOne(...(stopTokens || []), TokenType.SemiColon, TokenType.EOF)) {
node.setValue(expression);
if (this.peek(TokenType.SemiColon)) {
node.semicolonPosition = this.token.offset; // not part of the declaration, but useful information for code assist
}
return this.finish(node);
}
}
this.restoreAtMark(mark);
node.addChild(this._parseCustomPropertyValue(stopTokens));
node.addChild(this._parsePrio());
if (isDefined(node.colonPosition) && this.token.offset === node.colonPosition + 1) {
return this.finish(node, ParseError.PropertyValueExpected);
}
return this.finish(node);
}
/**
* Parse custom property values.
*
* Based on https://www.w3.org/TR/css-variables/#syntax
*
* This code is somewhat unusual, as the allowed syntax is incredibly broad,
* parsing almost any sequence of tokens, save for a small set of exceptions.
* Unbalanced delimitors, invalid tokens, and declaration
* terminators like semicolons and !important directives (when not inside
* of delimitors).
*/
public _parseCustomPropertyValue(stopTokens: TokenType[] = [TokenType.CurlyR]): nodes.Node {
const node = this.create(nodes.Node);
const isTopLevel = () => curlyDepth === 0 && parensDepth === 0 && bracketsDepth === 0;
const onStopToken = () => stopTokens.indexOf(this.token.type) !== -1;
let curlyDepth = 0;
let parensDepth = 0;
let bracketsDepth = 0;
done: while (true) {
switch (this.token.type) {
case TokenType.SemiColon:
// A semicolon only ends things if we're not inside a delimitor.
if (isTopLevel()) {
break done;
}
break;
case TokenType.Exclamation:
// An exclamation ends the value if we're not inside delims.
if (isTopLevel()) {
break done;
}
break;
case TokenType.CurlyL:
curlyDepth++;
break;
case TokenType.CurlyR:
curlyDepth--;
if (curlyDepth < 0) {
// The property value has been terminated without a semicolon, and
// this is the last declaration in the ruleset.
if (onStopToken() && parensDepth === 0 && bracketsDepth === 0) {
break done;
}
return this.finish(node, ParseError.LeftCurlyExpected);
}
break;
case TokenType.ParenthesisL:
parensDepth++;
break;
case TokenType.ParenthesisR:
parensDepth--;
if (parensDepth < 0) {
if (onStopToken() && bracketsDepth === 0 && curlyDepth === 0) {
break done;
}
return this.finish(node, ParseError.LeftParenthesisExpected);
}
break;
case TokenType.BracketL:
bracketsDepth++;
break;
case TokenType.BracketR:
bracketsDepth--;
if (bracketsDepth < 0) {
return this.finish(node, ParseError.LeftSquareBracketExpected);
}
break;
case TokenType.BadString: // fall through
break done;
case TokenType.EOF:
// We shouldn't have reached the end of input, something is
// unterminated.
let error = ParseError.RightCurlyExpected;
if (bracketsDepth > 0) {
error = ParseError.RightSquareBracketExpected;
} else if (parensDepth > 0) {
error = ParseError.RightParenthesisExpected;
}
return this.finish(node, error);
}
this.consumeToken();
}
return this.finish(node);
}
public _tryToParseDeclaration(stopTokens?: TokenType[]): nodes.Declaration | null {
const mark = this.mark();
if (this._parseProperty() && this.accept(TokenType.Colon)) {
// looks like a declaration, go ahead
this.restoreAtMark(mark);
return this._parseDeclaration(stopTokens);
}
this.restoreAtMark(mark);
return null;
}
public _parseProperty(): nodes.Property | null {
const node = this.create(nodes.Property);
const mark = this.mark();
if (this.acceptDelim('*') || this.acceptDelim('_')) {
// support for IE 5.x, 6 and 7 star hack: see http://en.wikipedia.org/wiki/CSS_filter#Star_hack
if (this.hasWhitespace()) {
this.restoreAtMark(mark);
return null;
}
}
if (node.setIdentifier(this._parsePropertyIdentifier())) {
return <nodes.Property>this.finish(node);
}
return null;
}
public _parsePropertyIdentifier(): nodes.Identifier | null {
return this._parseIdent();
}
public _parseCharset(): nodes.Node | null {
if (!this.peek(TokenType.Charset)) {
return null;
}
const node = this.create(nodes.Node);
this.consumeToken(); // charset
if (!this.accept(TokenType.String)) {
return this.finish(node, ParseError.IdentifierExpected);
}
if (!this.accept(TokenType.SemiColon)) {
return this.finish(node, ParseError.SemiColonExpected);
}
return this.finish(node);
}
public _parseImport(): nodes.Node | null {
// @import [ <url> | <string> ]
// [ layer | layer(<layer-name>) ]?
// <import-condition> ;
// <import-conditions> = [ supports( [ <supports-condition> | <declaration> ] ) ]?
// <media-query-list>?
if (!this.peekKeyword('@import')) {
return null;
}
const node = this.create(nodes.Import);
this.consumeToken(); // @import
if (!node.addChild(this._parseURILiteral()) && !node.addChild(this._parseStringLiteral())) {
return this.finish(node, ParseError.URIOrStringExpected);
}
return this._completeParseImport(node);
}
public _completeParseImport(node: nodes.Import): nodes.Node | null {
if (this.acceptIdent('layer')) {
if (this.accept(TokenType.ParenthesisL)) {
if (!node.addChild(this._parseLayerName())) {
return this.finish(node, ParseError.IdentifierExpected, [TokenType.SemiColon]);
}
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected, [TokenType.ParenthesisR], []);
}
}
}
if (this.acceptIdent('supports')) {
if (this.accept(TokenType.ParenthesisL)) {
node.addChild(this._tryToParseDeclaration() || this._parseSupportsCondition());
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected, [TokenType.ParenthesisR], []);
}
}
}
if (!this.peek(TokenType.SemiColon) && !this.peek(TokenType.EOF)) {
node.setMedialist(this._parseMediaQueryList());
}
return this.finish(node);
}
public _parseNamespace(): nodes.Node | null {
// http://www.w3.org/TR/css3-namespace/
// namespace : NAMESPACE_SYM S* [IDENT S*]? [STRING|URI] S* ';' S*
if (!this.peekKeyword('@namespace')) {
return null;
}
const node = this.create(nodes.Namespace);
this.consumeToken(); // @namespace
if (!node.addChild(this._parseURILiteral())) { // url literal also starts with ident
node.addChild(this._parseIdent()); // optional prefix
if (!node.addChild(this._parseURILiteral()) && !node.addChild(this._parseStringLiteral())) {
return this.finish(node, ParseError.URIExpected, [TokenType.SemiColon]);
}
}
if (!this.accept(TokenType.SemiColon)) {
return this.finish(node, ParseError.SemiColonExpected);
}
return this.finish(node);
}
public _parseFontFace(): nodes.Node | null {
if (!this.peekKeyword('@font-face')) {
return null;
}
const node = this.create(nodes.FontFace);
this.consumeToken(); // @font-face
return this._parseBody(node, this._parseRuleSetDeclaration.bind(this));
}
public _parseViewPort(): nodes.Node | null {
if (!this.peekKeyword('@-ms-viewport') &&
!this.peekKeyword('@-o-viewport') &&
!this.peekKeyword('@viewport')
) {
return null;
}
const node = this.create(nodes.ViewPort);
this.consumeToken(); // @-ms-viewport
return this._parseBody(node, this._parseRuleSetDeclaration.bind(this));
}
private keyframeRegex = /^@(\-(webkit|ms|moz|o)\-)?keyframes$/i;
public _parseKeyframe(): nodes.Node | null {
if (!this.peekRegExp(TokenType.AtKeyword, this.keyframeRegex)) {
return null;
}
const node = this.create(nodes.Keyframe);
const atNode = this.create(nodes.Node);
this.consumeToken(); // atkeyword
node.setKeyword(this.finish(atNode));
if (atNode.matches('@-ms-keyframes')) { // -ms-keyframes never existed
this.markError(atNode, ParseError.UnknownKeyword);
}
if (!node.setIdentifier(this._parseKeyframeIdent())) {
return this.finish(node, ParseError.IdentifierExpected, [TokenType.CurlyR]);
}
return this._parseBody(node, this._parseKeyframeSelector.bind(this));
}
public _parseKeyframeIdent(): nodes.Node | null {
return this._parseIdent([nodes.ReferenceType.Keyframe]);
}
public _parseKeyframeSelector(): nodes.Node | null {
const node = this.create(nodes.KeyframeSelector);
let hasContent = false;
if (node.addChild(this._parseIdent())) {
hasContent = true;
}
if (this.accept(TokenType.Percentage)) {
hasContent = true;
}
if (!hasContent) {
return null;
}
while (this.accept(TokenType.Comma)) {
hasContent = false;
if (node.addChild(this._parseIdent())) {
hasContent = true;
}
if (this.accept(TokenType.Percentage)) {
hasContent = true;
}
if (!hasContent) {
return this.finish(node, ParseError.PercentageExpected);
}
}
return this._parseBody(node, this._parseRuleSetDeclaration.bind(this));
}
public _tryParseKeyframeSelector(): nodes.Node | null {
const node = this.create(nodes.KeyframeSelector);
const pos = this.mark();
let hasContent = false;
if (node.addChild(this._parseIdent())) {
hasContent = true;
}
if (this.accept(TokenType.Percentage)) {
hasContent = true;
}
if (!hasContent) {
return null;
}
while (this.accept(TokenType.Comma)) {
hasContent = false;
if (node.addChild(this._parseIdent())) {
hasContent = true;
}
if (this.accept(TokenType.Percentage)) {
hasContent = true;
}
if (!hasContent) {
this.restoreAtMark(pos);
return null;
}
}
if (!this.peek(TokenType.CurlyL)) {
this.restoreAtMark(pos);
return null;
}
return this._parseBody(node, this._parseRuleSetDeclaration.bind(this));
}
public _parsePropertyAtRule(): nodes.Node | null {
// @property <custom-property-name> {
// <declaration-list>
// }
if (!this.peekKeyword('@property')) {
return null;
}
const node = this.create(nodes.PropertyAtRule);
this.consumeToken(); // @layer
if (!this.peekRegExp(TokenType.Ident, /^--/) || !node.setName(this._parseIdent([nodes.ReferenceType.Property]))) {
return this.finish(node, ParseError.IdentifierExpected);
}
return this._parseBody(node, this._parseDeclaration.bind(this));
}
public _parseLayer(isNested: boolean = false): nodes.Node | null {
// @layer layer-name {rules}
// @layer layer-name;
// @layer layer-name, layer-name, layer-name;
// @layer {rules}
if (!this.peekKeyword('@layer')) {
return null;
}
const node = this.create(nodes.Layer);
this.consumeToken(); // @layer
const names = this._parseLayerNameList();
if (names) {
node.setNames(names);
}
if ((!names || names.getChildren().length === 1) && this.peek(TokenType.CurlyL)) {
return this._parseBody(node, this._parseLayerDeclaration.bind(this, isNested));
}
if (!this.accept(TokenType.SemiColon)) {
return this.finish(node, ParseError.SemiColonExpected);
}
return this.finish(node);
}
public _parseLayerDeclaration(isNested = false): nodes.Node | null {
if (isNested) {
// if nested, the body can contain rulesets, but also declarations
return this._tryParseRuleset(true)
|| this._tryToParseDeclaration()
|| this._parseStylesheetStatement(true);
}
return this._parseStylesheetStatement(false);
}
public _parseLayerNameList(): nodes.Node | null {
const node = this.createNode(nodes.NodeType.LayerNameList);
if (!node.addChild(this._parseLayerName())) {
return null;
}
while (this.accept(TokenType.Comma)) {
if (!node.addChild(this._parseLayerName())) {
return this.finish(node, ParseError.IdentifierExpected);
}
}
return this.finish(node);
}
public _parseLayerName(): nodes.Node | null {
// <layer-name> = <ident> [ '.' <ident> ]*
const node = this.createNode(nodes.NodeType.LayerName);
if (!node.addChild(this._parseIdent()) ) {
return null;
}
while (!this.hasWhitespace() && this.acceptDelim('.')) {
if (this.hasWhitespace() || !node.addChild(this._parseIdent())) {
return this.finish(node, ParseError.IdentifierExpected);
}
}
return this.finish(node);
}
public _parseSupports(isNested = false): nodes.Node | null {
// SUPPORTS_SYM S* supports_condition '{' S* ruleset* '}' S*
if (!this.peekKeyword('@supports')) {
return null;
}
const node = this.create(nodes.Supports);
this.consumeToken(); // @supports
node.addChild(this._parseSupportsCondition());
return this._parseBody(node, this._parseSupportsDeclaration.bind(this, isNested));
}
public _parseSupportsDeclaration(isNested = false): nodes.Node | null {
if (isNested) {
// if nested, the body can contain rulesets, but also declarations
return this._tryParseRuleset(true)
|| this._tryToParseDeclaration()
|| this._parseStylesheetStatement(true);
}
return this._parseStylesheetStatement(false);
}
protected _parseSupportsCondition(): nodes.Node {
// supports_condition : supports_negation | supports_conjunction | supports_disjunction | supports_condition_in_parens ;
// supports_condition_in_parens: ( '(' S* supports_condition S* ')' ) | supports_declaration_condition | general_enclosed ;
// supports_negation: NOT S+ supports_condition_in_parens ;
// supports_conjunction: supports_condition_in_parens ( S+ AND S+ supports_condition_in_parens )+;
// supports_disjunction: supports_condition_in_parens ( S+ OR S+ supports_condition_in_parens )+;
// supports_declaration_condition: '(' S* declaration ')';
// general_enclosed: ( FUNCTION | '(' ) ( any | unused )* ')' ;
const node = this.create(nodes.SupportsCondition);
if (this.acceptIdent('not')) {
node.addChild(this._parseSupportsConditionInParens());