Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@ All notable changes to this project will be documented in this file.

## [Unreleased]

## [0.6.3] - 2025-10-10

### Added
- Invoke custom `#[error(fmt = <path>)]` handlers for structs and enum variants,
borrowing fields and forwarding the formatter reference just like `thiserror`.

### Changed
- Ensure duplicate `fmt` attributes report a single diagnostic without
suppressing the derived display implementation.

### Tests
- Extend the formatter trybuild suite with success cases covering struct and
enum formatter paths.

## [0.6.2] - 2025-10-09

### Added
Expand Down
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "masterror"
version = "0.6.2"
version = "0.6.3"
rust-version = "1.90"
edition = "2024"
license = "MIT OR Apache-2.0"
Expand Down Expand Up @@ -49,7 +49,7 @@ turnkey = []
openapi = ["dep:utoipa"]

[workspace.dependencies]
masterror-derive = { version = "0.2.2", path = "masterror-derive" }
masterror-derive = { version = "0.2.3", path = "masterror-derive" }
masterror-template = { version = "0.2.0", path = "masterror-template" }

[dependencies]
Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ Stable categories, conservative HTTP mapping, no `unsafe`.

~~~toml
[dependencies]
masterror = { version = "0.6.2", default-features = false }
masterror = { version = "0.6.3", default-features = false }
# or with features:
# masterror = { version = "0.6.2", features = [
# masterror = { version = "0.6.3", features = [
# "axum", "actix", "openapi", "serde_json",
# "sqlx", "sqlx-migrate", "reqwest", "redis",
# "validator", "config", "tokio", "multipart",
Expand Down Expand Up @@ -66,10 +66,10 @@ masterror = { version = "0.6.2", default-features = false }
~~~toml
[dependencies]
# lean core
masterror = { version = "0.6.2", default-features = false }
masterror = { version = "0.6.3", default-features = false }

# with Axum/Actix + JSON + integrations
# masterror = { version = "0.6.2", features = [
# masterror = { version = "0.6.3", features = [
# "axum", "actix", "openapi", "serde_json",
# "sqlx", "sqlx-migrate", "reqwest", "redis",
# "validator", "config", "tokio", "multipart",
Expand Down Expand Up @@ -383,13 +383,13 @@ assert_eq!(resp.status, 401);
Minimal core:

~~~toml
masterror = { version = "0.6.2", default-features = false }
masterror = { version = "0.6.3", default-features = false }
~~~

API (Axum + JSON + deps):

~~~toml
masterror = { version = "0.6.2", features = [
masterror = { version = "0.6.3", features = [
"axum", "serde_json", "openapi",
"sqlx", "reqwest", "redis", "validator", "config", "tokio"
] }
Expand All @@ -398,7 +398,7 @@ masterror = { version = "0.6.2", features = [
API (Actix + JSON + deps):

~~~toml
masterror = { version = "0.6.2", features = [
masterror = { version = "0.6.3", features = [
"actix", "serde_json", "openapi",
"sqlx", "reqwest", "redis", "validator", "config", "tokio"
] }
Expand Down
2 changes: 1 addition & 1 deletion masterror-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "masterror-derive"
rust-version = "1.90"
version = "0.2.2"
version = "0.2.3"
edition = "2024"
license = "MIT OR Apache-2.0"
repository = "https://github.com/RAprogramm/masterror"
Expand Down
74 changes: 69 additions & 5 deletions masterror-derive/src/display.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::collections::HashMap;
use masterror_template::template::{TemplateFormatter, TemplateFormatterKind};
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::{format_ident, quote, quote_spanned};
use syn::{Error, spanned::Spanned};
use syn::Error;

use crate::{
input::{
Expand Down Expand Up @@ -42,9 +42,7 @@ fn expand_struct(input: &ErrorInput, data: &StructData) -> Result<TokenStream, E
}
DisplaySpec::FormatterPath {
path, ..
} => {
return Err(Error::new(path.span(), "`fmt = ...` is not supported yet"));
}
} => render_struct_formatter_path(&data.fields, path)
};

let ident = &input.ident;
Expand Down Expand Up @@ -93,6 +91,26 @@ fn render_struct_transparent(fields: &Fields) -> TokenStream {
}
}

fn struct_formatter_arguments(fields: &Fields) -> Vec<TokenStream> {
match fields {
Fields::Unit => Vec::new(),
Fields::Named(fields) | Fields::Unnamed(fields) => fields
.iter()
.map(|field| {
let member = &field.member;
quote!(&self.#member)
})
.collect()
}
}

fn formatter_path_call(path: &syn::ExprPath, mut args: Vec<TokenStream>) -> TokenStream {
args.push(quote!(f));
quote! {
#path(#(#args),*)
}
}

fn render_variant(variant: &VariantData) -> Result<TokenStream, Error> {
match &variant.display {
DisplaySpec::Transparent {
Expand All @@ -105,10 +123,15 @@ fn render_variant(variant: &VariantData) -> Result<TokenStream, Error> {
} => render_variant_template(variant, template, Some(args)),
DisplaySpec::FormatterPath {
path, ..
} => Err(Error::new(path.span(), "`fmt = ...` is not supported yet"))
} => render_variant_formatter_path(variant, path)
}
}

fn render_struct_formatter_path(fields: &Fields, path: &syn::ExprPath) -> TokenStream {
let args = struct_formatter_arguments(fields);
formatter_path_call(path, args)
}

#[derive(Debug)]
struct ResolvedPlaceholderExpr {
expr: TokenStream,
Expand Down Expand Up @@ -279,6 +302,47 @@ fn render_variant_transparent(variant: &VariantData) -> Result<TokenStream, Erro
}
}

fn render_variant_formatter_path(
variant: &VariantData,
path: &syn::ExprPath
) -> Result<TokenStream, Error> {
let variant_ident = &variant.ident;
match &variant.fields {
Fields::Unit => {
let call = formatter_path_call(path, Vec::new());
Ok(quote! {
Self::#variant_ident => {
#call
}
})
}
Fields::Unnamed(fields) => {
let bindings: Vec<_> = fields.iter().map(binding_ident).collect();
let pattern = quote!(Self::#variant_ident(#(#bindings),*));
let call = formatter_path_call(path, variant_formatter_arguments(&bindings));
Ok(quote! {
#pattern => {
#call
}
})
}
Fields::Named(fields) => {
let bindings: Vec<_> = fields.iter().map(binding_ident).collect();
let pattern = quote!(Self::#variant_ident { #(#bindings),* });
let call = formatter_path_call(path, variant_formatter_arguments(&bindings));
Ok(quote! {
#pattern => {
#call
}
})
}
}
}

fn variant_formatter_arguments(bindings: &[Ident]) -> Vec<TokenStream> {
bindings.iter().map(|binding| quote!(#binding)).collect()
}

fn render_variant_template(
variant: &VariantData,
template: &DisplayTemplate,
Expand Down
7 changes: 6 additions & 1 deletion masterror-derive/src/input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,12 +404,15 @@ fn extract_display_spec(
errors: &mut Vec<Error>
) -> Result<DisplaySpec, ()> {
let mut display = None;
let mut saw_error_attribute = false;

for attr in attrs {
if !path_is(attr, "error") {
continue;
}

saw_error_attribute = true;

if display.is_some() {
errors.push(Error::new_spanned(attr, "duplicate #[error] attribute"));
continue;
Expand All @@ -424,7 +427,9 @@ fn extract_display_spec(
match display {
Some(spec) => Ok(spec),
None => {
errors.push(Error::new(missing_span, "missing #[error(...)] attribute"));
if !saw_error_attribute {
errors.push(Error::new(missing_span, "missing #[error(...)] attribute"));
}
Err(())
}
}
Expand Down
6 changes: 0 additions & 6 deletions tests/ui/formatter/fail/duplicate_fmt.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: duplicate `fmt` handler specified
|
4 | #[error(fmt = crate::format_error, fmt = crate::format_error)]
| ^^^

error: missing #[error(...)] attribute
--> tests/ui/formatter/fail/duplicate_fmt.rs:5:8
|
5 | struct DuplicateFmt;
| ^^^^^^^^^^^^
6 changes: 0 additions & 6 deletions tests/ui/formatter/fail/unsupported_flag.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: placeholder spanning bytes 0..11 uses an unsupported formatter
|
4 | #[error("{value:##x}")]
| ^^^^^^^^^^^^^

error: missing #[error(...)] attribute
--> tests/ui/formatter/fail/unsupported_flag.rs:5:8
|
5 | struct UnsupportedFlag {
| ^^^^^^^^^^^^^^^
6 changes: 0 additions & 6 deletions tests/ui/formatter/fail/unsupported_formatter.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: placeholder spanning bytes 0..9 uses an unsupported formatter
|
4 | #[error("{value:y}")]
| ^^^^^^^^^^^

error: missing #[error(...)] attribute
--> tests/ui/formatter/fail/unsupported_formatter.rs:5:8
|
5 | struct UnsupportedFormatter {
| ^^^^^^^^^^^^^^^^^^^^
6 changes: 0 additions & 6 deletions tests/ui/formatter/fail/uppercase_binary.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: placeholder spanning bytes 0..9 uses an unsupported formatter
|
4 | #[error("{value:B}")]
| ^^^^^^^^^^^

error: missing #[error(...)] attribute
--> tests/ui/formatter/fail/uppercase_binary.rs:5:8
|
5 | struct UppercaseBinary {
| ^^^^^^^^^^^^^^^
6 changes: 0 additions & 6 deletions tests/ui/formatter/fail/uppercase_pointer.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: placeholder spanning bytes 0..9 uses an unsupported formatter
|
4 | #[error("{value:P}")]
| ^^^^^^^^^^^

error: missing #[error(...)] attribute
--> tests/ui/formatter/fail/uppercase_pointer.rs:5:8
|
5 | struct UppercasePointer {
| ^^^^^^^^^^^^^^^^
53 changes: 53 additions & 0 deletions tests/ui/formatter/pass/fmt_path.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use masterror::Error;

fn format_unit(f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("unit")
}

fn format_pair(left: &i32, right: &i32, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "pair={left}:{right}")
}

fn format_struct_fields(
count: &usize,
label: &&'static str,
f: &mut core::fmt::Formatter<'_>
) -> core::fmt::Result {
write!(f, "struct={count}:{label}")
}

#[derive(Debug, Error)]
#[error(fmt = crate::format_struct_fields)]
struct StructFormatter {
count: usize,
label: &'static str,
}

#[derive(Debug, Error)]
enum EnumFormatter {
#[error(fmt = crate::format_unit)]
Unit,
#[error(fmt = crate::format_pair)]
Tuple(i32, i32),
#[error(fmt = crate::format_pair)]
Named { left: i32, right: i32 },
#[error(fmt = crate::format_struct_fields)]
Struct { count: usize, label: &'static str }
}

fn main() {
let _ = StructFormatter {
count: 1,
label: "alpha"
}
.to_string();

let _ = EnumFormatter::Unit.to_string();
let _ = EnumFormatter::Tuple(10, 20).to_string();
let _ = EnumFormatter::Named { left: 5, right: 15 }.to_string();
let _ = EnumFormatter::Struct {
count: 2,
label: "beta"
}
.to_string();
}
6 changes: 0 additions & 6 deletions tests/ui/transparent/arguments_not_supported.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,3 @@ error: format arguments are not supported with #[error(transparent)]
|
4 | #[error(transparent, code = 42)]
| ^

error: missing #[error(...)] attribute
--> tests/ui/transparent/arguments_not_supported.rs:5:8
|
5 | struct TransparentWithArgs(#[from] std::io::Error);
| ^^^^^^^^^^^^^^^^^^^
Loading