Repository navigation
Expand file tree
/
Copy pathCSS3Parser.ts
More file actions
698 lines (622 loc) · 17.4 KB
/
Copy pathCSS3Parser.ts
File metadata and controls
698 lines (622 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
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
export interface Stylesheet {
rules: Rule[];
}
export type Rule = QualifiedRule | AtRule;
export interface AtRule {
type: 'at-rule';
name: string;
prelude: InputToken[];
block: SimpleBlock;
}
export interface QualifiedRule {
type: 'qualified-rule';
prelude: InputToken[];
block: SimpleBlock;
}
// const nonQuoteURLRegEx = /(:?[^\)\s\t\n\r\f\'\"\(]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*/gym; // TODO: non-printable code points omitted
export type InputToken = '(' | ')' | '{' | '}' | '[' | ']' | ':' | ';' | ',' | ' ' | '^=' | '|=' | '$=' | '*=' | '~=' | '<!--' | '-->' | undefined | /* <EOF-token> */ InputTokenObject | FunctionInputToken | FunctionToken | SimpleBlock | AtKeywordToken;
export const enum TokenObjectType {
/**
* <string-token>
*/
string = 1,
/**
* <delim-token>
*/
delim = 2,
/**
* <number-token>
*/
number = 3,
/**
* <percentage-token>
*/
percentage = 4,
/**
* <dimension-token>
*/
dimension = 5,
/**
* <ident-token>
*/
ident = 6,
/**
* <url-token>
*/
url = 7,
/**
* <function-token>
* This is a token indicating a function's leading: <ident-token>(
*/
functionToken = 8,
/**
* <simple-block>
*/
simpleBlock = 9,
/**
* <comment-token>
*/
comment = 10,
/**
* <at-keyword-token>
*/
atKeyword = 11,
/**
* <hash-token>
*/
hash = 12,
/**
* <function>
* This is a complete consumed function: <function-token>([<component-value> [, <component-value>]*])")"
*/
function = 14,
}
export interface InputTokenObject {
type: TokenObjectType;
text: string;
}
/**
* This is a "<ident>(" token.
*/
export interface FunctionInputToken extends InputTokenObject {
name: string;
}
/**
* This is a completely parsed function like "<ident>([component [, component]*])".
*/
export interface FunctionToken extends FunctionInputToken {
components: any[];
}
export interface SimpleBlock extends InputTokenObject {
associatedToken: InputToken;
values: InputToken[];
}
export type AtKeywordToken = InputTokenObject;
const commentRegEx = /(\/\*(?:[^\*]|\*[^\/])*\*\/)/gmy;
// eslint-disable-next-line no-control-regex
const nameRegEx = /-?(?:(?:[a-zA-Z_]|[^\x00-\x7F]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))(?:[a-zA-Z_0-9\-]*|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)/gmy;
const numberRegEx = /[\+\-]?(?:\d+\.\d+|\d+|\.\d+)(?:[eE][\+\-]?\d+)?/gmy;
const doubleQuoteStringRegEx = /"((?:[^\n\r\f\"]|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?"|$)/gmy; // Besides $n, parse escape
const whitespaceRegEx = /[\s\t\n\r\f]*/gmy;
const singleQuoteStringRegEx = /'((?:[^\n\r\f\']|\\(?:\$|\n|[0-9a-fA-F]{1,6}\s?))*)(:?'|$)/gmy; // Besides $n, parse escape
/**
* CSS parser following relatively close:
* CSS Syntax Module Level 3
* https://www.w3.org/TR/css-syntax-3/
*/
export class CSS3Parser {
private nextInputCodePointIndex = 0;
private reconsumedInputToken: InputToken;
private topLevelFlag: boolean;
constructor(private text: string) {}
/**
* For testing purposes.
* This method allows us to run and assert the proper working of the tokenizer.
*/
tokenize(): InputToken[] {
const tokens: InputToken[] = [];
let inputToken: InputToken;
do {
inputToken = this.consumeAToken();
tokens.push(inputToken);
} while (inputToken);
return tokens;
}
/**
* 4.3.1. Consume a token
* https://www.w3.org/TR/css-syntax-3/#consume-a-token
*/
private consumeAToken(): InputToken {
if (this.reconsumedInputToken) {
const result = this.reconsumedInputToken;
this.reconsumedInputToken = null;
return result;
}
const char = this.text[this.nextInputCodePointIndex];
switch (char) {
case '"':
return this.consumeAStringToken();
case "'":
return this.consumeAStringToken();
case '(':
case ')':
case ',':
case ':':
case ';':
case '[':
case ']':
case '{':
case '}':
this.nextInputCodePointIndex++;
return <any>char;
case '#':
return this.consumeAHashToken() || this.consumeADelimToken();
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
return this.consumeAWhitespace();
case '@':
return this.consumeAtKeyword() || this.consumeADelimToken();
// TODO: Only if this is valid escape, otherwise it is a parse error
case '\\':
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return this.consumeANumericToken();
case 'u':
case 'U':
if (this.text[this.nextInputCodePointIndex + 1] === '+') {
const thirdChar = this.text[this.nextInputCodePointIndex + 2];
if ((thirdChar >= '0' && thirdChar <= '9') || thirdChar === '?') {
// TODO: Handle unicode stuff such as U+002B
throw new Error('Unicode tokens not supported!');
}
}
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
case '$':
case '*':
case '^':
case '|':
case '~':
return this.consumeAMatchToken() || this.consumeADelimToken();
case '-':
return this.consumeANumericToken() || this.consumeAnIdentLikeToken() || this.consumeCDC() || this.consumeADelimToken();
case '+':
case '.':
return this.consumeANumericToken() || this.consumeADelimToken();
case '/':
return this.consumeAComment() || this.consumeADelimToken();
case '<':
return this.consumeCDO() || this.consumeADelimToken();
case undefined:
return undefined;
default:
return this.consumeAnIdentLikeToken() || this.consumeADelimToken();
}
}
private consumeADelimToken(): InputToken {
return {
type: TokenObjectType.delim,
text: this.text[this.nextInputCodePointIndex++],
};
}
private consumeAWhitespace(): InputToken {
whitespaceRegEx.lastIndex = this.nextInputCodePointIndex;
whitespaceRegEx.exec(this.text);
this.nextInputCodePointIndex = whitespaceRegEx.lastIndex;
return ' ';
}
private consumeAHashToken(): InputTokenObject {
this.nextInputCodePointIndex++;
const hashName = this.consumeAName();
if (hashName) {
return { type: TokenObjectType.hash, text: '#' + hashName.text };
}
this.nextInputCodePointIndex--;
return null;
}
private consumeCDO(): '<!--' | null {
if (this.text.substr(this.nextInputCodePointIndex, 4) === '<!--') {
this.nextInputCodePointIndex += 4;
return '<!--';
}
return null;
}
private consumeCDC(): '-->' | null {
if (this.text.substr(this.nextInputCodePointIndex, 3) === '-->') {
this.nextInputCodePointIndex += 3;
return '-->';
}
return null;
}
private consumeAMatchToken(): '*=' | '$=' | '|=' | '~=' | '^=' | null {
if (this.text[this.nextInputCodePointIndex + 1] === '=') {
const token = this.text.substr(this.nextInputCodePointIndex, 2);
this.nextInputCodePointIndex += 2;
return <'*=' | '$=' | '|=' | '~=' | '^='>token;
}
return null;
}
/**
* 4.3.2. Consume a numeric token
* https://www.w3.org/TR/css-syntax-3/#consume-a-numeric-token
*/
private consumeANumericToken(): InputToken {
numberRegEx.lastIndex = this.nextInputCodePointIndex;
const result = numberRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = numberRegEx.lastIndex;
if (this.text[this.nextInputCodePointIndex] === '%') {
return { type: TokenObjectType.percentage, text: result[0] }; // TODO: Push the actual number and unit here...
}
const name = this.consumeAName();
if (name) {
return {
type: TokenObjectType.dimension,
text: result[0] + name.text,
};
}
return { type: TokenObjectType.number, text: result[0] };
}
/**
* 4.3.3. Consume an ident-like token
* https://www.w3.org/TR/css-syntax-3/#consume-an-ident-like-token
*/
private consumeAnIdentLikeToken(): InputToken {
const name = this.consumeAName();
if (!name) {
return null;
}
if (this.text[this.nextInputCodePointIndex] === '(') {
this.nextInputCodePointIndex++;
if (name.text.toLowerCase() === 'url') {
return this.consumeAURLToken();
}
return <FunctionInputToken>{
type: TokenObjectType.functionToken,
name: name.text,
text: name.text + '(',
};
}
return name;
}
/**
* 4.3.4. Consume a string token
* https://www.w3.org/TR/css-syntax-3/#consume-a-string-token
*/
private consumeAStringToken(): InputTokenObject {
const char = this.text[this.nextInputCodePointIndex];
let result: RegExpExecArray;
if (char === "'") {
singleQuoteStringRegEx.lastIndex = this.nextInputCodePointIndex;
result = singleQuoteStringRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = singleQuoteStringRegEx.lastIndex;
} else if (char === '"') {
doubleQuoteStringRegEx.lastIndex = this.nextInputCodePointIndex;
result = doubleQuoteStringRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = doubleQuoteStringRegEx.lastIndex;
}
// TODO: Handle bad-string.
// TODO: Perform string escaping.
return { type: TokenObjectType.string, text: result[0] };
}
/**
* 4.3.5. Consume a url token
* https://www.w3.org/TR/css-syntax-3/#consume-a-url-token
*/
private consumeAURLToken(): InputToken {
const start = this.nextInputCodePointIndex - 3 /* url */ - 1; /* ( */
const urlToken: InputToken = {
type: TokenObjectType.url,
text: undefined,
};
this.consumeAWhitespace();
if (this.nextInputCodePointIndex >= this.text.length) {
return urlToken;
}
const nextInputCodePoint = this.text[this.nextInputCodePointIndex];
if (nextInputCodePoint === '"' || nextInputCodePoint === "'") {
const stringToken = this.consumeAStringToken();
// TODO: Handle bad-string.
// TODO: Set value instead.
urlToken.text = stringToken.text;
this.consumeAWhitespace();
if (this.text[this.nextInputCodePointIndex] === ')' || this.nextInputCodePointIndex >= this.text.length) {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
urlToken.text = this.text.substring(start, end);
return urlToken;
} else {
// TODO: Handle bad-url.
return null;
}
}
while (this.nextInputCodePointIndex < this.text.length) {
const char = this.text[this.nextInputCodePointIndex++];
switch (char) {
case ')':
return urlToken;
case ' ':
case '\t':
case '\n':
case '\r':
case '\f':
this.consumeAWhitespace();
if (this.text[this.nextInputCodePointIndex] === ')') {
this.nextInputCodePointIndex++;
return urlToken;
} else {
// TODO: Bar url! Consume remnants.
return null;
}
case '"':
case "'":
// TODO: Parse error! Bar url! Consume remnants.
return null;
case '\\':
// TODO: Escape!
throw new Error('Escaping not yet supported!');
default:
// TODO: Non-printable chars - error.
urlToken.text += char;
}
}
return urlToken;
}
/**
* 4.3.11. Consume a name
* https://www.w3.org/TR/css-syntax-3/#consume-a-name
*/
private consumeAName(): InputTokenObject {
nameRegEx.lastIndex = this.nextInputCodePointIndex;
const result = nameRegEx.exec(this.text);
if (!result) {
return null;
}
this.nextInputCodePointIndex = nameRegEx.lastIndex;
// TODO: Perform string escaping.
return { type: TokenObjectType.ident, text: result[0] };
}
private consumeAtKeyword(): InputTokenObject {
this.nextInputCodePointIndex++;
const name = this.consumeAName();
if (name) {
return { type: TokenObjectType.atKeyword, text: name.text };
}
this.nextInputCodePointIndex--;
return null;
}
private consumeAComment(): InputToken {
if (this.text[this.nextInputCodePointIndex + 1] === '*') {
commentRegEx.lastIndex = this.nextInputCodePointIndex;
const result = commentRegEx.exec(this.text);
if (!result) {
return null; // TODO: Handle <bad-comment>
}
this.nextInputCodePointIndex = commentRegEx.lastIndex;
// The CSS spec tokenizer does not emmit comment tokens
return this.consumeAToken();
}
return null;
}
private reconsumeTheCurrentInputToken(currentInputToken: InputToken) {
this.reconsumedInputToken = currentInputToken;
}
/**
* 5.3.1. Parse a stylesheet
* https://www.w3.org/TR/css-syntax-3/#parse-a-stylesheet
*/
public parseAStylesheet(): Stylesheet {
this.topLevelFlag = true;
return {
rules: this.consumeAListOfRules(),
};
}
/**
* 5.4.1. Consume a list of rules
* https://www.w3.org/TR/css-syntax-3/#consume-a-list-of-rules
*/
public consumeAListOfRules(): Rule[] {
const rules: Rule[] = [];
let inputToken: InputToken;
while ((inputToken = this.consumeAToken())) {
switch (inputToken) {
case ' ':
continue;
case '<!--':
case '-->': {
if (this.topLevelFlag) {
continue;
}
this.reconsumeTheCurrentInputToken(inputToken);
const atRule = this.consumeAnAtRule();
if (atRule) {
rules.push(atRule);
}
continue;
}
}
if ((<InputTokenObject>inputToken).type === TokenObjectType.atKeyword) {
this.reconsumeTheCurrentInputToken(inputToken);
const atRule = this.consumeAnAtRule();
if (atRule) {
rules.push(atRule);
}
continue;
}
this.reconsumeTheCurrentInputToken(inputToken);
const qualifiedRule = this.consumeAQualifiedRule();
if (qualifiedRule) {
rules.push(qualifiedRule);
}
}
return rules;
}
/**
* 5.4.2. Consume an at-rule
* https://www.w3.org/TR/css-syntax-3/#consume-an-at-rule
*/
public consumeAnAtRule(): AtRule {
let inputToken = this.consumeAToken();
const atRule: AtRule = {
type: 'at-rule',
name: (<AtKeywordToken>inputToken).text,
prelude: [],
block: undefined,
};
while ((inputToken = this.consumeAToken())) {
if (inputToken === ';') {
return atRule;
} else if (inputToken === '{') {
atRule.block = this.consumeASimpleBlock(inputToken);
return atRule;
} else if ((<InputTokenObject>inputToken).type === TokenObjectType.simpleBlock && (<SimpleBlock>inputToken).associatedToken === '{') {
atRule.block = <SimpleBlock>inputToken;
return atRule;
}
this.reconsumeTheCurrentInputToken(inputToken);
const component = this.consumeAComponentValue();
if (component) {
atRule.prelude.push(component);
}
}
return atRule;
}
/**
* 5.4.3. Consume a qualified rule
* https://www.w3.org/TR/css-syntax-3/#consume-a-qualified-rule
*/
public consumeAQualifiedRule(): QualifiedRule {
const qualifiedRule: QualifiedRule = {
type: 'qualified-rule',
prelude: [],
block: undefined,
};
let inputToken: InputToken;
while ((inputToken = this.consumeAToken())) {
if (inputToken === '{') {
qualifiedRule.block = this.consumeASimpleBlock(inputToken);
return qualifiedRule;
} else if ((<InputTokenObject>inputToken).type === TokenObjectType.simpleBlock) {
const simpleBlock: SimpleBlock = <SimpleBlock>inputToken;
if (simpleBlock.associatedToken === '{') {
qualifiedRule.block = simpleBlock;
return qualifiedRule;
}
}
this.reconsumeTheCurrentInputToken(inputToken);
const componentValue = this.consumeAComponentValue();
if (componentValue) {
qualifiedRule.prelude.push(componentValue);
}
}
// TODO: This is a parse error, log parse errors!
return null;
}
/**
* 5.4.6. Consume a component value
* https://www.w3.org/TR/css-syntax-3/#consume-a-component-value
*/
private consumeAComponentValue(): InputToken {
// const inputToken = this.consumeAToken();
const inputToken = this.consumeAToken();
switch (inputToken) {
case '{':
case '[':
case '(':
this.nextInputCodePointIndex++;
return this.consumeASimpleBlock(inputToken);
}
if (typeof inputToken === 'object' && inputToken.type === TokenObjectType.functionToken) {
return this.consumeAFunction((<FunctionInputToken>inputToken).name);
}
return inputToken;
}
/**
* 5.4.7. Consume a simple block
* https://www.w3.org/TR/css-syntax-3/#consume-a-simple-block
*/
private consumeASimpleBlock(associatedToken: InputToken): SimpleBlock {
const endianToken: ']' | '}' | ')' = {
'[': ']',
'{': '}',
'(': ')',
}[<any>associatedToken];
const start = this.nextInputCodePointIndex - 1;
const block: SimpleBlock = {
type: TokenObjectType.simpleBlock,
text: undefined,
associatedToken,
values: [],
};
let nextInputToken;
while ((nextInputToken = this.text[this.nextInputCodePointIndex])) {
if (nextInputToken === endianToken) {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
block.text = this.text.substring(start, end);
return block;
}
const value = this.consumeAComponentValue();
if (value) {
block.values.push(value);
}
}
block.text = this.text.substring(start);
return block;
}
/**
* 5.4.8. Consume a function
* https://www.w3.org/TR/css-syntax-3/#consume-a-function
*/
private consumeAFunction(name: string): InputToken {
const start = this.nextInputCodePointIndex;
const funcToken: FunctionToken = {
type: TokenObjectType.function,
name,
text: undefined,
components: [],
};
// eslint-disable-next-line no-constant-condition
while (true) {
if (this.nextInputCodePointIndex >= this.text.length) {
funcToken.text = name + '(' + this.text.substring(start);
return funcToken;
}
const nextInputToken = this.text[this.nextInputCodePointIndex];
switch (nextInputToken) {
case ')': {
this.nextInputCodePointIndex++;
const end = this.nextInputCodePointIndex;
funcToken.text = name + '(' + this.text.substring(start, end);
return funcToken;
}
default: {
const component = this.consumeAComponentValue();
if (component) {
funcToken.components.push(component);
}
}
// TODO: Else we won't advance
}
}
}
}