Skip to content

Commit

Permalink
Change the default context selector suffix to Snafu
Browse files Browse the repository at this point in the history
  • Loading branch information
shepmaster committed May 3, 2021
1 parent 37077f9 commit dd06ca4
Show file tree
Hide file tree
Showing 57 changed files with 309 additions and 229 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,9 @@ type Result<T, E = Error> = std::result::Result<T, E>;

fn process_data() -> Result<()> {
let path = "config.toml";
let configuration = fs::read_to_string(path).context(ReadConfiguration { path })?;
let configuration = fs::read_to_string(path).context(ReadConfigurationSnafu { path })?;
let path = unpack_config(&configuration);
fs::write(&path, b"My complex calculation").context(WriteResult { path })?;
fs::write(&path, b"My complex calculation").context(WriteResultSnafu { path })?;
Ok(())
}

Expand Down
4 changes: 2 additions & 2 deletions compatibility-tests/backtrace-shim/tests/backtrace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ enum Error {
type Result<T, E = Error> = std::result::Result<T, E>;

fn check_less_than(user_id: i32) -> Result<()> {
ensure!(user_id >= 42, InvalidUser { user_id });
ensure!(user_id >= 42, InvalidUserSnafu { user_id });
Ok(())
}

fn check_greater_than(user_id: i32) -> Result<()> {
ensure!(user_id <= 42, InvalidUser { user_id });
ensure!(user_id <= 42, InvalidUserSnafu { user_id });
Ok(())
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ mod house {
}

pub fn answer_telephone() -> Result<(), Error> {
Fatal.fail()
FatalSnafu.fail()
}
}

Expand All @@ -28,7 +28,7 @@ enum Error {
}

fn delegate_example() -> Result<(), Error> {
house::answer_telephone().context(MovieTrope)?;
house::answer_telephone().context(MovieTropeSnafu)?;

Ok(())
}
Expand All @@ -47,7 +47,7 @@ fn backtrace_comes_from_delegated_error() {
}

fn delegate_and_rename_example() -> Result<(), Error> {
house::answer_telephone().context(SourceAndBacktraceAttrs)
house::answer_telephone().context(SourceAndBacktraceAttrsSnafu)
}

#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ enum Error {
type Result<T, E = Error> = std::result::Result<T, E>;

fn example() -> Result<()> {
WithBacktrace.fail()
WithBacktraceSnafu.fail()
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion compatibility-tests/backtraces-impl-std/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ enum Error {
type Result<T, E = Error> = std::result::Result<T, E>;

fn example() -> Result<()> {
WithBacktrace.fail()
WithBacktraceSnafu.fail()
}

#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ pub mod inner {
}

fn private_is_default() {
let _ = inner::Context.build();
let _ = inner::Snafu.build();
}

fn main() {}
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
error[E0603]: unit struct `Context` is private
error[E0603]: unit struct `Snafu` is private
--> $DIR/visibility.rs:11:20
|
11 | let _ = inner::Context.build();
| ^^^^^^^ private unit struct
11 | let _ = inner::Snafu.build();
| ^^^^^ private unit struct
|
note: the unit struct `Context` is defined here
note: the unit struct `Snafu` is defined here
--> $DIR/visibility.rs:6:21
|
6 | #[derive(Debug, Snafu)]
| ^^^^^
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0624]: associated function `build` is private
--> $DIR/visibility.rs:11:28
--> $DIR/visibility.rs:11:26
|
11 | let _ = inner::Context.build();
| ^^^^^ private associated function
11 | let _ = inner::Snafu.build();
| ^^^^^ private associated function
6 changes: 3 additions & 3 deletions compatibility-tests/compile-fail/tests/ui/visibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,16 @@ mod outer {
}

fn private_is_applied() {
let _ = self::inner::Private.build();
let _ = self::inner::PrivateSnafu.build();
}
}

fn pub_in_path_is_applied() {
let _ = self::outer::inner::PubInPath.build();
let _ = self::outer::inner::PubInPathSnafu.build();
}

fn private_is_applied() {
let _ = self::outer::inner::Private.build();
let _ = self::outer::inner::PrivateSnafu.build();
}

fn main() {}
42 changes: 21 additions & 21 deletions compatibility-tests/compile-fail/tests/ui/visibility.stderr
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
error[E0603]: unit struct `Private` is private
error[E0603]: unit struct `PrivateSnafu` is private
--> $DIR/visibility.rs:19:30
|
19 | let _ = self::inner::Private.build();
| ^^^^^^^ private unit struct
19 | let _ = self::inner::PrivateSnafu.build();
| ^^^^^^^^^^^^ private unit struct
|
note: the unit struct `Private` is defined here
note: the unit struct `PrivateSnafu` is defined here
--> $DIR/visibility.rs:7:25
|
7 | #[derive(Debug, Snafu)]
| ^^^^^
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0603]: unit struct `PubInPath` is private
error[E0603]: unit struct `PubInPathSnafu` is private
--> $DIR/visibility.rs:24:33
|
24 | let _ = self::outer::inner::PubInPath.build();
| ^^^^^^^^^ private unit struct
24 | let _ = self::outer::inner::PubInPathSnafu.build();
| ^^^^^^^^^^^^^^ private unit struct
|
note: the unit struct `PubInPath` is defined here
note: the unit struct `PubInPathSnafu` is defined here
--> $DIR/visibility.rs:7:25
|
7 | #[derive(Debug, Snafu)]
| ^^^^^
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0603]: unit struct `Private` is private
error[E0603]: unit struct `PrivateSnafu` is private
--> $DIR/visibility.rs:28:33
|
28 | let _ = self::outer::inner::Private.build();
| ^^^^^^^ private unit struct
28 | let _ = self::outer::inner::PrivateSnafu.build();
| ^^^^^^^^^^^^ private unit struct
|
note: the unit struct `Private` is defined here
note: the unit struct `PrivateSnafu` is defined here
--> $DIR/visibility.rs:7:25
|
7 | #[derive(Debug, Snafu)]
| ^^^^^
= note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)

error[E0624]: associated function `build` is private
--> $DIR/visibility.rs:19:38
--> $DIR/visibility.rs:19:43
|
19 | let _ = self::inner::Private.build();
| ^^^^^ private associated function
19 | let _ = self::inner::PrivateSnafu.build();
| ^^^^^ private associated function

error[E0624]: associated function `build` is private
--> $DIR/visibility.rs:24:43
--> $DIR/visibility.rs:24:48
|
24 | let _ = self::outer::inner::PubInPath.build();
| ^^^^^ private associated function
24 | let _ = self::outer::inner::PubInPathSnafu.build();
| ^^^^^ private associated function

error[E0624]: associated function `build` is private
--> $DIR/visibility.rs:28:41
--> $DIR/visibility.rs:28:46
|
28 | let _ = self::outer::inner::Private.build();
| ^^^^^ private associated function
28 | let _ = self::outer::inner::PrivateSnafu.build();
| ^^^^^ private associated function
18 changes: 9 additions & 9 deletions compatibility-tests/futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod api {
}

pub async fn fetch_page(url: &str) -> Result<String, Error> {
InvalidUrl { url }.fail()
InvalidUrlSnafu { url }.fail()
}

pub fn keep_fetching_page<'u>(url: &'u str) -> impl TryStream<Ok = String, Error = Error> + 'u {
Expand Down Expand Up @@ -51,11 +51,11 @@ enum Error {
async fn load_stock_data_sequential() -> Result<String, Error> {
let apple = api::fetch_page("apple")
.await
.context(UnableToLoadAppleStock)?;
.context(UnableToLoadAppleStockSnafu)?;

let google = api::fetch_page("google")
.await
.with_context(|| UnableToLoadGoogleStock {
.with_context(|| UnableToLoadGoogleStockSnafu {
name: String::from("sequential"),
})?;

Expand All @@ -73,8 +73,8 @@ async fn load_stock_data_sequential() -> Result<String, Error> {

// Can be used as a `Future` combinator
async fn load_stock_data_concurrent() -> Result<String, Error> {
let apple = api::fetch_page("apple").context(UnableToLoadAppleStock);
let google = api::fetch_page("google").with_context(|| UnableToLoadGoogleStock {
let apple = api::fetch_page("apple").context(UnableToLoadAppleStockSnafu);
let google = api::fetch_page("google").with_context(|| UnableToLoadGoogleStockSnafu {
name: String::from("concurrent"),
});
let other_1 = api::fetch_page("other_1").whatever_context::<_, Error>("Oh no!");
Expand All @@ -91,11 +91,11 @@ async fn load_stock_data_concurrent() -> Result<String, Error> {
// Return values of the combinators implement `Future`
async fn load_stock_data_sequential_again() -> Result<String, Error> {
let apple = api::fetch_page("apple")
.context(UnableToLoadAppleStock)
.context(UnableToLoadAppleStockSnafu)
.await?;

let google = api::fetch_page("google")
.with_context(|| UnableToLoadGoogleStock {
.with_context(|| UnableToLoadGoogleStockSnafu {
name: String::from("sequential"),
})
.await?;
Expand All @@ -114,8 +114,8 @@ async fn load_stock_data_sequential_again() -> Result<String, Error> {

// Can be used as a `Stream` combinator
async fn load_stock_data_series() -> Result<String, Error> {
let apple = api::keep_fetching_page("apple").context(UnableToLoadAppleStock);
let google = api::keep_fetching_page("google").with_context(|| UnableToLoadGoogleStock {
let apple = api::keep_fetching_page("apple").context(UnableToLoadAppleStockSnafu);
let google = api::keep_fetching_page("google").with_context(|| UnableToLoadGoogleStockSnafu {
name: String::from("stream"),
});
let other_1 = api::keep_fetching_page("other_1").whatever_context("Oh no!");
Expand Down
10 changes: 5 additions & 5 deletions compatibility-tests/v1_34/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ mod enum_style {
type Result<T, E = Error> = std::result::Result<T, E>;

fn create_without_source() -> Result<()> {
WithoutSource { id: 42 }.fail()
WithoutSourceSnafu { id: 42 }.fail()
}

fn create_with_source() -> Result<()> {
io_failure().context(WithSource { id: 42 })
io_failure().context(WithSourceSnafu { id: 42 })
}

#[test]
Expand Down Expand Up @@ -59,11 +59,11 @@ mod struct_style {
}

fn create_without_source() -> Result<(), WithoutSource> {
WithoutSourceContext { id: 42 }.fail()
WithoutSourceSnafu { id: 42 }.fail()
}

fn create_with_source() -> Result<(), WithSource> {
io_failure().context(WithSourceContext { id: 42 })
io_failure().context(WithSourceSnafu { id: 42 })
}

#[test]
Expand All @@ -86,7 +86,7 @@ mod opaque_style {
struct Opaque(Dummy);

fn create() -> Result<(), Opaque> {
Ok(DummyContext.fail()?)
Ok(DummySnafu.fail()?)
}

#[test]
Expand Down
33 changes: 14 additions & 19 deletions snafu-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ extern crate proc_macro;

use crate::parse::attributes_from_syn;
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use quote::quote;
use std::collections::VecDeque;
use std::fmt;

Expand Down Expand Up @@ -47,9 +47,15 @@ struct FieldContainer {
visibility: Option<UserInput>,
}

enum SuffixKind {
Default,
None,
Some(syn::Ident),
}

enum ContextSelectorKind {
Context {
suffix: Option<syn::Ident>,
suffix: SuffixKind,
source_field: Option<SourceField>,
user_fields: Vec<Field>,
},
Expand Down Expand Up @@ -839,7 +845,7 @@ fn field_container(
},

(None, None) => ContextSelectorKind::Context {
suffix: None,
suffix: SuffixKind::Default,
source_field,
user_fields,
},
Expand Down Expand Up @@ -1046,14 +1052,14 @@ fn parse_snafu_tuple_struct(

enum Context {
Flag(bool),
Suffix(syn::Ident),
Suffix(SuffixKind),
}

impl Context {
fn into_enabled(self) -> (bool, Option<syn::Ident>) {
fn into_enabled(self) -> (bool, SuffixKind) {
match self {
Context::Flag(b) => (b, None),
Context::Suffix(suffix) => (true, Some(suffix)),
Context::Flag(b) => (b, SuffixKind::None),
Context::Suffix(suffix) => (true, suffix),
}
}
}
Expand Down Expand Up @@ -1412,21 +1418,10 @@ impl<'a> quote::ToTokens for ErrorCompatImpl<'a> {
}

impl NamedStructInfo {
fn selector_name(&self) -> syn::Ident {
let selector_name = self.field_container.name.to_string();
let selector_name = selector_name.trim_end_matches("Error");
format_ident!(
"{}Context",
selector_name,
span = self.field_container.name.span()
)
}

fn generate_snafu(self) -> proc_macro2::TokenStream {
let parameterized_struct_name = self.parameterized_name();
let original_generics = self.provided_generics_without_defaults();
let where_clauses = self.provided_where_clauses();
let selector_name = self.selector_name();

let Self {
crate_root,
Expand Down Expand Up @@ -1517,7 +1512,7 @@ impl NamedStructInfo {
parameterized_error_name: &parameterized_struct_name,
selector_doc_string: &selector_doc_string,
selector_kind: &selector_kind,
selector_name: &selector_name,
selector_name: &field_container.name,
user_fields: &user_fields,
visibility: visibility.as_ref().map(|x| &**x),
where_clauses: &where_clauses,
Expand Down

0 comments on commit dd06ca4

Please sign in to comment.