Skip to content

Commit 59dd7cc

Browse files
committed
Add methods on Meta for error reporting an incorrect kind of attribute
1 parent 11c0b6c commit 59dd7cc

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/attr.rs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -505,6 +505,54 @@ impl Meta {
505505
Meta::NameValue(meta) => &meta.path,
506506
}
507507
}
508+
509+
/// Error if this is a `Meta::List` or `Meta::NameValue`.
510+
#[cfg(feature = "parsing")]
511+
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
512+
pub fn require_path_only(&self) -> Result<&Path> {
513+
let error_span = match self {
514+
Meta::Path(path) => return Ok(path),
515+
Meta::List(meta) => meta.delimiter.span().open(),
516+
Meta::NameValue(meta) => meta.eq_token.span,
517+
};
518+
Err(Error::new(error_span, "unexpected token in attribute"))
519+
}
520+
521+
/// Error if this is a `Meta::Path` or `Meta::NameValue`.
522+
#[cfg(feature = "parsing")]
523+
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
524+
pub fn require_list(&self) -> Result<&MetaList> {
525+
match self {
526+
Meta::List(meta) => Ok(meta),
527+
Meta::Path(path) => Err(crate::error::new2(
528+
path.segments.first().unwrap().ident.span(),
529+
path.segments.last().unwrap().ident.span(),
530+
format!(
531+
"expected attribute arguments in parentheses: `{}(...)`",
532+
parsing::DisplayPath(path),
533+
),
534+
)),
535+
Meta::NameValue(meta) => Err(Error::new(meta.eq_token.span, "expected `(`")),
536+
}
537+
}
538+
539+
/// Error if this is a `Meta::Path` or `Meta::List`.
540+
#[cfg(feature = "parsing")]
541+
#[cfg_attr(doc_cfg, doc(cfg(feature = "parsing")))]
542+
pub fn require_name_value(&self) -> Result<&MetaNameValue> {
543+
match self {
544+
Meta::NameValue(meta) => Ok(meta),
545+
Meta::Path(path) => Err(crate::error::new2(
546+
path.segments.first().unwrap().ident.span(),
547+
path.segments.last().unwrap().ident.span(),
548+
format!(
549+
"expected a value for this attribute: `{} = ...`",
550+
parsing::DisplayPath(path),
551+
),
552+
)),
553+
Meta::List(meta) => Err(Error::new(meta.delimiter.span().open(), "expected `=`")),
554+
}
555+
}
508556
}
509557

510558
impl MetaList {

0 commit comments

Comments
 (0)