Unverified Commit 1bc8f559 authored by Matt Mastracci's avatar Matt Mastracci Committed by GitHub

Add Err(anyhow(... ast-grep rule (#90869)

# What

Add an ast-grep rule to use `bail!` rather than `Err(anyhow!(` in a
return position.

# Why

This is slightly more compact, and allows us to port more code over to
turbofmt/turbobail.

Note: _this PR was previously merged into another branch due to a GH
bug_
parent 8dd8a958
......@@ -2,41 +2,41 @@ id: no-context
snapshots:
'fn foo(context: ChunkingContext) -> u32 { 5 };':
labels:
- source: context
style: primary
start: 7
end: 14
- source: 'context: ChunkingContext'
style: secondary
start: 7
end: 31
- source: context
style: primary
start: 7
end: 14
- source: 'context: ChunkingContext'
style: secondary
start: 7
end: 31
foo(|context| context):
labels:
- source: context
style: primary
start: 5
end: 12
- source: '|context|'
style: secondary
start: 4
end: 13
- source: context
style: primary
start: 5
end: 12
- source: '|context|'
style: secondary
start: 4
end: 13
let context = ChunkingContext::new();:
labels:
- source: context
style: primary
start: 4
end: 11
- source: let context = ChunkingContext::new();
style: secondary
start: 0
end: 37
- source: context
style: primary
start: 4
end: 11
- source: let context = ChunkingContext::new();
style: secondary
start: 0
end: 37
'struct Foo { context: Context };':
labels:
- source: context
style: primary
start: 13
end: 20
- source: 'context: Context'
style: secondary
start: 13
end: 29
- source: context
style: primary
start: 13
end: 20
- source: 'context: Context'
style: secondary
start: 13
end: 29
id: no-err-anyhow
snapshots:
Err(anyhow!("error message")):
labels:
- source: Err(anyhow!("error message"))
style: primary
start: 0
end: 29
'Err(anyhow!("error: {}", msg))':
labels:
- source: 'Err(anyhow!("error: {}", msg))'
style: primary
start: 0
end: 30
Err(anyhow::anyhow!("error message")):
labels:
- source: Err(anyhow::anyhow!("error message"))
style: primary
start: 0
end: 37
'Err(anyhow::anyhow!("error: {}", msg))':
labels:
- source: 'Err(anyhow::anyhow!("error: {}", msg))'
style: primary
start: 0
end: 38
......@@ -7,22 +7,22 @@ snapshots:
#[turbo_tasks::function]
pub async fn flag_this(x: ResolvedVc<MyType>) -> Vc<MyType> {}
labels:
- source: ResolvedVc<MyType>
style: primary
start: 74
end: 92
- source: flag_this
style: secondary
start: 38
end: 47
- source: '#[turbo_tasks::function]'
style: secondary
start: 0
end: 24
- source: 'pub async fn flag_this(x: ResolvedVc<MyType>) -> ResolvedVc<MyType> {}'
style: secondary
start: 25
end: 95
- source: ResolvedVc<MyType>
style: primary
start: 74
end: 92
- source: flag_this
style: secondary
start: 38
end: 47
- source: '#[turbo_tasks::function]'
style: secondary
start: 0
end: 24
- source: 'pub async fn flag_this(x: ResolvedVc<MyType>) -> ResolvedVc<MyType> {}'
style: secondary
start: 25
end: 95
? |
#[turbo_tasks::function]
pub async fn flag_this_too(x: ResolvedVc<MyType>) -> Result<ResolvedVc<MyType>> {}
......@@ -30,22 +30,22 @@ snapshots:
#[turbo_tasks::function]
pub async fn flag_this_too(x: ResolvedVc<MyType>) -> Result<Vc<MyType>> {}
labels:
- source: ResolvedVc<MyType>
style: primary
start: 85
end: 103
- source: flag_this_too
style: secondary
start: 38
end: 51
- source: '#[turbo_tasks::function]'
style: secondary
start: 0
end: 24
- source: 'pub async fn flag_this_too(x: ResolvedVc<MyType>) -> Result<ResolvedVc<MyType>> {}'
style: secondary
start: 25
end: 107
- source: ResolvedVc<MyType>
style: primary
start: 85
end: 103
- source: flag_this_too
style: secondary
start: 38
end: 51
- source: '#[turbo_tasks::function]'
style: secondary
start: 0
end: 24
- source: 'pub async fn flag_this_too(x: ResolvedVc<MyType>) -> Result<ResolvedVc<MyType>> {}'
style: secondary
start: 25
end: 107
? |
#[turbo_tasks::value_trait]
pub trait ValueTrait() {
......@@ -57,33 +57,33 @@ snapshots:
fn flag_this() -> Vc<MyType>;
}
labels:
- source: ResolvedVc<MyType>
style: primary
start: 75
end: 93
- source: '#[turbo_tasks::value_trait]'
style: secondary
start: 0
end: 27
- source: |-
pub trait ValueTrait() {
fn flag_this() -> ResolvedVc<MyType>;
}
style: secondary
start: 28
end: 96
- source: |-
pub trait ValueTrait() {
fn flag_this() -> ResolvedVc<MyType>;
}
style: secondary
start: 28
end: 96
- source: flag_this
style: secondary
start: 60
end: 69
- source: fn flag_this() -> ResolvedVc<MyType>;
style: secondary
start: 57
end: 94
- source: ResolvedVc<MyType>
style: primary
start: 75
end: 93
- source: '#[turbo_tasks::value_trait]'
style: secondary
start: 0
end: 27
- source: |-
pub trait ValueTrait() {
fn flag_this() -> ResolvedVc<MyType>;
}
style: secondary
start: 28
end: 96
- source: |-
pub trait ValueTrait() {
fn flag_this() -> ResolvedVc<MyType>;
}
style: secondary
start: 28
end: 96
- source: flag_this
style: secondary
start: 60
end: 69
- source: fn flag_this() -> ResolvedVc<MyType>;
style: secondary
start: 57
end: 94
......@@ -11,29 +11,29 @@ snapshots:
fn write_to_disk(self: Vc<Self>);
}
labels:
- source: ResolvedVc<Self>
style: primary
start: 75
end: 91
- source: '#[turbo_tasks::value_trait]'
style: secondary
start: 0
end: 27
- source: |-
pub trait Example {
fn write_to_disk(self: ResolvedVc<Self>);
}
style: secondary
start: 28
end: 95
- source: |-
pub trait Example {
fn write_to_disk(self: ResolvedVc<Self>);
}
style: secondary
start: 28
end: 95
- source: 'fn write_to_disk(self: ResolvedVc<Self>);'
style: secondary
start: 52
end: 93
- source: ResolvedVc<Self>
style: primary
start: 75
end: 91
- source: '#[turbo_tasks::value_trait]'
style: secondary
start: 0
end: 27
- source: |-
pub trait Example {
fn write_to_disk(self: ResolvedVc<Self>);
}
style: secondary
start: 28
end: 95
- source: |-
pub trait Example {
fn write_to_disk(self: ResolvedVc<Self>);
}
style: secondary
start: 28
end: 95
- source: 'fn write_to_disk(self: ResolvedVc<Self>);'
style: secondary
start: 52
end: 93
id: no-err-anyhow
valid:
- 'bail!("error message")'
- 'bail!("error: {}", msg)'
- 'Err(SomeOtherError::new("error"))'
- 'Err(err.into())'
- 'Err(anyhow!("error").context("context"))'
- 'Some(Err(anyhow!("wrapped in Some")))'
- 'Some(Err(anyhow::anyhow!("wrapped in Some")))'
- 'self.error = Err(anyhow::anyhow!("assigned to field"))'
- 'Err(anyhow::anyhow!("msg")).context("ctx")'
- |
let x = match blah {
1 => Err(anyhow!("foo")),
2 => Ok(()),
};
do_something();
return x;
invalid:
- 'Err(anyhow!("error message"))'
- 'Err(anyhow!("error: {}", msg))'
- 'Err(anyhow::anyhow!("error message"))'
- 'Err(anyhow::anyhow!("error: {}", msg))'
# yaml-language-server: $schema=https://raw.githubusercontent.com/ast-grep/ast-grep/main/schemas/rule.json
id: no-err-anyhow
message: Use `bail!()` instead of `Err(anyhow!())`.
note: The `bail!` macro from anyhow is more concise and idiomatic.
severity: error
language: Rust
rule:
all:
- any:
- pattern: Err(anyhow!($$$ARGS))
- pattern: Err(anyhow::anyhow!($$$ARGS))
- not:
inside:
kind: arguments
stopBy:
any:
- kind: block
- kind: closure_expression
- not:
inside:
kind: assignment_expression
stopBy:
any:
- kind: block
- kind: closure_expression
- not:
inside:
kind: let_declaration
stopBy:
any:
- kind: block
- kind: closure_expression
- not:
inside:
kind: field_expression
stopBy:
kind: call_expression
......@@ -7,6 +7,9 @@ dist/
target/
compiled/
# ast-grep snapshots (managed by ast-grep, not prettier)
.config/ast-grep/rule-tests/__snapshots__/
lerna.json
test-timings.json
pnpm-lock.yaml
......
......@@ -5,7 +5,7 @@
use std::{str::FromStr, time::Instant};
use anyhow::{Context, Result};
use anyhow::{Context, Result, bail};
use futures_util::{StreamExt, TryStreamExt};
use next_api::{
entrypoints::Entrypoints,
......@@ -135,7 +135,7 @@ impl FromStr for Strategy {
"parallel-randomized" => Ok(Strategy::Parallel { randomized: true }),
"development" => Ok(Strategy::Development { randomized: false }),
"development-randomized" => Ok(Strategy::Development { randomized: true }),
_ => Err(anyhow::anyhow!("invalid strategy")),
_ => bail!("invalid strategy"),
}
}
}
......
......@@ -7,7 +7,7 @@ use std::{
sync::atomic::{AtomicUsize, Ordering},
};
use anyhow::{Ok, Result};
use anyhow::{Ok, Result, bail};
use byteorder::WriteBytesExt;
use rustc_hash::FxHashMap;
use turbo_tasks::FxDashMap;
......@@ -341,7 +341,7 @@ fn read_key_value_pair<'l>(
1 => KeySpace::TaskMeta,
2 => KeySpace::TaskData,
3 => KeySpace::TaskCache,
_ => return Err(anyhow::anyhow!("Invalid key space")),
_ => bail!("Invalid key space"),
};
*pos += 1;
let key_len = u32::from_be_bytes(buffer[*pos..*pos + 4].try_into()?);
......
......@@ -1791,7 +1791,7 @@ impl FileSystemPath {
let result = &(*self.realpath_with_links().await?);
match &result.path_result {
Ok(path) => Ok(path.clone()),
Err(error) => Err(anyhow::anyhow!(error.as_error_message(self, result).await?)),
Err(error) => bail!("{}", error.as_error_message(self, result).await?),
}
}
......@@ -2410,8 +2410,8 @@ impl ValueToString for FileJsonContent {
fn to_string(&self) -> Result<Vc<RcStr>> {
match self {
FileJsonContent::Content(json) => Ok(Vc::cell(json.to_string().into())),
FileJsonContent::Unparsable(e) => Err(anyhow!("File is not valid JSON: {}", e)),
FileJsonContent::NotFound => Err(anyhow!("File not found")),
FileJsonContent::Unparsable(e) => bail!("File is not valid JSON: {}", e),
FileJsonContent::NotFound => bail!("File not found"),
}
}
}
......@@ -2422,8 +2422,8 @@ impl FileJsonContent {
pub async fn content(self: Vc<Self>) -> Result<Vc<Value>> {
match &*self.await? {
FileJsonContent::Content(json) => Ok(Vc::cell(json.clone())),
FileJsonContent::Unparsable(e) => Err(anyhow!("File is not valid JSON: {}", e)),
FileJsonContent::NotFound => Err(anyhow!("File not found")),
FileJsonContent::Unparsable(e) => bail!("File is not valid JSON: {}", e),
FileJsonContent::NotFound => bail!("File not found"),
}
}
}
......
......@@ -11,7 +11,7 @@ use std::{
sync::{Arc, Mutex, Weak},
};
use anyhow::{Result, anyhow};
use anyhow::{Result, anyhow, bail};
use futures::FutureExt;
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
......@@ -196,7 +196,7 @@ impl TurboTasksApi for VcStorage {
Task::Spawned(event) => Ok(Err(event.listen())),
Task::Finished(result) => match result {
Ok(vc) => Ok(Ok(*vc)),
Err(err) => Err(anyhow!(err.clone())),
Err(err) => bail!(err.clone()),
},
}
}
......
use std::fmt::{self, Display};
use anyhow::anyhow;
use anyhow::bail;
use crate::{RawVc, backend::TurboTasksExecutionError};
......@@ -14,7 +14,7 @@ pub enum OutputContent {
impl OutputContent {
pub fn as_read_result(&self) -> anyhow::Result<RawVc> {
match &self {
Self::Error(err) => Err(anyhow!(err.clone())),
Self::Error(err) => bail!(err.clone()),
Self::Link(raw_vc) => Ok(*raw_vc),
}
}
......
use std::{fmt, sync::Arc};
use anyhow::{Result, anyhow};
use anyhow::{Result, bail};
use crate::{
CellId, MagicAny, OutputContent, RawVc, TaskPersistence, TraitMethod, TurboTasksBackendApi,
......@@ -72,7 +72,7 @@ impl LocalTaskType {
) -> Result<RawVc> {
let this = this.resolve().await?;
let RawVc::TaskCell(_, CellId { type_id, .. }) = this else {
return Err(anyhow!("Trait method receiver must be a cell"));
bail!("Trait method receiver must be a cell");
};
let native_fn = Self::resolve_trait_method_from_value(trait_method, type_id)?;
......@@ -86,11 +86,11 @@ impl LocalTaskType {
) -> Result<&'static NativeFunction> {
match registry::get_value_type(value_type).get_trait_method(trait_method) {
Some(native_fn) => Ok(native_fn),
None => Err(anyhow!(
None => bail!(
"{} doesn't implement the trait for {:?}, the compiler should have flagged this",
registry::get_value_type(value_type),
trait_method
)),
),
}
}
}
......
use std::{sync::Arc, time::Duration};
use anyhow::{Context, Result, anyhow};
use anyhow::{Context, Result, bail};
use chromiumoxide::{
Page,
cdp::js_protocol::runtime::{EventBindingCalled, EventExceptionThrown},
......@@ -75,7 +75,7 @@ impl<'a> PageGuard<'a> {
}
}
Err(anyhow!("event stream ended before binding was called"))
bail!("event stream ended before binding was called")
}
/// Waits until the page and the page JavaScript is hydrated.
......
......@@ -5,7 +5,7 @@ use std::{
sync::Arc,
};
use anyhow::{Context, Result, anyhow};
use anyhow::{Context, Result, bail};
use chromiumoxide::{
Browser, Page,
cdp::{
......@@ -163,7 +163,7 @@ impl<'a> PreparedApp<'a> {
break;
}
}
None => return Err(anyhow!("event stream ended too early")),
None => bail!("event stream ended too early"),
}
}
......
use anyhow::{Result, anyhow};
use anyhow::{Result, bail};
use turbo_rcstr::{RcStr, rcstr};
use turbo_tasks::{ResolvedVc, TryFlatJoinIterExt, TryJoinIterExt, Vc};
use turbo_tasks_env::ProcessEnv;
......@@ -194,10 +194,10 @@ pub async fn create_web_entry_source(
})
} else {
// TODO convert into a serve-able asset
Err(anyhow!(
bail!(
"Entry module is not chunkable, so it can't be used to bootstrap the \
application"
))
)
}
})
.try_join()
......
use anyhow::Result;
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::Vc;
use turbo_tasks_fs::{FileContent, FileSystemEntryType, FileSystemPath, LinkContent};
......@@ -70,7 +70,7 @@ impl Asset for FileSource {
link_type: *link_type,
}
.cell()),
_ => Err(anyhow::anyhow!("Invalid symlink")),
_ => bail!("Invalid symlink"),
},
FileSystemEntryType::File => {
Ok(AssetContent::File(self.path.read().to_resolved().await?).cell())
......@@ -78,7 +78,7 @@ impl Asset for FileSource {
FileSystemEntryType::NotFound => {
Ok(AssetContent::File(FileContent::NotFound.resolved_cell()).cell())
}
_ => Err(anyhow::anyhow!("Invalid file type {:?}", file_type)),
_ => bail!("Invalid file type {:?}", file_type),
}
}
}
......@@ -8,7 +8,7 @@ use std::{
fmt::{Display, Formatter},
};
use anyhow::{Result, anyhow};
use anyhow::{Result, bail};
use auto_hash_map::AutoSet;
use bincode::{Decode, Encode};
use serde::{Deserialize, Serialize};
......@@ -1089,7 +1089,7 @@ pub async fn handle_issues<T: Send>(
message += &format!(" ({operation})");
};
Err(anyhow!(message))
bail!(message)
} else {
Ok(())
}
......
use std::sync::Arc;
use anyhow::{Context, Result, anyhow};
use anyhow::{Context, Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::{
IntoTraitRef, NonLocalValue, OperationValue, ReadRef, ResolvedVc, State, TraitRef, Vc,
......@@ -232,7 +232,7 @@ impl FileHashVersion {
.context("file not found")?;
Ok(Self::cell(FileHashVersion { hash }))
}
AssetContent::Redirect { .. } => Err(anyhow!("not a file")),
AssetContent::Redirect { .. } => bail!("not a file"),
}
}
}
......
......@@ -6,7 +6,7 @@ use std::{
str::FromStr,
};
use anyhow::{Context, Result, anyhow};
use anyhow::{Context, Result, bail};
use indoc::{formatdoc, indoc};
use serde_json::json;
use tempfile::TempDir;
......@@ -62,7 +62,7 @@ impl FromStr for EffectMode {
"none" => Ok(EffectMode::None),
"hook" => Ok(EffectMode::Hook),
"component" => Ok(EffectMode::Component),
_ => Err(anyhow!("unknown effect mode: {}", s)),
_ => bail!("unknown effect mode: {}", s),
}
}
}
......
......@@ -2770,7 +2770,7 @@ impl CodeGenResultComments {
.map_err(|_| anyhow!("Failed to grab lock on the index map for byte positions"))?;
let ix = lookup_table.len() as u32;
if ix >= 1 << 30 {
return Err(anyhow!("Too many byte positions being stored"));
bail!("Too many byte positions being stored");
}
lookup_table.push(ModulePosition(module, pos_u32));
Ok(ix)
......@@ -2787,7 +2787,7 @@ impl CodeGenResultComments {
let mut push = |module: u32, pos_u32: u32| -> Result<u32> {
let ix = lookup_table.len() as u32;
if ix >= 1 << 30 {
return Err(anyhow!("Too many byte positions being stored"));
bail!("Too many byte positions being stored");
}
lookup_table.push(ModulePosition(module, pos_u32));
Ok(ix)
......
use anyhow::{Result, anyhow, bail};
use anyhow::{Result, bail};
use either::Either;
use strsim::jaro;
use swc_core::{
......@@ -513,10 +513,7 @@ impl ModuleReference for EsmAssetReference {
} else if chunking_type == "none" {
None
} else {
return Err(anyhow!(
"unknown chunking_type: {}",
chunking_type.to_string_lossy()
));
bail!("unknown chunking_type: {}", chunking_type.to_string_lossy());
}
} else {
Some(ChunkingType::Parallel {
......
use std::{fmt::Debug, hash::Hash, sync::Arc};
use anyhow::Result;
use anyhow::{Result, bail};
use async_trait::async_trait;
use swc_core::{
atoms::{Atom, atom},
......@@ -133,10 +133,10 @@ impl EcmascriptInputTransform {
"classic" => Runtime::Classic,
"automatic" => Runtime::Automatic,
_ => {
return Err(anyhow::anyhow!(
bail!(
"Invalid value for swc.jsc.transform.react.runtime: {}",
runtime
));
);
}
}
} else {
......
......@@ -323,7 +323,7 @@ impl Asset for JsonSource {
FileSystemEntryType::NotFound => {
Ok(AssetContent::File(FileContent::NotFound.resolved_cell()).cell())
}
_ => Err(anyhow::anyhow!("Invalid file type {:?}", file_type)),
_ => bail!("Invalid file type {:?}", file_type),
}
}
}
......
......@@ -79,7 +79,7 @@ pub async fn create_worker(options: Arc<WorkerOptions>) -> anyhow::Result<u32> {
ThreadsafeFunctionCallMode::NonBlocking,
);
} else {
return Err(anyhow::anyhow!("Worker creator not registered"));
anyhow::bail!("Worker creator not registered");
}
let worker_id = rx.await?;
......
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