Skip to content

Commit afddfc5

Browse files
authored
Don't treat /* inside an unquoted url(…) as a comment in the CSS parser (#20699)
This PR fixes a bug in our CSS parser where a `/*` inside an unquoted `url(…)` was treated as the start of a comment. Per [CSS Syntax 3](https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token), `url(` (case-insensitive) followed by a character that is not a quote starts a single url token, which ends at the first unescaped `)`. Comments are only recognized at the start of a token, so a `/*` inside of the url is just text. Before this change: ```css /* Input */ .a { background-image: url(/b/*.png); } .b { color: red; } /* Output: the url silently lost a `/` */ .a { background-image: url(/b*.png); } .b { color: red; } ``` And when a real comment followed later in the file, the "comment" ran until that comment's `*/` and the parser threw `Missing closing } at .a`. The same happened in at-rule params (e.g. `@import url(/b/*.css);`), and in custom properties when a comment followed. The fix is small: when the parser sees a `(` that follows the ident `url`, and the next non-whitespace character is not a quote, it consumes everything up to the first unescaped `)` as one unit. This is done in the main loop (declarations, selectors, at-rules) and in the custom property loop. A quoted `url("…")` is a regular function with a string, and keeps the existing behavior. A function like `my-url(…)` is not a url token either. A quote or `(` inside of an unquoted url makes a "bad url" per spec. This PR keeps the current behavior for those. Related: postcss/postcss#2194, the same class of bug in PostCSS. ## Test plan Added tests to `css-parser.test.ts`, which fail without this change: - `url(/b/*.png)` keeps its `/` - A comment after `url(/b/*.png)` does not throw - `URL(/b/*.png)`, `url( /b/*.png )`, and `url(a.png),url(/b/*.png)` - An at-rule param with an unquoted url - A custom property with an unquoted url, followed by a comment And two tests to guard existing behavior: a real comment next to a `url(…)` is still removed, and a `/*` inside of `my-url(…)` is still a comment.
1 parent 1d61682 commit afddfc5

3 files changed

Lines changed: 288 additions & 2 deletions

File tree

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
### Fixed
2+
3+
- Don't treat `/*` inside an unquoted `url(…)` as the start of a comment in the CSS parser

‎packages/tailwindcss/src/css-parser.test.ts‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,165 @@ describe.each(['Unix', 'Windows'])('Line endings: %s', (lineEndings) => {
169169
},
170170
])
171171
})
172+
173+
describe('unquoted `url(…)`', () => {
174+
function rule(selector: string, property: string, value: string) {
175+
return {
176+
kind: 'rule',
177+
selector,
178+
nodes: [{ kind: 'declaration', property, value, important: false }],
179+
}
180+
}
181+
182+
it('should not treat `/*` inside of an unquoted `url(…)` as a comment', () => {
183+
expect(parse('.a{background-image:url(/b/*.png)}.b{color:red}')).toEqual([
184+
rule('.a', 'background-image', 'url(/b/*.png)'),
185+
rule('.b', 'color', 'red'),
186+
])
187+
})
188+
189+
it('should not treat `/*` inside of an unquoted `url(…)` as a comment when a comment follows', () => {
190+
expect(
191+
parse('.a{background-image:url(/b/*.png)}.b{color:red}/* x */.c{color:blue}'),
192+
).toEqual([
193+
rule('.a', 'background-image', 'url(/b/*.png)'),
194+
rule('.b', 'color', 'red'),
195+
rule('.c', 'color', 'blue'),
196+
])
197+
})
198+
199+
it('should treat `url(…)` case-insensitive', () => {
200+
expect(parse('.a{background-image:URL(/b/*.png)}/* x */.c{color:blue}')).toEqual([
201+
rule('.a', 'background-image', 'URL(/b/*.png)'),
202+
rule('.c', 'color', 'blue'),
203+
])
204+
})
205+
206+
it('should allow whitespace around the url', () => {
207+
expect(parse('.a{background-image:url( /b/*.png )}/* x */.c{color:blue}')).toEqual([
208+
rule('.a', 'background-image', 'url( /b/*.png )'),
209+
rule('.c', 'color', 'blue'),
210+
])
211+
})
212+
213+
it('should handle a list of unquoted `url(…)`', () => {
214+
expect(parse('.a{background-image:url(a.png),url(/b/*.png)}/* x */.c{color:blue}')).toEqual(
215+
[rule('.a', 'background-image', 'url(a.png),url(/b/*.png)'), rule('.c', 'color', 'blue')],
216+
)
217+
})
218+
219+
it('should handle an unquoted `url(…)` in a custom property when a comment follows', () => {
220+
expect(parse('.a{--x:url(/b/*.png)}/* x */.c{color:blue}')).toEqual([
221+
rule('.a', '--x', 'url(/b/*.png)'),
222+
rule('.c', 'color', 'blue'),
223+
])
224+
})
225+
226+
it('should handle an unquoted `url(…)` in the params of an at-rule', () => {
227+
expect(parse('@import url(/b/*.css);/* x */.c{color:blue}')).toEqual([
228+
{ kind: 'at-rule', name: '@import', params: 'url(/b/*.css)', nodes: [] },
229+
rule('.c', 'color', 'blue'),
230+
])
231+
})
232+
233+
it('should remove a comment next to an unquoted `url(…)`', () => {
234+
expect(parse('.a{background-image:/* x */url(/b.png)/* y */,url(/c.png)/* z */}')).toEqual([
235+
rule('.a', 'background-image', 'url(/b.png),url(/c.png)'),
236+
])
237+
})
238+
239+
it('should treat `/*` inside of a function that ends with `url` as a comment', () => {
240+
expect(parse('.a{background-image:my-url(/b/* x */.png)}')).toEqual([
241+
rule('.a', 'background-image', 'my-url(/b.png)'),
242+
])
243+
expect(parse('.a{background-image:my\\+url(/b/* x */.png)}')).toEqual([
244+
rule('.a', 'background-image', 'my\\+url(/b.png)'),
245+
])
246+
expect(parse('.a{x:\\+url(a/* ) */b)}')).toEqual([rule('.a', 'x', '\\+url(ab)')])
247+
expect(parse('.a{--x:\\+url(a/* ; */b);color:red}')).toEqual([
248+
{
249+
kind: 'rule',
250+
selector: '.a',
251+
nodes: [
252+
{
253+
kind: 'declaration',
254+
property: '--x',
255+
value: '\\+url(a/* ; */b)',
256+
important: false,
257+
},
258+
{ kind: 'declaration', property: 'color', value: 'red', important: false },
259+
],
260+
},
261+
])
262+
})
263+
264+
it('should treat `/*` inside of a function after the whitespace that ends a hex escape as a comment', () => {
265+
// The whitespace is part of the hex escape `\31 `, so the ident is
266+
// `1url` and not `url`.
267+
expect(parse('.a{x:\\31 url(a/* ) */b)}')).toEqual([rule('.a', 'x', '\\31 url(ab)')])
268+
expect(parse('.a{x:\\31\turl(a/* ) */b)}')).toEqual([rule('.a', 'x', '\\31\turl(ab)')])
269+
expect(parse('.a{x:\\000031\furl(a/* ) */b)}')).toEqual([
270+
rule('.a', 'x', '\\000031\furl(ab)'),
271+
])
272+
expect(parse('.a{--x:\\31\nurl(a/* ; */b);color:red}')).toEqual([
273+
{
274+
kind: 'rule',
275+
selector: '.a',
276+
nodes: [
277+
{
278+
kind: 'declaration',
279+
property: '--x',
280+
value: `\\31${lineEndings === 'Windows' ? '\r\n' : '\n'}url(a/* ; */b)`,
281+
important: false,
282+
},
283+
{ kind: 'declaration', property: 'color', value: 'red', important: false },
284+
],
285+
},
286+
])
287+
288+
// An escaped `\` does not start a hex escape, so the whitespace ends
289+
// the ident.
290+
expect(parse('.a{x:\\\\31 url(a/*b)}')).toEqual([rule('.a', 'x', '\\\\31 url(a/*b)')])
291+
292+
// A hex escape has at most 6 hex digits, so the whitespace ends the
293+
// ident.
294+
expect(parse('.a{x:\\0000031 url(a/*b)}')).toEqual([rule('.a', 'x', '\\0000031 url(a/*b)')])
295+
})
296+
297+
it('should handle whitespace before the quote of a quoted `url(…)`', () => {
298+
expect(parse('.a{background-image:url(\f"a)b")}')).toEqual([
299+
rule('.a', 'background-image', 'url(\f"a)b")'),
300+
])
301+
})
302+
303+
it('should keep the default behavior for a `(` or a quote inside of an unquoted `url(…)`', () => {
304+
expect(
305+
parse(
306+
".a{background-image:url(var(--foo));mask:url(var(--foo, './b.png'));--x:url(var(--y))}",
307+
),
308+
).toEqual([
309+
{
310+
kind: 'rule',
311+
selector: '.a',
312+
nodes: [
313+
{
314+
kind: 'declaration',
315+
property: 'background-image',
316+
value: 'url(var(--foo))',
317+
important: false,
318+
},
319+
{
320+
kind: 'declaration',
321+
property: 'mask',
322+
value: "url(var(--foo, './b.png'))",
323+
important: false,
324+
},
325+
{ kind: 'declaration', property: '--x', value: 'url(var(--y))', important: false },
326+
],
327+
},
328+
])
329+
})
330+
})
172331
})
173332

174333
describe('declarations', () => {

‎packages/tailwindcss/src/css-parser.ts‎

Lines changed: 126 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ const LINE_BREAK = 0x0a
2323
const CARRIAGE_RETURN = 0xd
2424
const SPACE = 0x20
2525
const TAB = 0x09
26+
const FORM_FEED = 0x0c
2627
const OPEN_CURLY = 0x7b
2728
const CLOSE_CURLY = 0x7d
2829
const OPEN_PAREN = 0x28
@@ -34,6 +35,21 @@ const AT_SIGN = 0x40
3435
const EXCLAMATION_MARK = 0x21
3536
const LESS_THAN = 0x3c
3637
const GREATER_THAN = 0x3e
38+
const HASH = 0x23
39+
const UNDERSCORE = 0x5f
40+
const ZERO = 0x30
41+
const NINE = 0x39
42+
const UPPER_A = 0x41
43+
const UPPER_Z = 0x5a
44+
const UPPER_F = 0x46
45+
const LOWER_A = 0x61
46+
const LOWER_F = 0x66
47+
const LOWER_Z = 0x7a
48+
const LOWER_L = 0x6c
49+
const LOWER_R = 0x72
50+
const LOWER_U = 0x75
51+
const NON_ASCII = 0x80
52+
const LOWERCASE_BIT = 0x20
3753

3854
export interface ParseOptions {
3955
from?: string
@@ -247,6 +263,8 @@ export function parse(input: string, opts?: ParseOptions) {
247263
// comments.
248264
let valueEnd = 0
249265

266+
let end = -1
267+
250268
for (let j = i + 2; j < input.length; j++) {
251269
peekChar = input.charCodeAt(j)
252270

@@ -287,6 +305,11 @@ export function parse(input: string, opts?: ParseOptions) {
287305
break
288306
}
289307

308+
// Start of an unquoted `url(…)`, a `/*` inside of it is not a comment.
309+
else if (peekChar === OPEN_PAREN && (end = findUnquotedUrlEnd(input, j)) !== -1) {
310+
j = end
311+
}
312+
290313
// Start of a block.
291314
else if (peekChar === OPEN_PAREN) {
292315
closingBracketStack += ')'
@@ -582,8 +605,25 @@ export function parse(input: string, opts?: ParseOptions) {
582605

583606
// `(`
584607
else if (currentChar === OPEN_PAREN) {
585-
closingBracketStack += ')'
586-
buffer += '('
608+
// An unquoted `url(…)` is a single token that ends at the first `)`. A
609+
// `/*` inside of it is not the start of a comment.
610+
//
611+
// E.g.:
612+
//
613+
// ```css
614+
// .foo {
615+
// background-image: url(/images/*.png);
616+
// ^^^^^^^^^^^^^^^
617+
// }
618+
// ```
619+
let end = findUnquotedUrlEnd(input, i)
620+
if (end !== -1) {
621+
buffer += input.slice(i, end + 1)
622+
i = end
623+
} else {
624+
closingBracketStack += ')'
625+
buffer += '('
626+
}
587627
}
588628

589629
// `)`
@@ -778,6 +818,90 @@ function isEscaped(value: string, idx: number) {
778818
return backslashes % 2 === 1
779819
}
780820

821+
// When the `(` at `idx` starts an unquoted `url(…)`, return the index of the
822+
// `)` that ends it. Otherwise, return `-1`.
823+
//
824+
// See: https://www.w3.org/TR/css-syntax-3/#consume-ident-like-token
825+
// See: https://www.w3.org/TR/css-syntax-3/#consume-url-token
826+
function findUnquotedUrlEnd(input: string, idx: number): number {
827+
// The `(` must follow the ident `url`, case-insensitive. Setting the
828+
// `LOWERCASE_BIT` turns an ASCII uppercase letter into its lowercase form.
829+
if (
830+
idx < 3 ||
831+
(input.charCodeAt(idx - 3) | LOWERCASE_BIT) !== LOWER_U ||
832+
(input.charCodeAt(idx - 2) | LOWERCASE_BIT) !== LOWER_R ||
833+
(input.charCodeAt(idx - 1) | LOWERCASE_BIT) !== LOWER_L
834+
) {
835+
return -1
836+
}
837+
838+
// The ident must start at `url`, e.g. `my-url(…)`, `my\+url(…)` and
839+
// `#url(…)` are not a url.
840+
let prevChar = input.charCodeAt(idx - 4)
841+
if (
842+
(prevChar >= LOWER_A && prevChar <= LOWER_Z) ||
843+
(prevChar >= UPPER_A && prevChar <= UPPER_Z) ||
844+
(prevChar >= ZERO && prevChar <= NINE) ||
845+
prevChar === DASH ||
846+
prevChar === UNDERSCORE ||
847+
prevChar >= NON_ASCII ||
848+
prevChar === BACKSLASH ||
849+
prevChar === HASH ||
850+
prevChar === AT_SIGN ||
851+
isEscaped(input, idx - 4) ||
852+
endsHexEscape(input, idx - 4)
853+
) {
854+
return -1
855+
}
856+
857+
// The url ends at the first `)` that is not escaped.
858+
for (let i = idx + 1; i < input.length; i++) {
859+
let char = input.charCodeAt(i)
860+
if (char === BACKSLASH) {
861+
i += 1
862+
} else if (char === CLOSE_PAREN) {
863+
return i
864+
}
865+
866+
// A quoted `url("…")` is a function with a string, not a url token. And a
867+
// quote or a `(` later on makes it a bad url, e.g. `url(var(--foo))`. Keep
868+
// the default behavior for those.
869+
else if (char === OPEN_PAREN || char === SINGLE_QUOTE || char === DOUBLE_QUOTE) {
870+
return -1
871+
}
872+
}
873+
874+
return -1
875+
}
876+
877+
// Whether the whitespace at `idx` ends a hex escape, e.g. the space in `\31 `.
878+
// That whitespace is part of the escape, so the ident goes on after it.
879+
//
880+
// See: https://www.w3.org/TR/css-syntax-3/#consume-escaped-code-point
881+
function endsHexEscape(input: string, idx: number): boolean {
882+
let char = input.charCodeAt(idx)
883+
if (char === LINE_BREAK) {
884+
// A `\r\n` is a single whitespace.
885+
if (input.charCodeAt(idx - 1) === CARRIAGE_RETURN) idx -= 1
886+
} else if (char !== SPACE && char !== TAB && char !== FORM_FEED && char !== CARRIAGE_RETURN) {
887+
return false
888+
}
889+
890+
// A hex escape is a `\` that is not escaped, followed by 1 to 6 hex digits.
891+
for (let i = idx - 1; i >= 0 && i >= idx - 7; i--) {
892+
char = input.charCodeAt(i)
893+
if (char === BACKSLASH) return i < idx - 1 && !isEscaped(input, i)
894+
895+
let isHexDigit =
896+
(char >= ZERO && char <= NINE) ||
897+
(char >= LOWER_A && char <= LOWER_F) ||
898+
(char >= UPPER_A && char <= UPPER_F)
899+
if (!isHexDigit) return false
900+
}
901+
902+
return false
903+
}
904+
781905
function parseString(
782906
input: string,
783907
startIdx: number,

0 commit comments

Comments
 (0)