| //! Meta-syntax validation logic of attributes for post-expansion. | |
| use std::convert::identity; | |
| use rustc_ast::SyntheticAttr::CfgAttrTrace; | |
| use rustc_ast::token::Delimiter; | |
| use rustc_ast::tokenstream::DelimSpan; | |
| use rustc_ast::{ | |
| self as ast, AttrArgs, AttrKind, Attribute, DelimArgs, MetaItem, MetaItemInner, MetaItemKind, | |
| Safety, | |
| }; | |
| use rustc_attr_ir::AttrPath; | |
| use rustc_errors::{Applicability, Diagnostic, PResult}; | |
| use rustc_lint_defs::builtin::ILL_FORMED_ATTRIBUTE_INPUT; | |
| use rustc_parse::parse_in; | |
| use rustc_session::diagnostics::report_lit_error; | |
| use rustc_session::parse::ParseSess; | |
| use rustc_span::{Span, Symbol, sym}; | |
| use crate::{AttributeTemplate, diagnostics as errors}; | |
| pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> { | |
| let item = attr.get_normal_item(); | |
| Ok(MetaItem { | |
| unsafety: item.unsafety, | |
| span: attr.span, | |
| path: item.path.clone(), | |
| kind: match &item.args { | |
| AttrArgs::Empty => MetaItemKind::Word, | |
| AttrArgs::Delimited(DelimArgs { dspan, delim, tokens }) => { | |
| check_meta_bad_delim(psess, *dspan, *delim); | |
| let nmis = | |
| parse_in(psess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?; | |
| MetaItemKind::List(nmis) | |
| } | |
| AttrArgs::Eq { expr, .. } => { | |
| check_attrs_on_rhs_expr(psess, expr)?; | |
| if let ast::ExprKind::Lit(token_lit) = expr.kind { | |
| let res = ast::MetaItemLit::from_token_lit(token_lit, expr.span); | |
| match res { | |
| Ok(lit) => { | |
| if token_lit.suffix.is_some() { | |
| let mut err = psess.dcx().struct_span_err( | |
| expr.span, | |
| "suffixed literals are not allowed in attributes", | |
| ); | |
| err.help( | |
| "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \ | |
| use an unsuffixed version (`1`, `1.0`, etc.)", | |
| ); | |
| return Err(err); | |
| } | |
| MetaItemKind::NameValue(lit) | |
| } | |
| Err(err) => { | |
| let guar = report_lit_error(psess, err, token_lit, expr.span); | |
| let lit = ast::MetaItemLit { | |
| symbol: token_lit.symbol, | |
| suffix: token_lit.suffix, | |
| kind: ast::LitKind::Err(guar), | |
| span: expr.span, | |
| }; | |
| MetaItemKind::NameValue(lit) | |
| } | |
| } | |
| } else { | |
| // Example cases: | |
| // - `#[foo = 1+1]`: results in `ast::ExprKind::Binary`. | |
| // - `#[foo = include_str!("nonexistent-file.rs")]`: | |
| // results in `ast::ExprKind::Err`. In that case we delay | |
| // the error because an earlier error will have already | |
| // been reported. | |
| let msg = "attribute value must be a literal"; | |
| let mut err = psess.dcx().struct_span_err(expr.span, msg); | |
| if let ast::ExprKind::Err(_) = expr.kind { | |
| err.downgrade_to_delayed_bug(); | |
| } | |
| return Err(err); | |
| } | |
| } | |
| }, | |
| }) | |
| } | |
| fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) { | |
| if let Delimiter::Parenthesis = delim { | |
| return; | |
| } | |
| psess.dcx().emit_err(errors::MetaBadDelim { | |
| span: span.entire(), | |
| sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close }, | |
| }); | |
| } | |
| pub(crate) fn check_attrs_on_rhs_expr<'sess>( | |
| psess: &'sess ParseSess, | |
| expr: &ast::Expr, | |
| ) -> PResult<'sess, ()> { | |
| // Cfg traces are not real attrs, they're just a marker that cfg expansion has occurred which is | |
| // perfectly legal, so don't trigger on them. We only need to worry about `cfg_attr` traces and | |
| // not about `cfg` ones because macro expansion would've already bailed out with an error if | |
| // there was a `cfg` on an expr. | |
| let attrs: Vec<_> = expr | |
| .attrs | |
| .iter() | |
| .filter(|attr| !matches!(attr.kind, AttrKind::Synthetic(CfgAttrTrace(_)))) | |
| .map(|attr| attr.span) | |
| .collect(); | |
| if !attrs.is_empty() { | |
| return Err(psess | |
| .dcx() | |
| .create_err(errors::AttributeInInvalidContext { count: attrs.len(), attrs })); | |
| } | |
| Ok(()) | |
| } | |
| /// Checks that the given meta-item is compatible with this `AttributeTemplate`. | |
| fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaItemKind) -> bool { | |
| let is_one_allowed_subword = |items: &[MetaItemInner]| match items { | |
| [item] => item.is_word() && template.one_of.iter().any(|&word| item.has_name(word)), | |
| _ => false, | |
| }; | |
| match meta { | |
| MetaItemKind::Word => template.word, | |
| MetaItemKind::List(items) => template.list.is_some() || is_one_allowed_subword(items), | |
| MetaItemKind::NameValue(lit) if lit.kind.is_str() => template.name_value_str.is_some(), | |
| MetaItemKind::NameValue(..) => false, | |
| } | |
| } | |
| pub fn check_builtin_meta_item( | |
| psess: &ParseSess, | |
| meta: &MetaItem, | |
| style: ast::AttrStyle, | |
| name: Symbol, | |
| template: AttributeTemplate, | |
| deny_unsafety: bool, | |
| ) { | |
| if !is_attr_template_compatible(&template, &meta.kind) { | |
| // attrs with new parsers are locally validated so excluded here | |
| emit_malformed_attribute(psess, style, meta.span, name, template); | |
| } | |
| if deny_unsafety && let Safety::Unsafe(unsafe_span) = meta.unsafety { | |
| psess.dcx().emit_err(errors::InvalidAttrUnsafe { | |
| span: unsafe_span, | |
| name: AttrPath::from_ast(&meta.path, identity), | |
| }); | |
| } | |
| } | |
| pub fn emit_malformed_attribute( | |
| psess: &ParseSess, | |
| style: ast::AttrStyle, | |
| span: Span, | |
| name: Symbol, | |
| template: AttributeTemplate, | |
| ) { | |
| // Some of previously accepted forms were used in practice, | |
| // report them as warnings for now. | |
| let should_warn = |name| matches!(name, sym::doc | sym::link | sym::test | sym::bench); | |
| let error_msg = format!("malformed `{name}` attribute input"); | |
| let mut suggestions = vec![]; | |
| let inner = if style == ast::AttrStyle::Inner { "!" } else { "" }; | |
| if template.word { | |
| suggestions.push(format!("#{inner}[{name}]")); | |
| } | |
| if let Some(descr) = template.list { | |
| for descr in descr { | |
| suggestions.push(format!("#{inner}[{name}({descr})]")); | |
| } | |
| } | |
| suggestions.extend(template.one_of.iter().map(|&word| format!("#{inner}[{name}({word})]"))); | |
| if let Some(descr) = template.name_value_str { | |
| for descr in descr { | |
| suggestions.push(format!("#{inner}[{name} = \"{descr}\"]")); | |
| } | |
| } | |
| // If there are too many suggestions, better remove all of them as it's just noise at this | |
| // point. | |
| if suggestions.len() > 3 { | |
| suggestions.clear(); | |
| } | |
| if should_warn(name) { | |
| let suggestions = suggestions.clone(); | |
| psess.dyn_buffer_lint( | |
| ILL_FORMED_ATTRIBUTE_INPUT, | |
| span, | |
| ast::CRATE_NODE_ID, | |
| move |dcx, level| { | |
| crate::diagnostics::IllFormedAttributeInput::new(&suggestions, template.docs, None) | |
| .into_diag(dcx, level) | |
| }, | |
| ); | |
| } else { | |
| suggestions.sort(); | |
| let mut err = psess.dcx().struct_span_err(span, error_msg).with_span_suggestions( | |
| span, | |
| if suggestions.len() == 1 { | |
| "must be of the form" | |
| } else { | |
| "the following are the possible correct uses" | |
| }, | |
| suggestions, | |
| Applicability::HasPlaceholders, | |
| ); | |
| if let Some(link) = template.docs { | |
| err.note(format!("for more information, visit <{link}>")); | |
| } | |
| err.emit(); | |
| } | |
| } |