Unverified Commit 69dd6a49 authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

turbopack-css: ignore false-positive EndOfInput for name-only @container (#98261)

Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 62005c33
......@@ -9664,6 +9664,7 @@ dependencies = [
"anyhow",
"async-trait",
"bincode",
"cssparser",
"indoc",
"lightningcss",
"parcel_selectors",
......
......@@ -16,6 +16,8 @@ workspace = true
anyhow = { workspace = true }
async-trait = { workspace = true }
bincode = { workspace = true }
# Must match the version used by `lightningcss`, so its parsers accept our `cssparser::Parser`.
cssparser = "0.37.0"
indoc = { workspace = true }
lightningcss = { workspace = true }
parcel_selectors = { workspace = true }
......
use std::{
borrow::Cow,
convert::Infallible,
sync::{Arc, RwLock},
};
......@@ -7,16 +8,21 @@ use anyhow::{Result, bail};
use async_trait::async_trait;
use lightningcss::{
css_modules::{CssModuleExport, Pattern, Segment},
error::ParserError,
rules::{
CssRule,
container::{ContainerCondition, ContainerName},
},
stylesheet::{
MinifyOptions, ParserFlags, ParserOptions, PrinterOptions, StyleSheet, ToCssResult,
},
targets::{BrowserslistConfig, Features, Targets},
traits::ToCss,
traits::{Parse, ToCss},
values::url::Url,
visit_types,
visitor::Visit,
visitor::{Visit, VisitTypes, Visitor},
};
use rustc_hash::FxHashMap;
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::smallvec;
use swc_core::base::sourcemap::SourceMapBuilder;
use tracing::Instrument;
......@@ -426,6 +432,108 @@ fn source_pos_for_loc(loc: &lightningcss::error::ErrorLocation, code_had_bom: bo
}
}
/// Workaround for a lightningcss bug with name-only container queries such as
/// `@container sidebar { ... }` (<https://github.com/vercel/next.js/issues/98261>).
///
/// With `error_recovery` enabled, lightningcss (as of 1.0.0-alpha.72) tries to
/// parse the empty condition after the container name, records an
/// `EndOfInput` warning at the rule's `{`, and keeps an empty
/// `ContainerCondition::Unknown` instead of `None`. The CSS is valid, so the
/// warning is a false positive.
///
/// This returns the location of the `{` of every name-only `@container` rule in
/// `code`, in lightningcss's coordinates (0-based line, 1-based UTF-16 column),
/// so those warnings can be dropped. `code` must be the exact (BOM-stripped)
/// string handed to lightningcss. Remove once lightningcss is fixed.
///
/// The scan is token-based, so it may also report such a sequence that isn't an
/// at-rule (e.g. inside a custom property value). That's harmless: only an
/// `EndOfInput` warning at exactly that `{` is dropped, and lightningcss doesn't
/// emit one there.
fn name_only_container_brace_locations(code: &str) -> FxHashSet<(u32, u32)> {
let mut input = cssparser::ParserInput::new(code);
let mut parser = cssparser::Parser::new(&mut input);
let mut locations = FxHashSet::default();
collect_name_only_container_braces(&mut parser, &mut locations);
locations
}
fn collect_name_only_container_braces<'i>(
input: &mut cssparser::Parser<'i, '_>,
locations: &mut FxHashSet<(u32, u32)>,
) {
loop {
let token = match input.next_including_whitespace_and_comments() {
Ok(token) => token.clone(),
Err(_) => return,
};
let enters_block = match token {
cssparser::Token::AtKeyword(ref name) if name.eq_ignore_ascii_case("container") => {
// Use lightningcss's own name parser so that exactly the names it
// accepts (no CSS-wide keywords, `none`, `and`, `not`, `or`) qualify.
let brace = input.try_parse(
|input| -> Result<_, cssparser::ParseError<'i, ParserError<'i>>> {
ContainerName::parse(input)?;
input.skip_whitespace();
let location = input.current_source_location();
match input.next()? {
cssparser::Token::CurlyBracketBlock => Ok(location),
token => {
let token = token.clone();
Err(location.new_unexpected_token_error(token))
}
}
},
);
match brace {
Ok(location) => {
locations.insert((location.line, location.column));
true
}
Err(_) => false,
}
}
cssparser::Token::CurlyBracketBlock
| cssparser::Token::SquareBracketBlock
| cssparser::Token::ParenthesisBlock
| cssparser::Token::Function(_) => true,
_ => false,
};
if enters_block {
let _ = input.parse_nested_block(|input| {
collect_name_only_container_braces(input, locations);
Ok::<_, cssparser::ParseError<'i, ()>>(())
});
}
}
}
/// Rewrites the empty `ContainerCondition::Unknown` that lightningcss produces
/// for a name-only `@container` rule in error-recovery mode to `None`, which is
/// what it produces without error recovery. Otherwise the rule is printed with
/// stray whitespace (`@container sidebar {`). See
/// [`name_only_container_brace_locations`].
struct NameOnlyContainerNormalizer;
impl<'i> Visitor<'i> for NameOnlyContainerNormalizer {
type Error = Infallible;
fn visit_types(&self) -> VisitTypes {
visit_types!(RULES)
}
fn visit_rule(&mut self, rule: &mut CssRule<'i>) -> Result<(), Self::Error> {
if let CssRule::Container(container) = rule
&& container.name.is_some()
&& let Some(ContainerCondition::Unknown(tokens)) = &container.condition
&& tokens.0.iter().all(|token| token.is_whitespace())
{
container.condition = None;
}
rule.visit_children(self)
}
}
/// Parse a CSS stylesheet and run CSS module validation.
///
/// Does not handle parser warnings — the caller is responsible for configuring
......@@ -441,6 +549,9 @@ fn parse_css_stylesheet<'a>(
let code = strip_bom(code);
let mut ss = StyleSheet::parse(code, config)?;
ss.visit(&mut NameOnlyContainerNormalizer)
.unwrap_or_else(|never| match never {});
if matches!(ty, CssModuleType::Module) {
let mut validator = CssValidator { errors: Vec::new() };
ss.visit(&mut validator).unwrap();
......@@ -537,7 +648,27 @@ async fn process_content(
source,
) {
Ok(mut ss) => {
for err in warnings.read().unwrap().iter() {
// Scoped so that the lock guard is not held across the `await` below.
{
let collected_warnings = warnings.read().unwrap();
// See `name_only_container_brace_locations`: only computed when
// there's a candidate warning, which is rare.
let false_positive_locations = if collected_warnings
.iter()
.any(|err| matches!(err.kind, lightningcss::error::ParserError::EndOfInput))
{
name_only_container_brace_locations(strip_bom(&code))
} else {
FxHashSet::default()
};
for err in collected_warnings.iter() {
if matches!(err.kind, lightningcss::error::ParserError::EndOfInput)
&& let Some(loc) = &err.loc
&& false_positive_locations.contains(&(loc.line, loc.column))
{
continue;
}
// Unsupported pseudo-classes/elements are common in real-world CSS
// (vendor prefixes, custom frameworks) and do not prevent the
// stylesheet from being used — treat them as recoverable warnings.
......@@ -573,6 +704,7 @@ async fn process_content(
.resolved_cell()
.emit();
}
}
let targets = *get_lightningcss_browser_targets(
environment.as_deref().copied(),
......@@ -841,7 +973,10 @@ mod tests {
visitor::Visit,
};
use super::{CssError, CssValidator, source_pos_for_loc, strip_bom};
use super::{
CssError, CssValidator, NameOnlyContainerNormalizer, name_only_container_brace_locations,
source_pos_for_loc, strip_bom,
};
fn lint_lightningcss(code: &str) -> Vec<CssError> {
let mut ss = StyleSheet::parse(
......@@ -1045,4 +1180,126 @@ mod tests {
source_pos_for_loc(&later_line, false).column,
);
}
/// Locations of the `EndOfInput` warnings lightningcss emits for `code` when
/// parsing with error recovery, as Turbopack does.
fn end_of_input_warning_locations(code: &str) -> Vec<(u32, u32)> {
let warnings: std::sync::Arc<std::sync::RwLock<Vec<_>>> = Default::default();
StyleSheet::parse(
code,
ParserOptions {
error_recovery: true,
warnings: Some(warnings.clone()),
..Default::default()
},
)
.unwrap();
let warnings = warnings.read().unwrap();
warnings
.iter()
.filter(|w| matches!(w.kind, lightningcss::error::ParserError::EndOfInput))
.map(|w| {
let loc = w.loc.as_ref().unwrap();
(loc.line, loc.column)
})
.collect()
}
/// Asserts that every false-positive `EndOfInput` warning lightningcss emits
/// for `code` is detected (and nothing else), and that there is at least one.
#[track_caller]
fn assert_name_only_false_positives(code: &str, expected: &[(u32, u32)]) {
let mut warned = end_of_input_warning_locations(code);
warned.sort();
let mut detected: Vec<_> = name_only_container_brace_locations(code)
.into_iter()
.collect();
detected.sort();
assert_eq!(warned, expected, "lightningcss warnings for: {code}");
assert_eq!(detected, expected, "detected braces for: {code}");
}
// Lightning CSS currently triggers a Miri Stacked Borrows violation in its string parser.
#[cfg(not(miri))]
#[test]
fn name_only_container_false_positive_is_detected() {
assert_name_only_false_positives("@container sidebar {}", &[(0, 20)]);
assert_name_only_false_positives("@CONTAINER Sidebar{.a{color:red}}", &[(0, 19)]);
assert_name_only_false_positives(
"@supports (container-type: scroll-state) {\n @container scroll-content {\n .a { \
max-width: 100cqw; }\n }\n}",
&[(1, 29)],
);
assert_name_only_false_positives(
"@container /* a */ sidebar /* b */\n\n { .a { color: red } }",
&[(2, 3)],
);
assert_name_only_false_positives("@container sid\\65 bar {}", &[(0, 23)]);
// Columns are counted in UTF-16 code units: 😀 is two of them.
assert_name_only_false_positives(
".a::before { content: '😀' }\n@container 😀 {}",
&[(1, 15)],
);
assert_name_only_false_positives(
"@media screen { @layer x { .a { @container s {} } } }\n@container t {}",
&[(0, 46), (1, 14)],
);
// BOM-stripped input, as handed to lightningcss.
assert_name_only_false_positives(strip_bom("\u{feff}@container s {}"), &[(0, 14)]);
}
// Lightning CSS currently triggers a Miri Stacked Borrows violation in its string parser.
#[cfg(not(miri))]
#[test]
fn other_container_preludes_are_not_detected() {
for code in [
"@container sidebar (min-width: 400px) {}",
"@container sidebar scroll-state(scrollable: top) {}",
"@container (min-width: 400px) {}",
"@container {}",
"@container sidebar other {}",
"@container none {}",
"@container AND {}",
"@container not {}",
"@container or {}",
"@container inherit {}",
"@container initial {}",
"@container unset {}",
"@container default {}",
"@container revert {}",
"@container revert-layer {}",
"@media sidebar {}",
] {
assert!(
name_only_container_brace_locations(code).is_empty(),
"unexpectedly detected: {code}"
);
}
}
// Lightning CSS currently triggers a Miri Stacked Borrows violation in its string parser.
#[cfg(not(miri))]
#[test]
fn name_only_container_condition_is_normalized() {
let code = "@container scroll-content { .a { color: red } }\n@container s (width > 1px) { \
.b { color: red } }";
let mut ss = StyleSheet::parse(
code,
ParserOptions {
error_recovery: true,
..Default::default()
},
)
.unwrap();
ss.visit(&mut NameOnlyContainerNormalizer).unwrap();
let css = ss
.to_css(lightningcss::stylesheet::PrinterOptions::default())
.unwrap()
.code;
assert_eq!(
css,
"@container scroll-content {\n .a {\n color: red;\n }\n}\n\n@container s (width \
> 1px) {\n .b {\n color: red;\n }\n}\n"
);
}
}
/*
* https://github.com/vercel/next.js/issues/98261
*
* A name-only `@container <name>` rule is valid CSS, but with `error_recovery`
* enabled lightningcss (1.0.0-alpha.72) still warns `EndOfInput` for the empty
* container condition, which is reported as a parse error issue. The rule itself
* is kept in the output. Once lightningcss is fixed, the issue snapshot should
* disappear.
* A name-only `@container <name>` rule is valid CSS. With `error_recovery`
* enabled, lightningcss (1.0.0-alpha.72) reports a false-positive
* `EndOfInput` warning for it and keeps an empty condition. turbopack-css
* drops that warning and normalizes the condition, so this file must produce
* no issue for it and print it as `@container scroll-content {`.
*/
@supports (container-type: inline-size scroll-state) {
@container scroll-content {
......@@ -26,3 +26,16 @@
color: blue;
}
}
/* Invalid container names must still be reported. */
@container none {
.reserved-name {
color: green;
}
}
@container inherit {
.css-wide-keyword {
color: green;
}
}
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css:11:28 Parsing CSS source code failed
7 | * is kept in the output. Once lightningcss is fixed, the issue snapshot should
8 | * disappear.
9 | */
10 | @supports (container-type: inline-size scroll-state) {
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css:37:10 Parsing CSS source code failed
33 | color: green;
34 | }
35 | }
36 |
+ v
11 + @container scroll-content {
37 + @container inherit {
+ ^
12 | .named-only {
13 | max-width: 100cqw;
14 | }
15 | }
38 | .css-wide-keyword {
39 | color: green;
40 | }
41 | }
Unexpected end of input
Unexpected token Ident("inherit")
Import trace:
test:
......
error - [parse] /turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css:31:10 Parsing CSS source code failed
27 | }
28 | }
29 |
30 | /* Invalid container names must still be reported. */
+ v
31 + @container none {
+ ^
32 | .reserved-name {
33 | color: green;
34 | }
35 | }
Unexpected token Ident("none")
Import trace:
test:
./turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css
./turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/index.js
\ No newline at end of file
......@@ -19,4 +19,16 @@
}
}
@container none {
.reserved-name {
color: green;
}
}
@container inherit {
.css-wide-keyword {
color: green;
}
}
/*# sourceMappingURL=1jsg_tests_snapshot_css_named-container-query_input_style_1i4y8ac_sk8d1.css.map*/
\ No newline at end of file
......@@ -2,5 +2,5 @@
"version": 3,
"sources": [],
"sections": [
{"offset": {"line": 1, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css"],"sourcesContent":["/*\n * https://github.com/vercel/next.js/issues/98261\n *\n * A name-only `@container <name>` rule is valid CSS, but with `error_recovery`\n * enabled lightningcss (1.0.0-alpha.72) still warns `EndOfInput` for the empty\n * container condition, which is reported as a parse error issue. The rule itself\n * is kept in the output. Once lightningcss is fixed, the issue snapshot should\n * disappear.\n */\n@supports (container-type: inline-size scroll-state) {\n @container scroll-content {\n .named-only {\n max-width: 100cqw;\n }\n }\n}\n\n@container sidebar (min-width: 400px) {\n .named-with-condition {\n color: red;\n }\n}\n\n@container scroll-state(scrollable: top) {\n .scroll-state {\n color: blue;\n }\n}\n"],"names":[],"mappings":"AASA;EACE;IACE;;;;;;AAMJ;EACE;;;;;AAKF;EACE"}}]
{"offset": {"line": 1, "column": 0}, "map": {"version":3,"sources":["turbopack:///[project]/turbopack/crates/turbopack-tests/tests/snapshot/css/named-container-query/input/style.css"],"sourcesContent":["/*\n * https://github.com/vercel/next.js/issues/98261\n *\n * A name-only `@container <name>` rule is valid CSS. With `error_recovery`\n * enabled, lightningcss (1.0.0-alpha.72) reports a false-positive\n * `EndOfInput` warning for it and keeps an empty condition. turbopack-css\n * drops that warning and normalizes the condition, so this file must produce\n * no issue for it and print it as `@container scroll-content {`.\n */\n@supports (container-type: inline-size scroll-state) {\n @container scroll-content {\n .named-only {\n max-width: 100cqw;\n }\n }\n}\n\n@container sidebar (min-width: 400px) {\n .named-with-condition {\n color: red;\n }\n}\n\n@container scroll-state(scrollable: top) {\n .scroll-state {\n color: blue;\n }\n}\n\n/* Invalid container names must still be reported. */\n@container none {\n .reserved-name {\n color: green;\n }\n}\n\n@container inherit {\n .css-wide-keyword {\n color: green;\n }\n}\n"],"names":[],"mappings":"AASA;EACE;IACE;;;;;;AAMJ;EACE;;;;;AAKF;EACE;;;;;AAMF;EACE;;;;;AAKF;EACE"}}]
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment