Skip to content

Commit

Permalink
Fix bad error reporting for assert directive
Browse files Browse the repository at this point in the history
  • Loading branch information
csnover committed Nov 15, 2022
1 parent 8ec595a commit eaad123
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 6 deletions.
6 changes: 3 additions & 3 deletions binrw/tests/ui/invalid_assert_condition.stderr
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
error[E0308]: mismatched types
--> tests/ui/invalid_assert_condition.rs:4:13
|
3 | #[derive(BinRead)]
| ------- arguments to this function are incorrect
4 | #[br(assert("wrong type"))]
| ^^^^^^^^^^^^ expected `bool`, found `&str`
| ------ ^^^^^^^^^^^^ expected `bool`, found `&str`
| |
| arguments to this function are incorrect
|
note: function defined here
--> src/private.rs
Expand Down
3 changes: 2 additions & 1 deletion binrw_derive/src/binrw/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ fn generate_trait_impl<const WRITE: bool>(
fn get_assertions(assertions: &[Assert]) -> impl Iterator<Item = TokenStream> + '_ {
assertions.iter().map(
|Assert {
kw_span,
condition,
consequent,
}| {
Expand All @@ -148,7 +149,7 @@ fn get_assertions(assertions: &[Assert]) -> impl Iterator<Item = TokenStream> +
}
};

quote! {
quote_spanned_any! {*kw_span=>
#ASSERT(#condition, #POS, #error_fn)?;
}
},
Expand Down
7 changes: 5 additions & 2 deletions binrw_derive/src/binrw/parser/types/assert.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::{binrw::parser::attrs, meta_types::KeywordToken};
use proc_macro2::TokenStream;
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse::Parse, spanned::Spanned, token::Token, Expr, ExprLit, Lit};

Expand All @@ -11,6 +11,7 @@ pub(crate) enum Error {

#[derive(Debug, Clone)]
pub(crate) struct Assert {
pub(crate) kw_span: Span,
pub(crate) condition: TokenStream,
pub(crate) consequent: Option<Error>,
}
Expand All @@ -19,13 +20,14 @@ impl<K: Parse + Spanned + Token> TryFrom<attrs::AssertLike<K>> for Assert {
type Error = syn::Error;

fn try_from(value: attrs::AssertLike<K>) -> Result<Self, Self::Error> {
let kw_span = value.keyword_span();
let mut args = value.fields.iter();

let condition = if let Some(cond) = args.next() {
cond.into_token_stream()
} else {
return Err(Self::Error::new(
value.keyword_span(),
kw_span,
format!(
"{} requires a boolean expression as an argument",
value.dyn_display()
Expand All @@ -49,6 +51,7 @@ impl<K: Parse + Spanned + Token> TryFrom<attrs::AssertLike<K>> for Assert {
};

Ok(Self {
kw_span,
condition,
consequent,
})
Expand Down

0 comments on commit eaad123

Please sign in to comment.