Skip to content

Commit 43b101f

Browse files
committed
Improve error messages for compile errors caused by the expression specified in #[from_str(with = ..)].
1 parent 18d4bdd commit 43b101f

File tree

3 files changed

+27
-2
lines changed

3 files changed

+27
-2
lines changed

parse-display-derive/src/lib.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,7 @@ impl<'a> ParserBuilder<'a> {
618618
},
619619
) in self.with.iter().enumerate()
620620
{
621-
with.push(quote! {
621+
with.push(quote_spanned! {expr.span()=>
622622
(#capture, #helpers::to_ast::<#ty, _>(&#expr))
623623
});
624624
let msg = format!(
@@ -1699,14 +1699,23 @@ fn build_parse_capture_expr(
16991699
if let Some(with) = &field.hattrs.with {
17001700
let ty = &field.source.ty;
17011701
expr1 = quote! {
1702-
#crate_path::helpers::parse_with::<#ty, _ >(#with, #expr0)
1702+
#crate_path::helpers::parse_with::<#ty, _>(#with, #expr0)
17031703
};
1704+
expr1 = set_span(expr1, with.span());
17041705
}
17051706
}
17061707
quote! {
17071708
#expr1.map_err(|e| #crate_path::ParseError::with_message(#msg))?
17081709
}
17091710
}
1711+
fn set_span(ts: TokenStream, span: Span) -> TokenStream {
1712+
ts.into_iter()
1713+
.map(|mut ts| {
1714+
ts.set_span(span);
1715+
ts
1716+
})
1717+
.collect()
1718+
}
17101719

17111720
fn unref_ty(ty: &Type) -> Type {
17121721
if let Type::Reference(ty) = ty {
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use parse_display::FromStr;
2+
3+
#[derive(FromStr, Debug, PartialEq)]
4+
struct X {
5+
#[from_str(with = "not impl FromStrFormat")]
6+
x: u8,
7+
}
8+
9+
fn main() {}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
error[E0277]: the trait bound `&'static str: FromStrFormat<u8>` is not satisfied
2+
--> tests/compile_fail/from_str/invalid_with.rs:5:23
3+
|
4+
5 | #[from_str(with = "not impl FromStrFormat")]
5+
| ^^^^^^^^^^^^^^^^^^^^^^^^ the trait `FromStrFormat<u8>` is not implemented for `&'static str`
6+
|
7+
= note: required for the cast from `&&'static str` to `&dyn FromStrFormat<u8, Err = _>`

0 commit comments

Comments
 (0)