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