use proc_macro2::Span;
use syn::{Attribute, Data, LitStr, Path, parse_quote};
pub(crate) fn not_enum_span(data: &Data) -> Span {
match data {
Data::Struct(s) => s.struct_token.span,
Data::Union(u) => u.union_token.span,
Data::Enum(e) => e.enum_token.span,
}
}
pub(crate) fn crate_path(attrs: &[Attribute]) -> syn::Result<Path> {
let mut found: Option<Path> = None;
for attr in attrs
.iter()
.filter(|a| a.path().is_ident("icedwright_probe"))
{
attr.parse_nested_meta(|meta| {
if !meta.path.is_ident("crate") {
return Err(
meta.error("unknown `icedwright_probe` option; expected `crate = path`")
);
}
if found.is_some() {
return Err(meta.error("`crate` is set more than once"));
}
let value = meta.value()?;
let path = if value.peek(LitStr) {
value.parse::<LitStr>()?.parse::<Path>()?
} else {
value.parse::<Path>()?
};
found = Some(path);
Ok(())
})?;
}
Ok(found.unwrap_or_else(|| parse_quote!(::icedwright_probe)))
}
#[cfg(test)]
mod tests {
use super::*;
use quote::ToTokens;
fn path_of(attrs: Vec<Attribute>) -> syn::Result<String> {
crate_path(&attrs).map(|p| p.to_token_stream().to_string())
}
#[test]
fn defaults_to_the_absolute_probe_path() {
assert_eq!(path_of(vec![]).ok().as_deref(), Some(":: icedwright_probe"));
}
#[test]
fn accepts_a_path_or_a_string() {
let bare: Attribute = parse_quote!(#[icedwright_probe(crate = crate::shim)]);
assert_eq!(path_of(vec![bare]).ok().as_deref(), Some("crate :: shim"));
let quoted: Attribute = parse_quote!(#[icedwright_probe(crate = "renamed")]);
assert_eq!(path_of(vec![quoted]).ok().as_deref(), Some("renamed"));
}
#[test]
fn rejects_unknown_options_and_repeats() {
let unknown: Attribute = parse_quote!(#[icedwright_probe(krate = x)]);
assert!(path_of(vec![unknown]).is_err());
let a: Attribute = parse_quote!(#[icedwright_probe(crate = a)]);
let b: Attribute = parse_quote!(#[icedwright_probe(crate = b)]);
assert!(path_of(vec![a, b]).is_err());
}
}