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
54 changes: 0 additions & 54 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
Expand Up @@ -7,12 +7,12 @@ description = "ergonomic errors with call-site location"
license = "MIT OR Apache-2.0"
authors = ["Frando <[email protected]>", "n0 team"]
repository = "https://github.com/n0-computer/n0-error"
keywords = ["error", "backtrace", "location"]
keywords = ["error", "location", "ergonomic"]

[dependencies]
n0-error-macros = { path = "n0-error-macros" }
anyhow = { version = "1.0.100", optional = true }
derive_more = { version = "2.0.1", features = ["debug", "display"] }
n0-error-macros = { path = "n0-error-macros" }
spez = "0.1.2"

[dev-dependencies]
Expand Down
5 changes: 2 additions & 3 deletions n0-error-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@ version = "0.1.0"
edition = "2021"
description = "macros for n0-error"
license = "MIT OR Apache-2.0"
authors = ["Frando <frando@n0.computer>", "n0 team"]
authors = ["Frando <franz@n0.computer>", "n0 team"]
repository = "https://github.com/n0-computer/n0-error"
keywords = ["error", "location", "ergonomic"]

[lib]
proc-macro = true

[dependencies]
heck = "0.5"
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full", "extra-traits"] }
heck = "0.5"
darling = "0.21.3"
96 changes: 82 additions & 14 deletions n0-error-macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
use darling::FromAttributes;
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::{quote, ToTokens};
Expand Down Expand Up @@ -164,12 +163,12 @@ fn add_meta_field(fields: &mut Fields) {
pub fn derive_stack_error(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as syn::DeriveInput);
match derive_error_inner(input) {
Err(tokens) => tokens.write_errors().into(),
Err(err) => err.to_compile_error().into(),
Ok(tokens) => tokens.into(),
}
}

fn derive_error_inner(input: DeriveInput) -> Result<proc_macro2::TokenStream, darling::Error> {
fn derive_error_inner(input: DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
match &input.data {
syn::Data::Enum(item) => {
let args = EnumAttrArgs::from_attributes(&input.attrs)?;
Expand All @@ -191,8 +190,7 @@ fn derive_error_inner(input: DeriveInput) -> Result<proc_macro2::TokenStream, da
_ => Err(err(
&input,
"#[derive(StackError)] only supports enums or structs",
)
.into()),
)),
}
}

Expand Down Expand Up @@ -222,24 +220,61 @@ enum SourceKind {
Std,
}

#[derive(Default, Clone, Copy, darling::FromMeta)]
#[darling(default, derive_syn_parse)]
#[derive(Default, Clone, Copy)]
struct StackErrAttrArgs {
add_meta: bool,
derive: bool,
from_sources: bool,
std_sources: bool,
}

#[derive(Default, Clone, Copy, FromAttributes)]
#[darling(default, attributes(error, stackerr))]
impl syn::parse::Parse for StackErrAttrArgs {
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let mut out = Self::default();
while !input.is_empty() {
let ident: Ident = input.parse()?;
match ident.to_string().as_str() {
"add_meta" => out.add_meta = true,
"derive" => out.derive = true,
"from_sources" => out.from_sources = true,
"std_sources" => out.std_sources = true,
other => Err(err(
ident,
format!("unknown stack_error option `{}`", other),
))?,
}
if input.peek(syn::Token![,]) {
let _ = input.parse::<syn::Token![,]>()?;
}
}
Ok(out)
}
}

#[derive(Default, Clone, Copy)]
struct EnumAttrArgs {
from_sources: bool,
std_sources: bool,
}

#[derive(Default, Clone, Copy, FromAttributes)]
#[darling(default, attributes(error))]
impl EnumAttrArgs {
fn from_attributes(attrs: &[Attribute]) -> Result<Self, syn::Error> {
let mut out = Self::default();
for ident in parse_error_attr_as_idents(attrs)? {
match ident.to_string().as_str() {
"from_sources" => out.from_sources = true,
"std_sources" => out.std_sources = true,
_ => Err(err(
ident,
"Invalid argument for the `error` attribute on fields",
))?,
}
}
Ok(out)
}
}

#[derive(Default, Clone, Copy)]
struct FieldAttrArgs {
source: bool,
from: bool,
Expand All @@ -248,6 +283,26 @@ struct FieldAttrArgs {
meta: bool,
}

impl FieldAttrArgs {
fn from_attributes(attrs: &[Attribute]) -> Result<Self, syn::Error> {
let mut out = Self::default();
for ident in parse_error_attr_as_idents(attrs)? {
match ident.to_string().as_str() {
"source" => out.source = true,
"from" => out.from = true,
"std_err" => out.std_err = true,
"stack_err" => out.stack_err = true,
"meta" => out.meta = true,
_ => Err(err(
ident,
"Invalid argument for the `error` attribute on fields",
))?,
}
}
Ok(out)
}
}

#[derive(Debug, Clone, Copy)]
enum VariantIdent<'a> {
Struct(&'a Ident),
Expand Down Expand Up @@ -888,8 +943,8 @@ impl DisplayArgs {
}

// #[error("...", args...)]
let mut it = args.into_iter();
let first = it.next().unwrap();
let mut args = args.into_iter();
let first = args.next().unwrap();
let fmt_lit = match first {
Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(s), .. }) => s,
other => return Err(err(
Expand All @@ -898,7 +953,7 @@ impl DisplayArgs {
))
};

let rest: Vec<Expr> = it.collect();
let rest: Vec<Expr> = args.collect();
Ok(DisplayArgs::Format(
quote! { write!(f, #fmt_lit #(, #rest)* ) },
))
Expand All @@ -908,3 +963,16 @@ impl DisplayArgs {
fn err(ident: impl ToTokens, err: impl ToString) -> syn::Error {
syn::Error::new_spanned(ident, err.to_string())
}

fn parse_error_attr_as_idents(attrs: &[Attribute]) -> Result<Vec<Ident>, syn::Error> {
let mut out = vec![];
for attr in attrs.iter().filter(|a| a.path().is_ident("error")) {
let idents = attr.parse_args_with(|input: syn::parse::ParseStream<'_>| {
let list: Punctuated<Ident, syn::Token![,]> =
Punctuated::<Ident, syn::Token![,]>::parse_terminated(input)?;
Ok(list.into_iter())
})?;
out.extend(idents);
}
Ok(out)
}
Loading