rust/src/librustc_parse/parser/attr.rs

339 lines
13 KiB
Rust
Raw Normal View History

2019-12-22 22:42:04 +00:00
use super::{Parser, PathStyle, TokenType};
2019-12-05 05:38:06 +00:00
use rustc_errors::PResult;
use rustc_span::{Span, Symbol};
use syntax::ast;
2019-12-23 13:08:12 +00:00
use syntax::attr;
2019-12-07 02:07:35 +00:00
use syntax::print::pprust;
use syntax::token::{self, Nonterminal};
2019-12-22 22:42:04 +00:00
use syntax::util::comments;
2019-10-11 11:06:36 +00:00
2019-02-06 17:33:01 +00:00
use log::debug;
2014-05-16 07:16:13 +00:00
#[derive(Debug)]
enum InnerAttributeParsePolicy<'a> {
Permitted,
2019-07-27 11:24:17 +00:00
NotPermitted { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
}
const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
permitted in this context";
2015-10-24 01:37:21 +00:00
impl<'a> Parser<'a> {
/// Parses attributes that appear before an item.
2019-10-08 07:35:34 +00:00
pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
let mut attrs: Vec<ast::Attribute> = Vec::new();
let mut just_parsed_doc_comment = false;
loop {
2016-01-27 19:42:26 +00:00
debug!("parse_outer_attributes: self.token={:?}", self.token);
2019-06-04 22:17:07 +00:00
match self.token.kind {
2016-01-27 19:42:26 +00:00
token::Pound => {
let inner_error_reason = if just_parsed_doc_comment {
"an inner attribute is not permitted following an outer doc comment"
} else if !attrs.is_empty() {
"an inner attribute is not permitted following an outer attribute"
} else {
DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
};
2019-12-22 22:42:04 +00:00
let inner_parse_policy = InnerAttributeParsePolicy::NotPermitted {
reason: inner_error_reason,
saw_doc_comment: just_parsed_doc_comment,
prev_attr_sp: attrs.last().and_then(|a| Some(a.span)),
};
let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
attrs.push(attr);
just_parsed_doc_comment = false;
2016-01-27 19:42:26 +00:00
}
token::DocComment(s) => {
2019-10-11 12:14:30 +00:00
let attr = self.mk_doc_comment(s);
2016-11-14 12:00:25 +00:00
if attr.style != ast::AttrStyle::Outer {
2019-12-31 00:13:00 +00:00
let span = self.token.span;
let mut err = self.struct_span_err(span, "expected outer doc comment");
2019-12-22 22:42:04 +00:00
err.note(
"inner doc comments like this (starting with \
`//!` or `/*!`) can only appear before items",
);
return Err(err);
2016-01-27 19:42:26 +00:00
}
attrs.push(attr);
self.bump();
just_parsed_doc_comment = true;
}
2016-01-27 19:42:26 +00:00
_ => break,
}
2012-05-24 20:44:42 +00:00
}
Ok(attrs)
}
2019-10-11 12:14:30 +00:00
fn mk_doc_comment(&self, s: Symbol) -> ast::Attribute {
let style = comments::doc_comment_style(&s.as_str());
attr::mk_doc_comment(style, s, self.token.span)
}
/// Matches `attribute = # ! [ meta_item ]`.
2014-06-09 20:12:30 +00:00
///
/// If `permit_inner` is `true`, then a leading `!` indicates an inner
/// attribute.
2019-10-16 11:23:46 +00:00
pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
2019-12-22 22:42:04 +00:00
debug!("parse_attribute: permit_inner={:?} self.token={:?}", permit_inner, self.token);
let inner_parse_policy = if permit_inner {
InnerAttributeParsePolicy::Permitted
} else {
2019-07-27 11:24:17 +00:00
InnerAttributeParsePolicy::NotPermitted {
reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
saw_doc_comment: false,
2019-12-22 22:42:04 +00:00
prev_attr_sp: None,
2019-07-27 11:24:17 +00:00
}
};
self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
}
/// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy`
/// that prescribes how to handle inner attributes.
2019-10-08 07:35:34 +00:00
fn parse_attribute_with_inner_parse_policy(
&mut self,
2019-12-22 22:42:04 +00:00
inner_parse_policy: InnerAttributeParsePolicy<'_>,
2019-10-08 07:35:34 +00:00
) -> PResult<'a, ast::Attribute> {
2019-12-22 22:42:04 +00:00
debug!(
"parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
inner_parse_policy, self.token
);
let (span, item, style) = match self.token.kind {
2014-10-27 08:22:52 +00:00
token::Pound => {
let lo = self.token.span;
self.bump();
if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
2016-01-27 19:42:26 +00:00
self.expected_tokens.push(TokenType::Token(token::Not));
}
let style = if self.token == token::Not {
self.bump();
ast::AttrStyle::Inner
} else {
ast::AttrStyle::Outer
};
self.expect(&token::OpenDelim(token::Bracket))?;
let item = self.parse_attr_item()?;
self.expect(&token::CloseDelim(token::Bracket))?;
let hi = self.prev_span;
let attr_sp = lo.to(hi);
// Emit error if inner attribute is encountered and not permitted
if style == ast::AttrStyle::Inner {
2019-12-22 22:42:04 +00:00
if let InnerAttributeParsePolicy::NotPermitted {
reason,
saw_doc_comment,
prev_attr_sp,
} = inner_parse_policy
{
2019-07-27 11:24:17 +00:00
let prev_attr_note = if saw_doc_comment {
"previous doc comment"
} else {
"previous outer attribute"
};
2019-12-30 13:56:57 +00:00
let mut diagnostic = self.struct_span_err(attr_sp, reason);
if let Some(prev_attr_sp) = prev_attr_sp {
diagnostic
.span_label(attr_sp, "not permitted following an outer attibute")
2019-07-27 11:24:17 +00:00
.span_label(prev_attr_sp, prev_attr_note);
}
diagnostic
2019-12-22 22:42:04 +00:00
.note(
"inner attributes, like `#![no_std]`, annotate the item \
enclosing them, and are usually found at the beginning of \
source files. Outer attributes, like `#[test]`, annotate the \
2019-12-22 22:42:04 +00:00
item following them.",
)
.emit()
}
}
(attr_sp, item, style)
}
_ => {
2019-12-07 02:07:35 +00:00
let token_str = pprust::token_to_string(&self.token);
2019-12-31 00:13:00 +00:00
let msg = &format!("expected `#`, found `{}`", token_str);
return Err(self.struct_span_err(self.token.span, msg));
}
};
Ok(attr::mk_attr_from_item(style, item, span))
2012-05-24 20:44:42 +00:00
}
/// Parses an inner part of an attribute (the path and following tokens).
/// The tokens must be either a delimited token stream, or empty token stream,
/// or the "legacy" key-value form.
/// PATH `(` TOKEN_STREAM `)`
/// PATH `[` TOKEN_STREAM `]`
/// PATH `{` TOKEN_STREAM `}`
/// PATH
2019-09-30 21:58:30 +00:00
/// PATH `=` UNSUFFIXED_LIT
/// The delimiters or `=` are still put into the resulting token stream.
pub fn parse_attr_item(&mut self) -> PResult<'a, ast::AttrItem> {
let item = match self.token.kind {
token::Interpolated(ref nt) => match **nt {
Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()),
2017-03-08 23:13:35 +00:00
_ => None,
},
_ => None,
};
Ok(if let Some(item) = item {
2017-03-08 23:13:35 +00:00
self.bump();
item
2017-03-08 23:13:35 +00:00
} else {
let path = self.parse_path(PathStyle::Mod)?;
let args = self.parse_attr_args()?;
ast::AttrItem { path, args }
2017-03-08 23:13:35 +00:00
})
}
/// Parses attributes that appear after the opening of an item. These should
2014-06-09 20:12:30 +00:00
/// be preceded by an exclamation mark, but we accept and warn about one
/// terminated by a semicolon.
///
/// Matches `inner_attrs*`.
crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
let mut attrs: Vec<ast::Attribute> = vec![];
loop {
2019-06-04 22:17:07 +00:00
match self.token.kind {
2014-10-27 08:22:52 +00:00
token::Pound => {
// Don't even try to parse if it's not an inner attribute.
if !self.look_ahead(1, |t| t == &token::Not) {
break;
}
let attr = self.parse_attribute(true)?;
assert_eq!(attr.style, ast::AttrStyle::Inner);
attrs.push(attr);
}
2014-10-27 08:22:52 +00:00
token::DocComment(s) => {
// We need to get the position of this token before we bump.
2019-10-11 12:14:30 +00:00
let attr = self.mk_doc_comment(s);
2016-11-14 12:00:25 +00:00
if attr.style == ast::AttrStyle::Inner {
attrs.push(attr);
self.bump();
} else {
break;
}
}
2016-01-27 19:42:26 +00:00
_ => break,
2012-05-24 20:44:42 +00:00
}
}
Ok(attrs)
2012-05-24 20:44:42 +00:00
}
2019-12-05 13:19:00 +00:00
crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
let lit = self.parse_lit()?;
debug!("checking if {:?} is unusuffixed", lit);
2019-09-26 15:56:53 +00:00
if !lit.kind.is_unsuffixed() {
let msg = "suffixed literals are not allowed in attributes";
2019-12-30 13:56:57 +00:00
self.struct_span_err(lit.span, msg)
2019-12-22 22:42:04 +00:00
.help(
"instead of using a suffixed literal \
2020-01-10 14:57:36 +00:00
(`1u8`, `1.0f32`, etc.), use an unsuffixed version \
(`1`, `1.0`, etc.)",
2019-12-22 22:42:04 +00:00
)
.emit()
}
Ok(lit)
}
2019-10-08 07:14:07 +00:00
/// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited.
2019-10-10 08:26:10 +00:00
pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> {
2019-10-08 07:14:07 +00:00
let cfg_predicate = self.parse_meta_item()?;
self.expect(&token::Comma)?;
// Presumably, the majority of the time there will only be one attr.
let mut expanded_attrs = Vec::with_capacity(1);
2019-12-05 05:45:50 +00:00
while self.token.kind != token::Eof {
let lo = self.token.span;
2019-10-08 07:14:07 +00:00
let item = self.parse_attr_item()?;
2019-12-05 05:45:50 +00:00
expanded_attrs.push((item, lo.to(self.prev_span)));
2019-12-05 13:19:00 +00:00
if !self.eat(&token::Comma) {
break;
}
2019-10-08 07:14:07 +00:00
}
Ok((cfg_predicate, expanded_attrs))
}
2019-12-05 13:19:00 +00:00
/// Matches `COMMASEP(meta_item_inner)`.
crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
// Presumably, the majority of the time there will only be one attr.
let mut nmis = Vec::with_capacity(1);
while self.token.kind != token::Eof {
nmis.push(self.parse_meta_item_inner()?);
if !self.eat(&token::Comma) {
break;
}
}
Ok(nmis)
}
/// Matches the following grammar (per RFC 1559).
///
2019-09-30 21:58:30 +00:00
/// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
/// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
2019-06-04 22:17:07 +00:00
let nt_meta = match self.token.kind {
token::Interpolated(ref nt) => match **nt {
token::NtMeta(ref e) => Some(e.clone()),
_ => None,
},
2016-01-27 19:42:26 +00:00
_ => None,
2014-09-13 16:06:01 +00:00
};
if let Some(item) = nt_meta {
return match item.meta(item.path.span) {
Some(meta) => {
self.bump();
Ok(meta)
}
None => self.unexpected(),
2019-12-22 22:42:04 +00:00
};
}
let lo = self.token.span;
let path = self.parse_path(PathStyle::Mod)?;
let kind = self.parse_meta_item_kind()?;
2018-01-30 05:30:39 +00:00
let span = lo.to(self.prev_span);
Ok(ast::MetaItem { path, kind, span })
}
crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
Ok(if self.eat(&token::Eq) {
ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
} else if self.check(&token::OpenDelim(token::Paren)) {
// Matches `meta_seq = ( COMMASEP(meta_item_inner) )`.
let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?;
ast::MetaItemKind::List(list)
} else {
ast::MetaItemKind::Word
})
}
/// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`.
fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
match self.parse_unsuffixed_lit() {
Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)),
2019-09-07 14:38:02 +00:00
Err(ref mut err) => err.cancel(),
}
match self.parse_meta_item() {
Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)),
2019-09-07 14:38:02 +00:00
Err(ref mut err) => err.cancel(),
}
2019-12-07 02:07:35 +00:00
let found = pprust::token_to_string(&self.token);
2019-03-06 21:16:52 +00:00
let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
2019-12-30 13:56:57 +00:00
Err(self.struct_span_err(self.token.span, &msg))
}
}