-
Notifications
You must be signed in to change notification settings - Fork 38
/
parser.dart
2959 lines (2611 loc) · 92.1 KB
/
parser.dart
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) 2012, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library csslib.parser;
import 'dart:math' as math;
import 'package:source_span/source_span.dart';
import 'src/messages.dart';
import 'src/options.dart';
import 'visitor.dart';
export 'src/messages.dart' show Message;
export 'src/options.dart';
part 'src/analyzer.dart';
part 'src/polyfill.dart';
part 'src/property.dart';
part 'src/token.dart';
part 'src/tokenizer_base.dart';
part 'src/tokenizer.dart';
part 'src/tokenkind.dart';
enum ClauseType {
none,
conjunction,
disjunction,
}
/** Used for parser lookup ahead (used for nested selectors Less support). */
class ParserState extends TokenizerState {
final Token peekToken;
final Token previousToken;
ParserState(this.peekToken, this.previousToken, Tokenizer tokenizer)
: super(tokenizer);
}
// TODO(jmesserly): this should not be global
void _createMessages({List<Message> errors, PreprocessorOptions options}) {
if (errors == null) errors = [];
if (options == null) {
options = new PreprocessorOptions(useColors: false, inputFile: 'memory');
}
messages = new Messages(options: options, printHandler: errors.add);
}
/** CSS checked mode enabled. */
bool get isChecked => messages.options.checked;
// TODO(terry): Remove nested name parameter.
/** Parse and analyze the CSS file. */
StyleSheet compile(input,
{List<Message> errors,
PreprocessorOptions options,
bool nested: true,
bool polyfill: false,
List<StyleSheet> includes: null}) {
if (includes == null) {
includes = [];
}
var source = _inputAsString(input);
_createMessages(errors: errors, options: options);
var file = new SourceFile.fromString(source);
var tree = new _Parser(file, source).parse();
analyze([tree], errors: errors, options: options);
if (polyfill) {
var processCss = new PolyFill(messages);
processCss.process(tree, includes: includes);
}
return tree;
}
/** Analyze the CSS file. */
void analyze(List<StyleSheet> styleSheets,
{List<Message> errors, PreprocessorOptions options}) {
_createMessages(errors: errors, options: options);
new Analyzer(styleSheets, messages).run();
}
/**
* Parse the [input] CSS stylesheet into a tree. The [input] can be a [String],
* or [List<int>] of bytes and returns a [StyleSheet] AST. The optional
* [errors] list will contain each error/warning as a [Message].
*/
StyleSheet parse(input, {List<Message> errors, PreprocessorOptions options}) {
var source = _inputAsString(input);
_createMessages(errors: errors, options: options);
var file = new SourceFile.fromString(source);
return new _Parser(file, source).parse();
}
/**
* Parse the [input] CSS selector into a tree. The [input] can be a [String],
* or [List<int>] of bytes and returns a [StyleSheet] AST. The optional
* [errors] list will contain each error/warning as a [Message].
*/
// TODO(jmesserly): should rename "parseSelector" and return Selector
StyleSheet selector(input, {List<Message> errors}) {
var source = _inputAsString(input);
_createMessages(errors: errors);
var file = new SourceFile.fromString(source);
return (new _Parser(file, source)..tokenizer.inSelector = true)
.parseSelector();
}
SelectorGroup parseSelectorGroup(input, {List<Message> errors}) {
var source = _inputAsString(input);
_createMessages(errors: errors);
var file = new SourceFile.fromString(source);
return (new _Parser(file, source)
// TODO(jmesserly): this fix should be applied to the parser. It's tricky
// because by the time the flag is set one token has already been fetched.
..tokenizer.inSelector = true)
.processSelectorGroup();
}
String _inputAsString(input) {
String source;
if (input is String) {
source = input;
} else if (input is List) {
// TODO(terry): The parse function needs an "encoding" argument and will
// default to whatever encoding CSS defaults to.
//
// Here's some info about CSS encodings:
// http://www.w3.org/International/questions/qa-css-charset.en.php
//
// As JMesserly suggests it will probably need a "preparser" html5lib
// (encoding_parser.dart) that interprets the bytes as ASCII and scans for
// @charset. But for now an "encoding" argument would work. Often the
// HTTP header will indicate the correct encoding.
//
// See encoding helpers at: package:html5lib/lib/src/char_encodings.dart
// These helpers can decode in different formats given an encoding name
// (mostly unicode, ascii, windows-1252 which is html5 default encoding).
source = new String.fromCharCodes(input as List<int>);
} else {
// TODO(terry): Support RandomAccessFile using console.
throw new ArgumentError("'source' must be a String or "
"List<int> (of bytes). RandomAccessFile not supported from this "
"simple interface");
}
return source;
}
// TODO(terry): Consider removing this class when all usages can be eliminated
// or replaced with compile API.
/** Public parsing interface for csslib. */
class Parser {
final _Parser _parser;
// TODO(jmesserly): having file and text is redundant.
// TODO(rnystrom): baseUrl isn't used. Remove from API.
Parser(SourceFile file, String text, {int start: 0, String baseUrl})
: _parser = new _Parser(file, text, start: start);
StyleSheet parse() => _parser.parse();
}
// CSS2.1 pseudo-elements which were defined with a single ':'.
final _legacyPseudoElements = new Set<String>.from(const [
'after',
'before',
'first-letter',
'first-line',
]);
/** A simple recursive descent parser for CSS. */
class _Parser {
final Tokenizer tokenizer;
/**
* File containing the source being parsed, used to report errors with
* source-span locations.
*/
final SourceFile file;
Token _previousToken;
Token _peekToken;
_Parser(SourceFile file, String text, {int start: 0})
: this.file = file,
tokenizer = new Tokenizer(file, text, true, start) {
_peekToken = tokenizer.next();
}
/** Main entry point for parsing an entire CSS file. */
StyleSheet parse() {
List<TreeNode> productions = [];
var start = _peekToken.span;
while (!_maybeEat(TokenKind.END_OF_FILE) && !_peekKind(TokenKind.RBRACE)) {
// TODO(terry): Need to handle charset.
final rule = processRule();
if (rule != null) {
productions.add(rule);
} else {
break;
}
}
checkEndOfFile();
return new StyleSheet(productions, _makeSpan(start));
}
/** Main entry point for parsing a simple selector sequence. */
StyleSheet parseSelector() {
List<TreeNode> productions = [];
var start = _peekToken.span;
while (!_maybeEat(TokenKind.END_OF_FILE) && !_peekKind(TokenKind.RBRACE)) {
var selector = processSelector();
if (selector != null) {
productions.add(selector);
}
}
checkEndOfFile();
return new StyleSheet.selector(productions, _makeSpan(start));
}
/** Generate an error if [file] has not been completely consumed. */
void checkEndOfFile() {
if (!(_peekKind(TokenKind.END_OF_FILE) ||
_peekKind(TokenKind.INCOMPLETE_COMMENT))) {
_error('premature end of file unknown CSS', _peekToken.span);
}
}
/** Guard to break out of parser when an unexpected end of file is found. */
// TODO(jimhug): Failure to call this method can lead to inifinite parser
// loops. Consider embracing exceptions for more errors to reduce
// the danger here.
bool isPrematureEndOfFile() {
if (_maybeEat(TokenKind.END_OF_FILE)) {
_error('unexpected end of file', _peekToken.span);
return true;
} else {
return false;
}
}
///////////////////////////////////////////////////////////////////
// Basic support methods
///////////////////////////////////////////////////////////////////
int _peek() {
return _peekToken.kind;
}
Token _next({unicodeRange: false}) {
_previousToken = _peekToken;
_peekToken = tokenizer.next(unicodeRange: unicodeRange);
return _previousToken;
}
bool _peekKind(int kind) {
return _peekToken.kind == kind;
}
/* Is the next token a legal identifier? This includes pseudo-keywords. */
bool _peekIdentifier() {
return TokenKind.isIdentifier(_peekToken.kind);
}
/** Marks the parser/tokenizer look ahead to support Less nested selectors. */
ParserState get _mark =>
new ParserState(_peekToken, _previousToken, tokenizer);
/** Restores the parser/tokenizer state to state remembered by _mark. */
void _restore(ParserState markedData) {
tokenizer.restore(markedData);
_peekToken = markedData.peekToken;
_previousToken = markedData.previousToken;
}
bool _maybeEat(int kind, {unicodeRange: false}) {
if (_peekToken.kind == kind) {
_previousToken = _peekToken;
_peekToken = tokenizer.next(unicodeRange: unicodeRange);
return true;
} else {
return false;
}
}
void _eat(int kind, {unicodeRange: false}) {
if (!_maybeEat(kind, unicodeRange: unicodeRange)) {
_errorExpected(TokenKind.kindToString(kind));
}
}
void _errorExpected(String expected) {
var tok = _next();
var message;
try {
message = 'expected $expected, but found $tok';
} catch (e) {
message = 'parsing error expected $expected';
}
_error(message, tok.span);
}
void _error(String message, SourceSpan location) {
if (location == null) {
location = _peekToken.span;
}
messages.error(message, location);
}
void _warning(String message, SourceSpan location) {
if (location == null) {
location = _peekToken.span;
}
messages.warning(message, location);
}
SourceSpan _makeSpan(FileSpan start) {
// TODO(terry): there are places where we are creating spans before we eat
// the tokens, so using _previousToken is not always valid.
// TODO(nweiz): use < rather than compareTo when SourceSpan supports it.
if (_previousToken == null || _previousToken.span.compareTo(start) < 0) {
return start;
}
return start.expand(_previousToken.span);
}
///////////////////////////////////////////////////////////////////
// Top level productions
///////////////////////////////////////////////////////////////////
/**
* The media_query_list production below replaces the media_list production
* from CSS2 the new grammar is:
*
* media_query_list
* : S* [media_query [ ',' S* media_query ]* ]?
* media_query
* : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
* | expression [ AND S* expression ]*
* media_type
* : IDENT
* expression
* : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
* media_feature
* : IDENT
*/
List<MediaQuery> processMediaQueryList() {
var mediaQueries = <MediaQuery>[];
do {
var mediaQuery = processMediaQuery();
if (mediaQuery != null) {
mediaQueries.add(mediaQuery);
} else {
break;
}
} while (_maybeEat(TokenKind.COMMA));
return mediaQueries;
}
MediaQuery processMediaQuery() {
// Grammar: [ONLY | NOT]? S* media_type S*
// [ AND S* MediaExpr ]* | MediaExpr [ AND S* MediaExpr ]*
var start = _peekToken.span;
// Is it a unary media operator?
var op = _peekToken.text;
var opLen = op.length;
var unaryOp = TokenKind.matchMediaOperator(op, 0, opLen);
if (unaryOp != -1) {
if (isChecked) {
if (unaryOp != TokenKind.MEDIA_OP_NOT ||
unaryOp != TokenKind.MEDIA_OP_ONLY) {
_warning("Only the unary operators NOT and ONLY allowed",
_makeSpan(start));
}
}
_next();
start = _peekToken.span;
}
var type;
// Get the media type.
if (_peekIdentifier()) type = identifier();
var exprs = <MediaExpression>[];
while (true) {
// Parse AND if query has a media_type or previous expression.
var andOp = exprs.isNotEmpty || type != null;
if (andOp) {
op = _peekToken.text;
opLen = op.length;
if (TokenKind.matchMediaOperator(op, 0, opLen) !=
TokenKind.MEDIA_OP_AND) {
break;
}
_next();
}
var expr = processMediaExpression(andOp);
if (expr == null) break;
exprs.add(expr);
}
if (unaryOp != -1 || type != null || exprs.length > 0) {
return new MediaQuery(unaryOp, type, exprs, _makeSpan(start));
}
return null;
}
MediaExpression processMediaExpression([bool andOperator = false]) {
var start = _peekToken.span;
// Grammar: '(' S* media_feature S* [ ':' S* expr ]? ')' S*
if (_maybeEat(TokenKind.LPAREN)) {
if (_peekIdentifier()) {
var feature = identifier(); // Media feature.
var exprs = _maybeEat(TokenKind.COLON)
? processExpr()
: new Expressions(_makeSpan(_peekToken.span));
if (_maybeEat(TokenKind.RPAREN)) {
return new MediaExpression(
andOperator, feature, exprs, _makeSpan(start));
} else if (isChecked) {
_warning(
"Missing parenthesis around media expression", _makeSpan(start));
return null;
}
} else if (isChecked) {
_warning("Missing media feature in media expression", _makeSpan(start));
}
}
return null;
}
/**
* Directive grammar:
*
* import: '@import' [string | URI] media_list?
* media: '@media' media_query_list '{' ruleset '}'
* page: '@page' [':' IDENT]? '{' declarations '}'
* stylet: '@stylet' IDENT '{' ruleset '}'
* media_query_list: IDENT [',' IDENT]
* keyframes: '@-webkit-keyframes ...' (see grammar below).
* font_face: '@font-face' '{' declarations '}'
* namespace: '@namespace name url("xmlns")
* host: '@host '{' ruleset '}'
* mixin: '@mixin name [(args,...)] '{' declarations/ruleset '}'
* include: '@include name [(@arg,@arg1)]
* '@include name [(@arg...)]
* content: '@content'
* -moz-document: '@-moz-document' [ <url> | url-prefix(<string>) |
* domain(<string>) | regexp(<string) ]# '{'
* declarations
* '}'
* supports: '@supports' supports_condition group_rule_body
*/
processDirective() {
var start = _peekToken.span;
var tokId = processVariableOrDirective();
if (tokId is VarDefinitionDirective) return tokId;
switch (tokId) {
case TokenKind.DIRECTIVE_IMPORT:
_next();
// @import "uri_string" or @import url("uri_string") are identical; only
// a url can follow an @import.
String importStr;
if (_peekIdentifier()) {
var func = processFunction(identifier());
if (func is UriTerm) {
importStr = func.text;
}
} else {
importStr = processQuotedString(false);
}
// Any medias?
var medias = processMediaQueryList();
if (importStr == null) {
_error('missing import string', _peekToken.span);
}
return new ImportDirective(importStr.trim(), medias, _makeSpan(start));
case TokenKind.DIRECTIVE_MEDIA:
_next();
// Any medias?
var media = processMediaQueryList();
List<TreeNode> rules = [];
if (_maybeEat(TokenKind.LBRACE)) {
while (!_maybeEat(TokenKind.END_OF_FILE)) {
final rule = processRule();
if (rule == null) break;
rules.add(rule);
}
if (!_maybeEat(TokenKind.RBRACE)) {
_error('expected } after ruleset for @media', _peekToken.span);
}
} else {
_error('expected { after media before ruleset', _peekToken.span);
}
return new MediaDirective(media, rules, _makeSpan(start));
case TokenKind.DIRECTIVE_HOST:
_next();
List<TreeNode> rules = [];
if (_maybeEat(TokenKind.LBRACE)) {
while (!_maybeEat(TokenKind.END_OF_FILE)) {
final rule = processRule();
if (rule == null) break;
rules.add(rule);
}
if (!_maybeEat(TokenKind.RBRACE)) {
_error('expected } after ruleset for @host', _peekToken.span);
}
} else {
_error('expected { after host before ruleset', _peekToken.span);
}
return new HostDirective(rules, _makeSpan(start));
case TokenKind.DIRECTIVE_PAGE:
/*
* @page S* IDENT? pseudo_page?
* S* '{' S*
* [ declaration | margin ]?
* [ ';' S* [ declaration | margin ]? ]* '}' S*
*
* pseudo_page :
* ':' [ "left" | "right" | "first" ]
*
* margin :
* margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
*
* margin_sym : @top-left-corner, @top-left, @bottom-left, etc.
*
* See http://www.w3.org/TR/css3-page/#CSS21
*/
_next();
// Page name
var name;
if (_peekIdentifier()) {
name = identifier();
}
// Any pseudo page?
var pseudoPage;
if (_maybeEat(TokenKind.COLON)) {
if (_peekIdentifier()) {
pseudoPage = identifier();
// TODO(terry): Normalize pseudoPage to lowercase.
if (isChecked &&
!(pseudoPage.name == 'left' ||
pseudoPage.name == 'right' ||
pseudoPage.name == 'first')) {
_warning(
"Pseudo page must be left, top or first", pseudoPage.span);
return null;
}
}
}
String pseudoName = pseudoPage is Identifier ? pseudoPage.name : '';
String ident = name is Identifier ? name.name : '';
return new PageDirective(
ident, pseudoName, processMarginsDeclarations(), _makeSpan(start));
case TokenKind.DIRECTIVE_CHARSET:
// @charset S* STRING S* ';'
_next();
var charEncoding = processQuotedString(false);
if (isChecked && charEncoding == null) {
// Missing character encoding.
_warning('missing character encoding string', _makeSpan(start));
}
return new CharsetDirective(charEncoding, _makeSpan(start));
// TODO(terry): Workaround Dart2js bug continue not implemented in switch
// see https://code.google.com/p/dart/issues/detail?id=8270
/*
case TokenKind.DIRECTIVE_MS_KEYFRAMES:
// TODO(terry): For now only IE 10 (are base level) supports @keyframes,
// -moz- has only been optional since Oct 2012 release of Firefox, not
// all versions of webkit support @keyframes and opera doesn't yet
// support w/o -o- prefix. Add more warnings for other prefixes when
// they become optional.
if (isChecked) {
_warning('@-ms-keyframes should be @keyframes', _makeSpan(start));
}
continue keyframeDirective;
keyframeDirective:
*/
case TokenKind.DIRECTIVE_KEYFRAMES:
case TokenKind.DIRECTIVE_WEB_KIT_KEYFRAMES:
case TokenKind.DIRECTIVE_MOZ_KEYFRAMES:
case TokenKind.DIRECTIVE_O_KEYFRAMES:
// TODO(terry): Remove workaround when bug 8270 is fixed.
case TokenKind.DIRECTIVE_MS_KEYFRAMES:
if (tokId == TokenKind.DIRECTIVE_MS_KEYFRAMES && isChecked) {
_warning('@-ms-keyframes should be @keyframes', _makeSpan(start));
}
// TODO(terry): End of workaround.
/* Key frames grammar:
*
* @[browser]? keyframes [IDENT|STRING] '{' keyframes-blocks '}';
*
* browser: [-webkit-, -moz-, -ms-, -o-]
*
* keyframes-blocks:
* [keyframe-selectors '{' declarations '}']* ;
*
* keyframe-selectors:
* ['from'|'to'|PERCENTAGE] [',' ['from'|'to'|PERCENTAGE] ]* ;
*/
_next();
var name;
if (_peekIdentifier()) {
name = identifier();
}
_eat(TokenKind.LBRACE);
var keyframe = new KeyFrameDirective(tokId, name, _makeSpan(start));
do {
Expressions selectors = new Expressions(_makeSpan(start));
do {
var term = processTerm();
// TODO(terry): Only allow from, to and PERCENTAGE ...
selectors.add(term);
} while (_maybeEat(TokenKind.COMMA));
keyframe.add(new KeyFrameBlock(
selectors, processDeclarations(), _makeSpan(start)));
} while (!_maybeEat(TokenKind.RBRACE) && !isPrematureEndOfFile());
return keyframe;
case TokenKind.DIRECTIVE_FONTFACE:
_next();
return new FontFaceDirective(processDeclarations(), _makeSpan(start));
case TokenKind.DIRECTIVE_STYLET:
/* Stylet grammar:
*
* @stylet IDENT '{'
* ruleset
* '}'
*/
_next();
var name;
if (_peekIdentifier()) {
name = identifier();
}
_eat(TokenKind.LBRACE);
List<TreeNode> productions = [];
start = _peekToken.span;
while (!_maybeEat(TokenKind.END_OF_FILE)) {
final rule = processRule();
if (rule == null) {
break;
}
productions.add(rule);
}
_eat(TokenKind.RBRACE);
return new StyletDirective(name, productions, _makeSpan(start));
case TokenKind.DIRECTIVE_NAMESPACE:
/* Namespace grammar:
*
* @namespace S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
* namespace_prefix : IDENT
*
*/
_next();
var prefix;
if (_peekIdentifier()) {
prefix = identifier();
}
// The namespace URI can be either a quoted string url("uri_string")
// are identical.
String namespaceUri;
if (_peekIdentifier()) {
var func = processFunction(identifier());
if (func is UriTerm) {
namespaceUri = func.text;
}
} else {
if (prefix != null && prefix.name == 'url') {
var func = processFunction(prefix);
if (func is UriTerm) {
// @namespace url("");
namespaceUri = func.text;
prefix = null;
}
} else {
namespaceUri = processQuotedString(false);
}
}
return new NamespaceDirective(
prefix != null ? prefix.name : '', namespaceUri, _makeSpan(start));
case TokenKind.DIRECTIVE_MIXIN:
return processMixin();
case TokenKind.DIRECTIVE_INCLUDE:
return processInclude(_makeSpan(start));
case TokenKind.DIRECTIVE_CONTENT:
// TODO(terry): TBD
_warning("@content not implemented.", _makeSpan(start));
return null;
case TokenKind.DIRECTIVE_MOZ_DOCUMENT:
return processDocumentDirective();
case TokenKind.DIRECTIVE_SUPPORTS:
return processSupportsDirective();
case TokenKind.DIRECTIVE_VIEWPORT:
case TokenKind.DIRECTIVE_MS_VIEWPORT:
return processViewportDirective();
}
return null;
}
/**
* Parse the mixin beginning token offset [start]. Returns a [MixinDefinition]
* node.
*
* Mixin grammar:
*
* @mixin IDENT [(args,...)] '{'
* [ruleset | property | directive]*
* '}'
*/
MixinDefinition processMixin() {
_next();
var name = identifier();
var params = <TreeNode>[];
// Any parameters?
if (_maybeEat(TokenKind.LPAREN)) {
var mustHaveParam = false;
var keepGoing = true;
while (keepGoing) {
var varDef = processVariableOrDirective(mixinParameter: true);
if (varDef is VarDefinitionDirective || varDef is VarDefinition) {
params.add(varDef);
} else if (mustHaveParam) {
_warning("Expecting parameter", _makeSpan(_peekToken.span));
keepGoing = false;
}
if (_maybeEat(TokenKind.COMMA)) {
mustHaveParam = true;
continue;
}
keepGoing = !_maybeEat(TokenKind.RPAREN);
}
}
_eat(TokenKind.LBRACE);
List<TreeNode> productions = [];
var mixinDirective;
var start = _peekToken.span;
while (!_maybeEat(TokenKind.END_OF_FILE)) {
var directive = processDirective();
if (directive != null) {
productions.add(directive);
continue;
}
var declGroup = processDeclarations(checkBrace: false);
if (declGroup.declarations.any((decl) {
return decl is Declaration && decl is! IncludeMixinAtDeclaration;
})) {
var newDecls = <Declaration>[];
productions.forEach((include) {
// If declGroup has items that are declarations then we assume
// this mixin is a declaration mixin not a top-level mixin.
if (include is IncludeDirective) {
newDecls.add(new IncludeMixinAtDeclaration(include, include.span));
} else {
_warning("Error mixing of top-level vs declarations mixins",
_makeSpan(include.span));
}
});
declGroup.declarations.insertAll(0, newDecls);
productions = [];
} else {
// Declarations are just @includes make it a list of productions
// not a declaration group (anything else is a ruleset). Make it a
// list of productions, not a declaration group.
for (var decl in declGroup.declarations) {
productions
.add(decl is IncludeMixinAtDeclaration ? decl.include : decl);
}
;
declGroup.declarations.clear();
}
if (declGroup.declarations.isNotEmpty) {
if (productions.isEmpty) {
mixinDirective = new MixinDeclarationDirective(
name.name, params, false, declGroup, _makeSpan(start));
break;
} else {
for (var decl in declGroup.declarations) {
productions
.add(decl is IncludeMixinAtDeclaration ? decl.include : decl);
}
}
} else {
mixinDirective = new MixinRulesetDirective(
name.name, params, false, productions, _makeSpan(start));
break;
}
}
if (productions.isNotEmpty) {
mixinDirective = new MixinRulesetDirective(
name.name, params, false, productions, _makeSpan(start));
}
_eat(TokenKind.RBRACE);
return mixinDirective;
}
/**
* Returns a VarDefinitionDirective or VarDefinition if a varaible otherwise
* return the token id of a directive or -1 if neither.
*/
processVariableOrDirective({bool mixinParameter: false}) {
var start = _peekToken.span;
var tokId = _peek();
// Handle case for @ directive (where there's a whitespace between the @
// sign and the directive name. Technically, it's not valid grammar but
// a number of CSS tests test for whitespace between @ and name.
if (tokId == TokenKind.AT) {
_next();
tokId = _peek();
if (_peekIdentifier()) {
// Is it a directive?
var directive = _peekToken.text;
var directiveLen = directive.length;
tokId = TokenKind.matchDirectives(directive, 0, directiveLen);
if (tokId == -1) {
tokId = TokenKind.matchMarginDirectives(directive, 0, directiveLen);
}
}
if (tokId == -1) {
if (messages.options.lessSupport) {
// Less compatibility:
// @name: value; => var-name: value; (VarDefinition)
// property: @name; => property: var(name); (VarUsage)
var name;
if (_peekIdentifier()) {
name = identifier();
}
Expressions exprs;
if (mixinParameter && _maybeEat(TokenKind.COLON)) {
exprs = processExpr();
} else if (!mixinParameter) {
_eat(TokenKind.COLON);
exprs = processExpr();
}
var span = _makeSpan(start);
return new VarDefinitionDirective(
new VarDefinition(name, exprs, span), span);
} else if (isChecked) {
_error('unexpected directive @$_peekToken', _peekToken.span);
}
}
} else if (mixinParameter && _peekToken.kind == TokenKind.VAR_DEFINITION) {
_next();
var definedName;
if (_peekIdentifier()) definedName = identifier();
Expressions exprs;
if (_maybeEat(TokenKind.COLON)) {
exprs = processExpr();
}
return new VarDefinition(definedName, exprs, _makeSpan(start));
}
return tokId;
}
IncludeDirective processInclude(SourceSpan span, {bool eatSemiColon: true}) {
/* Stylet grammar:
*
* @include IDENT [(args,...)];
*/
_next();
var name;
if (_peekIdentifier()) {
name = identifier();
}
var params = <List<Expression>>[];
// Any parameters? Parameters can be multiple terms per argument e.g.,
// 3px solid yellow, green is two parameters:
// 1. 3px solid yellow
// 2. green
// the first has 3 terms and the second has 1 term.
if (_maybeEat(TokenKind.LPAREN)) {
var terms = <Expression>[];
var expr;
var keepGoing = true;
while (keepGoing && (expr = processTerm()) != null) {
// VarUsage is returns as a list
terms.add(expr is List ? expr[0] : expr);
keepGoing = !_peekKind(TokenKind.RPAREN);
if (keepGoing) {
if (_maybeEat(TokenKind.COMMA)) {
params.add(terms);
terms = [];
}
}
}
params.add(terms);
_maybeEat(TokenKind.RPAREN);
}
if (eatSemiColon) {
_eat(TokenKind.SEMICOLON);
}
return new IncludeDirective(name.name, params, span);
}
DocumentDirective processDocumentDirective() {
var start = _peekToken.span;
_next(); // '@-moz-document'
var functions = <LiteralTerm>[];
do {
var function;
// Consume function token: IDENT '('
var ident = identifier();
_eat(TokenKind.LPAREN);