use syn::{Attribute, Path};
pub(crate) fn is(attr: &Attribute, name: &str) -> bool {
attr.path().segments.last().is_some_and(|s| s.ident == name)
}
pub(crate) fn take_all(attrs: &mut Vec<Attribute>, name: &str) -> Vec<Attribute> {
let mut taken = Vec::new();
attrs.retain(|a| {
if is(a, name) {
taken.push(a.clone());
false
} else {
true
}
});
taken
}
pub(crate) fn is_inert(attr: &Attribute) -> bool {
const INERT: &[&str] = &[
"doc", "allow", "warn", "deny", "expect", "cfg", "cfg_attr", "inline", "must_use", "deprecated",
"track_caller", "guards", "interceptors", "error_handlers", "meta", "construct",
];
INERT.iter().any(|name| is(attr, name))
}
pub(crate) fn check_marker(path: &Path) -> syn::Result<()> {
refusal(path).map_or(Ok(()), |message| Err(syn::Error::new_spanned(path, message)))
}
pub(crate) fn qualifier(path: &Path) -> Option<syn::Ident> {
(path.segments.len() == 2).then(|| path.segments[0].ident.clone())
}
fn refusal(path: &Path) -> Option<String> {
let segments: Vec<_> = path.segments.iter().collect();
let accepted = match segments.as_slice() {
[_] => path.leading_colon.is_none(),
[first, _] => first.ident == "ulo" && first.arguments.is_none(),
_ => false,
};
if accepted {
return None;
}
let name = segments.last().map(|segment| segment.ident.to_string()).unwrap_or_default();
Some(format!(
"write the marker bare, or as `ulo::{name}`; under a renamed dependency, alias it at the crate root, \
`extern crate <name> as ulo;`"
))
}
#[cfg(test)]
mod tests {
use super::*;
fn checked(text: &str) -> Result<(), String> {
check_marker(&syn::parse_str::<Path>(text).unwrap()).map_err(|e| e.to_string())
}
#[test]
fn a_bare_marker_and_one_under_ulo_are_accepted() {
for text in ["guards", "ulo::guards", "::ulo::guards"] {
assert_eq!(checked(text), Ok(()), "{text}");
}
}
#[test]
fn any_other_qualifier_is_refused_naming_the_two_forms() {
for text in ["wrong::guards", "framework::guards", "a::b::guards", "ulo::x::guards", "::guards", "crate::guards"] {
let error = checked(text).expect_err(text);
assert!(error.starts_with("write the marker bare, or as `ulo::guards`"), "{text}: {error}");
}
}
}