Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[lang] Improve invalid selector error #561

Merged
merged 10 commits into from
Nov 4, 2020
40 changes: 17 additions & 23 deletions crates/lang/ir/src/ir/attrs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ use crate::{
};
use core::{
convert::TryFrom,
num::ParseIntError,
result::Result,
};
use proc_macro2::{
Expand Down Expand Up @@ -566,11 +565,15 @@ impl InkAttribute {
}
}

fn err_non_hex<'a>(
meta: &'a syn::Meta,
pos: usize,
) -> impl FnOnce(ParseIntError) -> syn::Error + 'a {
move |_| format_err_spanned!(meta, "encountered non-hex digit at position {}", pos)
fn err_non_hex(meta: &'_ syn::Meta, pos: usize) -> syn::Error {
cmichi marked this conversation as resolved.
Show resolved Hide resolved
format_err_spanned!(meta, "encountered non-hex digit at position {}", pos)
}

fn invalid_selector_err_regex(meta: &'_ syn::Meta) -> syn::Error {
cmichi marked this conversation as resolved.
Show resolved Hide resolved
format_err_spanned!(
meta,
"invalid selector - a selector must consist of four bytes in hex (e.g. `selector = \"0xCAFEBABE\"`)"
)
}

impl TryFrom<syn::NestedMeta> for AttributeArg {
Expand All @@ -585,29 +588,20 @@ impl TryFrom<syn::NestedMeta> for AttributeArg {
if let syn::Lit::Str(lit_str) = &name_value.lit {
let regex = Regex::new(
r"0x([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})"
).map_err(|_| {
format_err_spanned!(
meta,
"invalid selector - a selector must consist of four bytes in hex (e.g. `selector = \"0xCAFEBABE\"`)"
)
})?;
).map_err(|_| invalid_selector_err_regex(&meta))?;
let str = lit_str.value();
let cap = regex.captures(&str)
.ok_or_else(||
format_err_spanned!(
meta,
"invalid selector - a selector must consist of four bytes in hex (e.g. `selector = \"0xCAFEBABE\"`)"
)
)?;
let cap = regex
.captures(&str)
.ok_or_else(|| invalid_selector_err_regex(&meta))?;
let selector_bytes = [
u8::from_str_radix(&cap[1], 16)
.map_err(err_non_hex(&meta, 0))?,
.map_err(|_| err_non_hex(&meta, 0))?,
u8::from_str_radix(&cap[2], 16)
.map_err(err_non_hex(&meta, 1))?,
.map_err(|_| err_non_hex(&meta, 1))?,
u8::from_str_radix(&cap[3], 16)
.map_err(err_non_hex(&meta, 2))?,
.map_err(|_| err_non_hex(&meta, 2))?,
u8::from_str_radix(&cap[4], 16)
.map_err(err_non_hex(&meta, 3))?,
.map_err(|_| err_non_hex(&meta, 3))?,
];
return Ok(AttributeArg {
ast: meta,
Expand Down