|
| 1 | +//! Implementation of the `#[cfg_accessible(path)]` attribute macro. |
| 2 | +
|
| 3 | +use rustc_ast::ast; |
| 4 | +use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier}; |
| 5 | +use rustc_feature::AttributeTemplate; |
| 6 | +use rustc_parse::validate_attr; |
| 7 | +use rustc_span::symbol::sym; |
| 8 | +use rustc_span::Span; |
| 9 | + |
| 10 | +crate struct Expander; |
| 11 | + |
| 12 | +fn validate_input<'a>(ecx: &mut ExtCtxt<'_>, mi: &'a ast::MetaItem) -> Option<&'a ast::Path> { |
| 13 | + match mi.meta_item_list() { |
| 14 | + None => {} |
| 15 | + Some([]) => ecx.span_err(mi.span, "`cfg_accessible` path is not specified"), |
| 16 | + Some([_, .., l]) => ecx.span_err(l.span(), "multiple `cfg_accessible` paths are specified"), |
| 17 | + Some([nmi]) => match nmi.meta_item() { |
| 18 | + None => ecx.span_err(nmi.span(), "`cfg_accessible` path cannot be a literal"), |
| 19 | + Some(mi) => { |
| 20 | + if !mi.is_word() { |
| 21 | + ecx.span_err(mi.span, "`cfg_accessible` path cannot accept arguments"); |
| 22 | + } |
| 23 | + return Some(&mi.path); |
| 24 | + } |
| 25 | + }, |
| 26 | + } |
| 27 | + None |
| 28 | +} |
| 29 | + |
| 30 | +impl MultiItemModifier for Expander { |
| 31 | + fn expand( |
| 32 | + &self, |
| 33 | + ecx: &mut ExtCtxt<'_>, |
| 34 | + _span: Span, |
| 35 | + meta_item: &ast::MetaItem, |
| 36 | + item: Annotatable, |
| 37 | + ) -> ExpandResult<Vec<Annotatable>, Annotatable> { |
| 38 | + let template = AttributeTemplate { list: Some("path"), ..Default::default() }; |
| 39 | + let attr = &ecx.attribute(meta_item.clone()); |
| 40 | + validate_attr::check_builtin_attribute(ecx.parse_sess, attr, sym::cfg_accessible, template); |
| 41 | + |
| 42 | + let path = match validate_input(ecx, meta_item) { |
| 43 | + Some(path) => path, |
| 44 | + None => return ExpandResult::Ready(Vec::new()), |
| 45 | + }; |
| 46 | + |
| 47 | + let failure_msg = "cannot determine whether the path is accessible or not"; |
| 48 | + match ecx.resolver.cfg_accessible(ecx.current_expansion.id, path) { |
| 49 | + Ok(true) => ExpandResult::Ready(vec![item]), |
| 50 | + Ok(false) => ExpandResult::Ready(Vec::new()), |
| 51 | + Err(_) => ExpandResult::Retry(item, failure_msg.into()), |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments