Skip to content

Commit b2e2424

Browse files
committed
[csslib] Fix StateError on error tokens, polyfill var mutation, and cyclic mixins
- Guard `Token.toString()` in `identifier()`, `simpleSelector()`, and `processVariableOrDirective()` via `_safeTokenString` so `ERROR` and `UNTERMINATED_COMMENT` tokens do not throw `StateError('Unknown TOKEN')`. - Snapshot `Expressions.expressions` in `PolyFill.processVars` before `_findTerminalVarDefinition` mutates the list via `replaceRange`. - Prevent infinite node expansion on self-referential and cyclic `@mixin` / `@include` definitions in `TopLevelIncludes` and `DeclarationIncludes`, and guard `include.span is FileSpan` in `processMixin()`.
1 parent 31678c5 commit b2e2424

5 files changed

Lines changed: 63 additions & 14 deletions

File tree

‎pkgs/csslib/CHANGELOG.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
## 1.0.3-wip
22

3-
- Fix unhandled exceptions (`RangeError`, `FormatException`, `TypeError`,
4-
`StackOverflowError`, and `AssertionError`) and infinite loops across the
5-
tokenizer, parser, analyzer, polyfill pass, and printers when processing
6-
malformed or deeply nested CSS, SCSS, and Less inputs.
3+
- Fix unhandled exceptions (`RangeError`, `FormatException`, `StateError`,
4+
`ConcurrentModificationError`, `TypeError`, `StackOverflowError`, and
5+
`AssertionError`) and infinite loops across the tokenizer, parser, analyzer,
6+
polyfill pass, and printers when processing malformed or deeply nested CSS,
7+
SCSS, and Less inputs.
78

89
## 1.0.2
910

‎pkgs/csslib/lib/parser.dart‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,14 @@ class _Parser {
308308
_error(message, tok.span);
309309
}
310310

311+
String _safeTokenString(Token tok) {
312+
try {
313+
return tok.toString();
314+
} catch (_) {
315+
return tok.text;
316+
}
317+
}
318+
311319
void _error(String message, SourceSpan? location) {
312320
location ??= _peekToken.span;
313321
messages.error(message, location);
@@ -806,8 +814,11 @@ class _Parser {
806814
if (include is IncludeDirective) {
807815
newDecls.add(IncludeMixinAtDeclaration(include, include.span));
808816
} else {
809-
_warning('Error mixing of top-level vs declarations mixins',
810-
_makeSpan(include.span as FileSpan));
817+
_warning(
818+
'Error mixing of top-level vs declarations mixins',
819+
include.span is FileSpan
820+
? _makeSpan(include.span as FileSpan)
821+
: include.span);
811822
}
812823
}
813824
declGroup.declarations.insertAll(0, newDecls);
@@ -890,7 +901,8 @@ class _Parser {
890901
var span = _makeSpan(start);
891902
return VarDefinitionDirective(VarDefinition(name, exprs, span), span);
892903
} else if (isChecked) {
893-
_error('unexpected directive @$_peekToken', _peekToken.span);
904+
_error('unexpected directive @${_safeTokenString(_peekToken)}',
905+
_peekToken.span);
894906
}
895907
}
896908
} else if (mixinParameter && _peekToken.kind == TokenKind.VAR_DEFINITION) {
@@ -1470,7 +1482,9 @@ class _Parser {
14701482
element = identifier();
14711483
break;
14721484
default:
1473-
_error('expected element name or universal(*), but found $_peekToken',
1485+
_error(
1486+
'expected element name or universal(*), '
1487+
'but found ${_safeTokenString(_peekToken)}',
14741488
_peekToken.span);
14751489
element = Identifier('', _makeSpan(start));
14761490
break;
@@ -2716,7 +2730,8 @@ class _Parser {
27162730
if (!TokenKind.isIdentifier(tok.kind) &&
27172731
!TokenKind.isKindIdentifier(tok.kind)) {
27182732
if (isChecked) {
2719-
_warning('expected identifier, but found $tok', tok.span);
2733+
_warning('expected identifier, but found ${_safeTokenString(tok)}',
2734+
tok.span);
27202735
}
27212736
return Identifier('', _makeSpan(tok.span));
27222737
}

‎pkgs/csslib/lib/src/analyzer.dart‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,9 @@ class TopLevelIncludes extends Visitor {
482482
@override
483483
void visitIncludeDirective(IncludeDirective node) {
484484
final currDef = this.currDef;
485-
if (map.containsKey(node.name)) {
485+
if (currDef is MixinRulesetDirective && node.name == currDef.name) {
486+
currDef.rulesets.removeWhere((entry) => entry == node);
487+
} else if (map.containsKey(node.name)) {
486488
var mixinDef = map[node.name];
487489
if (mixinDef is MixinRulesetDirective) {
488490
_TopLevelIncludeReplacer.replace(_styleSheet!, node, mixinDef.rulesets);
@@ -536,6 +538,7 @@ class TopLevelIncludes extends Visitor {
536538

537539
/// @include as a top-level with ruleset(s).
538540
class _TopLevelIncludeReplacer extends Visitor {
541+
static const int _maxExpansions = 256;
539542
final IncludeDirective _include;
540543
final List<TreeNode> _newRules;
541544

@@ -553,7 +556,9 @@ class _TopLevelIncludeReplacer extends Visitor {
553556
void visitStyleSheet(StyleSheet node) {
554557
var index = node.topLevels.indexOf(_include);
555558
if (index != -1) {
556-
node.topLevels.insertAll(index + 1, _newRules);
559+
if (node.topLevels.length < _maxExpansions) {
560+
node.topLevels.insertAll(index + 1, _newRules);
561+
}
557562
node.topLevels.replaceRange(index, index + 1, [NoOp()]);
558563
}
559564
super.visitStyleSheet(node);
@@ -563,7 +568,9 @@ class _TopLevelIncludeReplacer extends Visitor {
563568
void visitMixinRulesetDirective(MixinRulesetDirective node) {
564569
var index = node.rulesets.indexOf(_include);
565570
if (index != -1) {
566-
node.rulesets.insertAll(index + 1, _newRules);
571+
if (node.rulesets.length < _maxExpansions) {
572+
node.rulesets.insertAll(index + 1, _newRules);
573+
}
567574
// Only the resolve the @include once.
568575
node.rulesets.replaceRange(index, index + 1, [NoOp()]);
569576
}
@@ -882,6 +889,7 @@ class DeclarationIncludes extends Visitor {
882889

883890
/// @include as a top-level with ruleset(s).
884891
class _IncludeReplacer extends Visitor {
892+
static const int _maxExpansions = 256;
885893
final TreeNode _include;
886894
final List<TreeNode> _newDeclarations;
887895

@@ -899,7 +907,9 @@ class _IncludeReplacer extends Visitor {
899907
void visitDeclarationGroup(DeclarationGroup node) {
900908
var index = _findInclude(node.declarations, _include);
901909
if (index != -1) {
902-
node.declarations.insertAll(index + 1, _newDeclarations);
910+
if (node.declarations.length < _maxExpansions) {
911+
node.declarations.insertAll(index + 1, _newDeclarations);
912+
}
903913
// Change @include to NoOp so it's processed only once.
904914
node.declarations.replaceRange(index, index + 1, [NoOp()]);
905915
}

‎pkgs/csslib/lib/src/polyfill.dart‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class PolyFill {
4747
// Resolve all definitions to a non-VarUsage (terminal expression).
4848
mainStyleSheetVarDefs.forEach((key, value) {
4949
if (value.expression is Expressions) {
50-
for (var _ in (value.expression as Expressions).expressions) {
50+
for (var _ in (value.expression as Expressions).expressions.toList()) {
5151
mainStyleSheetVarDefs[key] =
5252
_findTerminalVarDefinition(_allVarDefinitions, value);
5353
}

‎pkgs/csslib/test/error_test.dart‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,12 +431,21 @@ void main() {
431431
_exerciseAllEntryPoints('@: 1px; a { var-: 2px; }');
432432
_exerciseAllEntryPoints(
433433
'@mixin m(@a) { color: @a; } @include ; a { @include m(); }');
434+
_exerciseAllEntryPoints(
435+
'@mixin m { @media screen { } color: red; } @include m;');
436+
_exerciseAllEntryPoints(
437+
'@mixin a { color: red; } @mixin a { @include a; } '
438+
'@include a; div { @include a; }');
439+
_exerciseAllEntryPoints(
440+
'@mixin b { color: red; } @mixin a { @include b; } '
441+
'@mixin b { @include a; } div { @include b; }');
434442
});
435443

436444
test('malformed @-moz-document and @supports directives', () {
437445
_exerciseAllEntryPoints(
438446
'@-moz-document regexp(".*"), foo(1), url-prefix() '
439447
'{ a { top: 0; } }');
448+
_exerciseAllEntryPoints('@-moz-document\uFFFDfoo(1) { a { top: 0; } }');
440449
_exerciseAllEntryPoints('@-moz-document { }');
441450
_exerciseAllEntryPoints('@supports () { } @supports not () { }');
442451
_exerciseAllEntryPoints('@supports (a: 1) and () { }');
@@ -457,6 +466,7 @@ void main() {
457466
test('malformed selectors, namespace selectors, and selector expressions',
458467
() {
459468
_exerciseAllEntryPoints('ns| { color: red; } | { color: blue; }');
469+
_exerciseAllEntryPoints('ns|\uFFFD { color: red; }');
460470
_exerciseAllEntryPoints(
461471
':not(ns|a) { color: red; } :not(ns|) { color: blue; }');
462472
expect(NamespaceSelector(null, '', null).clone().toString(), '|');
@@ -478,6 +488,18 @@ void main() {
478488
_exerciseAllEntryPoints(
479489
'a { color: #@foo; width: (@foo); height: [@foo]; top: @; }');
480490
_exerciseAllEntryPoints('a { color: var(); background: var(123); }');
491+
final errors = <Message>[];
492+
parse(
493+
'@\uFFFD { }',
494+
errors: errors,
495+
options: const PreprocessorOptions(
496+
useColors: false,
497+
checked: true,
498+
lessSupport: false,
499+
inputFile: 'memory',
500+
),
501+
);
502+
expect(errors, isNotEmpty);
481503
});
482504

483505
test('nested selectors inside directives and cyclic @extend / var()', () {
@@ -489,6 +511,7 @@ void main() {
489511
_exerciseAllEntryPoints(
490512
'@media screen { @media print { a { b { color: red; } } } }');
491513
_exerciseAllEntryPoints('a { @extend .b; } .b { @extend a; }');
514+
_exerciseAllEntryPoints('@namespefix; @name @name;');
492515
_exerciseAllEntryPoints('var-a: var(a); var-b: var(c); var-c: var(b); '
493516
'a { color: var(a); width: var(b, var(c)); '
494517
'height: var(u, 1px var(a)); }');

0 commit comments

Comments
 (0)