3 use crate::parse::{SeqSep, PResult};
4 use crate::parse::token::{self, Nonterminal, DelimToken};
5 use crate::parse::parser::{Parser, TokenType, PathStyle};
6 use crate::tokenstream::{TokenStream, TokenTree};
7 use crate::source_map::Span;
10 use smallvec::smallvec;
13 enum InnerAttributeParsePolicy<'a> {
15 NotPermitted { reason: &'a str, saw_doc_comment: bool, prev_attr_sp: Option<Span> },
18 const DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG: &str = "an inner attribute is not \
19 permitted in this context";
22 crate fn parse_arg_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
23 let attrs = self.parse_outer_attributes()?;
24 attrs.iter().for_each(|a|
25 self.sess.param_attr_spans.borrow_mut().push(a.span)
30 /// Parse attributes that appear before an item
31 crate fn parse_outer_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
32 let mut attrs: Vec<ast::Attribute> = Vec::new();
33 let mut just_parsed_doc_comment = false;
35 debug!("parse_outer_attributes: self.token={:?}", self.token);
36 match self.token.kind {
38 let inner_error_reason = if just_parsed_doc_comment {
39 "an inner attribute is not permitted following an outer doc comment"
40 } else if !attrs.is_empty() {
41 "an inner attribute is not permitted following an outer attribute"
43 DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG
45 let inner_parse_policy =
46 InnerAttributeParsePolicy::NotPermitted {
47 reason: inner_error_reason,
48 saw_doc_comment: just_parsed_doc_comment,
49 prev_attr_sp: attrs.last().and_then(|a| Some(a.span))
51 let attr = self.parse_attribute_with_inner_parse_policy(inner_parse_policy)?;
53 just_parsed_doc_comment = false;
55 token::DocComment(s) => {
56 let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, self.token.span);
57 if attr.style != ast::AttrStyle::Outer {
58 let mut err = self.fatal("expected outer doc comment");
59 err.note("inner doc comments like this (starting with \
60 `//!` or `/*!`) can only appear before items");
65 just_parsed_doc_comment = true;
73 /// Matches `attribute = # ! [ meta_item ]`
75 /// If permit_inner is true, then a leading `!` indicates an inner
77 pub fn parse_attribute(&mut self, permit_inner: bool) -> PResult<'a, ast::Attribute> {
78 debug!("parse_attribute: permit_inner={:?} self.token={:?}",
81 let inner_parse_policy = if permit_inner {
82 InnerAttributeParsePolicy::Permitted
84 InnerAttributeParsePolicy::NotPermitted {
85 reason: DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG,
86 saw_doc_comment: false,
90 self.parse_attribute_with_inner_parse_policy(inner_parse_policy)
93 /// The same as `parse_attribute`, except it takes in an `InnerAttributeParsePolicy`
94 /// that prescribes how to handle inner attributes.
95 fn parse_attribute_with_inner_parse_policy(&mut self,
96 inner_parse_policy: InnerAttributeParsePolicy<'_>)
97 -> PResult<'a, ast::Attribute> {
98 debug!("parse_attribute_with_inner_parse_policy: inner_parse_policy={:?} self.token={:?}",
101 let (span, path, tokens, style) = match self.token.kind {
103 let lo = self.token.span;
106 if let InnerAttributeParsePolicy::Permitted = inner_parse_policy {
107 self.expected_tokens.push(TokenType::Token(token::Not));
110 let style = if self.token == token::Not {
112 ast::AttrStyle::Inner
114 ast::AttrStyle::Outer
117 self.expect(&token::OpenDelim(token::Bracket))?;
118 let (path, tokens) = self.parse_meta_item_unrestricted()?;
119 self.expect(&token::CloseDelim(token::Bracket))?;
120 let hi = self.prev_span;
122 let attr_sp = lo.to(hi);
124 // Emit error if inner attribute is encountered and not permitted
125 if style == ast::AttrStyle::Inner {
126 if let InnerAttributeParsePolicy::NotPermitted { reason,
127 saw_doc_comment, prev_attr_sp } = inner_parse_policy {
128 let prev_attr_note = if saw_doc_comment {
129 "previous doc comment"
131 "previous outer attribute"
134 let mut diagnostic = self
136 .struct_span_err(attr_sp, reason);
138 if let Some(prev_attr_sp) = prev_attr_sp {
140 .span_label(attr_sp, "not permitted following an outer attibute")
141 .span_label(prev_attr_sp, prev_attr_note);
145 .note("inner attributes, like `#![no_std]`, annotate the item \
146 enclosing them, and are usually found at the beginning of \
147 source files. Outer attributes, like `#[test]`, annotate the \
148 item following them.")
153 (attr_sp, path, tokens, style)
156 let token_str = self.this_token_to_string();
157 return Err(self.fatal(&format!("expected `#`, found `{}`", token_str)));
162 id: attr::mk_attr_id(),
166 is_sugared_doc: false,
171 /// Parse an inner part of attribute - path and following tokens.
172 /// The tokens must be either a delimited token stream, or empty token stream,
173 /// or the "legacy" key-value form.
174 /// PATH `(` TOKEN_STREAM `)`
175 /// PATH `[` TOKEN_STREAM `]`
176 /// PATH `{` TOKEN_STREAM `}`
178 /// PATH `=` TOKEN_TREE
179 /// The delimiters or `=` are still put into the resulting token stream.
180 crate fn parse_meta_item_unrestricted(&mut self) -> PResult<'a, (ast::Path, TokenStream)> {
181 let meta = match self.token.kind {
182 token::Interpolated(ref nt) => match **nt {
183 Nonterminal::NtMeta(ref meta) => Some(meta.clone()),
188 Ok(if let Some(meta) = meta {
190 (meta.path, meta.node.tokens(meta.span))
192 let path = self.parse_path(PathStyle::Mod)?;
193 let tokens = if self.check(&token::OpenDelim(DelimToken::Paren)) ||
194 self.check(&token::OpenDelim(DelimToken::Bracket)) ||
195 self.check(&token::OpenDelim(DelimToken::Brace)) {
196 self.parse_token_tree().into()
197 } else if self.eat(&token::Eq) {
198 let eq = TokenTree::token(token::Eq, self.prev_span);
199 let mut is_interpolated_expr = false;
200 if let token::Interpolated(nt) = &self.token.kind {
201 if let token::NtExpr(..) = **nt {
202 is_interpolated_expr = true;
205 let tokens = if is_interpolated_expr {
206 // We need to accept arbitrary interpolated expressions to continue
207 // supporting things like `doc = $expr` that work on stable.
208 // Non-literal interpolated expressions are rejected after expansion.
209 self.parse_token_tree().into()
211 self.parse_unsuffixed_lit()?.tokens()
213 TokenStream::from_streams(smallvec![eq.into(), tokens])
221 /// Parse attributes that appear after the opening of an item. These should
222 /// be preceded by an exclamation mark, but we accept and warn about one
223 /// terminated by a semicolon.
225 /// matches inner_attrs*
226 crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec<ast::Attribute>> {
227 let mut attrs: Vec<ast::Attribute> = vec![];
229 match self.token.kind {
231 // Don't even try to parse if it's not an inner attribute.
232 if !self.look_ahead(1, |t| t == &token::Not) {
236 let attr = self.parse_attribute(true)?;
237 assert_eq!(attr.style, ast::AttrStyle::Inner);
240 token::DocComment(s) => {
241 // we need to get the position of this token before we bump.
242 let attr = attr::mk_sugared_doc_attr(attr::mk_attr_id(), s, self.token.span);
243 if attr.style == ast::AttrStyle::Inner {
256 fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> {
257 let lit = self.parse_lit()?;
258 debug!("checking if {:?} is unusuffixed", lit);
260 if !lit.node.is_unsuffixed() {
261 let msg = "suffixed literals are not allowed in attributes";
262 self.diagnostic().struct_span_err(lit.span, msg)
263 .help("instead of using a suffixed literal \
264 (1u8, 1.0f32, etc.), use an unsuffixed version \
272 /// Per RFC#1559, matches the following grammar:
274 /// meta_item : IDENT ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ;
275 /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ;
276 pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> {
277 let nt_meta = match self.token.kind {
278 token::Interpolated(ref nt) => match **nt {
279 token::NtMeta(ref e) => Some(e.clone()),
285 if let Some(meta) = nt_meta {
290 let lo = self.token.span;
291 let path = self.parse_path(PathStyle::Mod)?;
292 let node = self.parse_meta_item_kind()?;
293 let span = lo.to(self.prev_span);
294 Ok(ast::MetaItem { path, node, span })
297 crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> {
298 Ok(if self.eat(&token::Eq) {
299 ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?)
300 } else if self.eat(&token::OpenDelim(token::Paren)) {
301 ast::MetaItemKind::List(self.parse_meta_seq()?)
303 ast::MetaItemKind::Word
307 /// matches meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;
308 fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> {
309 match self.parse_unsuffixed_lit() {
311 return Ok(ast::NestedMetaItem::Literal(lit))
313 Err(ref mut err) => self.diagnostic().cancel(err)
316 match self.parse_meta_item() {
318 return Ok(ast::NestedMetaItem::MetaItem(mi))
320 Err(ref mut err) => self.diagnostic().cancel(err)
323 let found = self.this_token_to_string();
324 let msg = format!("expected unsuffixed literal or identifier, found `{}`", found);
325 Err(self.diagnostic().struct_span_err(self.token.span, &msg))
328 /// matches meta_seq = ( COMMASEP(meta_item_inner) )
329 fn parse_meta_seq(&mut self) -> PResult<'a, Vec<ast::NestedMetaItem>> {
330 self.parse_seq_to_end(&token::CloseDelim(token::Paren),
331 SeqSep::trailing_allowed(token::Comma),
332 |p: &mut Parser<'a>| p.parse_meta_item_inner())