File size: 8,991 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 |
use std::ops::Deref;
use serde::{Deserialize, Serialize};
use swc_core::{
common::{DUMMY_SP, SyntaxContext},
ecma::{
ast::{Expr, Lit, Str},
visit::AstParentKind,
},
};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{NonLocalValue, TaskInput, trace::TraceRawVcs};
use turbopack_core::{chunk::ModuleId, resolve::pattern::Pattern};
use crate::analyzer::{
ConstantNumber, ConstantValue, JsValue, JsValueUrlKind, ModuleValue, WellKnownFunctionKind,
WellKnownObjectKind,
};
pub fn unparen(expr: &Expr) -> &Expr {
if let Some(expr) = expr.as_paren() {
return unparen(&expr.expr);
}
if let Expr::Seq(seq) = expr {
return unparen(seq.exprs.last().unwrap());
}
expr
}
/// Converts a js-value into a Pattern for matching resources.
pub fn js_value_to_pattern(value: &JsValue) -> Pattern {
match value {
JsValue::Constant(v) => Pattern::Constant(match v {
ConstantValue::Str(str) => {
// Normalize windows file paths when constructing the pattern.
// See PACK-3279
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::BigInt(n) => n.to_string().into(),
ConstantValue::Regex(box (exp, flags)) => format!("/{exp}/{flags}").into(),
ConstantValue::Undefined => rcstr!("undefined"),
}),
JsValue::Url(v, JsValueUrlKind::Relative) => Pattern::Constant(v.as_rcstr()),
JsValue::Alternatives {
total_nodes: _,
values,
logical_property: _,
} => {
let mut alts = Pattern::Alternatives(values.iter().map(js_value_to_pattern).collect());
alts.normalize();
alts
}
JsValue::Concat(_, parts) => {
let mut concats =
Pattern::Concatenation(parts.iter().map(js_value_to_pattern).collect());
concats.normalize();
concats
}
JsValue::Add(..) => {
// TODO do we need to handle that here
// or is that already covered by normalization of JsValue
Pattern::Dynamic
}
_ => Pattern::Dynamic,
}
}
const JS_MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;
pub fn module_id_to_lit(module_id: &ModuleId) -> Expr {
Expr::Lit(match module_id {
ModuleId::Number(n) => {
if *n <= JS_MAX_SAFE_INTEGER {
Lit::Num((*n as f64).into())
} else {
Lit::Str(Str {
span: DUMMY_SP,
value: n.to_string().into(),
raw: None,
})
}
}
ModuleId::String(s) => Lit::Str(Str {
span: DUMMY_SP,
value: (s as &str).into(),
raw: None,
}),
})
}
pub struct StringifyModuleId<'a>(pub &'a ModuleId);
impl std::fmt::Display for StringifyModuleId<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
ModuleId::Number(n) => {
if *n <= JS_MAX_SAFE_INTEGER {
n.fmt(f)
} else {
write!(f, "\"{n}\"")
}
}
ModuleId::String(s) => StringifyJs(s).fmt(f),
}
}
}
pub struct StringifyJs<'a, T>(pub &'a T)
where
T: ?Sized;
impl<T> std::fmt::Display for StringifyJs<'_, T>
where
T: Serialize + ?Sized,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
/// [`std::fmt::Formatter`] does not implement [`std::io::Write`],
/// so we need to wrap it in a struct that does.
struct DisplayWriter<'a, 'b> {
f: &'a mut std::fmt::Formatter<'b>,
}
impl std::io::Write for DisplayWriter<'_, '_> {
fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> {
self.f
.write_str(std::str::from_utf8(bytes).map_err(std::io::Error::other)?)
.map_err(std::io::Error::other)?;
Ok(bytes.len())
}
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
unreachable!()
}
}
let to_writer = match f.alternate() {
true => serde_json::to_writer_pretty,
false => serde_json::to_writer,
};
to_writer(DisplayWriter { f }, self.0).map_err(|_err| std::fmt::Error)
}
}
pub struct FormatIter<T: Iterator, F: Fn() -> T>(pub F);
macro_rules! format_iter {
($trait:path) => {
impl<T: Iterator, F: Fn() -> T> $trait for FormatIter<T, F>
where
T::Item: $trait,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for item in self.0() {
item.fmt(f)?;
}
Ok(())
}
}
};
}
format_iter!(std::fmt::Binary);
format_iter!(std::fmt::Debug);
format_iter!(std::fmt::Display);
format_iter!(std::fmt::LowerExp);
format_iter!(std::fmt::LowerHex);
format_iter!(std::fmt::Octal);
format_iter!(std::fmt::Pointer);
format_iter!(std::fmt::UpperExp);
format_iter!(std::fmt::UpperHex);
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, TraceRawVcs, Debug, NonLocalValue)]
pub enum AstPathRange {
/// The ast path to the block or expression.
Exact(#[turbo_tasks(trace_ignore)] Vec<AstParentKind>),
/// The ast path to a expression just before the range in the parent of the
/// specific ast path.
StartAfter(#[turbo_tasks(trace_ignore)] Vec<AstParentKind>),
}
/// Converts a module value (ie an import) to a well known object,
/// which we specifically handle.
pub fn module_value_to_well_known_object(module_value: &ModuleValue) -> Option<JsValue> {
Some(match &*module_value.module {
"node:path" | "path" => JsValue::WellKnownObject(WellKnownObjectKind::PathModule),
"node:fs/promises" | "fs/promises" => {
JsValue::WellKnownObject(WellKnownObjectKind::FsModule)
}
"node:fs" | "fs" => JsValue::WellKnownObject(WellKnownObjectKind::FsModule),
"node:child_process" | "child_process" => {
JsValue::WellKnownObject(WellKnownObjectKind::ChildProcess)
}
"node:os" | "os" => JsValue::WellKnownObject(WellKnownObjectKind::OsModule),
"node:process" | "process" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProcess),
"node-pre-gyp" | "@mapbox/node-pre-gyp" => {
JsValue::WellKnownObject(WellKnownObjectKind::NodePreGyp)
}
"node-gyp-build" => JsValue::WellKnownFunction(WellKnownFunctionKind::NodeGypBuild),
"node:bindings" | "bindings" => {
JsValue::WellKnownFunction(WellKnownFunctionKind::NodeBindings)
}
"express" => JsValue::WellKnownFunction(WellKnownFunctionKind::NodeExpress),
"strong-globalize" => {
JsValue::WellKnownFunction(WellKnownFunctionKind::NodeStrongGlobalize)
}
"resolve-from" => JsValue::WellKnownFunction(WellKnownFunctionKind::NodeResolveFrom),
"@grpc/proto-loader" => JsValue::WellKnownObject(WellKnownObjectKind::NodeProtobufLoader),
_ => return None,
})
}
#[derive(Hash, Debug, Clone, Copy, Eq, Serialize, Deserialize, PartialEq, TraceRawVcs)]
pub struct AstSyntaxContext(#[turbo_tasks(trace_ignore)] SyntaxContext);
impl TaskInput for AstSyntaxContext {
fn is_transient(&self) -> bool {
false
}
}
unsafe impl NonLocalValue for AstSyntaxContext {}
impl Deref for AstSyntaxContext {
type Target = SyntaxContext;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<SyntaxContext> for AstSyntaxContext {
fn from(v: SyntaxContext) -> Self {
Self(v)
}
}
#[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()]
))
);
}
}
|