Repository: vercel/next.js
Pull request: [turbopack] Fix a few small things in the analyzer

* Delete some dead code
* Remove some unnecessary `async` and `pub` modifiers
     * i think the `async`'s were made unnecesssary when we made `FilesystemPath` no longer be a `Vc<>`

Closes PACK-5315

Changed files:
filename: turbopack/crates/turbopack-ecmascript/src/analyzer/mod.rs
patch: @@ -4,10 +4,8 @@ use std::{
     borrow::Cow,
     cmp::Ordering,
     fmt::{Display, Formatter, Write},
-    future::Future,
     hash::{BuildHasherDefault, Hash, Hasher},
     mem::take,
-    pin::Pin,
     sync::Arc,
 };
 
@@ -45,11 +43,6 @@ pub mod linker;
 pub mod top_level_await;
 pub mod well_known;
 
-type PinnedAsyncUntilSettledBox<'a, E> =
-    Pin<Box<dyn Future<Output = Result<(JsValue, bool), E>> + Send + 'a>>;
-
-type PinnedAsyncBox<'a, E> = Pin<Box<dyn Future<Output = Result<(JsValue, bool), E>> + 'a>>;
-
 #[derive(Debug, Clone, Hash, PartialEq, Eq)]
 pub enum ObjectPart {
     KeyValue(JsValue, JsValue),
@@ -2610,301 +2603,8 @@ fn shortcircuit_if_known<T: Copy>(
     None
 }
 
-/// Macro to visit all children of a node with an async function
-macro_rules! for_each_children_async {
-    ($value:expr, $visit_fn:expr, $($args:expr),+) => {
-        Ok(match &mut $value {
-            JsValue::Alternatives { total_nodes: _, values: list, logical_property: _ }
-            | JsValue::Concat(_, list)
-            | JsValue::Add(_, list)
-            | JsValue::Logical(_, _, list)
-            | JsValue::Array{ items: list, ..} => {
-                let mut modified = false;
-                for item in list.iter_mut() {
-                    let (v, m) = $visit_fn(take(item), $($args),+).await?;
-                    *item = v;
-                    if m {
-                        modified = true
-                    }
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::Object{ parts, ..} => {
-                let mut modified = false;
-                for item in parts.iter_mut() {
-                    match item {
-                        ObjectPart::KeyValue(key, value) => {
-                            let (v, m) = $visit_fn(take(key), $($args),+).await?;
-                            *key = v;
-                            if m {
-                                modified = true
-                            }
-                            let (v, m) = $visit_fn(take(value), $($args),+).await?;
-                            *value = v;
-                            if m {
-                                modified = true
-                            }
-                        }
-                        ObjectPart::Spread(value) => {
-                            let (v, m) = $visit_fn(take(value), $($args),+).await?;
-                            *value = v;
-                            if m {
-                                modified = true
-                            }
-                        }
-                    }
-
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::New(_, box callee, list) => {
-                let (new_callee, mut modified) = $visit_fn(take(callee), $($args),+).await?;
-                *callee = new_callee;
-                for item in list.iter_mut() {
-                    let (v, m) = $visit_fn(take(item), $($args),+).await?;
-                    *item = v;
-                    if m {
-                        modified = true
-                    }
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::Call(_, box callee, list) => {
-                let (new_callee, mut modified) = $visit_fn(take(callee), $($args),+).await?;
-                *callee = new_callee;
-                for item in list.iter_mut() {
-                    let (v, m) = $visit_fn(take(item), $($args),+).await?;
-                    *item = v;
-                    if m {
-                        modified = true
-                    }
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::SuperCall(_, list) => {
-                let mut modified = false;
-                for item in list.iter_mut() {
-                    let (v, m) = $visit_fn(take(item), $($args),+).await?;
-                    *item = v;
-                    if m {
-                        modified = true
-                    }
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::MemberCall(_, box obj, box prop, list) => {
-                let (new_callee, m1) = $visit_fn(take(obj), $($args),+).await?;
-                *obj = new_callee;
-                let (new_member, m2) = $visit_fn(take(prop), $($args),+).await?;
-                *prop = new_member;
-                let mut modified = m1 || m2;
-                for item in list.iter_mut() {
-                    let (v, m) = $visit_fn(take(item), $($args),+).await?;
-                    *item = v;
-                    if m {
-                        modified = true
-                    }
-                }
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-
-            JsValue::Function(_, _, box return_value) => {
-                let (new_return_value, modified) = $visit_fn(take(return_value), $($args),+).await?;
-                *return_value = new_return_value;
-
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::Not(_, box value) => {
-                let (new_value, modified) = $visit_fn(take(value), $($args),+).await?;
-                *value = new_value;
-
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::Binary(_, box a, _, box b) => {
-                let (v, m1) = $visit_fn(take(a), $($args),+).await?;
-                *a = v;
-                let (v, m2) = $visit_fn(take(b), $($args),+).await?;
-                *b = v;
-                $value.update_total_nodes();
-                ($value, m1 || m2)
-            }
-            JsValue::Tenary(_, box test, box cons, box alt) => {
-                let (v, m1) = $visit_fn(take(test), $($args),+).await?;
-                *test = v;
-                let (v, m2) = $visit_fn(take(cons), $($args),+).await?;
-                *cons = v;
-                let (v, m3) = $visit_fn(take(alt), $($args),+).await?;
-                *alt = v;
-                $value.update_total_nodes();
-                ($value, m1 || m2 || m3)
-            }
-            JsValue::Member(_, box obj, box prop) => {
-                let (v, m1) = $visit_fn(take(obj), $($args),+).await?;
-                *obj = v;
-                let (v, m2) = $visit_fn(take(prop), $($args),+).await?;
-                *prop = v;
-                $value.update_total_nodes();
-                ($value, m1 || m2)
-            }
-            JsValue::Iterated(_, box operand)
-            | JsValue::TypeOf(_, box operand)
-            | JsValue::Promise(_, box operand)
-            | JsValue::Awaited(_, box operand) => {
-                let (new_operand, modified) = $visit_fn(take(operand), $($args),+).await?;
-                *operand = new_operand;
-
-                $value.update_total_nodes();
-                ($value, modified)
-            }
-            JsValue::Constant(_)
-            | JsValue::FreeVar(_)
-            | JsValue::Variable(_)
-            | JsValue::Module(..)
-            | JsValue::Url(_, _)
-            | JsValue::WellKnownObject(_)
-            | JsValue::WellKnownFunction(_)
-            | JsValue::Unknown { .. }
-            | JsValue::Argument(..) => ($value, false),
-        })
-    }
-}
-
 // Visiting
 impl JsValue {
-    /// Visit the node and all its children with a function in a loop until the
-    /// visitor returns false for the node and all children
-    pub async fn visit_async_until_settled<'a, F, R, E>(
-        self,
-        visitor: &mut F,
-    ) -> Result<(Self, bool), E>
-    where
-        R: 'a + Future<Output = Result<(Self, bool), E>> + Send,
-        F: 'a + FnMut(JsValue) -> R + Send,
-    {
-        let mut modified = false;
-        let mut v = self;
-        loop {
-            let m;
-            (v, m) = visitor(take(&mut v)).await?;
-            if !m {
-                break;
-            }
-            modified = true;
-            v = take(&mut v)
-                .visit_each_children_async_until_settled(visitor)
-                .await?;
-        }
-        Ok((v, modified))
-    }
-
-    /// Visit all children of the node with an async function in a loop until
-    /// the visitor returns false
-    pub async fn visit_each_children_async_until_settled<'a, F, R, E>(
-        mut self,
-        visitor: &mut F,
-    ) -> Result<Self, E>
-    where
-        R: 'a + Future<Output = Result<(Self, bool), E>> + Send,
-        F: 'a + FnMut(JsValue) -> R + Send,
-    {
-        fn visit_async_until_settled_box<'a, F, R, E>(
-            value: JsValue,
-            visitor: &'a mut F,
-        ) -> PinnedAsyncUntilSettledBox<'a, E>
-        where
-            R: 'a + Future<Output = Result<(JsValue, bool), E>> + Send,
-            F: 'a + FnMut(JsValue) -> R + Send,
-            E: 'a,
-        {
-            Box::pin(value.visit_async_until_settled(visitor))
-        }
-        let (v, _) = for_each_children_async!(self, visit_async_until_settled_box, visitor)?;
-        Ok(v)
-    }
-
-    /// Visit the node and all its children with an async function.
-    pub async fn visit_async<'a, F, R, E>(self, visitor: &mut F) -> Result<(Self, bool), E>
-    where
-        R: 'a + Future<Output = Result<(Self, bool), E>>,
-        F: 'a + FnMut(JsValue) -> R,
-    {
-        let (v, modified) = self.visit_each_children_async(visitor).await?;
-        let (v, m) = visitor(v).await?;
-        if m { Ok((v, true)) } else { Ok((v, modified)) }
-    }
-
-    /// Visit all children of the node with an async function.
-    pub async fn visit_each_children_async<'a, F, R, E>(
-        mut self,
-        visitor: &mut F,
-    ) -> Result<(Self, bool), E>
-    where
-        R: 'a + Future<Output = Result<(Self, bool), E>>,
-        F: 'a + FnMut(JsValue) -> R,
-    {
-        fn visit_async_box<'a, F, R, E>(value: JsValue, visitor: &'a mut F) -> PinnedAsyncBox<'a, E>
-        where
-            R: 'a + Future<Output = Result<(JsValue, bool), E>>,
-            F: 'a + FnMut(JsValue) -> R,
-            E: 'a,
-        {
-            Box::pin(value.visit_async(visitor))
-        }
-        for_each_children_async!(self, visit_async_box, visitor)
-    }
-
-    /// Call an async function for each child of the node.
-    pub async fn for_each_children_async<'a, F, R, E>(
-        mut self,
-        visitor: &mut F,
-    ) -> Result<(Self, bool), E>
-    where
-        R: 'a + Future<Output = Result<(Self, bool), E>>,
-        F: 'a + FnMut(JsValue) -> R,
-    {
-        for_each_children_async!(self, |v, ()| visitor(v), ())
-    }
-
-    /// Visit the node and all its children with a function in a loop until the
-    /// visitor returns false
-    pub fn visit_mut_until_settled(&mut self, visitor: &mut impl FnMut(&mut JsValue) -> bool) {
-        while visitor(self) {
-            self.for_each_children_mut(&mut |value| {
-                value.visit_mut_until_settled(visitor);
-                false
-            });
-        }
-    }
-
-    /// Visit the node and all its children with a function.
-    pub fn visit_mut(&mut self, visitor: &mut impl FnMut(&mut JsValue) -> bool) -> bool {
-        let modified = self.for_each_children_mut(&mut |value| value.visit_mut(visitor));
-        if visitor(self) { true } else { modified }
-    }
-
-    /// Visit all children of the node with a function. Only visits nodes where
-    /// the condition is true.
-    pub fn visit_mut_conditional(
-        &mut self,
-        condition: impl Fn(&JsValue) -> bool,
-        visitor: &mut impl FnMut(&mut JsValue) -> bool,
-    ) -> bool {
-        if condition(self) {
-            let modified = self.for_each_children_mut(&mut |value| value.visit_mut(visitor));
-            if visitor(self) { true } else { modified }
-        } else {
-            false
-        }
-    }
-
     /// Calls a function for each child of the node. Allows mutating the node.
     /// Updates the total nodes count after mutation.
     pub fn for_each_children_mut(

filename: turbopack/crates/turbopack-ecmascript/src/analyzer/well_known.rs
patch: @@ -61,13 +61,13 @@ pub async fn well_known_function_call(
         WellKnownFunctionKind::Import => import(args),
         WellKnownFunctionKind::Require => require(args),
         WellKnownFunctionKind::RequireContextRequire(value) => {
-            require_context_require(value, args).await?
+            require_context_require(value, args)?
         }
         WellKnownFunctionKind::RequireContextRequireKeys(value) => {
-            require_context_require_keys(value, args).await?
+            require_context_require_keys(value, args)?
         }
         WellKnownFunctionKind::RequireContextRequireResolve(value) => {
-            require_context_require_resolve(value, args).await?
+            require_context_require_resolve(value, args)?
         }
         WellKnownFunctionKind::PathToFileUrl => path_to_file_url(args),
         WellKnownFunctionKind::OsArch => compile_time_info
@@ -118,7 +118,7 @@ pub async fn well_known_function_call(
     })
 }
 
-pub fn object_assign(args: Vec<JsValue>) -> JsValue {
+fn object_assign(args: Vec<JsValue>) -> JsValue {
     if args.iter().all(|arg| matches!(arg, JsValue::Object { .. })) {
         if let Some(mut merged_object) = args.into_iter().reduce(|mut acc, cur| {
             if let JsValue::Object { parts, mutable, .. } = &mut acc
@@ -161,7 +161,7 @@ pub fn object_assign(args: Vec<JsValue>) -> JsValue {
     }
 }
 
-pub fn path_join(args: Vec<JsValue>) -> JsValue {
+fn path_join(args: Vec<JsValue>) -> JsValue {
     if args.is_empty() {
         return rcstr!(".").into();
     }
@@ -217,7 +217,7 @@ pub fn path_join(args: Vec<JsValue>) -> JsValue {
     JsValue::concat(results)
 }
 
-pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
+fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
     // If no path segments are passed, `path.resolve()` will return the absolute
     // path of the current working directory.
     if args.is_empty() {
@@ -292,7 +292,7 @@ pub fn path_resolve(cwd: JsValue, mut args: Vec<JsValue>) -> JsValue {
     JsValue::concat(results)
 }
 
-pub fn path_dirname(mut args: Vec<JsValue>) -> JsValue {
+fn path_dirname(mut args: Vec<JsValue>) -> JsValue {
     if let Some(arg) = args.iter_mut().next() {
         if let Some(str) = arg.as_str() {
             if let Some(i) = str.rfind('/') {
@@ -344,7 +344,7 @@ pub fn import(args: Vec<JsValue>) -> JsValue {
 
 /// Resolve the contents of a require call, throwing errors
 /// if we come across any unsupported syntax.
-pub fn require(args: Vec<JsValue>) -> JsValue {
+fn require(args: Vec<JsValue>) -> JsValue {
     if args.len() == 1 {
         if let Some(s) = args[0].as_str() {
             JsValue::Module(ModuleValue {
@@ -374,7 +374,7 @@ pub fn require(args: Vec<JsValue>) -> JsValue {
 }
 
 /// (try to) statically evaluate `require.context(...)()`
-async fn require_context_require(val: RequireContextValue, args: Vec<JsValue>) -> Result<JsValue> {
+fn require_context_require(val: RequireContextValue, args: Vec<JsValue>) -> Result<JsValue> {
     if args.is_empty() {
         return Ok(JsValue::unknown(
             JsValue::call(
@@ -422,10 +422,7 @@ async fn require_context_require(val: RequireContextValue, args: Vec<JsValue>) -
 }
 
 /// (try to) statically evaluate `require.context(...).keys()`
-async fn require_context_require_keys(
-    val: RequireContextValue,
-    args: Vec<JsValue>,
-) -> Result<JsValue> {
+fn require_context_require_keys(val: RequireContextValue, args: Vec<JsValue>) -> Result<JsValue> {
     Ok(if args.is_empty() {
         JsValue::array(val.0.keys().cloned().map(|k| k.into()).collect())
     } else {
@@ -443,7 +440,7 @@ async fn require_context_require_keys(
 }
 
 /// (try to) statically evaluate `require.context(...).resolve()`
-async fn require_context_require_resolve(
+fn require_context_require_resolve(
     val: RequireContextValue,
     args: Vec<JsValue>,
 ) -> Result<JsValue> {
@@ -490,7 +487,7 @@ async fn require_context_require_resolve(
     Ok(m.as_str().into())
 }
 
-pub fn path_to_file_url(args: Vec<JsValue>) -> JsValue {
+fn path_to_file_url(args: Vec<JsValue>) -> JsValue {
     if args.len() == 1 {
         if let Some(path) = args[0].as_str() {
             Url::from_file_path(path)
@@ -533,7 +530,7 @@ pub fn path_to_file_url(args: Vec<JsValue>) -> JsValue {
     }
 }
 
-pub fn well_known_function_member(kind: WellKnownFunctionKind, prop: JsValue) -> (JsValue, bool) {
+fn well_known_function_member(kind: WellKnownFunctionKind, prop: JsValue) -> (JsValue, bool) {
     let new_value = match (kind, prop.as_str()) {
         (WellKnownFunctionKind::Require, Some("resolve")) => {
             JsValue::WellKnownFunction(WellKnownFunctionKind::RequireResolve)
@@ -570,7 +567,7 @@ pub fn well_known_function_member(kind: WellKnownFunctionKind, prop: JsValue) ->
     (new_value, true)
 }
 
-pub async fn well_known_object_member(
+async fn well_known_object_member(
     kind: WellKnownObjectKind,
     prop: JsValue,
     compile_time_info: Vc<CompileTimeInfo>,
@@ -621,7 +618,7 @@ fn global_object(prop: JsValue) -> JsValue {
     }
 }
 
-pub fn path_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
+fn path_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     match (kind, prop.as_str()) {
         (.., Some("join")) => JsValue::WellKnownFunction(WellKnownFunctionKind::PathJoin),
         (.., Some("dirname")) => JsValue::WellKnownFunction(WellKnownFunctionKind::PathDirname),
@@ -645,7 +642,7 @@ pub fn path_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     }
 }
 
-pub fn fs_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
+fn fs_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     if let Some(word) = prop.as_str() {
         match (kind, word) {
             (
@@ -676,7 +673,7 @@ pub fn fs_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     )
 }
 
-pub fn url_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
+fn url_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     match (kind, prop.as_str()) {
         (.., Some("pathToFileURL")) => {
             JsValue::WellKnownFunction(WellKnownFunctionKind::PathToFileUrl)
@@ -695,7 +692,7 @@ pub fn url_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     }
 }
 
-pub fn child_process_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
+fn child_process_module_member(kind: WellKnownObjectKind, prop: JsValue) -> JsValue {
     let prop_str = prop.as_str();
     match (kind, prop_str) {
         (.., Some("spawn" | "spawnSync" | "execFile" | "execFileSync")) => {

filename: turbopack/crates/turbopack-ecmascript/src/references/external_module.rs
patch: @@ -360,12 +360,6 @@ pub struct CachedExternalModuleChunkItem {
     chunking_context: ResolvedVc<Box<dyn ChunkingContext>>,
 }
 
-// Without this wrapper, VirtualFileSystem::new_with_name always returns a new filesystem
-#[turbo_tasks::function]
-fn external_fs() -> Vc<VirtualFileSystem> {
-    VirtualFileSystem::new_with_name(rcstr!("externals"))
-}
-
 #[turbo_tasks::value_impl]
 impl ChunkItem for CachedExternalModuleChunkItem {
     #[turbo_tasks::function]

filename: turbopack/crates/turbopack-ecmascript/src/references/mod.rs
patch: @@ -2638,7 +2638,7 @@ async fn handle_free_var_reference(
                 InputRelativeConstant::FileName => source_path,
             };
             analysis.add_code_gen(ConstantValueCodeGen::new(
-                as_abs_path(source_path).await?.into(),
+                as_abs_path(source_path).into(),
                 ast_path.to_vec().into(),
             ));
         }
@@ -2840,17 +2840,17 @@ async fn analyze_amd_define_with_deps(
 
 /// Used to generate the "root" path to a __filename/__dirname/import.meta.url
 /// reference.
-pub async fn as_abs_path(path: FileSystemPath) -> Result<String> {
+pub fn as_abs_path(path: FileSystemPath) -> String {
     // TODO: This should be updated to generate a real system path on the fly
     // during runtime, so that the generated code is constant between systems
     // but the runtime evaluation can take into account the project's
     // actual root directory.
-    require_resolve(path).await
+    require_resolve(path)
 }
 
 /// Generates an absolute path usable for `require.resolve()` calls.
-async fn require_resolve(path: FileSystemPath) -> Result<String> {
-    Ok(format!("/ROOT/{}", path.path.as_str()))
+fn require_resolve(path: FileSystemPath) -> String {
+    format!("/ROOT/{}", path.path.as_str())
 }
 
 async fn early_value_visitor(mut v: JsValue) -> Result<(JsValue, bool)> {
@@ -2977,12 +2977,8 @@ async fn value_visitor_inner(
             }
         }
         JsValue::FreeVar(ref kind) => match &**kind {
-            "__dirname" => as_abs_path(origin.origin_path().owned().await?.parent())
-                .await?
-                .into(),
-            "__filename" => as_abs_path(origin.origin_path().owned().await?)
-                .await?
-                .into(),
+            "__dirname" => as_abs_path(origin.origin_path().owned().await?.parent()).into(),
+            "__filename" => as_abs_path(origin.origin_path().owned().await?).into(),
 
             "require" => JsValue::unknown_if(
                 ignore,
@@ -3051,9 +3047,7 @@ async fn require_resolve_visitor(
             .await?
             .iter()
             .map(|&source| async move {
-                require_resolve(source.ident().path().owned().await?)
-                    .await
-                    .map(JsValue::from)
+                Ok(require_resolve(source.ident().path().owned().await?).into())
             })
             .try_join()
             .await?;