Skip to content

Commit 4ea8096

Browse files
mischnichuozhi
authored andcommitted
Turbopack: cleanup StyleSheetLike (#85718)
This abstraction was a leftover from when we had a swc_css and a lightningcss backend. Also inspired by #85524 as there was another constant-false `PartialEq` impl.
1 parent 11945e0 commit 4ea8096

File tree

3 files changed

+74
-94
lines changed

3 files changed

+74
-94
lines changed

turbopack/crates/turbopack-css/src/process.rs

Lines changed: 64 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -43,15 +43,6 @@ use crate::{
4343
},
4444
};
4545

46-
#[derive(Debug)]
47-
pub struct StyleSheetLike<'i, 'o>(pub(crate) StyleSheet<'i, 'o>);
48-
49-
impl PartialEq for StyleSheetLike<'_, '_> {
50-
fn eq(&self, _: &Self) -> bool {
51-
false
52-
}
53-
}
54-
5546
pub type CssOutput = (ToCssResult, Option<Rope>);
5647

5748
#[turbo_tasks::value(transparent)]
@@ -94,60 +85,49 @@ async fn get_lightningcss_browser_targets(
9485
}
9586
}
9687

97-
impl StyleSheetLike<'_, '_> {
98-
pub fn to_static(
99-
&self,
100-
options: ParserOptions<'static, 'static>,
101-
) -> StyleSheetLike<'static, 'static> {
102-
StyleSheetLike(stylesheet_into_static(&self.0, options))
103-
}
88+
async fn stylesheet_to_css(
89+
ss: &StyleSheet<'_, '_>,
90+
code: &str,
91+
minify_type: MinifyType,
92+
enable_srcmap: bool,
93+
handle_nesting: bool,
94+
mut origin_source_map: Option<parcel_sourcemap::SourceMap>,
95+
environment: Option<ResolvedVc<Environment>>,
96+
) -> Result<CssOutput> {
97+
let mut srcmap = if enable_srcmap {
98+
Some(parcel_sourcemap::SourceMap::new(""))
99+
} else {
100+
None
101+
};
104102

105-
pub async fn to_css(
106-
&self,
107-
code: &str,
108-
minify_type: MinifyType,
109-
enable_srcmap: bool,
110-
handle_nesting: bool,
111-
mut origin_source_map: Option<parcel_sourcemap::SourceMap>,
112-
environment: Option<ResolvedVc<Environment>>,
113-
) -> Result<CssOutput> {
114-
let ss = &self.0;
115-
let mut srcmap = if enable_srcmap {
116-
Some(parcel_sourcemap::SourceMap::new(""))
103+
let targets =
104+
*get_lightningcss_browser_targets(environment.as_deref().copied(), handle_nesting).await?;
105+
106+
let result = ss.to_css(PrinterOptions {
107+
minify: matches!(minify_type, MinifyType::Minify { .. }),
108+
source_map: srcmap.as_mut(),
109+
targets,
110+
analyze_dependencies: None,
111+
..Default::default()
112+
})?;
113+
114+
if let Some(srcmap) = &mut srcmap {
115+
debug_assert_eq!(ss.sources.len(), 1);
116+
117+
if let Some(origin_source_map) = origin_source_map.as_mut() {
118+
let _ = srcmap.extends(origin_source_map);
117119
} else {
118-
None
119-
};
120-
121-
let targets =
122-
*get_lightningcss_browser_targets(environment.as_deref().copied(), handle_nesting)
123-
.await?;
124-
125-
let result = ss.to_css(PrinterOptions {
126-
minify: matches!(minify_type, MinifyType::Minify { .. }),
127-
source_map: srcmap.as_mut(),
128-
targets,
129-
analyze_dependencies: None,
130-
..Default::default()
131-
})?;
132-
133-
if let Some(srcmap) = &mut srcmap {
134-
debug_assert_eq!(ss.sources.len(), 1);
135-
136-
if let Some(origin_source_map) = origin_source_map.as_mut() {
137-
let _ = srcmap.extends(origin_source_map);
138-
} else {
139-
srcmap.add_sources(ss.sources.clone());
140-
srcmap.set_source_content(0, code)?;
141-
}
120+
srcmap.add_sources(ss.sources.clone());
121+
srcmap.set_source_content(0, code)?;
142122
}
123+
}
143124

144-
let srcmap = match srcmap {
145-
Some(srcmap) => Some(generate_css_source_map(&srcmap)?),
146-
None => None,
147-
};
125+
let srcmap = match srcmap {
126+
Some(srcmap) => Some(generate_css_source_map(&srcmap)?),
127+
None => None,
128+
};
148129

149-
Ok((result, srcmap))
150-
}
130+
Ok((result, srcmap))
151131
}
152132

153133
/// Multiple [ModuleReference]s
@@ -161,7 +141,7 @@ pub enum ParseCssResult {
161141
code: ResolvedVc<FileContent>,
162142

163143
#[turbo_tasks(trace_ignore)]
164-
stylesheet: StyleSheetLike<'static, 'static>,
144+
stylesheet: StyleSheet<'static, 'static>,
165145

166146
references: ResolvedVc<ModuleReferences>,
167147

@@ -228,9 +208,16 @@ pub async fn process_css_with_placeholder(
228208

229209
// We use NoMinify because this is not a final css. We need to replace url references,
230210
// and we do final codegen with proper minification.
231-
let (result, _) = stylesheet
232-
.to_css(&code, MinifyType::NoMinify, false, false, None, environment)
233-
.await?;
211+
let (result, _) = stylesheet_to_css(
212+
stylesheet,
213+
&code,
214+
MinifyType::NoMinify,
215+
false,
216+
false,
217+
None,
218+
environment,
219+
)
220+
.await?;
234221

235222
let exports = result.exports.map(|exports| {
236223
let mut exports = exports.into_iter().collect::<FxIndexMap<_, _>>();
@@ -275,7 +262,7 @@ pub async fn finalize_css(
275262
options,
276263
code,
277264
..
278-
} => (stylesheet.to_static(options.clone()), *code),
265+
} => (stylesheet_into_static(stylesheet, options.clone()), *code),
279266
ParseCssResult::Unparsable => return Ok(FinalCssResult::Unparsable.cell()),
280267
ParseCssResult::NotFound => return Ok(FinalCssResult::NotFound.cell()),
281268
};
@@ -305,16 +292,16 @@ pub async fn finalize_css(
305292
None
306293
};
307294

308-
let (result, srcmap) = stylesheet
309-
.to_css(
310-
&code,
311-
minify_type,
312-
true,
313-
true,
314-
origin_source_map,
315-
environment,
316-
)
317-
.await?;
295+
let (result, srcmap) = stylesheet_to_css(
296+
&stylesheet,
297+
&code,
298+
minify_type,
299+
true,
300+
true,
301+
origin_source_map,
302+
environment,
303+
)
304+
.await?;
318305

319306
Ok(FinalCssResult::Ok {
320307
output_code: result.code,
@@ -435,7 +422,7 @@ async fn process_content(
435422
..Default::default()
436423
};
437424

438-
let stylesheet = StyleSheetLike({
425+
let stylesheet = {
439426
let warnings: Arc<RwLock<_>> = Default::default();
440427

441428
match StyleSheet::parse(
@@ -455,10 +442,7 @@ async fn process_content(
455442
}
456443
}
457444

458-
// We need to collect here because we need to avoid holding the lock while calling
459-
// `.await` in the loop.
460-
let warnings = warnings.read().unwrap().iter().cloned().collect::<Vec<_>>();
461-
for err in warnings.iter() {
445+
for err in warnings.read().unwrap().iter() {
462446
match err.kind {
463447
lightningcss::error::ParserError::UnexpectedToken(_)
464448
| lightningcss::error::ParserError::UnexpectedImportRule
@@ -546,10 +530,10 @@ async fn process_content(
546530
return Ok(ParseCssResult::Unparsable.cell());
547531
}
548532
}
549-
});
533+
};
550534

551535
let config = without_warnings(config);
552-
let mut stylesheet = stylesheet.to_static(config.clone());
536+
let mut stylesheet = stylesheet_into_static(&stylesheet, config.clone());
553537

554538
let (references, url_references) =
555539
analyze_references(&mut stylesheet, source, origin, import_context).await?;

turbopack/crates/turbopack-css/src/references/mod.rs

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use std::convert::Infallible;
33
use anyhow::Result;
44
use lightningcss::{
55
rules::CssRule,
6+
stylesheet::StyleSheet,
67
traits::IntoOwned,
78
values::url::Url,
89
visitor::{Visit, Visitor},
@@ -18,12 +19,9 @@ use turbopack_core::{
1819
source_pos::SourcePos,
1920
};
2021

21-
use crate::{
22-
StyleSheetLike,
23-
references::{
24-
import::{ImportAssetReference, ImportAttributes},
25-
url::UrlAssetReference,
26-
},
22+
use crate::references::{
23+
import::{ImportAssetReference, ImportAttributes},
24+
url::UrlAssetReference,
2725
};
2826

2927
pub(crate) mod compose;
@@ -38,7 +36,7 @@ pub type AnalyzedRefs = (
3836

3937
/// Returns `(all_references, urls)`.
4038
pub async fn analyze_references(
41-
stylesheet: &mut StyleSheetLike<'static, 'static>,
39+
stylesheet: &mut StyleSheet<'static, 'static>,
4240
source: ResolvedVc<Box<dyn Source>>,
4341
origin: ResolvedVc<Box<dyn ResolveOrigin>>,
4442
import_context: Option<ResolvedVc<ImportContext>>,
@@ -48,7 +46,7 @@ pub async fn analyze_references(
4846

4947
let mut visitor =
5048
ModuleReferencesVisitor::new(source, origin, import_context, &mut references, &mut urls);
51-
stylesheet.0.visit(&mut visitor).unwrap();
49+
stylesheet.visit(&mut visitor).unwrap();
5250

5351
tokio::try_join!(
5452
references.into_iter().map(|v| v.to_resolved()).try_join(),

turbopack/crates/turbopack-css/src/references/url.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ use std::convert::Infallible;
22

33
use anyhow::Result;
44
use lightningcss::{
5+
stylesheet::StyleSheet,
56
values::url::Url,
67
visit_types,
78
visitor::{Visit, Visitor},
@@ -18,7 +19,7 @@ use turbopack_core::{
1819
resolve::{ModuleResolveResult, origin::ResolveOrigin, parse::Request, url_resolve},
1920
};
2021

21-
use crate::{StyleSheetLike, embed::CssEmbed};
22+
use crate::embed::CssEmbed;
2223

2324
#[turbo_tasks::value]
2425
pub enum ReferencedAsset {
@@ -122,12 +123,9 @@ pub async fn resolve_url_reference(
122123
Ok(Vc::cell(None))
123124
}
124125

125-
pub fn replace_url_references(
126-
ss: &mut StyleSheetLike<'static, 'static>,
127-
urls: &FxHashMap<RcStr, RcStr>,
128-
) {
126+
pub fn replace_url_references<'i, 'o>(ss: &mut StyleSheet<'i, 'o>, urls: &FxHashMap<RcStr, RcStr>) {
129127
let mut replacer = AssetReferenceReplacer { urls };
130-
ss.0.visit(&mut replacer).unwrap();
128+
ss.visit(&mut replacer).unwrap();
131129
}
132130

133131
struct AssetReferenceReplacer<'a> {

0 commit comments

Comments
 (0)