Skip to content

Commit

Permalink
codemod(turbopack): Inline trivial uses of let this = self (vercel#…
Browse files Browse the repository at this point in the history
…70431)

A follow-up to the vercel#70431 codemod diff, which leave behind a lot of
trivial `let this = self;` statements.

Using the following ast-grep rule config:

```yaml
language: rust
id: inline_trivial_this

utils:
  block-with-this:
    all:
    - pattern: $BLOCK
    - kind: block
    - has:
        all:
          - pattern: let this = $SELF;
          - any:
            - pattern: let this = self;
            - pattern: let this = &self.0;

rule:
  matches: block-with-this

rewriters:
  - id: remove-let-this
    rule:
      pattern: let this = $SELF;
    fix: ""
  - id: inline-this-auto-deref
    rule:
      pattern: this
      inside:
        kind: field_expression
    transform:
      SELF_AUTO_DEREF:
        replace:
          source: $SELF
          replace: "&?(?<INNER>.*)"
          by: "$INNER"
    fix: $SELF_AUTO_DEREF
  - id: inline-this
    rule:
      pattern: this
    fix: $SELF

transform:
  NEW_BLOCK:
    rewrite:
      source: $BLOCK
      rewriters:
        - remove-let-this
        - inline-this-auto-deref
        - inline-this

fix:
  $NEW_BLOCK
```

Applied with

```
sg scan -U -r ../codemod_inline_trivial_this.yml .
```
  • Loading branch information
bgw authored and abhi12299 committed Sep 29, 2024
1 parent b712fdf commit 3ee8e76
Show file tree
Hide file tree
Showing 42 changed files with 149 additions and 233 deletions.
6 changes: 2 additions & 4 deletions crates/next-api/src/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,12 +256,10 @@ impl MiddlewareEndpoint {

#[turbo_tasks::function]
async fn userland_module(&self) -> Result<Vc<Box<dyn Module>>> {
let this = self;

Ok(this
Ok(self
.asset_context
.process(
this.source,
self.source,
Value::new(ReferenceType::Entry(EntryReferenceSubType::Middleware)),
)
.module())
Expand Down
19 changes: 8 additions & 11 deletions crates/next-api/src/pages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -641,8 +641,7 @@ impl PageEndpoint {

#[turbo_tasks::function]
async fn source(&self) -> Result<Vc<Box<dyn Source>>> {
let this = self;
Ok(Vc::upcast(FileSource::new(this.page.project_path())))
Ok(Vc::upcast(FileSource::new(self.page.project_path())))
}

#[turbo_tasks::function]
Expand Down Expand Up @@ -949,8 +948,7 @@ impl PageEndpoint {
&self,
entry_chunk: Vc<Box<dyn OutputAsset>>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
let this = self;
let node_root = this.pages_project.project().node_root();
let node_root = self.pages_project.project().node_root();
let chunk_path = entry_chunk.ident().path().await?;

let asset_path = node_root
Expand All @@ -960,11 +958,11 @@ impl PageEndpoint {
.context("ssr chunk entry path must be inside the node root")?;

let pages_manifest = PagesManifest {
pages: [(this.pathname.await?.clone_value(), asset_path.into())]
pages: [(self.pathname.await?.clone_value(), asset_path.into())]
.into_iter()
.collect(),
};
let manifest_path_prefix = get_asset_prefix_from_pathname(&this.pathname.await?);
let manifest_path_prefix = get_asset_prefix_from_pathname(&self.pathname.await?);
Ok(Vc::upcast(VirtualOutputAsset::new(
node_root
.join(format!("server/pages{manifest_path_prefix}/pages-manifest.json",).into()),
Expand Down Expand Up @@ -994,13 +992,12 @@ impl PageEndpoint {
&self,
client_chunks: Vc<OutputAssets>,
) -> Result<Vc<Box<dyn OutputAsset>>> {
let this = self;
let node_root = this.pages_project.project().node_root();
let client_relative_path = this.pages_project.project().client_relative_path();
let node_root = self.pages_project.project().node_root();
let client_relative_path = self.pages_project.project().client_relative_path();
let client_relative_path_ref = client_relative_path.await?;
let build_manifest = BuildManifest {
pages: [(
this.pathname.await?.clone_value(),
self.pathname.await?.clone_value(),
client_chunks
.await?
.iter()
Expand All @@ -1022,7 +1019,7 @@ impl PageEndpoint {
.collect(),
..Default::default()
};
let manifest_path_prefix = get_asset_prefix_from_pathname(&this.pathname.await?);
let manifest_path_prefix = get_asset_prefix_from_pathname(&self.pathname.await?);
Ok(Vc::upcast(VirtualOutputAsset::new(
node_root
.join(format!("server/pages{manifest_path_prefix}/build-manifest.json",).into()),
Expand Down
14 changes: 5 additions & 9 deletions crates/next-api/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,8 +302,6 @@ impl ProjectContainer {
impl ProjectContainer {
#[turbo_tasks::function]
pub async fn project(&self) -> Result<Vc<Project>> {
let this = self;

let env_map: Vc<EnvMap>;
let next_config;
let define_env;
Expand All @@ -317,7 +315,7 @@ impl ProjectContainer {
let preview_props;
let browserslist_query;
{
let options = this.options_state.get();
let options = self.options_state.get();
let options = options
.as_ref()
.context("ProjectContainer need to be initialized with initialize()")?;
Expand Down Expand Up @@ -361,7 +359,7 @@ impl ProjectContainer {
} else {
NextMode::Build.cell()
},
versioned_content_map: this.versioned_content_map,
versioned_content_map: self.versioned_content_map,
build_id,
encryption_key,
preview_props,
Expand Down Expand Up @@ -518,13 +516,12 @@ impl Project {

#[turbo_tasks::function]
async fn project_fs(&self) -> Result<Vc<DiskFileSystem>> {
let this = self;
let disk_fs = DiskFileSystem::new(
PROJECT_FILESYSTEM_NAME.into(),
this.root_path.clone(),
self.root_path.clone(),
vec![],
);
if this.watch {
if self.watch {
disk_fs.await?.start_watching_with_invalidation_reason()?;
}
Ok(disk_fs)
Expand All @@ -538,8 +535,7 @@ impl Project {

#[turbo_tasks::function]
pub async fn output_fs(&self) -> Result<Vc<DiskFileSystem>> {
let this = self;
let disk_fs = DiskFileSystem::new("output".into(), this.project_path.clone(), vec![]);
let disk_fs = DiskFileSystem::new("output".into(), self.project_path.clone(), vec![]);
Ok(disk_fs)
}

Expand Down
3 changes: 1 addition & 2 deletions crates/next-core/src/app_structure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -733,8 +733,7 @@ struct DuplicateParallelRouteIssue {
impl Issue for DuplicateParallelRouteIssue {
#[turbo_tasks::function]
async fn file_path(&self) -> Result<Vc<FileSystemPath>> {
let this = self;
Ok(this.app_dir.join(this.page.to_string().into()))
Ok(self.app_dir.join(self.page.to_string().into()))
}

#[turbo_tasks::function]
Expand Down
12 changes: 4 additions & 8 deletions crates/next-core/src/next_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -847,8 +847,7 @@ impl NextConfig {
&self,
active_conditions: Vec<RcStr>,
) -> Result<Vc<OptionWebpackRules>> {
let this = self;
let Some(turbo_rules) = this
let Some(turbo_rules) = self
.experimental
.turbo
.as_ref()
Expand Down Expand Up @@ -936,8 +935,7 @@ impl NextConfig {

#[turbo_tasks::function]
pub async fn resolve_alias_options(&self) -> Result<Vc<ResolveAliasMap>> {
let this = self;
let Some(resolve_alias) = this
let Some(resolve_alias) = self
.experimental
.turbo
.as_ref()
Expand All @@ -951,8 +949,7 @@ impl NextConfig {

#[turbo_tasks::function]
pub async fn resolve_extension(&self) -> Result<Vc<ResolveExtensions>> {
let this = self;
let Some(resolve_extensions) = this
let Some(resolve_extensions) = self
.experimental
.turbo
.as_ref()
Expand Down Expand Up @@ -1148,8 +1145,7 @@ impl NextConfig {

#[turbo_tasks::function]
pub async fn module_id_strategy_config(&self) -> Result<Vc<OptionModuleIdStrategy>> {
let this = self;
let Some(module_id_strategy) = this
let Some(module_id_strategy) = self
.experimental
.turbo
.as_ref()
Expand Down
4 changes: 1 addition & 3 deletions crates/next-core/src/next_dynamic/dynamic_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ impl NextDynamicEntryModule {
&self,
client_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<Vc<OutputAssets>> {
let this = self;

let Some(client_entry_module) =
Vc::try_resolve_sidecast::<Box<dyn ChunkableModule>>(this.client_entry_module).await?
Vc::try_resolve_sidecast::<Box<dyn ChunkableModule>>(self.client_entry_module).await?
else {
bail!("dynamic client asset must be chunkable");
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ impl NextServerComponentModule {

#[turbo_tasks::function]
pub async fn server_path(&self) -> Result<Vc<FileSystemPath>> {
let this = self;
Ok(this.module.ident().path())
Ok(self.module.ident().path())
}
}

Expand Down Expand Up @@ -144,12 +143,11 @@ impl EcmascriptChunkItem for NextServerComponentChunkItem {

#[turbo_tasks::function]
async fn content(&self) -> Result<Vc<EcmascriptChunkItemContent>> {
let this = self;
let inner = this.inner.await?;
let inner = self.inner.await?;

let module_id = inner
.module
.as_chunk_item(Vc::upcast(this.chunking_context))
.as_chunk_item(Vc::upcast(self.chunking_context))
.id()
.await?;
Ok(EcmascriptChunkItemContent {
Expand Down
5 changes: 2 additions & 3 deletions crates/next-core/src/page_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ impl PageLoaderAsset {
&self,
rebase_prefix_path: Vc<FileSystemPathOption>,
) -> Result<Vc<ChunksData>> {
let this = self;
let mut chunks = this.page_chunks;
let mut chunks = self.page_chunks;

// If we are provided a prefix path, we need to rewrite our chunk paths to
// remove that prefix.
Expand All @@ -119,7 +118,7 @@ impl PageLoaderAsset {
chunks = Vc::cell(rebased);
};

Ok(ChunkData::from_assets(this.server_root, chunks))
Ok(ChunkData::from_assets(self.server_root, chunks))
}
}

Expand Down
3 changes: 1 addition & 2 deletions turbopack/crates/turbo-tasks-env/src/dotenv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ impl DotenvProcessEnv {

#[turbo_tasks::function]
pub async fn read_prior(&self) -> Result<Vc<EnvMap>> {
let this = self;
match this.prior {
match self.prior {
None => Ok(EnvMap::empty()),
Some(p) => Ok(p.read_all()),
}
Expand Down
23 changes: 9 additions & 14 deletions turbopack/crates/turbo-tasks-fs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1171,10 +1171,9 @@ impl FileSystemPath {
/// None when the joined path would leave the filesystem root.
#[turbo_tasks::function]
pub async fn try_join(&self, path: RcStr) -> Result<Vc<FileSystemPathOption>> {
let this = self;
if let Some(path) = join_path(&this.path, &path) {
if let Some(path) = join_path(&self.path, &path) {
Ok(Vc::cell(Some(
Self::new_normalized(this.fs, path.into()).resolve().await?,
Self::new_normalized(self.fs, path.into()).resolve().await?,
)))
} else {
Ok(FileSystemPathOption::none())
Expand All @@ -1185,11 +1184,10 @@ impl FileSystemPath {
/// None when the joined path would leave the current path.
#[turbo_tasks::function]
pub async fn try_join_inside(&self, path: RcStr) -> Result<Vc<FileSystemPathOption>> {
let this = self;
if let Some(path) = join_path(&this.path, &path) {
if path.starts_with(&*this.path) {
if let Some(path) = join_path(&self.path, &path) {
if path.starts_with(&*self.path) {
return Ok(Vc::cell(Some(
Self::new_normalized(this.fs, path.into()).resolve().await?,
Self::new_normalized(self.fs, path.into()).resolve().await?,
)));
}
}
Expand Down Expand Up @@ -1217,8 +1215,7 @@ impl FileSystemPath {

#[turbo_tasks::function]
pub async fn extension(&self) -> Result<Vc<RcStr>> {
let this = self;
Ok(Vc::cell(this.extension_ref().unwrap_or("").into()))
Ok(Vc::cell(self.extension_ref().unwrap_or("").into()))
}

#[turbo_tasks::function]
Expand All @@ -1235,10 +1232,9 @@ impl FileSystemPath {
/// extension.
#[turbo_tasks::function]
pub async fn with_extension(&self, extension: RcStr) -> Result<Vc<FileSystemPath>> {
let this = self;
let (path_without_extension, _) = this.split_extension();
let (path_without_extension, _) = self.split_extension();
Ok(Self::new_normalized(
this.fs,
self.fs,
// Like `Path::with_extension` and `PathBuf::set_extension`, if the extension is empty,
// we remove the extension altogether.
match extension.is_empty() {
Expand All @@ -1258,8 +1254,7 @@ impl FileSystemPath {
/// * Otherwise, the portion of the file name before the final `.`
#[turbo_tasks::function]
pub async fn file_stem(&self) -> Result<Vc<Option<RcStr>>> {
let this = self;
let (_, file_stem, _) = this.split_file_stem_extension();
let (_, file_stem, _) = self.split_file_stem_extension();
if file_stem.is_empty() {
return Ok(Vc::cell(None));
}
Expand Down
5 changes: 2 additions & 3 deletions turbopack/crates/turbo-tasks/src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,8 @@ impl Bools {

#[turbo_tasks::function]
async fn into_bools(&self) -> Result<Vc<Vec<bool>>> {
let this = &self.0;

let bools = this
let bools = self
.0
.iter()
.map(|b| b.into_future().map_ok(|b| *b))
.try_join()
Expand Down
7 changes: 3 additions & 4 deletions turbopack/crates/turbopack-browser/src/ecmascript/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,10 @@ impl EcmascriptDevChunkContent {
impl EcmascriptDevChunkContent {
#[turbo_tasks::function]
pub(crate) async fn own_version(&self) -> Result<Vc<EcmascriptDevChunkVersion>> {
let this = self;
Ok(EcmascriptDevChunkVersion::new(
this.chunking_context.output_root(),
this.chunk.ident().path(),
this.entries,
self.chunking_context.output_root(),
self.chunk.ident().path(),
self.entries,
))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,9 @@ impl EcmascriptDevEvaluateChunk {

#[turbo_tasks::function]
async fn chunks_data(&self) -> Result<Vc<ChunksData>> {
let this = self;
Ok(ChunkData::from_assets(
this.chunking_context.output_root(),
this.other_chunks,
self.chunking_context.output_root(),
self.other_chunks,
))
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,10 @@ impl EcmascriptDevChunkListContent {
/// Computes the version of this content.
#[turbo_tasks::function]
pub async fn version(&self) -> Result<Vc<EcmascriptDevChunkListVersion>> {
let this = self;

let mut by_merger = IndexMap::<_, Vec<_>>::new();
let mut by_path = IndexMap::<_, _>::new();

for (chunk_path, chunk_content) in &this.chunks_contents {
for (chunk_path, chunk_content) in &self.chunks_contents {
if let Some(mergeable) =
Vc::try_resolve_sidecast::<Box<dyn MergeableVersionedContent>>(*chunk_content)
.await?
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,13 @@ impl AvailableChunkItems {

#[turbo_tasks::function]
pub async fn hash(&self) -> Result<Vc<u64>> {
let this = self;
let mut hasher = Xxh3Hash64Hasher::new();
if let Some(parent) = this.parent {
if let Some(parent) = self.parent {
hasher.write_value(parent.hash().await?);
} else {
hasher.write_value(0u64);
}
let item_idents = this
let item_idents = self
.chunk_items
.await?
.iter()
Expand All @@ -91,11 +90,10 @@ impl AvailableChunkItems {
&self,
chunk_item: Vc<Box<dyn ChunkItem>>,
) -> Result<Vc<OptionAvailableChunkItemInfo>> {
let this = self;
if let Some(&info) = this.chunk_items.await?.get(&chunk_item) {
if let Some(&info) = self.chunk_items.await?.get(&chunk_item) {
return Ok(Vc::cell(Some(info)));
};
if let Some(parent) = this.parent {
if let Some(parent) = self.parent {
return Ok(parent.get(chunk_item));
}
Ok(Vc::cell(None))
Expand Down
Loading

0 comments on commit 3ee8e76

Please sign in to comment.