Unverified Commit 22ac035b authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Normalize filepaths when parsing patterns from js values (#80511)

## Normalize Windows file paths in pattern construction

When interpreting js_values as `Pattern` objects for interpretation, normalize windows file endings away.

Also enable debug_assertions in unit tests.

### Why?
Enabling debug assertions on CI will prevent us from making mistakes

### Alternates?

Honestly, i am kind of confused about where to put this logic
https://vercel.slack.com/archives/C03EWR7LGEN/p1749854016509599?thread_ts=1749833045.978729&cid=C03EWR7LGEN

`Pattern::normalize` and `Pattern::with_normalized_path` are both reasonable alternatives.  However, the fact that `normalize` doesn't call `with_normalized_path` was a bit concerning, as was the complex nature of the Pattern type.

Fixes PACK-3279
Part of PACK-4578
parent b82ada30
...@@ -241,6 +241,12 @@ opt-level = 3 ...@@ -241,6 +241,12 @@ opt-level = 3
[profile.release.package.serde] [profile.release.package.serde]
opt-level = 3 opt-level = 3
# Use a custom profile for CI where many tests are performance sensitive but we still want the additional validation of debug-assertions
[profile.release-with-assertions]
inherits = "release"
debug-assertions = true
overflow-checks = true
[workspace.dependencies] [workspace.dependencies]
# Workspace crates # Workspace crates
next-api = { path = "crates/next-api" } next-api = { path = "crates/next-api" }
......
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
"rust-check-fmt": "cd ../..; cargo fmt -- --check", "rust-check-fmt": "cd ../..; cargo fmt -- --check",
"rust-check-clippy": "cargo clippy --workspace --all-targets -- -D warnings -A deprecated", "rust-check-clippy": "cargo clippy --workspace --all-targets -- -D warnings -A deprecated",
"rust-check-napi": "cargo check -p next-swc-napi", "rust-check-napi": "cargo check -p next-swc-napi",
"test-cargo-unit": "cargo nextest run --workspace --exclude next-swc-napi --exclude turbo-tasks-macros --release --no-fail-fast" "test-cargo-unit": "cargo nextest run --workspace --exclude next-swc-napi --exclude turbo-tasks-macros --cargo-profile release-with-assertions --no-fail-fast"
}, },
"napi": { "napi": {
"name": "next-swc", "name": "next-swc",
......
...@@ -532,17 +532,9 @@ impl Pattern { ...@@ -532,17 +532,9 @@ impl Pattern {
/// Order into Alternatives -> Concatenation -> Constant/Dynamic /// Order into Alternatives -> Concatenation -> Constant/Dynamic
/// Merge when possible /// Merge when possible
pub fn normalize(&mut self) { pub fn normalize(&mut self) {
let mut alternatives = [Vec::new()];
match self { match self {
Pattern::Constant(c) => { Pattern::Dynamic | Pattern::Constant(_) => {
for alt in alternatives.iter_mut() { // already normalized
alt.push(Pattern::Constant(c.clone()));
}
}
Pattern::Dynamic => {
for alt in alternatives.iter_mut() {
alt.push(Pattern::Dynamic);
}
} }
Pattern::Alternatives(list) => { Pattern::Alternatives(list) => {
for alt in list.iter_mut() { for alt in list.iter_mut() {
...@@ -630,6 +622,7 @@ impl Pattern { ...@@ -630,6 +622,7 @@ impl Pattern {
}) })
.collect(), .collect(),
); );
// The recursive call will deduplicate the alternatives after simplifying them
self.normalize(); self.normalize();
} else { } else {
let mut new_parts = Vec::new(); let mut new_parts = Vec::new();
......
...@@ -111,6 +111,13 @@ impl ConstantString { ...@@ -111,6 +111,13 @@ impl ConstantString {
} }
} }
pub fn as_rcstr(&self) -> RcStr {
match self {
Self::Atom(s) => RcStr::from(s.as_str()),
Self::RcStr(s) => s.clone(),
}
}
pub fn as_atom(&self) -> Cow<Atom> { pub fn as_atom(&self) -> Cow<Atom> {
match self { match self {
Self::Atom(s) => Cow::Borrowed(s), Self::Atom(s) => Cow::Borrowed(s),
......
...@@ -6,6 +6,7 @@ use swc_core::{ ...@@ -6,6 +6,7 @@ use swc_core::{
visit::AstParentKind, visit::AstParentKind,
}, },
}; };
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, trace::TraceRawVcs}; use turbo_tasks::{NonLocalValue, trace::TraceRawVcs};
use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern}; use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern};
...@@ -24,26 +25,42 @@ pub fn unparen(expr: &Expr) -> &Expr { ...@@ -24,26 +25,42 @@ pub fn unparen(expr: &Expr) -> &Expr {
expr expr
} }
/// Converts a js-value into a Pattern for matching resources.
pub fn js_value_to_pattern(value: &JsValue) -> Pattern { pub fn js_value_to_pattern(value: &JsValue) -> Pattern {
let mut result = match value { match value {
JsValue::Constant(v) => Pattern::Constant(match v { JsValue::Constant(v) => Pattern::Constant(match v {
ConstantValue::Str(str) => str.as_str().into(), ConstantValue::Str(str) => {
ConstantValue::True => "true".into(), // Normalize windows file paths when constructing the pattern.
ConstantValue::False => "false".into(), // See PACK-3279
ConstantValue::Null => "null".into(), if str.as_str().contains("\\") {
RcStr::from(str.to_string().replace('\\', "/"))
} else {
str.as_rcstr()
}
}
ConstantValue::True => rcstr!("true"),
ConstantValue::False => rcstr!("false"),
ConstantValue::Null => rcstr!("null"),
ConstantValue::Num(ConstantNumber(n)) => n.to_string().into(), ConstantValue::Num(ConstantNumber(n)) => n.to_string().into(),
ConstantValue::BigInt(n) => n.to_string().into(), ConstantValue::BigInt(n) => n.to_string().into(),
ConstantValue::Regex(box (exp, flags)) => format!("/{exp}/{flags}").into(), ConstantValue::Regex(box (exp, flags)) => format!("/{exp}/{flags}").into(),
ConstantValue::Undefined => "undefined".into(), ConstantValue::Undefined => rcstr!("undefined"),
}), }),
JsValue::Url(v, JsValueUrlKind::Relative) => Pattern::Constant(v.as_str().into()), JsValue::Url(v, JsValueUrlKind::Relative) => Pattern::Constant(v.as_rcstr()),
JsValue::Alternatives { JsValue::Alternatives {
total_nodes: _, total_nodes: _,
values, values,
logical_property: _, logical_property: _,
} => Pattern::Alternatives(values.iter().map(js_value_to_pattern).collect()), } => {
let mut alts = Pattern::Alternatives(values.iter().map(js_value_to_pattern).collect());
alts.normalize();
alts
}
JsValue::Concat(_, parts) => { JsValue::Concat(_, parts) => {
Pattern::Concatenation(parts.iter().map(js_value_to_pattern).collect()) let mut concats =
Pattern::Concatenation(parts.iter().map(js_value_to_pattern).collect());
concats.normalize();
concats
} }
JsValue::Add(..) => { JsValue::Add(..) => {
// TODO do we need to handle that here // TODO do we need to handle that here
...@@ -51,9 +68,7 @@ pub fn js_value_to_pattern(value: &JsValue) -> Pattern { ...@@ -51,9 +68,7 @@ pub fn js_value_to_pattern(value: &JsValue) -> Pattern {
Pattern::Dynamic Pattern::Dynamic
} }
_ => Pattern::Dynamic, _ => Pattern::Dynamic,
}; }
result.normalize();
result
} }
const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1; const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;
...@@ -200,3 +215,32 @@ pub fn module_value_to_well_known_object(module_value: &ModuleValue) -> Option<J ...@@ -200,3 +215,32 @@ pub fn module_value_to_well_known_object(module_value: &ModuleValue) -> Option<J
_ => return None, _ => return None,
}) })
} }
#[cfg(test)]
mod tests {
use turbo_rcstr::rcstr;
use turbopack_core::resolve::pattern::Pattern;
use crate::{
analyzer::{ConstantString, ConstantValue, JsValue},
utils::js_value_to_pattern,
};
#[test]
fn test_path_normalization_in_pattern() {
assert_eq!(
Pattern::Constant(rcstr!("hello/world")),
js_value_to_pattern(&JsValue::Constant(ConstantValue::Str(
ConstantString::RcStr(rcstr!("hello\\world"))
)))
);
assert_eq!(
Pattern::Constant(rcstr!("hello/world")),
js_value_to_pattern(&JsValue::Concat(
1,
vec!["hello".into(), "\\".into(), "world".into()]
))
);
}
}
...@@ -12,8 +12,7 @@ use serde::Deserialize; ...@@ -12,8 +12,7 @@ use serde::Deserialize;
use serde_json::json; use serde_json::json;
use turbo_rcstr::{RcStr, rcstr}; use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ use turbo_tasks::{
ReadConsistency, ReadRef, ResolvedVc, TryJoinIterExt, TurboTasks, ValueToString, Vc, ReadConsistency, ReadRef, ResolvedVc, TurboTasks, ValueToString, Vc, apply_effects,
apply_effects,
}; };
use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage}; use turbo_tasks_backend::{BackendOptions, TurboTasksBackend, noop_backing_storage};
use turbo_tasks_env::DotenvProcessEnv; use turbo_tasks_env::DotenvProcessEnv;
...@@ -495,11 +494,7 @@ async fn walk_asset( ...@@ -495,11 +494,7 @@ async fn walk_asset(
.await? .await?
.iter() .iter()
.copied() .copied()
.map(|asset| async move { Ok(ResolvedVc::try_downcast::<Box<dyn OutputAsset>>(asset)) }) .flat_map(ResolvedVc::try_downcast::<Box<dyn OutputAsset>>),
.try_join()
.await?
.into_iter()
.flatten(),
); );
Ok(()) Ok(())
......
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